bson.browser.umd.js 324 KB

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