bson.bundle.js 324 KB

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