bson.browser.esm.js 175 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667
  1. import long from 'long';
  2. import buffer from 'buffer';
  3. var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  4. function createCommonjsModule(fn, module) {
  5. return module = { exports: {} }, fn(module, module.exports), module.exports;
  6. }
  7. var map = createCommonjsModule(function (module) {
  8. if (typeof commonjsGlobal.Map !== 'undefined') {
  9. module.exports = commonjsGlobal.Map;
  10. module.exports.Map = commonjsGlobal.Map;
  11. } else {
  12. // We will return a polyfill
  13. var Map = function Map(array) {
  14. this._keys = [];
  15. this._values = {};
  16. for (var i = 0; i < array.length; i++) {
  17. if (array[i] == null) continue; // skip null and undefined
  18. var entry = array[i];
  19. var key = entry[0];
  20. var value = entry[1]; // Add the key to the list of keys in order
  21. this._keys.push(key); // Add the key and value to the values dictionary with a point
  22. // to the location in the ordered keys list
  23. this._values[key] = {
  24. v: value,
  25. i: this._keys.length - 1
  26. };
  27. }
  28. };
  29. Map.prototype.clear = function () {
  30. this._keys = [];
  31. this._values = {};
  32. };
  33. Map.prototype.delete = function (key) {
  34. var value = this._values[key];
  35. if (value == null) return false; // Delete entry
  36. delete this._values[key]; // Remove the key from the ordered keys list
  37. this._keys.splice(value.i, 1);
  38. return true;
  39. };
  40. Map.prototype.entries = function () {
  41. var self = this;
  42. var index = 0;
  43. return {
  44. next: function next() {
  45. var key = self._keys[index++];
  46. return {
  47. value: key !== undefined ? [key, self._values[key].v] : undefined,
  48. done: key !== undefined ? false : true
  49. };
  50. }
  51. };
  52. };
  53. Map.prototype.forEach = function (callback, self) {
  54. self = self || this;
  55. for (var i = 0; i < this._keys.length; i++) {
  56. var key = this._keys[i]; // Call the forEach callback
  57. callback.call(self, this._values[key].v, key, self);
  58. }
  59. };
  60. Map.prototype.get = function (key) {
  61. return this._values[key] ? this._values[key].v : undefined;
  62. };
  63. Map.prototype.has = function (key) {
  64. return this._values[key] != null;
  65. };
  66. Map.prototype.keys = function () {
  67. var self = this;
  68. var index = 0;
  69. return {
  70. next: function next() {
  71. var key = self._keys[index++];
  72. return {
  73. value: key !== undefined ? key : undefined,
  74. done: key !== undefined ? false : true
  75. };
  76. }
  77. };
  78. };
  79. Map.prototype.set = function (key, value) {
  80. if (this._values[key]) {
  81. this._values[key].v = value;
  82. return this;
  83. } // Add the key to the list of keys in order
  84. this._keys.push(key); // Add the key and value to the values dictionary with a point
  85. // to the location in the ordered keys list
  86. this._values[key] = {
  87. v: value,
  88. i: this._keys.length - 1
  89. };
  90. return this;
  91. };
  92. Map.prototype.values = function () {
  93. var self = this;
  94. var index = 0;
  95. return {
  96. next: function next() {
  97. var key = self._keys[index++];
  98. return {
  99. value: key !== undefined ? self._values[key].v : undefined,
  100. done: key !== undefined ? false : true
  101. };
  102. }
  103. };
  104. }; // Last ismaster
  105. Object.defineProperty(Map.prototype, 'size', {
  106. enumerable: true,
  107. get: function get() {
  108. return this._keys.length;
  109. }
  110. });
  111. module.exports = Map;
  112. }
  113. });
  114. var map_1 = map.Map;
  115. /**
  116. * @ignore
  117. */
  118. long.prototype.toExtendedJSON = function (options) {
  119. if (options && options.relaxed) return this.toNumber();
  120. return {
  121. $numberLong: this.toString()
  122. };
  123. };
  124. /**
  125. * @ignore
  126. */
  127. long.fromExtendedJSON = function (doc, options) {
  128. var result = long.fromString(doc.$numberLong);
  129. return options && options.relaxed ? result.toNumber() : result;
  130. };
  131. Object.defineProperty(long.prototype, '_bsontype', {
  132. value: 'Long'
  133. });
  134. var long_1 = long;
  135. function _typeof(obj) {
  136. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  137. _typeof = function (obj) {
  138. return typeof obj;
  139. };
  140. } else {
  141. _typeof = function (obj) {
  142. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  143. };
  144. }
  145. return _typeof(obj);
  146. }
  147. function _classCallCheck(instance, Constructor) {
  148. if (!(instance instanceof Constructor)) {
  149. throw new TypeError("Cannot call a class as a function");
  150. }
  151. }
  152. function _defineProperties(target, props) {
  153. for (var i = 0; i < props.length; i++) {
  154. var descriptor = props[i];
  155. descriptor.enumerable = descriptor.enumerable || false;
  156. descriptor.configurable = true;
  157. if ("value" in descriptor) descriptor.writable = true;
  158. Object.defineProperty(target, descriptor.key, descriptor);
  159. }
  160. }
  161. function _createClass(Constructor, protoProps, staticProps) {
  162. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  163. if (staticProps) _defineProperties(Constructor, staticProps);
  164. return Constructor;
  165. }
  166. function _inherits(subClass, superClass) {
  167. if (typeof superClass !== "function" && superClass !== null) {
  168. throw new TypeError("Super expression must either be null or a function");
  169. }
  170. subClass.prototype = Object.create(superClass && superClass.prototype, {
  171. constructor: {
  172. value: subClass,
  173. writable: true,
  174. configurable: true
  175. }
  176. });
  177. if (superClass) _setPrototypeOf(subClass, superClass);
  178. }
  179. function _getPrototypeOf(o) {
  180. _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
  181. return o.__proto__ || Object.getPrototypeOf(o);
  182. };
  183. return _getPrototypeOf(o);
  184. }
  185. function _setPrototypeOf(o, p) {
  186. _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  187. o.__proto__ = p;
  188. return o;
  189. };
  190. return _setPrototypeOf(o, p);
  191. }
  192. function _assertThisInitialized(self) {
  193. if (self === void 0) {
  194. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  195. }
  196. return self;
  197. }
  198. function _possibleConstructorReturn(self, call) {
  199. if (call && (typeof call === "object" || typeof call === "function")) {
  200. return call;
  201. }
  202. return _assertThisInitialized(self);
  203. }
  204. var Double =
  205. /*#__PURE__*/
  206. function () {
  207. /**
  208. * Create a Double type
  209. *
  210. * @param {number} value the number we want to represent as a double.
  211. * @return {Double}
  212. */
  213. function Double(value) {
  214. _classCallCheck(this, Double);
  215. this.value = value;
  216. }
  217. /**
  218. * Access the number value.
  219. *
  220. * @method
  221. * @return {number} returns the wrapped double number.
  222. */
  223. _createClass(Double, [{
  224. key: "valueOf",
  225. value: function valueOf() {
  226. return this.value;
  227. }
  228. /**
  229. * @ignore
  230. */
  231. }, {
  232. key: "toJSON",
  233. value: function toJSON() {
  234. return this.value;
  235. }
  236. /**
  237. * @ignore
  238. */
  239. }, {
  240. key: "toExtendedJSON",
  241. value: function toExtendedJSON(options) {
  242. if (options && options.relaxed && isFinite(this.value)) return this.value;
  243. return {
  244. $numberDouble: this.value.toString()
  245. };
  246. }
  247. /**
  248. * @ignore
  249. */
  250. }], [{
  251. key: "fromExtendedJSON",
  252. value: function fromExtendedJSON(doc, options) {
  253. return options && options.relaxed ? parseFloat(doc.$numberDouble) : new Double(parseFloat(doc.$numberDouble));
  254. }
  255. }]);
  256. return Double;
  257. }();
  258. Object.defineProperty(Double.prototype, '_bsontype', {
  259. value: 'Double'
  260. });
  261. var double_1 = Double;
  262. /**
  263. * @class
  264. * @param {number} low the low (signed) 32 bits of the Timestamp.
  265. * @param {number} high the high (signed) 32 bits of the Timestamp.
  266. * @return {Timestamp}
  267. */
  268. var Timestamp =
  269. /*#__PURE__*/
  270. function (_Long) {
  271. _inherits(Timestamp, _Long);
  272. function Timestamp(low, high) {
  273. var _this;
  274. _classCallCheck(this, Timestamp);
  275. if (low instanceof long_1) {
  276. _this = _possibleConstructorReturn(this, _getPrototypeOf(Timestamp).call(this, low.low, low.high));
  277. } else {
  278. _this = _possibleConstructorReturn(this, _getPrototypeOf(Timestamp).call(this, low, high));
  279. }
  280. return _possibleConstructorReturn(_this);
  281. }
  282. /**
  283. * Return the JSON value.
  284. *
  285. * @method
  286. * @return {String} the JSON representation.
  287. */
  288. _createClass(Timestamp, [{
  289. key: "toJSON",
  290. value: function toJSON() {
  291. return {
  292. $timestamp: this.toString()
  293. };
  294. }
  295. /**
  296. * Returns a Timestamp represented by the given (32-bit) integer value.
  297. *
  298. * @method
  299. * @param {number} value the 32-bit integer in question.
  300. * @return {Timestamp} the timestamp.
  301. */
  302. }, {
  303. key: "toExtendedJSON",
  304. /**
  305. * @ignore
  306. */
  307. value: function toExtendedJSON() {
  308. return {
  309. $timestamp: {
  310. t: this.high,
  311. i: this.low
  312. }
  313. };
  314. }
  315. /**
  316. * @ignore
  317. */
  318. }], [{
  319. key: "fromInt",
  320. value: function fromInt(value) {
  321. return new Timestamp(long_1.fromInt(value));
  322. }
  323. /**
  324. * Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned.
  325. *
  326. * @method
  327. * @param {number} value the number in question.
  328. * @return {Timestamp} the timestamp.
  329. */
  330. }, {
  331. key: "fromNumber",
  332. value: function fromNumber(value) {
  333. return new Timestamp(long_1.fromNumber(value));
  334. }
  335. /**
  336. * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits.
  337. *
  338. * @method
  339. * @param {number} lowBits the low 32-bits.
  340. * @param {number} highBits the high 32-bits.
  341. * @return {Timestamp} the timestamp.
  342. */
  343. }, {
  344. key: "fromBits",
  345. value: function fromBits(lowBits, highBits) {
  346. return new Timestamp(lowBits, highBits);
  347. }
  348. /**
  349. * Returns a Timestamp from the given string, optionally using the given radix.
  350. *
  351. * @method
  352. * @param {String} str the textual representation of the Timestamp.
  353. * @param {number} [opt_radix] the radix in which the text is written.
  354. * @return {Timestamp} the timestamp.
  355. */
  356. }, {
  357. key: "fromString",
  358. value: function fromString(str, opt_radix) {
  359. return new Timestamp(long_1.fromString(str, opt_radix));
  360. }
  361. }, {
  362. key: "fromExtendedJSON",
  363. value: function fromExtendedJSON(doc) {
  364. return new Timestamp(doc.$timestamp.i, doc.$timestamp.t);
  365. }
  366. }]);
  367. return Timestamp;
  368. }(long_1);
  369. Object.defineProperty(Timestamp.prototype, '_bsontype', {
  370. value: 'Timestamp'
  371. });
  372. var timestamp = Timestamp;
  373. var require$$0 = {};
  374. /* global window */
  375. /**
  376. * Normalizes our expected stringified form of a function across versions of node
  377. * @param {Function} fn The function to stringify
  378. */
  379. function normalizedFunctionString(fn) {
  380. return fn.toString().replace('function(', 'function (');
  381. }
  382. function insecureRandomBytes(size) {
  383. var result = new Uint8Array(size);
  384. for (var i = 0; i < size; ++i) {
  385. result[i] = Math.floor(Math.random() * 256);
  386. }
  387. return result;
  388. }
  389. var randomBytes = insecureRandomBytes;
  390. if (typeof window !== 'undefined' && window.crypto && window.crypto.getRandomValues) {
  391. randomBytes = function randomBytes(size) {
  392. return window.crypto.getRandomValues(new Uint8Array(size));
  393. };
  394. } else {
  395. try {
  396. randomBytes = require$$0.randomBytes;
  397. } catch (e) {} // keep the fallback
  398. // NOTE: in transpiled cases the above require might return null/undefined
  399. if (randomBytes == null) {
  400. randomBytes = insecureRandomBytes;
  401. }
  402. }
  403. var utils = {
  404. normalizedFunctionString: normalizedFunctionString,
  405. randomBytes: randomBytes
  406. };
  407. // shim for using process in browser
  408. // based off https://github.com/defunctzombie/node-process/blob/master/browser.js
  409. function defaultSetTimout() {
  410. throw new Error('setTimeout has not been defined');
  411. }
  412. function defaultClearTimeout() {
  413. throw new Error('clearTimeout has not been defined');
  414. }
  415. var cachedSetTimeout = defaultSetTimout;
  416. var cachedClearTimeout = defaultClearTimeout;
  417. if (typeof global.setTimeout === 'function') {
  418. cachedSetTimeout = setTimeout;
  419. }
  420. if (typeof global.clearTimeout === 'function') {
  421. cachedClearTimeout = clearTimeout;
  422. }
  423. function runTimeout(fun) {
  424. if (cachedSetTimeout === setTimeout) {
  425. //normal enviroments in sane situations
  426. return setTimeout(fun, 0);
  427. } // if setTimeout wasn't available but was latter defined
  428. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  429. cachedSetTimeout = setTimeout;
  430. return setTimeout(fun, 0);
  431. }
  432. try {
  433. // when when somebody has screwed with setTimeout but no I.E. maddness
  434. return cachedSetTimeout(fun, 0);
  435. } catch (e) {
  436. try {
  437. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  438. return cachedSetTimeout.call(null, fun, 0);
  439. } catch (e) {
  440. // 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
  441. return cachedSetTimeout.call(this, fun, 0);
  442. }
  443. }
  444. }
  445. function runClearTimeout(marker) {
  446. if (cachedClearTimeout === clearTimeout) {
  447. //normal enviroments in sane situations
  448. return clearTimeout(marker);
  449. } // if clearTimeout wasn't available but was latter defined
  450. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  451. cachedClearTimeout = clearTimeout;
  452. return clearTimeout(marker);
  453. }
  454. try {
  455. // when when somebody has screwed with setTimeout but no I.E. maddness
  456. return cachedClearTimeout(marker);
  457. } catch (e) {
  458. try {
  459. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  460. return cachedClearTimeout.call(null, marker);
  461. } catch (e) {
  462. // 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.
  463. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  464. return cachedClearTimeout.call(this, marker);
  465. }
  466. }
  467. }
  468. var queue = [];
  469. var draining = false;
  470. var currentQueue;
  471. var queueIndex = -1;
  472. function cleanUpNextTick() {
  473. if (!draining || !currentQueue) {
  474. return;
  475. }
  476. draining = false;
  477. if (currentQueue.length) {
  478. queue = currentQueue.concat(queue);
  479. } else {
  480. queueIndex = -1;
  481. }
  482. if (queue.length) {
  483. drainQueue();
  484. }
  485. }
  486. function drainQueue() {
  487. if (draining) {
  488. return;
  489. }
  490. var timeout = runTimeout(cleanUpNextTick);
  491. draining = true;
  492. var len = queue.length;
  493. while (len) {
  494. currentQueue = queue;
  495. queue = [];
  496. while (++queueIndex < len) {
  497. if (currentQueue) {
  498. currentQueue[queueIndex].run();
  499. }
  500. }
  501. queueIndex = -1;
  502. len = queue.length;
  503. }
  504. currentQueue = null;
  505. draining = false;
  506. runClearTimeout(timeout);
  507. }
  508. function nextTick(fun) {
  509. var args = new Array(arguments.length - 1);
  510. if (arguments.length > 1) {
  511. for (var i = 1; i < arguments.length; i++) {
  512. args[i - 1] = arguments[i];
  513. }
  514. }
  515. queue.push(new Item(fun, args));
  516. if (queue.length === 1 && !draining) {
  517. runTimeout(drainQueue);
  518. }
  519. } // v8 likes predictible objects
  520. function Item(fun, array) {
  521. this.fun = fun;
  522. this.array = array;
  523. }
  524. Item.prototype.run = function () {
  525. this.fun.apply(null, this.array);
  526. };
  527. var title = 'browser';
  528. var platform = 'browser';
  529. var browser = true;
  530. var env = {};
  531. var argv = [];
  532. var version = ''; // empty string to avoid regexp issues
  533. var versions = {};
  534. var release = {};
  535. var config = {};
  536. function noop() {}
  537. var on = noop;
  538. var addListener = noop;
  539. var once = noop;
  540. var off = noop;
  541. var removeListener = noop;
  542. var removeAllListeners = noop;
  543. var emit = noop;
  544. function binding(name) {
  545. throw new Error('process.binding is not supported');
  546. }
  547. function cwd() {
  548. return '/';
  549. }
  550. function chdir(dir) {
  551. throw new Error('process.chdir is not supported');
  552. }
  553. function umask() {
  554. return 0;
  555. } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
  556. var performance = global.performance || {};
  557. var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function () {
  558. return new Date().getTime();
  559. }; // generate timestamp or delta
  560. // see http://nodejs.org/api/process.html#process_process_hrtime
  561. function hrtime(previousTimestamp) {
  562. var clocktime = performanceNow.call(performance) * 1e-3;
  563. var seconds = Math.floor(clocktime);
  564. var nanoseconds = Math.floor(clocktime % 1 * 1e9);
  565. if (previousTimestamp) {
  566. seconds = seconds - previousTimestamp[0];
  567. nanoseconds = nanoseconds - previousTimestamp[1];
  568. if (nanoseconds < 0) {
  569. seconds--;
  570. nanoseconds += 1e9;
  571. }
  572. }
  573. return [seconds, nanoseconds];
  574. }
  575. var startTime = new Date();
  576. function uptime() {
  577. var currentTime = new Date();
  578. var dif = currentTime - startTime;
  579. return dif / 1000;
  580. }
  581. var process = {
  582. nextTick: nextTick,
  583. title: title,
  584. browser: browser,
  585. env: env,
  586. argv: argv,
  587. version: version,
  588. versions: versions,
  589. on: on,
  590. addListener: addListener,
  591. once: once,
  592. off: off,
  593. removeListener: removeListener,
  594. removeAllListeners: removeAllListeners,
  595. emit: emit,
  596. binding: binding,
  597. cwd: cwd,
  598. chdir: chdir,
  599. umask: umask,
  600. hrtime: hrtime,
  601. platform: platform,
  602. release: release,
  603. config: config,
  604. uptime: uptime
  605. };
  606. var inherits;
  607. if (typeof Object.create === 'function') {
  608. inherits = function inherits(ctor, superCtor) {
  609. // implementation from standard node.js 'util' module
  610. ctor.super_ = superCtor;
  611. ctor.prototype = Object.create(superCtor.prototype, {
  612. constructor: {
  613. value: ctor,
  614. enumerable: false,
  615. writable: true,
  616. configurable: true
  617. }
  618. });
  619. };
  620. } else {
  621. inherits = function inherits(ctor, superCtor) {
  622. ctor.super_ = superCtor;
  623. var TempCtor = function TempCtor() {};
  624. TempCtor.prototype = superCtor.prototype;
  625. ctor.prototype = new TempCtor();
  626. ctor.prototype.constructor = ctor;
  627. };
  628. }
  629. var inherits$1 = inherits;
  630. var formatRegExp = /%[sdj%]/g;
  631. function format(f) {
  632. if (!isString(f)) {
  633. var objects = [];
  634. for (var i = 0; i < arguments.length; i++) {
  635. objects.push(inspect(arguments[i]));
  636. }
  637. return objects.join(' ');
  638. }
  639. var i = 1;
  640. var args = arguments;
  641. var len = args.length;
  642. var str = String(f).replace(formatRegExp, function (x) {
  643. if (x === '%%') return '%';
  644. if (i >= len) return x;
  645. switch (x) {
  646. case '%s':
  647. return String(args[i++]);
  648. case '%d':
  649. return Number(args[i++]);
  650. case '%j':
  651. try {
  652. return JSON.stringify(args[i++]);
  653. } catch (_) {
  654. return '[Circular]';
  655. }
  656. default:
  657. return x;
  658. }
  659. });
  660. for (var x = args[i]; i < len; x = args[++i]) {
  661. if (isNull(x) || !isObject(x)) {
  662. str += ' ' + x;
  663. } else {
  664. str += ' ' + inspect(x);
  665. }
  666. }
  667. return str;
  668. }
  669. // Returns a modified function which warns once by default.
  670. // If --no-deprecation is set, then it is a no-op.
  671. function deprecate(fn, msg) {
  672. // Allow for deprecating things in the process of starting up.
  673. if (isUndefined(global.process)) {
  674. return function () {
  675. return deprecate(fn, msg).apply(this, arguments);
  676. };
  677. }
  678. var warned = false;
  679. function deprecated() {
  680. if (!warned) {
  681. {
  682. console.error(msg);
  683. }
  684. warned = true;
  685. }
  686. return fn.apply(this, arguments);
  687. }
  688. return deprecated;
  689. }
  690. var debugs = {};
  691. var debugEnviron;
  692. function debuglog(set) {
  693. if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || '';
  694. set = set.toUpperCase();
  695. if (!debugs[set]) {
  696. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  697. var pid = 0;
  698. debugs[set] = function () {
  699. var msg = format.apply(null, arguments);
  700. console.error('%s %d: %s', set, pid, msg);
  701. };
  702. } else {
  703. debugs[set] = function () {};
  704. }
  705. }
  706. return debugs[set];
  707. }
  708. /**
  709. * Echos the value of a value. Trys to print the value out
  710. * in the best way possible given the different types.
  711. *
  712. * @param {Object} obj The object to print out.
  713. * @param {Object} opts Optional options object that alters the output.
  714. */
  715. /* legacy: obj, showHidden, depth, colors*/
  716. function inspect(obj, opts) {
  717. // default options
  718. var ctx = {
  719. seen: [],
  720. stylize: stylizeNoColor
  721. }; // legacy...
  722. if (arguments.length >= 3) ctx.depth = arguments[2];
  723. if (arguments.length >= 4) ctx.colors = arguments[3];
  724. if (isBoolean(opts)) {
  725. // legacy...
  726. ctx.showHidden = opts;
  727. } else if (opts) {
  728. // got an "options" object
  729. _extend(ctx, opts);
  730. } // set default options
  731. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  732. if (isUndefined(ctx.depth)) ctx.depth = 2;
  733. if (isUndefined(ctx.colors)) ctx.colors = false;
  734. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  735. if (ctx.colors) ctx.stylize = stylizeWithColor;
  736. return formatValue(ctx, obj, ctx.depth);
  737. } // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  738. inspect.colors = {
  739. 'bold': [1, 22],
  740. 'italic': [3, 23],
  741. 'underline': [4, 24],
  742. 'inverse': [7, 27],
  743. 'white': [37, 39],
  744. 'grey': [90, 39],
  745. 'black': [30, 39],
  746. 'blue': [34, 39],
  747. 'cyan': [36, 39],
  748. 'green': [32, 39],
  749. 'magenta': [35, 39],
  750. 'red': [31, 39],
  751. 'yellow': [33, 39]
  752. }; // Don't use 'blue' not visible on cmd.exe
  753. inspect.styles = {
  754. 'special': 'cyan',
  755. 'number': 'yellow',
  756. 'boolean': 'yellow',
  757. 'undefined': 'grey',
  758. 'null': 'bold',
  759. 'string': 'green',
  760. 'date': 'magenta',
  761. // "name": intentionally not styling
  762. 'regexp': 'red'
  763. };
  764. function stylizeWithColor(str, styleType) {
  765. var style = inspect.styles[styleType];
  766. if (style) {
  767. return "\x1B[" + inspect.colors[style][0] + 'm' + str + "\x1B[" + inspect.colors[style][1] + 'm';
  768. } else {
  769. return str;
  770. }
  771. }
  772. function stylizeNoColor(str, styleType) {
  773. return str;
  774. }
  775. function arrayToHash(array) {
  776. var hash = {};
  777. array.forEach(function (val, idx) {
  778. hash[val] = true;
  779. });
  780. return hash;
  781. }
  782. function formatValue(ctx, value, recurseTimes) {
  783. // Provide a hook for user-specified inspect functions.
  784. // Check that value is an object with an inspect function on it
  785. if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special
  786. value.inspect !== inspect && // Also filter out any prototype objects using the circular check.
  787. !(value.constructor && value.constructor.prototype === value)) {
  788. var ret = value.inspect(recurseTimes, ctx);
  789. if (!isString(ret)) {
  790. ret = formatValue(ctx, ret, recurseTimes);
  791. }
  792. return ret;
  793. } // Primitive types cannot have properties
  794. var primitive = formatPrimitive(ctx, value);
  795. if (primitive) {
  796. return primitive;
  797. } // Look up the keys of the object.
  798. var keys = Object.keys(value);
  799. var visibleKeys = arrayToHash(keys);
  800. if (ctx.showHidden) {
  801. keys = Object.getOwnPropertyNames(value);
  802. } // IE doesn't make error fields non-enumerable
  803. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  804. if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  805. return formatError(value);
  806. } // Some type of object without properties can be shortcutted.
  807. if (keys.length === 0) {
  808. if (isFunction(value)) {
  809. var name = value.name ? ': ' + value.name : '';
  810. return ctx.stylize('[Function' + name + ']', 'special');
  811. }
  812. if (isRegExp(value)) {
  813. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  814. }
  815. if (isDate(value)) {
  816. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  817. }
  818. if (isError(value)) {
  819. return formatError(value);
  820. }
  821. }
  822. var base = '',
  823. array = false,
  824. braces = ['{', '}']; // Make Array say that they are Array
  825. if (isArray(value)) {
  826. array = true;
  827. braces = ['[', ']'];
  828. } // Make functions say that they are functions
  829. if (isFunction(value)) {
  830. var n = value.name ? ': ' + value.name : '';
  831. base = ' [Function' + n + ']';
  832. } // Make RegExps say that they are RegExps
  833. if (isRegExp(value)) {
  834. base = ' ' + RegExp.prototype.toString.call(value);
  835. } // Make dates with properties first say the date
  836. if (isDate(value)) {
  837. base = ' ' + Date.prototype.toUTCString.call(value);
  838. } // Make error with message first say the error
  839. if (isError(value)) {
  840. base = ' ' + formatError(value);
  841. }
  842. if (keys.length === 0 && (!array || value.length == 0)) {
  843. return braces[0] + base + braces[1];
  844. }
  845. if (recurseTimes < 0) {
  846. if (isRegExp(value)) {
  847. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  848. } else {
  849. return ctx.stylize('[Object]', 'special');
  850. }
  851. }
  852. ctx.seen.push(value);
  853. var output;
  854. if (array) {
  855. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  856. } else {
  857. output = keys.map(function (key) {
  858. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  859. });
  860. }
  861. ctx.seen.pop();
  862. return reduceToSingleString(output, base, braces);
  863. }
  864. function formatPrimitive(ctx, value) {
  865. if (isUndefined(value)) return ctx.stylize('undefined', 'undefined');
  866. if (isString(value)) {
  867. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '').replace(/'/g, "\\'").replace(/\\"/g, '"') + '\'';
  868. return ctx.stylize(simple, 'string');
  869. }
  870. if (isNumber(value)) return ctx.stylize('' + value, 'number');
  871. if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here.
  872. if (isNull(value)) return ctx.stylize('null', 'null');
  873. }
  874. function formatError(value) {
  875. return '[' + Error.prototype.toString.call(value) + ']';
  876. }
  877. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  878. var output = [];
  879. for (var i = 0, l = value.length; i < l; ++i) {
  880. if (hasOwnProperty(value, String(i))) {
  881. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true));
  882. } else {
  883. output.push('');
  884. }
  885. }
  886. keys.forEach(function (key) {
  887. if (!key.match(/^\d+$/)) {
  888. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true));
  889. }
  890. });
  891. return output;
  892. }
  893. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  894. var name, str, desc;
  895. desc = Object.getOwnPropertyDescriptor(value, key) || {
  896. value: value[key]
  897. };
  898. if (desc.get) {
  899. if (desc.set) {
  900. str = ctx.stylize('[Getter/Setter]', 'special');
  901. } else {
  902. str = ctx.stylize('[Getter]', 'special');
  903. }
  904. } else {
  905. if (desc.set) {
  906. str = ctx.stylize('[Setter]', 'special');
  907. }
  908. }
  909. if (!hasOwnProperty(visibleKeys, key)) {
  910. name = '[' + key + ']';
  911. }
  912. if (!str) {
  913. if (ctx.seen.indexOf(desc.value) < 0) {
  914. if (isNull(recurseTimes)) {
  915. str = formatValue(ctx, desc.value, null);
  916. } else {
  917. str = formatValue(ctx, desc.value, recurseTimes - 1);
  918. }
  919. if (str.indexOf('\n') > -1) {
  920. if (array) {
  921. str = str.split('\n').map(function (line) {
  922. return ' ' + line;
  923. }).join('\n').substr(2);
  924. } else {
  925. str = '\n' + str.split('\n').map(function (line) {
  926. return ' ' + line;
  927. }).join('\n');
  928. }
  929. }
  930. } else {
  931. str = ctx.stylize('[Circular]', 'special');
  932. }
  933. }
  934. if (isUndefined(name)) {
  935. if (array && key.match(/^\d+$/)) {
  936. return str;
  937. }
  938. name = JSON.stringify('' + key);
  939. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  940. name = name.substr(1, name.length - 2);
  941. name = ctx.stylize(name, 'name');
  942. } else {
  943. name = name.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'");
  944. name = ctx.stylize(name, 'string');
  945. }
  946. }
  947. return name + ': ' + str;
  948. }
  949. function reduceToSingleString(output, base, braces) {
  950. var length = output.reduce(function (prev, cur) {
  951. if (cur.indexOf('\n') >= 0) ;
  952. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  953. }, 0);
  954. if (length > 60) {
  955. return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1];
  956. }
  957. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  958. } // NOTE: These type checking functions intentionally don't use `instanceof`
  959. // because it is fragile and can be easily faked with `Object.create()`.
  960. function isArray(ar) {
  961. return Array.isArray(ar);
  962. }
  963. function isBoolean(arg) {
  964. return typeof arg === 'boolean';
  965. }
  966. function isNull(arg) {
  967. return arg === null;
  968. }
  969. function isNullOrUndefined(arg) {
  970. return arg == null;
  971. }
  972. function isNumber(arg) {
  973. return typeof arg === 'number';
  974. }
  975. function isString(arg) {
  976. return typeof arg === 'string';
  977. }
  978. function isSymbol(arg) {
  979. return _typeof(arg) === 'symbol';
  980. }
  981. function isUndefined(arg) {
  982. return arg === void 0;
  983. }
  984. function isRegExp(re) {
  985. return isObject(re) && objectToString(re) === '[object RegExp]';
  986. }
  987. function isObject(arg) {
  988. return _typeof(arg) === 'object' && arg !== null;
  989. }
  990. function isDate(d) {
  991. return isObject(d) && objectToString(d) === '[object Date]';
  992. }
  993. function isError(e) {
  994. return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error);
  995. }
  996. function isFunction(arg) {
  997. return typeof arg === 'function';
  998. }
  999. function isPrimitive(arg) {
  1000. return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || _typeof(arg) === 'symbol' || // ES6 symbol
  1001. typeof arg === 'undefined';
  1002. }
  1003. function isBuffer(maybeBuf) {
  1004. return Buffer.isBuffer(maybeBuf);
  1005. }
  1006. function objectToString(o) {
  1007. return Object.prototype.toString.call(o);
  1008. }
  1009. function pad(n) {
  1010. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  1011. }
  1012. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34
  1013. function timestamp$1() {
  1014. var d = new Date();
  1015. var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':');
  1016. return [d.getDate(), months[d.getMonth()], time].join(' ');
  1017. } // log is just a thin wrapper to console.log that prepends a timestamp
  1018. function log() {
  1019. console.log('%s - %s', timestamp$1(), format.apply(null, arguments));
  1020. }
  1021. function _extend(origin, add) {
  1022. // Don't do anything if add isn't an object
  1023. if (!add || !isObject(add)) return origin;
  1024. var keys = Object.keys(add);
  1025. var i = keys.length;
  1026. while (i--) {
  1027. origin[keys[i]] = add[keys[i]];
  1028. }
  1029. return origin;
  1030. }
  1031. function hasOwnProperty(obj, prop) {
  1032. return Object.prototype.hasOwnProperty.call(obj, prop);
  1033. }
  1034. var require$$2 = {
  1035. inherits: inherits$1,
  1036. _extend: _extend,
  1037. log: log,
  1038. isBuffer: isBuffer,
  1039. isPrimitive: isPrimitive,
  1040. isFunction: isFunction,
  1041. isError: isError,
  1042. isDate: isDate,
  1043. isObject: isObject,
  1044. isRegExp: isRegExp,
  1045. isUndefined: isUndefined,
  1046. isSymbol: isSymbol,
  1047. isString: isString,
  1048. isNumber: isNumber,
  1049. isNullOrUndefined: isNullOrUndefined,
  1050. isNull: isNull,
  1051. isBoolean: isBoolean,
  1052. isArray: isArray,
  1053. inspect: inspect,
  1054. deprecate: deprecate,
  1055. format: format,
  1056. debuglog: debuglog
  1057. };
  1058. var Buffer$1 = buffer.Buffer;
  1059. var randomBytes$1 = utils.randomBytes;
  1060. var deprecate$1 = require$$2.deprecate; // constants
  1061. var PROCESS_UNIQUE = randomBytes$1(5); // Regular expression that checks for hex value
  1062. var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$');
  1063. var hasBufferType = false; // Check if buffer exists
  1064. try {
  1065. if (Buffer$1 && Buffer$1.from) hasBufferType = true;
  1066. } catch (err) {
  1067. hasBufferType = false;
  1068. } // Precomputed hex table enables speedy hex string conversion
  1069. var hexTable = [];
  1070. for (var _i = 0; _i < 256; _i++) {
  1071. hexTable[_i] = (_i <= 15 ? '0' : '') + _i.toString(16);
  1072. } // Lookup tables
  1073. var decodeLookup = [];
  1074. var i = 0;
  1075. while (i < 10) {
  1076. decodeLookup[0x30 + i] = i++;
  1077. }
  1078. while (i < 16) {
  1079. decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++;
  1080. }
  1081. var _Buffer = Buffer$1;
  1082. function convertToHex(bytes) {
  1083. return bytes.toString('hex');
  1084. }
  1085. function makeObjectIdError(invalidString, index) {
  1086. var invalidCharacter = invalidString[index];
  1087. return new TypeError("ObjectId string \"".concat(invalidString, "\" contains invalid character \"").concat(invalidCharacter, "\" with character code (").concat(invalidString.charCodeAt(index), "). All character codes for a non-hex string must be less than 256."));
  1088. }
  1089. /**
  1090. * A class representation of the BSON ObjectId type.
  1091. */
  1092. var ObjectId =
  1093. /*#__PURE__*/
  1094. function () {
  1095. /**
  1096. * Create an ObjectId type
  1097. *
  1098. * @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number.
  1099. * @property {number} generationTime The generation time of this ObjectId instance
  1100. * @return {ObjectId} instance of ObjectId.
  1101. */
  1102. function ObjectId(id) {
  1103. _classCallCheck(this, ObjectId);
  1104. // Duck-typing to support ObjectId from different npm packages
  1105. if (id instanceof ObjectId) return id; // The most common usecase (blank id, new objectId instance)
  1106. if (id == null || typeof id === 'number') {
  1107. // Generate a new id
  1108. this.id = ObjectId.generate(id); // If we are caching the hex string
  1109. if (ObjectId.cacheHexString) this.__id = this.toString('hex'); // Return the object
  1110. return;
  1111. } // Check if the passed in id is valid
  1112. var valid = ObjectId.isValid(id); // Throw an error if it's not a valid setup
  1113. if (!valid && id != null) {
  1114. throw new TypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters');
  1115. } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) {
  1116. return new ObjectId(Buffer$1.from(id, 'hex'));
  1117. } else if (valid && typeof id === 'string' && id.length === 24) {
  1118. return ObjectId.createFromHexString(id);
  1119. } else if (id != null && id.length === 12) {
  1120. // assume 12 byte string
  1121. this.id = id;
  1122. } else if (id != null && id.toHexString) {
  1123. // Duck-typing to support ObjectId from different npm packages
  1124. return id;
  1125. } else {
  1126. throw new TypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters');
  1127. }
  1128. if (ObjectId.cacheHexString) this.__id = this.toString('hex');
  1129. }
  1130. /**
  1131. * Return the ObjectId id as a 24 byte hex string representation
  1132. *
  1133. * @method
  1134. * @return {string} return the 24 byte hex string representation.
  1135. */
  1136. _createClass(ObjectId, [{
  1137. key: "toHexString",
  1138. value: function toHexString() {
  1139. if (ObjectId.cacheHexString && this.__id) return this.__id;
  1140. var hexString = '';
  1141. if (!this.id || !this.id.length) {
  1142. throw new TypeError('invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + JSON.stringify(this.id) + ']');
  1143. }
  1144. if (this.id instanceof _Buffer) {
  1145. hexString = convertToHex(this.id);
  1146. if (ObjectId.cacheHexString) this.__id = hexString;
  1147. return hexString;
  1148. }
  1149. for (var _i2 = 0; _i2 < this.id.length; _i2++) {
  1150. var hexChar = hexTable[this.id.charCodeAt(_i2)];
  1151. if (typeof hexChar !== 'string') {
  1152. throw makeObjectIdError(this.id, _i2);
  1153. }
  1154. hexString += hexChar;
  1155. }
  1156. if (ObjectId.cacheHexString) this.__id = hexString;
  1157. return hexString;
  1158. }
  1159. /**
  1160. * Update the ObjectId index used in generating new ObjectId's on the driver
  1161. *
  1162. * @method
  1163. * @return {number} returns next index value.
  1164. * @ignore
  1165. */
  1166. }, {
  1167. key: "toString",
  1168. /**
  1169. * Converts the id into a 24 byte hex string for printing
  1170. *
  1171. * @param {String} format The Buffer toString format parameter.
  1172. * @return {String} return the 24 byte hex string representation.
  1173. * @ignore
  1174. */
  1175. value: function toString(format) {
  1176. // Is the id a buffer then use the buffer toString method to return the format
  1177. if (this.id && this.id.copy) {
  1178. return this.id.toString(typeof format === 'string' ? format : 'hex');
  1179. }
  1180. return this.toHexString();
  1181. }
  1182. /**
  1183. * Converts to its JSON representation.
  1184. *
  1185. * @return {String} return the 24 byte hex string representation.
  1186. * @ignore
  1187. */
  1188. }, {
  1189. key: "toJSON",
  1190. value: function toJSON() {
  1191. return this.toHexString();
  1192. }
  1193. /**
  1194. * Compares the equality of this ObjectId with `otherID`.
  1195. *
  1196. * @method
  1197. * @param {object} otherID ObjectId instance to compare against.
  1198. * @return {boolean} the result of comparing two ObjectId's
  1199. */
  1200. }, {
  1201. key: "equals",
  1202. value: function equals(otherId) {
  1203. if (otherId instanceof ObjectId) {
  1204. return this.toString() === otherId.toString();
  1205. }
  1206. if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12 && this.id instanceof _Buffer) {
  1207. return otherId === this.id.toString('binary');
  1208. }
  1209. if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) {
  1210. return otherId.toLowerCase() === this.toHexString();
  1211. }
  1212. if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) {
  1213. return otherId === this.id;
  1214. }
  1215. if (otherId != null && (otherId instanceof ObjectId || otherId.toHexString)) {
  1216. return otherId.toHexString() === this.toHexString();
  1217. }
  1218. return false;
  1219. }
  1220. /**
  1221. * Returns the generation date (accurate up to the second) that this ID was generated.
  1222. *
  1223. * @method
  1224. * @return {date} the generation date
  1225. */
  1226. }, {
  1227. key: "getTimestamp",
  1228. value: function getTimestamp() {
  1229. var timestamp = new Date();
  1230. var time = this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24;
  1231. timestamp.setTime(Math.floor(time) * 1000);
  1232. return timestamp;
  1233. }
  1234. /**
  1235. * @ignore
  1236. */
  1237. }, {
  1238. key: "toExtendedJSON",
  1239. /**
  1240. * @ignore
  1241. */
  1242. value: function toExtendedJSON() {
  1243. if (this.toHexString) return {
  1244. $oid: this.toHexString()
  1245. };
  1246. return {
  1247. $oid: this.toString('hex')
  1248. };
  1249. }
  1250. /**
  1251. * @ignore
  1252. */
  1253. }], [{
  1254. key: "getInc",
  1255. value: function getInc() {
  1256. return ObjectId.index = (ObjectId.index + 1) % 0xffffff;
  1257. }
  1258. /**
  1259. * Generate a 12 byte id buffer used in ObjectId's
  1260. *
  1261. * @method
  1262. * @param {number} [time] optional parameter allowing to pass in a second based timestamp.
  1263. * @return {Buffer} return the 12 byte id buffer string.
  1264. */
  1265. }, {
  1266. key: "generate",
  1267. value: function generate(time) {
  1268. if ('number' !== typeof time) {
  1269. time = ~~(Date.now() / 1000);
  1270. }
  1271. var inc = ObjectId.getInc();
  1272. var buffer$$1 = Buffer$1.alloc(12); // 4-byte timestamp
  1273. buffer$$1[3] = time & 0xff;
  1274. buffer$$1[2] = time >> 8 & 0xff;
  1275. buffer$$1[1] = time >> 16 & 0xff;
  1276. buffer$$1[0] = time >> 24 & 0xff; // 5-byte process unique
  1277. buffer$$1[4] = PROCESS_UNIQUE[0];
  1278. buffer$$1[5] = PROCESS_UNIQUE[1];
  1279. buffer$$1[6] = PROCESS_UNIQUE[2];
  1280. buffer$$1[7] = PROCESS_UNIQUE[3];
  1281. buffer$$1[8] = PROCESS_UNIQUE[4]; // 3-byte counter
  1282. buffer$$1[11] = inc & 0xff;
  1283. buffer$$1[10] = inc >> 8 & 0xff;
  1284. buffer$$1[9] = inc >> 16 & 0xff;
  1285. return buffer$$1;
  1286. }
  1287. }, {
  1288. key: "createPk",
  1289. value: function createPk() {
  1290. return new ObjectId();
  1291. }
  1292. /**
  1293. * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId.
  1294. *
  1295. * @method
  1296. * @param {number} time an integer number representing a number of seconds.
  1297. * @return {ObjectId} return the created ObjectId
  1298. */
  1299. }, {
  1300. key: "createFromTime",
  1301. value: function createFromTime(time) {
  1302. var buffer$$1 = Buffer$1.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); // Encode time into first 4 bytes
  1303. buffer$$1[3] = time & 0xff;
  1304. buffer$$1[2] = time >> 8 & 0xff;
  1305. buffer$$1[1] = time >> 16 & 0xff;
  1306. buffer$$1[0] = time >> 24 & 0xff; // Return the new objectId
  1307. return new ObjectId(buffer$$1);
  1308. }
  1309. /**
  1310. * Creates an ObjectId from a hex string representation of an ObjectId.
  1311. *
  1312. * @method
  1313. * @param {string} hexString create a ObjectId from a passed in 24 byte hexstring.
  1314. * @return {ObjectId} return the created ObjectId
  1315. */
  1316. }, {
  1317. key: "createFromHexString",
  1318. value: function createFromHexString(string) {
  1319. // Throw an error if it's not a valid setup
  1320. if (typeof string === 'undefined' || string != null && string.length !== 24) {
  1321. throw new TypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters');
  1322. } // Use Buffer.from method if available
  1323. if (hasBufferType) return new ObjectId(Buffer$1.from(string, 'hex')); // Calculate lengths
  1324. var array = new _Buffer(12);
  1325. var n = 0;
  1326. var i = 0;
  1327. while (i < 24) {
  1328. array[n++] = decodeLookup[string.charCodeAt(i++)] << 4 | decodeLookup[string.charCodeAt(i++)];
  1329. }
  1330. return new ObjectId(array);
  1331. }
  1332. /**
  1333. * Checks if a value is a valid bson ObjectId
  1334. *
  1335. * @method
  1336. * @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise.
  1337. */
  1338. }, {
  1339. key: "isValid",
  1340. value: function isValid(id) {
  1341. if (id == null) return false;
  1342. if (typeof id === 'number') {
  1343. return true;
  1344. }
  1345. if (typeof id === 'string') {
  1346. return id.length === 12 || id.length === 24 && checkForHexRegExp.test(id);
  1347. }
  1348. if (id instanceof ObjectId) {
  1349. return true;
  1350. }
  1351. if (id instanceof _Buffer && id.length === 12) {
  1352. return true;
  1353. } // Duck-Typing detection of ObjectId like objects
  1354. if (id.toHexString) {
  1355. return id.id.length === 12 || id.id.length === 24 && checkForHexRegExp.test(id.id);
  1356. }
  1357. return false;
  1358. }
  1359. }, {
  1360. key: "fromExtendedJSON",
  1361. value: function fromExtendedJSON(doc) {
  1362. return new ObjectId(doc.$oid);
  1363. }
  1364. }]);
  1365. return ObjectId;
  1366. }(); // Deprecated methods
  1367. ObjectId.get_inc = deprecate$1(function () {
  1368. return ObjectId.getInc();
  1369. }, 'Please use the static `ObjectId.getInc()` instead');
  1370. ObjectId.prototype.get_inc = deprecate$1(function () {
  1371. return ObjectId.getInc();
  1372. }, 'Please use the static `ObjectId.getInc()` instead');
  1373. ObjectId.prototype.getInc = deprecate$1(function () {
  1374. return ObjectId.getInc();
  1375. }, 'Please use the static `ObjectId.getInc()` instead');
  1376. ObjectId.prototype.generate = deprecate$1(function (time) {
  1377. return ObjectId.generate(time);
  1378. }, 'Please use the static `ObjectId.generate(time)` instead');
  1379. /**
  1380. * @ignore
  1381. */
  1382. Object.defineProperty(ObjectId.prototype, 'generationTime', {
  1383. enumerable: true,
  1384. get: function get() {
  1385. return this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24;
  1386. },
  1387. set: function set(value) {
  1388. // Encode time into first 4 bytes
  1389. this.id[3] = value & 0xff;
  1390. this.id[2] = value >> 8 & 0xff;
  1391. this.id[1] = value >> 16 & 0xff;
  1392. this.id[0] = value >> 24 & 0xff;
  1393. }
  1394. });
  1395. /**
  1396. * Converts to a string representation of this Id.
  1397. *
  1398. * @return {String} return the 24 byte hex string representation.
  1399. * @ignore
  1400. */
  1401. ObjectId.prototype.inspect = ObjectId.prototype.toString;
  1402. /**
  1403. * @ignore
  1404. */
  1405. ObjectId.index = ~~(Math.random() * 0xffffff);
  1406. Object.defineProperty(ObjectId.prototype, '_bsontype', {
  1407. value: 'ObjectId'
  1408. });
  1409. var objectid = ObjectId;
  1410. function alphabetize(str) {
  1411. return str.split('').sort().join('');
  1412. }
  1413. /**
  1414. * A class representation of the BSON RegExp type.
  1415. */
  1416. var BSONRegExp =
  1417. /*#__PURE__*/
  1418. function () {
  1419. /**
  1420. * Create a RegExp type
  1421. *
  1422. * @param {string} pattern The regular expression pattern to match
  1423. * @param {string} options The regular expression options
  1424. */
  1425. function BSONRegExp(pattern, options) {
  1426. _classCallCheck(this, BSONRegExp);
  1427. // Execute
  1428. this.pattern = pattern || '';
  1429. this.options = options ? alphabetize(options) : ''; // Validate options
  1430. for (var i = 0; i < this.options.length; i++) {
  1431. 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')) {
  1432. throw new Error("The regular expression option [".concat(this.options[i], "] is not supported"));
  1433. }
  1434. }
  1435. }
  1436. /**
  1437. * @ignore
  1438. */
  1439. _createClass(BSONRegExp, [{
  1440. key: "toExtendedJSON",
  1441. value: function toExtendedJSON() {
  1442. return {
  1443. $regularExpression: {
  1444. pattern: this.pattern,
  1445. options: this.options
  1446. }
  1447. };
  1448. }
  1449. /**
  1450. * @ignore
  1451. */
  1452. }], [{
  1453. key: "fromExtendedJSON",
  1454. value: function fromExtendedJSON(doc) {
  1455. return new BSONRegExp(doc.$regularExpression.pattern, doc.$regularExpression.options.split('').sort().join(''));
  1456. }
  1457. }]);
  1458. return BSONRegExp;
  1459. }();
  1460. Object.defineProperty(BSONRegExp.prototype, '_bsontype', {
  1461. value: 'BSONRegExp'
  1462. });
  1463. var regexp = BSONRegExp;
  1464. var BSONSymbol =
  1465. /*#__PURE__*/
  1466. function () {
  1467. /**
  1468. * Create a Symbol type
  1469. *
  1470. * @param {string} value the string representing the symbol.
  1471. */
  1472. function BSONSymbol(value) {
  1473. _classCallCheck(this, BSONSymbol);
  1474. this.value = value;
  1475. }
  1476. /**
  1477. * Access the wrapped string value.
  1478. *
  1479. * @method
  1480. * @return {String} returns the wrapped string.
  1481. */
  1482. _createClass(BSONSymbol, [{
  1483. key: "valueOf",
  1484. value: function valueOf() {
  1485. return this.value;
  1486. }
  1487. /**
  1488. * @ignore
  1489. */
  1490. }, {
  1491. key: "toString",
  1492. value: function toString() {
  1493. return this.value;
  1494. }
  1495. /**
  1496. * @ignore
  1497. */
  1498. }, {
  1499. key: "inspect",
  1500. value: function inspect() {
  1501. return this.value;
  1502. }
  1503. /**
  1504. * @ignore
  1505. */
  1506. }, {
  1507. key: "toJSON",
  1508. value: function toJSON() {
  1509. return this.value;
  1510. }
  1511. /**
  1512. * @ignore
  1513. */
  1514. }, {
  1515. key: "toExtendedJSON",
  1516. value: function toExtendedJSON() {
  1517. return {
  1518. $symbol: this.value
  1519. };
  1520. }
  1521. /**
  1522. * @ignore
  1523. */
  1524. }], [{
  1525. key: "fromExtendedJSON",
  1526. value: function fromExtendedJSON(doc) {
  1527. return new BSONSymbol(doc.$symbol);
  1528. }
  1529. }]);
  1530. return BSONSymbol;
  1531. }();
  1532. Object.defineProperty(BSONSymbol.prototype, '_bsontype', {
  1533. value: 'Symbol'
  1534. });
  1535. var symbol = BSONSymbol;
  1536. var Int32 =
  1537. /*#__PURE__*/
  1538. function () {
  1539. /**
  1540. * Create an Int32 type
  1541. *
  1542. * @param {number} value the number we want to represent as an int32.
  1543. * @return {Int32}
  1544. */
  1545. function Int32(value) {
  1546. _classCallCheck(this, Int32);
  1547. this.value = value;
  1548. }
  1549. /**
  1550. * Access the number value.
  1551. *
  1552. * @method
  1553. * @return {number} returns the wrapped int32 number.
  1554. */
  1555. _createClass(Int32, [{
  1556. key: "valueOf",
  1557. value: function valueOf() {
  1558. return this.value;
  1559. }
  1560. /**
  1561. * @ignore
  1562. */
  1563. }, {
  1564. key: "toJSON",
  1565. value: function toJSON() {
  1566. return this.value;
  1567. }
  1568. /**
  1569. * @ignore
  1570. */
  1571. }, {
  1572. key: "toExtendedJSON",
  1573. value: function toExtendedJSON(options) {
  1574. if (options && options.relaxed) return this.value;
  1575. return {
  1576. $numberInt: this.value.toString()
  1577. };
  1578. }
  1579. /**
  1580. * @ignore
  1581. */
  1582. }], [{
  1583. key: "fromExtendedJSON",
  1584. value: function fromExtendedJSON(doc, options) {
  1585. return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt);
  1586. }
  1587. }]);
  1588. return Int32;
  1589. }();
  1590. Object.defineProperty(Int32.prototype, '_bsontype', {
  1591. value: 'Int32'
  1592. });
  1593. var int_32 = Int32;
  1594. var Code =
  1595. /*#__PURE__*/
  1596. function () {
  1597. /**
  1598. * Create a Code type
  1599. *
  1600. * @param {(string|function)} code a string or function.
  1601. * @param {Object} [scope] an optional scope for the function.
  1602. * @return {Code}
  1603. */
  1604. function Code(code, scope) {
  1605. _classCallCheck(this, Code);
  1606. this.code = code;
  1607. this.scope = scope;
  1608. }
  1609. /**
  1610. * @ignore
  1611. */
  1612. _createClass(Code, [{
  1613. key: "toJSON",
  1614. value: function toJSON() {
  1615. return {
  1616. scope: this.scope,
  1617. code: this.code
  1618. };
  1619. }
  1620. /**
  1621. * @ignore
  1622. */
  1623. }, {
  1624. key: "toExtendedJSON",
  1625. value: function toExtendedJSON() {
  1626. if (this.scope) {
  1627. return {
  1628. $code: this.code,
  1629. $scope: this.scope
  1630. };
  1631. }
  1632. return {
  1633. $code: this.code
  1634. };
  1635. }
  1636. /**
  1637. * @ignore
  1638. */
  1639. }], [{
  1640. key: "fromExtendedJSON",
  1641. value: function fromExtendedJSON(doc) {
  1642. return new Code(doc.$code, doc.$scope);
  1643. }
  1644. }]);
  1645. return Code;
  1646. }();
  1647. Object.defineProperty(Code.prototype, '_bsontype', {
  1648. value: 'Code'
  1649. });
  1650. var code = Code;
  1651. var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
  1652. var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
  1653. var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
  1654. var EXPONENT_MAX = 6111;
  1655. var EXPONENT_MIN = -6176;
  1656. var EXPONENT_BIAS = 6176;
  1657. var MAX_DIGITS = 34; // Nan value bits as 32 bit values (due to lack of longs)
  1658. 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)
  1659. var INF_NEGATIVE_BUFFER = [0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse();
  1660. var INF_POSITIVE_BUFFER = [0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse();
  1661. var EXPONENT_REGEX = /^([-+])?(\d+)?$/; // Detect if the value is a digit
  1662. function isDigit(value) {
  1663. return !isNaN(parseInt(value, 10));
  1664. } // Divide two uint128 values
  1665. function divideu128(value) {
  1666. var DIVISOR = long_1.fromNumber(1000 * 1000 * 1000);
  1667. var _rem = long_1.fromNumber(0);
  1668. if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
  1669. return {
  1670. quotient: value,
  1671. rem: _rem
  1672. };
  1673. }
  1674. for (var i = 0; i <= 3; i++) {
  1675. // Adjust remainder to match value of next dividend
  1676. _rem = _rem.shiftLeft(32); // Add the divided to _rem
  1677. _rem = _rem.add(new long_1(value.parts[i], 0));
  1678. value.parts[i] = _rem.div(DIVISOR).low;
  1679. _rem = _rem.modulo(DIVISOR);
  1680. }
  1681. return {
  1682. quotient: value,
  1683. rem: _rem
  1684. };
  1685. } // Multiply two Long values and return the 128 bit value
  1686. function multiply64x2(left, right) {
  1687. if (!left && !right) {
  1688. return {
  1689. high: long_1.fromNumber(0),
  1690. low: long_1.fromNumber(0)
  1691. };
  1692. }
  1693. var leftHigh = left.shiftRightUnsigned(32);
  1694. var leftLow = new long_1(left.getLowBits(), 0);
  1695. var rightHigh = right.shiftRightUnsigned(32);
  1696. var rightLow = new long_1(right.getLowBits(), 0);
  1697. var productHigh = leftHigh.multiply(rightHigh);
  1698. var productMid = leftHigh.multiply(rightLow);
  1699. var productMid2 = leftLow.multiply(rightHigh);
  1700. var productLow = leftLow.multiply(rightLow);
  1701. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  1702. productMid = new long_1(productMid.getLowBits(), 0).add(productMid2).add(productLow.shiftRightUnsigned(32));
  1703. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  1704. productLow = productMid.shiftLeft(32).add(new long_1(productLow.getLowBits(), 0)); // Return the 128 bit result
  1705. return {
  1706. high: productHigh,
  1707. low: productLow
  1708. };
  1709. }
  1710. function lessThan(left, right) {
  1711. // Make values unsigned
  1712. var uhleft = left.high >>> 0;
  1713. var uhright = right.high >>> 0; // Compare high bits first
  1714. if (uhleft < uhright) {
  1715. return true;
  1716. } else if (uhleft === uhright) {
  1717. var ulleft = left.low >>> 0;
  1718. var ulright = right.low >>> 0;
  1719. if (ulleft < ulright) return true;
  1720. }
  1721. return false;
  1722. }
  1723. function invalidErr(string, message) {
  1724. throw new TypeError("\"".concat(string, "\" is not a valid Decimal128 string - ").concat(message));
  1725. }
  1726. /**
  1727. * A class representation of the BSON Decimal128 type.
  1728. *
  1729. * @class
  1730. * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes.
  1731. * @return {Double}
  1732. */
  1733. function Decimal128(bytes) {
  1734. this.bytes = bytes;
  1735. }
  1736. /**
  1737. * Create a Decimal128 instance from a string representation
  1738. *
  1739. * @method
  1740. * @param {string} string a numeric string representation.
  1741. * @return {Decimal128} returns a Decimal128 instance.
  1742. */
  1743. Decimal128.fromString = function (string) {
  1744. // Parse state tracking
  1745. var isNegative = false;
  1746. var sawRadix = false;
  1747. var foundNonZero = false; // Total number of significant digits (no leading or trailing zero)
  1748. var significantDigits = 0; // Total number of significand digits read
  1749. var nDigitsRead = 0; // Total number of digits (no leading zeros)
  1750. var nDigits = 0; // The number of the digits after radix
  1751. var radixPosition = 0; // The index of the first non-zero in *str*
  1752. var firstNonZero = 0; // Digits Array
  1753. var digits = [0]; // The number of digits in digits
  1754. var nDigitsStored = 0; // Insertion pointer for digits
  1755. var digitsInsert = 0; // The index of the first non-zero digit
  1756. var firstDigit = 0; // The index of the last digit
  1757. var lastDigit = 0; // Exponent
  1758. var exponent = 0; // loop index over array
  1759. var i = 0; // The high 17 digits of the significand
  1760. var significandHigh = [0, 0]; // The low 17 digits of the significand
  1761. var significandLow = [0, 0]; // The biased exponent
  1762. var biasedExponent = 0; // Read index
  1763. var index = 0; // Naively prevent against REDOS attacks.
  1764. // TODO: implementing a custom parsing for this, or refactoring the regex would yield
  1765. // further gains.
  1766. if (string.length >= 7000) {
  1767. throw new TypeError('' + string + ' not a valid Decimal128 string');
  1768. } // Results
  1769. var stringMatch = string.match(PARSE_STRING_REGEXP);
  1770. var infMatch = string.match(PARSE_INF_REGEXP);
  1771. var nanMatch = string.match(PARSE_NAN_REGEXP); // Validate the string
  1772. if (!stringMatch && !infMatch && !nanMatch || string.length === 0) {
  1773. throw new TypeError('' + string + ' not a valid Decimal128 string');
  1774. }
  1775. if (stringMatch) {
  1776. // full_match = stringMatch[0]
  1777. // sign = stringMatch[1]
  1778. var unsignedNumber = stringMatch[2]; // stringMatch[3] is undefined if a whole number (ex "1", 12")
  1779. // but defined if a number w/ decimal in it (ex "1.0, 12.2")
  1780. var e = stringMatch[4];
  1781. var expSign = stringMatch[5];
  1782. var expNumber = stringMatch[6]; // they provided e, but didn't give an exponent number. for ex "1e"
  1783. if (e && expNumber === undefined) invalidErr(string, 'missing exponent power'); // they provided e, but didn't give a number before it. for ex "e1"
  1784. if (e && unsignedNumber === undefined) invalidErr(string, 'missing exponent base');
  1785. if (e === undefined && (expSign || expNumber)) {
  1786. invalidErr(string, 'missing e before exponent');
  1787. }
  1788. } // Get the negative or positive sign
  1789. if (string[index] === '+' || string[index] === '-') {
  1790. isNegative = string[index++] === '-';
  1791. } // Check if user passed Infinity or NaN
  1792. if (!isDigit(string[index]) && string[index] !== '.') {
  1793. if (string[index] === 'i' || string[index] === 'I') {
  1794. return new Decimal128(Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER));
  1795. } else if (string[index] === 'N') {
  1796. return new Decimal128(Buffer.from(NAN_BUFFER));
  1797. }
  1798. } // Read all the digits
  1799. while (isDigit(string[index]) || string[index] === '.') {
  1800. if (string[index] === '.') {
  1801. if (sawRadix) invalidErr(string, 'contains multiple periods');
  1802. sawRadix = true;
  1803. index = index + 1;
  1804. continue;
  1805. }
  1806. if (nDigitsStored < 34) {
  1807. if (string[index] !== '0' || foundNonZero) {
  1808. if (!foundNonZero) {
  1809. firstNonZero = nDigitsRead;
  1810. }
  1811. foundNonZero = true; // Only store 34 digits
  1812. digits[digitsInsert++] = parseInt(string[index], 10);
  1813. nDigitsStored = nDigitsStored + 1;
  1814. }
  1815. }
  1816. if (foundNonZero) nDigits = nDigits + 1;
  1817. if (sawRadix) radixPosition = radixPosition + 1;
  1818. nDigitsRead = nDigitsRead + 1;
  1819. index = index + 1;
  1820. }
  1821. if (sawRadix && !nDigitsRead) throw new TypeError('' + string + ' not a valid Decimal128 string'); // Read exponent if exists
  1822. if (string[index] === 'e' || string[index] === 'E') {
  1823. // Read exponent digits
  1824. var match = string.substr(++index).match(EXPONENT_REGEX); // No digits read
  1825. if (!match || !match[2]) return new Decimal128(Buffer.from(NAN_BUFFER)); // Get exponent
  1826. exponent = parseInt(match[0], 10); // Adjust the index
  1827. index = index + match[0].length;
  1828. } // Return not a number
  1829. if (string[index]) return new Decimal128(Buffer.from(NAN_BUFFER)); // Done reading input
  1830. // Find first non-zero digit in digits
  1831. firstDigit = 0;
  1832. if (!nDigitsStored) {
  1833. firstDigit = 0;
  1834. lastDigit = 0;
  1835. digits[0] = 0;
  1836. nDigits = 1;
  1837. nDigitsStored = 1;
  1838. significantDigits = 0;
  1839. } else {
  1840. lastDigit = nDigitsStored - 1;
  1841. significantDigits = nDigits;
  1842. if (significantDigits !== 1) {
  1843. while (string[firstNonZero + significantDigits - 1] === '0') {
  1844. significantDigits = significantDigits - 1;
  1845. }
  1846. }
  1847. } // Normalization of exponent
  1848. // Correct exponent based on radix position, and shift significand as needed
  1849. // to represent user input
  1850. // Overflow prevention
  1851. if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) {
  1852. exponent = EXPONENT_MIN;
  1853. } else {
  1854. exponent = exponent - radixPosition;
  1855. } // Attempt to normalize the exponent
  1856. while (exponent > EXPONENT_MAX) {
  1857. // Shift exponent to significand and decrease
  1858. lastDigit = lastDigit + 1;
  1859. if (lastDigit - firstDigit > MAX_DIGITS) {
  1860. // Check if we have a zero then just hard clamp, otherwise fail
  1861. var digitsString = digits.join('');
  1862. if (digitsString.match(/^0+$/)) {
  1863. exponent = EXPONENT_MAX;
  1864. break;
  1865. }
  1866. invalidErr(string, 'overflow');
  1867. }
  1868. exponent = exponent - 1;
  1869. }
  1870. while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
  1871. // Shift last digit. can only do this if < significant digits than # stored.
  1872. if (lastDigit === 0 && significantDigits < nDigitsStored) {
  1873. exponent = EXPONENT_MIN;
  1874. significantDigits = 0;
  1875. break;
  1876. }
  1877. if (nDigitsStored < nDigits) {
  1878. // adjust to match digits not stored
  1879. nDigits = nDigits - 1;
  1880. } else {
  1881. // adjust to round
  1882. lastDigit = lastDigit - 1;
  1883. }
  1884. if (exponent < EXPONENT_MAX) {
  1885. exponent = exponent + 1;
  1886. } else {
  1887. // Check if we have a zero then just hard clamp, otherwise fail
  1888. var _digitsString = digits.join('');
  1889. if (_digitsString.match(/^0+$/)) {
  1890. exponent = EXPONENT_MAX;
  1891. break;
  1892. }
  1893. invalidErr(string, 'overflow');
  1894. }
  1895. } // Round
  1896. // We've normalized the exponent, but might still need to round.
  1897. if (lastDigit - firstDigit + 1 < significantDigits) {
  1898. var endOfString = nDigitsRead; // If we have seen a radix point, 'string' is 1 longer than we have
  1899. // documented with ndigits_read, so inc the position of the first nonzero
  1900. // digit and the position that digits are read to.
  1901. if (sawRadix) {
  1902. firstNonZero = firstNonZero + 1;
  1903. endOfString = endOfString + 1;
  1904. } // if negative, we need to increment again to account for - sign at start.
  1905. if (isNegative) {
  1906. firstNonZero = firstNonZero + 1;
  1907. endOfString = endOfString + 1;
  1908. }
  1909. var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10);
  1910. var roundBit = 0;
  1911. if (roundDigit >= 5) {
  1912. roundBit = 1;
  1913. if (roundDigit === 5) {
  1914. roundBit = digits[lastDigit] % 2 === 1;
  1915. for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) {
  1916. if (parseInt(string[i], 10)) {
  1917. roundBit = 1;
  1918. break;
  1919. }
  1920. }
  1921. }
  1922. }
  1923. if (roundBit) {
  1924. var dIdx = lastDigit;
  1925. for (; dIdx >= 0; dIdx--) {
  1926. if (++digits[dIdx] > 9) {
  1927. digits[dIdx] = 0; // overflowed most significant digit
  1928. if (dIdx === 0) {
  1929. if (exponent < EXPONENT_MAX) {
  1930. exponent = exponent + 1;
  1931. digits[dIdx] = 1;
  1932. } else {
  1933. return new Decimal128(Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER));
  1934. }
  1935. }
  1936. }
  1937. }
  1938. }
  1939. } // Encode significand
  1940. // The high 17 digits of the significand
  1941. significandHigh = long_1.fromNumber(0); // The low 17 digits of the significand
  1942. significandLow = long_1.fromNumber(0); // read a zero
  1943. if (significantDigits === 0) {
  1944. significandHigh = long_1.fromNumber(0);
  1945. significandLow = long_1.fromNumber(0);
  1946. } else if (lastDigit - firstDigit < 17) {
  1947. var _dIdx = firstDigit;
  1948. significandLow = long_1.fromNumber(digits[_dIdx++]);
  1949. significandHigh = new long_1(0, 0);
  1950. for (; _dIdx <= lastDigit; _dIdx++) {
  1951. significandLow = significandLow.multiply(long_1.fromNumber(10));
  1952. significandLow = significandLow.add(long_1.fromNumber(digits[_dIdx]));
  1953. }
  1954. } else {
  1955. var _dIdx2 = firstDigit;
  1956. significandHigh = long_1.fromNumber(digits[_dIdx2++]);
  1957. for (; _dIdx2 <= lastDigit - 17; _dIdx2++) {
  1958. significandHigh = significandHigh.multiply(long_1.fromNumber(10));
  1959. significandHigh = significandHigh.add(long_1.fromNumber(digits[_dIdx2]));
  1960. }
  1961. significandLow = long_1.fromNumber(digits[_dIdx2++]);
  1962. for (; _dIdx2 <= lastDigit; _dIdx2++) {
  1963. significandLow = significandLow.multiply(long_1.fromNumber(10));
  1964. significandLow = significandLow.add(long_1.fromNumber(digits[_dIdx2]));
  1965. }
  1966. }
  1967. var significand = multiply64x2(significandHigh, long_1.fromString('100000000000000000'));
  1968. significand.low = significand.low.add(significandLow);
  1969. if (lessThan(significand.low, significandLow)) {
  1970. significand.high = significand.high.add(long_1.fromNumber(1));
  1971. } // Biased exponent
  1972. biasedExponent = exponent + EXPONENT_BIAS;
  1973. var dec = {
  1974. low: long_1.fromNumber(0),
  1975. high: long_1.fromNumber(0)
  1976. }; // Encode combination, exponent, and significand.
  1977. if (significand.high.shiftRightUnsigned(49).and(long_1.fromNumber(1)).equals(long_1.fromNumber(1))) {
  1978. // Encode '11' into bits 1 to 3
  1979. dec.high = dec.high.or(long_1.fromNumber(0x3).shiftLeft(61));
  1980. dec.high = dec.high.or(long_1.fromNumber(biasedExponent).and(long_1.fromNumber(0x3fff).shiftLeft(47)));
  1981. dec.high = dec.high.or(significand.high.and(long_1.fromNumber(0x7fffffffffff)));
  1982. } else {
  1983. dec.high = dec.high.or(long_1.fromNumber(biasedExponent & 0x3fff).shiftLeft(49));
  1984. dec.high = dec.high.or(significand.high.and(long_1.fromNumber(0x1ffffffffffff)));
  1985. }
  1986. dec.low = significand.low; // Encode sign
  1987. if (isNegative) {
  1988. dec.high = dec.high.or(long_1.fromString('9223372036854775808'));
  1989. } // Encode into a buffer
  1990. var buffer$$1 = Buffer.alloc(16);
  1991. index = 0; // Encode the low 64 bits of the decimal
  1992. // Encode low bits
  1993. buffer$$1[index++] = dec.low.low & 0xff;
  1994. buffer$$1[index++] = dec.low.low >> 8 & 0xff;
  1995. buffer$$1[index++] = dec.low.low >> 16 & 0xff;
  1996. buffer$$1[index++] = dec.low.low >> 24 & 0xff; // Encode high bits
  1997. buffer$$1[index++] = dec.low.high & 0xff;
  1998. buffer$$1[index++] = dec.low.high >> 8 & 0xff;
  1999. buffer$$1[index++] = dec.low.high >> 16 & 0xff;
  2000. buffer$$1[index++] = dec.low.high >> 24 & 0xff; // Encode the high 64 bits of the decimal
  2001. // Encode low bits
  2002. buffer$$1[index++] = dec.high.low & 0xff;
  2003. buffer$$1[index++] = dec.high.low >> 8 & 0xff;
  2004. buffer$$1[index++] = dec.high.low >> 16 & 0xff;
  2005. buffer$$1[index++] = dec.high.low >> 24 & 0xff; // Encode high bits
  2006. buffer$$1[index++] = dec.high.high & 0xff;
  2007. buffer$$1[index++] = dec.high.high >> 8 & 0xff;
  2008. buffer$$1[index++] = dec.high.high >> 16 & 0xff;
  2009. buffer$$1[index++] = dec.high.high >> 24 & 0xff; // Return the new Decimal128
  2010. return new Decimal128(buffer$$1);
  2011. }; // Extract least significant 5 bits
  2012. var COMBINATION_MASK = 0x1f; // Extract least significant 14 bits
  2013. var EXPONENT_MASK = 0x3fff; // Value of combination field for Inf
  2014. var COMBINATION_INFINITY = 30; // Value of combination field for NaN
  2015. var COMBINATION_NAN = 31;
  2016. /**
  2017. * Create a string representation of the raw Decimal128 value
  2018. *
  2019. * @method
  2020. * @return {string} returns a Decimal128 string representation.
  2021. */
  2022. Decimal128.prototype.toString = function () {
  2023. // Note: bits in this routine are referred to starting at 0,
  2024. // from the sign bit, towards the coefficient.
  2025. // bits 0 - 31
  2026. var high; // bits 32 - 63
  2027. var midh; // bits 64 - 95
  2028. var midl; // bits 96 - 127
  2029. var low; // bits 1 - 5
  2030. var combination; // decoded biased exponent (14 bits)
  2031. var biased_exponent; // the number of significand digits
  2032. var significand_digits = 0; // the base-10 digits in the significand
  2033. var significand = new Array(36);
  2034. for (var i = 0; i < significand.length; i++) {
  2035. significand[i] = 0;
  2036. } // read pointer into significand
  2037. var index = 0; // unbiased exponent
  2038. var exponent; // the exponent if scientific notation is used
  2039. var scientific_exponent; // true if the number is zero
  2040. var is_zero = false; // the most signifcant significand bits (50-46)
  2041. var significand_msb; // temporary storage for significand decoding
  2042. var significand128 = {
  2043. parts: new Array(4)
  2044. }; // indexing variables
  2045. var j, k; // Output string
  2046. var string = []; // Unpack index
  2047. index = 0; // Buffer reference
  2048. var buffer$$1 = this.bytes; // Unpack the low 64bits into a long
  2049. low = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  2050. midl = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24; // Unpack the high 64bits into a long
  2051. midh = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  2052. high = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24; // Unpack index
  2053. index = 0; // Create the state of the decimal
  2054. var dec = {
  2055. low: new long_1(low, midl),
  2056. high: new long_1(midh, high)
  2057. };
  2058. if (dec.high.lessThan(long_1.ZERO)) {
  2059. string.push('-');
  2060. } // Decode combination field and exponent
  2061. combination = high >> 26 & COMBINATION_MASK;
  2062. if (combination >> 3 === 3) {
  2063. // Check for 'special' values
  2064. if (combination === COMBINATION_INFINITY) {
  2065. return string.join('') + 'Infinity';
  2066. } else if (combination === COMBINATION_NAN) {
  2067. return 'NaN';
  2068. } else {
  2069. biased_exponent = high >> 15 & EXPONENT_MASK;
  2070. significand_msb = 0x08 + (high >> 14 & 0x01);
  2071. }
  2072. } else {
  2073. significand_msb = high >> 14 & 0x07;
  2074. biased_exponent = high >> 17 & EXPONENT_MASK;
  2075. }
  2076. exponent = biased_exponent - EXPONENT_BIAS; // Create string of significand digits
  2077. // Convert the 114-bit binary number represented by
  2078. // (significand_high, significand_low) to at most 34 decimal
  2079. // digits through modulo and division.
  2080. significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14);
  2081. significand128.parts[1] = midh;
  2082. significand128.parts[2] = midl;
  2083. significand128.parts[3] = low;
  2084. if (significand128.parts[0] === 0 && significand128.parts[1] === 0 && significand128.parts[2] === 0 && significand128.parts[3] === 0) {
  2085. is_zero = true;
  2086. } else {
  2087. for (k = 3; k >= 0; k--) {
  2088. var least_digits = 0; // Peform the divide
  2089. var result = divideu128(significand128);
  2090. significand128 = result.quotient;
  2091. least_digits = result.rem.low; // We now have the 9 least significant digits (in base 2).
  2092. // Convert and output to string.
  2093. if (!least_digits) continue;
  2094. for (j = 8; j >= 0; j--) {
  2095. // significand[k * 9 + j] = Math.round(least_digits % 10);
  2096. significand[k * 9 + j] = least_digits % 10; // least_digits = Math.round(least_digits / 10);
  2097. least_digits = Math.floor(least_digits / 10);
  2098. }
  2099. }
  2100. } // Output format options:
  2101. // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd
  2102. // Regular - ddd.ddd
  2103. if (is_zero) {
  2104. significand_digits = 1;
  2105. significand[index] = 0;
  2106. } else {
  2107. significand_digits = 36;
  2108. while (!significand[index]) {
  2109. significand_digits = significand_digits - 1;
  2110. index = index + 1;
  2111. }
  2112. }
  2113. scientific_exponent = significand_digits - 1 + exponent; // The scientific exponent checks are dictated by the string conversion
  2114. // specification and are somewhat arbitrary cutoffs.
  2115. //
  2116. // We must check exponent > 0, because if this is the case, the number
  2117. // has trailing zeros. However, we *cannot* output these trailing zeros,
  2118. // because doing so would change the precision of the value, and would
  2119. // change stored data if the string converted number is round tripped.
  2120. if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
  2121. // Scientific format
  2122. // if there are too many significant digits, we should just be treating numbers
  2123. // as + or - 0 and using the non-scientific exponent (this is for the "invalid
  2124. // representation should be treated as 0/-0" spec cases in decimal128-1.json)
  2125. if (significand_digits > 34) {
  2126. string.push(0);
  2127. if (exponent > 0) string.push('E+' + exponent);else if (exponent < 0) string.push('E' + exponent);
  2128. return string.join('');
  2129. }
  2130. string.push(significand[index++]);
  2131. significand_digits = significand_digits - 1;
  2132. if (significand_digits) {
  2133. string.push('.');
  2134. }
  2135. for (var _i = 0; _i < significand_digits; _i++) {
  2136. string.push(significand[index++]);
  2137. } // Exponent
  2138. string.push('E');
  2139. if (scientific_exponent > 0) {
  2140. string.push('+' + scientific_exponent);
  2141. } else {
  2142. string.push(scientific_exponent);
  2143. }
  2144. } else {
  2145. // Regular format with no decimal place
  2146. if (exponent >= 0) {
  2147. for (var _i2 = 0; _i2 < significand_digits; _i2++) {
  2148. string.push(significand[index++]);
  2149. }
  2150. } else {
  2151. var radix_position = significand_digits + exponent; // non-zero digits before radix
  2152. if (radix_position > 0) {
  2153. for (var _i3 = 0; _i3 < radix_position; _i3++) {
  2154. string.push(significand[index++]);
  2155. }
  2156. } else {
  2157. string.push('0');
  2158. }
  2159. string.push('.'); // add leading zeros after radix
  2160. while (radix_position++ < 0) {
  2161. string.push('0');
  2162. }
  2163. for (var _i4 = 0; _i4 < significand_digits - Math.max(radix_position - 1, 0); _i4++) {
  2164. string.push(significand[index++]);
  2165. }
  2166. }
  2167. }
  2168. return string.join('');
  2169. };
  2170. Decimal128.prototype.toJSON = function () {
  2171. return {
  2172. $numberDecimal: this.toString()
  2173. };
  2174. };
  2175. /**
  2176. * @ignore
  2177. */
  2178. Decimal128.prototype.toExtendedJSON = function () {
  2179. return {
  2180. $numberDecimal: this.toString()
  2181. };
  2182. };
  2183. /**
  2184. * @ignore
  2185. */
  2186. Decimal128.fromExtendedJSON = function (doc) {
  2187. return Decimal128.fromString(doc.$numberDecimal);
  2188. };
  2189. Object.defineProperty(Decimal128.prototype, '_bsontype', {
  2190. value: 'Decimal128'
  2191. });
  2192. var decimal128 = Decimal128;
  2193. var MinKey =
  2194. /*#__PURE__*/
  2195. function () {
  2196. /**
  2197. * Create a MinKey type
  2198. *
  2199. * @return {MinKey} A MinKey instance
  2200. */
  2201. function MinKey() {
  2202. _classCallCheck(this, MinKey);
  2203. }
  2204. /**
  2205. * @ignore
  2206. */
  2207. _createClass(MinKey, [{
  2208. key: "toExtendedJSON",
  2209. value: function toExtendedJSON() {
  2210. return {
  2211. $minKey: 1
  2212. };
  2213. }
  2214. /**
  2215. * @ignore
  2216. */
  2217. }], [{
  2218. key: "fromExtendedJSON",
  2219. value: function fromExtendedJSON() {
  2220. return new MinKey();
  2221. }
  2222. }]);
  2223. return MinKey;
  2224. }();
  2225. Object.defineProperty(MinKey.prototype, '_bsontype', {
  2226. value: 'MinKey'
  2227. });
  2228. var min_key = MinKey;
  2229. var MaxKey =
  2230. /*#__PURE__*/
  2231. function () {
  2232. /**
  2233. * Create a MaxKey type
  2234. *
  2235. * @return {MaxKey} A MaxKey instance
  2236. */
  2237. function MaxKey() {
  2238. _classCallCheck(this, MaxKey);
  2239. }
  2240. /**
  2241. * @ignore
  2242. */
  2243. _createClass(MaxKey, [{
  2244. key: "toExtendedJSON",
  2245. value: function toExtendedJSON() {
  2246. return {
  2247. $maxKey: 1
  2248. };
  2249. }
  2250. /**
  2251. * @ignore
  2252. */
  2253. }], [{
  2254. key: "fromExtendedJSON",
  2255. value: function fromExtendedJSON() {
  2256. return new MaxKey();
  2257. }
  2258. }]);
  2259. return MaxKey;
  2260. }();
  2261. Object.defineProperty(MaxKey.prototype, '_bsontype', {
  2262. value: 'MaxKey'
  2263. });
  2264. var max_key = MaxKey;
  2265. var DBRef =
  2266. /*#__PURE__*/
  2267. function () {
  2268. /**
  2269. * Create a DBRef type
  2270. *
  2271. * @param {string} collection the collection name.
  2272. * @param {ObjectId} oid the reference ObjectId.
  2273. * @param {string} [db] optional db name, if omitted the reference is local to the current db.
  2274. * @return {DBRef}
  2275. */
  2276. function DBRef(collection, oid, db, fields) {
  2277. _classCallCheck(this, DBRef);
  2278. // check if namespace has been provided
  2279. var parts = collection.split('.');
  2280. if (parts.length === 2) {
  2281. db = parts.shift();
  2282. collection = parts.shift();
  2283. }
  2284. this.collection = collection;
  2285. this.oid = oid;
  2286. this.db = db;
  2287. this.fields = fields || {};
  2288. }
  2289. /**
  2290. * @ignore
  2291. * @api private
  2292. */
  2293. _createClass(DBRef, [{
  2294. key: "toJSON",
  2295. value: function toJSON() {
  2296. var o = Object.assign({
  2297. $ref: this.collection,
  2298. $id: this.oid
  2299. }, this.fields);
  2300. if (this.db != null) o.$db = this.db;
  2301. return o;
  2302. }
  2303. /**
  2304. * @ignore
  2305. */
  2306. }, {
  2307. key: "toExtendedJSON",
  2308. value: function toExtendedJSON() {
  2309. var o = {
  2310. $ref: this.collection,
  2311. $id: this.oid
  2312. };
  2313. if (this.db) o.$db = this.db;
  2314. o = Object.assign(o, this.fields);
  2315. return o;
  2316. }
  2317. /**
  2318. * @ignore
  2319. */
  2320. }], [{
  2321. key: "fromExtendedJSON",
  2322. value: function fromExtendedJSON(doc) {
  2323. var copy = Object.assign({}, doc);
  2324. ['$ref', '$id', '$db'].forEach(function (k) {
  2325. return delete copy[k];
  2326. });
  2327. return new DBRef(doc.$ref, doc.$id, doc.$db, copy);
  2328. }
  2329. }]);
  2330. return DBRef;
  2331. }();
  2332. Object.defineProperty(DBRef.prototype, '_bsontype', {
  2333. value: 'DBRef'
  2334. });
  2335. var db_ref = DBRef;
  2336. var Binary =
  2337. /*#__PURE__*/
  2338. function () {
  2339. /**
  2340. * Create a Binary type
  2341. *
  2342. * Sub types
  2343. * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type.
  2344. * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type.
  2345. * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type.
  2346. * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type.
  2347. * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type.
  2348. * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type.
  2349. *
  2350. * @param {Buffer} buffer a buffer object containing the binary data.
  2351. * @param {Number} [subType] the option binary type.
  2352. * @return {Binary}
  2353. */
  2354. function Binary(buffer$$1, subType) {
  2355. _classCallCheck(this, Binary);
  2356. if (buffer$$1 != null && !(typeof buffer$$1 === 'string') && !Buffer.isBuffer(buffer$$1) && !(buffer$$1 instanceof Uint8Array) && !Array.isArray(buffer$$1)) {
  2357. throw new TypeError('only String, Buffer, Uint8Array or Array accepted');
  2358. }
  2359. this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType;
  2360. this.position = 0;
  2361. if (buffer$$1 != null && !(buffer$$1 instanceof Number)) {
  2362. // Only accept Buffer, Uint8Array or Arrays
  2363. if (typeof buffer$$1 === 'string') {
  2364. // Different ways of writing the length of the string for the different types
  2365. if (typeof Buffer !== 'undefined') {
  2366. this.buffer = Buffer.from(buffer$$1);
  2367. } else if (typeof Uint8Array !== 'undefined' || Array.isArray(buffer$$1)) {
  2368. this.buffer = writeStringToArray(buffer$$1);
  2369. } else {
  2370. throw new TypeError('only String, Buffer, Uint8Array or Array accepted');
  2371. }
  2372. } else {
  2373. this.buffer = buffer$$1;
  2374. }
  2375. this.position = buffer$$1.length;
  2376. } else {
  2377. if (typeof Buffer !== 'undefined') {
  2378. this.buffer = Buffer.alloc(Binary.BUFFER_SIZE);
  2379. } else if (typeof Uint8Array !== 'undefined') {
  2380. this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE));
  2381. } else {
  2382. this.buffer = new Array(Binary.BUFFER_SIZE);
  2383. }
  2384. }
  2385. }
  2386. /**
  2387. * Updates this binary with byte_value.
  2388. *
  2389. * @method
  2390. * @param {string} byte_value a single byte we wish to write.
  2391. */
  2392. _createClass(Binary, [{
  2393. key: "put",
  2394. value: function put(byte_value) {
  2395. // If it's a string and a has more than one character throw an error
  2396. if (byte_value['length'] != null && typeof byte_value !== 'number' && byte_value.length !== 1) throw new TypeError('only accepts single character String, Uint8Array or Array');
  2397. if (typeof byte_value !== 'number' && byte_value < 0 || byte_value > 255) throw new TypeError('only accepts number in a valid unsigned byte range 0-255'); // Decode the byte value once
  2398. var decoded_byte = null;
  2399. if (typeof byte_value === 'string') {
  2400. decoded_byte = byte_value.charCodeAt(0);
  2401. } else if (byte_value['length'] != null) {
  2402. decoded_byte = byte_value[0];
  2403. } else {
  2404. decoded_byte = byte_value;
  2405. }
  2406. if (this.buffer.length > this.position) {
  2407. this.buffer[this.position++] = decoded_byte;
  2408. } else {
  2409. if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) {
  2410. // Create additional overflow buffer
  2411. var buffer$$1 = Buffer.alloc(Binary.BUFFER_SIZE + this.buffer.length); // Combine the two buffers together
  2412. this.buffer.copy(buffer$$1, 0, 0, this.buffer.length);
  2413. this.buffer = buffer$$1;
  2414. this.buffer[this.position++] = decoded_byte;
  2415. } else {
  2416. var _buffer = null; // Create a new buffer (typed or normal array)
  2417. if (isUint8Array(this.buffer)) {
  2418. _buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length));
  2419. } else {
  2420. _buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length);
  2421. } // We need to copy all the content to the new array
  2422. for (var i = 0; i < this.buffer.length; i++) {
  2423. _buffer[i] = this.buffer[i];
  2424. } // Reassign the buffer
  2425. this.buffer = _buffer; // Write the byte
  2426. this.buffer[this.position++] = decoded_byte;
  2427. }
  2428. }
  2429. }
  2430. /**
  2431. * Writes a buffer or string to the binary.
  2432. *
  2433. * @method
  2434. * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object.
  2435. * @param {number} offset specify the binary of where to write the content.
  2436. * @return {null}
  2437. */
  2438. }, {
  2439. key: "write",
  2440. value: function write(string, offset) {
  2441. offset = typeof offset === 'number' ? offset : this.position; // If the buffer is to small let's extend the buffer
  2442. if (this.buffer.length < offset + string.length) {
  2443. var buffer$$1 = null; // If we are in node.js
  2444. if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) {
  2445. buffer$$1 = Buffer.alloc(this.buffer.length + string.length);
  2446. this.buffer.copy(buffer$$1, 0, 0, this.buffer.length);
  2447. } else if (isUint8Array(this.buffer)) {
  2448. // Create a new buffer
  2449. buffer$$1 = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)); // Copy the content
  2450. for (var i = 0; i < this.position; i++) {
  2451. buffer$$1[i] = this.buffer[i];
  2452. }
  2453. } // Assign the new buffer
  2454. this.buffer = buffer$$1;
  2455. }
  2456. if (typeof Buffer !== 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) {
  2457. string.copy(this.buffer, offset, 0, string.length);
  2458. this.position = offset + string.length > this.position ? offset + string.length : this.position; // offset = string.length
  2459. } else if (typeof Buffer !== 'undefined' && typeof string === 'string' && Buffer.isBuffer(this.buffer)) {
  2460. this.buffer.write(string, offset, 'binary');
  2461. this.position = offset + string.length > this.position ? offset + string.length : this.position; // offset = string.length;
  2462. } else if (isUint8Array(string) || Array.isArray(string) && typeof string !== 'string') {
  2463. for (var _i = 0; _i < string.length; _i++) {
  2464. this.buffer[offset++] = string[_i];
  2465. }
  2466. this.position = offset > this.position ? offset : this.position;
  2467. } else if (typeof string === 'string') {
  2468. for (var _i2 = 0; _i2 < string.length; _i2++) {
  2469. this.buffer[offset++] = string.charCodeAt(_i2);
  2470. }
  2471. this.position = offset > this.position ? offset : this.position;
  2472. }
  2473. }
  2474. /**
  2475. * Reads **length** bytes starting at **position**.
  2476. *
  2477. * @method
  2478. * @param {number} position read from the given position in the Binary.
  2479. * @param {number} length the number of bytes to read.
  2480. * @return {Buffer}
  2481. */
  2482. }, {
  2483. key: "read",
  2484. value: function read(position, length) {
  2485. length = length && length > 0 ? length : this.position; // Let's return the data based on the type we have
  2486. if (this.buffer['slice']) {
  2487. return this.buffer.slice(position, position + length);
  2488. } // Create a buffer to keep the result
  2489. var buffer$$1 = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length);
  2490. for (var i = 0; i < length; i++) {
  2491. buffer$$1[i] = this.buffer[position++];
  2492. } // Return the buffer
  2493. return buffer$$1;
  2494. }
  2495. /**
  2496. * Returns the value of this binary as a string.
  2497. *
  2498. * @method
  2499. * @return {string}
  2500. */
  2501. }, {
  2502. key: "value",
  2503. value: function value(asRaw) {
  2504. asRaw = asRaw == null ? false : asRaw; // Optimize to serialize for the situation where the data == size of buffer
  2505. 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
  2506. if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) {
  2507. return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position);
  2508. } else {
  2509. if (asRaw) {
  2510. // we support the slice command use it
  2511. if (this.buffer['slice'] != null) {
  2512. return this.buffer.slice(0, this.position);
  2513. } else {
  2514. // Create a new buffer to copy content to
  2515. var newBuffer = isUint8Array(this.buffer) ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); // Copy content
  2516. for (var i = 0; i < this.position; i++) {
  2517. newBuffer[i] = this.buffer[i];
  2518. } // Return the buffer
  2519. return newBuffer;
  2520. }
  2521. } else {
  2522. return convertArraytoUtf8BinaryString(this.buffer, 0, this.position);
  2523. }
  2524. }
  2525. }
  2526. /**
  2527. * Length.
  2528. *
  2529. * @method
  2530. * @return {number} the length of the binary.
  2531. */
  2532. }, {
  2533. key: "length",
  2534. value: function length() {
  2535. return this.position;
  2536. }
  2537. /**
  2538. * @ignore
  2539. */
  2540. }, {
  2541. key: "toJSON",
  2542. value: function toJSON() {
  2543. return this.buffer != null ? this.buffer.toString('base64') : '';
  2544. }
  2545. /**
  2546. * @ignore
  2547. */
  2548. }, {
  2549. key: "toString",
  2550. value: function toString(format) {
  2551. return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : '';
  2552. }
  2553. /**
  2554. * @ignore
  2555. */
  2556. }, {
  2557. key: "toExtendedJSON",
  2558. value: function toExtendedJSON() {
  2559. var base64String = Buffer.isBuffer(this.buffer) ? this.buffer.toString('base64') : Buffer.from(this.buffer).toString('base64');
  2560. var subType = Number(this.sub_type).toString(16);
  2561. return {
  2562. $binary: {
  2563. base64: base64String,
  2564. subType: subType.length === 1 ? '0' + subType : subType
  2565. }
  2566. };
  2567. }
  2568. /**
  2569. * @ignore
  2570. */
  2571. }], [{
  2572. key: "fromExtendedJSON",
  2573. value: function fromExtendedJSON(doc) {
  2574. var type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
  2575. var data = new Buffer(doc.$binary.base64, 'base64');
  2576. return new Binary(data, type);
  2577. }
  2578. }]);
  2579. return Binary;
  2580. }();
  2581. /**
  2582. * Binary default subtype
  2583. * @ignore
  2584. */
  2585. var BSON_BINARY_SUBTYPE_DEFAULT = 0;
  2586. function isUint8Array(obj) {
  2587. return Object.prototype.toString.call(obj) === '[object Uint8Array]';
  2588. }
  2589. /**
  2590. * @ignore
  2591. */
  2592. function writeStringToArray(data) {
  2593. // Create a buffer
  2594. var buffer$$1 = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); // Write the content to the buffer
  2595. for (var i = 0; i < data.length; i++) {
  2596. buffer$$1[i] = data.charCodeAt(i);
  2597. } // Write the string to the buffer
  2598. return buffer$$1;
  2599. }
  2600. /**
  2601. * Convert Array ot Uint8Array to Binary String
  2602. *
  2603. * @ignore
  2604. */
  2605. function convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex) {
  2606. var result = '';
  2607. for (var i = startIndex; i < endIndex; i++) {
  2608. result = result + String.fromCharCode(byteArray[i]);
  2609. }
  2610. return result;
  2611. }
  2612. Binary.BUFFER_SIZE = 256;
  2613. /**
  2614. * Default BSON type
  2615. *
  2616. * @classconstant SUBTYPE_DEFAULT
  2617. **/
  2618. Binary.SUBTYPE_DEFAULT = 0;
  2619. /**
  2620. * Function BSON type
  2621. *
  2622. * @classconstant SUBTYPE_DEFAULT
  2623. **/
  2624. Binary.SUBTYPE_FUNCTION = 1;
  2625. /**
  2626. * Byte Array BSON type
  2627. *
  2628. * @classconstant SUBTYPE_DEFAULT
  2629. **/
  2630. Binary.SUBTYPE_BYTE_ARRAY = 2;
  2631. /**
  2632. * OLD UUID BSON type
  2633. *
  2634. * @classconstant SUBTYPE_DEFAULT
  2635. **/
  2636. Binary.SUBTYPE_UUID_OLD = 3;
  2637. /**
  2638. * UUID BSON type
  2639. *
  2640. * @classconstant SUBTYPE_DEFAULT
  2641. **/
  2642. Binary.SUBTYPE_UUID = 4;
  2643. /**
  2644. * MD5 BSON type
  2645. *
  2646. * @classconstant SUBTYPE_DEFAULT
  2647. **/
  2648. Binary.SUBTYPE_MD5 = 5;
  2649. /**
  2650. * User BSON type
  2651. *
  2652. * @classconstant SUBTYPE_DEFAULT
  2653. **/
  2654. Binary.SUBTYPE_USER_DEFINED = 128;
  2655. Object.defineProperty(Binary.prototype, '_bsontype', {
  2656. value: 'Binary'
  2657. });
  2658. var binary = Binary;
  2659. var constants = {
  2660. // BSON MAX VALUES
  2661. BSON_INT32_MAX: 0x7fffffff,
  2662. BSON_INT32_MIN: -0x80000000,
  2663. BSON_INT64_MAX: Math.pow(2, 63) - 1,
  2664. BSON_INT64_MIN: -Math.pow(2, 63),
  2665. // JS MAX PRECISE VALUES
  2666. JS_INT_MAX: 0x20000000000000,
  2667. // Any integer up to 2^53 can be precisely represented by a double.
  2668. JS_INT_MIN: -0x20000000000000,
  2669. // Any integer down to -2^53 can be precisely represented by a double.
  2670. /**
  2671. * Number BSON Type
  2672. *
  2673. * @classconstant BSON_DATA_NUMBER
  2674. **/
  2675. BSON_DATA_NUMBER: 1,
  2676. /**
  2677. * String BSON Type
  2678. *
  2679. * @classconstant BSON_DATA_STRING
  2680. **/
  2681. BSON_DATA_STRING: 2,
  2682. /**
  2683. * Object BSON Type
  2684. *
  2685. * @classconstant BSON_DATA_OBJECT
  2686. **/
  2687. BSON_DATA_OBJECT: 3,
  2688. /**
  2689. * Array BSON Type
  2690. *
  2691. * @classconstant BSON_DATA_ARRAY
  2692. **/
  2693. BSON_DATA_ARRAY: 4,
  2694. /**
  2695. * Binary BSON Type
  2696. *
  2697. * @classconstant BSON_DATA_BINARY
  2698. **/
  2699. BSON_DATA_BINARY: 5,
  2700. /**
  2701. * Binary BSON Type
  2702. *
  2703. * @classconstant BSON_DATA_UNDEFINED
  2704. **/
  2705. BSON_DATA_UNDEFINED: 6,
  2706. /**
  2707. * ObjectId BSON Type
  2708. *
  2709. * @classconstant BSON_DATA_OID
  2710. **/
  2711. BSON_DATA_OID: 7,
  2712. /**
  2713. * Boolean BSON Type
  2714. *
  2715. * @classconstant BSON_DATA_BOOLEAN
  2716. **/
  2717. BSON_DATA_BOOLEAN: 8,
  2718. /**
  2719. * Date BSON Type
  2720. *
  2721. * @classconstant BSON_DATA_DATE
  2722. **/
  2723. BSON_DATA_DATE: 9,
  2724. /**
  2725. * null BSON Type
  2726. *
  2727. * @classconstant BSON_DATA_NULL
  2728. **/
  2729. BSON_DATA_NULL: 10,
  2730. /**
  2731. * RegExp BSON Type
  2732. *
  2733. * @classconstant BSON_DATA_REGEXP
  2734. **/
  2735. BSON_DATA_REGEXP: 11,
  2736. /**
  2737. * Code BSON Type
  2738. *
  2739. * @classconstant BSON_DATA_DBPOINTER
  2740. **/
  2741. BSON_DATA_DBPOINTER: 12,
  2742. /**
  2743. * Code BSON Type
  2744. *
  2745. * @classconstant BSON_DATA_CODE
  2746. **/
  2747. BSON_DATA_CODE: 13,
  2748. /**
  2749. * Symbol BSON Type
  2750. *
  2751. * @classconstant BSON_DATA_SYMBOL
  2752. **/
  2753. BSON_DATA_SYMBOL: 14,
  2754. /**
  2755. * Code with Scope BSON Type
  2756. *
  2757. * @classconstant BSON_DATA_CODE_W_SCOPE
  2758. **/
  2759. BSON_DATA_CODE_W_SCOPE: 15,
  2760. /**
  2761. * 32 bit Integer BSON Type
  2762. *
  2763. * @classconstant BSON_DATA_INT
  2764. **/
  2765. BSON_DATA_INT: 16,
  2766. /**
  2767. * Timestamp BSON Type
  2768. *
  2769. * @classconstant BSON_DATA_TIMESTAMP
  2770. **/
  2771. BSON_DATA_TIMESTAMP: 17,
  2772. /**
  2773. * Long BSON Type
  2774. *
  2775. * @classconstant BSON_DATA_LONG
  2776. **/
  2777. BSON_DATA_LONG: 18,
  2778. /**
  2779. * Long BSON Type
  2780. *
  2781. * @classconstant BSON_DATA_DECIMAL128
  2782. **/
  2783. BSON_DATA_DECIMAL128: 19,
  2784. /**
  2785. * MinKey BSON Type
  2786. *
  2787. * @classconstant BSON_DATA_MIN_KEY
  2788. **/
  2789. BSON_DATA_MIN_KEY: 0xff,
  2790. /**
  2791. * MaxKey BSON Type
  2792. *
  2793. * @classconstant BSON_DATA_MAX_KEY
  2794. **/
  2795. BSON_DATA_MAX_KEY: 0x7f,
  2796. /**
  2797. * Binary Default Type
  2798. *
  2799. * @classconstant BSON_BINARY_SUBTYPE_DEFAULT
  2800. **/
  2801. BSON_BINARY_SUBTYPE_DEFAULT: 0,
  2802. /**
  2803. * Binary Function Type
  2804. *
  2805. * @classconstant BSON_BINARY_SUBTYPE_FUNCTION
  2806. **/
  2807. BSON_BINARY_SUBTYPE_FUNCTION: 1,
  2808. /**
  2809. * Binary Byte Array Type
  2810. *
  2811. * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY
  2812. **/
  2813. BSON_BINARY_SUBTYPE_BYTE_ARRAY: 2,
  2814. /**
  2815. * Binary UUID Type
  2816. *
  2817. * @classconstant BSON_BINARY_SUBTYPE_UUID
  2818. **/
  2819. BSON_BINARY_SUBTYPE_UUID: 3,
  2820. /**
  2821. * Binary MD5 Type
  2822. *
  2823. * @classconstant BSON_BINARY_SUBTYPE_MD5
  2824. **/
  2825. BSON_BINARY_SUBTYPE_MD5: 4,
  2826. /**
  2827. * Binary User Defined Type
  2828. *
  2829. * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED
  2830. **/
  2831. BSON_BINARY_SUBTYPE_USER_DEFINED: 128
  2832. };
  2833. // const Map = require('./map');
  2834. /**
  2835. * @namespace EJSON
  2836. */
  2837. // all the types where we don't need to do any special processing and can just pass the EJSON
  2838. //straight to type.fromExtendedJSON
  2839. var keysToCodecs = {
  2840. $oid: objectid,
  2841. $binary: binary,
  2842. $symbol: symbol,
  2843. $numberInt: int_32,
  2844. $numberDecimal: decimal128,
  2845. $numberDouble: double_1,
  2846. $numberLong: long_1,
  2847. $minKey: min_key,
  2848. $maxKey: max_key,
  2849. $regularExpression: regexp,
  2850. $timestamp: timestamp
  2851. };
  2852. function deserializeValue(self, key, value, options) {
  2853. if (typeof value === 'number') {
  2854. if (options.relaxed) {
  2855. return value;
  2856. } // if it's an integer, should interpret as smallest BSON integer
  2857. // that can represent it exactly. (if out of range, interpret as double.)
  2858. if (Math.floor(value) === value) {
  2859. if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) return new int_32(value);
  2860. if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) return new long_1.fromNumber(value);
  2861. } // If the number is a non-integer or out of integer range, should interpret as BSON Double.
  2862. return new double_1(value);
  2863. } // from here on out we're looking for bson types, so bail if its not an object
  2864. if (value == null || _typeof(value) !== 'object') return value; // upgrade deprecated undefined to null
  2865. if (value.$undefined) return null;
  2866. var keys = Object.keys(value).filter(function (k) {
  2867. return k.startsWith('$') && value[k] != null;
  2868. });
  2869. for (var i = 0; i < keys.length; i++) {
  2870. var c = keysToCodecs[keys[i]];
  2871. if (c) return c.fromExtendedJSON(value, options);
  2872. }
  2873. if (value.$date != null) {
  2874. var d = value.$date;
  2875. var date = new Date();
  2876. if (typeof d === 'string') date.setTime(Date.parse(d));else if (d instanceof long_1) date.setTime(d.toNumber());else if (typeof d === 'number' && options.relaxed) date.setTime(d);
  2877. return date;
  2878. }
  2879. if (value.$code != null) {
  2880. var copy = Object.assign({}, value);
  2881. if (value.$scope) {
  2882. copy.$scope = deserializeValue(self, null, value.$scope);
  2883. }
  2884. return code.fromExtendedJSON(value);
  2885. }
  2886. if (value.$ref != null || value.$dbPointer != null) {
  2887. var v = value.$ref ? value : value.$dbPointer; // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped)
  2888. // because of the order JSON.parse goes through the document
  2889. if (v instanceof db_ref) return v;
  2890. var dollarKeys = Object.keys(v).filter(function (k) {
  2891. return k.startsWith('$');
  2892. });
  2893. var valid = true;
  2894. dollarKeys.forEach(function (k) {
  2895. if (['$ref', '$id', '$db'].indexOf(k) === -1) valid = false;
  2896. }); // only make DBRef if $ keys are all valid
  2897. if (valid) return db_ref.fromExtendedJSON(v);
  2898. }
  2899. return value;
  2900. }
  2901. /**
  2902. * Parse an Extended JSON string, constructing the JavaScript value or object described by that
  2903. * string.
  2904. *
  2905. * @memberof EJSON
  2906. * @param {string} text
  2907. * @param {object} [options] Optional settings
  2908. * @param {boolean} [options.relaxed=true] Attempt to return native JS types where possible, rather than BSON types (if true)
  2909. * @return {object}
  2910. *
  2911. * @example
  2912. * const { EJSON } = require('bson');
  2913. * const text = '{ "int32": { "$numberInt": "10" } }';
  2914. *
  2915. * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }
  2916. * console.log(EJSON.parse(text, { relaxed: false }));
  2917. *
  2918. * // prints { int32: 10 }
  2919. * console.log(EJSON.parse(text));
  2920. */
  2921. function parse(text, options) {
  2922. var _this = this;
  2923. options = Object.assign({}, {
  2924. relaxed: true
  2925. }, options); // relaxed implies not strict
  2926. if (typeof options.relaxed === 'boolean') options.strict = !options.relaxed;
  2927. if (typeof options.strict === 'boolean') options.relaxed = !options.strict;
  2928. return JSON.parse(text, function (key, value) {
  2929. return deserializeValue(_this, key, value, options);
  2930. });
  2931. } //
  2932. // Serializer
  2933. //
  2934. // MAX INT32 boundaries
  2935. var BSON_INT32_MAX = 0x7fffffff,
  2936. BSON_INT32_MIN = -0x80000000,
  2937. BSON_INT64_MAX = 0x7fffffffffffffff,
  2938. BSON_INT64_MIN = -0x8000000000000000;
  2939. /**
  2940. * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer
  2941. * function is specified or optionally including only the specified properties if a replacer array
  2942. * is specified.
  2943. *
  2944. * @memberof EJSON
  2945. * @param {object} value The value to convert to extended JSON
  2946. * @param {function|array} [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
  2947. * @param {string|number} [space] A String or Number object that's used to insert white space into the output JSON string for readability purposes.
  2948. * @param {object} [options] Optional settings
  2949. * @param {boolean} [options.relaxed=true] Enabled Extended JSON's `relaxed` mode
  2950. * @returns {string}
  2951. *
  2952. * @example
  2953. * const { EJSON } = require('bson');
  2954. * const Int32 = require('mongodb').Int32;
  2955. * const doc = { int32: new Int32(10) };
  2956. *
  2957. * // prints '{"int32":{"$numberInt":"10"}}'
  2958. * console.log(EJSON.stringify(doc, { relaxed: false }));
  2959. *
  2960. * // prints '{"int32":10}'
  2961. * console.log(EJSON.stringify(doc));
  2962. */
  2963. function stringify(value, replacer, space, options) {
  2964. if (space != null && _typeof(space) === 'object') options = space, space = 0;
  2965. if (replacer != null && _typeof(replacer) === 'object') options = replacer, replacer = null, space = 0;
  2966. options = Object.assign({}, {
  2967. relaxed: true
  2968. }, options);
  2969. var doc = Array.isArray(value) ? serializeArray(value, options) : serializeDocument(value, options);
  2970. return JSON.stringify(doc, replacer, space);
  2971. }
  2972. /**
  2973. * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.
  2974. *
  2975. * @memberof EJSON
  2976. * @param {object} bson The object to serialize
  2977. * @param {object} [options] Optional settings passed to the `stringify` function
  2978. * @return {object}
  2979. */
  2980. function serialize(bson, options) {
  2981. options = options || {};
  2982. return JSON.parse(stringify(bson, options));
  2983. }
  2984. /**
  2985. * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types
  2986. *
  2987. * @memberof EJSON
  2988. * @param {object} ejson The Extended JSON object to deserialize
  2989. * @param {object} [options] Optional settings passed to the parse method
  2990. * @return {object}
  2991. */
  2992. function deserialize(ejson, options) {
  2993. options = options || {};
  2994. return parse(JSON.stringify(ejson), options);
  2995. }
  2996. function serializeArray(array, options) {
  2997. return array.map(function (v) {
  2998. return serializeValue(v, options);
  2999. });
  3000. }
  3001. function getISOString(date) {
  3002. var isoStr = date.toISOString(); // we should only show milliseconds in timestamp if they're non-zero
  3003. return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z';
  3004. }
  3005. function serializeValue(value, options) {
  3006. if (Array.isArray(value)) return serializeArray(value, options);
  3007. if (value === undefined) return null;
  3008. if (value instanceof Date) {
  3009. var dateNum = value.getTime(),
  3010. // is it in year range 1970-9999?
  3011. inRange = dateNum > -1 && dateNum < 253402318800000;
  3012. return options.relaxed && inRange ? {
  3013. $date: getISOString(value)
  3014. } : {
  3015. $date: {
  3016. $numberLong: value.getTime().toString()
  3017. }
  3018. };
  3019. }
  3020. if (typeof value === 'number' && !options.relaxed) {
  3021. // it's an integer
  3022. if (Math.floor(value) === value) {
  3023. var int32Range = value >= BSON_INT32_MIN && value <= BSON_INT32_MAX,
  3024. int64Range = value >= BSON_INT64_MIN && value <= BSON_INT64_MAX; // interpret as being of the smallest BSON integer type that can represent the number exactly
  3025. if (int32Range) return {
  3026. $numberInt: value.toString()
  3027. };
  3028. if (int64Range) return {
  3029. $numberLong: value.toString()
  3030. };
  3031. }
  3032. return {
  3033. $numberDouble: value.toString()
  3034. };
  3035. }
  3036. if (value != null && _typeof(value) === 'object') return serializeDocument(value, options);
  3037. return value;
  3038. }
  3039. function serializeDocument(doc, options) {
  3040. if (doc == null || _typeof(doc) !== 'object') throw new Error('not an object instance'); // the document itself is a BSON type
  3041. if (doc._bsontype && typeof doc.toExtendedJSON === 'function') {
  3042. if (doc._bsontype === 'Code' && doc.scope) {
  3043. doc.scope = serializeDocument(doc.scope, options);
  3044. } else if (doc._bsontype === 'DBRef' && doc.oid) {
  3045. doc.oid = serializeDocument(doc.oid, options);
  3046. }
  3047. return doc.toExtendedJSON(options);
  3048. } // the document is an object with nested BSON types
  3049. var _doc = {};
  3050. for (var name in doc) {
  3051. var val = doc[name];
  3052. if (Array.isArray(val)) {
  3053. _doc[name] = serializeArray(val, options);
  3054. } else if (val != null && typeof val.toExtendedJSON === 'function') {
  3055. if (val._bsontype === 'Code' && val.scope) {
  3056. val.scope = serializeDocument(val.scope, options);
  3057. } else if (val._bsontype === 'DBRef' && val.oid) {
  3058. val.oid = serializeDocument(val.oid, options);
  3059. }
  3060. _doc[name] = val.toExtendedJSON(options);
  3061. } else if (val instanceof Date) {
  3062. _doc[name] = serializeValue(val, options);
  3063. } else if (val != null && _typeof(val) === 'object') {
  3064. _doc[name] = serializeDocument(val, options);
  3065. }
  3066. _doc[name] = serializeValue(val, options);
  3067. if (val instanceof RegExp) {
  3068. var flags = val.flags;
  3069. if (flags === undefined) {
  3070. flags = val.toString().match(/[gimuy]*$/)[0];
  3071. }
  3072. var rx = new regexp(val.source, flags);
  3073. _doc[name] = rx.toExtendedJSON();
  3074. }
  3075. }
  3076. return _doc;
  3077. }
  3078. var extended_json = {
  3079. parse: parse,
  3080. deserialize: deserialize,
  3081. serialize: serialize,
  3082. stringify: stringify
  3083. };
  3084. var FIRST_BIT = 0x80;
  3085. var FIRST_TWO_BITS = 0xc0;
  3086. var FIRST_THREE_BITS = 0xe0;
  3087. var FIRST_FOUR_BITS = 0xf0;
  3088. var FIRST_FIVE_BITS = 0xf8;
  3089. var TWO_BIT_CHAR = 0xc0;
  3090. var THREE_BIT_CHAR = 0xe0;
  3091. var FOUR_BIT_CHAR = 0xf0;
  3092. var CONTINUING_CHAR = 0x80;
  3093. /**
  3094. * Determines if the passed in bytes are valid utf8
  3095. * @param {Buffer|Uint8Array} bytes An array of 8-bit bytes. Must be indexable and have length property
  3096. * @param {Number} start The index to start validating
  3097. * @param {Number} end The index to end validating
  3098. * @returns {boolean} True if valid utf8
  3099. */
  3100. function validateUtf8(bytes, start, end) {
  3101. var continuation = 0;
  3102. for (var i = start; i < end; i += 1) {
  3103. var byte = bytes[i];
  3104. if (continuation) {
  3105. if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) {
  3106. return false;
  3107. }
  3108. continuation -= 1;
  3109. } else if (byte & FIRST_BIT) {
  3110. if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) {
  3111. continuation = 1;
  3112. } else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) {
  3113. continuation = 2;
  3114. } else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) {
  3115. continuation = 3;
  3116. } else {
  3117. return false;
  3118. }
  3119. }
  3120. }
  3121. return !continuation;
  3122. }
  3123. var validateUtf8_1 = validateUtf8;
  3124. var validate_utf8 = {
  3125. validateUtf8: validateUtf8_1
  3126. };
  3127. var Buffer$2 = buffer.Buffer;
  3128. var validateUtf8$1 = validate_utf8.validateUtf8; // Internal long versions
  3129. var JS_INT_MAX_LONG = long_1.fromNumber(constants.JS_INT_MAX);
  3130. var JS_INT_MIN_LONG = long_1.fromNumber(constants.JS_INT_MIN);
  3131. var functionCache = {};
  3132. function deserialize$1(buffer$$1, options, isArray) {
  3133. options = options == null ? {} : options;
  3134. var index = options && options.index ? options.index : 0; // Read the document size
  3135. var size = buffer$$1[index] | buffer$$1[index + 1] << 8 | buffer$$1[index + 2] << 16 | buffer$$1[index + 3] << 24;
  3136. if (size < 5) {
  3137. throw new Error("bson size must be >= 5, is ".concat(size));
  3138. }
  3139. if (options.allowObjectSmallerThanBufferSize && buffer$$1.length < size) {
  3140. throw new Error("buffer length ".concat(buffer$$1.length, " must be >= bson size ").concat(size));
  3141. }
  3142. if (!options.allowObjectSmallerThanBufferSize && buffer$$1.length !== size) {
  3143. throw new Error("buffer length ".concat(buffer$$1.length, " must === bson size ").concat(size));
  3144. }
  3145. if (size + index > buffer$$1.length) {
  3146. throw new Error("(bson size ".concat(size, " + options.index ").concat(index, " must be <= buffer length ").concat(Buffer$2.byteLength(buffer$$1), ")"));
  3147. } // Illegal end value
  3148. if (buffer$$1[index + size - 1] !== 0) {
  3149. throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
  3150. } // Start deserializtion
  3151. return deserializeObject(buffer$$1, index, options, isArray);
  3152. }
  3153. function deserializeObject(buffer$$1, index, options, isArray) {
  3154. var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions'];
  3155. var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions'];
  3156. var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32'];
  3157. if (!cacheFunctionsCrc32) var crc32 = null;
  3158. var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; // Return raw bson buffer instead of parsing it
  3159. var raw = options['raw'] == null ? false : options['raw']; // Return BSONRegExp objects instead of native regular expressions
  3160. var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; // Controls the promotion of values vs wrapper classes
  3161. var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers'];
  3162. var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs'];
  3163. var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; // Set the start index
  3164. var startIndex = index; // Validate that we have at least 4 bytes of buffer
  3165. if (buffer$$1.length < 5) throw new Error('corrupt bson message < 5 bytes long'); // Read the document size
  3166. var size = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24; // Ensure buffer is valid size
  3167. if (size < 5 || size > buffer$$1.length) throw new Error('corrupt bson message'); // Create holding object
  3168. var object = isArray ? [] : {}; // Used for arrays to skip having to perform utf8 decoding
  3169. var arrayIndex = 0;
  3170. var done = false; // While we have more left data left keep parsing
  3171. while (!done) {
  3172. // Read the type
  3173. var elementType = buffer$$1[index++]; // If we get a zero it's the last byte, exit
  3174. if (elementType === 0) break; // Get the start search index
  3175. var i = index; // Locate the end of the c string
  3176. while (buffer$$1[i] !== 0x00 && i < buffer$$1.length) {
  3177. i++;
  3178. } // If are at the end of the buffer there is a problem with the document
  3179. if (i >= Buffer$2.byteLength(buffer$$1)) throw new Error('Bad BSON Document: illegal CString');
  3180. var name = isArray ? arrayIndex++ : buffer$$1.toString('utf8', index, i);
  3181. index = i + 1;
  3182. if (elementType === constants.BSON_DATA_STRING) {
  3183. var stringSize = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3184. if (stringSize <= 0 || stringSize > buffer$$1.length - index || buffer$$1[index + stringSize - 1] !== 0) throw new Error('bad string length in bson');
  3185. if (!validateUtf8$1(buffer$$1, index, index + stringSize - 1)) {
  3186. throw new Error('Invalid UTF-8 string in BSON document');
  3187. }
  3188. var s = buffer$$1.toString('utf8', index, index + stringSize - 1);
  3189. object[name] = s;
  3190. index = index + stringSize;
  3191. } else if (elementType === constants.BSON_DATA_OID) {
  3192. var oid = Buffer$2.alloc(12);
  3193. buffer$$1.copy(oid, 0, index, index + 12);
  3194. object[name] = new objectid(oid);
  3195. index = index + 12;
  3196. } else if (elementType === constants.BSON_DATA_INT && promoteValues === false) {
  3197. object[name] = new int_32(buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24);
  3198. } else if (elementType === constants.BSON_DATA_INT) {
  3199. object[name] = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3200. } else if (elementType === constants.BSON_DATA_NUMBER && promoteValues === false) {
  3201. object[name] = new double_1(buffer$$1.readDoubleLE(index));
  3202. index = index + 8;
  3203. } else if (elementType === constants.BSON_DATA_NUMBER) {
  3204. object[name] = buffer$$1.readDoubleLE(index);
  3205. index = index + 8;
  3206. } else if (elementType === constants.BSON_DATA_DATE) {
  3207. var lowBits = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3208. var highBits = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3209. object[name] = new Date(new long_1(lowBits, highBits).toNumber());
  3210. } else if (elementType === constants.BSON_DATA_BOOLEAN) {
  3211. if (buffer$$1[index] !== 0 && buffer$$1[index] !== 1) throw new Error('illegal boolean type value');
  3212. object[name] = buffer$$1[index++] === 1;
  3213. } else if (elementType === constants.BSON_DATA_OBJECT) {
  3214. var _index = index;
  3215. var objectSize = buffer$$1[index] | buffer$$1[index + 1] << 8 | buffer$$1[index + 2] << 16 | buffer$$1[index + 3] << 24;
  3216. if (objectSize <= 0 || objectSize > buffer$$1.length - index) throw new Error('bad embedded document length in bson'); // We have a raw value
  3217. if (raw) {
  3218. object[name] = buffer$$1.slice(index, index + objectSize);
  3219. } else {
  3220. object[name] = deserializeObject(buffer$$1, _index, options, false);
  3221. }
  3222. index = index + objectSize;
  3223. } else if (elementType === constants.BSON_DATA_ARRAY) {
  3224. var _index2 = index;
  3225. var _objectSize = buffer$$1[index] | buffer$$1[index + 1] << 8 | buffer$$1[index + 2] << 16 | buffer$$1[index + 3] << 24;
  3226. var arrayOptions = options; // Stop index
  3227. var stopIndex = index + _objectSize; // All elements of array to be returned as raw bson
  3228. if (fieldsAsRaw && fieldsAsRaw[name]) {
  3229. arrayOptions = {};
  3230. for (var n in options) {
  3231. arrayOptions[n] = options[n];
  3232. }
  3233. arrayOptions['raw'] = true;
  3234. }
  3235. object[name] = deserializeObject(buffer$$1, _index2, arrayOptions, true);
  3236. index = index + _objectSize;
  3237. if (buffer$$1[index - 1] !== 0) throw new Error('invalid array terminator byte');
  3238. if (index !== stopIndex) throw new Error('corrupted array bson');
  3239. } else if (elementType === constants.BSON_DATA_UNDEFINED) {
  3240. object[name] = undefined;
  3241. } else if (elementType === constants.BSON_DATA_NULL) {
  3242. object[name] = null;
  3243. } else if (elementType === constants.BSON_DATA_LONG) {
  3244. // Unpack the low and high bits
  3245. var _lowBits = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3246. var _highBits = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3247. var long$$1 = new long_1(_lowBits, _highBits); // Promote the long if possible
  3248. if (promoteLongs && promoteValues === true) {
  3249. object[name] = long$$1.lessThanOrEqual(JS_INT_MAX_LONG) && long$$1.greaterThanOrEqual(JS_INT_MIN_LONG) ? long$$1.toNumber() : long$$1;
  3250. } else {
  3251. object[name] = long$$1;
  3252. }
  3253. } else if (elementType === constants.BSON_DATA_DECIMAL128) {
  3254. // Buffer to contain the decimal bytes
  3255. var bytes = Buffer$2.alloc(16); // Copy the next 16 bytes into the bytes buffer
  3256. buffer$$1.copy(bytes, 0, index, index + 16); // Update index
  3257. index = index + 16; // Assign the new Decimal128 value
  3258. var decimal128$$1 = new decimal128(bytes); // If we have an alternative mapper use that
  3259. object[name] = decimal128$$1.toObject ? decimal128$$1.toObject() : decimal128$$1;
  3260. } else if (elementType === constants.BSON_DATA_BINARY) {
  3261. var binarySize = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3262. var totalBinarySize = binarySize;
  3263. var subType = buffer$$1[index++]; // Did we have a negative binary size, throw
  3264. if (binarySize < 0) throw new Error('Negative binary type element size found'); // Is the length longer than the document
  3265. if (binarySize > Buffer$2.byteLength(buffer$$1)) throw new Error('Binary type size larger than document size'); // Decode as raw Buffer object if options specifies it
  3266. if (buffer$$1['slice'] != null) {
  3267. // If we have subtype 2 skip the 4 bytes for the size
  3268. if (subType === binary.SUBTYPE_BYTE_ARRAY) {
  3269. binarySize = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3270. if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02');
  3271. if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size');
  3272. if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size');
  3273. }
  3274. if (promoteBuffers && promoteValues) {
  3275. object[name] = buffer$$1.slice(index, index + binarySize);
  3276. } else {
  3277. object[name] = new binary(buffer$$1.slice(index, index + binarySize), subType);
  3278. }
  3279. } else {
  3280. 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
  3281. if (subType === binary.SUBTYPE_BYTE_ARRAY) {
  3282. binarySize = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3283. if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02');
  3284. if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size');
  3285. if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size');
  3286. } // Copy the data
  3287. for (i = 0; i < binarySize; i++) {
  3288. _buffer[i] = buffer$$1[index + i];
  3289. }
  3290. if (promoteBuffers && promoteValues) {
  3291. object[name] = _buffer;
  3292. } else {
  3293. object[name] = new binary(_buffer, subType);
  3294. }
  3295. } // Update the index
  3296. index = index + binarySize;
  3297. } else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === false) {
  3298. // Get the start search index
  3299. i = index; // Locate the end of the c string
  3300. while (buffer$$1[i] !== 0x00 && i < buffer$$1.length) {
  3301. i++;
  3302. } // If are at the end of the buffer there is a problem with the document
  3303. if (i >= buffer$$1.length) throw new Error('Bad BSON Document: illegal CString'); // Return the C string
  3304. var source = buffer$$1.toString('utf8', index, i); // Create the regexp
  3305. index = i + 1; // Get the start search index
  3306. i = index; // Locate the end of the c string
  3307. while (buffer$$1[i] !== 0x00 && i < buffer$$1.length) {
  3308. i++;
  3309. } // If are at the end of the buffer there is a problem with the document
  3310. if (i >= buffer$$1.length) throw new Error('Bad BSON Document: illegal CString'); // Return the C string
  3311. var regExpOptions = buffer$$1.toString('utf8', index, i);
  3312. index = i + 1; // For each option add the corresponding one for javascript
  3313. var optionsArray = new Array(regExpOptions.length); // Parse options
  3314. for (i = 0; i < regExpOptions.length; i++) {
  3315. switch (regExpOptions[i]) {
  3316. case 'm':
  3317. optionsArray[i] = 'm';
  3318. break;
  3319. case 's':
  3320. optionsArray[i] = 'g';
  3321. break;
  3322. case 'i':
  3323. optionsArray[i] = 'i';
  3324. break;
  3325. }
  3326. }
  3327. object[name] = new RegExp(source, optionsArray.join(''));
  3328. } else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === true) {
  3329. // Get the start search index
  3330. i = index; // Locate the end of the c string
  3331. while (buffer$$1[i] !== 0x00 && i < buffer$$1.length) {
  3332. i++;
  3333. } // If are at the end of the buffer there is a problem with the document
  3334. if (i >= buffer$$1.length) throw new Error('Bad BSON Document: illegal CString'); // Return the C string
  3335. var _source = buffer$$1.toString('utf8', index, i);
  3336. index = i + 1; // Get the start search index
  3337. i = index; // Locate the end of the c string
  3338. while (buffer$$1[i] !== 0x00 && i < buffer$$1.length) {
  3339. i++;
  3340. } // If are at the end of the buffer there is a problem with the document
  3341. if (i >= buffer$$1.length) throw new Error('Bad BSON Document: illegal CString'); // Return the C string
  3342. var _regExpOptions = buffer$$1.toString('utf8', index, i);
  3343. index = i + 1; // Set the object
  3344. object[name] = new regexp(_source, _regExpOptions);
  3345. } else if (elementType === constants.BSON_DATA_SYMBOL) {
  3346. var _stringSize = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3347. if (_stringSize <= 0 || _stringSize > buffer$$1.length - index || buffer$$1[index + _stringSize - 1] !== 0) throw new Error('bad string length in bson'); // symbol is deprecated - upgrade to string.
  3348. object[name] = buffer$$1.toString('utf8', index, index + _stringSize - 1);
  3349. index = index + _stringSize;
  3350. } else if (elementType === constants.BSON_DATA_TIMESTAMP) {
  3351. var _lowBits2 = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3352. var _highBits2 = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3353. object[name] = new timestamp(_lowBits2, _highBits2);
  3354. } else if (elementType === constants.BSON_DATA_MIN_KEY) {
  3355. object[name] = new min_key();
  3356. } else if (elementType === constants.BSON_DATA_MAX_KEY) {
  3357. object[name] = new max_key();
  3358. } else if (elementType === constants.BSON_DATA_CODE) {
  3359. var _stringSize2 = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3360. if (_stringSize2 <= 0 || _stringSize2 > buffer$$1.length - index || buffer$$1[index + _stringSize2 - 1] !== 0) throw new Error('bad string length in bson');
  3361. var functionString = buffer$$1.toString('utf8', index, index + _stringSize2 - 1); // If we are evaluating the functions
  3362. if (evalFunctions) {
  3363. // If we have cache enabled let's look for the md5 of the function in the cache
  3364. if (cacheFunctions) {
  3365. var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; // Got to do this to avoid V8 deoptimizing the call due to finding eval
  3366. object[name] = isolateEvalWithHash(functionCache, hash, functionString, object);
  3367. } else {
  3368. object[name] = isolateEval(functionString);
  3369. }
  3370. } else {
  3371. object[name] = new code(functionString);
  3372. } // Update parse index position
  3373. index = index + _stringSize2;
  3374. } else if (elementType === constants.BSON_DATA_CODE_W_SCOPE) {
  3375. var totalSize = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24; // Element cannot be shorter than totalSize + stringSize + documentSize + terminator
  3376. if (totalSize < 4 + 4 + 4 + 1) {
  3377. throw new Error('code_w_scope total size shorter minimum expected length');
  3378. } // Get the code string size
  3379. var _stringSize3 = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24; // Check if we have a valid string
  3380. if (_stringSize3 <= 0 || _stringSize3 > buffer$$1.length - index || buffer$$1[index + _stringSize3 - 1] !== 0) throw new Error('bad string length in bson'); // Javascript function
  3381. var _functionString = buffer$$1.toString('utf8', index, index + _stringSize3 - 1); // Update parse index position
  3382. index = index + _stringSize3; // Parse the element
  3383. var _index3 = index; // Decode the size of the object document
  3384. var _objectSize2 = buffer$$1[index] | buffer$$1[index + 1] << 8 | buffer$$1[index + 2] << 16 | buffer$$1[index + 3] << 24; // Decode the scope object
  3385. var scopeObject = deserializeObject(buffer$$1, _index3, options, false); // Adjust the index
  3386. index = index + _objectSize2; // Check if field length is to short
  3387. if (totalSize < 4 + 4 + _objectSize2 + _stringSize3) {
  3388. throw new Error('code_w_scope total size is to short, truncating scope');
  3389. } // Check if totalSize field is to long
  3390. if (totalSize > 4 + 4 + _objectSize2 + _stringSize3) {
  3391. throw new Error('code_w_scope total size is to long, clips outer document');
  3392. } // If we are evaluating the functions
  3393. if (evalFunctions) {
  3394. // If we have cache enabled let's look for the md5 of the function in the cache
  3395. if (cacheFunctions) {
  3396. var _hash = cacheFunctionsCrc32 ? crc32(_functionString) : _functionString; // Got to do this to avoid V8 deoptimizing the call due to finding eval
  3397. object[name] = isolateEvalWithHash(functionCache, _hash, _functionString, object);
  3398. } else {
  3399. object[name] = isolateEval(_functionString);
  3400. }
  3401. object[name].scope = scopeObject;
  3402. } else {
  3403. object[name] = new code(_functionString, scopeObject);
  3404. }
  3405. } else if (elementType === constants.BSON_DATA_DBPOINTER) {
  3406. // Get the code string size
  3407. var _stringSize4 = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24; // Check if we have a valid string
  3408. if (_stringSize4 <= 0 || _stringSize4 > buffer$$1.length - index || buffer$$1[index + _stringSize4 - 1] !== 0) throw new Error('bad string length in bson'); // Namespace
  3409. if (!validateUtf8$1(buffer$$1, index, index + _stringSize4 - 1)) {
  3410. throw new Error('Invalid UTF-8 string in BSON document');
  3411. }
  3412. var namespace = buffer$$1.toString('utf8', index, index + _stringSize4 - 1); // Update parse index position
  3413. index = index + _stringSize4; // Read the oid
  3414. var oidBuffer = Buffer$2.alloc(12);
  3415. buffer$$1.copy(oidBuffer, 0, index, index + 12);
  3416. var _oid = new objectid(oidBuffer); // Update the index
  3417. index = index + 12; // Upgrade to DBRef type
  3418. object[name] = new db_ref(namespace, _oid);
  3419. } else {
  3420. throw new Error('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '", are you using the latest BSON parser?');
  3421. }
  3422. } // Check if the deserialization was against a valid array/object
  3423. if (size !== index - startIndex) {
  3424. if (isArray) throw new Error('corrupt array bson');
  3425. throw new Error('corrupt object bson');
  3426. } // check if object's $ keys are those of a DBRef
  3427. var dollarKeys = Object.keys(object).filter(function (k) {
  3428. return k.startsWith('$');
  3429. });
  3430. var valid = true;
  3431. dollarKeys.forEach(function (k) {
  3432. if (['$ref', '$id', '$db'].indexOf(k) === -1) valid = false;
  3433. }); // if a $key not in "$ref", "$id", "$db", don't make a DBRef
  3434. if (!valid) return object;
  3435. if (object['$id'] != null && object['$ref'] != null) {
  3436. var copy = Object.assign({}, object);
  3437. delete copy.$ref;
  3438. delete copy.$id;
  3439. delete copy.$db;
  3440. return new db_ref(object.$ref, object.$id, object.$db || null, copy);
  3441. }
  3442. return object;
  3443. }
  3444. /**
  3445. * Ensure eval is isolated.
  3446. *
  3447. * @ignore
  3448. * @api private
  3449. */
  3450. function isolateEvalWithHash(functionCache, hash, functionString, object) {
  3451. // Contains the value we are going to set
  3452. var value = null; // Check for cache hit, eval if missing and return cached function
  3453. if (functionCache[hash] == null) {
  3454. eval('value = ' + functionString);
  3455. functionCache[hash] = value;
  3456. } // Set the object
  3457. return functionCache[hash].bind(object);
  3458. }
  3459. /**
  3460. * Ensure eval is isolated.
  3461. *
  3462. * @ignore
  3463. * @api private
  3464. */
  3465. function isolateEval(functionString) {
  3466. // Contains the value we are going to set
  3467. var value = null; // Eval the function
  3468. eval('value = ' + functionString);
  3469. return value;
  3470. }
  3471. var deserializer = deserialize$1;
  3472. // All rights reserved.
  3473. //
  3474. // Redistribution and use in source and binary forms, with or without
  3475. // modification, are permitted provided that the following conditions are met:
  3476. //
  3477. // * Redistributions of source code must retain the above copyright notice,
  3478. // this list of conditions and the following disclaimer.
  3479. //
  3480. // * Redistributions in binary form must reproduce the above copyright notice,
  3481. // this list of conditions and the following disclaimer in the documentation
  3482. // and/or other materials provided with the distribution.
  3483. //
  3484. // * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors
  3485. // may be used to endorse or promote products derived from this software
  3486. // without specific prior written permission.
  3487. //
  3488. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  3489. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  3490. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  3491. // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  3492. // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  3493. // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  3494. // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  3495. // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  3496. // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  3497. // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  3498. // POSSIBILITY OF SUCH DAMAGE.
  3499. //
  3500. //
  3501. // Modifications to writeIEEE754 to support negative zeroes made by Brian White
  3502. function readIEEE754(buffer$$1, offset, endian, mLen, nBytes) {
  3503. var e,
  3504. m,
  3505. bBE = endian === 'big',
  3506. eLen = nBytes * 8 - mLen - 1,
  3507. eMax = (1 << eLen) - 1,
  3508. eBias = eMax >> 1,
  3509. nBits = -7,
  3510. i = bBE ? 0 : nBytes - 1,
  3511. d = bBE ? 1 : -1,
  3512. s = buffer$$1[offset + i];
  3513. i += d;
  3514. e = s & (1 << -nBits) - 1;
  3515. s >>= -nBits;
  3516. nBits += eLen;
  3517. for (; nBits > 0; e = e * 256 + buffer$$1[offset + i], i += d, nBits -= 8) {
  3518. }
  3519. m = e & (1 << -nBits) - 1;
  3520. e >>= -nBits;
  3521. nBits += mLen;
  3522. for (; nBits > 0; m = m * 256 + buffer$$1[offset + i], i += d, nBits -= 8) {
  3523. }
  3524. if (e === 0) {
  3525. e = 1 - eBias;
  3526. } else if (e === eMax) {
  3527. return m ? NaN : (s ? -1 : 1) * Infinity;
  3528. } else {
  3529. m = m + Math.pow(2, mLen);
  3530. e = e - eBias;
  3531. }
  3532. return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
  3533. }
  3534. function writeIEEE754(buffer$$1, value, offset, endian, mLen, nBytes) {
  3535. var e,
  3536. m,
  3537. c,
  3538. bBE = endian === 'big',
  3539. eLen = nBytes * 8 - mLen - 1,
  3540. eMax = (1 << eLen) - 1,
  3541. eBias = eMax >> 1,
  3542. rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0,
  3543. i = bBE ? nBytes - 1 : 0,
  3544. d = bBE ? -1 : 1,
  3545. s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
  3546. value = Math.abs(value);
  3547. if (isNaN(value) || value === Infinity) {
  3548. m = isNaN(value) ? 1 : 0;
  3549. e = eMax;
  3550. } else {
  3551. e = Math.floor(Math.log(value) / Math.LN2);
  3552. if (value * (c = Math.pow(2, -e)) < 1) {
  3553. e--;
  3554. c *= 2;
  3555. }
  3556. if (e + eBias >= 1) {
  3557. value += rt / c;
  3558. } else {
  3559. value += rt * Math.pow(2, 1 - eBias);
  3560. }
  3561. if (value * c >= 2) {
  3562. e++;
  3563. c /= 2;
  3564. }
  3565. if (e + eBias >= eMax) {
  3566. m = 0;
  3567. e = eMax;
  3568. } else if (e + eBias >= 1) {
  3569. m = (value * c - 1) * Math.pow(2, mLen);
  3570. e = e + eBias;
  3571. } else {
  3572. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  3573. e = 0;
  3574. }
  3575. }
  3576. if (isNaN(value)) m = 0;
  3577. while (mLen >= 8) {
  3578. buffer$$1[offset + i] = m & 0xff;
  3579. i += d;
  3580. m /= 256;
  3581. mLen -= 8;
  3582. }
  3583. e = e << mLen | m;
  3584. if (isNaN(value)) e += 8;
  3585. eLen += mLen;
  3586. while (eLen > 0) {
  3587. buffer$$1[offset + i] = e & 0xff;
  3588. i += d;
  3589. e /= 256;
  3590. eLen -= 8;
  3591. }
  3592. buffer$$1[offset + i - d] |= s * 128;
  3593. }
  3594. var float_parser = {
  3595. readIEEE754: readIEEE754,
  3596. writeIEEE754: writeIEEE754
  3597. };
  3598. var Buffer$3 = buffer.Buffer;
  3599. var writeIEEE754$1 = float_parser.writeIEEE754;
  3600. var normalizedFunctionString$1 = utils.normalizedFunctionString;
  3601. var regexp$1 = /\x00/; // eslint-disable-line no-control-regex
  3602. var ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); // To ensure that 0.4 of node works correctly
  3603. var isDate$1 = function isDate(d) {
  3604. return _typeof(d) === 'object' && Object.prototype.toString.call(d) === '[object Date]';
  3605. };
  3606. var isRegExp$1 = function isRegExp(d) {
  3607. return Object.prototype.toString.call(d) === '[object RegExp]';
  3608. };
  3609. function serializeString(buffer$$1, key, value, index, isArray) {
  3610. // Encode String type
  3611. buffer$$1[index++] = constants.BSON_DATA_STRING; // Number of written bytes
  3612. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3613. index = index + numberOfWrittenBytes + 1;
  3614. buffer$$1[index - 1] = 0; // Write the string
  3615. var size = buffer$$1.write(value, index + 4, 'utf8'); // Write the size of the string to buffer
  3616. buffer$$1[index + 3] = size + 1 >> 24 & 0xff;
  3617. buffer$$1[index + 2] = size + 1 >> 16 & 0xff;
  3618. buffer$$1[index + 1] = size + 1 >> 8 & 0xff;
  3619. buffer$$1[index] = size + 1 & 0xff; // Update index
  3620. index = index + 4 + size; // Write zero
  3621. buffer$$1[index++] = 0;
  3622. return index;
  3623. }
  3624. function serializeNumber(buffer$$1, key, value, index, isArray) {
  3625. // We have an integer value
  3626. if (Math.floor(value) === value && value >= constants.JS_INT_MIN && value <= constants.JS_INT_MAX) {
  3627. // If the value fits in 32 bits encode as int, if it fits in a double
  3628. // encode it as a double, otherwise long
  3629. if (value >= constants.BSON_INT32_MIN && value <= constants.BSON_INT32_MAX) {
  3630. // Set int type 32 bits or less
  3631. buffer$$1[index++] = constants.BSON_DATA_INT; // Number of written bytes
  3632. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3633. index = index + numberOfWrittenBytes;
  3634. buffer$$1[index++] = 0; // Write the int value
  3635. buffer$$1[index++] = value & 0xff;
  3636. buffer$$1[index++] = value >> 8 & 0xff;
  3637. buffer$$1[index++] = value >> 16 & 0xff;
  3638. buffer$$1[index++] = value >> 24 & 0xff;
  3639. } else if (value >= constants.JS_INT_MIN && value <= constants.JS_INT_MAX) {
  3640. // Encode as double
  3641. buffer$$1[index++] = constants.BSON_DATA_NUMBER; // Number of written bytes
  3642. var _numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3643. index = index + _numberOfWrittenBytes;
  3644. buffer$$1[index++] = 0; // Write float
  3645. writeIEEE754$1(buffer$$1, value, index, 'little', 52, 8); // Ajust index
  3646. index = index + 8;
  3647. } else {
  3648. // Set long type
  3649. buffer$$1[index++] = constants.BSON_DATA_LONG; // Number of written bytes
  3650. var _numberOfWrittenBytes2 = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3651. index = index + _numberOfWrittenBytes2;
  3652. buffer$$1[index++] = 0;
  3653. var longVal = long_1.fromNumber(value);
  3654. var lowBits = longVal.getLowBits();
  3655. var highBits = longVal.getHighBits(); // Encode low bits
  3656. buffer$$1[index++] = lowBits & 0xff;
  3657. buffer$$1[index++] = lowBits >> 8 & 0xff;
  3658. buffer$$1[index++] = lowBits >> 16 & 0xff;
  3659. buffer$$1[index++] = lowBits >> 24 & 0xff; // Encode high bits
  3660. buffer$$1[index++] = highBits & 0xff;
  3661. buffer$$1[index++] = highBits >> 8 & 0xff;
  3662. buffer$$1[index++] = highBits >> 16 & 0xff;
  3663. buffer$$1[index++] = highBits >> 24 & 0xff;
  3664. }
  3665. } else {
  3666. // Encode as double
  3667. buffer$$1[index++] = constants.BSON_DATA_NUMBER; // Number of written bytes
  3668. var _numberOfWrittenBytes3 = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3669. index = index + _numberOfWrittenBytes3;
  3670. buffer$$1[index++] = 0; // Write float
  3671. writeIEEE754$1(buffer$$1, value, index, 'little', 52, 8); // Ajust index
  3672. index = index + 8;
  3673. }
  3674. return index;
  3675. }
  3676. function serializeNull(buffer$$1, key, value, index, isArray) {
  3677. // Set long type
  3678. buffer$$1[index++] = constants.BSON_DATA_NULL; // Number of written bytes
  3679. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3680. index = index + numberOfWrittenBytes;
  3681. buffer$$1[index++] = 0;
  3682. return index;
  3683. }
  3684. function serializeBoolean(buffer$$1, key, value, index, isArray) {
  3685. // Write the type
  3686. buffer$$1[index++] = constants.BSON_DATA_BOOLEAN; // Number of written bytes
  3687. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3688. index = index + numberOfWrittenBytes;
  3689. buffer$$1[index++] = 0; // Encode the boolean value
  3690. buffer$$1[index++] = value ? 1 : 0;
  3691. return index;
  3692. }
  3693. function serializeDate(buffer$$1, key, value, index, isArray) {
  3694. // Write the type
  3695. buffer$$1[index++] = constants.BSON_DATA_DATE; // Number of written bytes
  3696. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3697. index = index + numberOfWrittenBytes;
  3698. buffer$$1[index++] = 0; // Write the date
  3699. var dateInMilis = long_1.fromNumber(value.getTime());
  3700. var lowBits = dateInMilis.getLowBits();
  3701. var highBits = dateInMilis.getHighBits(); // Encode low bits
  3702. buffer$$1[index++] = lowBits & 0xff;
  3703. buffer$$1[index++] = lowBits >> 8 & 0xff;
  3704. buffer$$1[index++] = lowBits >> 16 & 0xff;
  3705. buffer$$1[index++] = lowBits >> 24 & 0xff; // Encode high bits
  3706. buffer$$1[index++] = highBits & 0xff;
  3707. buffer$$1[index++] = highBits >> 8 & 0xff;
  3708. buffer$$1[index++] = highBits >> 16 & 0xff;
  3709. buffer$$1[index++] = highBits >> 24 & 0xff;
  3710. return index;
  3711. }
  3712. function serializeRegExp(buffer$$1, key, value, index, isArray) {
  3713. // Write the type
  3714. buffer$$1[index++] = constants.BSON_DATA_REGEXP; // Number of written bytes
  3715. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3716. index = index + numberOfWrittenBytes;
  3717. buffer$$1[index++] = 0;
  3718. if (value.source && value.source.match(regexp$1) != null) {
  3719. throw Error('value ' + value.source + ' must not contain null bytes');
  3720. } // Adjust the index
  3721. index = index + buffer$$1.write(value.source, index, 'utf8'); // Write zero
  3722. buffer$$1[index++] = 0x00; // Write the parameters
  3723. if (value.ignoreCase) buffer$$1[index++] = 0x69; // i
  3724. if (value.global) buffer$$1[index++] = 0x73; // s
  3725. if (value.multiline) buffer$$1[index++] = 0x6d; // m
  3726. // Add ending zero
  3727. buffer$$1[index++] = 0x00;
  3728. return index;
  3729. }
  3730. function serializeBSONRegExp(buffer$$1, key, value, index, isArray) {
  3731. // Write the type
  3732. buffer$$1[index++] = constants.BSON_DATA_REGEXP; // Number of written bytes
  3733. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3734. index = index + numberOfWrittenBytes;
  3735. buffer$$1[index++] = 0; // Check the pattern for 0 bytes
  3736. if (value.pattern.match(regexp$1) != null) {
  3737. // The BSON spec doesn't allow keys with null bytes because keys are
  3738. // null-terminated.
  3739. throw Error('pattern ' + value.pattern + ' must not contain null bytes');
  3740. } // Adjust the index
  3741. index = index + buffer$$1.write(value.pattern, index, 'utf8'); // Write zero
  3742. buffer$$1[index++] = 0x00; // Write the options
  3743. index = index + buffer$$1.write(value.options.split('').sort().join(''), index, 'utf8'); // Add ending zero
  3744. buffer$$1[index++] = 0x00;
  3745. return index;
  3746. }
  3747. function serializeMinMax(buffer$$1, key, value, index, isArray) {
  3748. // Write the type of either min or max key
  3749. if (value === null) {
  3750. buffer$$1[index++] = constants.BSON_DATA_NULL;
  3751. } else if (value instanceof min_key) {
  3752. buffer$$1[index++] = constants.BSON_DATA_MIN_KEY;
  3753. } else {
  3754. buffer$$1[index++] = constants.BSON_DATA_MAX_KEY;
  3755. } // Number of written bytes
  3756. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3757. index = index + numberOfWrittenBytes;
  3758. buffer$$1[index++] = 0;
  3759. return index;
  3760. }
  3761. function serializeObjectId(buffer$$1, key, value, index, isArray) {
  3762. // Write the type
  3763. buffer$$1[index++] = constants.BSON_DATA_OID; // Number of written bytes
  3764. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3765. index = index + numberOfWrittenBytes;
  3766. buffer$$1[index++] = 0; // Write the objectId into the shared buffer
  3767. if (typeof value.id === 'string') {
  3768. buffer$$1.write(value.id, index, 'binary');
  3769. } else if (value.id && value.id.copy) {
  3770. value.id.copy(buffer$$1, index, 0, 12);
  3771. } else {
  3772. throw new TypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId');
  3773. } // Ajust index
  3774. return index + 12;
  3775. }
  3776. function serializeBuffer(buffer$$1, key, value, index, isArray) {
  3777. // Write the type
  3778. buffer$$1[index++] = constants.BSON_DATA_BINARY; // Number of written bytes
  3779. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3780. index = index + numberOfWrittenBytes;
  3781. buffer$$1[index++] = 0; // Get size of the buffer (current write point)
  3782. var size = value.length; // Write the size of the string to buffer
  3783. buffer$$1[index++] = size & 0xff;
  3784. buffer$$1[index++] = size >> 8 & 0xff;
  3785. buffer$$1[index++] = size >> 16 & 0xff;
  3786. buffer$$1[index++] = size >> 24 & 0xff; // Write the default subtype
  3787. buffer$$1[index++] = constants.BSON_BINARY_SUBTYPE_DEFAULT; // Copy the content form the binary field to the buffer
  3788. value.copy(buffer$$1, index, 0, size); // Adjust the index
  3789. index = index + size;
  3790. return index;
  3791. }
  3792. function serializeObject(buffer$$1, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) {
  3793. for (var i = 0; i < path.length; i++) {
  3794. if (path[i] === value) throw new Error('cyclic dependency detected');
  3795. } // Push value to stack
  3796. path.push(value); // Write the type
  3797. buffer$$1[index++] = Array.isArray(value) ? constants.BSON_DATA_ARRAY : constants.BSON_DATA_OBJECT; // Number of written bytes
  3798. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3799. index = index + numberOfWrittenBytes;
  3800. buffer$$1[index++] = 0;
  3801. var endIndex = serializeInto(buffer$$1, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); // Pop stack
  3802. path.pop();
  3803. return endIndex;
  3804. }
  3805. function serializeDecimal128(buffer$$1, key, value, index, isArray) {
  3806. buffer$$1[index++] = constants.BSON_DATA_DECIMAL128; // Number of written bytes
  3807. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3808. index = index + numberOfWrittenBytes;
  3809. buffer$$1[index++] = 0; // Write the data from the value
  3810. value.bytes.copy(buffer$$1, index, 0, 16);
  3811. return index + 16;
  3812. }
  3813. function serializeLong(buffer$$1, key, value, index, isArray) {
  3814. // Write the type
  3815. buffer$$1[index++] = value._bsontype === 'Long' ? constants.BSON_DATA_LONG : constants.BSON_DATA_TIMESTAMP; // Number of written bytes
  3816. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3817. index = index + numberOfWrittenBytes;
  3818. buffer$$1[index++] = 0; // Write the date
  3819. var lowBits = value.getLowBits();
  3820. var highBits = value.getHighBits(); // Encode low bits
  3821. buffer$$1[index++] = lowBits & 0xff;
  3822. buffer$$1[index++] = lowBits >> 8 & 0xff;
  3823. buffer$$1[index++] = lowBits >> 16 & 0xff;
  3824. buffer$$1[index++] = lowBits >> 24 & 0xff; // Encode high bits
  3825. buffer$$1[index++] = highBits & 0xff;
  3826. buffer$$1[index++] = highBits >> 8 & 0xff;
  3827. buffer$$1[index++] = highBits >> 16 & 0xff;
  3828. buffer$$1[index++] = highBits >> 24 & 0xff;
  3829. return index;
  3830. }
  3831. function serializeInt32(buffer$$1, key, value, index, isArray) {
  3832. // Set int type 32 bits or less
  3833. buffer$$1[index++] = constants.BSON_DATA_INT; // Number of written bytes
  3834. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3835. index = index + numberOfWrittenBytes;
  3836. buffer$$1[index++] = 0; // Write the int value
  3837. buffer$$1[index++] = value & 0xff;
  3838. buffer$$1[index++] = value >> 8 & 0xff;
  3839. buffer$$1[index++] = value >> 16 & 0xff;
  3840. buffer$$1[index++] = value >> 24 & 0xff;
  3841. return index;
  3842. }
  3843. function serializeDouble(buffer$$1, key, value, index, isArray) {
  3844. // Encode as double
  3845. buffer$$1[index++] = constants.BSON_DATA_NUMBER; // Number of written bytes
  3846. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3847. index = index + numberOfWrittenBytes;
  3848. buffer$$1[index++] = 0; // Write float
  3849. writeIEEE754$1(buffer$$1, value.value, index, 'little', 52, 8); // Adjust index
  3850. index = index + 8;
  3851. return index;
  3852. }
  3853. function serializeFunction(buffer$$1, key, value, index, checkKeys, depth, isArray) {
  3854. buffer$$1[index++] = constants.BSON_DATA_CODE; // Number of written bytes
  3855. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3856. index = index + numberOfWrittenBytes;
  3857. buffer$$1[index++] = 0; // Function string
  3858. var functionString = normalizedFunctionString$1(value); // Write the string
  3859. var size = buffer$$1.write(functionString, index + 4, 'utf8') + 1; // Write the size of the string to buffer
  3860. buffer$$1[index] = size & 0xff;
  3861. buffer$$1[index + 1] = size >> 8 & 0xff;
  3862. buffer$$1[index + 2] = size >> 16 & 0xff;
  3863. buffer$$1[index + 3] = size >> 24 & 0xff; // Update index
  3864. index = index + 4 + size - 1; // Write zero
  3865. buffer$$1[index++] = 0;
  3866. return index;
  3867. }
  3868. function serializeCode(buffer$$1, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) {
  3869. if (value.scope && _typeof(value.scope) === 'object') {
  3870. // Write the type
  3871. buffer$$1[index++] = constants.BSON_DATA_CODE_W_SCOPE; // Number of written bytes
  3872. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3873. index = index + numberOfWrittenBytes;
  3874. buffer$$1[index++] = 0; // Starting index
  3875. var startIndex = index; // Serialize the function
  3876. // Get the function string
  3877. var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); // Index adjustment
  3878. index = index + 4; // Write string into buffer
  3879. var codeSize = buffer$$1.write(functionString, index + 4, 'utf8') + 1; // Write the size of the string to buffer
  3880. buffer$$1[index] = codeSize & 0xff;
  3881. buffer$$1[index + 1] = codeSize >> 8 & 0xff;
  3882. buffer$$1[index + 2] = codeSize >> 16 & 0xff;
  3883. buffer$$1[index + 3] = codeSize >> 24 & 0xff; // Write end 0
  3884. buffer$$1[index + 4 + codeSize - 1] = 0; // Write the
  3885. index = index + codeSize + 4; //
  3886. // Serialize the scope value
  3887. var endIndex = serializeInto(buffer$$1, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined);
  3888. index = endIndex - 1; // Writ the total
  3889. var totalSize = endIndex - startIndex; // Write the total size of the object
  3890. buffer$$1[startIndex++] = totalSize & 0xff;
  3891. buffer$$1[startIndex++] = totalSize >> 8 & 0xff;
  3892. buffer$$1[startIndex++] = totalSize >> 16 & 0xff;
  3893. buffer$$1[startIndex++] = totalSize >> 24 & 0xff; // Write trailing zero
  3894. buffer$$1[index++] = 0;
  3895. } else {
  3896. buffer$$1[index++] = constants.BSON_DATA_CODE; // Number of written bytes
  3897. var _numberOfWrittenBytes4 = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3898. index = index + _numberOfWrittenBytes4;
  3899. buffer$$1[index++] = 0; // Function string
  3900. var _functionString = value.code.toString(); // Write the string
  3901. var size = buffer$$1.write(_functionString, index + 4, 'utf8') + 1; // Write the size of the string to buffer
  3902. buffer$$1[index] = size & 0xff;
  3903. buffer$$1[index + 1] = size >> 8 & 0xff;
  3904. buffer$$1[index + 2] = size >> 16 & 0xff;
  3905. buffer$$1[index + 3] = size >> 24 & 0xff; // Update index
  3906. index = index + 4 + size - 1; // Write zero
  3907. buffer$$1[index++] = 0;
  3908. }
  3909. return index;
  3910. }
  3911. function serializeBinary(buffer$$1, key, value, index, isArray) {
  3912. // Write the type
  3913. buffer$$1[index++] = constants.BSON_DATA_BINARY; // Number of written bytes
  3914. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3915. index = index + numberOfWrittenBytes;
  3916. buffer$$1[index++] = 0; // Extract the buffer
  3917. var data = value.value(true); // Calculate size
  3918. var size = value.position; // Add the deprecated 02 type 4 bytes of size to total
  3919. if (value.sub_type === binary.SUBTYPE_BYTE_ARRAY) size = size + 4; // Write the size of the string to buffer
  3920. buffer$$1[index++] = size & 0xff;
  3921. buffer$$1[index++] = size >> 8 & 0xff;
  3922. buffer$$1[index++] = size >> 16 & 0xff;
  3923. buffer$$1[index++] = size >> 24 & 0xff; // Write the subtype to the buffer
  3924. buffer$$1[index++] = value.sub_type; // If we have binary type 2 the 4 first bytes are the size
  3925. if (value.sub_type === binary.SUBTYPE_BYTE_ARRAY) {
  3926. size = size - 4;
  3927. buffer$$1[index++] = size & 0xff;
  3928. buffer$$1[index++] = size >> 8 & 0xff;
  3929. buffer$$1[index++] = size >> 16 & 0xff;
  3930. buffer$$1[index++] = size >> 24 & 0xff;
  3931. } // Write the data to the object
  3932. data.copy(buffer$$1, index, 0, value.position); // Adjust the index
  3933. index = index + value.position;
  3934. return index;
  3935. }
  3936. function serializeSymbol(buffer$$1, key, value, index, isArray) {
  3937. // Write the type
  3938. buffer$$1[index++] = constants.BSON_DATA_SYMBOL; // Number of written bytes
  3939. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3940. index = index + numberOfWrittenBytes;
  3941. buffer$$1[index++] = 0; // Write the string
  3942. var size = buffer$$1.write(value.value, index + 4, 'utf8') + 1; // Write the size of the string to buffer
  3943. buffer$$1[index] = size & 0xff;
  3944. buffer$$1[index + 1] = size >> 8 & 0xff;
  3945. buffer$$1[index + 2] = size >> 16 & 0xff;
  3946. buffer$$1[index + 3] = size >> 24 & 0xff; // Update index
  3947. index = index + 4 + size - 1; // Write zero
  3948. buffer$$1[index++] = 0x00;
  3949. return index;
  3950. }
  3951. function serializeDBRef(buffer$$1, key, value, index, depth, serializeFunctions, isArray) {
  3952. // Write the type
  3953. buffer$$1[index++] = constants.BSON_DATA_OBJECT; // Number of written bytes
  3954. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3955. index = index + numberOfWrittenBytes;
  3956. buffer$$1[index++] = 0;
  3957. var startIndex = index;
  3958. var endIndex;
  3959. var output = {
  3960. $ref: value.collection,
  3961. $id: value.oid
  3962. };
  3963. if (value.db != null) output.$db = value.db;
  3964. output = Object.assign(output, value.fields);
  3965. endIndex = serializeInto(buffer$$1, output, false, index, depth + 1, serializeFunctions); // Calculate object size
  3966. var size = endIndex - startIndex; // Write the size
  3967. buffer$$1[startIndex++] = size & 0xff;
  3968. buffer$$1[startIndex++] = size >> 8 & 0xff;
  3969. buffer$$1[startIndex++] = size >> 16 & 0xff;
  3970. buffer$$1[startIndex++] = size >> 24 & 0xff; // Set index
  3971. return endIndex;
  3972. }
  3973. function serializeInto(buffer$$1, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) {
  3974. startingIndex = startingIndex || 0;
  3975. path = path || []; // Push the object to the path
  3976. path.push(object); // Start place to serialize into
  3977. var index = startingIndex + 4; // Special case isArray
  3978. if (Array.isArray(object)) {
  3979. // Get object keys
  3980. for (var i = 0; i < object.length; i++) {
  3981. var key = '' + i;
  3982. var value = object[i]; // Is there an override value
  3983. if (value && value.toBSON) {
  3984. if (typeof value.toBSON !== 'function') throw new TypeError('toBSON is not a function');
  3985. value = value.toBSON();
  3986. }
  3987. var type = _typeof(value);
  3988. if (type === 'string') {
  3989. index = serializeString(buffer$$1, key, value, index, true);
  3990. } else if (type === 'number') {
  3991. index = serializeNumber(buffer$$1, key, value, index, true);
  3992. } else if (type === 'boolean') {
  3993. index = serializeBoolean(buffer$$1, key, value, index, true);
  3994. } else if (value instanceof Date || isDate$1(value)) {
  3995. index = serializeDate(buffer$$1, key, value, index, true);
  3996. } else if (value === undefined) {
  3997. index = serializeNull(buffer$$1, key, value, index, true);
  3998. } else if (value === null) {
  3999. index = serializeNull(buffer$$1, key, value, index, true);
  4000. } else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') {
  4001. index = serializeObjectId(buffer$$1, key, value, index, true);
  4002. } else if (Buffer$3.isBuffer(value)) {
  4003. index = serializeBuffer(buffer$$1, key, value, index, true);
  4004. } else if (value instanceof RegExp || isRegExp$1(value)) {
  4005. index = serializeRegExp(buffer$$1, key, value, index, true);
  4006. } else if (type === 'object' && value['_bsontype'] == null) {
  4007. index = serializeObject(buffer$$1, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path);
  4008. } else if (type === 'object' && value['_bsontype'] === 'Decimal128') {
  4009. index = serializeDecimal128(buffer$$1, key, value, index, true);
  4010. } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') {
  4011. index = serializeLong(buffer$$1, key, value, index, true);
  4012. } else if (value['_bsontype'] === 'Double') {
  4013. index = serializeDouble(buffer$$1, key, value, index, true);
  4014. } else if (typeof value === 'function' && serializeFunctions) {
  4015. index = serializeFunction(buffer$$1, key, value, index, checkKeys, depth, serializeFunctions, true);
  4016. } else if (value['_bsontype'] === 'Code') {
  4017. index = serializeCode(buffer$$1, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true);
  4018. } else if (value['_bsontype'] === 'Binary') {
  4019. index = serializeBinary(buffer$$1, key, value, index, true);
  4020. } else if (value['_bsontype'] === 'Symbol') {
  4021. index = serializeSymbol(buffer$$1, key, value, index, true);
  4022. } else if (value['_bsontype'] === 'DBRef') {
  4023. index = serializeDBRef(buffer$$1, key, value, index, depth, serializeFunctions, true);
  4024. } else if (value['_bsontype'] === 'BSONRegExp') {
  4025. index = serializeBSONRegExp(buffer$$1, key, value, index, true);
  4026. } else if (value['_bsontype'] === 'Int32') {
  4027. index = serializeInt32(buffer$$1, key, value, index, true);
  4028. } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
  4029. index = serializeMinMax(buffer$$1, key, value, index, true);
  4030. }
  4031. }
  4032. } else if (object instanceof map) {
  4033. var iterator = object.entries();
  4034. var done = false;
  4035. while (!done) {
  4036. // Unpack the next entry
  4037. var entry = iterator.next();
  4038. done = entry.done; // Are we done, then skip and terminate
  4039. if (done) continue; // Get the entry values
  4040. var _key = entry.value[0];
  4041. var _value = entry.value[1]; // Check the type of the value
  4042. var _type = _typeof(_value); // Check the key and throw error if it's illegal
  4043. if (typeof _key === 'string' && !ignoreKeys.has(_key)) {
  4044. if (_key.match(regexp$1) != null) {
  4045. // The BSON spec doesn't allow keys with null bytes because keys are
  4046. // null-terminated.
  4047. throw Error('key ' + _key + ' must not contain null bytes');
  4048. }
  4049. if (checkKeys) {
  4050. if ('$' === _key[0]) {
  4051. throw Error('key ' + _key + " must not start with '$'");
  4052. } else if (~_key.indexOf('.')) {
  4053. throw Error('key ' + _key + " must not contain '.'");
  4054. }
  4055. }
  4056. }
  4057. if (_type === 'string') {
  4058. index = serializeString(buffer$$1, _key, _value, index);
  4059. } else if (_type === 'number') {
  4060. index = serializeNumber(buffer$$1, _key, _value, index);
  4061. } else if (_type === 'boolean') {
  4062. index = serializeBoolean(buffer$$1, _key, _value, index);
  4063. } else if (_value instanceof Date || isDate$1(_value)) {
  4064. index = serializeDate(buffer$$1, _key, _value, index);
  4065. } else if (_value === null || _value === undefined && ignoreUndefined === false) {
  4066. index = serializeNull(buffer$$1, _key, _value, index);
  4067. } else if (_value['_bsontype'] === 'ObjectId' || _value['_bsontype'] === 'ObjectID') {
  4068. index = serializeObjectId(buffer$$1, _key, _value, index);
  4069. } else if (Buffer$3.isBuffer(_value)) {
  4070. index = serializeBuffer(buffer$$1, _key, _value, index);
  4071. } else if (_value instanceof RegExp || isRegExp$1(_value)) {
  4072. index = serializeRegExp(buffer$$1, _key, _value, index);
  4073. } else if (_type === 'object' && _value['_bsontype'] == null) {
  4074. index = serializeObject(buffer$$1, _key, _value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path);
  4075. } else if (_type === 'object' && _value['_bsontype'] === 'Decimal128') {
  4076. index = serializeDecimal128(buffer$$1, _key, _value, index);
  4077. } else if (_value['_bsontype'] === 'Long' || _value['_bsontype'] === 'Timestamp') {
  4078. index = serializeLong(buffer$$1, _key, _value, index);
  4079. } else if (_value['_bsontype'] === 'Double') {
  4080. index = serializeDouble(buffer$$1, _key, _value, index);
  4081. } else if (_value['_bsontype'] === 'Code') {
  4082. index = serializeCode(buffer$$1, _key, _value, index, checkKeys, depth, serializeFunctions, ignoreUndefined);
  4083. } else if (typeof _value === 'function' && serializeFunctions) {
  4084. index = serializeFunction(buffer$$1, _key, _value, index, checkKeys, depth, serializeFunctions);
  4085. } else if (_value['_bsontype'] === 'Binary') {
  4086. index = serializeBinary(buffer$$1, _key, _value, index);
  4087. } else if (_value['_bsontype'] === 'Symbol') {
  4088. index = serializeSymbol(buffer$$1, _key, _value, index);
  4089. } else if (_value['_bsontype'] === 'DBRef') {
  4090. index = serializeDBRef(buffer$$1, _key, _value, index, depth, serializeFunctions);
  4091. } else if (_value['_bsontype'] === 'BSONRegExp') {
  4092. index = serializeBSONRegExp(buffer$$1, _key, _value, index);
  4093. } else if (_value['_bsontype'] === 'Int32') {
  4094. index = serializeInt32(buffer$$1, _key, _value, index);
  4095. } else if (_value['_bsontype'] === 'MinKey' || _value['_bsontype'] === 'MaxKey') {
  4096. index = serializeMinMax(buffer$$1, _key, _value, index);
  4097. }
  4098. }
  4099. } else {
  4100. // Did we provide a custom serialization method
  4101. if (object.toBSON) {
  4102. if (typeof object.toBSON !== 'function') throw new TypeError('toBSON is not a function');
  4103. object = object.toBSON();
  4104. if (object != null && _typeof(object) !== 'object') throw new TypeError('toBSON function did not return an object');
  4105. } // Iterate over all the keys
  4106. for (var _key2 in object) {
  4107. var _value2 = object[_key2]; // Is there an override value
  4108. if (_value2 && _value2.toBSON) {
  4109. if (typeof _value2.toBSON !== 'function') throw new TypeError('toBSON is not a function');
  4110. _value2 = _value2.toBSON();
  4111. } // Check the type of the value
  4112. var _type2 = _typeof(_value2); // Check the key and throw error if it's illegal
  4113. if (typeof _key2 === 'string' && !ignoreKeys.has(_key2)) {
  4114. if (_key2.match(regexp$1) != null) {
  4115. // The BSON spec doesn't allow keys with null bytes because keys are
  4116. // null-terminated.
  4117. throw Error('key ' + _key2 + ' must not contain null bytes');
  4118. }
  4119. if (checkKeys) {
  4120. if ('$' === _key2[0]) {
  4121. throw Error('key ' + _key2 + " must not start with '$'");
  4122. } else if (~_key2.indexOf('.')) {
  4123. throw Error('key ' + _key2 + " must not contain '.'");
  4124. }
  4125. }
  4126. }
  4127. if (_type2 === 'string') {
  4128. index = serializeString(buffer$$1, _key2, _value2, index);
  4129. } else if (_type2 === 'number') {
  4130. index = serializeNumber(buffer$$1, _key2, _value2, index);
  4131. } else if (_type2 === 'boolean') {
  4132. index = serializeBoolean(buffer$$1, _key2, _value2, index);
  4133. } else if (_value2 instanceof Date || isDate$1(_value2)) {
  4134. index = serializeDate(buffer$$1, _key2, _value2, index);
  4135. } else if (_value2 === undefined) {
  4136. if (ignoreUndefined === false) index = serializeNull(buffer$$1, _key2, _value2, index);
  4137. } else if (_value2 === null) {
  4138. index = serializeNull(buffer$$1, _key2, _value2, index);
  4139. } else if (_value2['_bsontype'] === 'ObjectId' || _value2['_bsontype'] === 'ObjectID') {
  4140. index = serializeObjectId(buffer$$1, _key2, _value2, index);
  4141. } else if (Buffer$3.isBuffer(_value2)) {
  4142. index = serializeBuffer(buffer$$1, _key2, _value2, index);
  4143. } else if (_value2 instanceof RegExp || isRegExp$1(_value2)) {
  4144. index = serializeRegExp(buffer$$1, _key2, _value2, index);
  4145. } else if (_type2 === 'object' && _value2['_bsontype'] == null) {
  4146. index = serializeObject(buffer$$1, _key2, _value2, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path);
  4147. } else if (_type2 === 'object' && _value2['_bsontype'] === 'Decimal128') {
  4148. index = serializeDecimal128(buffer$$1, _key2, _value2, index);
  4149. } else if (_value2['_bsontype'] === 'Long' || _value2['_bsontype'] === 'Timestamp') {
  4150. index = serializeLong(buffer$$1, _key2, _value2, index);
  4151. } else if (_value2['_bsontype'] === 'Double') {
  4152. index = serializeDouble(buffer$$1, _key2, _value2, index);
  4153. } else if (_value2['_bsontype'] === 'Code') {
  4154. index = serializeCode(buffer$$1, _key2, _value2, index, checkKeys, depth, serializeFunctions, ignoreUndefined);
  4155. } else if (typeof _value2 === 'function' && serializeFunctions) {
  4156. index = serializeFunction(buffer$$1, _key2, _value2, index, checkKeys, depth, serializeFunctions);
  4157. } else if (_value2['_bsontype'] === 'Binary') {
  4158. index = serializeBinary(buffer$$1, _key2, _value2, index);
  4159. } else if (_value2['_bsontype'] === 'Symbol') {
  4160. index = serializeSymbol(buffer$$1, _key2, _value2, index);
  4161. } else if (_value2['_bsontype'] === 'DBRef') {
  4162. index = serializeDBRef(buffer$$1, _key2, _value2, index, depth, serializeFunctions);
  4163. } else if (_value2['_bsontype'] === 'BSONRegExp') {
  4164. index = serializeBSONRegExp(buffer$$1, _key2, _value2, index);
  4165. } else if (_value2['_bsontype'] === 'Int32') {
  4166. index = serializeInt32(buffer$$1, _key2, _value2, index);
  4167. } else if (_value2['_bsontype'] === 'MinKey' || _value2['_bsontype'] === 'MaxKey') {
  4168. index = serializeMinMax(buffer$$1, _key2, _value2, index);
  4169. }
  4170. }
  4171. } // Remove the path
  4172. path.pop(); // Final padding byte for object
  4173. buffer$$1[index++] = 0x00; // Final size
  4174. var size = index - startingIndex; // Write the size of the object
  4175. buffer$$1[startingIndex++] = size & 0xff;
  4176. buffer$$1[startingIndex++] = size >> 8 & 0xff;
  4177. buffer$$1[startingIndex++] = size >> 16 & 0xff;
  4178. buffer$$1[startingIndex++] = size >> 24 & 0xff;
  4179. return index;
  4180. }
  4181. var serializer = serializeInto;
  4182. var Buffer$4 = buffer.Buffer;
  4183. var normalizedFunctionString$2 = utils.normalizedFunctionString; // To ensure that 0.4 of node works correctly
  4184. function isDate$2(d) {
  4185. return _typeof(d) === 'object' && Object.prototype.toString.call(d) === '[object Date]';
  4186. }
  4187. function calculateObjectSize(object, serializeFunctions, ignoreUndefined) {
  4188. var totalLength = 4 + 1;
  4189. if (Array.isArray(object)) {
  4190. for (var i = 0; i < object.length; i++) {
  4191. totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined);
  4192. }
  4193. } else {
  4194. // If we have toBSON defined, override the current object
  4195. if (object.toBSON) {
  4196. object = object.toBSON();
  4197. } // Calculate size
  4198. for (var key in object) {
  4199. totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined);
  4200. }
  4201. }
  4202. return totalLength;
  4203. }
  4204. /**
  4205. * @ignore
  4206. * @api private
  4207. */
  4208. function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) {
  4209. // If we have toBSON defined, override the current object
  4210. if (value && value.toBSON) {
  4211. value = value.toBSON();
  4212. }
  4213. switch (_typeof(value)) {
  4214. case 'string':
  4215. return 1 + Buffer$4.byteLength(name, 'utf8') + 1 + 4 + Buffer$4.byteLength(value, 'utf8') + 1;
  4216. case 'number':
  4217. if (Math.floor(value) === value && value >= constants.JS_INT_MIN && value <= constants.JS_INT_MAX) {
  4218. if (value >= constants.BSON_INT32_MIN && value <= constants.BSON_INT32_MAX) {
  4219. // 32 bit
  4220. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + (4 + 1);
  4221. } else {
  4222. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  4223. }
  4224. } else {
  4225. // 64 bit
  4226. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  4227. }
  4228. case 'undefined':
  4229. if (isArray || !ignoreUndefined) return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + 1;
  4230. return 0;
  4231. case 'boolean':
  4232. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + (1 + 1);
  4233. case 'object':
  4234. if (value == null || value instanceof min_key || value instanceof max_key || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
  4235. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + 1;
  4236. } else if (value instanceof objectid || value['_bsontype'] === 'ObjectId') {
  4237. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + (12 + 1);
  4238. } else if (value instanceof Date || isDate$2(value)) {
  4239. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  4240. } else if (typeof Buffer$4 !== 'undefined' && Buffer$4.isBuffer(value)) {
  4241. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length;
  4242. } else if (value instanceof long_1 || value instanceof double_1 || value instanceof timestamp || value['_bsontype'] === 'Long' || value['_bsontype'] === 'Double' || value['_bsontype'] === 'Timestamp') {
  4243. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  4244. } else if (value instanceof decimal128 || value['_bsontype'] === 'Decimal128') {
  4245. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + (16 + 1);
  4246. } else if (value instanceof code || value['_bsontype'] === 'Code') {
  4247. // Calculate size depending on the availability of a scope
  4248. if (value.scope != null && Object.keys(value.scope).length > 0) {
  4249. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer$4.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined);
  4250. } else {
  4251. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer$4.byteLength(value.code.toString(), 'utf8') + 1;
  4252. }
  4253. } else if (value instanceof binary || value['_bsontype'] === 'Binary') {
  4254. // Check what kind of subtype we have
  4255. if (value.sub_type === binary.SUBTYPE_BYTE_ARRAY) {
  4256. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1 + 4);
  4257. } else {
  4258. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1);
  4259. }
  4260. } else if (value instanceof symbol || value['_bsontype'] === 'Symbol') {
  4261. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + Buffer$4.byteLength(value.value, 'utf8') + 4 + 1 + 1;
  4262. } else if (value instanceof db_ref || value['_bsontype'] === 'DBRef') {
  4263. // Set up correct object for serialization
  4264. var ordered_values = Object.assign({
  4265. $ref: value.collection,
  4266. $id: value.oid
  4267. }, value.fields); // Add db reference if it exists
  4268. if (value.db != null) {
  4269. ordered_values['$db'] = value.db;
  4270. }
  4271. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined);
  4272. } else if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') {
  4273. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer$4.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1;
  4274. } else if (value instanceof regexp || value['_bsontype'] === 'BSONRegExp') {
  4275. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer$4.byteLength(value.pattern, 'utf8') + 1 + Buffer$4.byteLength(value.options, 'utf8') + 1;
  4276. } else {
  4277. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1;
  4278. }
  4279. case 'function':
  4280. // WTF for 0.4.X where typeof /someregexp/ === 'function'
  4281. if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) === '[object RegExp]') {
  4282. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer$4.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1;
  4283. } else {
  4284. if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) {
  4285. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer$4.byteLength(normalizedFunctionString$2(value), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined);
  4286. } else if (serializeFunctions) {
  4287. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer$4.byteLength(normalizedFunctionString$2(value), 'utf8') + 1;
  4288. }
  4289. }
  4290. }
  4291. return 0;
  4292. }
  4293. var calculate_size = calculateObjectSize;
  4294. var Buffer$5 = buffer.Buffer;
  4295. /**
  4296. * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer.
  4297. *
  4298. * @param {Buffer|Uint8Array} potentialBuffer The potential buffer
  4299. * @returns {Buffer} the input if potentialBuffer is a buffer, or a buffer that
  4300. * wraps a passed in Uint8Array
  4301. * @throws {TypeError} If anything other than a Buffer or Uint8Array is passed in
  4302. */
  4303. var ensure_buffer = function ensureBuffer(potentialBuffer) {
  4304. if (potentialBuffer instanceof Buffer$5) {
  4305. return potentialBuffer;
  4306. }
  4307. if (potentialBuffer instanceof Uint8Array) {
  4308. return Buffer$5.from(potentialBuffer.buffer);
  4309. }
  4310. throw new TypeError('Must use either Buffer or Uint8Array');
  4311. };
  4312. var Buffer$6 = buffer.Buffer; // Parts of the parser
  4313. /**
  4314. * @ignore
  4315. */
  4316. // Default Max Size
  4317. var MAXSIZE = 1024 * 1024 * 17; // Current Internal Temporary Serialization Buffer
  4318. var buffer$1 = Buffer$6.alloc(MAXSIZE);
  4319. /**
  4320. * Sets the size of the internal serialization buffer.
  4321. *
  4322. * @method
  4323. * @param {number} size The desired size for the internal serialization buffer
  4324. */
  4325. function setInternalBufferSize(size) {
  4326. // Resize the internal serialization buffer if needed
  4327. if (buffer$1.length < size) {
  4328. buffer$1 = Buffer$6.alloc(size);
  4329. }
  4330. }
  4331. /**
  4332. * Serialize a Javascript object.
  4333. *
  4334. * @param {Object} object the Javascript object to serialize.
  4335. * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid.
  4336. * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**.
  4337. * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**.
  4338. * @return {Buffer} returns the Buffer object containing the serialized object.
  4339. */
  4340. function serialize$1(object, options) {
  4341. options = options || {}; // Unpack the options
  4342. var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
  4343. var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  4344. var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  4345. var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; // Resize the internal serialization buffer if needed
  4346. if (buffer$1.length < minInternalBufferSize) {
  4347. buffer$1 = Buffer$6.alloc(minInternalBufferSize);
  4348. } // Attempt to serialize
  4349. var serializationIndex = serializer(buffer$1, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); // Create the final buffer
  4350. var finishedBuffer = Buffer$6.alloc(serializationIndex); // Copy into the finished buffer
  4351. buffer$1.copy(finishedBuffer, 0, 0, finishedBuffer.length); // Return the buffer
  4352. return finishedBuffer;
  4353. }
  4354. /**
  4355. * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization.
  4356. *
  4357. * @param {Object} object the Javascript object to serialize.
  4358. * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object.
  4359. * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid.
  4360. * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**.
  4361. * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**.
  4362. * @param {Number} [options.index] the index in the buffer where we wish to start serializing into.
  4363. * @return {Number} returns the index pointing to the last written byte in the buffer.
  4364. */
  4365. function serializeWithBufferAndIndex(object, finalBuffer, options) {
  4366. options = options || {}; // Unpack the options
  4367. var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
  4368. var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  4369. var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  4370. var startIndex = typeof options.index === 'number' ? options.index : 0; // Attempt to serialize
  4371. var serializationIndex = serializer(buffer$1, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined);
  4372. buffer$1.copy(finalBuffer, startIndex, 0, serializationIndex); // Return the index
  4373. return startIndex + serializationIndex - 1;
  4374. }
  4375. /**
  4376. * Deserialize data as BSON.
  4377. *
  4378. * @param {Buffer} buffer the buffer containing the serialized set of BSON documents.
  4379. * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized.
  4380. * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse.
  4381. * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function.
  4382. * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits
  4383. * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance.
  4384. * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types.
  4385. * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer.
  4386. * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances.
  4387. * @param {boolean} [options.allowObjectSmallerThanBufferSize=false] allows the buffer to be larger than the parsed BSON object
  4388. * @return {Object} returns the deserialized Javascript Object.
  4389. */
  4390. function deserialize$2(buffer$$1, options) {
  4391. buffer$$1 = ensure_buffer(buffer$$1);
  4392. return deserializer(buffer$$1, options);
  4393. }
  4394. /**
  4395. * Calculate the bson size for a passed in Javascript object.
  4396. *
  4397. * @param {Object} object the Javascript object to calculate the BSON byte size for.
  4398. * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**.
  4399. * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**.
  4400. * @return {Number} returns the number of bytes the BSON object will take up.
  4401. */
  4402. function calculateObjectSize$1(object, options) {
  4403. options = options || {};
  4404. var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  4405. var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  4406. return calculate_size(object, serializeFunctions, ignoreUndefined);
  4407. }
  4408. /**
  4409. * Deserialize stream data as BSON documents.
  4410. *
  4411. * @param {Buffer} data the buffer containing the serialized set of BSON documents.
  4412. * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start.
  4413. * @param {Number} numberOfDocuments number of documents to deserialize.
  4414. * @param {Array} documents an array where to store the deserialized documents.
  4415. * @param {Number} docStartIndex the index in the documents array from where to start inserting documents.
  4416. * @param {Object} [options] additional options used for the deserialization.
  4417. * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized.
  4418. * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse.
  4419. * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function.
  4420. * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits
  4421. * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance.
  4422. * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types.
  4423. * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer.
  4424. * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances.
  4425. * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents.
  4426. */
  4427. function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) {
  4428. options = Object.assign({
  4429. allowObjectSmallerThanBufferSize: true
  4430. }, options);
  4431. data = ensure_buffer(data);
  4432. var index = startIndex; // Loop over all documents
  4433. for (var i = 0; i < numberOfDocuments; i++) {
  4434. // Find size of the document
  4435. var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; // Update options with index
  4436. options.index = index; // Parse the document at this point
  4437. documents[docStartIndex + i] = deserializer(data, options); // Adjust index by the document size
  4438. index = index + size;
  4439. } // Return object containing end index of parsing and list of documents
  4440. return index;
  4441. }
  4442. var bson = {
  4443. // constants
  4444. // NOTE: this is done this way because rollup can't resolve an `Object.assign`ed export
  4445. BSON_INT32_MAX: constants.BSON_INT32_MAX,
  4446. BSON_INT32_MIN: constants.BSON_INT32_MIN,
  4447. BSON_INT64_MAX: constants.BSON_INT64_MAX,
  4448. BSON_INT64_MIN: constants.BSON_INT64_MIN,
  4449. JS_INT_MAX: constants.JS_INT_MAX,
  4450. JS_INT_MIN: constants.JS_INT_MIN,
  4451. BSON_DATA_NUMBER: constants.BSON_DATA_NUMBER,
  4452. BSON_DATA_STRING: constants.BSON_DATA_STRING,
  4453. BSON_DATA_OBJECT: constants.BSON_DATA_OBJECT,
  4454. BSON_DATA_ARRAY: constants.BSON_DATA_ARRAY,
  4455. BSON_DATA_BINARY: constants.BSON_DATA_BINARY,
  4456. BSON_DATA_UNDEFINED: constants.BSON_DATA_UNDEFINED,
  4457. BSON_DATA_OID: constants.BSON_DATA_OID,
  4458. BSON_DATA_BOOLEAN: constants.BSON_DATA_BOOLEAN,
  4459. BSON_DATA_DATE: constants.BSON_DATA_DATE,
  4460. BSON_DATA_NULL: constants.BSON_DATA_NULL,
  4461. BSON_DATA_REGEXP: constants.BSON_DATA_REGEXP,
  4462. BSON_DATA_DBPOINTER: constants.BSON_DATA_DBPOINTER,
  4463. BSON_DATA_CODE: constants.BSON_DATA_CODE,
  4464. BSON_DATA_SYMBOL: constants.BSON_DATA_SYMBOL,
  4465. BSON_DATA_CODE_W_SCOPE: constants.BSON_DATA_CODE_W_SCOPE,
  4466. BSON_DATA_INT: constants.BSON_DATA_INT,
  4467. BSON_DATA_TIMESTAMP: constants.BSON_DATA_TIMESTAMP,
  4468. BSON_DATA_LONG: constants.BSON_DATA_LONG,
  4469. BSON_DATA_DECIMAL128: constants.BSON_DATA_DECIMAL128,
  4470. BSON_DATA_MIN_KEY: constants.BSON_DATA_MIN_KEY,
  4471. BSON_DATA_MAX_KEY: constants.BSON_DATA_MAX_KEY,
  4472. BSON_BINARY_SUBTYPE_DEFAULT: constants.BSON_BINARY_SUBTYPE_DEFAULT,
  4473. BSON_BINARY_SUBTYPE_FUNCTION: constants.BSON_BINARY_SUBTYPE_FUNCTION,
  4474. BSON_BINARY_SUBTYPE_BYTE_ARRAY: constants.BSON_BINARY_SUBTYPE_BYTE_ARRAY,
  4475. BSON_BINARY_SUBTYPE_UUID: constants.BSON_BINARY_SUBTYPE_UUID,
  4476. BSON_BINARY_SUBTYPE_MD5: constants.BSON_BINARY_SUBTYPE_MD5,
  4477. BSON_BINARY_SUBTYPE_USER_DEFINED: constants.BSON_BINARY_SUBTYPE_USER_DEFINED,
  4478. // wrapped types
  4479. Code: code,
  4480. Map: map,
  4481. BSONSymbol: symbol,
  4482. DBRef: db_ref,
  4483. Binary: binary,
  4484. ObjectId: objectid,
  4485. Long: long_1,
  4486. Timestamp: timestamp,
  4487. Double: double_1,
  4488. Int32: int_32,
  4489. MinKey: min_key,
  4490. MaxKey: max_key,
  4491. BSONRegExp: regexp,
  4492. Decimal128: decimal128,
  4493. // methods
  4494. serialize: serialize$1,
  4495. serializeWithBufferAndIndex: serializeWithBufferAndIndex,
  4496. deserialize: deserialize$2,
  4497. calculateObjectSize: calculateObjectSize$1,
  4498. deserializeStream: deserializeStream,
  4499. setInternalBufferSize: setInternalBufferSize,
  4500. // legacy support
  4501. ObjectID: objectid,
  4502. // Extended JSON
  4503. EJSON: extended_json
  4504. };
  4505. var bson_1 = bson.BSON_INT32_MAX;
  4506. var bson_2 = bson.BSON_INT32_MIN;
  4507. var bson_3 = bson.BSON_INT64_MAX;
  4508. var bson_4 = bson.BSON_INT64_MIN;
  4509. var bson_5 = bson.JS_INT_MAX;
  4510. var bson_6 = bson.JS_INT_MIN;
  4511. var bson_7 = bson.BSON_DATA_NUMBER;
  4512. var bson_8 = bson.BSON_DATA_STRING;
  4513. var bson_9 = bson.BSON_DATA_OBJECT;
  4514. var bson_10 = bson.BSON_DATA_ARRAY;
  4515. var bson_11 = bson.BSON_DATA_BINARY;
  4516. var bson_12 = bson.BSON_DATA_UNDEFINED;
  4517. var bson_13 = bson.BSON_DATA_OID;
  4518. var bson_14 = bson.BSON_DATA_BOOLEAN;
  4519. var bson_15 = bson.BSON_DATA_DATE;
  4520. var bson_16 = bson.BSON_DATA_NULL;
  4521. var bson_17 = bson.BSON_DATA_REGEXP;
  4522. var bson_18 = bson.BSON_DATA_DBPOINTER;
  4523. var bson_19 = bson.BSON_DATA_CODE;
  4524. var bson_20 = bson.BSON_DATA_SYMBOL;
  4525. var bson_21 = bson.BSON_DATA_CODE_W_SCOPE;
  4526. var bson_22 = bson.BSON_DATA_INT;
  4527. var bson_23 = bson.BSON_DATA_TIMESTAMP;
  4528. var bson_24 = bson.BSON_DATA_LONG;
  4529. var bson_25 = bson.BSON_DATA_DECIMAL128;
  4530. var bson_26 = bson.BSON_DATA_MIN_KEY;
  4531. var bson_27 = bson.BSON_DATA_MAX_KEY;
  4532. var bson_28 = bson.BSON_BINARY_SUBTYPE_DEFAULT;
  4533. var bson_29 = bson.BSON_BINARY_SUBTYPE_FUNCTION;
  4534. var bson_30 = bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY;
  4535. var bson_31 = bson.BSON_BINARY_SUBTYPE_UUID;
  4536. var bson_32 = bson.BSON_BINARY_SUBTYPE_MD5;
  4537. var bson_33 = bson.BSON_BINARY_SUBTYPE_USER_DEFINED;
  4538. var bson_34 = bson.Code;
  4539. var bson_35 = bson.BSONSymbol;
  4540. var bson_36 = bson.DBRef;
  4541. var bson_37 = bson.Binary;
  4542. var bson_38 = bson.ObjectId;
  4543. var bson_39 = bson.Long;
  4544. var bson_40 = bson.Timestamp;
  4545. var bson_41 = bson.Double;
  4546. var bson_42 = bson.Int32;
  4547. var bson_43 = bson.MinKey;
  4548. var bson_44 = bson.MaxKey;
  4549. var bson_45 = bson.BSONRegExp;
  4550. var bson_46 = bson.Decimal128;
  4551. var bson_47 = bson.serialize;
  4552. var bson_48 = bson.serializeWithBufferAndIndex;
  4553. var bson_49 = bson.deserialize;
  4554. var bson_50 = bson.calculateObjectSize;
  4555. var bson_51 = bson.deserializeStream;
  4556. var bson_52 = bson.setInternalBufferSize;
  4557. var bson_53 = bson.ObjectID;
  4558. var bson_54 = bson.EJSON;
  4559. export default bson;
  4560. export { bson_1 as BSON_INT32_MAX, bson_2 as BSON_INT32_MIN, bson_3 as BSON_INT64_MAX, bson_4 as BSON_INT64_MIN, bson_5 as JS_INT_MAX, bson_6 as JS_INT_MIN, bson_7 as BSON_DATA_NUMBER, bson_8 as BSON_DATA_STRING, bson_9 as BSON_DATA_OBJECT, bson_10 as BSON_DATA_ARRAY, bson_11 as BSON_DATA_BINARY, bson_12 as BSON_DATA_UNDEFINED, bson_13 as BSON_DATA_OID, bson_14 as BSON_DATA_BOOLEAN, bson_15 as BSON_DATA_DATE, bson_16 as BSON_DATA_NULL, bson_17 as BSON_DATA_REGEXP, bson_18 as BSON_DATA_DBPOINTER, bson_19 as BSON_DATA_CODE, bson_20 as BSON_DATA_SYMBOL, bson_21 as BSON_DATA_CODE_W_SCOPE, bson_22 as BSON_DATA_INT, bson_23 as BSON_DATA_TIMESTAMP, bson_24 as BSON_DATA_LONG, bson_25 as BSON_DATA_DECIMAL128, bson_26 as BSON_DATA_MIN_KEY, bson_27 as BSON_DATA_MAX_KEY, bson_28 as BSON_BINARY_SUBTYPE_DEFAULT, bson_29 as BSON_BINARY_SUBTYPE_FUNCTION, bson_30 as BSON_BINARY_SUBTYPE_BYTE_ARRAY, bson_31 as BSON_BINARY_SUBTYPE_UUID, bson_32 as BSON_BINARY_SUBTYPE_MD5, bson_33 as BSON_BINARY_SUBTYPE_USER_DEFINED, bson_34 as Code, bson_35 as BSONSymbol, bson_36 as DBRef, bson_37 as Binary, bson_38 as ObjectId, bson_39 as Long, bson_40 as Timestamp, bson_41 as Double, bson_42 as Int32, bson_43 as MinKey, bson_44 as MaxKey, bson_45 as BSONRegExp, bson_46 as Decimal128, bson_47 as serialize, bson_48 as serializeWithBufferAndIndex, bson_49 as deserialize, bson_50 as calculateObjectSize, bson_51 as deserializeStream, bson_52 as setInternalBufferSize, bson_53 as ObjectID, bson_54 as EJSON };