bson.browser.umd.js 181 KB

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