bson.browser.esm.js 316 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952
  1. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  2. function unwrapExports (x) {
  3. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  4. }
  5. function createCommonjsModule(fn, module) {
  6. return module = { exports: {} }, fn(module, module.exports), module.exports;
  7. }
  8. var byteLength_1 = byteLength;
  9. var toByteArray_1 = toByteArray;
  10. var fromByteArray_1 = fromByteArray;
  11. var lookup = [];
  12. var revLookup = [];
  13. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
  14. var code$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  15. for (var i = 0, len = code$1.length; i < len; ++i) {
  16. lookup[i] = code$1[i];
  17. revLookup[code$1.charCodeAt(i)] = i;
  18. } // Support decoding URL-safe base64 strings, as Node.js does.
  19. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  20. revLookup['-'.charCodeAt(0)] = 62;
  21. revLookup['_'.charCodeAt(0)] = 63;
  22. function getLens(b64) {
  23. var len = b64.length;
  24. if (len % 4 > 0) {
  25. throw new Error('Invalid string. Length must be a multiple of 4');
  26. } // Trim off extra bytes after placeholder bytes are found
  27. // See: https://github.com/beatgammit/base64-js/issues/42
  28. var validLen = b64.indexOf('=');
  29. if (validLen === -1) validLen = len;
  30. var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4;
  31. return [validLen, placeHoldersLen];
  32. } // base64 is 4/3 + up to two characters of the original data
  33. function byteLength(b64) {
  34. var lens = getLens(b64);
  35. var validLen = lens[0];
  36. var placeHoldersLen = lens[1];
  37. return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
  38. }
  39. function _byteLength(b64, validLen, placeHoldersLen) {
  40. return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
  41. }
  42. function toByteArray(b64) {
  43. var tmp;
  44. var lens = getLens(b64);
  45. var validLen = lens[0];
  46. var placeHoldersLen = lens[1];
  47. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
  48. var curByte = 0; // if there are placeholders, only get up to the last complete 4 chars
  49. var len = placeHoldersLen > 0 ? validLen - 4 : validLen;
  50. var i;
  51. for (i = 0; i < len; i += 4) {
  52. tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
  53. arr[curByte++] = tmp >> 16 & 0xFF;
  54. arr[curByte++] = tmp >> 8 & 0xFF;
  55. arr[curByte++] = tmp & 0xFF;
  56. }
  57. if (placeHoldersLen === 2) {
  58. tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
  59. arr[curByte++] = tmp & 0xFF;
  60. }
  61. if (placeHoldersLen === 1) {
  62. tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
  63. arr[curByte++] = tmp >> 8 & 0xFF;
  64. arr[curByte++] = tmp & 0xFF;
  65. }
  66. return arr;
  67. }
  68. function tripletToBase64(num) {
  69. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F];
  70. }
  71. function encodeChunk(uint8, start, end) {
  72. var tmp;
  73. var output = [];
  74. for (var i = start; i < end; i += 3) {
  75. tmp = (uint8[i] << 16 & 0xFF0000) + (uint8[i + 1] << 8 & 0xFF00) + (uint8[i + 2] & 0xFF);
  76. output.push(tripletToBase64(tmp));
  77. }
  78. return output.join('');
  79. }
  80. function fromByteArray(uint8) {
  81. var tmp;
  82. var len = uint8.length;
  83. var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
  84. var parts = [];
  85. var maxChunkLength = 16383; // must be multiple of 3
  86. // go through the array every three bytes, we'll deal with trailing stuff later
  87. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  88. parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
  89. } // pad the end with zeros, but make sure to not forget the extra bytes
  90. if (extraBytes === 1) {
  91. tmp = uint8[len - 1];
  92. parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 0x3F] + '==');
  93. } else if (extraBytes === 2) {
  94. tmp = (uint8[len - 2] << 8) + uint8[len - 1];
  95. parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 0x3F] + lookup[tmp << 2 & 0x3F] + '=');
  96. }
  97. return parts.join('');
  98. }
  99. var base64Js = {
  100. byteLength: byteLength_1,
  101. toByteArray: toByteArray_1,
  102. fromByteArray: fromByteArray_1
  103. };
  104. /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
  105. var read = function read(buffer, offset, isLE, mLen, nBytes) {
  106. var e, m;
  107. var eLen = nBytes * 8 - mLen - 1;
  108. var eMax = (1 << eLen) - 1;
  109. var eBias = eMax >> 1;
  110. var nBits = -7;
  111. var i = isLE ? nBytes - 1 : 0;
  112. var d = isLE ? -1 : 1;
  113. var s = buffer[offset + i];
  114. i += d;
  115. e = s & (1 << -nBits) - 1;
  116. s >>= -nBits;
  117. nBits += eLen;
  118. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  119. m = e & (1 << -nBits) - 1;
  120. e >>= -nBits;
  121. nBits += mLen;
  122. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  123. if (e === 0) {
  124. e = 1 - eBias;
  125. } else if (e === eMax) {
  126. return m ? NaN : (s ? -1 : 1) * Infinity;
  127. } else {
  128. m = m + Math.pow(2, mLen);
  129. e = e - eBias;
  130. }
  131. return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
  132. };
  133. var write = function write(buffer, value, offset, isLE, mLen, nBytes) {
  134. var e, m, c;
  135. var eLen = nBytes * 8 - mLen - 1;
  136. var eMax = (1 << eLen) - 1;
  137. var eBias = eMax >> 1;
  138. var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
  139. var i = isLE ? 0 : nBytes - 1;
  140. var d = isLE ? 1 : -1;
  141. var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
  142. value = Math.abs(value);
  143. if (isNaN(value) || value === Infinity) {
  144. m = isNaN(value) ? 1 : 0;
  145. e = eMax;
  146. } else {
  147. e = Math.floor(Math.log(value) / Math.LN2);
  148. if (value * (c = Math.pow(2, -e)) < 1) {
  149. e--;
  150. c *= 2;
  151. }
  152. if (e + eBias >= 1) {
  153. value += rt / c;
  154. } else {
  155. value += rt * Math.pow(2, 1 - eBias);
  156. }
  157. if (value * c >= 2) {
  158. e++;
  159. c /= 2;
  160. }
  161. if (e + eBias >= eMax) {
  162. m = 0;
  163. e = eMax;
  164. } else if (e + eBias >= 1) {
  165. m = (value * c - 1) * Math.pow(2, mLen);
  166. e = e + eBias;
  167. } else {
  168. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  169. e = 0;
  170. }
  171. }
  172. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  173. e = e << mLen | m;
  174. eLen += mLen;
  175. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  176. buffer[offset + i - d] |= s * 128;
  177. };
  178. var ieee754 = {
  179. read: read,
  180. write: write
  181. };
  182. var buffer = createCommonjsModule(function (module, exports) {
  183. var customInspectSymbol = typeof Symbol === 'function' && typeof Symbol['for'] === 'function' ? // eslint-disable-line dot-notation
  184. Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation
  185. : null;
  186. exports.Buffer = Buffer;
  187. exports.SlowBuffer = SlowBuffer;
  188. exports.INSPECT_MAX_BYTES = 50;
  189. var K_MAX_LENGTH = 0x7fffffff;
  190. exports.kMaxLength = K_MAX_LENGTH;
  191. /**
  192. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  193. * === true Use Uint8Array implementation (fastest)
  194. * === false Print warning and recommend using `buffer` v4.x which has an Object
  195. * implementation (most compatible, even IE6)
  196. *
  197. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  198. * Opera 11.6+, iOS 4.2+.
  199. *
  200. * We report that the browser does not support typed arrays if the are not subclassable
  201. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  202. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  203. * for __proto__ and has a buggy typed array implementation.
  204. */
  205. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport();
  206. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && typeof console.error === 'function') {
  207. console.error('This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.');
  208. }
  209. function typedArraySupport() {
  210. // Can typed array instances can be augmented?
  211. try {
  212. var arr = new Uint8Array(1);
  213. var proto = {
  214. foo: function foo() {
  215. return 42;
  216. }
  217. };
  218. Object.setPrototypeOf(proto, Uint8Array.prototype);
  219. Object.setPrototypeOf(arr, proto);
  220. return arr.foo() === 42;
  221. } catch (e) {
  222. return false;
  223. }
  224. }
  225. Object.defineProperty(Buffer.prototype, 'parent', {
  226. enumerable: true,
  227. get: function get() {
  228. if (!Buffer.isBuffer(this)) return undefined;
  229. return this.buffer;
  230. }
  231. });
  232. Object.defineProperty(Buffer.prototype, 'offset', {
  233. enumerable: true,
  234. get: function get() {
  235. if (!Buffer.isBuffer(this)) return undefined;
  236. return this.byteOffset;
  237. }
  238. });
  239. function createBuffer(length) {
  240. if (length > K_MAX_LENGTH) {
  241. throw new RangeError('The value "' + length + '" is invalid for option "size"');
  242. } // Return an augmented `Uint8Array` instance
  243. var buf = new Uint8Array(length);
  244. Object.setPrototypeOf(buf, Buffer.prototype);
  245. return buf;
  246. }
  247. /**
  248. * The Buffer constructor returns instances of `Uint8Array` that have their
  249. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  250. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  251. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  252. * returns a single octet.
  253. *
  254. * The `Uint8Array` prototype remains unmodified.
  255. */
  256. function Buffer(arg, encodingOrOffset, length) {
  257. // Common case.
  258. if (typeof arg === 'number') {
  259. if (typeof encodingOrOffset === 'string') {
  260. throw new TypeError('The "string" argument must be of type string. Received type number');
  261. }
  262. return allocUnsafe(arg);
  263. }
  264. return from(arg, encodingOrOffset, length);
  265. }
  266. Buffer.poolSize = 8192; // not used by this implementation
  267. function from(value, encodingOrOffset, length) {
  268. if (typeof value === 'string') {
  269. return fromString(value, encodingOrOffset);
  270. }
  271. if (ArrayBuffer.isView(value)) {
  272. return fromArrayView(value);
  273. }
  274. if (value == null) {
  275. throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + babelHelpers["typeof"](value));
  276. }
  277. if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) {
  278. return fromArrayBuffer(value, encodingOrOffset, length);
  279. }
  280. if (typeof SharedArrayBuffer !== 'undefined' && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) {
  281. return fromArrayBuffer(value, encodingOrOffset, length);
  282. }
  283. if (typeof value === 'number') {
  284. throw new TypeError('The "value" argument must not be of type number. Received type number');
  285. }
  286. var valueOf = value.valueOf && value.valueOf();
  287. if (valueOf != null && valueOf !== value) {
  288. return Buffer.from(valueOf, encodingOrOffset, length);
  289. }
  290. var b = fromObject(value);
  291. if (b) return b;
  292. if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === 'function') {
  293. return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length);
  294. }
  295. throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + babelHelpers["typeof"](value));
  296. }
  297. /**
  298. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  299. * if value is a number.
  300. * Buffer.from(str[, encoding])
  301. * Buffer.from(array)
  302. * Buffer.from(buffer)
  303. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  304. **/
  305. Buffer.from = function (value, encodingOrOffset, length) {
  306. return from(value, encodingOrOffset, length);
  307. }; // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  308. // https://github.com/feross/buffer/pull/148
  309. Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype);
  310. Object.setPrototypeOf(Buffer, Uint8Array);
  311. function assertSize(size) {
  312. if (typeof size !== 'number') {
  313. throw new TypeError('"size" argument must be of type number');
  314. } else if (size < 0) {
  315. throw new RangeError('The value "' + size + '" is invalid for option "size"');
  316. }
  317. }
  318. function alloc(size, fill, encoding) {
  319. assertSize(size);
  320. if (size <= 0) {
  321. return createBuffer(size);
  322. }
  323. if (fill !== undefined) {
  324. // Only pay attention to encoding if it's a string. This
  325. // prevents accidentally sending in a number that would
  326. // be interpreted as a start offset.
  327. return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
  328. }
  329. return createBuffer(size);
  330. }
  331. /**
  332. * Creates a new filled Buffer instance.
  333. * alloc(size[, fill[, encoding]])
  334. **/
  335. Buffer.alloc = function (size, fill, encoding) {
  336. return alloc(size, fill, encoding);
  337. };
  338. function allocUnsafe(size) {
  339. assertSize(size);
  340. return createBuffer(size < 0 ? 0 : checked(size) | 0);
  341. }
  342. /**
  343. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  344. * */
  345. Buffer.allocUnsafe = function (size) {
  346. return allocUnsafe(size);
  347. };
  348. /**
  349. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  350. */
  351. Buffer.allocUnsafeSlow = function (size) {
  352. return allocUnsafe(size);
  353. };
  354. function fromString(string, encoding) {
  355. if (typeof encoding !== 'string' || encoding === '') {
  356. encoding = 'utf8';
  357. }
  358. if (!Buffer.isEncoding(encoding)) {
  359. throw new TypeError('Unknown encoding: ' + encoding);
  360. }
  361. var length = byteLength(string, encoding) | 0;
  362. var buf = createBuffer(length);
  363. var actual = buf.write(string, encoding);
  364. if (actual !== length) {
  365. // Writing a hex string, for example, that contains invalid characters will
  366. // cause everything after the first invalid character to be ignored. (e.g.
  367. // 'abxxcd' will be treated as 'ab')
  368. buf = buf.slice(0, actual);
  369. }
  370. return buf;
  371. }
  372. function fromArrayLike(array) {
  373. var length = array.length < 0 ? 0 : checked(array.length) | 0;
  374. var buf = createBuffer(length);
  375. for (var i = 0; i < length; i += 1) {
  376. buf[i] = array[i] & 255;
  377. }
  378. return buf;
  379. }
  380. function fromArrayView(arrayView) {
  381. if (isInstance(arrayView, Uint8Array)) {
  382. var copy = new Uint8Array(arrayView);
  383. return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength);
  384. }
  385. return fromArrayLike(arrayView);
  386. }
  387. function fromArrayBuffer(array, byteOffset, length) {
  388. if (byteOffset < 0 || array.byteLength < byteOffset) {
  389. throw new RangeError('"offset" is outside of buffer bounds');
  390. }
  391. if (array.byteLength < byteOffset + (length || 0)) {
  392. throw new RangeError('"length" is outside of buffer bounds');
  393. }
  394. var buf;
  395. if (byteOffset === undefined && length === undefined) {
  396. buf = new Uint8Array(array);
  397. } else if (length === undefined) {
  398. buf = new Uint8Array(array, byteOffset);
  399. } else {
  400. buf = new Uint8Array(array, byteOffset, length);
  401. } // Return an augmented `Uint8Array` instance
  402. Object.setPrototypeOf(buf, Buffer.prototype);
  403. return buf;
  404. }
  405. function fromObject(obj) {
  406. if (Buffer.isBuffer(obj)) {
  407. var len = checked(obj.length) | 0;
  408. var buf = createBuffer(len);
  409. if (buf.length === 0) {
  410. return buf;
  411. }
  412. obj.copy(buf, 0, 0, len);
  413. return buf;
  414. }
  415. if (obj.length !== undefined) {
  416. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  417. return createBuffer(0);
  418. }
  419. return fromArrayLike(obj);
  420. }
  421. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  422. return fromArrayLike(obj.data);
  423. }
  424. }
  425. function checked(length) {
  426. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  427. // length is NaN (which is otherwise coerced to zero.)
  428. if (length >= K_MAX_LENGTH) {
  429. throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes');
  430. }
  431. return length | 0;
  432. }
  433. function SlowBuffer(length) {
  434. if (+length != length) {
  435. // eslint-disable-line eqeqeq
  436. length = 0;
  437. }
  438. return Buffer.alloc(+length);
  439. }
  440. Buffer.isBuffer = function isBuffer(b) {
  441. return b != null && b._isBuffer === true && b !== Buffer.prototype; // so Buffer.isBuffer(Buffer.prototype) will be false
  442. };
  443. Buffer.compare = function compare(a, b) {
  444. if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength);
  445. if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength);
  446. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  447. throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');
  448. }
  449. if (a === b) return 0;
  450. var x = a.length;
  451. var y = b.length;
  452. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  453. if (a[i] !== b[i]) {
  454. x = a[i];
  455. y = b[i];
  456. break;
  457. }
  458. }
  459. if (x < y) return -1;
  460. if (y < x) return 1;
  461. return 0;
  462. };
  463. Buffer.isEncoding = function isEncoding(encoding) {
  464. switch (String(encoding).toLowerCase()) {
  465. case 'hex':
  466. case 'utf8':
  467. case 'utf-8':
  468. case 'ascii':
  469. case 'latin1':
  470. case 'binary':
  471. case 'base64':
  472. case 'ucs2':
  473. case 'ucs-2':
  474. case 'utf16le':
  475. case 'utf-16le':
  476. return true;
  477. default:
  478. return false;
  479. }
  480. };
  481. Buffer.concat = function concat(list, length) {
  482. if (!Array.isArray(list)) {
  483. throw new TypeError('"list" argument must be an Array of Buffers');
  484. }
  485. if (list.length === 0) {
  486. return Buffer.alloc(0);
  487. }
  488. var i;
  489. if (length === undefined) {
  490. length = 0;
  491. for (i = 0; i < list.length; ++i) {
  492. length += list[i].length;
  493. }
  494. }
  495. var buffer = Buffer.allocUnsafe(length);
  496. var pos = 0;
  497. for (i = 0; i < list.length; ++i) {
  498. var buf = list[i];
  499. if (isInstance(buf, Uint8Array)) {
  500. if (pos + buf.length > buffer.length) {
  501. Buffer.from(buf).copy(buffer, pos);
  502. } else {
  503. Uint8Array.prototype.set.call(buffer, buf, pos);
  504. }
  505. } else if (!Buffer.isBuffer(buf)) {
  506. throw new TypeError('"list" argument must be an Array of Buffers');
  507. } else {
  508. buf.copy(buffer, pos);
  509. }
  510. pos += buf.length;
  511. }
  512. return buffer;
  513. };
  514. function byteLength(string, encoding) {
  515. if (Buffer.isBuffer(string)) {
  516. return string.length;
  517. }
  518. if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
  519. return string.byteLength;
  520. }
  521. if (typeof string !== 'string') {
  522. throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + 'Received type ' + babelHelpers["typeof"](string));
  523. }
  524. var len = string.length;
  525. var mustMatch = arguments.length > 2 && arguments[2] === true;
  526. if (!mustMatch && len === 0) return 0; // Use a for loop to avoid recursion
  527. var loweredCase = false;
  528. for (;;) {
  529. switch (encoding) {
  530. case 'ascii':
  531. case 'latin1':
  532. case 'binary':
  533. return len;
  534. case 'utf8':
  535. case 'utf-8':
  536. return utf8ToBytes(string).length;
  537. case 'ucs2':
  538. case 'ucs-2':
  539. case 'utf16le':
  540. case 'utf-16le':
  541. return len * 2;
  542. case 'hex':
  543. return len >>> 1;
  544. case 'base64':
  545. return base64ToBytes(string).length;
  546. default:
  547. if (loweredCase) {
  548. return mustMatch ? -1 : utf8ToBytes(string).length; // assume utf8
  549. }
  550. encoding = ('' + encoding).toLowerCase();
  551. loweredCase = true;
  552. }
  553. }
  554. }
  555. Buffer.byteLength = byteLength;
  556. function slowToString(encoding, start, end) {
  557. var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  558. // property of a typed array.
  559. // This behaves neither like String nor Uint8Array in that we set start/end
  560. // to their upper/lower bounds if the value passed is out of range.
  561. // undefined is handled specially as per ECMA-262 6th Edition,
  562. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  563. if (start === undefined || start < 0) {
  564. start = 0;
  565. } // Return early if start > this.length. Done here to prevent potential uint32
  566. // coercion fail below.
  567. if (start > this.length) {
  568. return '';
  569. }
  570. if (end === undefined || end > this.length) {
  571. end = this.length;
  572. }
  573. if (end <= 0) {
  574. return '';
  575. } // Force coercion to uint32. This will also coerce falsey/NaN values to 0.
  576. end >>>= 0;
  577. start >>>= 0;
  578. if (end <= start) {
  579. return '';
  580. }
  581. if (!encoding) encoding = 'utf8';
  582. while (true) {
  583. switch (encoding) {
  584. case 'hex':
  585. return hexSlice(this, start, end);
  586. case 'utf8':
  587. case 'utf-8':
  588. return utf8Slice(this, start, end);
  589. case 'ascii':
  590. return asciiSlice(this, start, end);
  591. case 'latin1':
  592. case 'binary':
  593. return latin1Slice(this, start, end);
  594. case 'base64':
  595. return base64Slice(this, start, end);
  596. case 'ucs2':
  597. case 'ucs-2':
  598. case 'utf16le':
  599. case 'utf-16le':
  600. return utf16leSlice(this, start, end);
  601. default:
  602. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
  603. encoding = (encoding + '').toLowerCase();
  604. loweredCase = true;
  605. }
  606. }
  607. } // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  608. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  609. // reliably in a browserify context because there could be multiple different
  610. // copies of the 'buffer' package in use. This method works even for Buffer
  611. // instances that were created from another copy of the `buffer` package.
  612. // See: https://github.com/feross/buffer/issues/154
  613. Buffer.prototype._isBuffer = true;
  614. function swap(b, n, m) {
  615. var i = b[n];
  616. b[n] = b[m];
  617. b[m] = i;
  618. }
  619. Buffer.prototype.swap16 = function swap16() {
  620. var len = this.length;
  621. if (len % 2 !== 0) {
  622. throw new RangeError('Buffer size must be a multiple of 16-bits');
  623. }
  624. for (var i = 0; i < len; i += 2) {
  625. swap(this, i, i + 1);
  626. }
  627. return this;
  628. };
  629. Buffer.prototype.swap32 = function swap32() {
  630. var len = this.length;
  631. if (len % 4 !== 0) {
  632. throw new RangeError('Buffer size must be a multiple of 32-bits');
  633. }
  634. for (var i = 0; i < len; i += 4) {
  635. swap(this, i, i + 3);
  636. swap(this, i + 1, i + 2);
  637. }
  638. return this;
  639. };
  640. Buffer.prototype.swap64 = function swap64() {
  641. var len = this.length;
  642. if (len % 8 !== 0) {
  643. throw new RangeError('Buffer size must be a multiple of 64-bits');
  644. }
  645. for (var i = 0; i < len; i += 8) {
  646. swap(this, i, i + 7);
  647. swap(this, i + 1, i + 6);
  648. swap(this, i + 2, i + 5);
  649. swap(this, i + 3, i + 4);
  650. }
  651. return this;
  652. };
  653. Buffer.prototype.toString = function toString() {
  654. var length = this.length;
  655. if (length === 0) return '';
  656. if (arguments.length === 0) return utf8Slice(this, 0, length);
  657. return slowToString.apply(this, arguments);
  658. };
  659. Buffer.prototype.toLocaleString = Buffer.prototype.toString;
  660. Buffer.prototype.equals = function equals(b) {
  661. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer');
  662. if (this === b) return true;
  663. return Buffer.compare(this, b) === 0;
  664. };
  665. Buffer.prototype.inspect = function inspect() {
  666. var str = '';
  667. var max = exports.INSPECT_MAX_BYTES;
  668. str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim();
  669. if (this.length > max) str += ' ... ';
  670. return '<Buffer ' + str + '>';
  671. };
  672. if (customInspectSymbol) {
  673. Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect;
  674. }
  675. Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
  676. if (isInstance(target, Uint8Array)) {
  677. target = Buffer.from(target, target.offset, target.byteLength);
  678. }
  679. if (!Buffer.isBuffer(target)) {
  680. throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. ' + 'Received type ' + babelHelpers["typeof"](target));
  681. }
  682. if (start === undefined) {
  683. start = 0;
  684. }
  685. if (end === undefined) {
  686. end = target ? target.length : 0;
  687. }
  688. if (thisStart === undefined) {
  689. thisStart = 0;
  690. }
  691. if (thisEnd === undefined) {
  692. thisEnd = this.length;
  693. }
  694. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  695. throw new RangeError('out of range index');
  696. }
  697. if (thisStart >= thisEnd && start >= end) {
  698. return 0;
  699. }
  700. if (thisStart >= thisEnd) {
  701. return -1;
  702. }
  703. if (start >= end) {
  704. return 1;
  705. }
  706. start >>>= 0;
  707. end >>>= 0;
  708. thisStart >>>= 0;
  709. thisEnd >>>= 0;
  710. if (this === target) return 0;
  711. var x = thisEnd - thisStart;
  712. var y = end - start;
  713. var len = Math.min(x, y);
  714. var thisCopy = this.slice(thisStart, thisEnd);
  715. var targetCopy = target.slice(start, end);
  716. for (var i = 0; i < len; ++i) {
  717. if (thisCopy[i] !== targetCopy[i]) {
  718. x = thisCopy[i];
  719. y = targetCopy[i];
  720. break;
  721. }
  722. }
  723. if (x < y) return -1;
  724. if (y < x) return 1;
  725. return 0;
  726. }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  727. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  728. //
  729. // Arguments:
  730. // - buffer - a Buffer to search
  731. // - val - a string, Buffer, or number
  732. // - byteOffset - an index into `buffer`; will be clamped to an int32
  733. // - encoding - an optional encoding, relevant is val is a string
  734. // - dir - true for indexOf, false for lastIndexOf
  735. function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
  736. // Empty buffer means no match
  737. if (buffer.length === 0) return -1; // Normalize byteOffset
  738. if (typeof byteOffset === 'string') {
  739. encoding = byteOffset;
  740. byteOffset = 0;
  741. } else if (byteOffset > 0x7fffffff) {
  742. byteOffset = 0x7fffffff;
  743. } else if (byteOffset < -0x80000000) {
  744. byteOffset = -0x80000000;
  745. }
  746. byteOffset = +byteOffset; // Coerce to Number.
  747. if (numberIsNaN(byteOffset)) {
  748. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  749. byteOffset = dir ? 0 : buffer.length - 1;
  750. } // Normalize byteOffset: negative offsets start from the end of the buffer
  751. if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
  752. if (byteOffset >= buffer.length) {
  753. if (dir) return -1;else byteOffset = buffer.length - 1;
  754. } else if (byteOffset < 0) {
  755. if (dir) byteOffset = 0;else return -1;
  756. } // Normalize val
  757. if (typeof val === 'string') {
  758. val = Buffer.from(val, encoding);
  759. } // Finally, search either indexOf (if dir is true) or lastIndexOf
  760. if (Buffer.isBuffer(val)) {
  761. // Special case: looking for empty string/buffer always fails
  762. if (val.length === 0) {
  763. return -1;
  764. }
  765. return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
  766. } else if (typeof val === 'number') {
  767. val = val & 0xFF; // Search for a byte value [0-255]
  768. if (typeof Uint8Array.prototype.indexOf === 'function') {
  769. if (dir) {
  770. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
  771. } else {
  772. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
  773. }
  774. }
  775. return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
  776. }
  777. throw new TypeError('val must be string, number or Buffer');
  778. }
  779. function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
  780. var indexSize = 1;
  781. var arrLength = arr.length;
  782. var valLength = val.length;
  783. if (encoding !== undefined) {
  784. encoding = String(encoding).toLowerCase();
  785. if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') {
  786. if (arr.length < 2 || val.length < 2) {
  787. return -1;
  788. }
  789. indexSize = 2;
  790. arrLength /= 2;
  791. valLength /= 2;
  792. byteOffset /= 2;
  793. }
  794. }
  795. function read(buf, i) {
  796. if (indexSize === 1) {
  797. return buf[i];
  798. } else {
  799. return buf.readUInt16BE(i * indexSize);
  800. }
  801. }
  802. var i;
  803. if (dir) {
  804. var foundIndex = -1;
  805. for (i = byteOffset; i < arrLength; i++) {
  806. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  807. if (foundIndex === -1) foundIndex = i;
  808. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
  809. } else {
  810. if (foundIndex !== -1) i -= i - foundIndex;
  811. foundIndex = -1;
  812. }
  813. }
  814. } else {
  815. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
  816. for (i = byteOffset; i >= 0; i--) {
  817. var found = true;
  818. for (var j = 0; j < valLength; j++) {
  819. if (read(arr, i + j) !== read(val, j)) {
  820. found = false;
  821. break;
  822. }
  823. }
  824. if (found) return i;
  825. }
  826. }
  827. return -1;
  828. }
  829. Buffer.prototype.includes = function includes(val, byteOffset, encoding) {
  830. return this.indexOf(val, byteOffset, encoding) !== -1;
  831. };
  832. Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
  833. return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
  834. };
  835. Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
  836. return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
  837. };
  838. function hexWrite(buf, string, offset, length) {
  839. offset = Number(offset) || 0;
  840. var remaining = buf.length - offset;
  841. if (!length) {
  842. length = remaining;
  843. } else {
  844. length = Number(length);
  845. if (length > remaining) {
  846. length = remaining;
  847. }
  848. }
  849. var strLen = string.length;
  850. if (length > strLen / 2) {
  851. length = strLen / 2;
  852. }
  853. for (var i = 0; i < length; ++i) {
  854. var parsed = parseInt(string.substr(i * 2, 2), 16);
  855. if (numberIsNaN(parsed)) return i;
  856. buf[offset + i] = parsed;
  857. }
  858. return i;
  859. }
  860. function utf8Write(buf, string, offset, length) {
  861. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
  862. }
  863. function asciiWrite(buf, string, offset, length) {
  864. return blitBuffer(asciiToBytes(string), buf, offset, length);
  865. }
  866. function base64Write(buf, string, offset, length) {
  867. return blitBuffer(base64ToBytes(string), buf, offset, length);
  868. }
  869. function ucs2Write(buf, string, offset, length) {
  870. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
  871. }
  872. Buffer.prototype.write = function write(string, offset, length, encoding) {
  873. // Buffer#write(string)
  874. if (offset === undefined) {
  875. encoding = 'utf8';
  876. length = this.length;
  877. offset = 0; // Buffer#write(string, encoding)
  878. } else if (length === undefined && typeof offset === 'string') {
  879. encoding = offset;
  880. length = this.length;
  881. offset = 0; // Buffer#write(string, offset[, length][, encoding])
  882. } else if (isFinite(offset)) {
  883. offset = offset >>> 0;
  884. if (isFinite(length)) {
  885. length = length >>> 0;
  886. if (encoding === undefined) encoding = 'utf8';
  887. } else {
  888. encoding = length;
  889. length = undefined;
  890. }
  891. } else {
  892. throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported');
  893. }
  894. var remaining = this.length - offset;
  895. if (length === undefined || length > remaining) length = remaining;
  896. if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
  897. throw new RangeError('Attempt to write outside buffer bounds');
  898. }
  899. if (!encoding) encoding = 'utf8';
  900. var loweredCase = false;
  901. for (;;) {
  902. switch (encoding) {
  903. case 'hex':
  904. return hexWrite(this, string, offset, length);
  905. case 'utf8':
  906. case 'utf-8':
  907. return utf8Write(this, string, offset, length);
  908. case 'ascii':
  909. case 'latin1':
  910. case 'binary':
  911. return asciiWrite(this, string, offset, length);
  912. case 'base64':
  913. // Warning: maxLength not taken into account in base64Write
  914. return base64Write(this, string, offset, length);
  915. case 'ucs2':
  916. case 'ucs-2':
  917. case 'utf16le':
  918. case 'utf-16le':
  919. return ucs2Write(this, string, offset, length);
  920. default:
  921. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
  922. encoding = ('' + encoding).toLowerCase();
  923. loweredCase = true;
  924. }
  925. }
  926. };
  927. Buffer.prototype.toJSON = function toJSON() {
  928. return {
  929. type: 'Buffer',
  930. data: Array.prototype.slice.call(this._arr || this, 0)
  931. };
  932. };
  933. function base64Slice(buf, start, end) {
  934. if (start === 0 && end === buf.length) {
  935. return base64Js.fromByteArray(buf);
  936. } else {
  937. return base64Js.fromByteArray(buf.slice(start, end));
  938. }
  939. }
  940. function utf8Slice(buf, start, end) {
  941. end = Math.min(buf.length, end);
  942. var res = [];
  943. var i = start;
  944. while (i < end) {
  945. var firstByte = buf[i];
  946. var codePoint = null;
  947. var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1;
  948. if (i + bytesPerSequence <= end) {
  949. var secondByte, thirdByte, fourthByte, tempCodePoint;
  950. switch (bytesPerSequence) {
  951. case 1:
  952. if (firstByte < 0x80) {
  953. codePoint = firstByte;
  954. }
  955. break;
  956. case 2:
  957. secondByte = buf[i + 1];
  958. if ((secondByte & 0xC0) === 0x80) {
  959. tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F;
  960. if (tempCodePoint > 0x7F) {
  961. codePoint = tempCodePoint;
  962. }
  963. }
  964. break;
  965. case 3:
  966. secondByte = buf[i + 1];
  967. thirdByte = buf[i + 2];
  968. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  969. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F;
  970. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  971. codePoint = tempCodePoint;
  972. }
  973. }
  974. break;
  975. case 4:
  976. secondByte = buf[i + 1];
  977. thirdByte = buf[i + 2];
  978. fourthByte = buf[i + 3];
  979. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  980. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F;
  981. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  982. codePoint = tempCodePoint;
  983. }
  984. }
  985. }
  986. }
  987. if (codePoint === null) {
  988. // we did not generate a valid codePoint so insert a
  989. // replacement char (U+FFFD) and advance only 1 byte
  990. codePoint = 0xFFFD;
  991. bytesPerSequence = 1;
  992. } else if (codePoint > 0xFFFF) {
  993. // encode to utf16 (surrogate pair dance)
  994. codePoint -= 0x10000;
  995. res.push(codePoint >>> 10 & 0x3FF | 0xD800);
  996. codePoint = 0xDC00 | codePoint & 0x3FF;
  997. }
  998. res.push(codePoint);
  999. i += bytesPerSequence;
  1000. }
  1001. return decodeCodePointsArray(res);
  1002. } // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  1003. // the lowest limit is Chrome, with 0x10000 args.
  1004. // We go 1 magnitude less, for safety
  1005. var MAX_ARGUMENTS_LENGTH = 0x1000;
  1006. function decodeCodePointsArray(codePoints) {
  1007. var len = codePoints.length;
  1008. if (len <= MAX_ARGUMENTS_LENGTH) {
  1009. return String.fromCharCode.apply(String, codePoints); // avoid extra slice()
  1010. } // Decode in chunks to avoid "call stack size exceeded".
  1011. var res = '';
  1012. var i = 0;
  1013. while (i < len) {
  1014. res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));
  1015. }
  1016. return res;
  1017. }
  1018. function asciiSlice(buf, start, end) {
  1019. var ret = '';
  1020. end = Math.min(buf.length, end);
  1021. for (var i = start; i < end; ++i) {
  1022. ret += String.fromCharCode(buf[i] & 0x7F);
  1023. }
  1024. return ret;
  1025. }
  1026. function latin1Slice(buf, start, end) {
  1027. var ret = '';
  1028. end = Math.min(buf.length, end);
  1029. for (var i = start; i < end; ++i) {
  1030. ret += String.fromCharCode(buf[i]);
  1031. }
  1032. return ret;
  1033. }
  1034. function hexSlice(buf, start, end) {
  1035. var len = buf.length;
  1036. if (!start || start < 0) start = 0;
  1037. if (!end || end < 0 || end > len) end = len;
  1038. var out = '';
  1039. for (var i = start; i < end; ++i) {
  1040. out += hexSliceLookupTable[buf[i]];
  1041. }
  1042. return out;
  1043. }
  1044. function utf16leSlice(buf, start, end) {
  1045. var bytes = buf.slice(start, end);
  1046. var res = ''; // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)
  1047. for (var i = 0; i < bytes.length - 1; i += 2) {
  1048. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
  1049. }
  1050. return res;
  1051. }
  1052. Buffer.prototype.slice = function slice(start, end) {
  1053. var len = this.length;
  1054. start = ~~start;
  1055. end = end === undefined ? len : ~~end;
  1056. if (start < 0) {
  1057. start += len;
  1058. if (start < 0) start = 0;
  1059. } else if (start > len) {
  1060. start = len;
  1061. }
  1062. if (end < 0) {
  1063. end += len;
  1064. if (end < 0) end = 0;
  1065. } else if (end > len) {
  1066. end = len;
  1067. }
  1068. if (end < start) end = start;
  1069. var newBuf = this.subarray(start, end); // Return an augmented `Uint8Array` instance
  1070. Object.setPrototypeOf(newBuf, Buffer.prototype);
  1071. return newBuf;
  1072. };
  1073. /*
  1074. * Need to make sure that buffer isn't trying to write out of bounds.
  1075. */
  1076. function checkOffset(offset, ext, length) {
  1077. if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint');
  1078. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length');
  1079. }
  1080. Buffer.prototype.readUintLE = Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) {
  1081. offset = offset >>> 0;
  1082. byteLength = byteLength >>> 0;
  1083. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1084. var val = this[offset];
  1085. var mul = 1;
  1086. var i = 0;
  1087. while (++i < byteLength && (mul *= 0x100)) {
  1088. val += this[offset + i] * mul;
  1089. }
  1090. return val;
  1091. };
  1092. Buffer.prototype.readUintBE = Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) {
  1093. offset = offset >>> 0;
  1094. byteLength = byteLength >>> 0;
  1095. if (!noAssert) {
  1096. checkOffset(offset, byteLength, this.length);
  1097. }
  1098. var val = this[offset + --byteLength];
  1099. var mul = 1;
  1100. while (byteLength > 0 && (mul *= 0x100)) {
  1101. val += this[offset + --byteLength] * mul;
  1102. }
  1103. return val;
  1104. };
  1105. Buffer.prototype.readUint8 = Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) {
  1106. offset = offset >>> 0;
  1107. if (!noAssert) checkOffset(offset, 1, this.length);
  1108. return this[offset];
  1109. };
  1110. Buffer.prototype.readUint16LE = Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
  1111. offset = offset >>> 0;
  1112. if (!noAssert) checkOffset(offset, 2, this.length);
  1113. return this[offset] | this[offset + 1] << 8;
  1114. };
  1115. Buffer.prototype.readUint16BE = Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
  1116. offset = offset >>> 0;
  1117. if (!noAssert) checkOffset(offset, 2, this.length);
  1118. return this[offset] << 8 | this[offset + 1];
  1119. };
  1120. Buffer.prototype.readUint32LE = Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
  1121. offset = offset >>> 0;
  1122. if (!noAssert) checkOffset(offset, 4, this.length);
  1123. return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000;
  1124. };
  1125. Buffer.prototype.readUint32BE = Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
  1126. offset = offset >>> 0;
  1127. if (!noAssert) checkOffset(offset, 4, this.length);
  1128. return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
  1129. };
  1130. Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) {
  1131. offset = offset >>> 0;
  1132. byteLength = byteLength >>> 0;
  1133. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1134. var val = this[offset];
  1135. var mul = 1;
  1136. var i = 0;
  1137. while (++i < byteLength && (mul *= 0x100)) {
  1138. val += this[offset + i] * mul;
  1139. }
  1140. mul *= 0x80;
  1141. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  1142. return val;
  1143. };
  1144. Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) {
  1145. offset = offset >>> 0;
  1146. byteLength = byteLength >>> 0;
  1147. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1148. var i = byteLength;
  1149. var mul = 1;
  1150. var val = this[offset + --i];
  1151. while (i > 0 && (mul *= 0x100)) {
  1152. val += this[offset + --i] * mul;
  1153. }
  1154. mul *= 0x80;
  1155. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  1156. return val;
  1157. };
  1158. Buffer.prototype.readInt8 = function readInt8(offset, noAssert) {
  1159. offset = offset >>> 0;
  1160. if (!noAssert) checkOffset(offset, 1, this.length);
  1161. if (!(this[offset] & 0x80)) return this[offset];
  1162. return (0xff - this[offset] + 1) * -1;
  1163. };
  1164. Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
  1165. offset = offset >>> 0;
  1166. if (!noAssert) checkOffset(offset, 2, this.length);
  1167. var val = this[offset] | this[offset + 1] << 8;
  1168. return val & 0x8000 ? val | 0xFFFF0000 : val;
  1169. };
  1170. Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
  1171. offset = offset >>> 0;
  1172. if (!noAssert) checkOffset(offset, 2, this.length);
  1173. var val = this[offset + 1] | this[offset] << 8;
  1174. return val & 0x8000 ? val | 0xFFFF0000 : val;
  1175. };
  1176. Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
  1177. offset = offset >>> 0;
  1178. if (!noAssert) checkOffset(offset, 4, this.length);
  1179. return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
  1180. };
  1181. Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
  1182. offset = offset >>> 0;
  1183. if (!noAssert) checkOffset(offset, 4, this.length);
  1184. return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
  1185. };
  1186. Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
  1187. offset = offset >>> 0;
  1188. if (!noAssert) checkOffset(offset, 4, this.length);
  1189. return ieee754.read(this, offset, true, 23, 4);
  1190. };
  1191. Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
  1192. offset = offset >>> 0;
  1193. if (!noAssert) checkOffset(offset, 4, this.length);
  1194. return ieee754.read(this, offset, false, 23, 4);
  1195. };
  1196. Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
  1197. offset = offset >>> 0;
  1198. if (!noAssert) checkOffset(offset, 8, this.length);
  1199. return ieee754.read(this, offset, true, 52, 8);
  1200. };
  1201. Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
  1202. offset = offset >>> 0;
  1203. if (!noAssert) checkOffset(offset, 8, this.length);
  1204. return ieee754.read(this, offset, false, 52, 8);
  1205. };
  1206. function checkInt(buf, value, offset, ext, max, min) {
  1207. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
  1208. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds');
  1209. if (offset + ext > buf.length) throw new RangeError('Index out of range');
  1210. }
  1211. Buffer.prototype.writeUintLE = Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) {
  1212. value = +value;
  1213. offset = offset >>> 0;
  1214. byteLength = byteLength >>> 0;
  1215. if (!noAssert) {
  1216. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  1217. checkInt(this, value, offset, byteLength, maxBytes, 0);
  1218. }
  1219. var mul = 1;
  1220. var i = 0;
  1221. this[offset] = value & 0xFF;
  1222. while (++i < byteLength && (mul *= 0x100)) {
  1223. this[offset + i] = value / mul & 0xFF;
  1224. }
  1225. return offset + byteLength;
  1226. };
  1227. Buffer.prototype.writeUintBE = Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) {
  1228. value = +value;
  1229. offset = offset >>> 0;
  1230. byteLength = byteLength >>> 0;
  1231. if (!noAssert) {
  1232. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  1233. checkInt(this, value, offset, byteLength, maxBytes, 0);
  1234. }
  1235. var i = byteLength - 1;
  1236. var mul = 1;
  1237. this[offset + i] = value & 0xFF;
  1238. while (--i >= 0 && (mul *= 0x100)) {
  1239. this[offset + i] = value / mul & 0xFF;
  1240. }
  1241. return offset + byteLength;
  1242. };
  1243. Buffer.prototype.writeUint8 = Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
  1244. value = +value;
  1245. offset = offset >>> 0;
  1246. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
  1247. this[offset] = value & 0xff;
  1248. return offset + 1;
  1249. };
  1250. Buffer.prototype.writeUint16LE = Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
  1251. value = +value;
  1252. offset = offset >>> 0;
  1253. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  1254. this[offset] = value & 0xff;
  1255. this[offset + 1] = value >>> 8;
  1256. return offset + 2;
  1257. };
  1258. Buffer.prototype.writeUint16BE = Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
  1259. value = +value;
  1260. offset = offset >>> 0;
  1261. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  1262. this[offset] = value >>> 8;
  1263. this[offset + 1] = value & 0xff;
  1264. return offset + 2;
  1265. };
  1266. Buffer.prototype.writeUint32LE = Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
  1267. value = +value;
  1268. offset = offset >>> 0;
  1269. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  1270. this[offset + 3] = value >>> 24;
  1271. this[offset + 2] = value >>> 16;
  1272. this[offset + 1] = value >>> 8;
  1273. this[offset] = value & 0xff;
  1274. return offset + 4;
  1275. };
  1276. Buffer.prototype.writeUint32BE = Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
  1277. value = +value;
  1278. offset = offset >>> 0;
  1279. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  1280. this[offset] = value >>> 24;
  1281. this[offset + 1] = value >>> 16;
  1282. this[offset + 2] = value >>> 8;
  1283. this[offset + 3] = value & 0xff;
  1284. return offset + 4;
  1285. };
  1286. Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) {
  1287. value = +value;
  1288. offset = offset >>> 0;
  1289. if (!noAssert) {
  1290. var limit = Math.pow(2, 8 * byteLength - 1);
  1291. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  1292. }
  1293. var i = 0;
  1294. var mul = 1;
  1295. var sub = 0;
  1296. this[offset] = value & 0xFF;
  1297. while (++i < byteLength && (mul *= 0x100)) {
  1298. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1299. sub = 1;
  1300. }
  1301. this[offset + i] = (value / mul >> 0) - sub & 0xFF;
  1302. }
  1303. return offset + byteLength;
  1304. };
  1305. Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) {
  1306. value = +value;
  1307. offset = offset >>> 0;
  1308. if (!noAssert) {
  1309. var limit = Math.pow(2, 8 * byteLength - 1);
  1310. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  1311. }
  1312. var i = byteLength - 1;
  1313. var mul = 1;
  1314. var sub = 0;
  1315. this[offset + i] = value & 0xFF;
  1316. while (--i >= 0 && (mul *= 0x100)) {
  1317. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1318. sub = 1;
  1319. }
  1320. this[offset + i] = (value / mul >> 0) - sub & 0xFF;
  1321. }
  1322. return offset + byteLength;
  1323. };
  1324. Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
  1325. value = +value;
  1326. offset = offset >>> 0;
  1327. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
  1328. if (value < 0) value = 0xff + value + 1;
  1329. this[offset] = value & 0xff;
  1330. return offset + 1;
  1331. };
  1332. Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
  1333. value = +value;
  1334. offset = offset >>> 0;
  1335. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  1336. this[offset] = value & 0xff;
  1337. this[offset + 1] = value >>> 8;
  1338. return offset + 2;
  1339. };
  1340. Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
  1341. value = +value;
  1342. offset = offset >>> 0;
  1343. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  1344. this[offset] = value >>> 8;
  1345. this[offset + 1] = value & 0xff;
  1346. return offset + 2;
  1347. };
  1348. Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
  1349. value = +value;
  1350. offset = offset >>> 0;
  1351. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  1352. this[offset] = value & 0xff;
  1353. this[offset + 1] = value >>> 8;
  1354. this[offset + 2] = value >>> 16;
  1355. this[offset + 3] = value >>> 24;
  1356. return offset + 4;
  1357. };
  1358. Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
  1359. value = +value;
  1360. offset = offset >>> 0;
  1361. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  1362. if (value < 0) value = 0xffffffff + value + 1;
  1363. this[offset] = value >>> 24;
  1364. this[offset + 1] = value >>> 16;
  1365. this[offset + 2] = value >>> 8;
  1366. this[offset + 3] = value & 0xff;
  1367. return offset + 4;
  1368. };
  1369. function checkIEEE754(buf, value, offset, ext, max, min) {
  1370. if (offset + ext > buf.length) throw new RangeError('Index out of range');
  1371. if (offset < 0) throw new RangeError('Index out of range');
  1372. }
  1373. function writeFloat(buf, value, offset, littleEndian, noAssert) {
  1374. value = +value;
  1375. offset = offset >>> 0;
  1376. if (!noAssert) {
  1377. checkIEEE754(buf, value, offset, 4);
  1378. }
  1379. ieee754.write(buf, value, offset, littleEndian, 23, 4);
  1380. return offset + 4;
  1381. }
  1382. Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
  1383. return writeFloat(this, value, offset, true, noAssert);
  1384. };
  1385. Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
  1386. return writeFloat(this, value, offset, false, noAssert);
  1387. };
  1388. function writeDouble(buf, value, offset, littleEndian, noAssert) {
  1389. value = +value;
  1390. offset = offset >>> 0;
  1391. if (!noAssert) {
  1392. checkIEEE754(buf, value, offset, 8);
  1393. }
  1394. ieee754.write(buf, value, offset, littleEndian, 52, 8);
  1395. return offset + 8;
  1396. }
  1397. Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
  1398. return writeDouble(this, value, offset, true, noAssert);
  1399. };
  1400. Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
  1401. return writeDouble(this, value, offset, false, noAssert);
  1402. }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  1403. Buffer.prototype.copy = function copy(target, targetStart, start, end) {
  1404. if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer');
  1405. if (!start) start = 0;
  1406. if (!end && end !== 0) end = this.length;
  1407. if (targetStart >= target.length) targetStart = target.length;
  1408. if (!targetStart) targetStart = 0;
  1409. if (end > 0 && end < start) end = start; // Copy 0 bytes; we're done
  1410. if (end === start) return 0;
  1411. if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions
  1412. if (targetStart < 0) {
  1413. throw new RangeError('targetStart out of bounds');
  1414. }
  1415. if (start < 0 || start >= this.length) throw new RangeError('Index out of range');
  1416. if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob?
  1417. if (end > this.length) end = this.length;
  1418. if (target.length - targetStart < end - start) {
  1419. end = target.length - targetStart + start;
  1420. }
  1421. var len = end - start;
  1422. if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
  1423. // Use built-in when available, missing from IE11
  1424. this.copyWithin(targetStart, start, end);
  1425. } else {
  1426. Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart);
  1427. }
  1428. return len;
  1429. }; // Usage:
  1430. // buffer.fill(number[, offset[, end]])
  1431. // buffer.fill(buffer[, offset[, end]])
  1432. // buffer.fill(string[, offset[, end]][, encoding])
  1433. Buffer.prototype.fill = function fill(val, start, end, encoding) {
  1434. // Handle string cases:
  1435. if (typeof val === 'string') {
  1436. if (typeof start === 'string') {
  1437. encoding = start;
  1438. start = 0;
  1439. end = this.length;
  1440. } else if (typeof end === 'string') {
  1441. encoding = end;
  1442. end = this.length;
  1443. }
  1444. if (encoding !== undefined && typeof encoding !== 'string') {
  1445. throw new TypeError('encoding must be a string');
  1446. }
  1447. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  1448. throw new TypeError('Unknown encoding: ' + encoding);
  1449. }
  1450. if (val.length === 1) {
  1451. var code = val.charCodeAt(0);
  1452. if (encoding === 'utf8' && code < 128 || encoding === 'latin1') {
  1453. // Fast path: If `val` fits into a single byte, use that numeric value.
  1454. val = code;
  1455. }
  1456. }
  1457. } else if (typeof val === 'number') {
  1458. val = val & 255;
  1459. } else if (typeof val === 'boolean') {
  1460. val = Number(val);
  1461. } // Invalid ranges are not set to a default, so can range check early.
  1462. if (start < 0 || this.length < start || this.length < end) {
  1463. throw new RangeError('Out of range index');
  1464. }
  1465. if (end <= start) {
  1466. return this;
  1467. }
  1468. start = start >>> 0;
  1469. end = end === undefined ? this.length : end >>> 0;
  1470. if (!val) val = 0;
  1471. var i;
  1472. if (typeof val === 'number') {
  1473. for (i = start; i < end; ++i) {
  1474. this[i] = val;
  1475. }
  1476. } else {
  1477. var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding);
  1478. var len = bytes.length;
  1479. if (len === 0) {
  1480. throw new TypeError('The value "' + val + '" is invalid for argument "value"');
  1481. }
  1482. for (i = 0; i < end - start; ++i) {
  1483. this[i + start] = bytes[i % len];
  1484. }
  1485. }
  1486. return this;
  1487. }; // HELPER FUNCTIONS
  1488. // ================
  1489. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
  1490. function base64clean(str) {
  1491. // Node takes equal signs as end of the Base64 encoding
  1492. str = str.split('=')[0]; // Node strips out invalid characters like \n and \t from the string, base64-js does not
  1493. str = str.trim().replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to ''
  1494. if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  1495. while (str.length % 4 !== 0) {
  1496. str = str + '=';
  1497. }
  1498. return str;
  1499. }
  1500. function utf8ToBytes(string, units) {
  1501. units = units || Infinity;
  1502. var codePoint;
  1503. var length = string.length;
  1504. var leadSurrogate = null;
  1505. var bytes = [];
  1506. for (var i = 0; i < length; ++i) {
  1507. codePoint = string.charCodeAt(i); // is surrogate component
  1508. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  1509. // last char was a lead
  1510. if (!leadSurrogate) {
  1511. // no lead yet
  1512. if (codePoint > 0xDBFF) {
  1513. // unexpected trail
  1514. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  1515. continue;
  1516. } else if (i + 1 === length) {
  1517. // unpaired lead
  1518. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  1519. continue;
  1520. } // valid lead
  1521. leadSurrogate = codePoint;
  1522. continue;
  1523. } // 2 leads in a row
  1524. if (codePoint < 0xDC00) {
  1525. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  1526. leadSurrogate = codePoint;
  1527. continue;
  1528. } // valid surrogate pair
  1529. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
  1530. } else if (leadSurrogate) {
  1531. // valid bmp char, but last char was a lead
  1532. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  1533. }
  1534. leadSurrogate = null; // encode utf8
  1535. if (codePoint < 0x80) {
  1536. if ((units -= 1) < 0) break;
  1537. bytes.push(codePoint);
  1538. } else if (codePoint < 0x800) {
  1539. if ((units -= 2) < 0) break;
  1540. bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80);
  1541. } else if (codePoint < 0x10000) {
  1542. if ((units -= 3) < 0) break;
  1543. bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
  1544. } else if (codePoint < 0x110000) {
  1545. if ((units -= 4) < 0) break;
  1546. bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
  1547. } else {
  1548. throw new Error('Invalid code point');
  1549. }
  1550. }
  1551. return bytes;
  1552. }
  1553. function asciiToBytes(str) {
  1554. var byteArray = [];
  1555. for (var i = 0; i < str.length; ++i) {
  1556. // Node's code seems to be doing this and not & 0x7F..
  1557. byteArray.push(str.charCodeAt(i) & 0xFF);
  1558. }
  1559. return byteArray;
  1560. }
  1561. function utf16leToBytes(str, units) {
  1562. var c, hi, lo;
  1563. var byteArray = [];
  1564. for (var i = 0; i < str.length; ++i) {
  1565. if ((units -= 2) < 0) break;
  1566. c = str.charCodeAt(i);
  1567. hi = c >> 8;
  1568. lo = c % 256;
  1569. byteArray.push(lo);
  1570. byteArray.push(hi);
  1571. }
  1572. return byteArray;
  1573. }
  1574. function base64ToBytes(str) {
  1575. return base64Js.toByteArray(base64clean(str));
  1576. }
  1577. function blitBuffer(src, dst, offset, length) {
  1578. for (var i = 0; i < length; ++i) {
  1579. if (i + offset >= dst.length || i >= src.length) break;
  1580. dst[i + offset] = src[i];
  1581. }
  1582. return i;
  1583. } // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
  1584. // the `instanceof` check but they should be treated as of that type.
  1585. // See: https://github.com/feross/buffer/issues/166
  1586. function isInstance(obj, type) {
  1587. return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name;
  1588. }
  1589. function numberIsNaN(obj) {
  1590. // For IE11 support
  1591. return obj !== obj; // eslint-disable-line no-self-compare
  1592. } // Create lookup table for `toString('hex')`
  1593. // See: https://github.com/feross/buffer/issues/219
  1594. var hexSliceLookupTable = function () {
  1595. var alphabet = '0123456789abcdef';
  1596. var table = new Array(256);
  1597. for (var i = 0; i < 16; ++i) {
  1598. var i16 = i * 16;
  1599. for (var j = 0; j < 16; ++j) {
  1600. table[i16 + j] = alphabet[i] + alphabet[j];
  1601. }
  1602. }
  1603. return table;
  1604. }();
  1605. });
  1606. buffer.Buffer;
  1607. buffer.SlowBuffer;
  1608. buffer.INSPECT_MAX_BYTES;
  1609. buffer.kMaxLength;
  1610. var require$$0 = {};
  1611. // shim for using process in browser
  1612. var performance = global.performance || {};
  1613. performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function () {
  1614. return new Date().getTime();
  1615. }; // generate timestamp or delta
  1616. var inherits;
  1617. if (typeof Object.create === 'function') {
  1618. inherits = function inherits(ctor, superCtor) {
  1619. // implementation from standard node.js 'util' module
  1620. ctor.super_ = superCtor;
  1621. ctor.prototype = Object.create(superCtor.prototype, {
  1622. constructor: {
  1623. value: ctor,
  1624. enumerable: false,
  1625. writable: true,
  1626. configurable: true
  1627. }
  1628. });
  1629. };
  1630. } else {
  1631. inherits = function inherits(ctor, superCtor) {
  1632. ctor.super_ = superCtor;
  1633. var TempCtor = function TempCtor() {};
  1634. TempCtor.prototype = superCtor.prototype;
  1635. ctor.prototype = new TempCtor();
  1636. ctor.prototype.constructor = ctor;
  1637. };
  1638. }
  1639. var inherits$1 = inherits;
  1640. // Copyright Joyent, Inc. and other Node contributors.
  1641. var formatRegExp = /%[sdj%]/g;
  1642. function format(f) {
  1643. if (!isString(f)) {
  1644. var objects = [];
  1645. for (var i = 0; i < arguments.length; i++) {
  1646. objects.push(inspect(arguments[i]));
  1647. }
  1648. return objects.join(' ');
  1649. }
  1650. var i = 1;
  1651. var args = arguments;
  1652. var len = args.length;
  1653. var str = String(f).replace(formatRegExp, function (x) {
  1654. if (x === '%%') return '%';
  1655. if (i >= len) return x;
  1656. switch (x) {
  1657. case '%s':
  1658. return String(args[i++]);
  1659. case '%d':
  1660. return Number(args[i++]);
  1661. case '%j':
  1662. try {
  1663. return JSON.stringify(args[i++]);
  1664. } catch (_) {
  1665. return '[Circular]';
  1666. }
  1667. default:
  1668. return x;
  1669. }
  1670. });
  1671. for (var x = args[i]; i < len; x = args[++i]) {
  1672. if (isNull(x) || !isObject(x)) {
  1673. str += ' ' + x;
  1674. } else {
  1675. str += ' ' + inspect(x);
  1676. }
  1677. }
  1678. return str;
  1679. }
  1680. // Returns a modified function which warns once by default.
  1681. // If --no-deprecation is set, then it is a no-op.
  1682. function deprecate(fn, msg) {
  1683. // Allow for deprecating things in the process of starting up.
  1684. if (isUndefined(global.process)) {
  1685. return function () {
  1686. return deprecate(fn, msg).apply(this, arguments);
  1687. };
  1688. }
  1689. var warned = false;
  1690. function deprecated() {
  1691. if (!warned) {
  1692. {
  1693. console.error(msg);
  1694. }
  1695. warned = true;
  1696. }
  1697. return fn.apply(this, arguments);
  1698. }
  1699. return deprecated;
  1700. }
  1701. var debugs = {};
  1702. var debugEnviron;
  1703. function debuglog(set) {
  1704. if (isUndefined(debugEnviron)) debugEnviron = '';
  1705. set = set.toUpperCase();
  1706. if (!debugs[set]) {
  1707. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  1708. var pid = 0;
  1709. debugs[set] = function () {
  1710. var msg = format.apply(null, arguments);
  1711. console.error('%s %d: %s', set, pid, msg);
  1712. };
  1713. } else {
  1714. debugs[set] = function () {};
  1715. }
  1716. }
  1717. return debugs[set];
  1718. }
  1719. /**
  1720. * Echos the value of a value. Trys to print the value out
  1721. * in the best way possible given the different types.
  1722. *
  1723. * @param {Object} obj The object to print out.
  1724. * @param {Object} opts Optional options object that alters the output.
  1725. */
  1726. /* legacy: obj, showHidden, depth, colors*/
  1727. function inspect(obj, opts) {
  1728. // default options
  1729. var ctx = {
  1730. seen: [],
  1731. stylize: stylizeNoColor
  1732. }; // legacy...
  1733. if (arguments.length >= 3) ctx.depth = arguments[2];
  1734. if (arguments.length >= 4) ctx.colors = arguments[3];
  1735. if (isBoolean(opts)) {
  1736. // legacy...
  1737. ctx.showHidden = opts;
  1738. } else if (opts) {
  1739. // got an "options" object
  1740. _extend(ctx, opts);
  1741. } // set default options
  1742. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  1743. if (isUndefined(ctx.depth)) ctx.depth = 2;
  1744. if (isUndefined(ctx.colors)) ctx.colors = false;
  1745. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  1746. if (ctx.colors) ctx.stylize = stylizeWithColor;
  1747. return formatValue(ctx, obj, ctx.depth);
  1748. } // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  1749. inspect.colors = {
  1750. 'bold': [1, 22],
  1751. 'italic': [3, 23],
  1752. 'underline': [4, 24],
  1753. 'inverse': [7, 27],
  1754. 'white': [37, 39],
  1755. 'grey': [90, 39],
  1756. 'black': [30, 39],
  1757. 'blue': [34, 39],
  1758. 'cyan': [36, 39],
  1759. 'green': [32, 39],
  1760. 'magenta': [35, 39],
  1761. 'red': [31, 39],
  1762. 'yellow': [33, 39]
  1763. }; // Don't use 'blue' not visible on cmd.exe
  1764. inspect.styles = {
  1765. 'special': 'cyan',
  1766. 'number': 'yellow',
  1767. 'boolean': 'yellow',
  1768. 'undefined': 'grey',
  1769. 'null': 'bold',
  1770. 'string': 'green',
  1771. 'date': 'magenta',
  1772. // "name": intentionally not styling
  1773. 'regexp': 'red'
  1774. };
  1775. function stylizeWithColor(str, styleType) {
  1776. var style = inspect.styles[styleType];
  1777. if (style) {
  1778. return "\x1B[" + inspect.colors[style][0] + 'm' + str + "\x1B[" + inspect.colors[style][1] + 'm';
  1779. } else {
  1780. return str;
  1781. }
  1782. }
  1783. function stylizeNoColor(str, styleType) {
  1784. return str;
  1785. }
  1786. function arrayToHash(array) {
  1787. var hash = {};
  1788. array.forEach(function (val, idx) {
  1789. hash[val] = true;
  1790. });
  1791. return hash;
  1792. }
  1793. function formatValue(ctx, value, recurseTimes) {
  1794. // Provide a hook for user-specified inspect functions.
  1795. // Check that value is an object with an inspect function on it
  1796. if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special
  1797. value.inspect !== inspect && // Also filter out any prototype objects using the circular check.
  1798. !(value.constructor && value.constructor.prototype === value)) {
  1799. var ret = value.inspect(recurseTimes, ctx);
  1800. if (!isString(ret)) {
  1801. ret = formatValue(ctx, ret, recurseTimes);
  1802. }
  1803. return ret;
  1804. } // Primitive types cannot have properties
  1805. var primitive = formatPrimitive(ctx, value);
  1806. if (primitive) {
  1807. return primitive;
  1808. } // Look up the keys of the object.
  1809. var keys = Object.keys(value);
  1810. var visibleKeys = arrayToHash(keys);
  1811. if (ctx.showHidden) {
  1812. keys = Object.getOwnPropertyNames(value);
  1813. } // IE doesn't make error fields non-enumerable
  1814. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  1815. if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  1816. return formatError(value);
  1817. } // Some type of object without properties can be shortcutted.
  1818. if (keys.length === 0) {
  1819. if (isFunction(value)) {
  1820. var name = value.name ? ': ' + value.name : '';
  1821. return ctx.stylize('[Function' + name + ']', 'special');
  1822. }
  1823. if (isRegExp(value)) {
  1824. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  1825. }
  1826. if (isDate(value)) {
  1827. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  1828. }
  1829. if (isError(value)) {
  1830. return formatError(value);
  1831. }
  1832. }
  1833. var base = '',
  1834. array = false,
  1835. braces = ['{', '}']; // Make Array say that they are Array
  1836. if (isArray(value)) {
  1837. array = true;
  1838. braces = ['[', ']'];
  1839. } // Make functions say that they are functions
  1840. if (isFunction(value)) {
  1841. var n = value.name ? ': ' + value.name : '';
  1842. base = ' [Function' + n + ']';
  1843. } // Make RegExps say that they are RegExps
  1844. if (isRegExp(value)) {
  1845. base = ' ' + RegExp.prototype.toString.call(value);
  1846. } // Make dates with properties first say the date
  1847. if (isDate(value)) {
  1848. base = ' ' + Date.prototype.toUTCString.call(value);
  1849. } // Make error with message first say the error
  1850. if (isError(value)) {
  1851. base = ' ' + formatError(value);
  1852. }
  1853. if (keys.length === 0 && (!array || value.length == 0)) {
  1854. return braces[0] + base + braces[1];
  1855. }
  1856. if (recurseTimes < 0) {
  1857. if (isRegExp(value)) {
  1858. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  1859. } else {
  1860. return ctx.stylize('[Object]', 'special');
  1861. }
  1862. }
  1863. ctx.seen.push(value);
  1864. var output;
  1865. if (array) {
  1866. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  1867. } else {
  1868. output = keys.map(function (key) {
  1869. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  1870. });
  1871. }
  1872. ctx.seen.pop();
  1873. return reduceToSingleString(output, base, braces);
  1874. }
  1875. function formatPrimitive(ctx, value) {
  1876. if (isUndefined(value)) return ctx.stylize('undefined', 'undefined');
  1877. if (isString(value)) {
  1878. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '').replace(/'/g, "\\'").replace(/\\"/g, '"') + '\'';
  1879. return ctx.stylize(simple, 'string');
  1880. }
  1881. if (isNumber(value)) return ctx.stylize('' + value, 'number');
  1882. if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here.
  1883. if (isNull(value)) return ctx.stylize('null', 'null');
  1884. }
  1885. function formatError(value) {
  1886. return '[' + Error.prototype.toString.call(value) + ']';
  1887. }
  1888. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  1889. var output = [];
  1890. for (var i = 0, l = value.length; i < l; ++i) {
  1891. if (hasOwnProperty(value, String(i))) {
  1892. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true));
  1893. } else {
  1894. output.push('');
  1895. }
  1896. }
  1897. keys.forEach(function (key) {
  1898. if (!key.match(/^\d+$/)) {
  1899. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true));
  1900. }
  1901. });
  1902. return output;
  1903. }
  1904. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  1905. var name, str, desc;
  1906. desc = Object.getOwnPropertyDescriptor(value, key) || {
  1907. value: value[key]
  1908. };
  1909. if (desc.get) {
  1910. if (desc.set) {
  1911. str = ctx.stylize('[Getter/Setter]', 'special');
  1912. } else {
  1913. str = ctx.stylize('[Getter]', 'special');
  1914. }
  1915. } else {
  1916. if (desc.set) {
  1917. str = ctx.stylize('[Setter]', 'special');
  1918. }
  1919. }
  1920. if (!hasOwnProperty(visibleKeys, key)) {
  1921. name = '[' + key + ']';
  1922. }
  1923. if (!str) {
  1924. if (ctx.seen.indexOf(desc.value) < 0) {
  1925. if (isNull(recurseTimes)) {
  1926. str = formatValue(ctx, desc.value, null);
  1927. } else {
  1928. str = formatValue(ctx, desc.value, recurseTimes - 1);
  1929. }
  1930. if (str.indexOf('\n') > -1) {
  1931. if (array) {
  1932. str = str.split('\n').map(function (line) {
  1933. return ' ' + line;
  1934. }).join('\n').substr(2);
  1935. } else {
  1936. str = '\n' + str.split('\n').map(function (line) {
  1937. return ' ' + line;
  1938. }).join('\n');
  1939. }
  1940. }
  1941. } else {
  1942. str = ctx.stylize('[Circular]', 'special');
  1943. }
  1944. }
  1945. if (isUndefined(name)) {
  1946. if (array && key.match(/^\d+$/)) {
  1947. return str;
  1948. }
  1949. name = JSON.stringify('' + key);
  1950. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  1951. name = name.substr(1, name.length - 2);
  1952. name = ctx.stylize(name, 'name');
  1953. } else {
  1954. name = name.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'");
  1955. name = ctx.stylize(name, 'string');
  1956. }
  1957. }
  1958. return name + ': ' + str;
  1959. }
  1960. function reduceToSingleString(output, base, braces) {
  1961. var length = output.reduce(function (prev, cur) {
  1962. if (cur.indexOf('\n') >= 0) ;
  1963. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  1964. }, 0);
  1965. if (length > 60) {
  1966. return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1];
  1967. }
  1968. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  1969. } // NOTE: These type checking functions intentionally don't use `instanceof`
  1970. // because it is fragile and can be easily faked with `Object.create()`.
  1971. function isArray(ar) {
  1972. return Array.isArray(ar);
  1973. }
  1974. function isBoolean(arg) {
  1975. return typeof arg === 'boolean';
  1976. }
  1977. function isNull(arg) {
  1978. return arg === null;
  1979. }
  1980. function isNullOrUndefined(arg) {
  1981. return arg == null;
  1982. }
  1983. function isNumber(arg) {
  1984. return typeof arg === 'number';
  1985. }
  1986. function isString(arg) {
  1987. return typeof arg === 'string';
  1988. }
  1989. function isSymbol(arg) {
  1990. return babelHelpers["typeof"](arg) === 'symbol';
  1991. }
  1992. function isUndefined(arg) {
  1993. return arg === void 0;
  1994. }
  1995. function isRegExp(re) {
  1996. return isObject(re) && objectToString(re) === '[object RegExp]';
  1997. }
  1998. function isObject(arg) {
  1999. return babelHelpers["typeof"](arg) === 'object' && arg !== null;
  2000. }
  2001. function isDate(d) {
  2002. return isObject(d) && objectToString(d) === '[object Date]';
  2003. }
  2004. function isError(e) {
  2005. return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error);
  2006. }
  2007. function isFunction(arg) {
  2008. return typeof arg === 'function';
  2009. }
  2010. function isPrimitive(arg) {
  2011. return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || babelHelpers["typeof"](arg) === 'symbol' || // ES6 symbol
  2012. typeof arg === 'undefined';
  2013. }
  2014. function isBuffer(maybeBuf) {
  2015. return Buffer.isBuffer(maybeBuf);
  2016. }
  2017. function objectToString(o) {
  2018. return Object.prototype.toString.call(o);
  2019. }
  2020. function pad(n) {
  2021. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  2022. }
  2023. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34
  2024. function timestamp$1() {
  2025. var d = new Date();
  2026. var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':');
  2027. return [d.getDate(), months[d.getMonth()], time].join(' ');
  2028. } // log is just a thin wrapper to console.log that prepends a timestamp
  2029. function log() {
  2030. console.log('%s - %s', timestamp$1(), format.apply(null, arguments));
  2031. }
  2032. function _extend(origin, add) {
  2033. // Don't do anything if add isn't an object
  2034. if (!add || !isObject(add)) return origin;
  2035. var keys = Object.keys(add);
  2036. var i = keys.length;
  2037. while (i--) {
  2038. origin[keys[i]] = add[keys[i]];
  2039. }
  2040. return origin;
  2041. }
  2042. function hasOwnProperty(obj, prop) {
  2043. return Object.prototype.hasOwnProperty.call(obj, prop);
  2044. }
  2045. var require$$1 = {
  2046. inherits: inherits$1,
  2047. _extend: _extend,
  2048. log: log,
  2049. isBuffer: isBuffer,
  2050. isPrimitive: isPrimitive,
  2051. isFunction: isFunction,
  2052. isError: isError,
  2053. isDate: isDate,
  2054. isObject: isObject,
  2055. isRegExp: isRegExp,
  2056. isUndefined: isUndefined,
  2057. isSymbol: isSymbol,
  2058. isString: isString,
  2059. isNumber: isNumber,
  2060. isNullOrUndefined: isNullOrUndefined,
  2061. isNull: isNull,
  2062. isBoolean: isBoolean,
  2063. isArray: isArray,
  2064. inspect: inspect,
  2065. deprecate: deprecate,
  2066. format: format,
  2067. debuglog: debuglog
  2068. };
  2069. var utils = createCommonjsModule(function (module, exports) {
  2070. Object.defineProperty(exports, "__esModule", { value: true });
  2071. exports.deprecate = exports.isObjectLike = exports.isDate = exports.haveBuffer = exports.isMap = exports.isRegExp = exports.isBigUInt64Array = exports.isBigInt64Array = exports.isUint8Array = exports.isAnyArrayBuffer = exports.randomBytes = exports.normalizedFunctionString = void 0;
  2072. /**
  2073. * Normalizes our expected stringified form of a function across versions of node
  2074. * @param fn - The function to stringify
  2075. */
  2076. function normalizedFunctionString(fn) {
  2077. return fn.toString().replace('function(', 'function (');
  2078. }
  2079. exports.normalizedFunctionString = normalizedFunctionString;
  2080. var isReactNative = typeof commonjsGlobal.navigator === 'object' && commonjsGlobal.navigator.product === 'ReactNative';
  2081. var insecureWarning = isReactNative
  2082. ? 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.'
  2083. : 'BSON: No cryptographic implementation for random bytes present, falling back to a less secure implementation.';
  2084. var insecureRandomBytes = function insecureRandomBytes(size) {
  2085. console.warn(insecureWarning);
  2086. var result = buffer.Buffer.alloc(size);
  2087. for (var i = 0; i < size; ++i)
  2088. result[i] = Math.floor(Math.random() * 256);
  2089. return result;
  2090. };
  2091. var detectRandomBytes = function () {
  2092. if (typeof window !== 'undefined') {
  2093. // browser crypto implementation(s)
  2094. var target_1 = window.crypto || window.msCrypto; // allow for IE11
  2095. if (target_1 && target_1.getRandomValues) {
  2096. return function (size) { return target_1.getRandomValues(buffer.Buffer.alloc(size)); };
  2097. }
  2098. }
  2099. if (typeof commonjsGlobal !== 'undefined' && commonjsGlobal.crypto && commonjsGlobal.crypto.getRandomValues) {
  2100. // allow for RN packages such as https://www.npmjs.com/package/react-native-get-random-values to populate global
  2101. return function (size) { return commonjsGlobal.crypto.getRandomValues(buffer.Buffer.alloc(size)); };
  2102. }
  2103. var requiredRandomBytes;
  2104. try {
  2105. // eslint-disable-next-line @typescript-eslint/no-var-requires
  2106. requiredRandomBytes = require$$0.randomBytes;
  2107. }
  2108. catch (e) {
  2109. // keep the fallback
  2110. }
  2111. // NOTE: in transpiled cases the above require might return null/undefined
  2112. return requiredRandomBytes || insecureRandomBytes;
  2113. };
  2114. exports.randomBytes = detectRandomBytes();
  2115. function isAnyArrayBuffer(value) {
  2116. return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value));
  2117. }
  2118. exports.isAnyArrayBuffer = isAnyArrayBuffer;
  2119. function isUint8Array(value) {
  2120. return Object.prototype.toString.call(value) === '[object Uint8Array]';
  2121. }
  2122. exports.isUint8Array = isUint8Array;
  2123. function isBigInt64Array(value) {
  2124. return Object.prototype.toString.call(value) === '[object BigInt64Array]';
  2125. }
  2126. exports.isBigInt64Array = isBigInt64Array;
  2127. function isBigUInt64Array(value) {
  2128. return Object.prototype.toString.call(value) === '[object BigUint64Array]';
  2129. }
  2130. exports.isBigUInt64Array = isBigUInt64Array;
  2131. function isRegExp(d) {
  2132. return Object.prototype.toString.call(d) === '[object RegExp]';
  2133. }
  2134. exports.isRegExp = isRegExp;
  2135. function isMap(d) {
  2136. return Object.prototype.toString.call(d) === '[object Map]';
  2137. }
  2138. exports.isMap = isMap;
  2139. /** Call to check if your environment has `Buffer` */
  2140. function haveBuffer() {
  2141. return typeof commonjsGlobal !== 'undefined' && typeof commonjsGlobal.Buffer !== 'undefined';
  2142. }
  2143. exports.haveBuffer = haveBuffer;
  2144. // To ensure that 0.4 of node works correctly
  2145. function isDate(d) {
  2146. return isObjectLike(d) && Object.prototype.toString.call(d) === '[object Date]';
  2147. }
  2148. exports.isDate = isDate;
  2149. /**
  2150. * @internal
  2151. * this is to solve the `'someKey' in x` problem where x is unknown.
  2152. * https://github.com/typescript-eslint/typescript-eslint/issues/1071#issuecomment-541955753
  2153. */
  2154. function isObjectLike(candidate) {
  2155. return typeof candidate === 'object' && candidate !== null;
  2156. }
  2157. exports.isObjectLike = isObjectLike;
  2158. function deprecate(fn, message) {
  2159. if (typeof window === 'undefined' && typeof self === 'undefined') {
  2160. // eslint-disable-next-line @typescript-eslint/no-var-requires
  2161. return require$$1.deprecate(fn, message);
  2162. }
  2163. var warned = false;
  2164. function deprecated() {
  2165. var args = [];
  2166. for (var _i = 0; _i < arguments.length; _i++) {
  2167. args[_i] = arguments[_i];
  2168. }
  2169. if (!warned) {
  2170. console.warn(message);
  2171. warned = true;
  2172. }
  2173. return fn.apply(this, args);
  2174. }
  2175. return deprecated;
  2176. }
  2177. exports.deprecate = deprecate;
  2178. });
  2179. unwrapExports(utils);
  2180. utils.deprecate;
  2181. utils.isObjectLike;
  2182. utils.isDate;
  2183. utils.haveBuffer;
  2184. utils.isMap;
  2185. utils.isRegExp;
  2186. utils.isBigUInt64Array;
  2187. utils.isBigInt64Array;
  2188. utils.isUint8Array;
  2189. utils.isAnyArrayBuffer;
  2190. utils.randomBytes;
  2191. utils.normalizedFunctionString;
  2192. var ensure_buffer = createCommonjsModule(function (module, exports) {
  2193. Object.defineProperty(exports, "__esModule", { value: true });
  2194. exports.ensureBuffer = void 0;
  2195. /**
  2196. * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer.
  2197. *
  2198. * @param potentialBuffer - The potential buffer
  2199. * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that
  2200. * wraps a passed in Uint8Array
  2201. * @throws TypeError If anything other than a Buffer or Uint8Array is passed in
  2202. */
  2203. function ensureBuffer(potentialBuffer) {
  2204. if (ArrayBuffer.isView(potentialBuffer)) {
  2205. return buffer.Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength);
  2206. }
  2207. if (utils.isAnyArrayBuffer(potentialBuffer)) {
  2208. return buffer.Buffer.from(potentialBuffer);
  2209. }
  2210. throw new TypeError('Must use either Buffer or TypedArray');
  2211. }
  2212. exports.ensureBuffer = ensureBuffer;
  2213. });
  2214. unwrapExports(ensure_buffer);
  2215. ensure_buffer.ensureBuffer;
  2216. var uuid_utils = createCommonjsModule(function (module, exports) {
  2217. Object.defineProperty(exports, "__esModule", { value: true });
  2218. exports.bufferToUuidHexString = exports.uuidHexStringToBuffer = exports.uuidValidateString = void 0;
  2219. // Validation regex for v4 uuid (validates with or without dashes)
  2220. var VALIDATION_REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i;
  2221. var uuidValidateString = function (str) {
  2222. return typeof str === 'string' && VALIDATION_REGEX.test(str);
  2223. };
  2224. exports.uuidValidateString = uuidValidateString;
  2225. var uuidHexStringToBuffer = function (hexString) {
  2226. if (!exports.uuidValidateString(hexString)) {
  2227. throw new TypeError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".');
  2228. }
  2229. var sanitizedHexString = hexString.replace(/-/g, '');
  2230. return buffer.Buffer.from(sanitizedHexString, 'hex');
  2231. };
  2232. exports.uuidHexStringToBuffer = uuidHexStringToBuffer;
  2233. var bufferToUuidHexString = function (buffer, includeDashes) {
  2234. if (includeDashes === void 0) { includeDashes = true; }
  2235. return includeDashes
  2236. ? buffer.toString('hex', 0, 4) +
  2237. '-' +
  2238. buffer.toString('hex', 4, 6) +
  2239. '-' +
  2240. buffer.toString('hex', 6, 8) +
  2241. '-' +
  2242. buffer.toString('hex', 8, 10) +
  2243. '-' +
  2244. buffer.toString('hex', 10, 16)
  2245. : buffer.toString('hex');
  2246. };
  2247. exports.bufferToUuidHexString = bufferToUuidHexString;
  2248. });
  2249. unwrapExports(uuid_utils);
  2250. uuid_utils.bufferToUuidHexString;
  2251. uuid_utils.uuidHexStringToBuffer;
  2252. uuid_utils.uuidValidateString;
  2253. var uuid = createCommonjsModule(function (module, exports) {
  2254. Object.defineProperty(exports, "__esModule", { value: true });
  2255. exports.UUID = void 0;
  2256. var BYTE_LENGTH = 16;
  2257. var kId = Symbol('id');
  2258. /**
  2259. * A class representation of the BSON UUID type.
  2260. * @public
  2261. */
  2262. var UUID = /** @class */ (function () {
  2263. /**
  2264. * Create an UUID type
  2265. *
  2266. * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer.
  2267. */
  2268. function UUID(input) {
  2269. if (typeof input === 'undefined') {
  2270. // The most common use case (blank id, new UUID() instance)
  2271. this.id = UUID.generate();
  2272. }
  2273. else if (input instanceof UUID) {
  2274. this[kId] = buffer.Buffer.from(input.id);
  2275. this.__id = input.__id;
  2276. }
  2277. else if (ArrayBuffer.isView(input) && input.byteLength === BYTE_LENGTH) {
  2278. this.id = ensure_buffer.ensureBuffer(input);
  2279. }
  2280. else if (typeof input === 'string') {
  2281. this.id = uuid_utils.uuidHexStringToBuffer(input);
  2282. }
  2283. else {
  2284. throw new TypeError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).');
  2285. }
  2286. }
  2287. Object.defineProperty(UUID.prototype, "id", {
  2288. /**
  2289. * The UUID bytes
  2290. * @readonly
  2291. */
  2292. get: function () {
  2293. return this[kId];
  2294. },
  2295. set: function (value) {
  2296. this[kId] = value;
  2297. if (UUID.cacheHexString) {
  2298. this.__id = uuid_utils.bufferToUuidHexString(value);
  2299. }
  2300. },
  2301. enumerable: false,
  2302. configurable: true
  2303. });
  2304. /**
  2305. * Generate a 16 byte uuid v4 buffer used in UUIDs
  2306. */
  2307. /**
  2308. * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated)
  2309. * @param includeDashes - should the string exclude dash-separators.
  2310. * */
  2311. UUID.prototype.toHexString = function (includeDashes) {
  2312. if (includeDashes === void 0) { includeDashes = true; }
  2313. if (UUID.cacheHexString && this.__id) {
  2314. return this.__id;
  2315. }
  2316. var uuidHexString = uuid_utils.bufferToUuidHexString(this.id, includeDashes);
  2317. if (UUID.cacheHexString) {
  2318. this.__id = uuidHexString;
  2319. }
  2320. return uuidHexString;
  2321. };
  2322. /**
  2323. * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified.
  2324. * @internal
  2325. */
  2326. UUID.prototype.toString = function (encoding) {
  2327. return encoding ? this.id.toString(encoding) : this.toHexString();
  2328. };
  2329. /**
  2330. * Converts the id into its JSON string representation. A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  2331. * @internal
  2332. */
  2333. UUID.prototype.toJSON = function () {
  2334. return this.toHexString();
  2335. };
  2336. /**
  2337. * Compares the equality of this UUID with `otherID`.
  2338. *
  2339. * @param otherId - UUID instance to compare against.
  2340. */
  2341. UUID.prototype.equals = function (otherId) {
  2342. if (!otherId) {
  2343. return false;
  2344. }
  2345. if (otherId instanceof UUID) {
  2346. return otherId.id.equals(this.id);
  2347. }
  2348. try {
  2349. return new UUID(otherId).id.equals(this.id);
  2350. }
  2351. catch (_a) {
  2352. return false;
  2353. }
  2354. };
  2355. /**
  2356. * Creates a Binary instance from the current UUID.
  2357. */
  2358. UUID.prototype.toBinary = function () {
  2359. return new binary.Binary(this.id, binary.Binary.SUBTYPE_UUID);
  2360. };
  2361. /**
  2362. * Generates a populated buffer containing a v4 uuid
  2363. */
  2364. UUID.generate = function () {
  2365. var bytes = utils.randomBytes(BYTE_LENGTH);
  2366. // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  2367. // Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js
  2368. bytes[6] = (bytes[6] & 0x0f) | 0x40;
  2369. bytes[8] = (bytes[8] & 0x3f) | 0x80;
  2370. return buffer.Buffer.from(bytes);
  2371. };
  2372. /**
  2373. * Checks if a value is a valid bson UUID
  2374. * @param input - UUID, string or Buffer to validate.
  2375. */
  2376. UUID.isValid = function (input) {
  2377. if (!input) {
  2378. return false;
  2379. }
  2380. if (input instanceof UUID) {
  2381. return true;
  2382. }
  2383. if (typeof input === 'string') {
  2384. return uuid_utils.uuidValidateString(input);
  2385. }
  2386. if (utils.isUint8Array(input)) {
  2387. // check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3)
  2388. if (input.length !== BYTE_LENGTH) {
  2389. return false;
  2390. }
  2391. try {
  2392. // get this byte as hex: xxxxxxxx-xxxx-XXxx-xxxx-xxxxxxxxxxxx
  2393. // check first part as uuid version: xxxxxxxx-xxxx-Xxxx-xxxx-xxxxxxxxxxxx
  2394. return parseInt(input[6].toString(16)[0], 10) === binary.Binary.SUBTYPE_UUID;
  2395. }
  2396. catch (_a) {
  2397. return false;
  2398. }
  2399. }
  2400. return false;
  2401. };
  2402. /**
  2403. * Creates an UUID from a hex string representation of an UUID.
  2404. * @param hexString - 32 or 36 character hex string (dashes excluded/included).
  2405. */
  2406. UUID.createFromHexString = function (hexString) {
  2407. var buffer = uuid_utils.uuidHexStringToBuffer(hexString);
  2408. return new UUID(buffer);
  2409. };
  2410. /**
  2411. * Converts to a string representation of this Id.
  2412. *
  2413. * @returns return the 36 character hex string representation.
  2414. * @internal
  2415. */
  2416. UUID.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  2417. return this.inspect();
  2418. };
  2419. UUID.prototype.inspect = function () {
  2420. return "new UUID(\"" + this.toHexString() + "\")";
  2421. };
  2422. return UUID;
  2423. }());
  2424. exports.UUID = UUID;
  2425. Object.defineProperty(UUID.prototype, '_bsontype', { value: 'UUID' });
  2426. });
  2427. unwrapExports(uuid);
  2428. uuid.UUID;
  2429. var binary = createCommonjsModule(function (module, exports) {
  2430. Object.defineProperty(exports, "__esModule", { value: true });
  2431. exports.Binary = void 0;
  2432. /**
  2433. * A class representation of the BSON Binary type.
  2434. * @public
  2435. */
  2436. var Binary = /** @class */ (function () {
  2437. /**
  2438. * @param buffer - a buffer object containing the binary data.
  2439. * @param subType - the option binary type.
  2440. */
  2441. function Binary(buffer$1, subType) {
  2442. if (!(this instanceof Binary))
  2443. return new Binary(buffer$1, subType);
  2444. if (!(buffer$1 == null) &&
  2445. !(typeof buffer$1 === 'string') &&
  2446. !ArrayBuffer.isView(buffer$1) &&
  2447. !(buffer$1 instanceof ArrayBuffer) &&
  2448. !Array.isArray(buffer$1)) {
  2449. throw new TypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array<number>');
  2450. }
  2451. this.sub_type = subType !== null && subType !== void 0 ? subType : Binary.BSON_BINARY_SUBTYPE_DEFAULT;
  2452. if (buffer$1 == null) {
  2453. // create an empty binary buffer
  2454. this.buffer = buffer.Buffer.alloc(Binary.BUFFER_SIZE);
  2455. this.position = 0;
  2456. }
  2457. else {
  2458. if (typeof buffer$1 === 'string') {
  2459. // string
  2460. this.buffer = buffer.Buffer.from(buffer$1, 'binary');
  2461. }
  2462. else if (Array.isArray(buffer$1)) {
  2463. // number[]
  2464. this.buffer = buffer.Buffer.from(buffer$1);
  2465. }
  2466. else {
  2467. // Buffer | TypedArray | ArrayBuffer
  2468. this.buffer = ensure_buffer.ensureBuffer(buffer$1);
  2469. }
  2470. this.position = this.buffer.byteLength;
  2471. }
  2472. }
  2473. /**
  2474. * Updates this binary with byte_value.
  2475. *
  2476. * @param byteValue - a single byte we wish to write.
  2477. */
  2478. Binary.prototype.put = function (byteValue) {
  2479. // If it's a string and a has more than one character throw an error
  2480. if (typeof byteValue === 'string' && byteValue.length !== 1) {
  2481. throw new TypeError('only accepts single character String');
  2482. }
  2483. else if (typeof byteValue !== 'number' && byteValue.length !== 1)
  2484. throw new TypeError('only accepts single character Uint8Array or Array');
  2485. // Decode the byte value once
  2486. var decodedByte;
  2487. if (typeof byteValue === 'string') {
  2488. decodedByte = byteValue.charCodeAt(0);
  2489. }
  2490. else if (typeof byteValue === 'number') {
  2491. decodedByte = byteValue;
  2492. }
  2493. else {
  2494. decodedByte = byteValue[0];
  2495. }
  2496. if (decodedByte < 0 || decodedByte > 255) {
  2497. throw new TypeError('only accepts number in a valid unsigned byte range 0-255');
  2498. }
  2499. if (this.buffer.length > this.position) {
  2500. this.buffer[this.position++] = decodedByte;
  2501. }
  2502. else {
  2503. var buffer$1 = buffer.Buffer.alloc(Binary.BUFFER_SIZE + this.buffer.length);
  2504. // Combine the two buffers together
  2505. this.buffer.copy(buffer$1, 0, 0, this.buffer.length);
  2506. this.buffer = buffer$1;
  2507. this.buffer[this.position++] = decodedByte;
  2508. }
  2509. };
  2510. /**
  2511. * Writes a buffer or string to the binary.
  2512. *
  2513. * @param sequence - a string or buffer to be written to the Binary BSON object.
  2514. * @param offset - specify the binary of where to write the content.
  2515. */
  2516. Binary.prototype.write = function (sequence, offset) {
  2517. offset = typeof offset === 'number' ? offset : this.position;
  2518. // If the buffer is to small let's extend the buffer
  2519. if (this.buffer.length < offset + sequence.length) {
  2520. var buffer$1 = buffer.Buffer.alloc(this.buffer.length + sequence.length);
  2521. this.buffer.copy(buffer$1, 0, 0, this.buffer.length);
  2522. // Assign the new buffer
  2523. this.buffer = buffer$1;
  2524. }
  2525. if (ArrayBuffer.isView(sequence)) {
  2526. this.buffer.set(ensure_buffer.ensureBuffer(sequence), offset);
  2527. this.position =
  2528. offset + sequence.byteLength > this.position ? offset + sequence.length : this.position;
  2529. }
  2530. else if (typeof sequence === 'string') {
  2531. this.buffer.write(sequence, offset, sequence.length, 'binary');
  2532. this.position =
  2533. offset + sequence.length > this.position ? offset + sequence.length : this.position;
  2534. }
  2535. };
  2536. /**
  2537. * Reads **length** bytes starting at **position**.
  2538. *
  2539. * @param position - read from the given position in the Binary.
  2540. * @param length - the number of bytes to read.
  2541. */
  2542. Binary.prototype.read = function (position, length) {
  2543. length = length && length > 0 ? length : this.position;
  2544. // Let's return the data based on the type we have
  2545. return this.buffer.slice(position, position + length);
  2546. };
  2547. /**
  2548. * Returns the value of this binary as a string.
  2549. * @param asRaw - Will skip converting to a string
  2550. * @remarks
  2551. * This is handy when calling this function conditionally for some key value pairs and not others
  2552. */
  2553. Binary.prototype.value = function (asRaw) {
  2554. asRaw = !!asRaw;
  2555. // Optimize to serialize for the situation where the data == size of buffer
  2556. if (asRaw && this.buffer.length === this.position) {
  2557. return this.buffer;
  2558. }
  2559. // If it's a node.js buffer object
  2560. if (asRaw) {
  2561. return this.buffer.slice(0, this.position);
  2562. }
  2563. return this.buffer.toString('binary', 0, this.position);
  2564. };
  2565. /** the length of the binary sequence */
  2566. Binary.prototype.length = function () {
  2567. return this.position;
  2568. };
  2569. /** @internal */
  2570. Binary.prototype.toJSON = function () {
  2571. return this.buffer.toString('base64');
  2572. };
  2573. /** @internal */
  2574. Binary.prototype.toString = function (format) {
  2575. return this.buffer.toString(format);
  2576. };
  2577. /** @internal */
  2578. Binary.prototype.toExtendedJSON = function (options) {
  2579. options = options || {};
  2580. var base64String = this.buffer.toString('base64');
  2581. var subType = Number(this.sub_type).toString(16);
  2582. if (options.legacy) {
  2583. return {
  2584. $binary: base64String,
  2585. $type: subType.length === 1 ? '0' + subType : subType
  2586. };
  2587. }
  2588. return {
  2589. $binary: {
  2590. base64: base64String,
  2591. subType: subType.length === 1 ? '0' + subType : subType
  2592. }
  2593. };
  2594. };
  2595. /** @internal */
  2596. Binary.prototype.toUUID = function () {
  2597. if (this.sub_type === Binary.SUBTYPE_UUID) {
  2598. return new uuid.UUID(this.buffer.slice(0, this.position));
  2599. }
  2600. throw new Error("Binary sub_type \"" + this.sub_type + "\" is not supported for converting to UUID. Only \"" + Binary.SUBTYPE_UUID + "\" is currently supported.");
  2601. };
  2602. /** @internal */
  2603. Binary.fromExtendedJSON = function (doc, options) {
  2604. options = options || {};
  2605. var data;
  2606. var type;
  2607. if ('$binary' in doc) {
  2608. if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) {
  2609. type = doc.$type ? parseInt(doc.$type, 16) : 0;
  2610. data = buffer.Buffer.from(doc.$binary, 'base64');
  2611. }
  2612. else {
  2613. if (typeof doc.$binary !== 'string') {
  2614. type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
  2615. data = buffer.Buffer.from(doc.$binary.base64, 'base64');
  2616. }
  2617. }
  2618. }
  2619. else if ('$uuid' in doc) {
  2620. type = 4;
  2621. data = uuid_utils.uuidHexStringToBuffer(doc.$uuid);
  2622. }
  2623. if (!data) {
  2624. throw new TypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc));
  2625. }
  2626. return new Binary(data, type);
  2627. };
  2628. /** @internal */
  2629. Binary.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  2630. return this.inspect();
  2631. };
  2632. Binary.prototype.inspect = function () {
  2633. var asBuffer = this.value(true);
  2634. return "new Binary(Buffer.from(\"" + asBuffer.toString('hex') + "\", \"hex\"), " + this.sub_type + ")";
  2635. };
  2636. /**
  2637. * Binary default subtype
  2638. * @internal
  2639. */
  2640. Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0;
  2641. /** Initial buffer default size */
  2642. Binary.BUFFER_SIZE = 256;
  2643. /** Default BSON type */
  2644. Binary.SUBTYPE_DEFAULT = 0;
  2645. /** Function BSON type */
  2646. Binary.SUBTYPE_FUNCTION = 1;
  2647. /** Byte Array BSON type */
  2648. Binary.SUBTYPE_BYTE_ARRAY = 2;
  2649. /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */
  2650. Binary.SUBTYPE_UUID_OLD = 3;
  2651. /** UUID BSON type */
  2652. Binary.SUBTYPE_UUID = 4;
  2653. /** MD5 BSON type */
  2654. Binary.SUBTYPE_MD5 = 5;
  2655. /** User BSON type */
  2656. Binary.SUBTYPE_USER_DEFINED = 128;
  2657. return Binary;
  2658. }());
  2659. exports.Binary = Binary;
  2660. Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' });
  2661. });
  2662. unwrapExports(binary);
  2663. binary.Binary;
  2664. var code = createCommonjsModule(function (module, exports) {
  2665. Object.defineProperty(exports, "__esModule", { value: true });
  2666. exports.Code = void 0;
  2667. /**
  2668. * A class representation of the BSON Code type.
  2669. * @public
  2670. */
  2671. var Code = /** @class */ (function () {
  2672. /**
  2673. * @param code - a string or function.
  2674. * @param scope - an optional scope for the function.
  2675. */
  2676. function Code(code, scope) {
  2677. if (!(this instanceof Code))
  2678. return new Code(code, scope);
  2679. this.code = code;
  2680. this.scope = scope;
  2681. }
  2682. /** @internal */
  2683. Code.prototype.toJSON = function () {
  2684. return { code: this.code, scope: this.scope };
  2685. };
  2686. /** @internal */
  2687. Code.prototype.toExtendedJSON = function () {
  2688. if (this.scope) {
  2689. return { $code: this.code, $scope: this.scope };
  2690. }
  2691. return { $code: this.code };
  2692. };
  2693. /** @internal */
  2694. Code.fromExtendedJSON = function (doc) {
  2695. return new Code(doc.$code, doc.$scope);
  2696. };
  2697. /** @internal */
  2698. Code.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  2699. return this.inspect();
  2700. };
  2701. Code.prototype.inspect = function () {
  2702. var codeJson = this.toJSON();
  2703. return "new Code(\"" + codeJson.code + "\"" + (codeJson.scope ? ", " + JSON.stringify(codeJson.scope) : '') + ")";
  2704. };
  2705. return Code;
  2706. }());
  2707. exports.Code = Code;
  2708. Object.defineProperty(Code.prototype, '_bsontype', { value: 'Code' });
  2709. });
  2710. unwrapExports(code);
  2711. code.Code;
  2712. var db_ref = createCommonjsModule(function (module, exports) {
  2713. Object.defineProperty(exports, "__esModule", { value: true });
  2714. exports.DBRef = exports.isDBRefLike = void 0;
  2715. /** @internal */
  2716. function isDBRefLike(value) {
  2717. return (utils.isObjectLike(value) &&
  2718. value.$id != null &&
  2719. typeof value.$ref === 'string' &&
  2720. (value.$db == null || typeof value.$db === 'string'));
  2721. }
  2722. exports.isDBRefLike = isDBRefLike;
  2723. /**
  2724. * A class representation of the BSON DBRef type.
  2725. * @public
  2726. */
  2727. var DBRef = /** @class */ (function () {
  2728. /**
  2729. * @param collection - the collection name.
  2730. * @param oid - the reference ObjectId.
  2731. * @param db - optional db name, if omitted the reference is local to the current db.
  2732. */
  2733. function DBRef(collection, oid, db, fields) {
  2734. if (!(this instanceof DBRef))
  2735. return new DBRef(collection, oid, db, fields);
  2736. // check if namespace has been provided
  2737. var parts = collection.split('.');
  2738. if (parts.length === 2) {
  2739. db = parts.shift();
  2740. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  2741. collection = parts.shift();
  2742. }
  2743. this.collection = collection;
  2744. this.oid = oid;
  2745. this.db = db;
  2746. this.fields = fields || {};
  2747. }
  2748. Object.defineProperty(DBRef.prototype, "namespace", {
  2749. // Property provided for compatibility with the 1.x parser
  2750. // the 1.x parser used a "namespace" property, while 4.x uses "collection"
  2751. /** @internal */
  2752. get: function () {
  2753. return this.collection;
  2754. },
  2755. set: function (value) {
  2756. this.collection = value;
  2757. },
  2758. enumerable: false,
  2759. configurable: true
  2760. });
  2761. /** @internal */
  2762. DBRef.prototype.toJSON = function () {
  2763. var o = Object.assign({
  2764. $ref: this.collection,
  2765. $id: this.oid
  2766. }, this.fields);
  2767. if (this.db != null)
  2768. o.$db = this.db;
  2769. return o;
  2770. };
  2771. /** @internal */
  2772. DBRef.prototype.toExtendedJSON = function (options) {
  2773. options = options || {};
  2774. var o = {
  2775. $ref: this.collection,
  2776. $id: this.oid
  2777. };
  2778. if (options.legacy) {
  2779. return o;
  2780. }
  2781. if (this.db)
  2782. o.$db = this.db;
  2783. o = Object.assign(o, this.fields);
  2784. return o;
  2785. };
  2786. /** @internal */
  2787. DBRef.fromExtendedJSON = function (doc) {
  2788. var copy = Object.assign({}, doc);
  2789. delete copy.$ref;
  2790. delete copy.$id;
  2791. delete copy.$db;
  2792. return new DBRef(doc.$ref, doc.$id, doc.$db, copy);
  2793. };
  2794. /** @internal */
  2795. DBRef.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  2796. return this.inspect();
  2797. };
  2798. DBRef.prototype.inspect = function () {
  2799. // NOTE: if OID is an ObjectId class it will just print the oid string.
  2800. var oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString();
  2801. return "new DBRef(\"" + this.namespace + "\", new ObjectId(\"" + oid + "\")" + (this.db ? ", \"" + this.db + "\"" : '') + ")";
  2802. };
  2803. return DBRef;
  2804. }());
  2805. exports.DBRef = DBRef;
  2806. Object.defineProperty(DBRef.prototype, '_bsontype', { value: 'DBRef' });
  2807. });
  2808. unwrapExports(db_ref);
  2809. db_ref.DBRef;
  2810. db_ref.isDBRefLike;
  2811. var long_1 = createCommonjsModule(function (module, exports) {
  2812. Object.defineProperty(exports, "__esModule", { value: true });
  2813. exports.Long = void 0;
  2814. /**
  2815. * wasm optimizations, to do native i64 multiplication and divide
  2816. */
  2817. var wasm = undefined;
  2818. try {
  2819. wasm = new WebAssembly.Instance(new WebAssembly.Module(
  2820. // prettier-ignore
  2821. new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports;
  2822. }
  2823. catch (_a) {
  2824. // no wasm support
  2825. }
  2826. var TWO_PWR_16_DBL = 1 << 16;
  2827. var TWO_PWR_24_DBL = 1 << 24;
  2828. var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
  2829. var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
  2830. var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
  2831. /** A cache of the Long representations of small integer values. */
  2832. var INT_CACHE = {};
  2833. /** A cache of the Long representations of small unsigned integer values. */
  2834. var UINT_CACHE = {};
  2835. /**
  2836. * A class representing a 64-bit integer
  2837. * @public
  2838. * @remarks
  2839. * The internal representation of a long is the two given signed, 32-bit values.
  2840. * We use 32-bit pieces because these are the size of integers on which
  2841. * Javascript performs bit-operations. For operations like addition and
  2842. * multiplication, we split each number into 16 bit pieces, which can easily be
  2843. * multiplied within Javascript's floating-point representation without overflow
  2844. * or change in sign.
  2845. * In the algorithms below, we frequently reduce the negative case to the
  2846. * positive case by negating the input(s) and then post-processing the result.
  2847. * Note that we must ALWAYS check specially whether those values are MIN_VALUE
  2848. * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
  2849. * a positive number, it overflows back into a negative). Not handling this
  2850. * case would often result in infinite recursion.
  2851. * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class.
  2852. */
  2853. var Long = /** @class */ (function () {
  2854. /**
  2855. * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
  2856. * See the from* functions below for more convenient ways of constructing Longs.
  2857. *
  2858. * Acceptable signatures are:
  2859. * - Long(low, high, unsigned?)
  2860. * - Long(bigint, unsigned?)
  2861. * - Long(string, unsigned?)
  2862. *
  2863. * @param low - The low (signed) 32 bits of the long
  2864. * @param high - The high (signed) 32 bits of the long
  2865. * @param unsigned - Whether unsigned or not, defaults to signed
  2866. */
  2867. function Long(low, high, unsigned) {
  2868. if (low === void 0) { low = 0; }
  2869. if (!(this instanceof Long))
  2870. return new Long(low, high, unsigned);
  2871. if (typeof low === 'bigint') {
  2872. Object.assign(this, Long.fromBigInt(low, !!high));
  2873. }
  2874. else if (typeof low === 'string') {
  2875. Object.assign(this, Long.fromString(low, !!high));
  2876. }
  2877. else {
  2878. this.low = low | 0;
  2879. this.high = high | 0;
  2880. this.unsigned = !!unsigned;
  2881. }
  2882. Object.defineProperty(this, '__isLong__', {
  2883. value: true,
  2884. configurable: false,
  2885. writable: false,
  2886. enumerable: false
  2887. });
  2888. }
  2889. /**
  2890. * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits.
  2891. * Each is assumed to use 32 bits.
  2892. * @param lowBits - The low 32 bits
  2893. * @param highBits - The high 32 bits
  2894. * @param unsigned - Whether unsigned or not, defaults to signed
  2895. * @returns The corresponding Long value
  2896. */
  2897. Long.fromBits = function (lowBits, highBits, unsigned) {
  2898. return new Long(lowBits, highBits, unsigned);
  2899. };
  2900. /**
  2901. * Returns a Long representing the given 32 bit integer value.
  2902. * @param value - The 32 bit integer in question
  2903. * @param unsigned - Whether unsigned or not, defaults to signed
  2904. * @returns The corresponding Long value
  2905. */
  2906. Long.fromInt = function (value, unsigned) {
  2907. var obj, cachedObj, cache;
  2908. if (unsigned) {
  2909. value >>>= 0;
  2910. if ((cache = 0 <= value && value < 256)) {
  2911. cachedObj = UINT_CACHE[value];
  2912. if (cachedObj)
  2913. return cachedObj;
  2914. }
  2915. obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true);
  2916. if (cache)
  2917. UINT_CACHE[value] = obj;
  2918. return obj;
  2919. }
  2920. else {
  2921. value |= 0;
  2922. if ((cache = -128 <= value && value < 128)) {
  2923. cachedObj = INT_CACHE[value];
  2924. if (cachedObj)
  2925. return cachedObj;
  2926. }
  2927. obj = Long.fromBits(value, value < 0 ? -1 : 0, false);
  2928. if (cache)
  2929. INT_CACHE[value] = obj;
  2930. return obj;
  2931. }
  2932. };
  2933. /**
  2934. * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
  2935. * @param value - The number in question
  2936. * @param unsigned - Whether unsigned or not, defaults to signed
  2937. * @returns The corresponding Long value
  2938. */
  2939. Long.fromNumber = function (value, unsigned) {
  2940. if (isNaN(value))
  2941. return unsigned ? Long.UZERO : Long.ZERO;
  2942. if (unsigned) {
  2943. if (value < 0)
  2944. return Long.UZERO;
  2945. if (value >= TWO_PWR_64_DBL)
  2946. return Long.MAX_UNSIGNED_VALUE;
  2947. }
  2948. else {
  2949. if (value <= -TWO_PWR_63_DBL)
  2950. return Long.MIN_VALUE;
  2951. if (value + 1 >= TWO_PWR_63_DBL)
  2952. return Long.MAX_VALUE;
  2953. }
  2954. if (value < 0)
  2955. return Long.fromNumber(-value, unsigned).neg();
  2956. return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
  2957. };
  2958. /**
  2959. * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
  2960. * @param value - The number in question
  2961. * @param unsigned - Whether unsigned or not, defaults to signed
  2962. * @returns The corresponding Long value
  2963. */
  2964. Long.fromBigInt = function (value, unsigned) {
  2965. return Long.fromString(value.toString(), unsigned);
  2966. };
  2967. /**
  2968. * Returns a Long representation of the given string, written using the specified radix.
  2969. * @param str - The textual representation of the Long
  2970. * @param unsigned - Whether unsigned or not, defaults to signed
  2971. * @param radix - The radix in which the text is written (2-36), defaults to 10
  2972. * @returns The corresponding Long value
  2973. */
  2974. Long.fromString = function (str, unsigned, radix) {
  2975. if (str.length === 0)
  2976. throw Error('empty string');
  2977. if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity')
  2978. return Long.ZERO;
  2979. if (typeof unsigned === 'number') {
  2980. // For goog.math.long compatibility
  2981. (radix = unsigned), (unsigned = false);
  2982. }
  2983. else {
  2984. unsigned = !!unsigned;
  2985. }
  2986. radix = radix || 10;
  2987. if (radix < 2 || 36 < radix)
  2988. throw RangeError('radix');
  2989. var p;
  2990. if ((p = str.indexOf('-')) > 0)
  2991. throw Error('interior hyphen');
  2992. else if (p === 0) {
  2993. return Long.fromString(str.substring(1), unsigned, radix).neg();
  2994. }
  2995. // Do several (8) digits each time through the loop, so as to
  2996. // minimize the calls to the very expensive emulated div.
  2997. var radixToPower = Long.fromNumber(Math.pow(radix, 8));
  2998. var result = Long.ZERO;
  2999. for (var i = 0; i < str.length; i += 8) {
  3000. var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix);
  3001. if (size < 8) {
  3002. var power = Long.fromNumber(Math.pow(radix, size));
  3003. result = result.mul(power).add(Long.fromNumber(value));
  3004. }
  3005. else {
  3006. result = result.mul(radixToPower);
  3007. result = result.add(Long.fromNumber(value));
  3008. }
  3009. }
  3010. result.unsigned = unsigned;
  3011. return result;
  3012. };
  3013. /**
  3014. * Creates a Long from its byte representation.
  3015. * @param bytes - Byte representation
  3016. * @param unsigned - Whether unsigned or not, defaults to signed
  3017. * @param le - Whether little or big endian, defaults to big endian
  3018. * @returns The corresponding Long value
  3019. */
  3020. Long.fromBytes = function (bytes, unsigned, le) {
  3021. return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
  3022. };
  3023. /**
  3024. * Creates a Long from its little endian byte representation.
  3025. * @param bytes - Little endian byte representation
  3026. * @param unsigned - Whether unsigned or not, defaults to signed
  3027. * @returns The corresponding Long value
  3028. */
  3029. Long.fromBytesLE = function (bytes, unsigned) {
  3030. return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned);
  3031. };
  3032. /**
  3033. * Creates a Long from its big endian byte representation.
  3034. * @param bytes - Big endian byte representation
  3035. * @param unsigned - Whether unsigned or not, defaults to signed
  3036. * @returns The corresponding Long value
  3037. */
  3038. Long.fromBytesBE = function (bytes, unsigned) {
  3039. return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned);
  3040. };
  3041. /**
  3042. * Tests if the specified object is a Long.
  3043. */
  3044. // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
  3045. Long.isLong = function (value) {
  3046. return utils.isObjectLike(value) && value['__isLong__'] === true;
  3047. };
  3048. /**
  3049. * Converts the specified value to a Long.
  3050. * @param unsigned - Whether unsigned or not, defaults to signed
  3051. */
  3052. Long.fromValue = function (val, unsigned) {
  3053. if (typeof val === 'number')
  3054. return Long.fromNumber(val, unsigned);
  3055. if (typeof val === 'string')
  3056. return Long.fromString(val, unsigned);
  3057. // Throws for non-objects, converts non-instanceof Long:
  3058. return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);
  3059. };
  3060. /** Returns the sum of this and the specified Long. */
  3061. Long.prototype.add = function (addend) {
  3062. if (!Long.isLong(addend))
  3063. addend = Long.fromValue(addend);
  3064. // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
  3065. var a48 = this.high >>> 16;
  3066. var a32 = this.high & 0xffff;
  3067. var a16 = this.low >>> 16;
  3068. var a00 = this.low & 0xffff;
  3069. var b48 = addend.high >>> 16;
  3070. var b32 = addend.high & 0xffff;
  3071. var b16 = addend.low >>> 16;
  3072. var b00 = addend.low & 0xffff;
  3073. var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  3074. c00 += a00 + b00;
  3075. c16 += c00 >>> 16;
  3076. c00 &= 0xffff;
  3077. c16 += a16 + b16;
  3078. c32 += c16 >>> 16;
  3079. c16 &= 0xffff;
  3080. c32 += a32 + b32;
  3081. c48 += c32 >>> 16;
  3082. c32 &= 0xffff;
  3083. c48 += a48 + b48;
  3084. c48 &= 0xffff;
  3085. return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
  3086. };
  3087. /**
  3088. * Returns the sum of this and the specified Long.
  3089. * @returns Sum
  3090. */
  3091. Long.prototype.and = function (other) {
  3092. if (!Long.isLong(other))
  3093. other = Long.fromValue(other);
  3094. return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned);
  3095. };
  3096. /**
  3097. * Compares this Long's value with the specified's.
  3098. * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater
  3099. */
  3100. Long.prototype.compare = function (other) {
  3101. if (!Long.isLong(other))
  3102. other = Long.fromValue(other);
  3103. if (this.eq(other))
  3104. return 0;
  3105. var thisNeg = this.isNegative(), otherNeg = other.isNegative();
  3106. if (thisNeg && !otherNeg)
  3107. return -1;
  3108. if (!thisNeg && otherNeg)
  3109. return 1;
  3110. // At this point the sign bits are the same
  3111. if (!this.unsigned)
  3112. return this.sub(other).isNegative() ? -1 : 1;
  3113. // Both are positive if at least one is unsigned
  3114. return other.high >>> 0 > this.high >>> 0 ||
  3115. (other.high === this.high && other.low >>> 0 > this.low >>> 0)
  3116. ? -1
  3117. : 1;
  3118. };
  3119. /** This is an alias of {@link Long.compare} */
  3120. Long.prototype.comp = function (other) {
  3121. return this.compare(other);
  3122. };
  3123. /**
  3124. * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned.
  3125. * @returns Quotient
  3126. */
  3127. Long.prototype.divide = function (divisor) {
  3128. if (!Long.isLong(divisor))
  3129. divisor = Long.fromValue(divisor);
  3130. if (divisor.isZero())
  3131. throw Error('division by zero');
  3132. // use wasm support if present
  3133. if (wasm) {
  3134. // guard against signed division overflow: the largest
  3135. // negative number / -1 would be 1 larger than the largest
  3136. // positive number, due to two's complement.
  3137. if (!this.unsigned &&
  3138. this.high === -0x80000000 &&
  3139. divisor.low === -1 &&
  3140. divisor.high === -1) {
  3141. // be consistent with non-wasm code path
  3142. return this;
  3143. }
  3144. var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high);
  3145. return Long.fromBits(low, wasm.get_high(), this.unsigned);
  3146. }
  3147. if (this.isZero())
  3148. return this.unsigned ? Long.UZERO : Long.ZERO;
  3149. var approx, rem, res;
  3150. if (!this.unsigned) {
  3151. // This section is only relevant for signed longs and is derived from the
  3152. // closure library as a whole.
  3153. if (this.eq(Long.MIN_VALUE)) {
  3154. if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE))
  3155. return Long.MIN_VALUE;
  3156. // recall that -MIN_VALUE == MIN_VALUE
  3157. else if (divisor.eq(Long.MIN_VALUE))
  3158. return Long.ONE;
  3159. else {
  3160. // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
  3161. var halfThis = this.shr(1);
  3162. approx = halfThis.div(divisor).shl(1);
  3163. if (approx.eq(Long.ZERO)) {
  3164. return divisor.isNegative() ? Long.ONE : Long.NEG_ONE;
  3165. }
  3166. else {
  3167. rem = this.sub(divisor.mul(approx));
  3168. res = approx.add(rem.div(divisor));
  3169. return res;
  3170. }
  3171. }
  3172. }
  3173. else if (divisor.eq(Long.MIN_VALUE))
  3174. return this.unsigned ? Long.UZERO : Long.ZERO;
  3175. if (this.isNegative()) {
  3176. if (divisor.isNegative())
  3177. return this.neg().div(divisor.neg());
  3178. return this.neg().div(divisor).neg();
  3179. }
  3180. else if (divisor.isNegative())
  3181. return this.div(divisor.neg()).neg();
  3182. res = Long.ZERO;
  3183. }
  3184. else {
  3185. // The algorithm below has not been made for unsigned longs. It's therefore
  3186. // required to take special care of the MSB prior to running it.
  3187. if (!divisor.unsigned)
  3188. divisor = divisor.toUnsigned();
  3189. if (divisor.gt(this))
  3190. return Long.UZERO;
  3191. if (divisor.gt(this.shru(1)))
  3192. // 15 >>> 1 = 7 ; with divisor = 8 ; true
  3193. return Long.UONE;
  3194. res = Long.UZERO;
  3195. }
  3196. // Repeat the following until the remainder is less than other: find a
  3197. // floating-point that approximates remainder / other *from below*, add this
  3198. // into the result, and subtract it from the remainder. It is critical that
  3199. // the approximate value is less than or equal to the real value so that the
  3200. // remainder never becomes negative.
  3201. rem = this;
  3202. while (rem.gte(divisor)) {
  3203. // Approximate the result of division. This may be a little greater or
  3204. // smaller than the actual value.
  3205. approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
  3206. // We will tweak the approximate result by changing it in the 48-th digit or
  3207. // the smallest non-fractional digit, whichever is larger.
  3208. var log2 = Math.ceil(Math.log(approx) / Math.LN2);
  3209. var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);
  3210. // Decrease the approximation until it is smaller than the remainder. Note
  3211. // that if it is too large, the product overflows and is negative.
  3212. var approxRes = Long.fromNumber(approx);
  3213. var approxRem = approxRes.mul(divisor);
  3214. while (approxRem.isNegative() || approxRem.gt(rem)) {
  3215. approx -= delta;
  3216. approxRes = Long.fromNumber(approx, this.unsigned);
  3217. approxRem = approxRes.mul(divisor);
  3218. }
  3219. // We know the answer can't be zero... and actually, zero would cause
  3220. // infinite recursion since we would make no progress.
  3221. if (approxRes.isZero())
  3222. approxRes = Long.ONE;
  3223. res = res.add(approxRes);
  3224. rem = rem.sub(approxRem);
  3225. }
  3226. return res;
  3227. };
  3228. /**This is an alias of {@link Long.divide} */
  3229. Long.prototype.div = function (divisor) {
  3230. return this.divide(divisor);
  3231. };
  3232. /**
  3233. * Tests if this Long's value equals the specified's.
  3234. * @param other - Other value
  3235. */
  3236. Long.prototype.equals = function (other) {
  3237. if (!Long.isLong(other))
  3238. other = Long.fromValue(other);
  3239. if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
  3240. return false;
  3241. return this.high === other.high && this.low === other.low;
  3242. };
  3243. /** This is an alias of {@link Long.equals} */
  3244. Long.prototype.eq = function (other) {
  3245. return this.equals(other);
  3246. };
  3247. /** Gets the high 32 bits as a signed integer. */
  3248. Long.prototype.getHighBits = function () {
  3249. return this.high;
  3250. };
  3251. /** Gets the high 32 bits as an unsigned integer. */
  3252. Long.prototype.getHighBitsUnsigned = function () {
  3253. return this.high >>> 0;
  3254. };
  3255. /** Gets the low 32 bits as a signed integer. */
  3256. Long.prototype.getLowBits = function () {
  3257. return this.low;
  3258. };
  3259. /** Gets the low 32 bits as an unsigned integer. */
  3260. Long.prototype.getLowBitsUnsigned = function () {
  3261. return this.low >>> 0;
  3262. };
  3263. /** Gets the number of bits needed to represent the absolute value of this Long. */
  3264. Long.prototype.getNumBitsAbs = function () {
  3265. if (this.isNegative()) {
  3266. // Unsigned Longs are never negative
  3267. return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
  3268. }
  3269. var val = this.high !== 0 ? this.high : this.low;
  3270. var bit;
  3271. for (bit = 31; bit > 0; bit--)
  3272. if ((val & (1 << bit)) !== 0)
  3273. break;
  3274. return this.high !== 0 ? bit + 33 : bit + 1;
  3275. };
  3276. /** Tests if this Long's value is greater than the specified's. */
  3277. Long.prototype.greaterThan = function (other) {
  3278. return this.comp(other) > 0;
  3279. };
  3280. /** This is an alias of {@link Long.greaterThan} */
  3281. Long.prototype.gt = function (other) {
  3282. return this.greaterThan(other);
  3283. };
  3284. /** Tests if this Long's value is greater than or equal the specified's. */
  3285. Long.prototype.greaterThanOrEqual = function (other) {
  3286. return this.comp(other) >= 0;
  3287. };
  3288. /** This is an alias of {@link Long.greaterThanOrEqual} */
  3289. Long.prototype.gte = function (other) {
  3290. return this.greaterThanOrEqual(other);
  3291. };
  3292. /** This is an alias of {@link Long.greaterThanOrEqual} */
  3293. Long.prototype.ge = function (other) {
  3294. return this.greaterThanOrEqual(other);
  3295. };
  3296. /** Tests if this Long's value is even. */
  3297. Long.prototype.isEven = function () {
  3298. return (this.low & 1) === 0;
  3299. };
  3300. /** Tests if this Long's value is negative. */
  3301. Long.prototype.isNegative = function () {
  3302. return !this.unsigned && this.high < 0;
  3303. };
  3304. /** Tests if this Long's value is odd. */
  3305. Long.prototype.isOdd = function () {
  3306. return (this.low & 1) === 1;
  3307. };
  3308. /** Tests if this Long's value is positive. */
  3309. Long.prototype.isPositive = function () {
  3310. return this.unsigned || this.high >= 0;
  3311. };
  3312. /** Tests if this Long's value equals zero. */
  3313. Long.prototype.isZero = function () {
  3314. return this.high === 0 && this.low === 0;
  3315. };
  3316. /** Tests if this Long's value is less than the specified's. */
  3317. Long.prototype.lessThan = function (other) {
  3318. return this.comp(other) < 0;
  3319. };
  3320. /** This is an alias of {@link Long#lessThan}. */
  3321. Long.prototype.lt = function (other) {
  3322. return this.lessThan(other);
  3323. };
  3324. /** Tests if this Long's value is less than or equal the specified's. */
  3325. Long.prototype.lessThanOrEqual = function (other) {
  3326. return this.comp(other) <= 0;
  3327. };
  3328. /** This is an alias of {@link Long.lessThanOrEqual} */
  3329. Long.prototype.lte = function (other) {
  3330. return this.lessThanOrEqual(other);
  3331. };
  3332. /** Returns this Long modulo the specified. */
  3333. Long.prototype.modulo = function (divisor) {
  3334. if (!Long.isLong(divisor))
  3335. divisor = Long.fromValue(divisor);
  3336. // use wasm support if present
  3337. if (wasm) {
  3338. var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high);
  3339. return Long.fromBits(low, wasm.get_high(), this.unsigned);
  3340. }
  3341. return this.sub(this.div(divisor).mul(divisor));
  3342. };
  3343. /** This is an alias of {@link Long.modulo} */
  3344. Long.prototype.mod = function (divisor) {
  3345. return this.modulo(divisor);
  3346. };
  3347. /** This is an alias of {@link Long.modulo} */
  3348. Long.prototype.rem = function (divisor) {
  3349. return this.modulo(divisor);
  3350. };
  3351. /**
  3352. * Returns the product of this and the specified Long.
  3353. * @param multiplier - Multiplier
  3354. * @returns Product
  3355. */
  3356. Long.prototype.multiply = function (multiplier) {
  3357. if (this.isZero())
  3358. return Long.ZERO;
  3359. if (!Long.isLong(multiplier))
  3360. multiplier = Long.fromValue(multiplier);
  3361. // use wasm support if present
  3362. if (wasm) {
  3363. var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
  3364. return Long.fromBits(low, wasm.get_high(), this.unsigned);
  3365. }
  3366. if (multiplier.isZero())
  3367. return Long.ZERO;
  3368. if (this.eq(Long.MIN_VALUE))
  3369. return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO;
  3370. if (multiplier.eq(Long.MIN_VALUE))
  3371. return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;
  3372. if (this.isNegative()) {
  3373. if (multiplier.isNegative())
  3374. return this.neg().mul(multiplier.neg());
  3375. else
  3376. return this.neg().mul(multiplier).neg();
  3377. }
  3378. else if (multiplier.isNegative())
  3379. return this.mul(multiplier.neg()).neg();
  3380. // If both longs are small, use float multiplication
  3381. if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24))
  3382. return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
  3383. // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
  3384. // We can skip products that would overflow.
  3385. var a48 = this.high >>> 16;
  3386. var a32 = this.high & 0xffff;
  3387. var a16 = this.low >>> 16;
  3388. var a00 = this.low & 0xffff;
  3389. var b48 = multiplier.high >>> 16;
  3390. var b32 = multiplier.high & 0xffff;
  3391. var b16 = multiplier.low >>> 16;
  3392. var b00 = multiplier.low & 0xffff;
  3393. var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  3394. c00 += a00 * b00;
  3395. c16 += c00 >>> 16;
  3396. c00 &= 0xffff;
  3397. c16 += a16 * b00;
  3398. c32 += c16 >>> 16;
  3399. c16 &= 0xffff;
  3400. c16 += a00 * b16;
  3401. c32 += c16 >>> 16;
  3402. c16 &= 0xffff;
  3403. c32 += a32 * b00;
  3404. c48 += c32 >>> 16;
  3405. c32 &= 0xffff;
  3406. c32 += a16 * b16;
  3407. c48 += c32 >>> 16;
  3408. c32 &= 0xffff;
  3409. c32 += a00 * b32;
  3410. c48 += c32 >>> 16;
  3411. c32 &= 0xffff;
  3412. c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
  3413. c48 &= 0xffff;
  3414. return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
  3415. };
  3416. /** This is an alias of {@link Long.multiply} */
  3417. Long.prototype.mul = function (multiplier) {
  3418. return this.multiply(multiplier);
  3419. };
  3420. /** Returns the Negation of this Long's value. */
  3421. Long.prototype.negate = function () {
  3422. if (!this.unsigned && this.eq(Long.MIN_VALUE))
  3423. return Long.MIN_VALUE;
  3424. return this.not().add(Long.ONE);
  3425. };
  3426. /** This is an alias of {@link Long.negate} */
  3427. Long.prototype.neg = function () {
  3428. return this.negate();
  3429. };
  3430. /** Returns the bitwise NOT of this Long. */
  3431. Long.prototype.not = function () {
  3432. return Long.fromBits(~this.low, ~this.high, this.unsigned);
  3433. };
  3434. /** Tests if this Long's value differs from the specified's. */
  3435. Long.prototype.notEquals = function (other) {
  3436. return !this.equals(other);
  3437. };
  3438. /** This is an alias of {@link Long.notEquals} */
  3439. Long.prototype.neq = function (other) {
  3440. return this.notEquals(other);
  3441. };
  3442. /** This is an alias of {@link Long.notEquals} */
  3443. Long.prototype.ne = function (other) {
  3444. return this.notEquals(other);
  3445. };
  3446. /**
  3447. * Returns the bitwise OR of this Long and the specified.
  3448. */
  3449. Long.prototype.or = function (other) {
  3450. if (!Long.isLong(other))
  3451. other = Long.fromValue(other);
  3452. return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned);
  3453. };
  3454. /**
  3455. * Returns this Long with bits shifted to the left by the given amount.
  3456. * @param numBits - Number of bits
  3457. * @returns Shifted Long
  3458. */
  3459. Long.prototype.shiftLeft = function (numBits) {
  3460. if (Long.isLong(numBits))
  3461. numBits = numBits.toInt();
  3462. if ((numBits &= 63) === 0)
  3463. return this;
  3464. else if (numBits < 32)
  3465. return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
  3466. else
  3467. return Long.fromBits(0, this.low << (numBits - 32), this.unsigned);
  3468. };
  3469. /** This is an alias of {@link Long.shiftLeft} */
  3470. Long.prototype.shl = function (numBits) {
  3471. return this.shiftLeft(numBits);
  3472. };
  3473. /**
  3474. * Returns this Long with bits arithmetically shifted to the right by the given amount.
  3475. * @param numBits - Number of bits
  3476. * @returns Shifted Long
  3477. */
  3478. Long.prototype.shiftRight = function (numBits) {
  3479. if (Long.isLong(numBits))
  3480. numBits = numBits.toInt();
  3481. if ((numBits &= 63) === 0)
  3482. return this;
  3483. else if (numBits < 32)
  3484. return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
  3485. else
  3486. return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
  3487. };
  3488. /** This is an alias of {@link Long.shiftRight} */
  3489. Long.prototype.shr = function (numBits) {
  3490. return this.shiftRight(numBits);
  3491. };
  3492. /**
  3493. * Returns this Long with bits logically shifted to the right by the given amount.
  3494. * @param numBits - Number of bits
  3495. * @returns Shifted Long
  3496. */
  3497. Long.prototype.shiftRightUnsigned = function (numBits) {
  3498. if (Long.isLong(numBits))
  3499. numBits = numBits.toInt();
  3500. numBits &= 63;
  3501. if (numBits === 0)
  3502. return this;
  3503. else {
  3504. var high = this.high;
  3505. if (numBits < 32) {
  3506. var low = this.low;
  3507. return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
  3508. }
  3509. else if (numBits === 32)
  3510. return Long.fromBits(high, 0, this.unsigned);
  3511. else
  3512. return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned);
  3513. }
  3514. };
  3515. /** This is an alias of {@link Long.shiftRightUnsigned} */
  3516. Long.prototype.shr_u = function (numBits) {
  3517. return this.shiftRightUnsigned(numBits);
  3518. };
  3519. /** This is an alias of {@link Long.shiftRightUnsigned} */
  3520. Long.prototype.shru = function (numBits) {
  3521. return this.shiftRightUnsigned(numBits);
  3522. };
  3523. /**
  3524. * Returns the difference of this and the specified Long.
  3525. * @param subtrahend - Subtrahend
  3526. * @returns Difference
  3527. */
  3528. Long.prototype.subtract = function (subtrahend) {
  3529. if (!Long.isLong(subtrahend))
  3530. subtrahend = Long.fromValue(subtrahend);
  3531. return this.add(subtrahend.neg());
  3532. };
  3533. /** This is an alias of {@link Long.subtract} */
  3534. Long.prototype.sub = function (subtrahend) {
  3535. return this.subtract(subtrahend);
  3536. };
  3537. /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */
  3538. Long.prototype.toInt = function () {
  3539. return this.unsigned ? this.low >>> 0 : this.low;
  3540. };
  3541. /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */
  3542. Long.prototype.toNumber = function () {
  3543. if (this.unsigned)
  3544. return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
  3545. return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
  3546. };
  3547. /** Converts the Long to a BigInt (arbitrary precision). */
  3548. Long.prototype.toBigInt = function () {
  3549. return BigInt(this.toString());
  3550. };
  3551. /**
  3552. * Converts this Long to its byte representation.
  3553. * @param le - Whether little or big endian, defaults to big endian
  3554. * @returns Byte representation
  3555. */
  3556. Long.prototype.toBytes = function (le) {
  3557. return le ? this.toBytesLE() : this.toBytesBE();
  3558. };
  3559. /**
  3560. * Converts this Long to its little endian byte representation.
  3561. * @returns Little endian byte representation
  3562. */
  3563. Long.prototype.toBytesLE = function () {
  3564. var hi = this.high, lo = this.low;
  3565. return [
  3566. lo & 0xff,
  3567. (lo >>> 8) & 0xff,
  3568. (lo >>> 16) & 0xff,
  3569. lo >>> 24,
  3570. hi & 0xff,
  3571. (hi >>> 8) & 0xff,
  3572. (hi >>> 16) & 0xff,
  3573. hi >>> 24
  3574. ];
  3575. };
  3576. /**
  3577. * Converts this Long to its big endian byte representation.
  3578. * @returns Big endian byte representation
  3579. */
  3580. Long.prototype.toBytesBE = function () {
  3581. var hi = this.high, lo = this.low;
  3582. return [
  3583. hi >>> 24,
  3584. (hi >>> 16) & 0xff,
  3585. (hi >>> 8) & 0xff,
  3586. hi & 0xff,
  3587. lo >>> 24,
  3588. (lo >>> 16) & 0xff,
  3589. (lo >>> 8) & 0xff,
  3590. lo & 0xff
  3591. ];
  3592. };
  3593. /**
  3594. * Converts this Long to signed.
  3595. */
  3596. Long.prototype.toSigned = function () {
  3597. if (!this.unsigned)
  3598. return this;
  3599. return Long.fromBits(this.low, this.high, false);
  3600. };
  3601. /**
  3602. * Converts the Long to a string written in the specified radix.
  3603. * @param radix - Radix (2-36), defaults to 10
  3604. * @throws RangeError If `radix` is out of range
  3605. */
  3606. Long.prototype.toString = function (radix) {
  3607. radix = radix || 10;
  3608. if (radix < 2 || 36 < radix)
  3609. throw RangeError('radix');
  3610. if (this.isZero())
  3611. return '0';
  3612. if (this.isNegative()) {
  3613. // Unsigned Longs are never negative
  3614. if (this.eq(Long.MIN_VALUE)) {
  3615. // We need to change the Long value before it can be negated, so we remove
  3616. // the bottom-most digit in this base and then recurse to do the rest.
  3617. var radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this);
  3618. return div.toString(radix) + rem1.toInt().toString(radix);
  3619. }
  3620. else
  3621. return '-' + this.neg().toString(radix);
  3622. }
  3623. // Do several (6) digits each time through the loop, so as to
  3624. // minimize the calls to the very expensive emulated div.
  3625. var radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned);
  3626. // eslint-disable-next-line @typescript-eslint/no-this-alias
  3627. var rem = this;
  3628. var result = '';
  3629. // eslint-disable-next-line no-constant-condition
  3630. while (true) {
  3631. var remDiv = rem.div(radixToPower);
  3632. var intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0;
  3633. var digits = intval.toString(radix);
  3634. rem = remDiv;
  3635. if (rem.isZero()) {
  3636. return digits + result;
  3637. }
  3638. else {
  3639. while (digits.length < 6)
  3640. digits = '0' + digits;
  3641. result = '' + digits + result;
  3642. }
  3643. }
  3644. };
  3645. /** Converts this Long to unsigned. */
  3646. Long.prototype.toUnsigned = function () {
  3647. if (this.unsigned)
  3648. return this;
  3649. return Long.fromBits(this.low, this.high, true);
  3650. };
  3651. /** Returns the bitwise XOR of this Long and the given one. */
  3652. Long.prototype.xor = function (other) {
  3653. if (!Long.isLong(other))
  3654. other = Long.fromValue(other);
  3655. return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
  3656. };
  3657. /** This is an alias of {@link Long.isZero} */
  3658. Long.prototype.eqz = function () {
  3659. return this.isZero();
  3660. };
  3661. /** This is an alias of {@link Long.lessThanOrEqual} */
  3662. Long.prototype.le = function (other) {
  3663. return this.lessThanOrEqual(other);
  3664. };
  3665. /*
  3666. ****************************************************************
  3667. * BSON SPECIFIC ADDITIONS *
  3668. ****************************************************************
  3669. */
  3670. Long.prototype.toExtendedJSON = function (options) {
  3671. if (options && options.relaxed)
  3672. return this.toNumber();
  3673. return { $numberLong: this.toString() };
  3674. };
  3675. Long.fromExtendedJSON = function (doc, options) {
  3676. var result = Long.fromString(doc.$numberLong);
  3677. return options && options.relaxed ? result.toNumber() : result;
  3678. };
  3679. /** @internal */
  3680. Long.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  3681. return this.inspect();
  3682. };
  3683. Long.prototype.inspect = function () {
  3684. return "new Long(\"" + this.toString() + "\"" + (this.unsigned ? ', true' : '') + ")";
  3685. };
  3686. Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL);
  3687. /** Maximum unsigned value. */
  3688. Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true);
  3689. /** Signed zero */
  3690. Long.ZERO = Long.fromInt(0);
  3691. /** Unsigned zero. */
  3692. Long.UZERO = Long.fromInt(0, true);
  3693. /** Signed one. */
  3694. Long.ONE = Long.fromInt(1);
  3695. /** Unsigned one. */
  3696. Long.UONE = Long.fromInt(1, true);
  3697. /** Signed negative one. */
  3698. Long.NEG_ONE = Long.fromInt(-1);
  3699. /** Maximum signed value. */
  3700. Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false);
  3701. /** Minimum signed value. */
  3702. Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false);
  3703. return Long;
  3704. }());
  3705. exports.Long = Long;
  3706. Object.defineProperty(Long.prototype, '__isLong__', { value: true });
  3707. Object.defineProperty(Long.prototype, '_bsontype', { value: 'Long' });
  3708. });
  3709. unwrapExports(long_1);
  3710. long_1.Long;
  3711. var decimal128 = createCommonjsModule(function (module, exports) {
  3712. Object.defineProperty(exports, "__esModule", { value: true });
  3713. exports.Decimal128 = void 0;
  3714. var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
  3715. var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
  3716. var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
  3717. var EXPONENT_MAX = 6111;
  3718. var EXPONENT_MIN = -6176;
  3719. var EXPONENT_BIAS = 6176;
  3720. var MAX_DIGITS = 34;
  3721. // Nan value bits as 32 bit values (due to lack of longs)
  3722. var NAN_BUFFER = [
  3723. 0x7c,
  3724. 0x00,
  3725. 0x00,
  3726. 0x00,
  3727. 0x00,
  3728. 0x00,
  3729. 0x00,
  3730. 0x00,
  3731. 0x00,
  3732. 0x00,
  3733. 0x00,
  3734. 0x00,
  3735. 0x00,
  3736. 0x00,
  3737. 0x00,
  3738. 0x00
  3739. ].reverse();
  3740. // Infinity value bits 32 bit values (due to lack of longs)
  3741. var INF_NEGATIVE_BUFFER = [
  3742. 0xf8,
  3743. 0x00,
  3744. 0x00,
  3745. 0x00,
  3746. 0x00,
  3747. 0x00,
  3748. 0x00,
  3749. 0x00,
  3750. 0x00,
  3751. 0x00,
  3752. 0x00,
  3753. 0x00,
  3754. 0x00,
  3755. 0x00,
  3756. 0x00,
  3757. 0x00
  3758. ].reverse();
  3759. var INF_POSITIVE_BUFFER = [
  3760. 0x78,
  3761. 0x00,
  3762. 0x00,
  3763. 0x00,
  3764. 0x00,
  3765. 0x00,
  3766. 0x00,
  3767. 0x00,
  3768. 0x00,
  3769. 0x00,
  3770. 0x00,
  3771. 0x00,
  3772. 0x00,
  3773. 0x00,
  3774. 0x00,
  3775. 0x00
  3776. ].reverse();
  3777. var EXPONENT_REGEX = /^([-+])?(\d+)?$/;
  3778. // Extract least significant 5 bits
  3779. var COMBINATION_MASK = 0x1f;
  3780. // Extract least significant 14 bits
  3781. var EXPONENT_MASK = 0x3fff;
  3782. // Value of combination field for Inf
  3783. var COMBINATION_INFINITY = 30;
  3784. // Value of combination field for NaN
  3785. var COMBINATION_NAN = 31;
  3786. // Detect if the value is a digit
  3787. function isDigit(value) {
  3788. return !isNaN(parseInt(value, 10));
  3789. }
  3790. // Divide two uint128 values
  3791. function divideu128(value) {
  3792. var DIVISOR = long_1.Long.fromNumber(1000 * 1000 * 1000);
  3793. var _rem = long_1.Long.fromNumber(0);
  3794. if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
  3795. return { quotient: value, rem: _rem };
  3796. }
  3797. for (var i = 0; i <= 3; i++) {
  3798. // Adjust remainder to match value of next dividend
  3799. _rem = _rem.shiftLeft(32);
  3800. // Add the divided to _rem
  3801. _rem = _rem.add(new long_1.Long(value.parts[i], 0));
  3802. value.parts[i] = _rem.div(DIVISOR).low;
  3803. _rem = _rem.modulo(DIVISOR);
  3804. }
  3805. return { quotient: value, rem: _rem };
  3806. }
  3807. // Multiply two Long values and return the 128 bit value
  3808. function multiply64x2(left, right) {
  3809. if (!left && !right) {
  3810. return { high: long_1.Long.fromNumber(0), low: long_1.Long.fromNumber(0) };
  3811. }
  3812. var leftHigh = left.shiftRightUnsigned(32);
  3813. var leftLow = new long_1.Long(left.getLowBits(), 0);
  3814. var rightHigh = right.shiftRightUnsigned(32);
  3815. var rightLow = new long_1.Long(right.getLowBits(), 0);
  3816. var productHigh = leftHigh.multiply(rightHigh);
  3817. var productMid = leftHigh.multiply(rightLow);
  3818. var productMid2 = leftLow.multiply(rightHigh);
  3819. var productLow = leftLow.multiply(rightLow);
  3820. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  3821. productMid = new long_1.Long(productMid.getLowBits(), 0)
  3822. .add(productMid2)
  3823. .add(productLow.shiftRightUnsigned(32));
  3824. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  3825. productLow = productMid.shiftLeft(32).add(new long_1.Long(productLow.getLowBits(), 0));
  3826. // Return the 128 bit result
  3827. return { high: productHigh, low: productLow };
  3828. }
  3829. function lessThan(left, right) {
  3830. // Make values unsigned
  3831. var uhleft = left.high >>> 0;
  3832. var uhright = right.high >>> 0;
  3833. // Compare high bits first
  3834. if (uhleft < uhright) {
  3835. return true;
  3836. }
  3837. else if (uhleft === uhright) {
  3838. var ulleft = left.low >>> 0;
  3839. var ulright = right.low >>> 0;
  3840. if (ulleft < ulright)
  3841. return true;
  3842. }
  3843. return false;
  3844. }
  3845. function invalidErr(string, message) {
  3846. throw new TypeError("\"" + string + "\" is not a valid Decimal128 string - " + message);
  3847. }
  3848. /**
  3849. * A class representation of the BSON Decimal128 type.
  3850. * @public
  3851. */
  3852. var Decimal128 = /** @class */ (function () {
  3853. /**
  3854. * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order,
  3855. * or a string representation as returned by .toString()
  3856. */
  3857. function Decimal128(bytes) {
  3858. if (!(this instanceof Decimal128))
  3859. return new Decimal128(bytes);
  3860. if (typeof bytes === 'string') {
  3861. this.bytes = Decimal128.fromString(bytes).bytes;
  3862. }
  3863. else {
  3864. this.bytes = bytes;
  3865. }
  3866. }
  3867. /**
  3868. * Create a Decimal128 instance from a string representation
  3869. *
  3870. * @param representation - a numeric string representation.
  3871. */
  3872. Decimal128.fromString = function (representation) {
  3873. // Parse state tracking
  3874. var isNegative = false;
  3875. var sawRadix = false;
  3876. var foundNonZero = false;
  3877. // Total number of significant digits (no leading or trailing zero)
  3878. var significantDigits = 0;
  3879. // Total number of significand digits read
  3880. var nDigitsRead = 0;
  3881. // Total number of digits (no leading zeros)
  3882. var nDigits = 0;
  3883. // The number of the digits after radix
  3884. var radixPosition = 0;
  3885. // The index of the first non-zero in *str*
  3886. var firstNonZero = 0;
  3887. // Digits Array
  3888. var digits = [0];
  3889. // The number of digits in digits
  3890. var nDigitsStored = 0;
  3891. // Insertion pointer for digits
  3892. var digitsInsert = 0;
  3893. // The index of the first non-zero digit
  3894. var firstDigit = 0;
  3895. // The index of the last digit
  3896. var lastDigit = 0;
  3897. // Exponent
  3898. var exponent = 0;
  3899. // loop index over array
  3900. var i = 0;
  3901. // The high 17 digits of the significand
  3902. var significandHigh = new long_1.Long(0, 0);
  3903. // The low 17 digits of the significand
  3904. var significandLow = new long_1.Long(0, 0);
  3905. // The biased exponent
  3906. var biasedExponent = 0;
  3907. // Read index
  3908. var index = 0;
  3909. // Naively prevent against REDOS attacks.
  3910. // TODO: implementing a custom parsing for this, or refactoring the regex would yield
  3911. // further gains.
  3912. if (representation.length >= 7000) {
  3913. throw new TypeError('' + representation + ' not a valid Decimal128 string');
  3914. }
  3915. // Results
  3916. var stringMatch = representation.match(PARSE_STRING_REGEXP);
  3917. var infMatch = representation.match(PARSE_INF_REGEXP);
  3918. var nanMatch = representation.match(PARSE_NAN_REGEXP);
  3919. // Validate the string
  3920. if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) {
  3921. throw new TypeError('' + representation + ' not a valid Decimal128 string');
  3922. }
  3923. if (stringMatch) {
  3924. // full_match = stringMatch[0]
  3925. // sign = stringMatch[1]
  3926. var unsignedNumber = stringMatch[2];
  3927. // stringMatch[3] is undefined if a whole number (ex "1", 12")
  3928. // but defined if a number w/ decimal in it (ex "1.0, 12.2")
  3929. var e = stringMatch[4];
  3930. var expSign = stringMatch[5];
  3931. var expNumber = stringMatch[6];
  3932. // they provided e, but didn't give an exponent number. for ex "1e"
  3933. if (e && expNumber === undefined)
  3934. invalidErr(representation, 'missing exponent power');
  3935. // they provided e, but didn't give a number before it. for ex "e1"
  3936. if (e && unsignedNumber === undefined)
  3937. invalidErr(representation, 'missing exponent base');
  3938. if (e === undefined && (expSign || expNumber)) {
  3939. invalidErr(representation, 'missing e before exponent');
  3940. }
  3941. }
  3942. // Get the negative or positive sign
  3943. if (representation[index] === '+' || representation[index] === '-') {
  3944. isNegative = representation[index++] === '-';
  3945. }
  3946. // Check if user passed Infinity or NaN
  3947. if (!isDigit(representation[index]) && representation[index] !== '.') {
  3948. if (representation[index] === 'i' || representation[index] === 'I') {
  3949. return new Decimal128(buffer.Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER));
  3950. }
  3951. else if (representation[index] === 'N') {
  3952. return new Decimal128(buffer.Buffer.from(NAN_BUFFER));
  3953. }
  3954. }
  3955. // Read all the digits
  3956. while (isDigit(representation[index]) || representation[index] === '.') {
  3957. if (representation[index] === '.') {
  3958. if (sawRadix)
  3959. invalidErr(representation, 'contains multiple periods');
  3960. sawRadix = true;
  3961. index = index + 1;
  3962. continue;
  3963. }
  3964. if (nDigitsStored < 34) {
  3965. if (representation[index] !== '0' || foundNonZero) {
  3966. if (!foundNonZero) {
  3967. firstNonZero = nDigitsRead;
  3968. }
  3969. foundNonZero = true;
  3970. // Only store 34 digits
  3971. digits[digitsInsert++] = parseInt(representation[index], 10);
  3972. nDigitsStored = nDigitsStored + 1;
  3973. }
  3974. }
  3975. if (foundNonZero)
  3976. nDigits = nDigits + 1;
  3977. if (sawRadix)
  3978. radixPosition = radixPosition + 1;
  3979. nDigitsRead = nDigitsRead + 1;
  3980. index = index + 1;
  3981. }
  3982. if (sawRadix && !nDigitsRead)
  3983. throw new TypeError('' + representation + ' not a valid Decimal128 string');
  3984. // Read exponent if exists
  3985. if (representation[index] === 'e' || representation[index] === 'E') {
  3986. // Read exponent digits
  3987. var match = representation.substr(++index).match(EXPONENT_REGEX);
  3988. // No digits read
  3989. if (!match || !match[2])
  3990. return new Decimal128(buffer.Buffer.from(NAN_BUFFER));
  3991. // Get exponent
  3992. exponent = parseInt(match[0], 10);
  3993. // Adjust the index
  3994. index = index + match[0].length;
  3995. }
  3996. // Return not a number
  3997. if (representation[index])
  3998. return new Decimal128(buffer.Buffer.from(NAN_BUFFER));
  3999. // Done reading input
  4000. // Find first non-zero digit in digits
  4001. firstDigit = 0;
  4002. if (!nDigitsStored) {
  4003. firstDigit = 0;
  4004. lastDigit = 0;
  4005. digits[0] = 0;
  4006. nDigits = 1;
  4007. nDigitsStored = 1;
  4008. significantDigits = 0;
  4009. }
  4010. else {
  4011. lastDigit = nDigitsStored - 1;
  4012. significantDigits = nDigits;
  4013. if (significantDigits !== 1) {
  4014. while (representation[firstNonZero + significantDigits - 1] === '0') {
  4015. significantDigits = significantDigits - 1;
  4016. }
  4017. }
  4018. }
  4019. // Normalization of exponent
  4020. // Correct exponent based on radix position, and shift significand as needed
  4021. // to represent user input
  4022. // Overflow prevention
  4023. if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) {
  4024. exponent = EXPONENT_MIN;
  4025. }
  4026. else {
  4027. exponent = exponent - radixPosition;
  4028. }
  4029. // Attempt to normalize the exponent
  4030. while (exponent > EXPONENT_MAX) {
  4031. // Shift exponent to significand and decrease
  4032. lastDigit = lastDigit + 1;
  4033. if (lastDigit - firstDigit > MAX_DIGITS) {
  4034. // Check if we have a zero then just hard clamp, otherwise fail
  4035. var digitsString = digits.join('');
  4036. if (digitsString.match(/^0+$/)) {
  4037. exponent = EXPONENT_MAX;
  4038. break;
  4039. }
  4040. invalidErr(representation, 'overflow');
  4041. }
  4042. exponent = exponent - 1;
  4043. }
  4044. while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
  4045. // Shift last digit. can only do this if < significant digits than # stored.
  4046. if (lastDigit === 0 && significantDigits < nDigitsStored) {
  4047. exponent = EXPONENT_MIN;
  4048. significantDigits = 0;
  4049. break;
  4050. }
  4051. if (nDigitsStored < nDigits) {
  4052. // adjust to match digits not stored
  4053. nDigits = nDigits - 1;
  4054. }
  4055. else {
  4056. // adjust to round
  4057. lastDigit = lastDigit - 1;
  4058. }
  4059. if (exponent < EXPONENT_MAX) {
  4060. exponent = exponent + 1;
  4061. }
  4062. else {
  4063. // Check if we have a zero then just hard clamp, otherwise fail
  4064. var digitsString = digits.join('');
  4065. if (digitsString.match(/^0+$/)) {
  4066. exponent = EXPONENT_MAX;
  4067. break;
  4068. }
  4069. invalidErr(representation, 'overflow');
  4070. }
  4071. }
  4072. // Round
  4073. // We've normalized the exponent, but might still need to round.
  4074. if (lastDigit - firstDigit + 1 < significantDigits) {
  4075. var endOfString = nDigitsRead;
  4076. // If we have seen a radix point, 'string' is 1 longer than we have
  4077. // documented with ndigits_read, so inc the position of the first nonzero
  4078. // digit and the position that digits are read to.
  4079. if (sawRadix) {
  4080. firstNonZero = firstNonZero + 1;
  4081. endOfString = endOfString + 1;
  4082. }
  4083. // if negative, we need to increment again to account for - sign at start.
  4084. if (isNegative) {
  4085. firstNonZero = firstNonZero + 1;
  4086. endOfString = endOfString + 1;
  4087. }
  4088. var roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
  4089. var roundBit = 0;
  4090. if (roundDigit >= 5) {
  4091. roundBit = 1;
  4092. if (roundDigit === 5) {
  4093. roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0;
  4094. for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) {
  4095. if (parseInt(representation[i], 10)) {
  4096. roundBit = 1;
  4097. break;
  4098. }
  4099. }
  4100. }
  4101. }
  4102. if (roundBit) {
  4103. var dIdx = lastDigit;
  4104. for (; dIdx >= 0; dIdx--) {
  4105. if (++digits[dIdx] > 9) {
  4106. digits[dIdx] = 0;
  4107. // overflowed most significant digit
  4108. if (dIdx === 0) {
  4109. if (exponent < EXPONENT_MAX) {
  4110. exponent = exponent + 1;
  4111. digits[dIdx] = 1;
  4112. }
  4113. else {
  4114. return new Decimal128(buffer.Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER));
  4115. }
  4116. }
  4117. }
  4118. }
  4119. }
  4120. }
  4121. // Encode significand
  4122. // The high 17 digits of the significand
  4123. significandHigh = long_1.Long.fromNumber(0);
  4124. // The low 17 digits of the significand
  4125. significandLow = long_1.Long.fromNumber(0);
  4126. // read a zero
  4127. if (significantDigits === 0) {
  4128. significandHigh = long_1.Long.fromNumber(0);
  4129. significandLow = long_1.Long.fromNumber(0);
  4130. }
  4131. else if (lastDigit - firstDigit < 17) {
  4132. var dIdx = firstDigit;
  4133. significandLow = long_1.Long.fromNumber(digits[dIdx++]);
  4134. significandHigh = new long_1.Long(0, 0);
  4135. for (; dIdx <= lastDigit; dIdx++) {
  4136. significandLow = significandLow.multiply(long_1.Long.fromNumber(10));
  4137. significandLow = significandLow.add(long_1.Long.fromNumber(digits[dIdx]));
  4138. }
  4139. }
  4140. else {
  4141. var dIdx = firstDigit;
  4142. significandHigh = long_1.Long.fromNumber(digits[dIdx++]);
  4143. for (; dIdx <= lastDigit - 17; dIdx++) {
  4144. significandHigh = significandHigh.multiply(long_1.Long.fromNumber(10));
  4145. significandHigh = significandHigh.add(long_1.Long.fromNumber(digits[dIdx]));
  4146. }
  4147. significandLow = long_1.Long.fromNumber(digits[dIdx++]);
  4148. for (; dIdx <= lastDigit; dIdx++) {
  4149. significandLow = significandLow.multiply(long_1.Long.fromNumber(10));
  4150. significandLow = significandLow.add(long_1.Long.fromNumber(digits[dIdx]));
  4151. }
  4152. }
  4153. var significand = multiply64x2(significandHigh, long_1.Long.fromString('100000000000000000'));
  4154. significand.low = significand.low.add(significandLow);
  4155. if (lessThan(significand.low, significandLow)) {
  4156. significand.high = significand.high.add(long_1.Long.fromNumber(1));
  4157. }
  4158. // Biased exponent
  4159. biasedExponent = exponent + EXPONENT_BIAS;
  4160. var dec = { low: long_1.Long.fromNumber(0), high: long_1.Long.fromNumber(0) };
  4161. // Encode combination, exponent, and significand.
  4162. if (significand.high.shiftRightUnsigned(49).and(long_1.Long.fromNumber(1)).equals(long_1.Long.fromNumber(1))) {
  4163. // Encode '11' into bits 1 to 3
  4164. dec.high = dec.high.or(long_1.Long.fromNumber(0x3).shiftLeft(61));
  4165. dec.high = dec.high.or(long_1.Long.fromNumber(biasedExponent).and(long_1.Long.fromNumber(0x3fff).shiftLeft(47)));
  4166. dec.high = dec.high.or(significand.high.and(long_1.Long.fromNumber(0x7fffffffffff)));
  4167. }
  4168. else {
  4169. dec.high = dec.high.or(long_1.Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49));
  4170. dec.high = dec.high.or(significand.high.and(long_1.Long.fromNumber(0x1ffffffffffff)));
  4171. }
  4172. dec.low = significand.low;
  4173. // Encode sign
  4174. if (isNegative) {
  4175. dec.high = dec.high.or(long_1.Long.fromString('9223372036854775808'));
  4176. }
  4177. // Encode into a buffer
  4178. var buffer$1 = buffer.Buffer.alloc(16);
  4179. index = 0;
  4180. // Encode the low 64 bits of the decimal
  4181. // Encode low bits
  4182. buffer$1[index++] = dec.low.low & 0xff;
  4183. buffer$1[index++] = (dec.low.low >> 8) & 0xff;
  4184. buffer$1[index++] = (dec.low.low >> 16) & 0xff;
  4185. buffer$1[index++] = (dec.low.low >> 24) & 0xff;
  4186. // Encode high bits
  4187. buffer$1[index++] = dec.low.high & 0xff;
  4188. buffer$1[index++] = (dec.low.high >> 8) & 0xff;
  4189. buffer$1[index++] = (dec.low.high >> 16) & 0xff;
  4190. buffer$1[index++] = (dec.low.high >> 24) & 0xff;
  4191. // Encode the high 64 bits of the decimal
  4192. // Encode low bits
  4193. buffer$1[index++] = dec.high.low & 0xff;
  4194. buffer$1[index++] = (dec.high.low >> 8) & 0xff;
  4195. buffer$1[index++] = (dec.high.low >> 16) & 0xff;
  4196. buffer$1[index++] = (dec.high.low >> 24) & 0xff;
  4197. // Encode high bits
  4198. buffer$1[index++] = dec.high.high & 0xff;
  4199. buffer$1[index++] = (dec.high.high >> 8) & 0xff;
  4200. buffer$1[index++] = (dec.high.high >> 16) & 0xff;
  4201. buffer$1[index++] = (dec.high.high >> 24) & 0xff;
  4202. // Return the new Decimal128
  4203. return new Decimal128(buffer$1);
  4204. };
  4205. /** Create a string representation of the raw Decimal128 value */
  4206. Decimal128.prototype.toString = function () {
  4207. // Note: bits in this routine are referred to starting at 0,
  4208. // from the sign bit, towards the coefficient.
  4209. // decoded biased exponent (14 bits)
  4210. var biased_exponent;
  4211. // the number of significand digits
  4212. var significand_digits = 0;
  4213. // the base-10 digits in the significand
  4214. var significand = new Array(36);
  4215. for (var i = 0; i < significand.length; i++)
  4216. significand[i] = 0;
  4217. // read pointer into significand
  4218. var index = 0;
  4219. // true if the number is zero
  4220. var is_zero = false;
  4221. // the most significant significand bits (50-46)
  4222. var significand_msb;
  4223. // temporary storage for significand decoding
  4224. var significand128 = { parts: [0, 0, 0, 0] };
  4225. // indexing variables
  4226. var j, k;
  4227. // Output string
  4228. var string = [];
  4229. // Unpack index
  4230. index = 0;
  4231. // Buffer reference
  4232. var buffer = this.bytes;
  4233. // Unpack the low 64bits into a long
  4234. // bits 96 - 127
  4235. var low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  4236. // bits 64 - 95
  4237. var midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  4238. // Unpack the high 64bits into a long
  4239. // bits 32 - 63
  4240. var midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  4241. // bits 0 - 31
  4242. var high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  4243. // Unpack index
  4244. index = 0;
  4245. // Create the state of the decimal
  4246. var dec = {
  4247. low: new long_1.Long(low, midl),
  4248. high: new long_1.Long(midh, high)
  4249. };
  4250. if (dec.high.lessThan(long_1.Long.ZERO)) {
  4251. string.push('-');
  4252. }
  4253. // Decode combination field and exponent
  4254. // bits 1 - 5
  4255. var combination = (high >> 26) & COMBINATION_MASK;
  4256. if (combination >> 3 === 3) {
  4257. // Check for 'special' values
  4258. if (combination === COMBINATION_INFINITY) {
  4259. return string.join('') + 'Infinity';
  4260. }
  4261. else if (combination === COMBINATION_NAN) {
  4262. return 'NaN';
  4263. }
  4264. else {
  4265. biased_exponent = (high >> 15) & EXPONENT_MASK;
  4266. significand_msb = 0x08 + ((high >> 14) & 0x01);
  4267. }
  4268. }
  4269. else {
  4270. significand_msb = (high >> 14) & 0x07;
  4271. biased_exponent = (high >> 17) & EXPONENT_MASK;
  4272. }
  4273. // unbiased exponent
  4274. var exponent = biased_exponent - EXPONENT_BIAS;
  4275. // Create string of significand digits
  4276. // Convert the 114-bit binary number represented by
  4277. // (significand_high, significand_low) to at most 34 decimal
  4278. // digits through modulo and division.
  4279. significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14);
  4280. significand128.parts[1] = midh;
  4281. significand128.parts[2] = midl;
  4282. significand128.parts[3] = low;
  4283. if (significand128.parts[0] === 0 &&
  4284. significand128.parts[1] === 0 &&
  4285. significand128.parts[2] === 0 &&
  4286. significand128.parts[3] === 0) {
  4287. is_zero = true;
  4288. }
  4289. else {
  4290. for (k = 3; k >= 0; k--) {
  4291. var least_digits = 0;
  4292. // Perform the divide
  4293. var result = divideu128(significand128);
  4294. significand128 = result.quotient;
  4295. least_digits = result.rem.low;
  4296. // We now have the 9 least significant digits (in base 2).
  4297. // Convert and output to string.
  4298. if (!least_digits)
  4299. continue;
  4300. for (j = 8; j >= 0; j--) {
  4301. // significand[k * 9 + j] = Math.round(least_digits % 10);
  4302. significand[k * 9 + j] = least_digits % 10;
  4303. // least_digits = Math.round(least_digits / 10);
  4304. least_digits = Math.floor(least_digits / 10);
  4305. }
  4306. }
  4307. }
  4308. // Output format options:
  4309. // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd
  4310. // Regular - ddd.ddd
  4311. if (is_zero) {
  4312. significand_digits = 1;
  4313. significand[index] = 0;
  4314. }
  4315. else {
  4316. significand_digits = 36;
  4317. while (!significand[index]) {
  4318. significand_digits = significand_digits - 1;
  4319. index = index + 1;
  4320. }
  4321. }
  4322. // the exponent if scientific notation is used
  4323. var scientific_exponent = significand_digits - 1 + exponent;
  4324. // The scientific exponent checks are dictated by the string conversion
  4325. // specification and are somewhat arbitrary cutoffs.
  4326. //
  4327. // We must check exponent > 0, because if this is the case, the number
  4328. // has trailing zeros. However, we *cannot* output these trailing zeros,
  4329. // because doing so would change the precision of the value, and would
  4330. // change stored data if the string converted number is round tripped.
  4331. if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
  4332. // Scientific format
  4333. // if there are too many significant digits, we should just be treating numbers
  4334. // as + or - 0 and using the non-scientific exponent (this is for the "invalid
  4335. // representation should be treated as 0/-0" spec cases in decimal128-1.json)
  4336. if (significand_digits > 34) {
  4337. string.push("" + 0);
  4338. if (exponent > 0)
  4339. string.push('E+' + exponent);
  4340. else if (exponent < 0)
  4341. string.push('E' + exponent);
  4342. return string.join('');
  4343. }
  4344. string.push("" + significand[index++]);
  4345. significand_digits = significand_digits - 1;
  4346. if (significand_digits) {
  4347. string.push('.');
  4348. }
  4349. for (var i = 0; i < significand_digits; i++) {
  4350. string.push("" + significand[index++]);
  4351. }
  4352. // Exponent
  4353. string.push('E');
  4354. if (scientific_exponent > 0) {
  4355. string.push('+' + scientific_exponent);
  4356. }
  4357. else {
  4358. string.push("" + scientific_exponent);
  4359. }
  4360. }
  4361. else {
  4362. // Regular format with no decimal place
  4363. if (exponent >= 0) {
  4364. for (var i = 0; i < significand_digits; i++) {
  4365. string.push("" + significand[index++]);
  4366. }
  4367. }
  4368. else {
  4369. var radix_position = significand_digits + exponent;
  4370. // non-zero digits before radix
  4371. if (radix_position > 0) {
  4372. for (var i = 0; i < radix_position; i++) {
  4373. string.push("" + significand[index++]);
  4374. }
  4375. }
  4376. else {
  4377. string.push('0');
  4378. }
  4379. string.push('.');
  4380. // add leading zeros after radix
  4381. while (radix_position++ < 0) {
  4382. string.push('0');
  4383. }
  4384. for (var i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) {
  4385. string.push("" + significand[index++]);
  4386. }
  4387. }
  4388. }
  4389. return string.join('');
  4390. };
  4391. Decimal128.prototype.toJSON = function () {
  4392. return { $numberDecimal: this.toString() };
  4393. };
  4394. /** @internal */
  4395. Decimal128.prototype.toExtendedJSON = function () {
  4396. return { $numberDecimal: this.toString() };
  4397. };
  4398. /** @internal */
  4399. Decimal128.fromExtendedJSON = function (doc) {
  4400. return Decimal128.fromString(doc.$numberDecimal);
  4401. };
  4402. /** @internal */
  4403. Decimal128.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  4404. return this.inspect();
  4405. };
  4406. Decimal128.prototype.inspect = function () {
  4407. return "new Decimal128(\"" + this.toString() + "\")";
  4408. };
  4409. return Decimal128;
  4410. }());
  4411. exports.Decimal128 = Decimal128;
  4412. Object.defineProperty(Decimal128.prototype, '_bsontype', { value: 'Decimal128' });
  4413. });
  4414. unwrapExports(decimal128);
  4415. decimal128.Decimal128;
  4416. var double_1 = createCommonjsModule(function (module, exports) {
  4417. Object.defineProperty(exports, "__esModule", { value: true });
  4418. exports.Double = void 0;
  4419. /**
  4420. * A class representation of the BSON Double type.
  4421. * @public
  4422. */
  4423. var Double = /** @class */ (function () {
  4424. /**
  4425. * Create a Double type
  4426. *
  4427. * @param value - the number we want to represent as a double.
  4428. */
  4429. function Double(value) {
  4430. if (!(this instanceof Double))
  4431. return new Double(value);
  4432. if (value instanceof Number) {
  4433. value = value.valueOf();
  4434. }
  4435. this.value = +value;
  4436. }
  4437. /**
  4438. * Access the number value.
  4439. *
  4440. * @returns returns the wrapped double number.
  4441. */
  4442. Double.prototype.valueOf = function () {
  4443. return this.value;
  4444. };
  4445. /** @internal */
  4446. Double.prototype.toJSON = function () {
  4447. return this.value;
  4448. };
  4449. /** @internal */
  4450. Double.prototype.toExtendedJSON = function (options) {
  4451. if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) {
  4452. return this.value;
  4453. }
  4454. // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user
  4455. // explicitly provided `-0` then we need to ensure the sign makes it into the output
  4456. if (Object.is(Math.sign(this.value), -0)) {
  4457. return { $numberDouble: "-" + this.value.toFixed(1) };
  4458. }
  4459. var $numberDouble;
  4460. if (Number.isInteger(this.value)) {
  4461. $numberDouble = this.value.toFixed(1);
  4462. if ($numberDouble.length >= 13) {
  4463. $numberDouble = this.value.toExponential(13).toUpperCase();
  4464. }
  4465. }
  4466. else {
  4467. $numberDouble = this.value.toString();
  4468. }
  4469. return { $numberDouble: $numberDouble };
  4470. };
  4471. /** @internal */
  4472. Double.fromExtendedJSON = function (doc, options) {
  4473. var doubleValue = parseFloat(doc.$numberDouble);
  4474. return options && options.relaxed ? doubleValue : new Double(doubleValue);
  4475. };
  4476. /** @internal */
  4477. Double.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  4478. return this.inspect();
  4479. };
  4480. Double.prototype.inspect = function () {
  4481. var eJSON = this.toExtendedJSON();
  4482. return "new Double(" + eJSON.$numberDouble + ")";
  4483. };
  4484. return Double;
  4485. }());
  4486. exports.Double = Double;
  4487. Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' });
  4488. });
  4489. unwrapExports(double_1);
  4490. double_1.Double;
  4491. var int_32 = createCommonjsModule(function (module, exports) {
  4492. Object.defineProperty(exports, "__esModule", { value: true });
  4493. exports.Int32 = void 0;
  4494. /**
  4495. * A class representation of a BSON Int32 type.
  4496. * @public
  4497. */
  4498. var Int32 = /** @class */ (function () {
  4499. /**
  4500. * Create an Int32 type
  4501. *
  4502. * @param value - the number we want to represent as an int32.
  4503. */
  4504. function Int32(value) {
  4505. if (!(this instanceof Int32))
  4506. return new Int32(value);
  4507. if (value instanceof Number) {
  4508. value = value.valueOf();
  4509. }
  4510. this.value = +value;
  4511. }
  4512. /**
  4513. * Access the number value.
  4514. *
  4515. * @returns returns the wrapped int32 number.
  4516. */
  4517. Int32.prototype.valueOf = function () {
  4518. return this.value;
  4519. };
  4520. /** @internal */
  4521. Int32.prototype.toJSON = function () {
  4522. return this.value;
  4523. };
  4524. /** @internal */
  4525. Int32.prototype.toExtendedJSON = function (options) {
  4526. if (options && (options.relaxed || options.legacy))
  4527. return this.value;
  4528. return { $numberInt: this.value.toString() };
  4529. };
  4530. /** @internal */
  4531. Int32.fromExtendedJSON = function (doc, options) {
  4532. return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt);
  4533. };
  4534. /** @internal */
  4535. Int32.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  4536. return this.inspect();
  4537. };
  4538. Int32.prototype.inspect = function () {
  4539. return "new Int32(" + this.valueOf() + ")";
  4540. };
  4541. return Int32;
  4542. }());
  4543. exports.Int32 = Int32;
  4544. Object.defineProperty(Int32.prototype, '_bsontype', { value: 'Int32' });
  4545. });
  4546. unwrapExports(int_32);
  4547. int_32.Int32;
  4548. var max_key = createCommonjsModule(function (module, exports) {
  4549. Object.defineProperty(exports, "__esModule", { value: true });
  4550. exports.MaxKey = void 0;
  4551. /**
  4552. * A class representation of the BSON MaxKey type.
  4553. * @public
  4554. */
  4555. var MaxKey = /** @class */ (function () {
  4556. function MaxKey() {
  4557. if (!(this instanceof MaxKey))
  4558. return new MaxKey();
  4559. }
  4560. /** @internal */
  4561. MaxKey.prototype.toExtendedJSON = function () {
  4562. return { $maxKey: 1 };
  4563. };
  4564. /** @internal */
  4565. MaxKey.fromExtendedJSON = function () {
  4566. return new MaxKey();
  4567. };
  4568. /** @internal */
  4569. MaxKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  4570. return this.inspect();
  4571. };
  4572. MaxKey.prototype.inspect = function () {
  4573. return 'new MaxKey()';
  4574. };
  4575. return MaxKey;
  4576. }());
  4577. exports.MaxKey = MaxKey;
  4578. Object.defineProperty(MaxKey.prototype, '_bsontype', { value: 'MaxKey' });
  4579. });
  4580. unwrapExports(max_key);
  4581. max_key.MaxKey;
  4582. var min_key = createCommonjsModule(function (module, exports) {
  4583. Object.defineProperty(exports, "__esModule", { value: true });
  4584. exports.MinKey = void 0;
  4585. /**
  4586. * A class representation of the BSON MinKey type.
  4587. * @public
  4588. */
  4589. var MinKey = /** @class */ (function () {
  4590. function MinKey() {
  4591. if (!(this instanceof MinKey))
  4592. return new MinKey();
  4593. }
  4594. /** @internal */
  4595. MinKey.prototype.toExtendedJSON = function () {
  4596. return { $minKey: 1 };
  4597. };
  4598. /** @internal */
  4599. MinKey.fromExtendedJSON = function () {
  4600. return new MinKey();
  4601. };
  4602. /** @internal */
  4603. MinKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  4604. return this.inspect();
  4605. };
  4606. MinKey.prototype.inspect = function () {
  4607. return 'new MinKey()';
  4608. };
  4609. return MinKey;
  4610. }());
  4611. exports.MinKey = MinKey;
  4612. Object.defineProperty(MinKey.prototype, '_bsontype', { value: 'MinKey' });
  4613. });
  4614. unwrapExports(min_key);
  4615. min_key.MinKey;
  4616. var objectid = createCommonjsModule(function (module, exports) {
  4617. Object.defineProperty(exports, "__esModule", { value: true });
  4618. exports.ObjectId = void 0;
  4619. // Regular expression that checks for hex value
  4620. var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$');
  4621. // Unique sequence for the current process (initialized on first use)
  4622. var PROCESS_UNIQUE = null;
  4623. var kId = Symbol('id');
  4624. /**
  4625. * A class representation of the BSON ObjectId type.
  4626. * @public
  4627. */
  4628. var ObjectId = /** @class */ (function () {
  4629. /**
  4630. * Create an ObjectId type
  4631. *
  4632. * @param id - Can be a 24 character hex string, 12 byte binary Buffer, or a number.
  4633. */
  4634. function ObjectId(id) {
  4635. if (!(this instanceof ObjectId))
  4636. return new ObjectId(id);
  4637. // Duck-typing to support ObjectId from different npm packages
  4638. if (id instanceof ObjectId) {
  4639. this[kId] = id.id;
  4640. this.__id = id.__id;
  4641. }
  4642. if (typeof id === 'object' && id && 'id' in id) {
  4643. if ('toHexString' in id && typeof id.toHexString === 'function') {
  4644. this[kId] = buffer.Buffer.from(id.toHexString(), 'hex');
  4645. }
  4646. else {
  4647. this[kId] = typeof id.id === 'string' ? buffer.Buffer.from(id.id) : id.id;
  4648. }
  4649. }
  4650. // The most common use case (blank id, new objectId instance)
  4651. if (id == null || typeof id === 'number') {
  4652. // Generate a new id
  4653. this[kId] = ObjectId.generate(typeof id === 'number' ? id : undefined);
  4654. // If we are caching the hex string
  4655. if (ObjectId.cacheHexString) {
  4656. this.__id = this.id.toString('hex');
  4657. }
  4658. }
  4659. if (ArrayBuffer.isView(id) && id.byteLength === 12) {
  4660. this[kId] = ensure_buffer.ensureBuffer(id);
  4661. }
  4662. if (typeof id === 'string') {
  4663. if (id.length === 12) {
  4664. var bytes = buffer.Buffer.from(id);
  4665. if (bytes.byteLength === 12) {
  4666. this[kId] = bytes;
  4667. }
  4668. }
  4669. else if (id.length === 24 && checkForHexRegExp.test(id)) {
  4670. this[kId] = buffer.Buffer.from(id, 'hex');
  4671. }
  4672. else {
  4673. throw new TypeError('Argument passed in must be a Buffer or string of 12 bytes or a string of 24 hex characters');
  4674. }
  4675. }
  4676. if (ObjectId.cacheHexString) {
  4677. this.__id = this.id.toString('hex');
  4678. }
  4679. }
  4680. Object.defineProperty(ObjectId.prototype, "id", {
  4681. /**
  4682. * The ObjectId bytes
  4683. * @readonly
  4684. */
  4685. get: function () {
  4686. return this[kId];
  4687. },
  4688. set: function (value) {
  4689. this[kId] = value;
  4690. if (ObjectId.cacheHexString) {
  4691. this.__id = value.toString('hex');
  4692. }
  4693. },
  4694. enumerable: false,
  4695. configurable: true
  4696. });
  4697. Object.defineProperty(ObjectId.prototype, "generationTime", {
  4698. /**
  4699. * The generation time of this ObjectId instance
  4700. * @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch
  4701. */
  4702. get: function () {
  4703. return this.id.readInt32BE(0);
  4704. },
  4705. set: function (value) {
  4706. // Encode time into first 4 bytes
  4707. this.id.writeUInt32BE(value, 0);
  4708. },
  4709. enumerable: false,
  4710. configurable: true
  4711. });
  4712. /** Returns the ObjectId id as a 24 character hex string representation */
  4713. ObjectId.prototype.toHexString = function () {
  4714. if (ObjectId.cacheHexString && this.__id) {
  4715. return this.__id;
  4716. }
  4717. var hexString = this.id.toString('hex');
  4718. if (ObjectId.cacheHexString && !this.__id) {
  4719. this.__id = hexString;
  4720. }
  4721. return hexString;
  4722. };
  4723. /**
  4724. * Update the ObjectId index
  4725. * @privateRemarks
  4726. * Used in generating new ObjectId's on the driver
  4727. * @internal
  4728. */
  4729. ObjectId.getInc = function () {
  4730. return (ObjectId.index = (ObjectId.index + 1) % 0xffffff);
  4731. };
  4732. /**
  4733. * Generate a 12 byte id buffer used in ObjectId's
  4734. *
  4735. * @param time - pass in a second based timestamp.
  4736. */
  4737. ObjectId.generate = function (time) {
  4738. if ('number' !== typeof time) {
  4739. time = ~~(Date.now() / 1000);
  4740. }
  4741. var inc = ObjectId.getInc();
  4742. var buffer$1 = buffer.Buffer.alloc(12);
  4743. // 4-byte timestamp
  4744. buffer$1.writeUInt32BE(time, 0);
  4745. // set PROCESS_UNIQUE if yet not initialized
  4746. if (PROCESS_UNIQUE === null) {
  4747. PROCESS_UNIQUE = utils.randomBytes(5);
  4748. }
  4749. // 5-byte process unique
  4750. buffer$1[4] = PROCESS_UNIQUE[0];
  4751. buffer$1[5] = PROCESS_UNIQUE[1];
  4752. buffer$1[6] = PROCESS_UNIQUE[2];
  4753. buffer$1[7] = PROCESS_UNIQUE[3];
  4754. buffer$1[8] = PROCESS_UNIQUE[4];
  4755. // 3-byte counter
  4756. buffer$1[11] = inc & 0xff;
  4757. buffer$1[10] = (inc >> 8) & 0xff;
  4758. buffer$1[9] = (inc >> 16) & 0xff;
  4759. return buffer$1;
  4760. };
  4761. /**
  4762. * Converts the id into a 24 character hex string for printing
  4763. *
  4764. * @param format - The Buffer toString format parameter.
  4765. * @internal
  4766. */
  4767. ObjectId.prototype.toString = function (format) {
  4768. // Is the id a buffer then use the buffer toString method to return the format
  4769. if (format)
  4770. return this.id.toString(format);
  4771. return this.toHexString();
  4772. };
  4773. /**
  4774. * Converts to its JSON the 24 character hex string representation.
  4775. * @internal
  4776. */
  4777. ObjectId.prototype.toJSON = function () {
  4778. return this.toHexString();
  4779. };
  4780. /**
  4781. * Compares the equality of this ObjectId with `otherID`.
  4782. *
  4783. * @param otherId - ObjectId instance to compare against.
  4784. */
  4785. ObjectId.prototype.equals = function (otherId) {
  4786. if (otherId === undefined || otherId === null) {
  4787. return false;
  4788. }
  4789. if (otherId instanceof ObjectId) {
  4790. return this.toString() === otherId.toString();
  4791. }
  4792. if (typeof otherId === 'string' &&
  4793. ObjectId.isValid(otherId) &&
  4794. otherId.length === 12 &&
  4795. utils.isUint8Array(this.id)) {
  4796. return otherId === buffer.Buffer.prototype.toString.call(this.id, 'latin1');
  4797. }
  4798. if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) {
  4799. return otherId.toLowerCase() === this.toHexString();
  4800. }
  4801. if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) {
  4802. return buffer.Buffer.from(otherId).equals(this.id);
  4803. }
  4804. if (typeof otherId === 'object' &&
  4805. 'toHexString' in otherId &&
  4806. typeof otherId.toHexString === 'function') {
  4807. return otherId.toHexString() === this.toHexString();
  4808. }
  4809. return false;
  4810. };
  4811. /** Returns the generation date (accurate up to the second) that this ID was generated. */
  4812. ObjectId.prototype.getTimestamp = function () {
  4813. var timestamp = new Date();
  4814. var time = this.id.readUInt32BE(0);
  4815. timestamp.setTime(Math.floor(time) * 1000);
  4816. return timestamp;
  4817. };
  4818. /** @internal */
  4819. ObjectId.createPk = function () {
  4820. return new ObjectId();
  4821. };
  4822. /**
  4823. * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId.
  4824. *
  4825. * @param time - an integer number representing a number of seconds.
  4826. */
  4827. ObjectId.createFromTime = function (time) {
  4828. var buffer$1 = buffer.Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
  4829. // Encode time into first 4 bytes
  4830. buffer$1.writeUInt32BE(time, 0);
  4831. // Return the new objectId
  4832. return new ObjectId(buffer$1);
  4833. };
  4834. /**
  4835. * Creates an ObjectId from a hex string representation of an ObjectId.
  4836. *
  4837. * @param hexString - create a ObjectId from a passed in 24 character hexstring.
  4838. */
  4839. ObjectId.createFromHexString = function (hexString) {
  4840. // Throw an error if it's not a valid setup
  4841. if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) {
  4842. throw new TypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters');
  4843. }
  4844. return new ObjectId(buffer.Buffer.from(hexString, 'hex'));
  4845. };
  4846. /**
  4847. * Checks if a value is a valid bson ObjectId
  4848. *
  4849. * @param id - ObjectId instance to validate.
  4850. */
  4851. ObjectId.isValid = function (id) {
  4852. if (id == null)
  4853. return false;
  4854. if (typeof id === 'number') {
  4855. return true;
  4856. }
  4857. if (typeof id === 'string') {
  4858. return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id));
  4859. }
  4860. if (id instanceof ObjectId) {
  4861. return true;
  4862. }
  4863. if (utils.isUint8Array(id) && id.length === 12) {
  4864. return true;
  4865. }
  4866. // Duck-Typing detection of ObjectId like objects
  4867. if (typeof id === 'object' && 'toHexString' in id && typeof id.toHexString === 'function') {
  4868. if (typeof id.id === 'string') {
  4869. return id.id.length === 12;
  4870. }
  4871. return id.toHexString().length === 24 && checkForHexRegExp.test(id.id.toString('hex'));
  4872. }
  4873. return false;
  4874. };
  4875. /** @internal */
  4876. ObjectId.prototype.toExtendedJSON = function () {
  4877. if (this.toHexString)
  4878. return { $oid: this.toHexString() };
  4879. return { $oid: this.toString('hex') };
  4880. };
  4881. /** @internal */
  4882. ObjectId.fromExtendedJSON = function (doc) {
  4883. return new ObjectId(doc.$oid);
  4884. };
  4885. /**
  4886. * Converts to a string representation of this Id.
  4887. *
  4888. * @returns return the 24 character hex string representation.
  4889. * @internal
  4890. */
  4891. ObjectId.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  4892. return this.inspect();
  4893. };
  4894. ObjectId.prototype.inspect = function () {
  4895. return "new ObjectId(\"" + this.toHexString() + "\")";
  4896. };
  4897. /** @internal */
  4898. ObjectId.index = ~~(Math.random() * 0xffffff);
  4899. return ObjectId;
  4900. }());
  4901. exports.ObjectId = ObjectId;
  4902. // Deprecated methods
  4903. Object.defineProperty(ObjectId.prototype, 'generate', {
  4904. value: utils.deprecate(function (time) { return ObjectId.generate(time); }, 'Please use the static `ObjectId.generate(time)` instead')
  4905. });
  4906. Object.defineProperty(ObjectId.prototype, 'getInc', {
  4907. value: utils.deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead')
  4908. });
  4909. Object.defineProperty(ObjectId.prototype, 'get_inc', {
  4910. value: utils.deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead')
  4911. });
  4912. Object.defineProperty(ObjectId, 'get_inc', {
  4913. value: utils.deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead')
  4914. });
  4915. Object.defineProperty(ObjectId.prototype, '_bsontype', { value: 'ObjectID' });
  4916. });
  4917. unwrapExports(objectid);
  4918. objectid.ObjectId;
  4919. var regexp = createCommonjsModule(function (module, exports) {
  4920. Object.defineProperty(exports, "__esModule", { value: true });
  4921. exports.BSONRegExp = void 0;
  4922. function alphabetize(str) {
  4923. return str.split('').sort().join('');
  4924. }
  4925. /**
  4926. * A class representation of the BSON RegExp type.
  4927. * @public
  4928. */
  4929. var BSONRegExp = /** @class */ (function () {
  4930. /**
  4931. * @param pattern - The regular expression pattern to match
  4932. * @param options - The regular expression options
  4933. */
  4934. function BSONRegExp(pattern, options) {
  4935. if (!(this instanceof BSONRegExp))
  4936. return new BSONRegExp(pattern, options);
  4937. this.pattern = pattern;
  4938. this.options = alphabetize(options !== null && options !== void 0 ? options : '');
  4939. // Validate options
  4940. for (var i = 0; i < this.options.length; i++) {
  4941. if (!(this.options[i] === 'i' ||
  4942. this.options[i] === 'm' ||
  4943. this.options[i] === 'x' ||
  4944. this.options[i] === 'l' ||
  4945. this.options[i] === 's' ||
  4946. this.options[i] === 'u')) {
  4947. throw new Error("The regular expression option [" + this.options[i] + "] is not supported");
  4948. }
  4949. }
  4950. }
  4951. BSONRegExp.parseOptions = function (options) {
  4952. return options ? options.split('').sort().join('') : '';
  4953. };
  4954. /** @internal */
  4955. BSONRegExp.prototype.toExtendedJSON = function (options) {
  4956. options = options || {};
  4957. if (options.legacy) {
  4958. return { $regex: this.pattern, $options: this.options };
  4959. }
  4960. return { $regularExpression: { pattern: this.pattern, options: this.options } };
  4961. };
  4962. /** @internal */
  4963. BSONRegExp.fromExtendedJSON = function (doc) {
  4964. if ('$regex' in doc) {
  4965. if (typeof doc.$regex !== 'string') {
  4966. // This is for $regex query operators that have extended json values.
  4967. if (doc.$regex._bsontype === 'BSONRegExp') {
  4968. return doc;
  4969. }
  4970. }
  4971. else {
  4972. return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options));
  4973. }
  4974. }
  4975. if ('$regularExpression' in doc) {
  4976. return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options));
  4977. }
  4978. throw new TypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc));
  4979. };
  4980. return BSONRegExp;
  4981. }());
  4982. exports.BSONRegExp = BSONRegExp;
  4983. Object.defineProperty(BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' });
  4984. });
  4985. unwrapExports(regexp);
  4986. regexp.BSONRegExp;
  4987. var symbol = createCommonjsModule(function (module, exports) {
  4988. Object.defineProperty(exports, "__esModule", { value: true });
  4989. exports.BSONSymbol = void 0;
  4990. /**
  4991. * A class representation of the BSON Symbol type.
  4992. * @public
  4993. */
  4994. var BSONSymbol = /** @class */ (function () {
  4995. /**
  4996. * @param value - the string representing the symbol.
  4997. */
  4998. function BSONSymbol(value) {
  4999. if (!(this instanceof BSONSymbol))
  5000. return new BSONSymbol(value);
  5001. this.value = value;
  5002. }
  5003. /** Access the wrapped string value. */
  5004. BSONSymbol.prototype.valueOf = function () {
  5005. return this.value;
  5006. };
  5007. /** @internal */
  5008. BSONSymbol.prototype.toString = function () {
  5009. return this.value;
  5010. };
  5011. /** @internal */
  5012. BSONSymbol.prototype.inspect = function () {
  5013. return "new BSONSymbol(\"" + this.value + "\")";
  5014. };
  5015. /** @internal */
  5016. BSONSymbol.prototype.toJSON = function () {
  5017. return this.value;
  5018. };
  5019. /** @internal */
  5020. BSONSymbol.prototype.toExtendedJSON = function () {
  5021. return { $symbol: this.value };
  5022. };
  5023. /** @internal */
  5024. BSONSymbol.fromExtendedJSON = function (doc) {
  5025. return new BSONSymbol(doc.$symbol);
  5026. };
  5027. /** @internal */
  5028. BSONSymbol.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  5029. return this.inspect();
  5030. };
  5031. return BSONSymbol;
  5032. }());
  5033. exports.BSONSymbol = BSONSymbol;
  5034. Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' });
  5035. });
  5036. unwrapExports(symbol);
  5037. symbol.BSONSymbol;
  5038. /*! *****************************************************************************
  5039. Copyright (c) Microsoft Corporation.
  5040. Permission to use, copy, modify, and/or distribute this software for any
  5041. purpose with or without fee is hereby granted.
  5042. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  5043. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  5044. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  5045. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  5046. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  5047. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  5048. PERFORMANCE OF THIS SOFTWARE.
  5049. ***************************************************************************** */
  5050. /* global Reflect, Promise */
  5051. var _extendStatics = function extendStatics(d, b) {
  5052. _extendStatics = Object.setPrototypeOf || {
  5053. __proto__: []
  5054. } instanceof Array && function (d, b) {
  5055. d.__proto__ = b;
  5056. } || function (d, b) {
  5057. for (var p in b) {
  5058. if (b.hasOwnProperty(p)) d[p] = b[p];
  5059. }
  5060. };
  5061. return _extendStatics(d, b);
  5062. };
  5063. function __extends(d, b) {
  5064. _extendStatics(d, b);
  5065. function __() {
  5066. this.constructor = d;
  5067. }
  5068. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  5069. }
  5070. var _assign = function __assign() {
  5071. _assign = Object.assign || function __assign(t) {
  5072. for (var s, i = 1, n = arguments.length; i < n; i++) {
  5073. s = arguments[i];
  5074. for (var p in s) {
  5075. if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
  5076. }
  5077. }
  5078. return t;
  5079. };
  5080. return _assign.apply(this, arguments);
  5081. };
  5082. function __rest(s, e) {
  5083. var t = {};
  5084. for (var p in s) {
  5085. if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
  5086. }
  5087. if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  5088. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
  5089. }
  5090. return t;
  5091. }
  5092. function __decorate(decorators, target, key, desc) {
  5093. var c = arguments.length,
  5094. r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
  5095. d;
  5096. if ((typeof Reflect === "undefined" ? "undefined" : babelHelpers["typeof"](Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) {
  5097. if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5098. }
  5099. return c > 3 && r && Object.defineProperty(target, key, r), r;
  5100. }
  5101. function __param(paramIndex, decorator) {
  5102. return function (target, key) {
  5103. decorator(target, key, paramIndex);
  5104. };
  5105. }
  5106. function __metadata(metadataKey, metadataValue) {
  5107. if ((typeof Reflect === "undefined" ? "undefined" : babelHelpers["typeof"](Reflect)) === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
  5108. }
  5109. function __awaiter(thisArg, _arguments, P, generator) {
  5110. function adopt(value) {
  5111. return value instanceof P ? value : new P(function (resolve) {
  5112. resolve(value);
  5113. });
  5114. }
  5115. return new (P || (P = Promise))(function (resolve, reject) {
  5116. function fulfilled(value) {
  5117. try {
  5118. step(generator.next(value));
  5119. } catch (e) {
  5120. reject(e);
  5121. }
  5122. }
  5123. function rejected(value) {
  5124. try {
  5125. step(generator["throw"](value));
  5126. } catch (e) {
  5127. reject(e);
  5128. }
  5129. }
  5130. function step(result) {
  5131. result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
  5132. }
  5133. step((generator = generator.apply(thisArg, _arguments || [])).next());
  5134. });
  5135. }
  5136. function __generator(thisArg, body) {
  5137. var _ = {
  5138. label: 0,
  5139. sent: function sent() {
  5140. if (t[0] & 1) throw t[1];
  5141. return t[1];
  5142. },
  5143. trys: [],
  5144. ops: []
  5145. },
  5146. f,
  5147. y,
  5148. t,
  5149. g;
  5150. return g = {
  5151. next: verb(0),
  5152. "throw": verb(1),
  5153. "return": verb(2)
  5154. }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
  5155. return this;
  5156. }), g;
  5157. function verb(n) {
  5158. return function (v) {
  5159. return step([n, v]);
  5160. };
  5161. }
  5162. function step(op) {
  5163. if (f) throw new TypeError("Generator is already executing.");
  5164. while (_) {
  5165. try {
  5166. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  5167. if (y = 0, t) op = [op[0] & 2, t.value];
  5168. switch (op[0]) {
  5169. case 0:
  5170. case 1:
  5171. t = op;
  5172. break;
  5173. case 4:
  5174. _.label++;
  5175. return {
  5176. value: op[1],
  5177. done: false
  5178. };
  5179. case 5:
  5180. _.label++;
  5181. y = op[1];
  5182. op = [0];
  5183. continue;
  5184. case 7:
  5185. op = _.ops.pop();
  5186. _.trys.pop();
  5187. continue;
  5188. default:
  5189. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
  5190. _ = 0;
  5191. continue;
  5192. }
  5193. if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
  5194. _.label = op[1];
  5195. break;
  5196. }
  5197. if (op[0] === 6 && _.label < t[1]) {
  5198. _.label = t[1];
  5199. t = op;
  5200. break;
  5201. }
  5202. if (t && _.label < t[2]) {
  5203. _.label = t[2];
  5204. _.ops.push(op);
  5205. break;
  5206. }
  5207. if (t[2]) _.ops.pop();
  5208. _.trys.pop();
  5209. continue;
  5210. }
  5211. op = body.call(thisArg, _);
  5212. } catch (e) {
  5213. op = [6, e];
  5214. y = 0;
  5215. } finally {
  5216. f = t = 0;
  5217. }
  5218. }
  5219. if (op[0] & 5) throw op[1];
  5220. return {
  5221. value: op[0] ? op[1] : void 0,
  5222. done: true
  5223. };
  5224. }
  5225. }
  5226. function __createBinding(o, m, k, k2) {
  5227. if (k2 === undefined) k2 = k;
  5228. o[k2] = m[k];
  5229. }
  5230. function __exportStar(m, exports) {
  5231. for (var p in m) {
  5232. if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p];
  5233. }
  5234. }
  5235. function __values(o) {
  5236. var s = typeof Symbol === "function" && Symbol.iterator,
  5237. m = s && o[s],
  5238. i = 0;
  5239. if (m) return m.call(o);
  5240. if (o && typeof o.length === "number") return {
  5241. next: function next() {
  5242. if (o && i >= o.length) o = void 0;
  5243. return {
  5244. value: o && o[i++],
  5245. done: !o
  5246. };
  5247. }
  5248. };
  5249. throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
  5250. }
  5251. function __read(o, n) {
  5252. var m = typeof Symbol === "function" && o[Symbol.iterator];
  5253. if (!m) return o;
  5254. var i = m.call(o),
  5255. r,
  5256. ar = [],
  5257. e;
  5258. try {
  5259. while ((n === void 0 || n-- > 0) && !(r = i.next()).done) {
  5260. ar.push(r.value);
  5261. }
  5262. } catch (error) {
  5263. e = {
  5264. error: error
  5265. };
  5266. } finally {
  5267. try {
  5268. if (r && !r.done && (m = i["return"])) m.call(i);
  5269. } finally {
  5270. if (e) throw e.error;
  5271. }
  5272. }
  5273. return ar;
  5274. }
  5275. function __spread() {
  5276. for (var ar = [], i = 0; i < arguments.length; i++) {
  5277. ar = ar.concat(__read(arguments[i]));
  5278. }
  5279. return ar;
  5280. }
  5281. function __spreadArrays() {
  5282. for (var s = 0, i = 0, il = arguments.length; i < il; i++) {
  5283. s += arguments[i].length;
  5284. }
  5285. for (var r = Array(s), k = 0, i = 0; i < il; i++) {
  5286. for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) {
  5287. r[k] = a[j];
  5288. }
  5289. }
  5290. return r;
  5291. }
  5292. function __await(v) {
  5293. return this instanceof __await ? (this.v = v, this) : new __await(v);
  5294. }
  5295. function __asyncGenerator(thisArg, _arguments, generator) {
  5296. if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  5297. var g = generator.apply(thisArg, _arguments || []),
  5298. i,
  5299. q = [];
  5300. return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () {
  5301. return this;
  5302. }, i;
  5303. function verb(n) {
  5304. if (g[n]) i[n] = function (v) {
  5305. return new Promise(function (a, b) {
  5306. q.push([n, v, a, b]) > 1 || resume(n, v);
  5307. });
  5308. };
  5309. }
  5310. function resume(n, v) {
  5311. try {
  5312. step(g[n](v));
  5313. } catch (e) {
  5314. settle(q[0][3], e);
  5315. }
  5316. }
  5317. function step(r) {
  5318. r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
  5319. }
  5320. function fulfill(value) {
  5321. resume("next", value);
  5322. }
  5323. function reject(value) {
  5324. resume("throw", value);
  5325. }
  5326. function settle(f, v) {
  5327. if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
  5328. }
  5329. }
  5330. function __asyncDelegator(o) {
  5331. var i, p;
  5332. return i = {}, verb("next"), verb("throw", function (e) {
  5333. throw e;
  5334. }), verb("return"), i[Symbol.iterator] = function () {
  5335. return this;
  5336. }, i;
  5337. function verb(n, f) {
  5338. i[n] = o[n] ? function (v) {
  5339. return (p = !p) ? {
  5340. value: __await(o[n](v)),
  5341. done: n === "return"
  5342. } : f ? f(v) : v;
  5343. } : f;
  5344. }
  5345. }
  5346. function __asyncValues(o) {
  5347. if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  5348. var m = o[Symbol.asyncIterator],
  5349. i;
  5350. return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () {
  5351. return this;
  5352. }, i);
  5353. function verb(n) {
  5354. i[n] = o[n] && function (v) {
  5355. return new Promise(function (resolve, reject) {
  5356. v = o[n](v), settle(resolve, reject, v.done, v.value);
  5357. });
  5358. };
  5359. }
  5360. function settle(resolve, reject, d, v) {
  5361. Promise.resolve(v).then(function (v) {
  5362. resolve({
  5363. value: v,
  5364. done: d
  5365. });
  5366. }, reject);
  5367. }
  5368. }
  5369. function __makeTemplateObject(cooked, raw) {
  5370. if (Object.defineProperty) {
  5371. Object.defineProperty(cooked, "raw", {
  5372. value: raw
  5373. });
  5374. } else {
  5375. cooked.raw = raw;
  5376. }
  5377. return cooked;
  5378. }
  5379. function __importStar(mod) {
  5380. if (mod && mod.__esModule) return mod;
  5381. var result = {};
  5382. if (mod != null) for (var k in mod) {
  5383. if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
  5384. }
  5385. result["default"] = mod;
  5386. return result;
  5387. }
  5388. function __importDefault(mod) {
  5389. return mod && mod.__esModule ? mod : {
  5390. "default": mod
  5391. };
  5392. }
  5393. function __classPrivateFieldGet(receiver, privateMap) {
  5394. if (!privateMap.has(receiver)) {
  5395. throw new TypeError("attempted to get private field on non-instance");
  5396. }
  5397. return privateMap.get(receiver);
  5398. }
  5399. function __classPrivateFieldSet(receiver, privateMap, value) {
  5400. if (!privateMap.has(receiver)) {
  5401. throw new TypeError("attempted to set private field on non-instance");
  5402. }
  5403. privateMap.set(receiver, value);
  5404. return value;
  5405. }
  5406. var tslib_es6 = /*#__PURE__*/Object.freeze({
  5407. __proto__: null,
  5408. __extends: __extends,
  5409. get __assign () { return _assign; },
  5410. __rest: __rest,
  5411. __decorate: __decorate,
  5412. __param: __param,
  5413. __metadata: __metadata,
  5414. __awaiter: __awaiter,
  5415. __generator: __generator,
  5416. __createBinding: __createBinding,
  5417. __exportStar: __exportStar,
  5418. __values: __values,
  5419. __read: __read,
  5420. __spread: __spread,
  5421. __spreadArrays: __spreadArrays,
  5422. __await: __await,
  5423. __asyncGenerator: __asyncGenerator,
  5424. __asyncDelegator: __asyncDelegator,
  5425. __asyncValues: __asyncValues,
  5426. __makeTemplateObject: __makeTemplateObject,
  5427. __importStar: __importStar,
  5428. __importDefault: __importDefault,
  5429. __classPrivateFieldGet: __classPrivateFieldGet,
  5430. __classPrivateFieldSet: __classPrivateFieldSet
  5431. });
  5432. var timestamp = createCommonjsModule(function (module, exports) {
  5433. Object.defineProperty(exports, "__esModule", { value: true });
  5434. exports.Timestamp = exports.LongWithoutOverridesClass = void 0;
  5435. /** @public */
  5436. exports.LongWithoutOverridesClass = long_1.Long;
  5437. /** @public */
  5438. var Timestamp = /** @class */ (function (_super) {
  5439. tslib_es6.__extends(Timestamp, _super);
  5440. function Timestamp(low, high) {
  5441. var _this = this;
  5442. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5443. ///@ts-expect-error
  5444. if (!(_this instanceof Timestamp))
  5445. return new Timestamp(low, high);
  5446. if (long_1.Long.isLong(low)) {
  5447. _this = _super.call(this, low.low, low.high, true) || this;
  5448. }
  5449. else {
  5450. _this = _super.call(this, low, high, true) || this;
  5451. }
  5452. Object.defineProperty(_this, '_bsontype', {
  5453. value: 'Timestamp',
  5454. writable: false,
  5455. configurable: false,
  5456. enumerable: false
  5457. });
  5458. return _this;
  5459. }
  5460. Timestamp.prototype.toJSON = function () {
  5461. return {
  5462. $timestamp: this.toString()
  5463. };
  5464. };
  5465. /** Returns a Timestamp represented by the given (32-bit) integer value. */
  5466. Timestamp.fromInt = function (value) {
  5467. return new Timestamp(long_1.Long.fromInt(value, true));
  5468. };
  5469. /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */
  5470. Timestamp.fromNumber = function (value) {
  5471. return new Timestamp(long_1.Long.fromNumber(value, true));
  5472. };
  5473. /**
  5474. * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits.
  5475. *
  5476. * @param lowBits - the low 32-bits.
  5477. * @param highBits - the high 32-bits.
  5478. */
  5479. Timestamp.fromBits = function (lowBits, highBits) {
  5480. return new Timestamp(lowBits, highBits);
  5481. };
  5482. /**
  5483. * Returns a Timestamp from the given string, optionally using the given radix.
  5484. *
  5485. * @param str - the textual representation of the Timestamp.
  5486. * @param optRadix - the radix in which the text is written.
  5487. */
  5488. Timestamp.fromString = function (str, optRadix) {
  5489. return new Timestamp(long_1.Long.fromString(str, true, optRadix));
  5490. };
  5491. /** @internal */
  5492. Timestamp.prototype.toExtendedJSON = function () {
  5493. return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } };
  5494. };
  5495. /** @internal */
  5496. Timestamp.fromExtendedJSON = function (doc) {
  5497. return new Timestamp(doc.$timestamp.i, doc.$timestamp.t);
  5498. };
  5499. /** @internal */
  5500. Timestamp.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  5501. return this.inspect();
  5502. };
  5503. Timestamp.prototype.inspect = function () {
  5504. return "new Timestamp(" + this.getLowBits().toString() + ", " + this.getHighBits().toString() + ")";
  5505. };
  5506. Timestamp.MAX_VALUE = long_1.Long.MAX_UNSIGNED_VALUE;
  5507. return Timestamp;
  5508. }(exports.LongWithoutOverridesClass));
  5509. exports.Timestamp = Timestamp;
  5510. });
  5511. unwrapExports(timestamp);
  5512. timestamp.Timestamp;
  5513. timestamp.LongWithoutOverridesClass;
  5514. var extended_json = createCommonjsModule(function (module, exports) {
  5515. Object.defineProperty(exports, "__esModule", { value: true });
  5516. exports.EJSON = exports.isBSONType = void 0;
  5517. function isBSONType(value) {
  5518. return (utils.isObjectLike(value) && Reflect.has(value, '_bsontype') && typeof value._bsontype === 'string');
  5519. }
  5520. exports.isBSONType = isBSONType;
  5521. // INT32 boundaries
  5522. var BSON_INT32_MAX = 0x7fffffff;
  5523. var BSON_INT32_MIN = -0x80000000;
  5524. // INT64 boundaries
  5525. var BSON_INT64_MAX = 0x7fffffffffffffff;
  5526. var BSON_INT64_MIN = -0x8000000000000000;
  5527. // all the types where we don't need to do any special processing and can just pass the EJSON
  5528. //straight to type.fromExtendedJSON
  5529. var keysToCodecs = {
  5530. $oid: objectid.ObjectId,
  5531. $binary: binary.Binary,
  5532. $uuid: binary.Binary,
  5533. $symbol: symbol.BSONSymbol,
  5534. $numberInt: int_32.Int32,
  5535. $numberDecimal: decimal128.Decimal128,
  5536. $numberDouble: double_1.Double,
  5537. $numberLong: long_1.Long,
  5538. $minKey: min_key.MinKey,
  5539. $maxKey: max_key.MaxKey,
  5540. $regex: regexp.BSONRegExp,
  5541. $regularExpression: regexp.BSONRegExp,
  5542. $timestamp: timestamp.Timestamp
  5543. };
  5544. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5545. function deserializeValue(value, options) {
  5546. if (options === void 0) { options = {}; }
  5547. if (typeof value === 'number') {
  5548. if (options.relaxed || options.legacy) {
  5549. return value;
  5550. }
  5551. // if it's an integer, should interpret as smallest BSON integer
  5552. // that can represent it exactly. (if out of range, interpret as double.)
  5553. if (Math.floor(value) === value) {
  5554. if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX)
  5555. return new int_32.Int32(value);
  5556. if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX)
  5557. return long_1.Long.fromNumber(value);
  5558. }
  5559. // If the number is a non-integer or out of integer range, should interpret as BSON Double.
  5560. return new double_1.Double(value);
  5561. }
  5562. // from here on out we're looking for bson types, so bail if its not an object
  5563. if (value == null || typeof value !== 'object')
  5564. return value;
  5565. // upgrade deprecated undefined to null
  5566. if (value.$undefined)
  5567. return null;
  5568. var keys = Object.keys(value).filter(function (k) { return k.startsWith('$') && value[k] != null; });
  5569. for (var i = 0; i < keys.length; i++) {
  5570. var c = keysToCodecs[keys[i]];
  5571. if (c)
  5572. return c.fromExtendedJSON(value, options);
  5573. }
  5574. if (value.$date != null) {
  5575. var d = value.$date;
  5576. var date = new Date();
  5577. if (options.legacy) {
  5578. if (typeof d === 'number')
  5579. date.setTime(d);
  5580. else if (typeof d === 'string')
  5581. date.setTime(Date.parse(d));
  5582. }
  5583. else {
  5584. if (typeof d === 'string')
  5585. date.setTime(Date.parse(d));
  5586. else if (long_1.Long.isLong(d))
  5587. date.setTime(d.toNumber());
  5588. else if (typeof d === 'number' && options.relaxed)
  5589. date.setTime(d);
  5590. }
  5591. return date;
  5592. }
  5593. if (value.$code != null) {
  5594. var copy = Object.assign({}, value);
  5595. if (value.$scope) {
  5596. copy.$scope = deserializeValue(value.$scope);
  5597. }
  5598. return code.Code.fromExtendedJSON(value);
  5599. }
  5600. if (db_ref.isDBRefLike(value) || value.$dbPointer) {
  5601. var v = value.$ref ? value : value.$dbPointer;
  5602. // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped)
  5603. // because of the order JSON.parse goes through the document
  5604. if (v instanceof db_ref.DBRef)
  5605. return v;
  5606. var dollarKeys = Object.keys(v).filter(function (k) { return k.startsWith('$'); });
  5607. var valid_1 = true;
  5608. dollarKeys.forEach(function (k) {
  5609. if (['$ref', '$id', '$db'].indexOf(k) === -1)
  5610. valid_1 = false;
  5611. });
  5612. // only make DBRef if $ keys are all valid
  5613. if (valid_1)
  5614. return db_ref.DBRef.fromExtendedJSON(v);
  5615. }
  5616. return value;
  5617. }
  5618. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5619. function serializeArray(array, options) {
  5620. return array.map(function (v, index) {
  5621. options.seenObjects.push({ propertyName: "index " + index, obj: null });
  5622. try {
  5623. return serializeValue(v, options);
  5624. }
  5625. finally {
  5626. options.seenObjects.pop();
  5627. }
  5628. });
  5629. }
  5630. function getISOString(date) {
  5631. var isoStr = date.toISOString();
  5632. // we should only show milliseconds in timestamp if they're non-zero
  5633. return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z';
  5634. }
  5635. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5636. function serializeValue(value, options) {
  5637. if ((typeof value === 'object' || typeof value === 'function') && value !== null) {
  5638. var index = options.seenObjects.findIndex(function (entry) { return entry.obj === value; });
  5639. if (index !== -1) {
  5640. var props = options.seenObjects.map(function (entry) { return entry.propertyName; });
  5641. var leadingPart = props
  5642. .slice(0, index)
  5643. .map(function (prop) { return prop + " -> "; })
  5644. .join('');
  5645. var alreadySeen = props[index];
  5646. var circularPart = ' -> ' +
  5647. props
  5648. .slice(index + 1, props.length - 1)
  5649. .map(function (prop) { return prop + " -> "; })
  5650. .join('');
  5651. var current = props[props.length - 1];
  5652. var leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2);
  5653. var dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1);
  5654. throw new TypeError('Converting circular structure to EJSON:\n' +
  5655. (" " + leadingPart + alreadySeen + circularPart + current + "\n") +
  5656. (" " + leadingSpace + "\\" + dashes + "/"));
  5657. }
  5658. options.seenObjects[options.seenObjects.length - 1].obj = value;
  5659. }
  5660. if (Array.isArray(value))
  5661. return serializeArray(value, options);
  5662. if (value === undefined)
  5663. return null;
  5664. if (value instanceof Date || utils.isDate(value)) {
  5665. var dateNum = value.getTime(),
  5666. // is it in year range 1970-9999?
  5667. inRange = dateNum > -1 && dateNum < 253402318800000;
  5668. if (options.legacy) {
  5669. return options.relaxed && inRange
  5670. ? { $date: value.getTime() }
  5671. : { $date: getISOString(value) };
  5672. }
  5673. return options.relaxed && inRange
  5674. ? { $date: getISOString(value) }
  5675. : { $date: { $numberLong: value.getTime().toString() } };
  5676. }
  5677. if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) {
  5678. // it's an integer
  5679. if (Math.floor(value) === value) {
  5680. var int32Range = value >= BSON_INT32_MIN && value <= BSON_INT32_MAX, int64Range = value >= BSON_INT64_MIN && value <= BSON_INT64_MAX;
  5681. // interpret as being of the smallest BSON integer type that can represent the number exactly
  5682. if (int32Range)
  5683. return { $numberInt: value.toString() };
  5684. if (int64Range)
  5685. return { $numberLong: value.toString() };
  5686. }
  5687. return { $numberDouble: value.toString() };
  5688. }
  5689. if (value instanceof RegExp || utils.isRegExp(value)) {
  5690. var flags = value.flags;
  5691. if (flags === undefined) {
  5692. var match = value.toString().match(/[gimuy]*$/);
  5693. if (match) {
  5694. flags = match[0];
  5695. }
  5696. }
  5697. var rx = new regexp.BSONRegExp(value.source, flags);
  5698. return rx.toExtendedJSON(options);
  5699. }
  5700. if (value != null && typeof value === 'object')
  5701. return serializeDocument(value, options);
  5702. return value;
  5703. }
  5704. var BSON_TYPE_MAPPINGS = {
  5705. Binary: function (o) { return new binary.Binary(o.value(), o.sub_type); },
  5706. Code: function (o) { return new code.Code(o.code, o.scope); },
  5707. DBRef: function (o) { return new db_ref.DBRef(o.collection || o.namespace, o.oid, o.db, o.fields); },
  5708. Decimal128: function (o) { return new decimal128.Decimal128(o.bytes); },
  5709. Double: function (o) { return new double_1.Double(o.value); },
  5710. Int32: function (o) { return new int_32.Int32(o.value); },
  5711. Long: function (o) {
  5712. return long_1.Long.fromBits(
  5713. // underscore variants for 1.x backwards compatibility
  5714. o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_);
  5715. },
  5716. MaxKey: function () { return new max_key.MaxKey(); },
  5717. MinKey: function () { return new min_key.MinKey(); },
  5718. ObjectID: function (o) { return new objectid.ObjectId(o); },
  5719. ObjectId: function (o) { return new objectid.ObjectId(o); },
  5720. BSONRegExp: function (o) { return new regexp.BSONRegExp(o.pattern, o.options); },
  5721. Symbol: function (o) { return new symbol.BSONSymbol(o.value); },
  5722. Timestamp: function (o) { return timestamp.Timestamp.fromBits(o.low, o.high); }
  5723. };
  5724. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5725. function serializeDocument(doc, options) {
  5726. if (doc == null || typeof doc !== 'object')
  5727. throw new Error('not an object instance');
  5728. var bsontype = doc._bsontype;
  5729. if (typeof bsontype === 'undefined') {
  5730. // It's a regular object. Recursively serialize its property values.
  5731. var _doc = {};
  5732. for (var name in doc) {
  5733. options.seenObjects.push({ propertyName: name, obj: null });
  5734. try {
  5735. _doc[name] = serializeValue(doc[name], options);
  5736. }
  5737. finally {
  5738. options.seenObjects.pop();
  5739. }
  5740. }
  5741. return _doc;
  5742. }
  5743. else if (isBSONType(doc)) {
  5744. // the "document" is really just a BSON type object
  5745. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5746. var outDoc = doc;
  5747. if (typeof outDoc.toExtendedJSON !== 'function') {
  5748. // There's no EJSON serialization function on the object. It's probably an
  5749. // object created by a previous version of this library (or another library)
  5750. // that's duck-typing objects to look like they were generated by this library).
  5751. // Copy the object into this library's version of that type.
  5752. var mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
  5753. if (!mapper) {
  5754. throw new TypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
  5755. }
  5756. outDoc = mapper(outDoc);
  5757. }
  5758. // Two BSON types may have nested objects that may need to be serialized too
  5759. if (bsontype === 'Code' && outDoc.scope) {
  5760. outDoc = new code.Code(outDoc.code, serializeValue(outDoc.scope, options));
  5761. }
  5762. else if (bsontype === 'DBRef' && outDoc.oid) {
  5763. outDoc = new db_ref.DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options));
  5764. }
  5765. return outDoc.toExtendedJSON(options);
  5766. }
  5767. else {
  5768. throw new Error('_bsontype must be a string, but was: ' + typeof bsontype);
  5769. }
  5770. }
  5771. (function (EJSON) {
  5772. /**
  5773. * Parse an Extended JSON string, constructing the JavaScript value or object described by that
  5774. * string.
  5775. *
  5776. * @example
  5777. * ```js
  5778. * const { EJSON } = require('bson');
  5779. * const text = '{ "int32": { "$numberInt": "10" } }';
  5780. *
  5781. * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }
  5782. * console.log(EJSON.parse(text, { relaxed: false }));
  5783. *
  5784. * // prints { int32: 10 }
  5785. * console.log(EJSON.parse(text));
  5786. * ```
  5787. */
  5788. function parse(text, options) {
  5789. var finalOptions = Object.assign({}, { relaxed: true, legacy: false }, options);
  5790. // relaxed implies not strict
  5791. if (typeof finalOptions.relaxed === 'boolean')
  5792. finalOptions.strict = !finalOptions.relaxed;
  5793. if (typeof finalOptions.strict === 'boolean')
  5794. finalOptions.relaxed = !finalOptions.strict;
  5795. return JSON.parse(text, function (_key, value) { return deserializeValue(value, finalOptions); });
  5796. }
  5797. EJSON.parse = parse;
  5798. /**
  5799. * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer
  5800. * function is specified or optionally including only the specified properties if a replacer array
  5801. * is specified.
  5802. *
  5803. * @param value - The value to convert to extended JSON
  5804. * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string
  5805. * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes.
  5806. * @param options - Optional settings
  5807. *
  5808. * @example
  5809. * ```js
  5810. * const { EJSON } = require('bson');
  5811. * const Int32 = require('mongodb').Int32;
  5812. * const doc = { int32: new Int32(10) };
  5813. *
  5814. * // prints '{"int32":{"$numberInt":"10"}}'
  5815. * console.log(EJSON.stringify(doc, { relaxed: false }));
  5816. *
  5817. * // prints '{"int32":10}'
  5818. * console.log(EJSON.stringify(doc));
  5819. * ```
  5820. */
  5821. function stringify(value,
  5822. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5823. replacer, space, options) {
  5824. if (space != null && typeof space === 'object') {
  5825. options = space;
  5826. space = 0;
  5827. }
  5828. if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) {
  5829. options = replacer;
  5830. replacer = undefined;
  5831. space = 0;
  5832. }
  5833. var serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, {
  5834. seenObjects: [{ propertyName: '(root)', obj: null }]
  5835. });
  5836. var doc = serializeValue(value, serializeOptions);
  5837. return JSON.stringify(doc, replacer, space);
  5838. }
  5839. EJSON.stringify = stringify;
  5840. /**
  5841. * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.
  5842. *
  5843. * @param value - The object to serialize
  5844. * @param options - Optional settings passed to the `stringify` function
  5845. */
  5846. function serialize(value, options) {
  5847. options = options || {};
  5848. return JSON.parse(stringify(value, options));
  5849. }
  5850. EJSON.serialize = serialize;
  5851. /**
  5852. * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types
  5853. *
  5854. * @param ejson - The Extended JSON object to deserialize
  5855. * @param options - Optional settings passed to the parse method
  5856. */
  5857. function deserialize(ejson, options) {
  5858. options = options || {};
  5859. return parse(JSON.stringify(ejson), options);
  5860. }
  5861. EJSON.deserialize = deserialize;
  5862. })(exports.EJSON || (exports.EJSON = {}));
  5863. });
  5864. unwrapExports(extended_json);
  5865. extended_json.EJSON;
  5866. extended_json.isBSONType;
  5867. var map = createCommonjsModule(function (module, exports) {
  5868. /* eslint-disable @typescript-eslint/no-explicit-any */
  5869. // We have an ES6 Map available, return the native instance
  5870. Object.defineProperty(exports, "__esModule", { value: true });
  5871. exports.Map = void 0;
  5872. /** @public */
  5873. var bsonMap;
  5874. exports.Map = bsonMap;
  5875. var check = function (potentialGlobal) {
  5876. // eslint-disable-next-line eqeqeq
  5877. return potentialGlobal && potentialGlobal.Math == Math && potentialGlobal;
  5878. };
  5879. // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
  5880. function getGlobal() {
  5881. // eslint-disable-next-line no-undef
  5882. return (check(typeof globalThis === 'object' && globalThis) ||
  5883. check(typeof window === 'object' && window) ||
  5884. check(typeof self === 'object' && self) ||
  5885. check(typeof commonjsGlobal === 'object' && commonjsGlobal) ||
  5886. Function('return this')());
  5887. }
  5888. var bsonGlobal = getGlobal();
  5889. if (Object.prototype.hasOwnProperty.call(bsonGlobal, 'Map')) {
  5890. exports.Map = bsonMap = bsonGlobal.Map;
  5891. }
  5892. else {
  5893. // We will return a polyfill
  5894. exports.Map = bsonMap = /** @class */ (function () {
  5895. function Map(array) {
  5896. if (array === void 0) { array = []; }
  5897. this._keys = [];
  5898. this._values = {};
  5899. for (var i = 0; i < array.length; i++) {
  5900. if (array[i] == null)
  5901. continue; // skip null and undefined
  5902. var entry = array[i];
  5903. var key = entry[0];
  5904. var value = entry[1];
  5905. // Add the key to the list of keys in order
  5906. this._keys.push(key);
  5907. // Add the key and value to the values dictionary with a point
  5908. // to the location in the ordered keys list
  5909. this._values[key] = { v: value, i: this._keys.length - 1 };
  5910. }
  5911. }
  5912. Map.prototype.clear = function () {
  5913. this._keys = [];
  5914. this._values = {};
  5915. };
  5916. Map.prototype.delete = function (key) {
  5917. var value = this._values[key];
  5918. if (value == null)
  5919. return false;
  5920. // Delete entry
  5921. delete this._values[key];
  5922. // Remove the key from the ordered keys list
  5923. this._keys.splice(value.i, 1);
  5924. return true;
  5925. };
  5926. Map.prototype.entries = function () {
  5927. var _this = this;
  5928. var index = 0;
  5929. return {
  5930. next: function () {
  5931. var key = _this._keys[index++];
  5932. return {
  5933. value: key !== undefined ? [key, _this._values[key].v] : undefined,
  5934. done: key !== undefined ? false : true
  5935. };
  5936. }
  5937. };
  5938. };
  5939. Map.prototype.forEach = function (callback, self) {
  5940. self = self || this;
  5941. for (var i = 0; i < this._keys.length; i++) {
  5942. var key = this._keys[i];
  5943. // Call the forEach callback
  5944. callback.call(self, this._values[key].v, key, self);
  5945. }
  5946. };
  5947. Map.prototype.get = function (key) {
  5948. return this._values[key] ? this._values[key].v : undefined;
  5949. };
  5950. Map.prototype.has = function (key) {
  5951. return this._values[key] != null;
  5952. };
  5953. Map.prototype.keys = function () {
  5954. var _this = this;
  5955. var index = 0;
  5956. return {
  5957. next: function () {
  5958. var key = _this._keys[index++];
  5959. return {
  5960. value: key !== undefined ? key : undefined,
  5961. done: key !== undefined ? false : true
  5962. };
  5963. }
  5964. };
  5965. };
  5966. Map.prototype.set = function (key, value) {
  5967. if (this._values[key]) {
  5968. this._values[key].v = value;
  5969. return this;
  5970. }
  5971. // Add the key to the list of keys in order
  5972. this._keys.push(key);
  5973. // Add the key and value to the values dictionary with a point
  5974. // to the location in the ordered keys list
  5975. this._values[key] = { v: value, i: this._keys.length - 1 };
  5976. return this;
  5977. };
  5978. Map.prototype.values = function () {
  5979. var _this = this;
  5980. var index = 0;
  5981. return {
  5982. next: function () {
  5983. var key = _this._keys[index++];
  5984. return {
  5985. value: key !== undefined ? _this._values[key].v : undefined,
  5986. done: key !== undefined ? false : true
  5987. };
  5988. }
  5989. };
  5990. };
  5991. Object.defineProperty(Map.prototype, "size", {
  5992. get: function () {
  5993. return this._keys.length;
  5994. },
  5995. enumerable: false,
  5996. configurable: true
  5997. });
  5998. return Map;
  5999. }());
  6000. }
  6001. });
  6002. unwrapExports(map);
  6003. map.Map;
  6004. var constants = createCommonjsModule(function (module, exports) {
  6005. Object.defineProperty(exports, "__esModule", { value: true });
  6006. exports.BSON_BINARY_SUBTYPE_USER_DEFINED = exports.BSON_BINARY_SUBTYPE_MD5 = exports.BSON_BINARY_SUBTYPE_UUID_NEW = exports.BSON_BINARY_SUBTYPE_UUID = exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = exports.BSON_BINARY_SUBTYPE_FUNCTION = exports.BSON_BINARY_SUBTYPE_DEFAULT = exports.BSON_DATA_MAX_KEY = exports.BSON_DATA_MIN_KEY = exports.BSON_DATA_DECIMAL128 = exports.BSON_DATA_LONG = exports.BSON_DATA_TIMESTAMP = exports.BSON_DATA_INT = exports.BSON_DATA_CODE_W_SCOPE = exports.BSON_DATA_SYMBOL = exports.BSON_DATA_CODE = exports.BSON_DATA_DBPOINTER = exports.BSON_DATA_REGEXP = exports.BSON_DATA_NULL = exports.BSON_DATA_DATE = exports.BSON_DATA_BOOLEAN = exports.BSON_DATA_OID = exports.BSON_DATA_UNDEFINED = exports.BSON_DATA_BINARY = exports.BSON_DATA_ARRAY = exports.BSON_DATA_OBJECT = exports.BSON_DATA_STRING = exports.BSON_DATA_NUMBER = exports.JS_INT_MIN = exports.JS_INT_MAX = exports.BSON_INT64_MIN = exports.BSON_INT64_MAX = exports.BSON_INT32_MIN = exports.BSON_INT32_MAX = void 0;
  6007. /** @internal */
  6008. exports.BSON_INT32_MAX = 0x7fffffff;
  6009. /** @internal */
  6010. exports.BSON_INT32_MIN = -0x80000000;
  6011. /** @internal */
  6012. exports.BSON_INT64_MAX = Math.pow(2, 63) - 1;
  6013. /** @internal */
  6014. exports.BSON_INT64_MIN = -Math.pow(2, 63);
  6015. /**
  6016. * Any integer up to 2^53 can be precisely represented by a double.
  6017. * @internal
  6018. */
  6019. exports.JS_INT_MAX = Math.pow(2, 53);
  6020. /**
  6021. * Any integer down to -2^53 can be precisely represented by a double.
  6022. * @internal
  6023. */
  6024. exports.JS_INT_MIN = -Math.pow(2, 53);
  6025. /** Number BSON Type @internal */
  6026. exports.BSON_DATA_NUMBER = 1;
  6027. /** String BSON Type @internal */
  6028. exports.BSON_DATA_STRING = 2;
  6029. /** Object BSON Type @internal */
  6030. exports.BSON_DATA_OBJECT = 3;
  6031. /** Array BSON Type @internal */
  6032. exports.BSON_DATA_ARRAY = 4;
  6033. /** Binary BSON Type @internal */
  6034. exports.BSON_DATA_BINARY = 5;
  6035. /** Binary BSON Type @internal */
  6036. exports.BSON_DATA_UNDEFINED = 6;
  6037. /** ObjectId BSON Type @internal */
  6038. exports.BSON_DATA_OID = 7;
  6039. /** Boolean BSON Type @internal */
  6040. exports.BSON_DATA_BOOLEAN = 8;
  6041. /** Date BSON Type @internal */
  6042. exports.BSON_DATA_DATE = 9;
  6043. /** null BSON Type @internal */
  6044. exports.BSON_DATA_NULL = 10;
  6045. /** RegExp BSON Type @internal */
  6046. exports.BSON_DATA_REGEXP = 11;
  6047. /** Code BSON Type @internal */
  6048. exports.BSON_DATA_DBPOINTER = 12;
  6049. /** Code BSON Type @internal */
  6050. exports.BSON_DATA_CODE = 13;
  6051. /** Symbol BSON Type @internal */
  6052. exports.BSON_DATA_SYMBOL = 14;
  6053. /** Code with Scope BSON Type @internal */
  6054. exports.BSON_DATA_CODE_W_SCOPE = 15;
  6055. /** 32 bit Integer BSON Type @internal */
  6056. exports.BSON_DATA_INT = 16;
  6057. /** Timestamp BSON Type @internal */
  6058. exports.BSON_DATA_TIMESTAMP = 17;
  6059. /** Long BSON Type @internal */
  6060. exports.BSON_DATA_LONG = 18;
  6061. /** Decimal128 BSON Type @internal */
  6062. exports.BSON_DATA_DECIMAL128 = 19;
  6063. /** MinKey BSON Type @internal */
  6064. exports.BSON_DATA_MIN_KEY = 0xff;
  6065. /** MaxKey BSON Type @internal */
  6066. exports.BSON_DATA_MAX_KEY = 0x7f;
  6067. /** Binary Default Type @internal */
  6068. exports.BSON_BINARY_SUBTYPE_DEFAULT = 0;
  6069. /** Binary Function Type @internal */
  6070. exports.BSON_BINARY_SUBTYPE_FUNCTION = 1;
  6071. /** Binary Byte Array Type @internal */
  6072. exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
  6073. /** Binary Deprecated UUID Type @deprecated Please use BSON_BINARY_SUBTYPE_UUID_NEW @internal */
  6074. exports.BSON_BINARY_SUBTYPE_UUID = 3;
  6075. /** Binary UUID Type @internal */
  6076. exports.BSON_BINARY_SUBTYPE_UUID_NEW = 4;
  6077. /** Binary MD5 Type @internal */
  6078. exports.BSON_BINARY_SUBTYPE_MD5 = 5;
  6079. /** Binary User Defined Type @internal */
  6080. exports.BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
  6081. });
  6082. unwrapExports(constants);
  6083. constants.BSON_BINARY_SUBTYPE_USER_DEFINED;
  6084. constants.BSON_BINARY_SUBTYPE_MD5;
  6085. constants.BSON_BINARY_SUBTYPE_UUID_NEW;
  6086. constants.BSON_BINARY_SUBTYPE_UUID;
  6087. constants.BSON_BINARY_SUBTYPE_BYTE_ARRAY;
  6088. constants.BSON_BINARY_SUBTYPE_FUNCTION;
  6089. constants.BSON_BINARY_SUBTYPE_DEFAULT;
  6090. constants.BSON_DATA_MAX_KEY;
  6091. constants.BSON_DATA_MIN_KEY;
  6092. constants.BSON_DATA_DECIMAL128;
  6093. constants.BSON_DATA_LONG;
  6094. constants.BSON_DATA_TIMESTAMP;
  6095. constants.BSON_DATA_INT;
  6096. constants.BSON_DATA_CODE_W_SCOPE;
  6097. constants.BSON_DATA_SYMBOL;
  6098. constants.BSON_DATA_CODE;
  6099. constants.BSON_DATA_DBPOINTER;
  6100. constants.BSON_DATA_REGEXP;
  6101. constants.BSON_DATA_NULL;
  6102. constants.BSON_DATA_DATE;
  6103. constants.BSON_DATA_BOOLEAN;
  6104. constants.BSON_DATA_OID;
  6105. constants.BSON_DATA_UNDEFINED;
  6106. constants.BSON_DATA_BINARY;
  6107. constants.BSON_DATA_ARRAY;
  6108. constants.BSON_DATA_OBJECT;
  6109. constants.BSON_DATA_STRING;
  6110. constants.BSON_DATA_NUMBER;
  6111. constants.JS_INT_MIN;
  6112. constants.JS_INT_MAX;
  6113. constants.BSON_INT64_MIN;
  6114. constants.BSON_INT64_MAX;
  6115. constants.BSON_INT32_MIN;
  6116. constants.BSON_INT32_MAX;
  6117. var calculate_size = createCommonjsModule(function (module, exports) {
  6118. Object.defineProperty(exports, "__esModule", { value: true });
  6119. exports.calculateObjectSize = void 0;
  6120. function calculateObjectSize(object, serializeFunctions, ignoreUndefined) {
  6121. var totalLength = 4 + 1;
  6122. if (Array.isArray(object)) {
  6123. for (var i = 0; i < object.length; i++) {
  6124. totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined);
  6125. }
  6126. }
  6127. else {
  6128. // If we have toBSON defined, override the current object
  6129. if (object.toBSON) {
  6130. object = object.toBSON();
  6131. }
  6132. // Calculate size
  6133. for (var key in object) {
  6134. totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined);
  6135. }
  6136. }
  6137. return totalLength;
  6138. }
  6139. exports.calculateObjectSize = calculateObjectSize;
  6140. /** @internal */
  6141. function calculateElement(name,
  6142. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6143. value, serializeFunctions, isArray, ignoreUndefined) {
  6144. if (serializeFunctions === void 0) { serializeFunctions = false; }
  6145. if (isArray === void 0) { isArray = false; }
  6146. if (ignoreUndefined === void 0) { ignoreUndefined = false; }
  6147. // If we have toBSON defined, override the current object
  6148. if (value && value.toBSON) {
  6149. value = value.toBSON();
  6150. }
  6151. switch (typeof value) {
  6152. case 'string':
  6153. return 1 + buffer.Buffer.byteLength(name, 'utf8') + 1 + 4 + buffer.Buffer.byteLength(value, 'utf8') + 1;
  6154. case 'number':
  6155. if (Math.floor(value) === value &&
  6156. value >= constants.JS_INT_MIN &&
  6157. value <= constants.JS_INT_MAX) {
  6158. if (value >= constants.BSON_INT32_MIN && value <= constants.BSON_INT32_MAX) {
  6159. // 32 bit
  6160. return (name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1);
  6161. }
  6162. else {
  6163. return (name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  6164. }
  6165. }
  6166. else {
  6167. // 64 bit
  6168. return (name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  6169. }
  6170. case 'undefined':
  6171. if (isArray || !ignoreUndefined)
  6172. return (name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + 1;
  6173. return 0;
  6174. case 'boolean':
  6175. return (name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1);
  6176. case 'object':
  6177. if (value == null || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
  6178. return (name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + 1;
  6179. }
  6180. else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') {
  6181. return (name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1);
  6182. }
  6183. else if (value instanceof Date || utils.isDate(value)) {
  6184. return (name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  6185. }
  6186. else if (ArrayBuffer.isView(value) ||
  6187. value instanceof ArrayBuffer ||
  6188. utils.isAnyArrayBuffer(value)) {
  6189. return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.byteLength);
  6190. }
  6191. else if (value['_bsontype'] === 'Long' ||
  6192. value['_bsontype'] === 'Double' ||
  6193. value['_bsontype'] === 'Timestamp') {
  6194. return (name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  6195. }
  6196. else if (value['_bsontype'] === 'Decimal128') {
  6197. return (name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1);
  6198. }
  6199. else if (value['_bsontype'] === 'Code') {
  6200. // Calculate size depending on the availability of a scope
  6201. if (value.scope != null && Object.keys(value.scope).length > 0) {
  6202. return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) +
  6203. 1 +
  6204. 4 +
  6205. 4 +
  6206. buffer.Buffer.byteLength(value.code.toString(), 'utf8') +
  6207. 1 +
  6208. calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined));
  6209. }
  6210. else {
  6211. return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) +
  6212. 1 +
  6213. 4 +
  6214. buffer.Buffer.byteLength(value.code.toString(), 'utf8') +
  6215. 1);
  6216. }
  6217. }
  6218. else if (value['_bsontype'] === 'Binary') {
  6219. // Check what kind of subtype we have
  6220. if (value.sub_type === binary.Binary.SUBTYPE_BYTE_ARRAY) {
  6221. return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) +
  6222. (value.position + 1 + 4 + 1 + 4));
  6223. }
  6224. else {
  6225. return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1));
  6226. }
  6227. }
  6228. else if (value['_bsontype'] === 'Symbol') {
  6229. return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) +
  6230. buffer.Buffer.byteLength(value.value, 'utf8') +
  6231. 4 +
  6232. 1 +
  6233. 1);
  6234. }
  6235. else if (value['_bsontype'] === 'DBRef') {
  6236. // Set up correct object for serialization
  6237. var ordered_values = Object.assign({
  6238. $ref: value.collection,
  6239. $id: value.oid
  6240. }, value.fields);
  6241. // Add db reference if it exists
  6242. if (value.db != null) {
  6243. ordered_values['$db'] = value.db;
  6244. }
  6245. return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) +
  6246. 1 +
  6247. calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined));
  6248. }
  6249. else if (value instanceof RegExp || utils.isRegExp(value)) {
  6250. return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) +
  6251. 1 +
  6252. buffer.Buffer.byteLength(value.source, 'utf8') +
  6253. 1 +
  6254. (value.global ? 1 : 0) +
  6255. (value.ignoreCase ? 1 : 0) +
  6256. (value.multiline ? 1 : 0) +
  6257. 1);
  6258. }
  6259. else if (value['_bsontype'] === 'BSONRegExp') {
  6260. return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) +
  6261. 1 +
  6262. buffer.Buffer.byteLength(value.pattern, 'utf8') +
  6263. 1 +
  6264. buffer.Buffer.byteLength(value.options, 'utf8') +
  6265. 1);
  6266. }
  6267. else {
  6268. return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) +
  6269. calculateObjectSize(value, serializeFunctions, ignoreUndefined) +
  6270. 1);
  6271. }
  6272. case 'function':
  6273. // WTF for 0.4.X where typeof /someregexp/ === 'function'
  6274. if (value instanceof RegExp || utils.isRegExp(value) || String.call(value) === '[object RegExp]') {
  6275. return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) +
  6276. 1 +
  6277. buffer.Buffer.byteLength(value.source, 'utf8') +
  6278. 1 +
  6279. (value.global ? 1 : 0) +
  6280. (value.ignoreCase ? 1 : 0) +
  6281. (value.multiline ? 1 : 0) +
  6282. 1);
  6283. }
  6284. else {
  6285. if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) {
  6286. return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) +
  6287. 1 +
  6288. 4 +
  6289. 4 +
  6290. buffer.Buffer.byteLength(utils.normalizedFunctionString(value), 'utf8') +
  6291. 1 +
  6292. calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined));
  6293. }
  6294. else if (serializeFunctions) {
  6295. return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) +
  6296. 1 +
  6297. 4 +
  6298. buffer.Buffer.byteLength(utils.normalizedFunctionString(value), 'utf8') +
  6299. 1);
  6300. }
  6301. }
  6302. }
  6303. return 0;
  6304. }
  6305. });
  6306. unwrapExports(calculate_size);
  6307. calculate_size.calculateObjectSize;
  6308. var validate_utf8 = createCommonjsModule(function (module, exports) {
  6309. Object.defineProperty(exports, "__esModule", { value: true });
  6310. exports.validateUtf8 = void 0;
  6311. var FIRST_BIT = 0x80;
  6312. var FIRST_TWO_BITS = 0xc0;
  6313. var FIRST_THREE_BITS = 0xe0;
  6314. var FIRST_FOUR_BITS = 0xf0;
  6315. var FIRST_FIVE_BITS = 0xf8;
  6316. var TWO_BIT_CHAR = 0xc0;
  6317. var THREE_BIT_CHAR = 0xe0;
  6318. var FOUR_BIT_CHAR = 0xf0;
  6319. var CONTINUING_CHAR = 0x80;
  6320. /**
  6321. * Determines if the passed in bytes are valid utf8
  6322. * @param bytes - An array of 8-bit bytes. Must be indexable and have length property
  6323. * @param start - The index to start validating
  6324. * @param end - The index to end validating
  6325. */
  6326. function validateUtf8(bytes, start, end) {
  6327. var continuation = 0;
  6328. for (var i = start; i < end; i += 1) {
  6329. var byte = bytes[i];
  6330. if (continuation) {
  6331. if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) {
  6332. return false;
  6333. }
  6334. continuation -= 1;
  6335. }
  6336. else if (byte & FIRST_BIT) {
  6337. if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) {
  6338. continuation = 1;
  6339. }
  6340. else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) {
  6341. continuation = 2;
  6342. }
  6343. else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) {
  6344. continuation = 3;
  6345. }
  6346. else {
  6347. return false;
  6348. }
  6349. }
  6350. }
  6351. return !continuation;
  6352. }
  6353. exports.validateUtf8 = validateUtf8;
  6354. });
  6355. unwrapExports(validate_utf8);
  6356. validate_utf8.validateUtf8;
  6357. var deserializer = createCommonjsModule(function (module, exports) {
  6358. Object.defineProperty(exports, "__esModule", { value: true });
  6359. exports.deserialize = void 0;
  6360. // Internal long versions
  6361. var JS_INT_MAX_LONG = long_1.Long.fromNumber(constants.JS_INT_MAX);
  6362. var JS_INT_MIN_LONG = long_1.Long.fromNumber(constants.JS_INT_MIN);
  6363. var functionCache = {};
  6364. function deserialize(buffer, options, isArray) {
  6365. options = options == null ? {} : options;
  6366. var index = options && options.index ? options.index : 0;
  6367. // Read the document size
  6368. var size = buffer[index] |
  6369. (buffer[index + 1] << 8) |
  6370. (buffer[index + 2] << 16) |
  6371. (buffer[index + 3] << 24);
  6372. if (size < 5) {
  6373. throw new Error("bson size must be >= 5, is " + size);
  6374. }
  6375. if (options.allowObjectSmallerThanBufferSize && buffer.length < size) {
  6376. throw new Error("buffer length " + buffer.length + " must be >= bson size " + size);
  6377. }
  6378. if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) {
  6379. throw new Error("buffer length " + buffer.length + " must === bson size " + size);
  6380. }
  6381. if (size + index > buffer.byteLength) {
  6382. throw new Error("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")");
  6383. }
  6384. // Illegal end value
  6385. if (buffer[index + size - 1] !== 0) {
  6386. throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
  6387. }
  6388. // Start deserializtion
  6389. return deserializeObject(buffer, index, options, isArray);
  6390. }
  6391. exports.deserialize = deserialize;
  6392. function deserializeObject(buffer$1, index, options, isArray) {
  6393. if (isArray === void 0) { isArray = false; }
  6394. var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions'];
  6395. var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions'];
  6396. var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw'];
  6397. // Return raw bson buffer instead of parsing it
  6398. var raw = options['raw'] == null ? false : options['raw'];
  6399. // Return BSONRegExp objects instead of native regular expressions
  6400. var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false;
  6401. // Controls the promotion of values vs wrapper classes
  6402. var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers'];
  6403. var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs'];
  6404. var promoteValues = options['promoteValues'] == null ? true : options['promoteValues'];
  6405. // Set the start index
  6406. var startIndex = index;
  6407. // Validate that we have at least 4 bytes of buffer
  6408. if (buffer$1.length < 5)
  6409. throw new Error('corrupt bson message < 5 bytes long');
  6410. // Read the document size
  6411. var size = buffer$1[index++] | (buffer$1[index++] << 8) | (buffer$1[index++] << 16) | (buffer$1[index++] << 24);
  6412. // Ensure buffer is valid size
  6413. if (size < 5 || size > buffer$1.length)
  6414. throw new Error('corrupt bson message');
  6415. // Create holding object
  6416. var object = isArray ? [] : {};
  6417. // Used for arrays to skip having to perform utf8 decoding
  6418. var arrayIndex = 0;
  6419. var done = false;
  6420. // While we have more left data left keep parsing
  6421. while (!done) {
  6422. // Read the type
  6423. var elementType = buffer$1[index++];
  6424. // If we get a zero it's the last byte, exit
  6425. if (elementType === 0)
  6426. break;
  6427. // Get the start search index
  6428. var i = index;
  6429. // Locate the end of the c string
  6430. while (buffer$1[i] !== 0x00 && i < buffer$1.length) {
  6431. i++;
  6432. }
  6433. // If are at the end of the buffer there is a problem with the document
  6434. if (i >= buffer$1.byteLength)
  6435. throw new Error('Bad BSON Document: illegal CString');
  6436. var name = isArray ? arrayIndex++ : buffer$1.toString('utf8', index, i);
  6437. var value = void 0;
  6438. index = i + 1;
  6439. if (elementType === constants.BSON_DATA_STRING) {
  6440. var stringSize = buffer$1[index++] |
  6441. (buffer$1[index++] << 8) |
  6442. (buffer$1[index++] << 16) |
  6443. (buffer$1[index++] << 24);
  6444. if (stringSize <= 0 ||
  6445. stringSize > buffer$1.length - index ||
  6446. buffer$1[index + stringSize - 1] !== 0)
  6447. throw new Error('bad string length in bson');
  6448. if (!validate_utf8.validateUtf8(buffer$1, index, index + stringSize - 1)) {
  6449. throw new Error('Invalid UTF-8 string in BSON document');
  6450. }
  6451. value = buffer$1.toString('utf8', index, index + stringSize - 1);
  6452. index = index + stringSize;
  6453. }
  6454. else if (elementType === constants.BSON_DATA_OID) {
  6455. var oid = buffer.Buffer.alloc(12);
  6456. buffer$1.copy(oid, 0, index, index + 12);
  6457. value = new objectid.ObjectId(oid);
  6458. index = index + 12;
  6459. }
  6460. else if (elementType === constants.BSON_DATA_INT && promoteValues === false) {
  6461. value = new int_32.Int32(buffer$1[index++] | (buffer$1[index++] << 8) | (buffer$1[index++] << 16) | (buffer$1[index++] << 24));
  6462. }
  6463. else if (elementType === constants.BSON_DATA_INT) {
  6464. value =
  6465. buffer$1[index++] |
  6466. (buffer$1[index++] << 8) |
  6467. (buffer$1[index++] << 16) |
  6468. (buffer$1[index++] << 24);
  6469. }
  6470. else if (elementType === constants.BSON_DATA_NUMBER && promoteValues === false) {
  6471. value = new double_1.Double(buffer$1.readDoubleLE(index));
  6472. index = index + 8;
  6473. }
  6474. else if (elementType === constants.BSON_DATA_NUMBER) {
  6475. value = buffer$1.readDoubleLE(index);
  6476. index = index + 8;
  6477. }
  6478. else if (elementType === constants.BSON_DATA_DATE) {
  6479. var lowBits = buffer$1[index++] |
  6480. (buffer$1[index++] << 8) |
  6481. (buffer$1[index++] << 16) |
  6482. (buffer$1[index++] << 24);
  6483. var highBits = buffer$1[index++] |
  6484. (buffer$1[index++] << 8) |
  6485. (buffer$1[index++] << 16) |
  6486. (buffer$1[index++] << 24);
  6487. value = new Date(new long_1.Long(lowBits, highBits).toNumber());
  6488. }
  6489. else if (elementType === constants.BSON_DATA_BOOLEAN) {
  6490. if (buffer$1[index] !== 0 && buffer$1[index] !== 1)
  6491. throw new Error('illegal boolean type value');
  6492. value = buffer$1[index++] === 1;
  6493. }
  6494. else if (elementType === constants.BSON_DATA_OBJECT) {
  6495. var _index = index;
  6496. var objectSize = buffer$1[index] |
  6497. (buffer$1[index + 1] << 8) |
  6498. (buffer$1[index + 2] << 16) |
  6499. (buffer$1[index + 3] << 24);
  6500. if (objectSize <= 0 || objectSize > buffer$1.length - index)
  6501. throw new Error('bad embedded document length in bson');
  6502. // We have a raw value
  6503. if (raw) {
  6504. value = buffer$1.slice(index, index + objectSize);
  6505. }
  6506. else {
  6507. value = deserializeObject(buffer$1, _index, options, false);
  6508. }
  6509. index = index + objectSize;
  6510. }
  6511. else if (elementType === constants.BSON_DATA_ARRAY) {
  6512. var _index = index;
  6513. var objectSize = buffer$1[index] |
  6514. (buffer$1[index + 1] << 8) |
  6515. (buffer$1[index + 2] << 16) |
  6516. (buffer$1[index + 3] << 24);
  6517. var arrayOptions = options;
  6518. // Stop index
  6519. var stopIndex = index + objectSize;
  6520. // All elements of array to be returned as raw bson
  6521. if (fieldsAsRaw && fieldsAsRaw[name]) {
  6522. arrayOptions = {};
  6523. for (var n in options) {
  6524. arrayOptions[n] = options[n];
  6525. }
  6526. arrayOptions['raw'] = true;
  6527. }
  6528. value = deserializeObject(buffer$1, _index, arrayOptions, true);
  6529. index = index + objectSize;
  6530. if (buffer$1[index - 1] !== 0)
  6531. throw new Error('invalid array terminator byte');
  6532. if (index !== stopIndex)
  6533. throw new Error('corrupted array bson');
  6534. }
  6535. else if (elementType === constants.BSON_DATA_UNDEFINED) {
  6536. value = undefined;
  6537. }
  6538. else if (elementType === constants.BSON_DATA_NULL) {
  6539. value = null;
  6540. }
  6541. else if (elementType === constants.BSON_DATA_LONG) {
  6542. // Unpack the low and high bits
  6543. var lowBits = buffer$1[index++] |
  6544. (buffer$1[index++] << 8) |
  6545. (buffer$1[index++] << 16) |
  6546. (buffer$1[index++] << 24);
  6547. var highBits = buffer$1[index++] |
  6548. (buffer$1[index++] << 8) |
  6549. (buffer$1[index++] << 16) |
  6550. (buffer$1[index++] << 24);
  6551. var long = new long_1.Long(lowBits, highBits);
  6552. // Promote the long if possible
  6553. if (promoteLongs && promoteValues === true) {
  6554. value =
  6555. long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG)
  6556. ? long.toNumber()
  6557. : long;
  6558. }
  6559. else {
  6560. value = long;
  6561. }
  6562. }
  6563. else if (elementType === constants.BSON_DATA_DECIMAL128) {
  6564. // Buffer to contain the decimal bytes
  6565. var bytes = buffer.Buffer.alloc(16);
  6566. // Copy the next 16 bytes into the bytes buffer
  6567. buffer$1.copy(bytes, 0, index, index + 16);
  6568. // Update index
  6569. index = index + 16;
  6570. // Assign the new Decimal128 value
  6571. var decimal128$1 = new decimal128.Decimal128(bytes);
  6572. // If we have an alternative mapper use that
  6573. if ('toObject' in decimal128$1 && typeof decimal128$1.toObject === 'function') {
  6574. value = decimal128$1.toObject();
  6575. }
  6576. else {
  6577. value = decimal128$1;
  6578. }
  6579. }
  6580. else if (elementType === constants.BSON_DATA_BINARY) {
  6581. var binarySize = buffer$1[index++] |
  6582. (buffer$1[index++] << 8) |
  6583. (buffer$1[index++] << 16) |
  6584. (buffer$1[index++] << 24);
  6585. var totalBinarySize = binarySize;
  6586. var subType = buffer$1[index++];
  6587. // Did we have a negative binary size, throw
  6588. if (binarySize < 0)
  6589. throw new Error('Negative binary type element size found');
  6590. // Is the length longer than the document
  6591. if (binarySize > buffer$1.byteLength)
  6592. throw new Error('Binary type size larger than document size');
  6593. // Decode as raw Buffer object if options specifies it
  6594. if (buffer$1['slice'] != null) {
  6595. // If we have subtype 2 skip the 4 bytes for the size
  6596. if (subType === binary.Binary.SUBTYPE_BYTE_ARRAY) {
  6597. binarySize =
  6598. buffer$1[index++] |
  6599. (buffer$1[index++] << 8) |
  6600. (buffer$1[index++] << 16) |
  6601. (buffer$1[index++] << 24);
  6602. if (binarySize < 0)
  6603. throw new Error('Negative binary type element size found for subtype 0x02');
  6604. if (binarySize > totalBinarySize - 4)
  6605. throw new Error('Binary type with subtype 0x02 contains too long binary size');
  6606. if (binarySize < totalBinarySize - 4)
  6607. throw new Error('Binary type with subtype 0x02 contains too short binary size');
  6608. }
  6609. if (promoteBuffers && promoteValues) {
  6610. value = buffer$1.slice(index, index + binarySize);
  6611. }
  6612. else {
  6613. value = new binary.Binary(buffer$1.slice(index, index + binarySize), subType);
  6614. }
  6615. }
  6616. else {
  6617. var _buffer = buffer.Buffer.alloc(binarySize);
  6618. // If we have subtype 2 skip the 4 bytes for the size
  6619. if (subType === binary.Binary.SUBTYPE_BYTE_ARRAY) {
  6620. binarySize =
  6621. buffer$1[index++] |
  6622. (buffer$1[index++] << 8) |
  6623. (buffer$1[index++] << 16) |
  6624. (buffer$1[index++] << 24);
  6625. if (binarySize < 0)
  6626. throw new Error('Negative binary type element size found for subtype 0x02');
  6627. if (binarySize > totalBinarySize - 4)
  6628. throw new Error('Binary type with subtype 0x02 contains too long binary size');
  6629. if (binarySize < totalBinarySize - 4)
  6630. throw new Error('Binary type with subtype 0x02 contains too short binary size');
  6631. }
  6632. // Copy the data
  6633. for (i = 0; i < binarySize; i++) {
  6634. _buffer[i] = buffer$1[index + i];
  6635. }
  6636. if (promoteBuffers && promoteValues) {
  6637. value = _buffer;
  6638. }
  6639. else {
  6640. value = new binary.Binary(_buffer, subType);
  6641. }
  6642. }
  6643. // Update the index
  6644. index = index + binarySize;
  6645. }
  6646. else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === false) {
  6647. // Get the start search index
  6648. i = index;
  6649. // Locate the end of the c string
  6650. while (buffer$1[i] !== 0x00 && i < buffer$1.length) {
  6651. i++;
  6652. }
  6653. // If are at the end of the buffer there is a problem with the document
  6654. if (i >= buffer$1.length)
  6655. throw new Error('Bad BSON Document: illegal CString');
  6656. // Return the C string
  6657. var source = buffer$1.toString('utf8', index, i);
  6658. // Create the regexp
  6659. index = i + 1;
  6660. // Get the start search index
  6661. i = index;
  6662. // Locate the end of the c string
  6663. while (buffer$1[i] !== 0x00 && i < buffer$1.length) {
  6664. i++;
  6665. }
  6666. // If are at the end of the buffer there is a problem with the document
  6667. if (i >= buffer$1.length)
  6668. throw new Error('Bad BSON Document: illegal CString');
  6669. // Return the C string
  6670. var regExpOptions = buffer$1.toString('utf8', index, i);
  6671. index = i + 1;
  6672. // For each option add the corresponding one for javascript
  6673. var optionsArray = new Array(regExpOptions.length);
  6674. // Parse options
  6675. for (i = 0; i < regExpOptions.length; i++) {
  6676. switch (regExpOptions[i]) {
  6677. case 'm':
  6678. optionsArray[i] = 'm';
  6679. break;
  6680. case 's':
  6681. optionsArray[i] = 'g';
  6682. break;
  6683. case 'i':
  6684. optionsArray[i] = 'i';
  6685. break;
  6686. }
  6687. }
  6688. value = new RegExp(source, optionsArray.join(''));
  6689. }
  6690. else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === true) {
  6691. // Get the start search index
  6692. i = index;
  6693. // Locate the end of the c string
  6694. while (buffer$1[i] !== 0x00 && i < buffer$1.length) {
  6695. i++;
  6696. }
  6697. // If are at the end of the buffer there is a problem with the document
  6698. if (i >= buffer$1.length)
  6699. throw new Error('Bad BSON Document: illegal CString');
  6700. // Return the C string
  6701. var source = buffer$1.toString('utf8', index, i);
  6702. index = i + 1;
  6703. // Get the start search index
  6704. i = index;
  6705. // Locate the end of the c string
  6706. while (buffer$1[i] !== 0x00 && i < buffer$1.length) {
  6707. i++;
  6708. }
  6709. // If are at the end of the buffer there is a problem with the document
  6710. if (i >= buffer$1.length)
  6711. throw new Error('Bad BSON Document: illegal CString');
  6712. // Return the C string
  6713. var regExpOptions = buffer$1.toString('utf8', index, i);
  6714. index = i + 1;
  6715. // Set the object
  6716. value = new regexp.BSONRegExp(source, regExpOptions);
  6717. }
  6718. else if (elementType === constants.BSON_DATA_SYMBOL) {
  6719. var stringSize = buffer$1[index++] |
  6720. (buffer$1[index++] << 8) |
  6721. (buffer$1[index++] << 16) |
  6722. (buffer$1[index++] << 24);
  6723. if (stringSize <= 0 ||
  6724. stringSize > buffer$1.length - index ||
  6725. buffer$1[index + stringSize - 1] !== 0)
  6726. throw new Error('bad string length in bson');
  6727. var symbol$1 = buffer$1.toString('utf8', index, index + stringSize - 1);
  6728. value = promoteValues ? symbol$1 : new symbol.BSONSymbol(symbol$1);
  6729. index = index + stringSize;
  6730. }
  6731. else if (elementType === constants.BSON_DATA_TIMESTAMP) {
  6732. var lowBits = buffer$1[index++] |
  6733. (buffer$1[index++] << 8) |
  6734. (buffer$1[index++] << 16) |
  6735. (buffer$1[index++] << 24);
  6736. var highBits = buffer$1[index++] |
  6737. (buffer$1[index++] << 8) |
  6738. (buffer$1[index++] << 16) |
  6739. (buffer$1[index++] << 24);
  6740. value = new timestamp.Timestamp(lowBits, highBits);
  6741. }
  6742. else if (elementType === constants.BSON_DATA_MIN_KEY) {
  6743. value = new min_key.MinKey();
  6744. }
  6745. else if (elementType === constants.BSON_DATA_MAX_KEY) {
  6746. value = new max_key.MaxKey();
  6747. }
  6748. else if (elementType === constants.BSON_DATA_CODE) {
  6749. var stringSize = buffer$1[index++] |
  6750. (buffer$1[index++] << 8) |
  6751. (buffer$1[index++] << 16) |
  6752. (buffer$1[index++] << 24);
  6753. if (stringSize <= 0 ||
  6754. stringSize > buffer$1.length - index ||
  6755. buffer$1[index + stringSize - 1] !== 0)
  6756. throw new Error('bad string length in bson');
  6757. var functionString = buffer$1.toString('utf8', index, index + stringSize - 1);
  6758. // If we are evaluating the functions
  6759. if (evalFunctions) {
  6760. // If we have cache enabled let's look for the md5 of the function in the cache
  6761. if (cacheFunctions) {
  6762. // Got to do this to avoid V8 deoptimizing the call due to finding eval
  6763. value = isolateEval(functionString, functionCache, object);
  6764. }
  6765. else {
  6766. value = isolateEval(functionString);
  6767. }
  6768. }
  6769. else {
  6770. value = new code.Code(functionString);
  6771. }
  6772. // Update parse index position
  6773. index = index + stringSize;
  6774. }
  6775. else if (elementType === constants.BSON_DATA_CODE_W_SCOPE) {
  6776. var totalSize = buffer$1[index++] |
  6777. (buffer$1[index++] << 8) |
  6778. (buffer$1[index++] << 16) |
  6779. (buffer$1[index++] << 24);
  6780. // Element cannot be shorter than totalSize + stringSize + documentSize + terminator
  6781. if (totalSize < 4 + 4 + 4 + 1) {
  6782. throw new Error('code_w_scope total size shorter minimum expected length');
  6783. }
  6784. // Get the code string size
  6785. var stringSize = buffer$1[index++] |
  6786. (buffer$1[index++] << 8) |
  6787. (buffer$1[index++] << 16) |
  6788. (buffer$1[index++] << 24);
  6789. // Check if we have a valid string
  6790. if (stringSize <= 0 ||
  6791. stringSize > buffer$1.length - index ||
  6792. buffer$1[index + stringSize - 1] !== 0)
  6793. throw new Error('bad string length in bson');
  6794. // Javascript function
  6795. var functionString = buffer$1.toString('utf8', index, index + stringSize - 1);
  6796. // Update parse index position
  6797. index = index + stringSize;
  6798. // Parse the element
  6799. var _index = index;
  6800. // Decode the size of the object document
  6801. var objectSize = buffer$1[index] |
  6802. (buffer$1[index + 1] << 8) |
  6803. (buffer$1[index + 2] << 16) |
  6804. (buffer$1[index + 3] << 24);
  6805. // Decode the scope object
  6806. var scopeObject = deserializeObject(buffer$1, _index, options, false);
  6807. // Adjust the index
  6808. index = index + objectSize;
  6809. // Check if field length is too short
  6810. if (totalSize < 4 + 4 + objectSize + stringSize) {
  6811. throw new Error('code_w_scope total size is too short, truncating scope');
  6812. }
  6813. // Check if totalSize field is too long
  6814. if (totalSize > 4 + 4 + objectSize + stringSize) {
  6815. throw new Error('code_w_scope total size is too long, clips outer document');
  6816. }
  6817. // If we are evaluating the functions
  6818. if (evalFunctions) {
  6819. // If we have cache enabled let's look for the md5 of the function in the cache
  6820. if (cacheFunctions) {
  6821. // Got to do this to avoid V8 deoptimizing the call due to finding eval
  6822. value = isolateEval(functionString, functionCache, object);
  6823. }
  6824. else {
  6825. value = isolateEval(functionString);
  6826. }
  6827. value.scope = scopeObject;
  6828. }
  6829. else {
  6830. value = new code.Code(functionString, scopeObject);
  6831. }
  6832. }
  6833. else if (elementType === constants.BSON_DATA_DBPOINTER) {
  6834. // Get the code string size
  6835. var stringSize = buffer$1[index++] |
  6836. (buffer$1[index++] << 8) |
  6837. (buffer$1[index++] << 16) |
  6838. (buffer$1[index++] << 24);
  6839. // Check if we have a valid string
  6840. if (stringSize <= 0 ||
  6841. stringSize > buffer$1.length - index ||
  6842. buffer$1[index + stringSize - 1] !== 0)
  6843. throw new Error('bad string length in bson');
  6844. // Namespace
  6845. if (!validate_utf8.validateUtf8(buffer$1, index, index + stringSize - 1)) {
  6846. throw new Error('Invalid UTF-8 string in BSON document');
  6847. }
  6848. var namespace = buffer$1.toString('utf8', index, index + stringSize - 1);
  6849. // Update parse index position
  6850. index = index + stringSize;
  6851. // Read the oid
  6852. var oidBuffer = buffer.Buffer.alloc(12);
  6853. buffer$1.copy(oidBuffer, 0, index, index + 12);
  6854. var oid = new objectid.ObjectId(oidBuffer);
  6855. // Update the index
  6856. index = index + 12;
  6857. // Upgrade to DBRef type
  6858. value = new db_ref.DBRef(namespace, oid);
  6859. }
  6860. else {
  6861. throw new Error('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"');
  6862. }
  6863. if (name === '__proto__') {
  6864. Object.defineProperty(object, name, {
  6865. value: value,
  6866. writable: true,
  6867. enumerable: true,
  6868. configurable: true
  6869. });
  6870. }
  6871. else {
  6872. object[name] = value;
  6873. }
  6874. }
  6875. // Check if the deserialization was against a valid array/object
  6876. if (size !== index - startIndex) {
  6877. if (isArray)
  6878. throw new Error('corrupt array bson');
  6879. throw new Error('corrupt object bson');
  6880. }
  6881. // check if object's $ keys are those of a DBRef
  6882. var dollarKeys = Object.keys(object).filter(function (k) { return k.startsWith('$'); });
  6883. var valid = true;
  6884. dollarKeys.forEach(function (k) {
  6885. if (['$ref', '$id', '$db'].indexOf(k) === -1)
  6886. valid = false;
  6887. });
  6888. // if a $key not in "$ref", "$id", "$db", don't make a DBRef
  6889. if (!valid)
  6890. return object;
  6891. if (db_ref.isDBRefLike(object)) {
  6892. var copy = Object.assign({}, object);
  6893. delete copy.$ref;
  6894. delete copy.$id;
  6895. delete copy.$db;
  6896. return new db_ref.DBRef(object.$ref, object.$id, object.$db, copy);
  6897. }
  6898. return object;
  6899. }
  6900. /**
  6901. * Ensure eval is isolated, store the result in functionCache.
  6902. *
  6903. * @internal
  6904. */
  6905. function isolateEval(functionString, functionCache, object) {
  6906. if (!functionCache)
  6907. return new Function(functionString);
  6908. // Check for cache hit, eval if missing and return cached function
  6909. if (functionCache[functionString] == null) {
  6910. functionCache[functionString] = new Function(functionString);
  6911. }
  6912. // Set the object
  6913. return functionCache[functionString].bind(object);
  6914. }
  6915. });
  6916. unwrapExports(deserializer);
  6917. deserializer.deserialize;
  6918. var float_parser = createCommonjsModule(function (module, exports) {
  6919. // Copyright (c) 2008, Fair Oaks Labs, Inc.
  6920. // All rights reserved.
  6921. //
  6922. // Redistribution and use in source and binary forms, with or without
  6923. // modification, are permitted provided that the following conditions are met:
  6924. //
  6925. // * Redistributions of source code must retain the above copyright notice,
  6926. // this list of conditions and the following disclaimer.
  6927. //
  6928. // * Redistributions in binary form must reproduce the above copyright notice,
  6929. // this list of conditions and the following disclaimer in the documentation
  6930. // and/or other materials provided with the distribution.
  6931. //
  6932. // * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors
  6933. // may be used to endorse or promote products derived from this software
  6934. // without specific prior written permission.
  6935. //
  6936. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  6937. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  6938. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  6939. // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  6940. // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  6941. // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  6942. // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  6943. // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  6944. // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  6945. // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  6946. // POSSIBILITY OF SUCH DAMAGE.
  6947. //
  6948. //
  6949. // Modifications to writeIEEE754 to support negative zeroes made by Brian White
  6950. Object.defineProperty(exports, "__esModule", { value: true });
  6951. exports.writeIEEE754 = exports.readIEEE754 = void 0;
  6952. function readIEEE754(buffer, offset, endian, mLen, nBytes) {
  6953. var e;
  6954. var m;
  6955. var bBE = endian === 'big';
  6956. var eLen = nBytes * 8 - mLen - 1;
  6957. var eMax = (1 << eLen) - 1;
  6958. var eBias = eMax >> 1;
  6959. var nBits = -7;
  6960. var i = bBE ? 0 : nBytes - 1;
  6961. var d = bBE ? 1 : -1;
  6962. var s = buffer[offset + i];
  6963. i += d;
  6964. e = s & ((1 << -nBits) - 1);
  6965. s >>= -nBits;
  6966. nBits += eLen;
  6967. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8)
  6968. ;
  6969. m = e & ((1 << -nBits) - 1);
  6970. e >>= -nBits;
  6971. nBits += mLen;
  6972. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8)
  6973. ;
  6974. if (e === 0) {
  6975. e = 1 - eBias;
  6976. }
  6977. else if (e === eMax) {
  6978. return m ? NaN : (s ? -1 : 1) * Infinity;
  6979. }
  6980. else {
  6981. m = m + Math.pow(2, mLen);
  6982. e = e - eBias;
  6983. }
  6984. return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
  6985. }
  6986. exports.readIEEE754 = readIEEE754;
  6987. function writeIEEE754(buffer, value, offset, endian, mLen, nBytes) {
  6988. var e;
  6989. var m;
  6990. var c;
  6991. var bBE = endian === 'big';
  6992. var eLen = nBytes * 8 - mLen - 1;
  6993. var eMax = (1 << eLen) - 1;
  6994. var eBias = eMax >> 1;
  6995. var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
  6996. var i = bBE ? nBytes - 1 : 0;
  6997. var d = bBE ? -1 : 1;
  6998. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
  6999. value = Math.abs(value);
  7000. if (isNaN(value) || value === Infinity) {
  7001. m = isNaN(value) ? 1 : 0;
  7002. e = eMax;
  7003. }
  7004. else {
  7005. e = Math.floor(Math.log(value) / Math.LN2);
  7006. if (value * (c = Math.pow(2, -e)) < 1) {
  7007. e--;
  7008. c *= 2;
  7009. }
  7010. if (e + eBias >= 1) {
  7011. value += rt / c;
  7012. }
  7013. else {
  7014. value += rt * Math.pow(2, 1 - eBias);
  7015. }
  7016. if (value * c >= 2) {
  7017. e++;
  7018. c /= 2;
  7019. }
  7020. if (e + eBias >= eMax) {
  7021. m = 0;
  7022. e = eMax;
  7023. }
  7024. else if (e + eBias >= 1) {
  7025. m = (value * c - 1) * Math.pow(2, mLen);
  7026. e = e + eBias;
  7027. }
  7028. else {
  7029. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  7030. e = 0;
  7031. }
  7032. }
  7033. if (isNaN(value))
  7034. m = 0;
  7035. while (mLen >= 8) {
  7036. buffer[offset + i] = m & 0xff;
  7037. i += d;
  7038. m /= 256;
  7039. mLen -= 8;
  7040. }
  7041. e = (e << mLen) | m;
  7042. if (isNaN(value))
  7043. e += 8;
  7044. eLen += mLen;
  7045. while (eLen > 0) {
  7046. buffer[offset + i] = e & 0xff;
  7047. i += d;
  7048. e /= 256;
  7049. eLen -= 8;
  7050. }
  7051. buffer[offset + i - d] |= s * 128;
  7052. }
  7053. exports.writeIEEE754 = writeIEEE754;
  7054. });
  7055. unwrapExports(float_parser);
  7056. float_parser.writeIEEE754;
  7057. float_parser.readIEEE754;
  7058. var serializer = createCommonjsModule(function (module, exports) {
  7059. Object.defineProperty(exports, "__esModule", { value: true });
  7060. exports.serializeInto = void 0;
  7061. var regexp = /\x00/; // eslint-disable-line no-control-regex
  7062. var ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']);
  7063. /*
  7064. * isArray indicates if we are writing to a BSON array (type 0x04)
  7065. * which forces the "key" which really an array index as a string to be written as ascii
  7066. * This will catch any errors in index as a string generation
  7067. */
  7068. function serializeString(buffer, key, value, index, isArray) {
  7069. // Encode String type
  7070. buffer[index++] = constants.BSON_DATA_STRING;
  7071. // Number of written bytes
  7072. var numberOfWrittenBytes = !isArray
  7073. ? buffer.write(key, index, undefined, 'utf8')
  7074. : buffer.write(key, index, undefined, 'ascii');
  7075. // Encode the name
  7076. index = index + numberOfWrittenBytes + 1;
  7077. buffer[index - 1] = 0;
  7078. // Write the string
  7079. var size = buffer.write(value, index + 4, undefined, 'utf8');
  7080. // Write the size of the string to buffer
  7081. buffer[index + 3] = ((size + 1) >> 24) & 0xff;
  7082. buffer[index + 2] = ((size + 1) >> 16) & 0xff;
  7083. buffer[index + 1] = ((size + 1) >> 8) & 0xff;
  7084. buffer[index] = (size + 1) & 0xff;
  7085. // Update index
  7086. index = index + 4 + size;
  7087. // Write zero
  7088. buffer[index++] = 0;
  7089. return index;
  7090. }
  7091. function serializeNumber(buffer, key, value, index, isArray) {
  7092. // We have an integer value
  7093. // TODO(NODE-2529): Add support for big int
  7094. if (Number.isInteger(value) &&
  7095. value >= constants.BSON_INT32_MIN &&
  7096. value <= constants.BSON_INT32_MAX) {
  7097. // If the value fits in 32 bits encode as int32
  7098. // Set int type 32 bits or less
  7099. buffer[index++] = constants.BSON_DATA_INT;
  7100. // Number of written bytes
  7101. var numberOfWrittenBytes = !isArray
  7102. ? buffer.write(key, index, undefined, 'utf8')
  7103. : buffer.write(key, index, undefined, 'ascii');
  7104. // Encode the name
  7105. index = index + numberOfWrittenBytes;
  7106. buffer[index++] = 0;
  7107. // Write the int value
  7108. buffer[index++] = value & 0xff;
  7109. buffer[index++] = (value >> 8) & 0xff;
  7110. buffer[index++] = (value >> 16) & 0xff;
  7111. buffer[index++] = (value >> 24) & 0xff;
  7112. }
  7113. else {
  7114. // Encode as double
  7115. buffer[index++] = constants.BSON_DATA_NUMBER;
  7116. // Number of written bytes
  7117. var numberOfWrittenBytes = !isArray
  7118. ? buffer.write(key, index, undefined, 'utf8')
  7119. : buffer.write(key, index, undefined, 'ascii');
  7120. // Encode the name
  7121. index = index + numberOfWrittenBytes;
  7122. buffer[index++] = 0;
  7123. // Write float
  7124. float_parser.writeIEEE754(buffer, value, index, 'little', 52, 8);
  7125. // Adjust index
  7126. index = index + 8;
  7127. }
  7128. return index;
  7129. }
  7130. function serializeNull(buffer, key, _, index, isArray) {
  7131. // Set long type
  7132. buffer[index++] = constants.BSON_DATA_NULL;
  7133. // Number of written bytes
  7134. var numberOfWrittenBytes = !isArray
  7135. ? buffer.write(key, index, undefined, 'utf8')
  7136. : buffer.write(key, index, undefined, 'ascii');
  7137. // Encode the name
  7138. index = index + numberOfWrittenBytes;
  7139. buffer[index++] = 0;
  7140. return index;
  7141. }
  7142. function serializeBoolean(buffer, key, value, index, isArray) {
  7143. // Write the type
  7144. buffer[index++] = constants.BSON_DATA_BOOLEAN;
  7145. // Number of written bytes
  7146. var numberOfWrittenBytes = !isArray
  7147. ? buffer.write(key, index, undefined, 'utf8')
  7148. : buffer.write(key, index, undefined, 'ascii');
  7149. // Encode the name
  7150. index = index + numberOfWrittenBytes;
  7151. buffer[index++] = 0;
  7152. // Encode the boolean value
  7153. buffer[index++] = value ? 1 : 0;
  7154. return index;
  7155. }
  7156. function serializeDate(buffer, key, value, index, isArray) {
  7157. // Write the type
  7158. buffer[index++] = constants.BSON_DATA_DATE;
  7159. // Number of written bytes
  7160. var numberOfWrittenBytes = !isArray
  7161. ? buffer.write(key, index, undefined, 'utf8')
  7162. : buffer.write(key, index, undefined, 'ascii');
  7163. // Encode the name
  7164. index = index + numberOfWrittenBytes;
  7165. buffer[index++] = 0;
  7166. // Write the date
  7167. var dateInMilis = long_1.Long.fromNumber(value.getTime());
  7168. var lowBits = dateInMilis.getLowBits();
  7169. var highBits = dateInMilis.getHighBits();
  7170. // Encode low bits
  7171. buffer[index++] = lowBits & 0xff;
  7172. buffer[index++] = (lowBits >> 8) & 0xff;
  7173. buffer[index++] = (lowBits >> 16) & 0xff;
  7174. buffer[index++] = (lowBits >> 24) & 0xff;
  7175. // Encode high bits
  7176. buffer[index++] = highBits & 0xff;
  7177. buffer[index++] = (highBits >> 8) & 0xff;
  7178. buffer[index++] = (highBits >> 16) & 0xff;
  7179. buffer[index++] = (highBits >> 24) & 0xff;
  7180. return index;
  7181. }
  7182. function serializeRegExp(buffer, key, value, index, isArray) {
  7183. // Write the type
  7184. buffer[index++] = constants.BSON_DATA_REGEXP;
  7185. // Number of written bytes
  7186. var numberOfWrittenBytes = !isArray
  7187. ? buffer.write(key, index, undefined, 'utf8')
  7188. : buffer.write(key, index, undefined, 'ascii');
  7189. // Encode the name
  7190. index = index + numberOfWrittenBytes;
  7191. buffer[index++] = 0;
  7192. if (value.source && value.source.match(regexp) != null) {
  7193. throw Error('value ' + value.source + ' must not contain null bytes');
  7194. }
  7195. // Adjust the index
  7196. index = index + buffer.write(value.source, index, undefined, 'utf8');
  7197. // Write zero
  7198. buffer[index++] = 0x00;
  7199. // Write the parameters
  7200. if (value.ignoreCase)
  7201. buffer[index++] = 0x69; // i
  7202. if (value.global)
  7203. buffer[index++] = 0x73; // s
  7204. if (value.multiline)
  7205. buffer[index++] = 0x6d; // m
  7206. // Add ending zero
  7207. buffer[index++] = 0x00;
  7208. return index;
  7209. }
  7210. function serializeBSONRegExp(buffer, key, value, index, isArray) {
  7211. // Write the type
  7212. buffer[index++] = constants.BSON_DATA_REGEXP;
  7213. // Number of written bytes
  7214. var numberOfWrittenBytes = !isArray
  7215. ? buffer.write(key, index, undefined, 'utf8')
  7216. : buffer.write(key, index, undefined, 'ascii');
  7217. // Encode the name
  7218. index = index + numberOfWrittenBytes;
  7219. buffer[index++] = 0;
  7220. // Check the pattern for 0 bytes
  7221. if (value.pattern.match(regexp) != null) {
  7222. // The BSON spec doesn't allow keys with null bytes because keys are
  7223. // null-terminated.
  7224. throw Error('pattern ' + value.pattern + ' must not contain null bytes');
  7225. }
  7226. // Adjust the index
  7227. index = index + buffer.write(value.pattern, index, undefined, 'utf8');
  7228. // Write zero
  7229. buffer[index++] = 0x00;
  7230. // Write the options
  7231. index = index + buffer.write(value.options.split('').sort().join(''), index, undefined, 'utf8');
  7232. // Add ending zero
  7233. buffer[index++] = 0x00;
  7234. return index;
  7235. }
  7236. function serializeMinMax(buffer, key, value, index, isArray) {
  7237. // Write the type of either min or max key
  7238. if (value === null) {
  7239. buffer[index++] = constants.BSON_DATA_NULL;
  7240. }
  7241. else if (value._bsontype === 'MinKey') {
  7242. buffer[index++] = constants.BSON_DATA_MIN_KEY;
  7243. }
  7244. else {
  7245. buffer[index++] = constants.BSON_DATA_MAX_KEY;
  7246. }
  7247. // Number of written bytes
  7248. var numberOfWrittenBytes = !isArray
  7249. ? buffer.write(key, index, undefined, 'utf8')
  7250. : buffer.write(key, index, undefined, 'ascii');
  7251. // Encode the name
  7252. index = index + numberOfWrittenBytes;
  7253. buffer[index++] = 0;
  7254. return index;
  7255. }
  7256. function serializeObjectId(buffer, key, value, index, isArray) {
  7257. // Write the type
  7258. buffer[index++] = constants.BSON_DATA_OID;
  7259. // Number of written bytes
  7260. var numberOfWrittenBytes = !isArray
  7261. ? buffer.write(key, index, undefined, 'utf8')
  7262. : buffer.write(key, index, undefined, 'ascii');
  7263. // Encode the name
  7264. index = index + numberOfWrittenBytes;
  7265. buffer[index++] = 0;
  7266. // Write the objectId into the shared buffer
  7267. if (typeof value.id === 'string') {
  7268. buffer.write(value.id, index, undefined, 'binary');
  7269. }
  7270. else if (utils.isUint8Array(value.id)) {
  7271. // Use the standard JS methods here because buffer.copy() is buggy with the
  7272. // browser polyfill
  7273. buffer.set(value.id.subarray(0, 12), index);
  7274. }
  7275. else {
  7276. throw new TypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId');
  7277. }
  7278. // Adjust index
  7279. return index + 12;
  7280. }
  7281. function serializeBuffer(buffer, key, value, index, isArray) {
  7282. // Write the type
  7283. buffer[index++] = constants.BSON_DATA_BINARY;
  7284. // Number of written bytes
  7285. var numberOfWrittenBytes = !isArray
  7286. ? buffer.write(key, index, undefined, 'utf8')
  7287. : buffer.write(key, index, undefined, 'ascii');
  7288. // Encode the name
  7289. index = index + numberOfWrittenBytes;
  7290. buffer[index++] = 0;
  7291. // Get size of the buffer (current write point)
  7292. var size = value.length;
  7293. // Write the size of the string to buffer
  7294. buffer[index++] = size & 0xff;
  7295. buffer[index++] = (size >> 8) & 0xff;
  7296. buffer[index++] = (size >> 16) & 0xff;
  7297. buffer[index++] = (size >> 24) & 0xff;
  7298. // Write the default subtype
  7299. buffer[index++] = constants.BSON_BINARY_SUBTYPE_DEFAULT;
  7300. // Copy the content form the binary field to the buffer
  7301. buffer.set(ensure_buffer.ensureBuffer(value), index);
  7302. // Adjust the index
  7303. index = index + size;
  7304. return index;
  7305. }
  7306. function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) {
  7307. if (checkKeys === void 0) { checkKeys = false; }
  7308. if (depth === void 0) { depth = 0; }
  7309. if (serializeFunctions === void 0) { serializeFunctions = false; }
  7310. if (ignoreUndefined === void 0) { ignoreUndefined = true; }
  7311. if (isArray === void 0) { isArray = false; }
  7312. if (path === void 0) { path = []; }
  7313. for (var i = 0; i < path.length; i++) {
  7314. if (path[i] === value)
  7315. throw new Error('cyclic dependency detected');
  7316. }
  7317. // Push value to stack
  7318. path.push(value);
  7319. // Write the type
  7320. buffer[index++] = Array.isArray(value) ? constants.BSON_DATA_ARRAY : constants.BSON_DATA_OBJECT;
  7321. // Number of written bytes
  7322. var numberOfWrittenBytes = !isArray
  7323. ? buffer.write(key, index, undefined, 'utf8')
  7324. : buffer.write(key, index, undefined, 'ascii');
  7325. // Encode the name
  7326. index = index + numberOfWrittenBytes;
  7327. buffer[index++] = 0;
  7328. var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
  7329. // Pop stack
  7330. path.pop();
  7331. return endIndex;
  7332. }
  7333. function serializeDecimal128(buffer, key, value, index, isArray) {
  7334. buffer[index++] = constants.BSON_DATA_DECIMAL128;
  7335. // Number of written bytes
  7336. var numberOfWrittenBytes = !isArray
  7337. ? buffer.write(key, index, undefined, 'utf8')
  7338. : buffer.write(key, index, undefined, 'ascii');
  7339. // Encode the name
  7340. index = index + numberOfWrittenBytes;
  7341. buffer[index++] = 0;
  7342. // Write the data from the value
  7343. // Prefer the standard JS methods because their typechecking is not buggy,
  7344. // unlike the `buffer` polyfill's.
  7345. buffer.set(value.bytes.subarray(0, 16), index);
  7346. return index + 16;
  7347. }
  7348. function serializeLong(buffer, key, value, index, isArray) {
  7349. // Write the type
  7350. buffer[index++] =
  7351. value._bsontype === 'Long' ? constants.BSON_DATA_LONG : constants.BSON_DATA_TIMESTAMP;
  7352. // Number of written bytes
  7353. var numberOfWrittenBytes = !isArray
  7354. ? buffer.write(key, index, undefined, 'utf8')
  7355. : buffer.write(key, index, undefined, 'ascii');
  7356. // Encode the name
  7357. index = index + numberOfWrittenBytes;
  7358. buffer[index++] = 0;
  7359. // Write the date
  7360. var lowBits = value.getLowBits();
  7361. var highBits = value.getHighBits();
  7362. // Encode low bits
  7363. buffer[index++] = lowBits & 0xff;
  7364. buffer[index++] = (lowBits >> 8) & 0xff;
  7365. buffer[index++] = (lowBits >> 16) & 0xff;
  7366. buffer[index++] = (lowBits >> 24) & 0xff;
  7367. // Encode high bits
  7368. buffer[index++] = highBits & 0xff;
  7369. buffer[index++] = (highBits >> 8) & 0xff;
  7370. buffer[index++] = (highBits >> 16) & 0xff;
  7371. buffer[index++] = (highBits >> 24) & 0xff;
  7372. return index;
  7373. }
  7374. function serializeInt32(buffer, key, value, index, isArray) {
  7375. value = value.valueOf();
  7376. // Set int type 32 bits or less
  7377. buffer[index++] = constants.BSON_DATA_INT;
  7378. // Number of written bytes
  7379. var numberOfWrittenBytes = !isArray
  7380. ? buffer.write(key, index, undefined, 'utf8')
  7381. : buffer.write(key, index, undefined, 'ascii');
  7382. // Encode the name
  7383. index = index + numberOfWrittenBytes;
  7384. buffer[index++] = 0;
  7385. // Write the int value
  7386. buffer[index++] = value & 0xff;
  7387. buffer[index++] = (value >> 8) & 0xff;
  7388. buffer[index++] = (value >> 16) & 0xff;
  7389. buffer[index++] = (value >> 24) & 0xff;
  7390. return index;
  7391. }
  7392. function serializeDouble(buffer, key, value, index, isArray) {
  7393. // Encode as double
  7394. buffer[index++] = constants.BSON_DATA_NUMBER;
  7395. // Number of written bytes
  7396. var numberOfWrittenBytes = !isArray
  7397. ? buffer.write(key, index, undefined, 'utf8')
  7398. : buffer.write(key, index, undefined, 'ascii');
  7399. // Encode the name
  7400. index = index + numberOfWrittenBytes;
  7401. buffer[index++] = 0;
  7402. // Write float
  7403. float_parser.writeIEEE754(buffer, value.value, index, 'little', 52, 8);
  7404. // Adjust index
  7405. index = index + 8;
  7406. return index;
  7407. }
  7408. function serializeFunction(buffer, key, value, index, _checkKeys, _depth, isArray) {
  7409. buffer[index++] = constants.BSON_DATA_CODE;
  7410. // Number of written bytes
  7411. var numberOfWrittenBytes = !isArray
  7412. ? buffer.write(key, index, undefined, 'utf8')
  7413. : buffer.write(key, index, undefined, 'ascii');
  7414. // Encode the name
  7415. index = index + numberOfWrittenBytes;
  7416. buffer[index++] = 0;
  7417. // Function string
  7418. var functionString = utils.normalizedFunctionString(value);
  7419. // Write the string
  7420. var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1;
  7421. // Write the size of the string to buffer
  7422. buffer[index] = size & 0xff;
  7423. buffer[index + 1] = (size >> 8) & 0xff;
  7424. buffer[index + 2] = (size >> 16) & 0xff;
  7425. buffer[index + 3] = (size >> 24) & 0xff;
  7426. // Update index
  7427. index = index + 4 + size - 1;
  7428. // Write zero
  7429. buffer[index++] = 0;
  7430. return index;
  7431. }
  7432. function serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) {
  7433. if (checkKeys === void 0) { checkKeys = false; }
  7434. if (depth === void 0) { depth = 0; }
  7435. if (serializeFunctions === void 0) { serializeFunctions = false; }
  7436. if (ignoreUndefined === void 0) { ignoreUndefined = true; }
  7437. if (isArray === void 0) { isArray = false; }
  7438. if (value.scope && typeof value.scope === 'object') {
  7439. // Write the type
  7440. buffer[index++] = constants.BSON_DATA_CODE_W_SCOPE;
  7441. // Number of written bytes
  7442. var numberOfWrittenBytes = !isArray
  7443. ? buffer.write(key, index, undefined, 'utf8')
  7444. : buffer.write(key, index, undefined, 'ascii');
  7445. // Encode the name
  7446. index = index + numberOfWrittenBytes;
  7447. buffer[index++] = 0;
  7448. // Starting index
  7449. var startIndex = index;
  7450. // Serialize the function
  7451. // Get the function string
  7452. var functionString = typeof value.code === 'string' ? value.code : value.code.toString();
  7453. // Index adjustment
  7454. index = index + 4;
  7455. // Write string into buffer
  7456. var codeSize = buffer.write(functionString, index + 4, undefined, 'utf8') + 1;
  7457. // Write the size of the string to buffer
  7458. buffer[index] = codeSize & 0xff;
  7459. buffer[index + 1] = (codeSize >> 8) & 0xff;
  7460. buffer[index + 2] = (codeSize >> 16) & 0xff;
  7461. buffer[index + 3] = (codeSize >> 24) & 0xff;
  7462. // Write end 0
  7463. buffer[index + 4 + codeSize - 1] = 0;
  7464. // Write the
  7465. index = index + codeSize + 4;
  7466. //
  7467. // Serialize the scope value
  7468. var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined);
  7469. index = endIndex - 1;
  7470. // Writ the total
  7471. var totalSize = endIndex - startIndex;
  7472. // Write the total size of the object
  7473. buffer[startIndex++] = totalSize & 0xff;
  7474. buffer[startIndex++] = (totalSize >> 8) & 0xff;
  7475. buffer[startIndex++] = (totalSize >> 16) & 0xff;
  7476. buffer[startIndex++] = (totalSize >> 24) & 0xff;
  7477. // Write trailing zero
  7478. buffer[index++] = 0;
  7479. }
  7480. else {
  7481. buffer[index++] = constants.BSON_DATA_CODE;
  7482. // Number of written bytes
  7483. var numberOfWrittenBytes = !isArray
  7484. ? buffer.write(key, index, undefined, 'utf8')
  7485. : buffer.write(key, index, undefined, 'ascii');
  7486. // Encode the name
  7487. index = index + numberOfWrittenBytes;
  7488. buffer[index++] = 0;
  7489. // Function string
  7490. var functionString = value.code.toString();
  7491. // Write the string
  7492. var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1;
  7493. // Write the size of the string to buffer
  7494. buffer[index] = size & 0xff;
  7495. buffer[index + 1] = (size >> 8) & 0xff;
  7496. buffer[index + 2] = (size >> 16) & 0xff;
  7497. buffer[index + 3] = (size >> 24) & 0xff;
  7498. // Update index
  7499. index = index + 4 + size - 1;
  7500. // Write zero
  7501. buffer[index++] = 0;
  7502. }
  7503. return index;
  7504. }
  7505. function serializeBinary(buffer, key, value, index, isArray) {
  7506. // Write the type
  7507. buffer[index++] = constants.BSON_DATA_BINARY;
  7508. // Number of written bytes
  7509. var numberOfWrittenBytes = !isArray
  7510. ? buffer.write(key, index, undefined, 'utf8')
  7511. : buffer.write(key, index, undefined, 'ascii');
  7512. // Encode the name
  7513. index = index + numberOfWrittenBytes;
  7514. buffer[index++] = 0;
  7515. // Extract the buffer
  7516. var data = value.value(true);
  7517. // Calculate size
  7518. var size = value.position;
  7519. // Add the deprecated 02 type 4 bytes of size to total
  7520. if (value.sub_type === binary.Binary.SUBTYPE_BYTE_ARRAY)
  7521. size = size + 4;
  7522. // Write the size of the string to buffer
  7523. buffer[index++] = size & 0xff;
  7524. buffer[index++] = (size >> 8) & 0xff;
  7525. buffer[index++] = (size >> 16) & 0xff;
  7526. buffer[index++] = (size >> 24) & 0xff;
  7527. // Write the subtype to the buffer
  7528. buffer[index++] = value.sub_type;
  7529. // If we have binary type 2 the 4 first bytes are the size
  7530. if (value.sub_type === binary.Binary.SUBTYPE_BYTE_ARRAY) {
  7531. size = size - 4;
  7532. buffer[index++] = size & 0xff;
  7533. buffer[index++] = (size >> 8) & 0xff;
  7534. buffer[index++] = (size >> 16) & 0xff;
  7535. buffer[index++] = (size >> 24) & 0xff;
  7536. }
  7537. // Write the data to the object
  7538. buffer.set(data, index);
  7539. // Adjust the index
  7540. index = index + value.position;
  7541. return index;
  7542. }
  7543. function serializeSymbol(buffer, key, value, index, isArray) {
  7544. // Write the type
  7545. buffer[index++] = constants.BSON_DATA_SYMBOL;
  7546. // Number of written bytes
  7547. var numberOfWrittenBytes = !isArray
  7548. ? buffer.write(key, index, undefined, 'utf8')
  7549. : buffer.write(key, index, undefined, 'ascii');
  7550. // Encode the name
  7551. index = index + numberOfWrittenBytes;
  7552. buffer[index++] = 0;
  7553. // Write the string
  7554. var size = buffer.write(value.value, index + 4, undefined, 'utf8') + 1;
  7555. // Write the size of the string to buffer
  7556. buffer[index] = size & 0xff;
  7557. buffer[index + 1] = (size >> 8) & 0xff;
  7558. buffer[index + 2] = (size >> 16) & 0xff;
  7559. buffer[index + 3] = (size >> 24) & 0xff;
  7560. // Update index
  7561. index = index + 4 + size - 1;
  7562. // Write zero
  7563. buffer[index++] = 0x00;
  7564. return index;
  7565. }
  7566. function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, isArray) {
  7567. // Write the type
  7568. buffer[index++] = constants.BSON_DATA_OBJECT;
  7569. // Number of written bytes
  7570. var numberOfWrittenBytes = !isArray
  7571. ? buffer.write(key, index, undefined, 'utf8')
  7572. : buffer.write(key, index, undefined, 'ascii');
  7573. // Encode the name
  7574. index = index + numberOfWrittenBytes;
  7575. buffer[index++] = 0;
  7576. var startIndex = index;
  7577. var output = {
  7578. $ref: value.collection || value.namespace,
  7579. $id: value.oid
  7580. };
  7581. if (value.db != null) {
  7582. output.$db = value.db;
  7583. }
  7584. output = Object.assign(output, value.fields);
  7585. var endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions);
  7586. // Calculate object size
  7587. var size = endIndex - startIndex;
  7588. // Write the size
  7589. buffer[startIndex++] = size & 0xff;
  7590. buffer[startIndex++] = (size >> 8) & 0xff;
  7591. buffer[startIndex++] = (size >> 16) & 0xff;
  7592. buffer[startIndex++] = (size >> 24) & 0xff;
  7593. // Set index
  7594. return endIndex;
  7595. }
  7596. function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) {
  7597. if (checkKeys === void 0) { checkKeys = false; }
  7598. if (startingIndex === void 0) { startingIndex = 0; }
  7599. if (depth === void 0) { depth = 0; }
  7600. if (serializeFunctions === void 0) { serializeFunctions = false; }
  7601. if (ignoreUndefined === void 0) { ignoreUndefined = true; }
  7602. if (path === void 0) { path = []; }
  7603. startingIndex = startingIndex || 0;
  7604. path = path || [];
  7605. // Push the object to the path
  7606. path.push(object);
  7607. // Start place to serialize into
  7608. var index = startingIndex + 4;
  7609. // Special case isArray
  7610. if (Array.isArray(object)) {
  7611. // Get object keys
  7612. for (var i = 0; i < object.length; i++) {
  7613. var key = '' + i;
  7614. var value = object[i];
  7615. // Is there an override value
  7616. if (value && value.toBSON) {
  7617. if (typeof value.toBSON !== 'function')
  7618. throw new TypeError('toBSON is not a function');
  7619. value = value.toBSON();
  7620. }
  7621. if (typeof value === 'string') {
  7622. index = serializeString(buffer, key, value, index, true);
  7623. }
  7624. else if (typeof value === 'number') {
  7625. index = serializeNumber(buffer, key, value, index, true);
  7626. }
  7627. else if (typeof value === 'bigint') {
  7628. throw new TypeError('Unsupported type BigInt, please use Decimal128');
  7629. }
  7630. else if (typeof value === 'boolean') {
  7631. index = serializeBoolean(buffer, key, value, index, true);
  7632. }
  7633. else if (value instanceof Date || utils.isDate(value)) {
  7634. index = serializeDate(buffer, key, value, index, true);
  7635. }
  7636. else if (value === undefined) {
  7637. index = serializeNull(buffer, key, value, index, true);
  7638. }
  7639. else if (value === null) {
  7640. index = serializeNull(buffer, key, value, index, true);
  7641. }
  7642. else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') {
  7643. index = serializeObjectId(buffer, key, value, index, true);
  7644. }
  7645. else if (utils.isUint8Array(value)) {
  7646. index = serializeBuffer(buffer, key, value, index, true);
  7647. }
  7648. else if (value instanceof RegExp || utils.isRegExp(value)) {
  7649. index = serializeRegExp(buffer, key, value, index, true);
  7650. }
  7651. else if (typeof value === 'object' && value['_bsontype'] == null) {
  7652. index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path);
  7653. }
  7654. else if (typeof value === 'object' &&
  7655. extended_json.isBSONType(value) &&
  7656. value._bsontype === 'Decimal128') {
  7657. index = serializeDecimal128(buffer, key, value, index, true);
  7658. }
  7659. else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') {
  7660. index = serializeLong(buffer, key, value, index, true);
  7661. }
  7662. else if (value['_bsontype'] === 'Double') {
  7663. index = serializeDouble(buffer, key, value, index, true);
  7664. }
  7665. else if (typeof value === 'function' && serializeFunctions) {
  7666. index = serializeFunction(buffer, key, value, index, checkKeys, depth, true);
  7667. }
  7668. else if (value['_bsontype'] === 'Code') {
  7669. index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true);
  7670. }
  7671. else if (value['_bsontype'] === 'Binary') {
  7672. index = serializeBinary(buffer, key, value, index, true);
  7673. }
  7674. else if (value['_bsontype'] === 'Symbol') {
  7675. index = serializeSymbol(buffer, key, value, index, true);
  7676. }
  7677. else if (value['_bsontype'] === 'DBRef') {
  7678. index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true);
  7679. }
  7680. else if (value['_bsontype'] === 'BSONRegExp') {
  7681. index = serializeBSONRegExp(buffer, key, value, index, true);
  7682. }
  7683. else if (value['_bsontype'] === 'Int32') {
  7684. index = serializeInt32(buffer, key, value, index, true);
  7685. }
  7686. else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
  7687. index = serializeMinMax(buffer, key, value, index, true);
  7688. }
  7689. else if (typeof value['_bsontype'] !== 'undefined') {
  7690. throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
  7691. }
  7692. }
  7693. }
  7694. else if (object instanceof map.Map || utils.isMap(object)) {
  7695. var iterator = object.entries();
  7696. var done = false;
  7697. while (!done) {
  7698. // Unpack the next entry
  7699. var entry = iterator.next();
  7700. done = !!entry.done;
  7701. // Are we done, then skip and terminate
  7702. if (done)
  7703. continue;
  7704. // Get the entry values
  7705. var key = entry.value[0];
  7706. var value = entry.value[1];
  7707. // Check the type of the value
  7708. var type = typeof value;
  7709. // Check the key and throw error if it's illegal
  7710. if (typeof key === 'string' && !ignoreKeys.has(key)) {
  7711. if (key.match(regexp) != null) {
  7712. // The BSON spec doesn't allow keys with null bytes because keys are
  7713. // null-terminated.
  7714. throw Error('key ' + key + ' must not contain null bytes');
  7715. }
  7716. if (checkKeys) {
  7717. if ('$' === key[0]) {
  7718. throw Error('key ' + key + " must not start with '$'");
  7719. }
  7720. else if (~key.indexOf('.')) {
  7721. throw Error('key ' + key + " must not contain '.'");
  7722. }
  7723. }
  7724. }
  7725. if (type === 'string') {
  7726. index = serializeString(buffer, key, value, index);
  7727. }
  7728. else if (type === 'number') {
  7729. index = serializeNumber(buffer, key, value, index);
  7730. }
  7731. else if (type === 'bigint' || utils.isBigInt64Array(value) || utils.isBigUInt64Array(value)) {
  7732. throw new TypeError('Unsupported type BigInt, please use Decimal128');
  7733. }
  7734. else if (type === 'boolean') {
  7735. index = serializeBoolean(buffer, key, value, index);
  7736. }
  7737. else if (value instanceof Date || utils.isDate(value)) {
  7738. index = serializeDate(buffer, key, value, index);
  7739. }
  7740. else if (value === null || (value === undefined && ignoreUndefined === false)) {
  7741. index = serializeNull(buffer, key, value, index);
  7742. }
  7743. else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') {
  7744. index = serializeObjectId(buffer, key, value, index);
  7745. }
  7746. else if (utils.isUint8Array(value)) {
  7747. index = serializeBuffer(buffer, key, value, index);
  7748. }
  7749. else if (value instanceof RegExp || utils.isRegExp(value)) {
  7750. index = serializeRegExp(buffer, key, value, index);
  7751. }
  7752. else if (type === 'object' && value['_bsontype'] == null) {
  7753. index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path);
  7754. }
  7755. else if (type === 'object' && value['_bsontype'] === 'Decimal128') {
  7756. index = serializeDecimal128(buffer, key, value, index);
  7757. }
  7758. else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') {
  7759. index = serializeLong(buffer, key, value, index);
  7760. }
  7761. else if (value['_bsontype'] === 'Double') {
  7762. index = serializeDouble(buffer, key, value, index);
  7763. }
  7764. else if (value['_bsontype'] === 'Code') {
  7765. index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined);
  7766. }
  7767. else if (typeof value === 'function' && serializeFunctions) {
  7768. index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions);
  7769. }
  7770. else if (value['_bsontype'] === 'Binary') {
  7771. index = serializeBinary(buffer, key, value, index);
  7772. }
  7773. else if (value['_bsontype'] === 'Symbol') {
  7774. index = serializeSymbol(buffer, key, value, index);
  7775. }
  7776. else if (value['_bsontype'] === 'DBRef') {
  7777. index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions);
  7778. }
  7779. else if (value['_bsontype'] === 'BSONRegExp') {
  7780. index = serializeBSONRegExp(buffer, key, value, index);
  7781. }
  7782. else if (value['_bsontype'] === 'Int32') {
  7783. index = serializeInt32(buffer, key, value, index);
  7784. }
  7785. else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
  7786. index = serializeMinMax(buffer, key, value, index);
  7787. }
  7788. else if (typeof value['_bsontype'] !== 'undefined') {
  7789. throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
  7790. }
  7791. }
  7792. }
  7793. else {
  7794. // Did we provide a custom serialization method
  7795. if (object.toBSON) {
  7796. if (typeof object.toBSON !== 'function')
  7797. throw new TypeError('toBSON is not a function');
  7798. object = object.toBSON();
  7799. if (object != null && typeof object !== 'object')
  7800. throw new TypeError('toBSON function did not return an object');
  7801. }
  7802. // Iterate over all the keys
  7803. for (var key in object) {
  7804. var value = object[key];
  7805. // Is there an override value
  7806. if (value && value.toBSON) {
  7807. if (typeof value.toBSON !== 'function')
  7808. throw new TypeError('toBSON is not a function');
  7809. value = value.toBSON();
  7810. }
  7811. // Check the type of the value
  7812. var type = typeof value;
  7813. // Check the key and throw error if it's illegal
  7814. if (typeof key === 'string' && !ignoreKeys.has(key)) {
  7815. if (key.match(regexp) != null) {
  7816. // The BSON spec doesn't allow keys with null bytes because keys are
  7817. // null-terminated.
  7818. throw Error('key ' + key + ' must not contain null bytes');
  7819. }
  7820. if (checkKeys) {
  7821. if ('$' === key[0]) {
  7822. throw Error('key ' + key + " must not start with '$'");
  7823. }
  7824. else if (~key.indexOf('.')) {
  7825. throw Error('key ' + key + " must not contain '.'");
  7826. }
  7827. }
  7828. }
  7829. if (type === 'string') {
  7830. index = serializeString(buffer, key, value, index);
  7831. }
  7832. else if (type === 'number') {
  7833. index = serializeNumber(buffer, key, value, index);
  7834. }
  7835. else if (type === 'bigint') {
  7836. throw new TypeError('Unsupported type BigInt, please use Decimal128');
  7837. }
  7838. else if (type === 'boolean') {
  7839. index = serializeBoolean(buffer, key, value, index);
  7840. }
  7841. else if (value instanceof Date || utils.isDate(value)) {
  7842. index = serializeDate(buffer, key, value, index);
  7843. }
  7844. else if (value === undefined) {
  7845. if (ignoreUndefined === false)
  7846. index = serializeNull(buffer, key, value, index);
  7847. }
  7848. else if (value === null) {
  7849. index = serializeNull(buffer, key, value, index);
  7850. }
  7851. else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') {
  7852. index = serializeObjectId(buffer, key, value, index);
  7853. }
  7854. else if (utils.isUint8Array(value)) {
  7855. index = serializeBuffer(buffer, key, value, index);
  7856. }
  7857. else if (value instanceof RegExp || utils.isRegExp(value)) {
  7858. index = serializeRegExp(buffer, key, value, index);
  7859. }
  7860. else if (type === 'object' && value['_bsontype'] == null) {
  7861. index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path);
  7862. }
  7863. else if (type === 'object' && value['_bsontype'] === 'Decimal128') {
  7864. index = serializeDecimal128(buffer, key, value, index);
  7865. }
  7866. else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') {
  7867. index = serializeLong(buffer, key, value, index);
  7868. }
  7869. else if (value['_bsontype'] === 'Double') {
  7870. index = serializeDouble(buffer, key, value, index);
  7871. }
  7872. else if (value['_bsontype'] === 'Code') {
  7873. index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined);
  7874. }
  7875. else if (typeof value === 'function' && serializeFunctions) {
  7876. index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions);
  7877. }
  7878. else if (value['_bsontype'] === 'Binary') {
  7879. index = serializeBinary(buffer, key, value, index);
  7880. }
  7881. else if (value['_bsontype'] === 'Symbol') {
  7882. index = serializeSymbol(buffer, key, value, index);
  7883. }
  7884. else if (value['_bsontype'] === 'DBRef') {
  7885. index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions);
  7886. }
  7887. else if (value['_bsontype'] === 'BSONRegExp') {
  7888. index = serializeBSONRegExp(buffer, key, value, index);
  7889. }
  7890. else if (value['_bsontype'] === 'Int32') {
  7891. index = serializeInt32(buffer, key, value, index);
  7892. }
  7893. else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
  7894. index = serializeMinMax(buffer, key, value, index);
  7895. }
  7896. else if (typeof value['_bsontype'] !== 'undefined') {
  7897. throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
  7898. }
  7899. }
  7900. }
  7901. // Remove the path
  7902. path.pop();
  7903. // Final padding byte for object
  7904. buffer[index++] = 0x00;
  7905. // Final size
  7906. var size = index - startingIndex;
  7907. // Write the size of the object
  7908. buffer[startingIndex++] = size & 0xff;
  7909. buffer[startingIndex++] = (size >> 8) & 0xff;
  7910. buffer[startingIndex++] = (size >> 16) & 0xff;
  7911. buffer[startingIndex++] = (size >> 24) & 0xff;
  7912. return index;
  7913. }
  7914. exports.serializeInto = serializeInto;
  7915. });
  7916. unwrapExports(serializer);
  7917. serializer.serializeInto;
  7918. var bson = createCommonjsModule(function (module, exports) {
  7919. Object.defineProperty(exports, "__esModule", { value: true });
  7920. exports.ObjectID = exports.Decimal128 = exports.BSONRegExp = exports.MaxKey = exports.MinKey = exports.Int32 = exports.Double = exports.Timestamp = exports.Long = exports.UUID = exports.ObjectId = exports.Binary = exports.DBRef = exports.BSONSymbol = exports.Map = exports.Code = exports.LongWithoutOverridesClass = exports.EJSON = exports.BSON_INT64_MIN = exports.BSON_INT64_MAX = exports.BSON_INT32_MIN = exports.BSON_INT32_MAX = exports.BSON_DATA_UNDEFINED = exports.BSON_DATA_TIMESTAMP = exports.BSON_DATA_SYMBOL = exports.BSON_DATA_STRING = exports.BSON_DATA_REGEXP = exports.BSON_DATA_OID = exports.BSON_DATA_OBJECT = exports.BSON_DATA_NUMBER = exports.BSON_DATA_NULL = exports.BSON_DATA_MIN_KEY = exports.BSON_DATA_MAX_KEY = exports.BSON_DATA_LONG = exports.BSON_DATA_INT = exports.BSON_DATA_DECIMAL128 = exports.BSON_DATA_DBPOINTER = exports.BSON_DATA_DATE = exports.BSON_DATA_CODE_W_SCOPE = exports.BSON_DATA_CODE = exports.BSON_DATA_BOOLEAN = exports.BSON_DATA_BINARY = exports.BSON_DATA_ARRAY = exports.BSON_BINARY_SUBTYPE_UUID_NEW = exports.BSON_BINARY_SUBTYPE_UUID = exports.BSON_BINARY_SUBTYPE_USER_DEFINED = exports.BSON_BINARY_SUBTYPE_MD5 = exports.BSON_BINARY_SUBTYPE_FUNCTION = exports.BSON_BINARY_SUBTYPE_DEFAULT = exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = void 0;
  7921. exports.deserializeStream = exports.calculateObjectSize = exports.deserialize = exports.serializeWithBufferAndIndex = exports.serialize = exports.setInternalBufferSize = void 0;
  7922. Object.defineProperty(exports, "Binary", { enumerable: true, get: function () { return binary.Binary; } });
  7923. Object.defineProperty(exports, "Code", { enumerable: true, get: function () { return code.Code; } });
  7924. Object.defineProperty(exports, "DBRef", { enumerable: true, get: function () { return db_ref.DBRef; } });
  7925. Object.defineProperty(exports, "Decimal128", { enumerable: true, get: function () { return decimal128.Decimal128; } });
  7926. Object.defineProperty(exports, "Double", { enumerable: true, get: function () { return double_1.Double; } });
  7927. Object.defineProperty(exports, "Int32", { enumerable: true, get: function () { return int_32.Int32; } });
  7928. Object.defineProperty(exports, "Long", { enumerable: true, get: function () { return long_1.Long; } });
  7929. Object.defineProperty(exports, "Map", { enumerable: true, get: function () { return map.Map; } });
  7930. Object.defineProperty(exports, "MaxKey", { enumerable: true, get: function () { return max_key.MaxKey; } });
  7931. Object.defineProperty(exports, "MinKey", { enumerable: true, get: function () { return min_key.MinKey; } });
  7932. Object.defineProperty(exports, "ObjectId", { enumerable: true, get: function () { return objectid.ObjectId; } });
  7933. Object.defineProperty(exports, "ObjectID", { enumerable: true, get: function () { return objectid.ObjectId; } });
  7934. // Parts of the parser
  7935. Object.defineProperty(exports, "BSONRegExp", { enumerable: true, get: function () { return regexp.BSONRegExp; } });
  7936. Object.defineProperty(exports, "BSONSymbol", { enumerable: true, get: function () { return symbol.BSONSymbol; } });
  7937. Object.defineProperty(exports, "Timestamp", { enumerable: true, get: function () { return timestamp.Timestamp; } });
  7938. Object.defineProperty(exports, "UUID", { enumerable: true, get: function () { return uuid.UUID; } });
  7939. Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_BYTE_ARRAY", { enumerable: true, get: function () { return constants.BSON_BINARY_SUBTYPE_BYTE_ARRAY; } });
  7940. Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_DEFAULT", { enumerable: true, get: function () { return constants.BSON_BINARY_SUBTYPE_DEFAULT; } });
  7941. Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_FUNCTION", { enumerable: true, get: function () { return constants.BSON_BINARY_SUBTYPE_FUNCTION; } });
  7942. Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_MD5", { enumerable: true, get: function () { return constants.BSON_BINARY_SUBTYPE_MD5; } });
  7943. Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_USER_DEFINED", { enumerable: true, get: function () { return constants.BSON_BINARY_SUBTYPE_USER_DEFINED; } });
  7944. Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_UUID", { enumerable: true, get: function () { return constants.BSON_BINARY_SUBTYPE_UUID; } });
  7945. Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_UUID_NEW", { enumerable: true, get: function () { return constants.BSON_BINARY_SUBTYPE_UUID_NEW; } });
  7946. Object.defineProperty(exports, "BSON_DATA_ARRAY", { enumerable: true, get: function () { return constants.BSON_DATA_ARRAY; } });
  7947. Object.defineProperty(exports, "BSON_DATA_BINARY", { enumerable: true, get: function () { return constants.BSON_DATA_BINARY; } });
  7948. Object.defineProperty(exports, "BSON_DATA_BOOLEAN", { enumerable: true, get: function () { return constants.BSON_DATA_BOOLEAN; } });
  7949. Object.defineProperty(exports, "BSON_DATA_CODE", { enumerable: true, get: function () { return constants.BSON_DATA_CODE; } });
  7950. Object.defineProperty(exports, "BSON_DATA_CODE_W_SCOPE", { enumerable: true, get: function () { return constants.BSON_DATA_CODE_W_SCOPE; } });
  7951. Object.defineProperty(exports, "BSON_DATA_DATE", { enumerable: true, get: function () { return constants.BSON_DATA_DATE; } });
  7952. Object.defineProperty(exports, "BSON_DATA_DBPOINTER", { enumerable: true, get: function () { return constants.BSON_DATA_DBPOINTER; } });
  7953. Object.defineProperty(exports, "BSON_DATA_DECIMAL128", { enumerable: true, get: function () { return constants.BSON_DATA_DECIMAL128; } });
  7954. Object.defineProperty(exports, "BSON_DATA_INT", { enumerable: true, get: function () { return constants.BSON_DATA_INT; } });
  7955. Object.defineProperty(exports, "BSON_DATA_LONG", { enumerable: true, get: function () { return constants.BSON_DATA_LONG; } });
  7956. Object.defineProperty(exports, "BSON_DATA_MAX_KEY", { enumerable: true, get: function () { return constants.BSON_DATA_MAX_KEY; } });
  7957. Object.defineProperty(exports, "BSON_DATA_MIN_KEY", { enumerable: true, get: function () { return constants.BSON_DATA_MIN_KEY; } });
  7958. Object.defineProperty(exports, "BSON_DATA_NULL", { enumerable: true, get: function () { return constants.BSON_DATA_NULL; } });
  7959. Object.defineProperty(exports, "BSON_DATA_NUMBER", { enumerable: true, get: function () { return constants.BSON_DATA_NUMBER; } });
  7960. Object.defineProperty(exports, "BSON_DATA_OBJECT", { enumerable: true, get: function () { return constants.BSON_DATA_OBJECT; } });
  7961. Object.defineProperty(exports, "BSON_DATA_OID", { enumerable: true, get: function () { return constants.BSON_DATA_OID; } });
  7962. Object.defineProperty(exports, "BSON_DATA_REGEXP", { enumerable: true, get: function () { return constants.BSON_DATA_REGEXP; } });
  7963. Object.defineProperty(exports, "BSON_DATA_STRING", { enumerable: true, get: function () { return constants.BSON_DATA_STRING; } });
  7964. Object.defineProperty(exports, "BSON_DATA_SYMBOL", { enumerable: true, get: function () { return constants.BSON_DATA_SYMBOL; } });
  7965. Object.defineProperty(exports, "BSON_DATA_TIMESTAMP", { enumerable: true, get: function () { return constants.BSON_DATA_TIMESTAMP; } });
  7966. Object.defineProperty(exports, "BSON_DATA_UNDEFINED", { enumerable: true, get: function () { return constants.BSON_DATA_UNDEFINED; } });
  7967. Object.defineProperty(exports, "BSON_INT32_MAX", { enumerable: true, get: function () { return constants.BSON_INT32_MAX; } });
  7968. Object.defineProperty(exports, "BSON_INT32_MIN", { enumerable: true, get: function () { return constants.BSON_INT32_MIN; } });
  7969. Object.defineProperty(exports, "BSON_INT64_MAX", { enumerable: true, get: function () { return constants.BSON_INT64_MAX; } });
  7970. Object.defineProperty(exports, "BSON_INT64_MIN", { enumerable: true, get: function () { return constants.BSON_INT64_MIN; } });
  7971. var extended_json_2 = extended_json;
  7972. Object.defineProperty(exports, "EJSON", { enumerable: true, get: function () { return extended_json_2.EJSON; } });
  7973. var timestamp_2 = timestamp;
  7974. Object.defineProperty(exports, "LongWithoutOverridesClass", { enumerable: true, get: function () { return timestamp_2.LongWithoutOverridesClass; } });
  7975. /** @internal */
  7976. // Default Max Size
  7977. var MAXSIZE = 1024 * 1024 * 17;
  7978. // Current Internal Temporary Serialization Buffer
  7979. var buffer$1 = buffer.Buffer.alloc(MAXSIZE);
  7980. /**
  7981. * Sets the size of the internal serialization buffer.
  7982. *
  7983. * @param size - The desired size for the internal serialization buffer
  7984. * @public
  7985. */
  7986. function setInternalBufferSize(size) {
  7987. // Resize the internal serialization buffer if needed
  7988. if (buffer$1.length < size) {
  7989. buffer$1 = buffer.Buffer.alloc(size);
  7990. }
  7991. }
  7992. exports.setInternalBufferSize = setInternalBufferSize;
  7993. /**
  7994. * Serialize a Javascript object.
  7995. *
  7996. * @param object - the Javascript object to serialize.
  7997. * @returns Buffer object containing the serialized object.
  7998. * @public
  7999. */
  8000. function serialize(object, options) {
  8001. if (options === void 0) { options = {}; }
  8002. // Unpack the options
  8003. var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
  8004. var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  8005. var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  8006. var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE;
  8007. // Resize the internal serialization buffer if needed
  8008. if (buffer$1.length < minInternalBufferSize) {
  8009. buffer$1 = buffer.Buffer.alloc(minInternalBufferSize);
  8010. }
  8011. // Attempt to serialize
  8012. var serializationIndex = serializer.serializeInto(buffer$1, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []);
  8013. // Create the final buffer
  8014. var finishedBuffer = buffer.Buffer.alloc(serializationIndex);
  8015. // Copy into the finished buffer
  8016. buffer$1.copy(finishedBuffer, 0, 0, finishedBuffer.length);
  8017. // Return the buffer
  8018. return finishedBuffer;
  8019. }
  8020. exports.serialize = serialize;
  8021. /**
  8022. * Serialize a Javascript object using a predefined Buffer and index into the buffer,
  8023. * useful when pre-allocating the space for serialization.
  8024. *
  8025. * @param object - the Javascript object to serialize.
  8026. * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object.
  8027. * @returns the index pointing to the last written byte in the buffer.
  8028. * @public
  8029. */
  8030. function serializeWithBufferAndIndex(object, finalBuffer, options) {
  8031. if (options === void 0) { options = {}; }
  8032. // Unpack the options
  8033. var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
  8034. var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  8035. var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  8036. var startIndex = typeof options.index === 'number' ? options.index : 0;
  8037. // Attempt to serialize
  8038. var serializationIndex = serializer.serializeInto(buffer$1, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined);
  8039. buffer$1.copy(finalBuffer, startIndex, 0, serializationIndex);
  8040. // Return the index
  8041. return startIndex + serializationIndex - 1;
  8042. }
  8043. exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex;
  8044. /**
  8045. * Deserialize data as BSON.
  8046. *
  8047. * @param buffer - the buffer containing the serialized set of BSON documents.
  8048. * @returns returns the deserialized Javascript Object.
  8049. * @public
  8050. */
  8051. function deserialize(buffer, options) {
  8052. if (options === void 0) { options = {}; }
  8053. return deserializer.deserialize(ensure_buffer.ensureBuffer(buffer), options);
  8054. }
  8055. exports.deserialize = deserialize;
  8056. /**
  8057. * Calculate the bson size for a passed in Javascript object.
  8058. *
  8059. * @param object - the Javascript object to calculate the BSON byte size for
  8060. * @returns size of BSON object in bytes
  8061. * @public
  8062. */
  8063. function calculateObjectSize(object, options) {
  8064. if (options === void 0) { options = {}; }
  8065. options = options || {};
  8066. var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  8067. var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  8068. return calculate_size.calculateObjectSize(object, serializeFunctions, ignoreUndefined);
  8069. }
  8070. exports.calculateObjectSize = calculateObjectSize;
  8071. /**
  8072. * Deserialize stream data as BSON documents.
  8073. *
  8074. * @param data - the buffer containing the serialized set of BSON documents.
  8075. * @param startIndex - the start index in the data Buffer where the deserialization is to start.
  8076. * @param numberOfDocuments - number of documents to deserialize.
  8077. * @param documents - an array where to store the deserialized documents.
  8078. * @param docStartIndex - the index in the documents array from where to start inserting documents.
  8079. * @param options - additional options used for the deserialization.
  8080. * @returns next index in the buffer after deserialization **x** numbers of documents.
  8081. * @public
  8082. */
  8083. function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) {
  8084. var internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options);
  8085. var bufferData = ensure_buffer.ensureBuffer(data);
  8086. var index = startIndex;
  8087. // Loop over all documents
  8088. for (var i = 0; i < numberOfDocuments; i++) {
  8089. // Find size of the document
  8090. var size = bufferData[index] |
  8091. (bufferData[index + 1] << 8) |
  8092. (bufferData[index + 2] << 16) |
  8093. (bufferData[index + 3] << 24);
  8094. // Update options with index
  8095. internalOptions.index = index;
  8096. // Parse the document at this point
  8097. documents[docStartIndex + i] = deserializer.deserialize(bufferData, internalOptions);
  8098. // Adjust index by the document size
  8099. index = index + size;
  8100. }
  8101. // Return object containing end index of parsing and list of documents
  8102. return index;
  8103. }
  8104. exports.deserializeStream = deserializeStream;
  8105. /**
  8106. * BSON default export
  8107. * @deprecated Please use named exports
  8108. * @privateRemarks
  8109. * We want to someday deprecate the default export,
  8110. * so none of the new TS types are being exported on the default
  8111. * @public
  8112. */
  8113. var BSON = {
  8114. Binary: binary.Binary,
  8115. Code: code.Code,
  8116. DBRef: db_ref.DBRef,
  8117. Decimal128: decimal128.Decimal128,
  8118. Double: double_1.Double,
  8119. Int32: int_32.Int32,
  8120. Long: long_1.Long,
  8121. UUID: uuid.UUID,
  8122. Map: map.Map,
  8123. MaxKey: max_key.MaxKey,
  8124. MinKey: min_key.MinKey,
  8125. ObjectId: objectid.ObjectId,
  8126. ObjectID: objectid.ObjectId,
  8127. BSONRegExp: regexp.BSONRegExp,
  8128. BSONSymbol: symbol.BSONSymbol,
  8129. Timestamp: timestamp.Timestamp,
  8130. EJSON: extended_json.EJSON,
  8131. setInternalBufferSize: setInternalBufferSize,
  8132. serialize: serialize,
  8133. serializeWithBufferAndIndex: serializeWithBufferAndIndex,
  8134. deserialize: deserialize,
  8135. calculateObjectSize: calculateObjectSize,
  8136. deserializeStream: deserializeStream
  8137. };
  8138. exports.default = BSON;
  8139. });
  8140. var bson$1 = unwrapExports(bson);
  8141. var bson_1 = bson.ObjectID;
  8142. var bson_2 = bson.Decimal128;
  8143. var bson_3 = bson.BSONRegExp;
  8144. var bson_4 = bson.MaxKey;
  8145. var bson_5 = bson.MinKey;
  8146. var bson_6 = bson.Int32;
  8147. var bson_7 = bson.Double;
  8148. var bson_8 = bson.Timestamp;
  8149. var bson_9 = bson.Long;
  8150. var bson_10 = bson.UUID;
  8151. var bson_11 = bson.ObjectId;
  8152. var bson_12 = bson.Binary;
  8153. var bson_13 = bson.DBRef;
  8154. var bson_14 = bson.BSONSymbol;
  8155. var bson_15 = bson.Map;
  8156. var bson_16 = bson.Code;
  8157. var bson_17 = bson.LongWithoutOverridesClass;
  8158. var bson_18 = bson.EJSON;
  8159. var bson_19 = bson.BSON_INT64_MIN;
  8160. var bson_20 = bson.BSON_INT64_MAX;
  8161. var bson_21 = bson.BSON_INT32_MIN;
  8162. var bson_22 = bson.BSON_INT32_MAX;
  8163. var bson_23 = bson.BSON_DATA_UNDEFINED;
  8164. var bson_24 = bson.BSON_DATA_TIMESTAMP;
  8165. var bson_25 = bson.BSON_DATA_SYMBOL;
  8166. var bson_26 = bson.BSON_DATA_STRING;
  8167. var bson_27 = bson.BSON_DATA_REGEXP;
  8168. var bson_28 = bson.BSON_DATA_OID;
  8169. var bson_29 = bson.BSON_DATA_OBJECT;
  8170. var bson_30 = bson.BSON_DATA_NUMBER;
  8171. var bson_31 = bson.BSON_DATA_NULL;
  8172. var bson_32 = bson.BSON_DATA_MIN_KEY;
  8173. var bson_33 = bson.BSON_DATA_MAX_KEY;
  8174. var bson_34 = bson.BSON_DATA_LONG;
  8175. var bson_35 = bson.BSON_DATA_INT;
  8176. var bson_36 = bson.BSON_DATA_DECIMAL128;
  8177. var bson_37 = bson.BSON_DATA_DBPOINTER;
  8178. var bson_38 = bson.BSON_DATA_DATE;
  8179. var bson_39 = bson.BSON_DATA_CODE_W_SCOPE;
  8180. var bson_40 = bson.BSON_DATA_CODE;
  8181. var bson_41 = bson.BSON_DATA_BOOLEAN;
  8182. var bson_42 = bson.BSON_DATA_BINARY;
  8183. var bson_43 = bson.BSON_DATA_ARRAY;
  8184. var bson_44 = bson.BSON_BINARY_SUBTYPE_UUID_NEW;
  8185. var bson_45 = bson.BSON_BINARY_SUBTYPE_UUID;
  8186. var bson_46 = bson.BSON_BINARY_SUBTYPE_USER_DEFINED;
  8187. var bson_47 = bson.BSON_BINARY_SUBTYPE_MD5;
  8188. var bson_48 = bson.BSON_BINARY_SUBTYPE_FUNCTION;
  8189. var bson_49 = bson.BSON_BINARY_SUBTYPE_DEFAULT;
  8190. var bson_50 = bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY;
  8191. var bson_51 = bson.deserializeStream;
  8192. var bson_52 = bson.calculateObjectSize;
  8193. var bson_53 = bson.deserialize;
  8194. var bson_54 = bson.serializeWithBufferAndIndex;
  8195. var bson_55 = bson.serialize;
  8196. var bson_56 = bson.setInternalBufferSize;
  8197. export default bson$1;
  8198. export { bson_3 as BSONRegExp, bson_14 as BSONSymbol, bson_50 as BSON_BINARY_SUBTYPE_BYTE_ARRAY, bson_49 as BSON_BINARY_SUBTYPE_DEFAULT, bson_48 as BSON_BINARY_SUBTYPE_FUNCTION, bson_47 as BSON_BINARY_SUBTYPE_MD5, bson_46 as BSON_BINARY_SUBTYPE_USER_DEFINED, bson_45 as BSON_BINARY_SUBTYPE_UUID, bson_44 as BSON_BINARY_SUBTYPE_UUID_NEW, bson_43 as BSON_DATA_ARRAY, bson_42 as BSON_DATA_BINARY, bson_41 as BSON_DATA_BOOLEAN, bson_40 as BSON_DATA_CODE, bson_39 as BSON_DATA_CODE_W_SCOPE, bson_38 as BSON_DATA_DATE, bson_37 as BSON_DATA_DBPOINTER, bson_36 as BSON_DATA_DECIMAL128, bson_35 as BSON_DATA_INT, bson_34 as BSON_DATA_LONG, bson_33 as BSON_DATA_MAX_KEY, bson_32 as BSON_DATA_MIN_KEY, bson_31 as BSON_DATA_NULL, bson_30 as BSON_DATA_NUMBER, bson_29 as BSON_DATA_OBJECT, bson_28 as BSON_DATA_OID, bson_27 as BSON_DATA_REGEXP, bson_26 as BSON_DATA_STRING, bson_25 as BSON_DATA_SYMBOL, bson_24 as BSON_DATA_TIMESTAMP, bson_23 as BSON_DATA_UNDEFINED, bson_22 as BSON_INT32_MAX, bson_21 as BSON_INT32_MIN, bson_20 as BSON_INT64_MAX, bson_19 as BSON_INT64_MIN, bson_12 as Binary, bson_16 as Code, bson_13 as DBRef, bson_2 as Decimal128, bson_7 as Double, bson_18 as EJSON, bson_6 as Int32, bson_9 as Long, bson_17 as LongWithoutOverridesClass, bson_15 as Map, bson_4 as MaxKey, bson_5 as MinKey, bson_1 as ObjectID, bson_11 as ObjectId, bson_8 as Timestamp, bson_10 as UUID, bson_52 as calculateObjectSize, bson_53 as deserialize, bson_51 as deserializeStream, bson_55 as serialize, bson_54 as serializeWithBufferAndIndex, bson_56 as setInternalBufferSize };
  8199. //# sourceMappingURL=bson.browser.esm.js.map