bson.esm.js 214 KB

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