bson.bundle.js 281 KB

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