bson.esm.js 258 KB

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