bson.cjs 155 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144
  1. 'use strict';
  2. function isAnyArrayBuffer(value) {
  3. return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value));
  4. }
  5. function isUint8Array(value) {
  6. return Object.prototype.toString.call(value) === '[object Uint8Array]';
  7. }
  8. function isRegExp(d) {
  9. return Object.prototype.toString.call(d) === '[object RegExp]';
  10. }
  11. function isMap(d) {
  12. return Object.prototype.toString.call(d) === '[object Map]';
  13. }
  14. function isDate(d) {
  15. return Object.prototype.toString.call(d) === '[object Date]';
  16. }
  17. const BSON_MAJOR_VERSION = 5;
  18. const BSON_INT32_MAX = 0x7fffffff;
  19. const BSON_INT32_MIN = -0x80000000;
  20. const BSON_INT64_MAX = Math.pow(2, 63) - 1;
  21. const BSON_INT64_MIN = -Math.pow(2, 63);
  22. const JS_INT_MAX = Math.pow(2, 53);
  23. const JS_INT_MIN = -Math.pow(2, 53);
  24. const BSON_DATA_NUMBER = 1;
  25. const BSON_DATA_STRING = 2;
  26. const BSON_DATA_OBJECT = 3;
  27. const BSON_DATA_ARRAY = 4;
  28. const BSON_DATA_BINARY = 5;
  29. const BSON_DATA_UNDEFINED = 6;
  30. const BSON_DATA_OID = 7;
  31. const BSON_DATA_BOOLEAN = 8;
  32. const BSON_DATA_DATE = 9;
  33. const BSON_DATA_NULL = 10;
  34. const BSON_DATA_REGEXP = 11;
  35. const BSON_DATA_DBPOINTER = 12;
  36. const BSON_DATA_CODE = 13;
  37. const BSON_DATA_SYMBOL = 14;
  38. const BSON_DATA_CODE_W_SCOPE = 15;
  39. const BSON_DATA_INT = 16;
  40. const BSON_DATA_TIMESTAMP = 17;
  41. const BSON_DATA_LONG = 18;
  42. const BSON_DATA_DECIMAL128 = 19;
  43. const BSON_DATA_MIN_KEY = 0xff;
  44. const BSON_DATA_MAX_KEY = 0x7f;
  45. const BSON_BINARY_SUBTYPE_DEFAULT = 0;
  46. const BSON_BINARY_SUBTYPE_UUID_NEW = 4;
  47. const BSONType = Object.freeze({
  48. double: 1,
  49. string: 2,
  50. object: 3,
  51. array: 4,
  52. binData: 5,
  53. undefined: 6,
  54. objectId: 7,
  55. bool: 8,
  56. date: 9,
  57. null: 10,
  58. regex: 11,
  59. dbPointer: 12,
  60. javascript: 13,
  61. symbol: 14,
  62. javascriptWithScope: 15,
  63. int: 16,
  64. timestamp: 17,
  65. long: 18,
  66. decimal: 19,
  67. minKey: -1,
  68. maxKey: 127
  69. });
  70. class BSONError extends Error {
  71. get bsonError() {
  72. return true;
  73. }
  74. get name() {
  75. return 'BSONError';
  76. }
  77. constructor(message) {
  78. super(message);
  79. }
  80. static isBSONError(value) {
  81. return (value != null &&
  82. typeof value === 'object' &&
  83. 'bsonError' in value &&
  84. value.bsonError === true &&
  85. 'name' in value &&
  86. 'message' in value &&
  87. 'stack' in value);
  88. }
  89. }
  90. class BSONVersionError extends BSONError {
  91. get name() {
  92. return 'BSONVersionError';
  93. }
  94. constructor() {
  95. super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`);
  96. }
  97. }
  98. class BSONRuntimeError extends BSONError {
  99. get name() {
  100. return 'BSONRuntimeError';
  101. }
  102. constructor(message) {
  103. super(message);
  104. }
  105. }
  106. function nodejsMathRandomBytes(byteLength) {
  107. return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
  108. }
  109. const nodejsRandomBytes = (() => {
  110. try {
  111. return require('crypto').randomBytes;
  112. }
  113. catch {
  114. return nodejsMathRandomBytes;
  115. }
  116. })();
  117. const nodeJsByteUtils = {
  118. toLocalBufferType(potentialBuffer) {
  119. if (Buffer.isBuffer(potentialBuffer)) {
  120. return potentialBuffer;
  121. }
  122. if (ArrayBuffer.isView(potentialBuffer)) {
  123. return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength);
  124. }
  125. const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer);
  126. if (stringTag === 'ArrayBuffer' ||
  127. stringTag === 'SharedArrayBuffer' ||
  128. stringTag === '[object ArrayBuffer]' ||
  129. stringTag === '[object SharedArrayBuffer]') {
  130. return Buffer.from(potentialBuffer);
  131. }
  132. throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`);
  133. },
  134. allocate(size) {
  135. return Buffer.alloc(size);
  136. },
  137. equals(a, b) {
  138. return nodeJsByteUtils.toLocalBufferType(a).equals(b);
  139. },
  140. fromNumberArray(array) {
  141. return Buffer.from(array);
  142. },
  143. fromBase64(base64) {
  144. return Buffer.from(base64, 'base64');
  145. },
  146. toBase64(buffer) {
  147. return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64');
  148. },
  149. fromISO88591(codePoints) {
  150. return Buffer.from(codePoints, 'binary');
  151. },
  152. toISO88591(buffer) {
  153. return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary');
  154. },
  155. fromHex(hex) {
  156. return Buffer.from(hex, 'hex');
  157. },
  158. toHex(buffer) {
  159. return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex');
  160. },
  161. fromUTF8(text) {
  162. return Buffer.from(text, 'utf8');
  163. },
  164. toUTF8(buffer, start, end) {
  165. return nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8', start, end);
  166. },
  167. utf8ByteLength(input) {
  168. return Buffer.byteLength(input, 'utf8');
  169. },
  170. encodeUTF8Into(buffer, source, byteOffset) {
  171. return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8');
  172. },
  173. randomBytes: nodejsRandomBytes
  174. };
  175. function isReactNative() {
  176. const { navigator } = globalThis;
  177. return typeof navigator === 'object' && navigator.product === 'ReactNative';
  178. }
  179. function webMathRandomBytes(byteLength) {
  180. if (byteLength < 0) {
  181. throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`);
  182. }
  183. return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
  184. }
  185. const webRandomBytes = (() => {
  186. const { crypto } = globalThis;
  187. if (crypto != null && typeof crypto.getRandomValues === 'function') {
  188. return (byteLength) => {
  189. return crypto.getRandomValues(webByteUtils.allocate(byteLength));
  190. };
  191. }
  192. else {
  193. if (isReactNative()) {
  194. const { console } = globalThis;
  195. console?.warn?.('BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.');
  196. }
  197. return webMathRandomBytes;
  198. }
  199. })();
  200. const HEX_DIGIT = /(\d|[a-f])/i;
  201. const webByteUtils = {
  202. toLocalBufferType(potentialUint8array) {
  203. const stringTag = potentialUint8array?.[Symbol.toStringTag] ??
  204. Object.prototype.toString.call(potentialUint8array);
  205. if (stringTag === 'Uint8Array') {
  206. return potentialUint8array;
  207. }
  208. if (ArrayBuffer.isView(potentialUint8array)) {
  209. return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength));
  210. }
  211. if (stringTag === 'ArrayBuffer' ||
  212. stringTag === 'SharedArrayBuffer' ||
  213. stringTag === '[object ArrayBuffer]' ||
  214. stringTag === '[object SharedArrayBuffer]') {
  215. return new Uint8Array(potentialUint8array);
  216. }
  217. throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`);
  218. },
  219. allocate(size) {
  220. if (typeof size !== 'number') {
  221. throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`);
  222. }
  223. return new Uint8Array(size);
  224. },
  225. equals(a, b) {
  226. if (a.byteLength !== b.byteLength) {
  227. return false;
  228. }
  229. for (let i = 0; i < a.byteLength; i++) {
  230. if (a[i] !== b[i]) {
  231. return false;
  232. }
  233. }
  234. return true;
  235. },
  236. fromNumberArray(array) {
  237. return Uint8Array.from(array);
  238. },
  239. fromBase64(base64) {
  240. return Uint8Array.from(atob(base64), c => c.charCodeAt(0));
  241. },
  242. toBase64(uint8array) {
  243. return btoa(webByteUtils.toISO88591(uint8array));
  244. },
  245. fromISO88591(codePoints) {
  246. return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff);
  247. },
  248. toISO88591(uint8array) {
  249. return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join('');
  250. },
  251. fromHex(hex) {
  252. const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1);
  253. const buffer = [];
  254. for (let i = 0; i < evenLengthHex.length; i += 2) {
  255. const firstDigit = evenLengthHex[i];
  256. const secondDigit = evenLengthHex[i + 1];
  257. if (!HEX_DIGIT.test(firstDigit)) {
  258. break;
  259. }
  260. if (!HEX_DIGIT.test(secondDigit)) {
  261. break;
  262. }
  263. const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16);
  264. buffer.push(hexDigit);
  265. }
  266. return Uint8Array.from(buffer);
  267. },
  268. toHex(uint8array) {
  269. return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join('');
  270. },
  271. fromUTF8(text) {
  272. return new TextEncoder().encode(text);
  273. },
  274. toUTF8(uint8array, start, end) {
  275. return new TextDecoder('utf8', { fatal: false }).decode(uint8array.slice(start, end));
  276. },
  277. utf8ByteLength(input) {
  278. return webByteUtils.fromUTF8(input).byteLength;
  279. },
  280. encodeUTF8Into(buffer, source, byteOffset) {
  281. const bytes = webByteUtils.fromUTF8(source);
  282. buffer.set(bytes, byteOffset);
  283. return bytes.byteLength;
  284. },
  285. randomBytes: webRandomBytes
  286. };
  287. const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true;
  288. const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils;
  289. class BSONDataView extends DataView {
  290. static fromUint8Array(input) {
  291. return new DataView(input.buffer, input.byteOffset, input.byteLength);
  292. }
  293. }
  294. class BSONValue {
  295. get [Symbol.for('@@mdb.bson.version')]() {
  296. return BSON_MAJOR_VERSION;
  297. }
  298. }
  299. class Binary extends BSONValue {
  300. get _bsontype() {
  301. return 'Binary';
  302. }
  303. constructor(buffer, subType) {
  304. super();
  305. if (!(buffer == null) &&
  306. !(typeof buffer === 'string') &&
  307. !ArrayBuffer.isView(buffer) &&
  308. !(buffer instanceof ArrayBuffer) &&
  309. !Array.isArray(buffer)) {
  310. throw new BSONError('Binary can only be constructed from string, Buffer, TypedArray, or Array<number>');
  311. }
  312. this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT;
  313. if (buffer == null) {
  314. this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE);
  315. this.position = 0;
  316. }
  317. else {
  318. if (typeof buffer === 'string') {
  319. this.buffer = ByteUtils.fromISO88591(buffer);
  320. }
  321. else if (Array.isArray(buffer)) {
  322. this.buffer = ByteUtils.fromNumberArray(buffer);
  323. }
  324. else {
  325. this.buffer = ByteUtils.toLocalBufferType(buffer);
  326. }
  327. this.position = this.buffer.byteLength;
  328. }
  329. }
  330. put(byteValue) {
  331. if (typeof byteValue === 'string' && byteValue.length !== 1) {
  332. throw new BSONError('only accepts single character String');
  333. }
  334. else if (typeof byteValue !== 'number' && byteValue.length !== 1)
  335. throw new BSONError('only accepts single character Uint8Array or Array');
  336. let decodedByte;
  337. if (typeof byteValue === 'string') {
  338. decodedByte = byteValue.charCodeAt(0);
  339. }
  340. else if (typeof byteValue === 'number') {
  341. decodedByte = byteValue;
  342. }
  343. else {
  344. decodedByte = byteValue[0];
  345. }
  346. if (decodedByte < 0 || decodedByte > 255) {
  347. throw new BSONError('only accepts number in a valid unsigned byte range 0-255');
  348. }
  349. if (this.buffer.byteLength > this.position) {
  350. this.buffer[this.position++] = decodedByte;
  351. }
  352. else {
  353. const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length);
  354. newSpace.set(this.buffer, 0);
  355. this.buffer = newSpace;
  356. this.buffer[this.position++] = decodedByte;
  357. }
  358. }
  359. write(sequence, offset) {
  360. offset = typeof offset === 'number' ? offset : this.position;
  361. if (this.buffer.byteLength < offset + sequence.length) {
  362. const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length);
  363. newSpace.set(this.buffer, 0);
  364. this.buffer = newSpace;
  365. }
  366. if (ArrayBuffer.isView(sequence)) {
  367. this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset);
  368. this.position =
  369. offset + sequence.byteLength > this.position ? offset + sequence.length : this.position;
  370. }
  371. else if (typeof sequence === 'string') {
  372. const bytes = ByteUtils.fromISO88591(sequence);
  373. this.buffer.set(bytes, offset);
  374. this.position =
  375. offset + sequence.length > this.position ? offset + sequence.length : this.position;
  376. }
  377. }
  378. read(position, length) {
  379. length = length && length > 0 ? length : this.position;
  380. return this.buffer.slice(position, position + length);
  381. }
  382. value(asRaw) {
  383. asRaw = !!asRaw;
  384. if (asRaw && this.buffer.length === this.position) {
  385. return this.buffer;
  386. }
  387. if (asRaw) {
  388. return this.buffer.slice(0, this.position);
  389. }
  390. return ByteUtils.toISO88591(this.buffer.subarray(0, this.position));
  391. }
  392. length() {
  393. return this.position;
  394. }
  395. toJSON() {
  396. return ByteUtils.toBase64(this.buffer);
  397. }
  398. toString(encoding) {
  399. if (encoding === 'hex')
  400. return ByteUtils.toHex(this.buffer);
  401. if (encoding === 'base64')
  402. return ByteUtils.toBase64(this.buffer);
  403. if (encoding === 'utf8' || encoding === 'utf-8')
  404. return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength);
  405. return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength);
  406. }
  407. toExtendedJSON(options) {
  408. options = options || {};
  409. const base64String = ByteUtils.toBase64(this.buffer);
  410. const subType = Number(this.sub_type).toString(16);
  411. if (options.legacy) {
  412. return {
  413. $binary: base64String,
  414. $type: subType.length === 1 ? '0' + subType : subType
  415. };
  416. }
  417. return {
  418. $binary: {
  419. base64: base64String,
  420. subType: subType.length === 1 ? '0' + subType : subType
  421. }
  422. };
  423. }
  424. toUUID() {
  425. if (this.sub_type === Binary.SUBTYPE_UUID) {
  426. return new UUID(this.buffer.slice(0, this.position));
  427. }
  428. throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.`);
  429. }
  430. static createFromHexString(hex, subType) {
  431. return new Binary(ByteUtils.fromHex(hex), subType);
  432. }
  433. static createFromBase64(base64, subType) {
  434. return new Binary(ByteUtils.fromBase64(base64), subType);
  435. }
  436. static fromExtendedJSON(doc, options) {
  437. options = options || {};
  438. let data;
  439. let type;
  440. if ('$binary' in doc) {
  441. if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) {
  442. type = doc.$type ? parseInt(doc.$type, 16) : 0;
  443. data = ByteUtils.fromBase64(doc.$binary);
  444. }
  445. else {
  446. if (typeof doc.$binary !== 'string') {
  447. type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
  448. data = ByteUtils.fromBase64(doc.$binary.base64);
  449. }
  450. }
  451. }
  452. else if ('$uuid' in doc) {
  453. type = 4;
  454. data = UUID.bytesFromString(doc.$uuid);
  455. }
  456. if (!data) {
  457. throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`);
  458. }
  459. return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type);
  460. }
  461. [Symbol.for('nodejs.util.inspect.custom')]() {
  462. return this.inspect();
  463. }
  464. inspect() {
  465. const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position));
  466. return `Binary.createFromBase64("${base64}", ${this.sub_type})`;
  467. }
  468. }
  469. Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0;
  470. Binary.BUFFER_SIZE = 256;
  471. Binary.SUBTYPE_DEFAULT = 0;
  472. Binary.SUBTYPE_FUNCTION = 1;
  473. Binary.SUBTYPE_BYTE_ARRAY = 2;
  474. Binary.SUBTYPE_UUID_OLD = 3;
  475. Binary.SUBTYPE_UUID = 4;
  476. Binary.SUBTYPE_MD5 = 5;
  477. Binary.SUBTYPE_ENCRYPTED = 6;
  478. Binary.SUBTYPE_COLUMN = 7;
  479. Binary.SUBTYPE_USER_DEFINED = 128;
  480. const UUID_BYTE_LENGTH = 16;
  481. const UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i;
  482. const UUID_WITH_DASHES = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;
  483. class UUID extends Binary {
  484. constructor(input) {
  485. let bytes;
  486. if (input == null) {
  487. bytes = UUID.generate();
  488. }
  489. else if (input instanceof UUID) {
  490. bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));
  491. }
  492. else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) {
  493. bytes = ByteUtils.toLocalBufferType(input);
  494. }
  495. else if (typeof input === 'string') {
  496. bytes = UUID.bytesFromString(input);
  497. }
  498. else {
  499. throw new BSONError('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).');
  500. }
  501. super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW);
  502. }
  503. get id() {
  504. return this.buffer;
  505. }
  506. set id(value) {
  507. this.buffer = value;
  508. }
  509. toHexString(includeDashes = true) {
  510. if (includeDashes) {
  511. return [
  512. ByteUtils.toHex(this.buffer.subarray(0, 4)),
  513. ByteUtils.toHex(this.buffer.subarray(4, 6)),
  514. ByteUtils.toHex(this.buffer.subarray(6, 8)),
  515. ByteUtils.toHex(this.buffer.subarray(8, 10)),
  516. ByteUtils.toHex(this.buffer.subarray(10, 16))
  517. ].join('-');
  518. }
  519. return ByteUtils.toHex(this.buffer);
  520. }
  521. toString(encoding) {
  522. if (encoding === 'hex')
  523. return ByteUtils.toHex(this.id);
  524. if (encoding === 'base64')
  525. return ByteUtils.toBase64(this.id);
  526. return this.toHexString();
  527. }
  528. toJSON() {
  529. return this.toHexString();
  530. }
  531. equals(otherId) {
  532. if (!otherId) {
  533. return false;
  534. }
  535. if (otherId instanceof UUID) {
  536. return ByteUtils.equals(otherId.id, this.id);
  537. }
  538. try {
  539. return ByteUtils.equals(new UUID(otherId).id, this.id);
  540. }
  541. catch {
  542. return false;
  543. }
  544. }
  545. toBinary() {
  546. return new Binary(this.id, Binary.SUBTYPE_UUID);
  547. }
  548. static generate() {
  549. const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH);
  550. bytes[6] = (bytes[6] & 0x0f) | 0x40;
  551. bytes[8] = (bytes[8] & 0x3f) | 0x80;
  552. return bytes;
  553. }
  554. static isValid(input) {
  555. if (!input) {
  556. return false;
  557. }
  558. if (typeof input === 'string') {
  559. return UUID.isValidUUIDString(input);
  560. }
  561. if (isUint8Array(input)) {
  562. return input.byteLength === UUID_BYTE_LENGTH;
  563. }
  564. return (input._bsontype === 'Binary' &&
  565. input.sub_type === this.SUBTYPE_UUID &&
  566. input.buffer.byteLength === 16);
  567. }
  568. static createFromHexString(hexString) {
  569. const buffer = UUID.bytesFromString(hexString);
  570. return new UUID(buffer);
  571. }
  572. static createFromBase64(base64) {
  573. return new UUID(ByteUtils.fromBase64(base64));
  574. }
  575. static bytesFromString(representation) {
  576. if (!UUID.isValidUUIDString(representation)) {
  577. throw new BSONError('UUID string representation must be 32 hex digits or canonical hyphenated representation');
  578. }
  579. return ByteUtils.fromHex(representation.replace(/-/g, ''));
  580. }
  581. static isValidUUIDString(representation) {
  582. return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation);
  583. }
  584. [Symbol.for('nodejs.util.inspect.custom')]() {
  585. return this.inspect();
  586. }
  587. inspect() {
  588. return `new UUID("${this.toHexString()}")`;
  589. }
  590. }
  591. UUID.cacheHexString = false;
  592. class Code extends BSONValue {
  593. get _bsontype() {
  594. return 'Code';
  595. }
  596. constructor(code, scope) {
  597. super();
  598. this.code = code.toString();
  599. this.scope = scope ?? null;
  600. }
  601. toJSON() {
  602. if (this.scope != null) {
  603. return { code: this.code, scope: this.scope };
  604. }
  605. return { code: this.code };
  606. }
  607. toExtendedJSON() {
  608. if (this.scope) {
  609. return { $code: this.code, $scope: this.scope };
  610. }
  611. return { $code: this.code };
  612. }
  613. static fromExtendedJSON(doc) {
  614. return new Code(doc.$code, doc.$scope);
  615. }
  616. [Symbol.for('nodejs.util.inspect.custom')]() {
  617. return this.inspect();
  618. }
  619. inspect() {
  620. const codeJson = this.toJSON();
  621. return `new Code("${String(codeJson.code)}"${codeJson.scope != null ? `, ${JSON.stringify(codeJson.scope)}` : ''})`;
  622. }
  623. }
  624. function isDBRefLike(value) {
  625. return (value != null &&
  626. typeof value === 'object' &&
  627. '$id' in value &&
  628. value.$id != null &&
  629. '$ref' in value &&
  630. typeof value.$ref === 'string' &&
  631. (!('$db' in value) || ('$db' in value && typeof value.$db === 'string')));
  632. }
  633. class DBRef extends BSONValue {
  634. get _bsontype() {
  635. return 'DBRef';
  636. }
  637. constructor(collection, oid, db, fields) {
  638. super();
  639. const parts = collection.split('.');
  640. if (parts.length === 2) {
  641. db = parts.shift();
  642. collection = parts.shift();
  643. }
  644. this.collection = collection;
  645. this.oid = oid;
  646. this.db = db;
  647. this.fields = fields || {};
  648. }
  649. get namespace() {
  650. return this.collection;
  651. }
  652. set namespace(value) {
  653. this.collection = value;
  654. }
  655. toJSON() {
  656. const o = Object.assign({
  657. $ref: this.collection,
  658. $id: this.oid
  659. }, this.fields);
  660. if (this.db != null)
  661. o.$db = this.db;
  662. return o;
  663. }
  664. toExtendedJSON(options) {
  665. options = options || {};
  666. let o = {
  667. $ref: this.collection,
  668. $id: this.oid
  669. };
  670. if (options.legacy) {
  671. return o;
  672. }
  673. if (this.db)
  674. o.$db = this.db;
  675. o = Object.assign(o, this.fields);
  676. return o;
  677. }
  678. static fromExtendedJSON(doc) {
  679. const copy = Object.assign({}, doc);
  680. delete copy.$ref;
  681. delete copy.$id;
  682. delete copy.$db;
  683. return new DBRef(doc.$ref, doc.$id, doc.$db, copy);
  684. }
  685. [Symbol.for('nodejs.util.inspect.custom')]() {
  686. return this.inspect();
  687. }
  688. inspect() {
  689. const oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString();
  690. return `new DBRef("${this.namespace}", new ObjectId("${String(oid)}")${this.db ? `, "${this.db}"` : ''})`;
  691. }
  692. }
  693. let wasm = undefined;
  694. try {
  695. wasm = new WebAssembly.Instance(new WebAssembly.Module(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;
  696. }
  697. catch {
  698. }
  699. const TWO_PWR_16_DBL = 1 << 16;
  700. const TWO_PWR_24_DBL = 1 << 24;
  701. const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
  702. const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
  703. const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
  704. const INT_CACHE = {};
  705. const UINT_CACHE = {};
  706. const MAX_INT64_STRING_LENGTH = 20;
  707. const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/;
  708. class Long extends BSONValue {
  709. get _bsontype() {
  710. return 'Long';
  711. }
  712. get __isLong__() {
  713. return true;
  714. }
  715. constructor(low = 0, high, unsigned) {
  716. super();
  717. if (typeof low === 'bigint') {
  718. Object.assign(this, Long.fromBigInt(low, !!high));
  719. }
  720. else if (typeof low === 'string') {
  721. Object.assign(this, Long.fromString(low, !!high));
  722. }
  723. else {
  724. this.low = low | 0;
  725. this.high = high | 0;
  726. this.unsigned = !!unsigned;
  727. }
  728. }
  729. static fromBits(lowBits, highBits, unsigned) {
  730. return new Long(lowBits, highBits, unsigned);
  731. }
  732. static fromInt(value, unsigned) {
  733. let obj, cachedObj, cache;
  734. if (unsigned) {
  735. value >>>= 0;
  736. if ((cache = 0 <= value && value < 256)) {
  737. cachedObj = UINT_CACHE[value];
  738. if (cachedObj)
  739. return cachedObj;
  740. }
  741. obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true);
  742. if (cache)
  743. UINT_CACHE[value] = obj;
  744. return obj;
  745. }
  746. else {
  747. value |= 0;
  748. if ((cache = -128 <= value && value < 128)) {
  749. cachedObj = INT_CACHE[value];
  750. if (cachedObj)
  751. return cachedObj;
  752. }
  753. obj = Long.fromBits(value, value < 0 ? -1 : 0, false);
  754. if (cache)
  755. INT_CACHE[value] = obj;
  756. return obj;
  757. }
  758. }
  759. static fromNumber(value, unsigned) {
  760. if (isNaN(value))
  761. return unsigned ? Long.UZERO : Long.ZERO;
  762. if (unsigned) {
  763. if (value < 0)
  764. return Long.UZERO;
  765. if (value >= TWO_PWR_64_DBL)
  766. return Long.MAX_UNSIGNED_VALUE;
  767. }
  768. else {
  769. if (value <= -TWO_PWR_63_DBL)
  770. return Long.MIN_VALUE;
  771. if (value + 1 >= TWO_PWR_63_DBL)
  772. return Long.MAX_VALUE;
  773. }
  774. if (value < 0)
  775. return Long.fromNumber(-value, unsigned).neg();
  776. return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
  777. }
  778. static fromBigInt(value, unsigned) {
  779. return Long.fromString(value.toString(), unsigned);
  780. }
  781. static fromString(str, unsigned, radix) {
  782. if (str.length === 0)
  783. throw new BSONError('empty string');
  784. if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity')
  785. return Long.ZERO;
  786. if (typeof unsigned === 'number') {
  787. (radix = unsigned), (unsigned = false);
  788. }
  789. else {
  790. unsigned = !!unsigned;
  791. }
  792. radix = radix || 10;
  793. if (radix < 2 || 36 < radix)
  794. throw new BSONError('radix');
  795. let p;
  796. if ((p = str.indexOf('-')) > 0)
  797. throw new BSONError('interior hyphen');
  798. else if (p === 0) {
  799. return Long.fromString(str.substring(1), unsigned, radix).neg();
  800. }
  801. const radixToPower = Long.fromNumber(Math.pow(radix, 8));
  802. let result = Long.ZERO;
  803. for (let i = 0; i < str.length; i += 8) {
  804. const size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix);
  805. if (size < 8) {
  806. const power = Long.fromNumber(Math.pow(radix, size));
  807. result = result.mul(power).add(Long.fromNumber(value));
  808. }
  809. else {
  810. result = result.mul(radixToPower);
  811. result = result.add(Long.fromNumber(value));
  812. }
  813. }
  814. result.unsigned = unsigned;
  815. return result;
  816. }
  817. static fromBytes(bytes, unsigned, le) {
  818. return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
  819. }
  820. static fromBytesLE(bytes, unsigned) {
  821. 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);
  822. }
  823. static fromBytesBE(bytes, unsigned) {
  824. 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);
  825. }
  826. static isLong(value) {
  827. return (value != null &&
  828. typeof value === 'object' &&
  829. '__isLong__' in value &&
  830. value.__isLong__ === true);
  831. }
  832. static fromValue(val, unsigned) {
  833. if (typeof val === 'number')
  834. return Long.fromNumber(val, unsigned);
  835. if (typeof val === 'string')
  836. return Long.fromString(val, unsigned);
  837. return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);
  838. }
  839. add(addend) {
  840. if (!Long.isLong(addend))
  841. addend = Long.fromValue(addend);
  842. const a48 = this.high >>> 16;
  843. const a32 = this.high & 0xffff;
  844. const a16 = this.low >>> 16;
  845. const a00 = this.low & 0xffff;
  846. const b48 = addend.high >>> 16;
  847. const b32 = addend.high & 0xffff;
  848. const b16 = addend.low >>> 16;
  849. const b00 = addend.low & 0xffff;
  850. let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  851. c00 += a00 + b00;
  852. c16 += c00 >>> 16;
  853. c00 &= 0xffff;
  854. c16 += a16 + b16;
  855. c32 += c16 >>> 16;
  856. c16 &= 0xffff;
  857. c32 += a32 + b32;
  858. c48 += c32 >>> 16;
  859. c32 &= 0xffff;
  860. c48 += a48 + b48;
  861. c48 &= 0xffff;
  862. return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
  863. }
  864. and(other) {
  865. if (!Long.isLong(other))
  866. other = Long.fromValue(other);
  867. return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned);
  868. }
  869. compare(other) {
  870. if (!Long.isLong(other))
  871. other = Long.fromValue(other);
  872. if (this.eq(other))
  873. return 0;
  874. const thisNeg = this.isNegative(), otherNeg = other.isNegative();
  875. if (thisNeg && !otherNeg)
  876. return -1;
  877. if (!thisNeg && otherNeg)
  878. return 1;
  879. if (!this.unsigned)
  880. return this.sub(other).isNegative() ? -1 : 1;
  881. return other.high >>> 0 > this.high >>> 0 ||
  882. (other.high === this.high && other.low >>> 0 > this.low >>> 0)
  883. ? -1
  884. : 1;
  885. }
  886. comp(other) {
  887. return this.compare(other);
  888. }
  889. divide(divisor) {
  890. if (!Long.isLong(divisor))
  891. divisor = Long.fromValue(divisor);
  892. if (divisor.isZero())
  893. throw new BSONError('division by zero');
  894. if (wasm) {
  895. if (!this.unsigned &&
  896. this.high === -0x80000000 &&
  897. divisor.low === -1 &&
  898. divisor.high === -1) {
  899. return this;
  900. }
  901. const low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high);
  902. return Long.fromBits(low, wasm.get_high(), this.unsigned);
  903. }
  904. if (this.isZero())
  905. return this.unsigned ? Long.UZERO : Long.ZERO;
  906. let approx, rem, res;
  907. if (!this.unsigned) {
  908. if (this.eq(Long.MIN_VALUE)) {
  909. if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE))
  910. return Long.MIN_VALUE;
  911. else if (divisor.eq(Long.MIN_VALUE))
  912. return Long.ONE;
  913. else {
  914. const halfThis = this.shr(1);
  915. approx = halfThis.div(divisor).shl(1);
  916. if (approx.eq(Long.ZERO)) {
  917. return divisor.isNegative() ? Long.ONE : Long.NEG_ONE;
  918. }
  919. else {
  920. rem = this.sub(divisor.mul(approx));
  921. res = approx.add(rem.div(divisor));
  922. return res;
  923. }
  924. }
  925. }
  926. else if (divisor.eq(Long.MIN_VALUE))
  927. return this.unsigned ? Long.UZERO : Long.ZERO;
  928. if (this.isNegative()) {
  929. if (divisor.isNegative())
  930. return this.neg().div(divisor.neg());
  931. return this.neg().div(divisor).neg();
  932. }
  933. else if (divisor.isNegative())
  934. return this.div(divisor.neg()).neg();
  935. res = Long.ZERO;
  936. }
  937. else {
  938. if (!divisor.unsigned)
  939. divisor = divisor.toUnsigned();
  940. if (divisor.gt(this))
  941. return Long.UZERO;
  942. if (divisor.gt(this.shru(1)))
  943. return Long.UONE;
  944. res = Long.UZERO;
  945. }
  946. rem = this;
  947. while (rem.gte(divisor)) {
  948. approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
  949. const log2 = Math.ceil(Math.log(approx) / Math.LN2);
  950. const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);
  951. let approxRes = Long.fromNumber(approx);
  952. let approxRem = approxRes.mul(divisor);
  953. while (approxRem.isNegative() || approxRem.gt(rem)) {
  954. approx -= delta;
  955. approxRes = Long.fromNumber(approx, this.unsigned);
  956. approxRem = approxRes.mul(divisor);
  957. }
  958. if (approxRes.isZero())
  959. approxRes = Long.ONE;
  960. res = res.add(approxRes);
  961. rem = rem.sub(approxRem);
  962. }
  963. return res;
  964. }
  965. div(divisor) {
  966. return this.divide(divisor);
  967. }
  968. equals(other) {
  969. if (!Long.isLong(other))
  970. other = Long.fromValue(other);
  971. if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
  972. return false;
  973. return this.high === other.high && this.low === other.low;
  974. }
  975. eq(other) {
  976. return this.equals(other);
  977. }
  978. getHighBits() {
  979. return this.high;
  980. }
  981. getHighBitsUnsigned() {
  982. return this.high >>> 0;
  983. }
  984. getLowBits() {
  985. return this.low;
  986. }
  987. getLowBitsUnsigned() {
  988. return this.low >>> 0;
  989. }
  990. getNumBitsAbs() {
  991. if (this.isNegative()) {
  992. return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
  993. }
  994. const val = this.high !== 0 ? this.high : this.low;
  995. let bit;
  996. for (bit = 31; bit > 0; bit--)
  997. if ((val & (1 << bit)) !== 0)
  998. break;
  999. return this.high !== 0 ? bit + 33 : bit + 1;
  1000. }
  1001. greaterThan(other) {
  1002. return this.comp(other) > 0;
  1003. }
  1004. gt(other) {
  1005. return this.greaterThan(other);
  1006. }
  1007. greaterThanOrEqual(other) {
  1008. return this.comp(other) >= 0;
  1009. }
  1010. gte(other) {
  1011. return this.greaterThanOrEqual(other);
  1012. }
  1013. ge(other) {
  1014. return this.greaterThanOrEqual(other);
  1015. }
  1016. isEven() {
  1017. return (this.low & 1) === 0;
  1018. }
  1019. isNegative() {
  1020. return !this.unsigned && this.high < 0;
  1021. }
  1022. isOdd() {
  1023. return (this.low & 1) === 1;
  1024. }
  1025. isPositive() {
  1026. return this.unsigned || this.high >= 0;
  1027. }
  1028. isZero() {
  1029. return this.high === 0 && this.low === 0;
  1030. }
  1031. lessThan(other) {
  1032. return this.comp(other) < 0;
  1033. }
  1034. lt(other) {
  1035. return this.lessThan(other);
  1036. }
  1037. lessThanOrEqual(other) {
  1038. return this.comp(other) <= 0;
  1039. }
  1040. lte(other) {
  1041. return this.lessThanOrEqual(other);
  1042. }
  1043. modulo(divisor) {
  1044. if (!Long.isLong(divisor))
  1045. divisor = Long.fromValue(divisor);
  1046. if (wasm) {
  1047. const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high);
  1048. return Long.fromBits(low, wasm.get_high(), this.unsigned);
  1049. }
  1050. return this.sub(this.div(divisor).mul(divisor));
  1051. }
  1052. mod(divisor) {
  1053. return this.modulo(divisor);
  1054. }
  1055. rem(divisor) {
  1056. return this.modulo(divisor);
  1057. }
  1058. multiply(multiplier) {
  1059. if (this.isZero())
  1060. return Long.ZERO;
  1061. if (!Long.isLong(multiplier))
  1062. multiplier = Long.fromValue(multiplier);
  1063. if (wasm) {
  1064. const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
  1065. return Long.fromBits(low, wasm.get_high(), this.unsigned);
  1066. }
  1067. if (multiplier.isZero())
  1068. return Long.ZERO;
  1069. if (this.eq(Long.MIN_VALUE))
  1070. return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO;
  1071. if (multiplier.eq(Long.MIN_VALUE))
  1072. return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;
  1073. if (this.isNegative()) {
  1074. if (multiplier.isNegative())
  1075. return this.neg().mul(multiplier.neg());
  1076. else
  1077. return this.neg().mul(multiplier).neg();
  1078. }
  1079. else if (multiplier.isNegative())
  1080. return this.mul(multiplier.neg()).neg();
  1081. if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24))
  1082. return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
  1083. const a48 = this.high >>> 16;
  1084. const a32 = this.high & 0xffff;
  1085. const a16 = this.low >>> 16;
  1086. const a00 = this.low & 0xffff;
  1087. const b48 = multiplier.high >>> 16;
  1088. const b32 = multiplier.high & 0xffff;
  1089. const b16 = multiplier.low >>> 16;
  1090. const b00 = multiplier.low & 0xffff;
  1091. let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  1092. c00 += a00 * b00;
  1093. c16 += c00 >>> 16;
  1094. c00 &= 0xffff;
  1095. c16 += a16 * b00;
  1096. c32 += c16 >>> 16;
  1097. c16 &= 0xffff;
  1098. c16 += a00 * b16;
  1099. c32 += c16 >>> 16;
  1100. c16 &= 0xffff;
  1101. c32 += a32 * b00;
  1102. c48 += c32 >>> 16;
  1103. c32 &= 0xffff;
  1104. c32 += a16 * b16;
  1105. c48 += c32 >>> 16;
  1106. c32 &= 0xffff;
  1107. c32 += a00 * b32;
  1108. c48 += c32 >>> 16;
  1109. c32 &= 0xffff;
  1110. c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
  1111. c48 &= 0xffff;
  1112. return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
  1113. }
  1114. mul(multiplier) {
  1115. return this.multiply(multiplier);
  1116. }
  1117. negate() {
  1118. if (!this.unsigned && this.eq(Long.MIN_VALUE))
  1119. return Long.MIN_VALUE;
  1120. return this.not().add(Long.ONE);
  1121. }
  1122. neg() {
  1123. return this.negate();
  1124. }
  1125. not() {
  1126. return Long.fromBits(~this.low, ~this.high, this.unsigned);
  1127. }
  1128. notEquals(other) {
  1129. return !this.equals(other);
  1130. }
  1131. neq(other) {
  1132. return this.notEquals(other);
  1133. }
  1134. ne(other) {
  1135. return this.notEquals(other);
  1136. }
  1137. or(other) {
  1138. if (!Long.isLong(other))
  1139. other = Long.fromValue(other);
  1140. return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned);
  1141. }
  1142. shiftLeft(numBits) {
  1143. if (Long.isLong(numBits))
  1144. numBits = numBits.toInt();
  1145. if ((numBits &= 63) === 0)
  1146. return this;
  1147. else if (numBits < 32)
  1148. return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
  1149. else
  1150. return Long.fromBits(0, this.low << (numBits - 32), this.unsigned);
  1151. }
  1152. shl(numBits) {
  1153. return this.shiftLeft(numBits);
  1154. }
  1155. shiftRight(numBits) {
  1156. if (Long.isLong(numBits))
  1157. numBits = numBits.toInt();
  1158. if ((numBits &= 63) === 0)
  1159. return this;
  1160. else if (numBits < 32)
  1161. return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
  1162. else
  1163. return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
  1164. }
  1165. shr(numBits) {
  1166. return this.shiftRight(numBits);
  1167. }
  1168. shiftRightUnsigned(numBits) {
  1169. if (Long.isLong(numBits))
  1170. numBits = numBits.toInt();
  1171. numBits &= 63;
  1172. if (numBits === 0)
  1173. return this;
  1174. else {
  1175. const high = this.high;
  1176. if (numBits < 32) {
  1177. const low = this.low;
  1178. return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
  1179. }
  1180. else if (numBits === 32)
  1181. return Long.fromBits(high, 0, this.unsigned);
  1182. else
  1183. return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned);
  1184. }
  1185. }
  1186. shr_u(numBits) {
  1187. return this.shiftRightUnsigned(numBits);
  1188. }
  1189. shru(numBits) {
  1190. return this.shiftRightUnsigned(numBits);
  1191. }
  1192. subtract(subtrahend) {
  1193. if (!Long.isLong(subtrahend))
  1194. subtrahend = Long.fromValue(subtrahend);
  1195. return this.add(subtrahend.neg());
  1196. }
  1197. sub(subtrahend) {
  1198. return this.subtract(subtrahend);
  1199. }
  1200. toInt() {
  1201. return this.unsigned ? this.low >>> 0 : this.low;
  1202. }
  1203. toNumber() {
  1204. if (this.unsigned)
  1205. return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
  1206. return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
  1207. }
  1208. toBigInt() {
  1209. return BigInt(this.toString());
  1210. }
  1211. toBytes(le) {
  1212. return le ? this.toBytesLE() : this.toBytesBE();
  1213. }
  1214. toBytesLE() {
  1215. const hi = this.high, lo = this.low;
  1216. return [
  1217. lo & 0xff,
  1218. (lo >>> 8) & 0xff,
  1219. (lo >>> 16) & 0xff,
  1220. lo >>> 24,
  1221. hi & 0xff,
  1222. (hi >>> 8) & 0xff,
  1223. (hi >>> 16) & 0xff,
  1224. hi >>> 24
  1225. ];
  1226. }
  1227. toBytesBE() {
  1228. const hi = this.high, lo = this.low;
  1229. return [
  1230. hi >>> 24,
  1231. (hi >>> 16) & 0xff,
  1232. (hi >>> 8) & 0xff,
  1233. hi & 0xff,
  1234. lo >>> 24,
  1235. (lo >>> 16) & 0xff,
  1236. (lo >>> 8) & 0xff,
  1237. lo & 0xff
  1238. ];
  1239. }
  1240. toSigned() {
  1241. if (!this.unsigned)
  1242. return this;
  1243. return Long.fromBits(this.low, this.high, false);
  1244. }
  1245. toString(radix) {
  1246. radix = radix || 10;
  1247. if (radix < 2 || 36 < radix)
  1248. throw new BSONError('radix');
  1249. if (this.isZero())
  1250. return '0';
  1251. if (this.isNegative()) {
  1252. if (this.eq(Long.MIN_VALUE)) {
  1253. const radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this);
  1254. return div.toString(radix) + rem1.toInt().toString(radix);
  1255. }
  1256. else
  1257. return '-' + this.neg().toString(radix);
  1258. }
  1259. const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned);
  1260. let rem = this;
  1261. let result = '';
  1262. while (true) {
  1263. const remDiv = rem.div(radixToPower);
  1264. const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0;
  1265. let digits = intval.toString(radix);
  1266. rem = remDiv;
  1267. if (rem.isZero()) {
  1268. return digits + result;
  1269. }
  1270. else {
  1271. while (digits.length < 6)
  1272. digits = '0' + digits;
  1273. result = '' + digits + result;
  1274. }
  1275. }
  1276. }
  1277. toUnsigned() {
  1278. if (this.unsigned)
  1279. return this;
  1280. return Long.fromBits(this.low, this.high, true);
  1281. }
  1282. xor(other) {
  1283. if (!Long.isLong(other))
  1284. other = Long.fromValue(other);
  1285. return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
  1286. }
  1287. eqz() {
  1288. return this.isZero();
  1289. }
  1290. le(other) {
  1291. return this.lessThanOrEqual(other);
  1292. }
  1293. toExtendedJSON(options) {
  1294. if (options && options.relaxed)
  1295. return this.toNumber();
  1296. return { $numberLong: this.toString() };
  1297. }
  1298. static fromExtendedJSON(doc, options) {
  1299. const { useBigInt64 = false, relaxed = true } = { ...options };
  1300. if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) {
  1301. throw new BSONError('$numberLong string is too long');
  1302. }
  1303. if (!DECIMAL_REG_EX.test(doc.$numberLong)) {
  1304. throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`);
  1305. }
  1306. if (useBigInt64) {
  1307. const bigIntResult = BigInt(doc.$numberLong);
  1308. return BigInt.asIntN(64, bigIntResult);
  1309. }
  1310. const longResult = Long.fromString(doc.$numberLong);
  1311. if (relaxed) {
  1312. return longResult.toNumber();
  1313. }
  1314. return longResult;
  1315. }
  1316. [Symbol.for('nodejs.util.inspect.custom')]() {
  1317. return this.inspect();
  1318. }
  1319. inspect() {
  1320. return `new Long("${this.toString()}"${this.unsigned ? ', true' : ''})`;
  1321. }
  1322. }
  1323. Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL);
  1324. Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true);
  1325. Long.ZERO = Long.fromInt(0);
  1326. Long.UZERO = Long.fromInt(0, true);
  1327. Long.ONE = Long.fromInt(1);
  1328. Long.UONE = Long.fromInt(1, true);
  1329. Long.NEG_ONE = Long.fromInt(-1);
  1330. Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false);
  1331. Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false);
  1332. const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
  1333. const PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
  1334. const PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
  1335. const EXPONENT_MAX = 6111;
  1336. const EXPONENT_MIN = -6176;
  1337. const EXPONENT_BIAS = 6176;
  1338. const MAX_DIGITS = 34;
  1339. const NAN_BUFFER = ByteUtils.fromNumberArray([
  1340. 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  1341. ].reverse());
  1342. const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([
  1343. 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  1344. ].reverse());
  1345. const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([
  1346. 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  1347. ].reverse());
  1348. const EXPONENT_REGEX = /^([-+])?(\d+)?$/;
  1349. const COMBINATION_MASK = 0x1f;
  1350. const EXPONENT_MASK = 0x3fff;
  1351. const COMBINATION_INFINITY = 30;
  1352. const COMBINATION_NAN = 31;
  1353. function isDigit(value) {
  1354. return !isNaN(parseInt(value, 10));
  1355. }
  1356. function divideu128(value) {
  1357. const DIVISOR = Long.fromNumber(1000 * 1000 * 1000);
  1358. let _rem = Long.fromNumber(0);
  1359. if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
  1360. return { quotient: value, rem: _rem };
  1361. }
  1362. for (let i = 0; i <= 3; i++) {
  1363. _rem = _rem.shiftLeft(32);
  1364. _rem = _rem.add(new Long(value.parts[i], 0));
  1365. value.parts[i] = _rem.div(DIVISOR).low;
  1366. _rem = _rem.modulo(DIVISOR);
  1367. }
  1368. return { quotient: value, rem: _rem };
  1369. }
  1370. function multiply64x2(left, right) {
  1371. if (!left && !right) {
  1372. return { high: Long.fromNumber(0), low: Long.fromNumber(0) };
  1373. }
  1374. const leftHigh = left.shiftRightUnsigned(32);
  1375. const leftLow = new Long(left.getLowBits(), 0);
  1376. const rightHigh = right.shiftRightUnsigned(32);
  1377. const rightLow = new Long(right.getLowBits(), 0);
  1378. let productHigh = leftHigh.multiply(rightHigh);
  1379. let productMid = leftHigh.multiply(rightLow);
  1380. const productMid2 = leftLow.multiply(rightHigh);
  1381. let productLow = leftLow.multiply(rightLow);
  1382. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  1383. productMid = new Long(productMid.getLowBits(), 0)
  1384. .add(productMid2)
  1385. .add(productLow.shiftRightUnsigned(32));
  1386. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  1387. productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0));
  1388. return { high: productHigh, low: productLow };
  1389. }
  1390. function lessThan(left, right) {
  1391. const uhleft = left.high >>> 0;
  1392. const uhright = right.high >>> 0;
  1393. if (uhleft < uhright) {
  1394. return true;
  1395. }
  1396. else if (uhleft === uhright) {
  1397. const ulleft = left.low >>> 0;
  1398. const ulright = right.low >>> 0;
  1399. if (ulleft < ulright)
  1400. return true;
  1401. }
  1402. return false;
  1403. }
  1404. function invalidErr(string, message) {
  1405. throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`);
  1406. }
  1407. class Decimal128 extends BSONValue {
  1408. get _bsontype() {
  1409. return 'Decimal128';
  1410. }
  1411. constructor(bytes) {
  1412. super();
  1413. if (typeof bytes === 'string') {
  1414. this.bytes = Decimal128.fromString(bytes).bytes;
  1415. }
  1416. else if (isUint8Array(bytes)) {
  1417. if (bytes.byteLength !== 16) {
  1418. throw new BSONError('Decimal128 must take a Buffer of 16 bytes');
  1419. }
  1420. this.bytes = bytes;
  1421. }
  1422. else {
  1423. throw new BSONError('Decimal128 must take a Buffer or string');
  1424. }
  1425. }
  1426. static fromString(representation) {
  1427. return Decimal128._fromString(representation, { allowRounding: false });
  1428. }
  1429. static fromStringWithRounding(representation) {
  1430. return Decimal128._fromString(representation, { allowRounding: true });
  1431. }
  1432. static _fromString(representation, options) {
  1433. let isNegative = false;
  1434. let sawSign = false;
  1435. let sawRadix = false;
  1436. let foundNonZero = false;
  1437. let significantDigits = 0;
  1438. let nDigitsRead = 0;
  1439. let nDigits = 0;
  1440. let radixPosition = 0;
  1441. let firstNonZero = 0;
  1442. const digits = [0];
  1443. let nDigitsStored = 0;
  1444. let digitsInsert = 0;
  1445. let lastDigit = 0;
  1446. let exponent = 0;
  1447. let significandHigh = new Long(0, 0);
  1448. let significandLow = new Long(0, 0);
  1449. let biasedExponent = 0;
  1450. let index = 0;
  1451. if (representation.length >= 7000) {
  1452. throw new BSONError('' + representation + ' not a valid Decimal128 string');
  1453. }
  1454. const stringMatch = representation.match(PARSE_STRING_REGEXP);
  1455. const infMatch = representation.match(PARSE_INF_REGEXP);
  1456. const nanMatch = representation.match(PARSE_NAN_REGEXP);
  1457. if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) {
  1458. throw new BSONError('' + representation + ' not a valid Decimal128 string');
  1459. }
  1460. if (stringMatch) {
  1461. const unsignedNumber = stringMatch[2];
  1462. const e = stringMatch[4];
  1463. const expSign = stringMatch[5];
  1464. const expNumber = stringMatch[6];
  1465. if (e && expNumber === undefined)
  1466. invalidErr(representation, 'missing exponent power');
  1467. if (e && unsignedNumber === undefined)
  1468. invalidErr(representation, 'missing exponent base');
  1469. if (e === undefined && (expSign || expNumber)) {
  1470. invalidErr(representation, 'missing e before exponent');
  1471. }
  1472. }
  1473. if (representation[index] === '+' || representation[index] === '-') {
  1474. sawSign = true;
  1475. isNegative = representation[index++] === '-';
  1476. }
  1477. if (!isDigit(representation[index]) && representation[index] !== '.') {
  1478. if (representation[index] === 'i' || representation[index] === 'I') {
  1479. return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
  1480. }
  1481. else if (representation[index] === 'N') {
  1482. return new Decimal128(NAN_BUFFER);
  1483. }
  1484. }
  1485. while (isDigit(representation[index]) || representation[index] === '.') {
  1486. if (representation[index] === '.') {
  1487. if (sawRadix)
  1488. invalidErr(representation, 'contains multiple periods');
  1489. sawRadix = true;
  1490. index = index + 1;
  1491. continue;
  1492. }
  1493. if (nDigitsStored < MAX_DIGITS) {
  1494. if (representation[index] !== '0' || foundNonZero) {
  1495. if (!foundNonZero) {
  1496. firstNonZero = nDigitsRead;
  1497. }
  1498. foundNonZero = true;
  1499. digits[digitsInsert++] = parseInt(representation[index], 10);
  1500. nDigitsStored = nDigitsStored + 1;
  1501. }
  1502. }
  1503. if (foundNonZero)
  1504. nDigits = nDigits + 1;
  1505. if (sawRadix)
  1506. radixPosition = radixPosition + 1;
  1507. nDigitsRead = nDigitsRead + 1;
  1508. index = index + 1;
  1509. }
  1510. if (sawRadix && !nDigitsRead)
  1511. throw new BSONError('' + representation + ' not a valid Decimal128 string');
  1512. if (representation[index] === 'e' || representation[index] === 'E') {
  1513. const match = representation.substr(++index).match(EXPONENT_REGEX);
  1514. if (!match || !match[2])
  1515. return new Decimal128(NAN_BUFFER);
  1516. exponent = parseInt(match[0], 10);
  1517. index = index + match[0].length;
  1518. }
  1519. if (representation[index])
  1520. return new Decimal128(NAN_BUFFER);
  1521. if (!nDigitsStored) {
  1522. digits[0] = 0;
  1523. nDigits = 1;
  1524. nDigitsStored = 1;
  1525. significantDigits = 0;
  1526. }
  1527. else {
  1528. lastDigit = nDigitsStored - 1;
  1529. significantDigits = nDigits;
  1530. if (significantDigits !== 1) {
  1531. while (representation[firstNonZero + significantDigits - 1 + Number(sawSign) + Number(sawRadix)] === '0') {
  1532. significantDigits = significantDigits - 1;
  1533. }
  1534. }
  1535. }
  1536. if (exponent <= radixPosition && radixPosition > exponent + (1 << 14)) {
  1537. exponent = EXPONENT_MIN;
  1538. }
  1539. else {
  1540. exponent = exponent - radixPosition;
  1541. }
  1542. while (exponent > EXPONENT_MAX) {
  1543. lastDigit = lastDigit + 1;
  1544. if (lastDigit >= MAX_DIGITS) {
  1545. if (significantDigits === 0) {
  1546. exponent = EXPONENT_MAX;
  1547. break;
  1548. }
  1549. invalidErr(representation, 'overflow');
  1550. }
  1551. exponent = exponent - 1;
  1552. }
  1553. if (options.allowRounding) {
  1554. while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
  1555. if (lastDigit === 0 && significantDigits < nDigitsStored) {
  1556. exponent = EXPONENT_MIN;
  1557. significantDigits = 0;
  1558. break;
  1559. }
  1560. if (nDigitsStored < nDigits) {
  1561. nDigits = nDigits - 1;
  1562. }
  1563. else {
  1564. lastDigit = lastDigit - 1;
  1565. }
  1566. if (exponent < EXPONENT_MAX) {
  1567. exponent = exponent + 1;
  1568. }
  1569. else {
  1570. const digitsString = digits.join('');
  1571. if (digitsString.match(/^0+$/)) {
  1572. exponent = EXPONENT_MAX;
  1573. break;
  1574. }
  1575. invalidErr(representation, 'overflow');
  1576. }
  1577. }
  1578. if (lastDigit + 1 < significantDigits) {
  1579. let endOfString = nDigitsRead;
  1580. if (sawRadix) {
  1581. firstNonZero = firstNonZero + 1;
  1582. endOfString = endOfString + 1;
  1583. }
  1584. if (sawSign) {
  1585. firstNonZero = firstNonZero + 1;
  1586. endOfString = endOfString + 1;
  1587. }
  1588. const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
  1589. let roundBit = 0;
  1590. if (roundDigit >= 5) {
  1591. roundBit = 1;
  1592. if (roundDigit === 5) {
  1593. roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0;
  1594. for (let i = firstNonZero + lastDigit + 2; i < endOfString; i++) {
  1595. if (parseInt(representation[i], 10)) {
  1596. roundBit = 1;
  1597. break;
  1598. }
  1599. }
  1600. }
  1601. }
  1602. if (roundBit) {
  1603. let dIdx = lastDigit;
  1604. for (; dIdx >= 0; dIdx--) {
  1605. if (++digits[dIdx] > 9) {
  1606. digits[dIdx] = 0;
  1607. if (dIdx === 0) {
  1608. if (exponent < EXPONENT_MAX) {
  1609. exponent = exponent + 1;
  1610. digits[dIdx] = 1;
  1611. }
  1612. else {
  1613. return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
  1614. }
  1615. }
  1616. }
  1617. else {
  1618. break;
  1619. }
  1620. }
  1621. }
  1622. }
  1623. }
  1624. else {
  1625. while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
  1626. if (lastDigit === 0) {
  1627. if (significantDigits === 0) {
  1628. exponent = EXPONENT_MIN;
  1629. break;
  1630. }
  1631. invalidErr(representation, 'exponent underflow');
  1632. }
  1633. if (nDigitsStored < nDigits) {
  1634. if (representation[nDigits - 1 + Number(sawSign) + Number(sawRadix)] !== '0' &&
  1635. significantDigits !== 0) {
  1636. invalidErr(representation, 'inexact rounding');
  1637. }
  1638. nDigits = nDigits - 1;
  1639. }
  1640. else {
  1641. if (digits[lastDigit] !== 0) {
  1642. invalidErr(representation, 'inexact rounding');
  1643. }
  1644. lastDigit = lastDigit - 1;
  1645. }
  1646. if (exponent < EXPONENT_MAX) {
  1647. exponent = exponent + 1;
  1648. }
  1649. else {
  1650. invalidErr(representation, 'overflow');
  1651. }
  1652. }
  1653. if (lastDigit + 1 < significantDigits) {
  1654. if (sawRadix) {
  1655. firstNonZero = firstNonZero + 1;
  1656. }
  1657. if (sawSign) {
  1658. firstNonZero = firstNonZero + 1;
  1659. }
  1660. const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
  1661. if (roundDigit !== 0) {
  1662. invalidErr(representation, 'inexact rounding');
  1663. }
  1664. }
  1665. }
  1666. significandHigh = Long.fromNumber(0);
  1667. significandLow = Long.fromNumber(0);
  1668. if (significantDigits === 0) {
  1669. significandHigh = Long.fromNumber(0);
  1670. significandLow = Long.fromNumber(0);
  1671. }
  1672. else if (lastDigit < 17) {
  1673. let dIdx = 0;
  1674. significandLow = Long.fromNumber(digits[dIdx++]);
  1675. significandHigh = new Long(0, 0);
  1676. for (; dIdx <= lastDigit; dIdx++) {
  1677. significandLow = significandLow.multiply(Long.fromNumber(10));
  1678. significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
  1679. }
  1680. }
  1681. else {
  1682. let dIdx = 0;
  1683. significandHigh = Long.fromNumber(digits[dIdx++]);
  1684. for (; dIdx <= lastDigit - 17; dIdx++) {
  1685. significandHigh = significandHigh.multiply(Long.fromNumber(10));
  1686. significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx]));
  1687. }
  1688. significandLow = Long.fromNumber(digits[dIdx++]);
  1689. for (; dIdx <= lastDigit; dIdx++) {
  1690. significandLow = significandLow.multiply(Long.fromNumber(10));
  1691. significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
  1692. }
  1693. }
  1694. const significand = multiply64x2(significandHigh, Long.fromString('100000000000000000'));
  1695. significand.low = significand.low.add(significandLow);
  1696. if (lessThan(significand.low, significandLow)) {
  1697. significand.high = significand.high.add(Long.fromNumber(1));
  1698. }
  1699. biasedExponent = exponent + EXPONENT_BIAS;
  1700. const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) };
  1701. if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) {
  1702. dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61));
  1703. dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)));
  1704. dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff)));
  1705. }
  1706. else {
  1707. dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49));
  1708. dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff)));
  1709. }
  1710. dec.low = significand.low;
  1711. if (isNegative) {
  1712. dec.high = dec.high.or(Long.fromString('9223372036854775808'));
  1713. }
  1714. const buffer = ByteUtils.allocate(16);
  1715. index = 0;
  1716. buffer[index++] = dec.low.low & 0xff;
  1717. buffer[index++] = (dec.low.low >> 8) & 0xff;
  1718. buffer[index++] = (dec.low.low >> 16) & 0xff;
  1719. buffer[index++] = (dec.low.low >> 24) & 0xff;
  1720. buffer[index++] = dec.low.high & 0xff;
  1721. buffer[index++] = (dec.low.high >> 8) & 0xff;
  1722. buffer[index++] = (dec.low.high >> 16) & 0xff;
  1723. buffer[index++] = (dec.low.high >> 24) & 0xff;
  1724. buffer[index++] = dec.high.low & 0xff;
  1725. buffer[index++] = (dec.high.low >> 8) & 0xff;
  1726. buffer[index++] = (dec.high.low >> 16) & 0xff;
  1727. buffer[index++] = (dec.high.low >> 24) & 0xff;
  1728. buffer[index++] = dec.high.high & 0xff;
  1729. buffer[index++] = (dec.high.high >> 8) & 0xff;
  1730. buffer[index++] = (dec.high.high >> 16) & 0xff;
  1731. buffer[index++] = (dec.high.high >> 24) & 0xff;
  1732. return new Decimal128(buffer);
  1733. }
  1734. toString() {
  1735. let biased_exponent;
  1736. let significand_digits = 0;
  1737. const significand = new Array(36);
  1738. for (let i = 0; i < significand.length; i++)
  1739. significand[i] = 0;
  1740. let index = 0;
  1741. let is_zero = false;
  1742. let significand_msb;
  1743. let significand128 = { parts: [0, 0, 0, 0] };
  1744. let j, k;
  1745. const string = [];
  1746. index = 0;
  1747. const buffer = this.bytes;
  1748. const low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  1749. const midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  1750. const midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  1751. const high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  1752. index = 0;
  1753. const dec = {
  1754. low: new Long(low, midl),
  1755. high: new Long(midh, high)
  1756. };
  1757. if (dec.high.lessThan(Long.ZERO)) {
  1758. string.push('-');
  1759. }
  1760. const combination = (high >> 26) & COMBINATION_MASK;
  1761. if (combination >> 3 === 3) {
  1762. if (combination === COMBINATION_INFINITY) {
  1763. return string.join('') + 'Infinity';
  1764. }
  1765. else if (combination === COMBINATION_NAN) {
  1766. return 'NaN';
  1767. }
  1768. else {
  1769. biased_exponent = (high >> 15) & EXPONENT_MASK;
  1770. significand_msb = 0x08 + ((high >> 14) & 0x01);
  1771. }
  1772. }
  1773. else {
  1774. significand_msb = (high >> 14) & 0x07;
  1775. biased_exponent = (high >> 17) & EXPONENT_MASK;
  1776. }
  1777. const exponent = biased_exponent - EXPONENT_BIAS;
  1778. significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14);
  1779. significand128.parts[1] = midh;
  1780. significand128.parts[2] = midl;
  1781. significand128.parts[3] = low;
  1782. if (significand128.parts[0] === 0 &&
  1783. significand128.parts[1] === 0 &&
  1784. significand128.parts[2] === 0 &&
  1785. significand128.parts[3] === 0) {
  1786. is_zero = true;
  1787. }
  1788. else {
  1789. for (k = 3; k >= 0; k--) {
  1790. let least_digits = 0;
  1791. const result = divideu128(significand128);
  1792. significand128 = result.quotient;
  1793. least_digits = result.rem.low;
  1794. if (!least_digits)
  1795. continue;
  1796. for (j = 8; j >= 0; j--) {
  1797. significand[k * 9 + j] = least_digits % 10;
  1798. least_digits = Math.floor(least_digits / 10);
  1799. }
  1800. }
  1801. }
  1802. if (is_zero) {
  1803. significand_digits = 1;
  1804. significand[index] = 0;
  1805. }
  1806. else {
  1807. significand_digits = 36;
  1808. while (!significand[index]) {
  1809. significand_digits = significand_digits - 1;
  1810. index = index + 1;
  1811. }
  1812. }
  1813. const scientific_exponent = significand_digits - 1 + exponent;
  1814. if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
  1815. if (significand_digits > 34) {
  1816. string.push(`${0}`);
  1817. if (exponent > 0)
  1818. string.push(`E+${exponent}`);
  1819. else if (exponent < 0)
  1820. string.push(`E${exponent}`);
  1821. return string.join('');
  1822. }
  1823. string.push(`${significand[index++]}`);
  1824. significand_digits = significand_digits - 1;
  1825. if (significand_digits) {
  1826. string.push('.');
  1827. }
  1828. for (let i = 0; i < significand_digits; i++) {
  1829. string.push(`${significand[index++]}`);
  1830. }
  1831. string.push('E');
  1832. if (scientific_exponent > 0) {
  1833. string.push(`+${scientific_exponent}`);
  1834. }
  1835. else {
  1836. string.push(`${scientific_exponent}`);
  1837. }
  1838. }
  1839. else {
  1840. if (exponent >= 0) {
  1841. for (let i = 0; i < significand_digits; i++) {
  1842. string.push(`${significand[index++]}`);
  1843. }
  1844. }
  1845. else {
  1846. let radix_position = significand_digits + exponent;
  1847. if (radix_position > 0) {
  1848. for (let i = 0; i < radix_position; i++) {
  1849. string.push(`${significand[index++]}`);
  1850. }
  1851. }
  1852. else {
  1853. string.push('0');
  1854. }
  1855. string.push('.');
  1856. while (radix_position++ < 0) {
  1857. string.push('0');
  1858. }
  1859. for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) {
  1860. string.push(`${significand[index++]}`);
  1861. }
  1862. }
  1863. }
  1864. return string.join('');
  1865. }
  1866. toJSON() {
  1867. return { $numberDecimal: this.toString() };
  1868. }
  1869. toExtendedJSON() {
  1870. return { $numberDecimal: this.toString() };
  1871. }
  1872. static fromExtendedJSON(doc) {
  1873. return Decimal128.fromString(doc.$numberDecimal);
  1874. }
  1875. [Symbol.for('nodejs.util.inspect.custom')]() {
  1876. return this.inspect();
  1877. }
  1878. inspect() {
  1879. return `new Decimal128("${this.toString()}")`;
  1880. }
  1881. }
  1882. class Double extends BSONValue {
  1883. get _bsontype() {
  1884. return 'Double';
  1885. }
  1886. constructor(value) {
  1887. super();
  1888. if (value instanceof Number) {
  1889. value = value.valueOf();
  1890. }
  1891. this.value = +value;
  1892. }
  1893. valueOf() {
  1894. return this.value;
  1895. }
  1896. toJSON() {
  1897. return this.value;
  1898. }
  1899. toString(radix) {
  1900. return this.value.toString(radix);
  1901. }
  1902. toExtendedJSON(options) {
  1903. if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) {
  1904. return this.value;
  1905. }
  1906. if (Object.is(Math.sign(this.value), -0)) {
  1907. return { $numberDouble: '-0.0' };
  1908. }
  1909. return {
  1910. $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString()
  1911. };
  1912. }
  1913. static fromExtendedJSON(doc, options) {
  1914. const doubleValue = parseFloat(doc.$numberDouble);
  1915. return options && options.relaxed ? doubleValue : new Double(doubleValue);
  1916. }
  1917. [Symbol.for('nodejs.util.inspect.custom')]() {
  1918. return this.inspect();
  1919. }
  1920. inspect() {
  1921. const eJSON = this.toExtendedJSON();
  1922. return `new Double(${eJSON.$numberDouble})`;
  1923. }
  1924. }
  1925. class Int32 extends BSONValue {
  1926. get _bsontype() {
  1927. return 'Int32';
  1928. }
  1929. constructor(value) {
  1930. super();
  1931. if (value instanceof Number) {
  1932. value = value.valueOf();
  1933. }
  1934. this.value = +value | 0;
  1935. }
  1936. valueOf() {
  1937. return this.value;
  1938. }
  1939. toString(radix) {
  1940. return this.value.toString(radix);
  1941. }
  1942. toJSON() {
  1943. return this.value;
  1944. }
  1945. toExtendedJSON(options) {
  1946. if (options && (options.relaxed || options.legacy))
  1947. return this.value;
  1948. return { $numberInt: this.value.toString() };
  1949. }
  1950. static fromExtendedJSON(doc, options) {
  1951. return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt);
  1952. }
  1953. [Symbol.for('nodejs.util.inspect.custom')]() {
  1954. return this.inspect();
  1955. }
  1956. inspect() {
  1957. return `new Int32(${this.valueOf()})`;
  1958. }
  1959. }
  1960. class MaxKey extends BSONValue {
  1961. get _bsontype() {
  1962. return 'MaxKey';
  1963. }
  1964. toExtendedJSON() {
  1965. return { $maxKey: 1 };
  1966. }
  1967. static fromExtendedJSON() {
  1968. return new MaxKey();
  1969. }
  1970. [Symbol.for('nodejs.util.inspect.custom')]() {
  1971. return this.inspect();
  1972. }
  1973. inspect() {
  1974. return 'new MaxKey()';
  1975. }
  1976. }
  1977. class MinKey extends BSONValue {
  1978. get _bsontype() {
  1979. return 'MinKey';
  1980. }
  1981. toExtendedJSON() {
  1982. return { $minKey: 1 };
  1983. }
  1984. static fromExtendedJSON() {
  1985. return new MinKey();
  1986. }
  1987. [Symbol.for('nodejs.util.inspect.custom')]() {
  1988. return this.inspect();
  1989. }
  1990. inspect() {
  1991. return 'new MinKey()';
  1992. }
  1993. }
  1994. const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$');
  1995. let PROCESS_UNIQUE = null;
  1996. const kId = Symbol('id');
  1997. class ObjectId extends BSONValue {
  1998. get _bsontype() {
  1999. return 'ObjectId';
  2000. }
  2001. constructor(inputId) {
  2002. super();
  2003. let workingId;
  2004. if (typeof inputId === 'object' && inputId && 'id' in inputId) {
  2005. if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) {
  2006. throw new BSONError('Argument passed in must have an id that is of type string or Buffer');
  2007. }
  2008. if ('toHexString' in inputId && typeof inputId.toHexString === 'function') {
  2009. workingId = ByteUtils.fromHex(inputId.toHexString());
  2010. }
  2011. else {
  2012. workingId = inputId.id;
  2013. }
  2014. }
  2015. else {
  2016. workingId = inputId;
  2017. }
  2018. if (workingId == null || typeof workingId === 'number') {
  2019. this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined);
  2020. }
  2021. else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) {
  2022. this[kId] = ByteUtils.toLocalBufferType(workingId);
  2023. }
  2024. else if (typeof workingId === 'string') {
  2025. if (workingId.length === 12) {
  2026. const bytes = ByteUtils.fromUTF8(workingId);
  2027. if (bytes.byteLength === 12) {
  2028. this[kId] = bytes;
  2029. }
  2030. else {
  2031. throw new BSONError('Argument passed in must be a string of 12 bytes');
  2032. }
  2033. }
  2034. else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) {
  2035. this[kId] = ByteUtils.fromHex(workingId);
  2036. }
  2037. else {
  2038. throw new BSONError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer');
  2039. }
  2040. }
  2041. else {
  2042. throw new BSONError('Argument passed in does not match the accepted types');
  2043. }
  2044. if (ObjectId.cacheHexString) {
  2045. this.__id = ByteUtils.toHex(this.id);
  2046. }
  2047. }
  2048. get id() {
  2049. return this[kId];
  2050. }
  2051. set id(value) {
  2052. this[kId] = value;
  2053. if (ObjectId.cacheHexString) {
  2054. this.__id = ByteUtils.toHex(value);
  2055. }
  2056. }
  2057. toHexString() {
  2058. if (ObjectId.cacheHexString && this.__id) {
  2059. return this.__id;
  2060. }
  2061. const hexString = ByteUtils.toHex(this.id);
  2062. if (ObjectId.cacheHexString && !this.__id) {
  2063. this.__id = hexString;
  2064. }
  2065. return hexString;
  2066. }
  2067. static getInc() {
  2068. return (ObjectId.index = (ObjectId.index + 1) % 0xffffff);
  2069. }
  2070. static generate(time) {
  2071. if ('number' !== typeof time) {
  2072. time = Math.floor(Date.now() / 1000);
  2073. }
  2074. const inc = ObjectId.getInc();
  2075. const buffer = ByteUtils.allocate(12);
  2076. BSONDataView.fromUint8Array(buffer).setUint32(0, time, false);
  2077. if (PROCESS_UNIQUE === null) {
  2078. PROCESS_UNIQUE = ByteUtils.randomBytes(5);
  2079. }
  2080. buffer[4] = PROCESS_UNIQUE[0];
  2081. buffer[5] = PROCESS_UNIQUE[1];
  2082. buffer[6] = PROCESS_UNIQUE[2];
  2083. buffer[7] = PROCESS_UNIQUE[3];
  2084. buffer[8] = PROCESS_UNIQUE[4];
  2085. buffer[11] = inc & 0xff;
  2086. buffer[10] = (inc >> 8) & 0xff;
  2087. buffer[9] = (inc >> 16) & 0xff;
  2088. return buffer;
  2089. }
  2090. toString(encoding) {
  2091. if (encoding === 'base64')
  2092. return ByteUtils.toBase64(this.id);
  2093. if (encoding === 'hex')
  2094. return this.toHexString();
  2095. return this.toHexString();
  2096. }
  2097. toJSON() {
  2098. return this.toHexString();
  2099. }
  2100. equals(otherId) {
  2101. if (otherId === undefined || otherId === null) {
  2102. return false;
  2103. }
  2104. if (otherId instanceof ObjectId) {
  2105. return this[kId][11] === otherId[kId][11] && ByteUtils.equals(this[kId], otherId[kId]);
  2106. }
  2107. if (typeof otherId === 'string' &&
  2108. ObjectId.isValid(otherId) &&
  2109. otherId.length === 12 &&
  2110. isUint8Array(this.id)) {
  2111. return ByteUtils.equals(this.id, ByteUtils.fromISO88591(otherId));
  2112. }
  2113. if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) {
  2114. return otherId.toLowerCase() === this.toHexString();
  2115. }
  2116. if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) {
  2117. return ByteUtils.equals(ByteUtils.fromUTF8(otherId), this.id);
  2118. }
  2119. if (typeof otherId === 'object' &&
  2120. 'toHexString' in otherId &&
  2121. typeof otherId.toHexString === 'function') {
  2122. const otherIdString = otherId.toHexString();
  2123. const thisIdString = this.toHexString().toLowerCase();
  2124. return typeof otherIdString === 'string' && otherIdString.toLowerCase() === thisIdString;
  2125. }
  2126. return false;
  2127. }
  2128. getTimestamp() {
  2129. const timestamp = new Date();
  2130. const time = BSONDataView.fromUint8Array(this.id).getUint32(0, false);
  2131. timestamp.setTime(Math.floor(time) * 1000);
  2132. return timestamp;
  2133. }
  2134. static createPk() {
  2135. return new ObjectId();
  2136. }
  2137. static createFromTime(time) {
  2138. const buffer = ByteUtils.fromNumberArray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
  2139. BSONDataView.fromUint8Array(buffer).setUint32(0, time, false);
  2140. return new ObjectId(buffer);
  2141. }
  2142. static createFromHexString(hexString) {
  2143. if (hexString?.length !== 24) {
  2144. throw new BSONError('hex string must be 24 characters');
  2145. }
  2146. return new ObjectId(ByteUtils.fromHex(hexString));
  2147. }
  2148. static createFromBase64(base64) {
  2149. if (base64?.length !== 16) {
  2150. throw new BSONError('base64 string must be 16 characters');
  2151. }
  2152. return new ObjectId(ByteUtils.fromBase64(base64));
  2153. }
  2154. static isValid(id) {
  2155. if (id == null)
  2156. return false;
  2157. try {
  2158. new ObjectId(id);
  2159. return true;
  2160. }
  2161. catch {
  2162. return false;
  2163. }
  2164. }
  2165. toExtendedJSON() {
  2166. if (this.toHexString)
  2167. return { $oid: this.toHexString() };
  2168. return { $oid: this.toString('hex') };
  2169. }
  2170. static fromExtendedJSON(doc) {
  2171. return new ObjectId(doc.$oid);
  2172. }
  2173. [Symbol.for('nodejs.util.inspect.custom')]() {
  2174. return this.inspect();
  2175. }
  2176. inspect() {
  2177. return `new ObjectId("${this.toHexString()}")`;
  2178. }
  2179. }
  2180. ObjectId.index = Math.floor(Math.random() * 0xffffff);
  2181. function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) {
  2182. let totalLength = 4 + 1;
  2183. if (Array.isArray(object)) {
  2184. for (let i = 0; i < object.length; i++) {
  2185. totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined);
  2186. }
  2187. }
  2188. else {
  2189. if (typeof object?.toBSON === 'function') {
  2190. object = object.toBSON();
  2191. }
  2192. for (const key of Object.keys(object)) {
  2193. totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined);
  2194. }
  2195. }
  2196. return totalLength;
  2197. }
  2198. function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) {
  2199. if (typeof value?.toBSON === 'function') {
  2200. value = value.toBSON();
  2201. }
  2202. switch (typeof value) {
  2203. case 'string':
  2204. return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1;
  2205. case 'number':
  2206. if (Math.floor(value) === value &&
  2207. value >= JS_INT_MIN &&
  2208. value <= JS_INT_MAX) {
  2209. if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
  2210. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1);
  2211. }
  2212. else {
  2213. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
  2214. }
  2215. }
  2216. else {
  2217. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
  2218. }
  2219. case 'undefined':
  2220. if (isArray || !ignoreUndefined)
  2221. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1;
  2222. return 0;
  2223. case 'boolean':
  2224. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1);
  2225. case 'object':
  2226. if (value != null &&
  2227. typeof value._bsontype === 'string' &&
  2228. value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) {
  2229. throw new BSONVersionError();
  2230. }
  2231. else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
  2232. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1;
  2233. }
  2234. else if (value._bsontype === 'ObjectId') {
  2235. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1);
  2236. }
  2237. else if (value instanceof Date || isDate(value)) {
  2238. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
  2239. }
  2240. else if (ArrayBuffer.isView(value) ||
  2241. value instanceof ArrayBuffer ||
  2242. isAnyArrayBuffer(value)) {
  2243. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength);
  2244. }
  2245. else if (value._bsontype === 'Long' ||
  2246. value._bsontype === 'Double' ||
  2247. value._bsontype === 'Timestamp') {
  2248. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
  2249. }
  2250. else if (value._bsontype === 'Decimal128') {
  2251. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1);
  2252. }
  2253. else if (value._bsontype === 'Code') {
  2254. if (value.scope != null && Object.keys(value.scope).length > 0) {
  2255. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2256. 1 +
  2257. 4 +
  2258. 4 +
  2259. ByteUtils.utf8ByteLength(value.code.toString()) +
  2260. 1 +
  2261. internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined));
  2262. }
  2263. else {
  2264. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2265. 1 +
  2266. 4 +
  2267. ByteUtils.utf8ByteLength(value.code.toString()) +
  2268. 1);
  2269. }
  2270. }
  2271. else if (value._bsontype === 'Binary') {
  2272. const binary = value;
  2273. if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
  2274. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2275. (binary.position + 1 + 4 + 1 + 4));
  2276. }
  2277. else {
  2278. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1));
  2279. }
  2280. }
  2281. else if (value._bsontype === 'Symbol') {
  2282. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2283. ByteUtils.utf8ByteLength(value.value) +
  2284. 4 +
  2285. 1 +
  2286. 1);
  2287. }
  2288. else if (value._bsontype === 'DBRef') {
  2289. const ordered_values = Object.assign({
  2290. $ref: value.collection,
  2291. $id: value.oid
  2292. }, value.fields);
  2293. if (value.db != null) {
  2294. ordered_values['$db'] = value.db;
  2295. }
  2296. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2297. 1 +
  2298. internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined));
  2299. }
  2300. else if (value instanceof RegExp || isRegExp(value)) {
  2301. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2302. 1 +
  2303. ByteUtils.utf8ByteLength(value.source) +
  2304. 1 +
  2305. (value.global ? 1 : 0) +
  2306. (value.ignoreCase ? 1 : 0) +
  2307. (value.multiline ? 1 : 0) +
  2308. 1);
  2309. }
  2310. else if (value._bsontype === 'BSONRegExp') {
  2311. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2312. 1 +
  2313. ByteUtils.utf8ByteLength(value.pattern) +
  2314. 1 +
  2315. ByteUtils.utf8ByteLength(value.options) +
  2316. 1);
  2317. }
  2318. else {
  2319. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2320. internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) +
  2321. 1);
  2322. }
  2323. case 'function':
  2324. if (serializeFunctions) {
  2325. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2326. 1 +
  2327. 4 +
  2328. ByteUtils.utf8ByteLength(value.toString()) +
  2329. 1);
  2330. }
  2331. }
  2332. return 0;
  2333. }
  2334. function alphabetize(str) {
  2335. return str.split('').sort().join('');
  2336. }
  2337. class BSONRegExp extends BSONValue {
  2338. get _bsontype() {
  2339. return 'BSONRegExp';
  2340. }
  2341. constructor(pattern, options) {
  2342. super();
  2343. this.pattern = pattern;
  2344. this.options = alphabetize(options ?? '');
  2345. if (this.pattern.indexOf('\x00') !== -1) {
  2346. throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`);
  2347. }
  2348. if (this.options.indexOf('\x00') !== -1) {
  2349. throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`);
  2350. }
  2351. for (let i = 0; i < this.options.length; i++) {
  2352. if (!(this.options[i] === 'i' ||
  2353. this.options[i] === 'm' ||
  2354. this.options[i] === 'x' ||
  2355. this.options[i] === 'l' ||
  2356. this.options[i] === 's' ||
  2357. this.options[i] === 'u')) {
  2358. throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`);
  2359. }
  2360. }
  2361. }
  2362. static parseOptions(options) {
  2363. return options ? options.split('').sort().join('') : '';
  2364. }
  2365. toExtendedJSON(options) {
  2366. options = options || {};
  2367. if (options.legacy) {
  2368. return { $regex: this.pattern, $options: this.options };
  2369. }
  2370. return { $regularExpression: { pattern: this.pattern, options: this.options } };
  2371. }
  2372. static fromExtendedJSON(doc) {
  2373. if ('$regex' in doc) {
  2374. if (typeof doc.$regex !== 'string') {
  2375. if (doc.$regex._bsontype === 'BSONRegExp') {
  2376. return doc;
  2377. }
  2378. }
  2379. else {
  2380. return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options));
  2381. }
  2382. }
  2383. if ('$regularExpression' in doc) {
  2384. return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options));
  2385. }
  2386. throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`);
  2387. }
  2388. [Symbol.for('nodejs.util.inspect.custom')]() {
  2389. return this.inspect();
  2390. }
  2391. inspect() {
  2392. return `new BSONRegExp(${JSON.stringify(this.pattern)}, ${JSON.stringify(this.options)})`;
  2393. }
  2394. }
  2395. class BSONSymbol extends BSONValue {
  2396. get _bsontype() {
  2397. return 'BSONSymbol';
  2398. }
  2399. constructor(value) {
  2400. super();
  2401. this.value = value;
  2402. }
  2403. valueOf() {
  2404. return this.value;
  2405. }
  2406. toString() {
  2407. return this.value;
  2408. }
  2409. inspect() {
  2410. return `new BSONSymbol("${this.value}")`;
  2411. }
  2412. toJSON() {
  2413. return this.value;
  2414. }
  2415. toExtendedJSON() {
  2416. return { $symbol: this.value };
  2417. }
  2418. static fromExtendedJSON(doc) {
  2419. return new BSONSymbol(doc.$symbol);
  2420. }
  2421. [Symbol.for('nodejs.util.inspect.custom')]() {
  2422. return this.inspect();
  2423. }
  2424. }
  2425. const LongWithoutOverridesClass = Long;
  2426. class Timestamp extends LongWithoutOverridesClass {
  2427. get _bsontype() {
  2428. return 'Timestamp';
  2429. }
  2430. constructor(low) {
  2431. if (low == null) {
  2432. super(0, 0, true);
  2433. }
  2434. else if (typeof low === 'bigint') {
  2435. super(low, true);
  2436. }
  2437. else if (Long.isLong(low)) {
  2438. super(low.low, low.high, true);
  2439. }
  2440. else if (typeof low === 'object' && 't' in low && 'i' in low) {
  2441. if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) {
  2442. throw new BSONError('Timestamp constructed from { t, i } must provide t as a number');
  2443. }
  2444. if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) {
  2445. throw new BSONError('Timestamp constructed from { t, i } must provide i as a number');
  2446. }
  2447. const t = Number(low.t);
  2448. const i = Number(low.i);
  2449. if (t < 0 || Number.isNaN(t)) {
  2450. throw new BSONError('Timestamp constructed from { t, i } must provide a positive t');
  2451. }
  2452. if (i < 0 || Number.isNaN(i)) {
  2453. throw new BSONError('Timestamp constructed from { t, i } must provide a positive i');
  2454. }
  2455. if (t > 4294967295) {
  2456. throw new BSONError('Timestamp constructed from { t, i } must provide t equal or less than uint32 max');
  2457. }
  2458. if (i > 4294967295) {
  2459. throw new BSONError('Timestamp constructed from { t, i } must provide i equal or less than uint32 max');
  2460. }
  2461. super(i, t, true);
  2462. }
  2463. else {
  2464. throw new BSONError('A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }');
  2465. }
  2466. }
  2467. toJSON() {
  2468. return {
  2469. $timestamp: this.toString()
  2470. };
  2471. }
  2472. static fromInt(value) {
  2473. return new Timestamp(Long.fromInt(value, true));
  2474. }
  2475. static fromNumber(value) {
  2476. return new Timestamp(Long.fromNumber(value, true));
  2477. }
  2478. static fromBits(lowBits, highBits) {
  2479. return new Timestamp({ i: lowBits, t: highBits });
  2480. }
  2481. static fromString(str, optRadix) {
  2482. return new Timestamp(Long.fromString(str, true, optRadix));
  2483. }
  2484. toExtendedJSON() {
  2485. return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } };
  2486. }
  2487. static fromExtendedJSON(doc) {
  2488. const i = Long.isLong(doc.$timestamp.i)
  2489. ? doc.$timestamp.i.getLowBitsUnsigned()
  2490. : doc.$timestamp.i;
  2491. const t = Long.isLong(doc.$timestamp.t)
  2492. ? doc.$timestamp.t.getLowBitsUnsigned()
  2493. : doc.$timestamp.t;
  2494. return new Timestamp({ t, i });
  2495. }
  2496. [Symbol.for('nodejs.util.inspect.custom')]() {
  2497. return this.inspect();
  2498. }
  2499. inspect() {
  2500. return `new Timestamp({ t: ${this.getHighBits()}, i: ${this.getLowBits()} })`;
  2501. }
  2502. }
  2503. Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE;
  2504. const FIRST_BIT = 0x80;
  2505. const FIRST_TWO_BITS = 0xc0;
  2506. const FIRST_THREE_BITS = 0xe0;
  2507. const FIRST_FOUR_BITS = 0xf0;
  2508. const FIRST_FIVE_BITS = 0xf8;
  2509. const TWO_BIT_CHAR = 0xc0;
  2510. const THREE_BIT_CHAR = 0xe0;
  2511. const FOUR_BIT_CHAR = 0xf0;
  2512. const CONTINUING_CHAR = 0x80;
  2513. function validateUtf8(bytes, start, end) {
  2514. let continuation = 0;
  2515. for (let i = start; i < end; i += 1) {
  2516. const byte = bytes[i];
  2517. if (continuation) {
  2518. if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) {
  2519. return false;
  2520. }
  2521. continuation -= 1;
  2522. }
  2523. else if (byte & FIRST_BIT) {
  2524. if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) {
  2525. continuation = 1;
  2526. }
  2527. else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) {
  2528. continuation = 2;
  2529. }
  2530. else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) {
  2531. continuation = 3;
  2532. }
  2533. else {
  2534. return false;
  2535. }
  2536. }
  2537. }
  2538. return !continuation;
  2539. }
  2540. const JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX);
  2541. const JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN);
  2542. function internalDeserialize(buffer, options, isArray) {
  2543. options = options == null ? {} : options;
  2544. const index = options && options.index ? options.index : 0;
  2545. const size = buffer[index] |
  2546. (buffer[index + 1] << 8) |
  2547. (buffer[index + 2] << 16) |
  2548. (buffer[index + 3] << 24);
  2549. if (size < 5) {
  2550. throw new BSONError(`bson size must be >= 5, is ${size}`);
  2551. }
  2552. if (options.allowObjectSmallerThanBufferSize && buffer.length < size) {
  2553. throw new BSONError(`buffer length ${buffer.length} must be >= bson size ${size}`);
  2554. }
  2555. if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) {
  2556. throw new BSONError(`buffer length ${buffer.length} must === bson size ${size}`);
  2557. }
  2558. if (size + index > buffer.byteLength) {
  2559. throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer.byteLength})`);
  2560. }
  2561. if (buffer[index + size - 1] !== 0) {
  2562. throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
  2563. }
  2564. return deserializeObject(buffer, index, options, isArray);
  2565. }
  2566. const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/;
  2567. function deserializeObject(buffer, index, options, isArray = false) {
  2568. const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw'];
  2569. const raw = options['raw'] == null ? false : options['raw'];
  2570. const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false;
  2571. const promoteBuffers = options.promoteBuffers ?? false;
  2572. const promoteLongs = options.promoteLongs ?? true;
  2573. const promoteValues = options.promoteValues ?? true;
  2574. const useBigInt64 = options.useBigInt64 ?? false;
  2575. if (useBigInt64 && !promoteValues) {
  2576. throw new BSONError('Must either request bigint or Long for int64 deserialization');
  2577. }
  2578. if (useBigInt64 && !promoteLongs) {
  2579. throw new BSONError('Must either request bigint or Long for int64 deserialization');
  2580. }
  2581. const validation = options.validation == null ? { utf8: true } : options.validation;
  2582. let globalUTFValidation = true;
  2583. let validationSetting;
  2584. const utf8KeysSet = new Set();
  2585. const utf8ValidatedKeys = validation.utf8;
  2586. if (typeof utf8ValidatedKeys === 'boolean') {
  2587. validationSetting = utf8ValidatedKeys;
  2588. }
  2589. else {
  2590. globalUTFValidation = false;
  2591. const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) {
  2592. return utf8ValidatedKeys[key];
  2593. });
  2594. if (utf8ValidationValues.length === 0) {
  2595. throw new BSONError('UTF-8 validation setting cannot be empty');
  2596. }
  2597. if (typeof utf8ValidationValues[0] !== 'boolean') {
  2598. throw new BSONError('Invalid UTF-8 validation option, must specify boolean values');
  2599. }
  2600. validationSetting = utf8ValidationValues[0];
  2601. if (!utf8ValidationValues.every(item => item === validationSetting)) {
  2602. throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false');
  2603. }
  2604. }
  2605. if (!globalUTFValidation) {
  2606. for (const key of Object.keys(utf8ValidatedKeys)) {
  2607. utf8KeysSet.add(key);
  2608. }
  2609. }
  2610. const startIndex = index;
  2611. if (buffer.length < 5)
  2612. throw new BSONError('corrupt bson message < 5 bytes long');
  2613. const size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  2614. if (size < 5 || size > buffer.length)
  2615. throw new BSONError('corrupt bson message');
  2616. const object = isArray ? [] : {};
  2617. let arrayIndex = 0;
  2618. const done = false;
  2619. let isPossibleDBRef = isArray ? false : null;
  2620. const dataview = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  2621. while (!done) {
  2622. const elementType = buffer[index++];
  2623. if (elementType === 0)
  2624. break;
  2625. let i = index;
  2626. while (buffer[i] !== 0x00 && i < buffer.length) {
  2627. i++;
  2628. }
  2629. if (i >= buffer.byteLength)
  2630. throw new BSONError('Bad BSON Document: illegal CString');
  2631. const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer, index, i);
  2632. let shouldValidateKey = true;
  2633. if (globalUTFValidation || utf8KeysSet.has(name)) {
  2634. shouldValidateKey = validationSetting;
  2635. }
  2636. else {
  2637. shouldValidateKey = !validationSetting;
  2638. }
  2639. if (isPossibleDBRef !== false && name[0] === '$') {
  2640. isPossibleDBRef = allowedDBRefKeys.test(name);
  2641. }
  2642. let value;
  2643. index = i + 1;
  2644. if (elementType === BSON_DATA_STRING) {
  2645. const stringSize = buffer[index++] |
  2646. (buffer[index++] << 8) |
  2647. (buffer[index++] << 16) |
  2648. (buffer[index++] << 24);
  2649. if (stringSize <= 0 ||
  2650. stringSize > buffer.length - index ||
  2651. buffer[index + stringSize - 1] !== 0) {
  2652. throw new BSONError('bad string length in bson');
  2653. }
  2654. value = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
  2655. index = index + stringSize;
  2656. }
  2657. else if (elementType === BSON_DATA_OID) {
  2658. const oid = ByteUtils.allocate(12);
  2659. oid.set(buffer.subarray(index, index + 12));
  2660. value = new ObjectId(oid);
  2661. index = index + 12;
  2662. }
  2663. else if (elementType === BSON_DATA_INT && promoteValues === false) {
  2664. value = new Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24));
  2665. }
  2666. else if (elementType === BSON_DATA_INT) {
  2667. value =
  2668. buffer[index++] |
  2669. (buffer[index++] << 8) |
  2670. (buffer[index++] << 16) |
  2671. (buffer[index++] << 24);
  2672. }
  2673. else if (elementType === BSON_DATA_NUMBER && promoteValues === false) {
  2674. value = new Double(dataview.getFloat64(index, true));
  2675. index = index + 8;
  2676. }
  2677. else if (elementType === BSON_DATA_NUMBER) {
  2678. value = dataview.getFloat64(index, true);
  2679. index = index + 8;
  2680. }
  2681. else if (elementType === BSON_DATA_DATE) {
  2682. const lowBits = buffer[index++] |
  2683. (buffer[index++] << 8) |
  2684. (buffer[index++] << 16) |
  2685. (buffer[index++] << 24);
  2686. const highBits = buffer[index++] |
  2687. (buffer[index++] << 8) |
  2688. (buffer[index++] << 16) |
  2689. (buffer[index++] << 24);
  2690. value = new Date(new Long(lowBits, highBits).toNumber());
  2691. }
  2692. else if (elementType === BSON_DATA_BOOLEAN) {
  2693. if (buffer[index] !== 0 && buffer[index] !== 1)
  2694. throw new BSONError('illegal boolean type value');
  2695. value = buffer[index++] === 1;
  2696. }
  2697. else if (elementType === BSON_DATA_OBJECT) {
  2698. const _index = index;
  2699. const objectSize = buffer[index] |
  2700. (buffer[index + 1] << 8) |
  2701. (buffer[index + 2] << 16) |
  2702. (buffer[index + 3] << 24);
  2703. if (objectSize <= 0 || objectSize > buffer.length - index)
  2704. throw new BSONError('bad embedded document length in bson');
  2705. if (raw) {
  2706. value = buffer.slice(index, index + objectSize);
  2707. }
  2708. else {
  2709. let objectOptions = options;
  2710. if (!globalUTFValidation) {
  2711. objectOptions = { ...options, validation: { utf8: shouldValidateKey } };
  2712. }
  2713. value = deserializeObject(buffer, _index, objectOptions, false);
  2714. }
  2715. index = index + objectSize;
  2716. }
  2717. else if (elementType === BSON_DATA_ARRAY) {
  2718. const _index = index;
  2719. const objectSize = buffer[index] |
  2720. (buffer[index + 1] << 8) |
  2721. (buffer[index + 2] << 16) |
  2722. (buffer[index + 3] << 24);
  2723. let arrayOptions = options;
  2724. const stopIndex = index + objectSize;
  2725. if (fieldsAsRaw && fieldsAsRaw[name]) {
  2726. arrayOptions = { ...options, raw: true };
  2727. }
  2728. if (!globalUTFValidation) {
  2729. arrayOptions = { ...arrayOptions, validation: { utf8: shouldValidateKey } };
  2730. }
  2731. value = deserializeObject(buffer, _index, arrayOptions, true);
  2732. index = index + objectSize;
  2733. if (buffer[index - 1] !== 0)
  2734. throw new BSONError('invalid array terminator byte');
  2735. if (index !== stopIndex)
  2736. throw new BSONError('corrupted array bson');
  2737. }
  2738. else if (elementType === BSON_DATA_UNDEFINED) {
  2739. value = undefined;
  2740. }
  2741. else if (elementType === BSON_DATA_NULL) {
  2742. value = null;
  2743. }
  2744. else if (elementType === BSON_DATA_LONG) {
  2745. const dataview = BSONDataView.fromUint8Array(buffer.subarray(index, index + 8));
  2746. const lowBits = buffer[index++] |
  2747. (buffer[index++] << 8) |
  2748. (buffer[index++] << 16) |
  2749. (buffer[index++] << 24);
  2750. const highBits = buffer[index++] |
  2751. (buffer[index++] << 8) |
  2752. (buffer[index++] << 16) |
  2753. (buffer[index++] << 24);
  2754. const long = new Long(lowBits, highBits);
  2755. if (useBigInt64) {
  2756. value = dataview.getBigInt64(0, true);
  2757. }
  2758. else if (promoteLongs && promoteValues === true) {
  2759. value =
  2760. long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG)
  2761. ? long.toNumber()
  2762. : long;
  2763. }
  2764. else {
  2765. value = long;
  2766. }
  2767. }
  2768. else if (elementType === BSON_DATA_DECIMAL128) {
  2769. const bytes = ByteUtils.allocate(16);
  2770. bytes.set(buffer.subarray(index, index + 16), 0);
  2771. index = index + 16;
  2772. value = new Decimal128(bytes);
  2773. }
  2774. else if (elementType === BSON_DATA_BINARY) {
  2775. let binarySize = buffer[index++] |
  2776. (buffer[index++] << 8) |
  2777. (buffer[index++] << 16) |
  2778. (buffer[index++] << 24);
  2779. const totalBinarySize = binarySize;
  2780. const subType = buffer[index++];
  2781. if (binarySize < 0)
  2782. throw new BSONError('Negative binary type element size found');
  2783. if (binarySize > buffer.byteLength)
  2784. throw new BSONError('Binary type size larger than document size');
  2785. if (buffer['slice'] != null) {
  2786. if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
  2787. binarySize =
  2788. buffer[index++] |
  2789. (buffer[index++] << 8) |
  2790. (buffer[index++] << 16) |
  2791. (buffer[index++] << 24);
  2792. if (binarySize < 0)
  2793. throw new BSONError('Negative binary type element size found for subtype 0x02');
  2794. if (binarySize > totalBinarySize - 4)
  2795. throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
  2796. if (binarySize < totalBinarySize - 4)
  2797. throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
  2798. }
  2799. if (promoteBuffers && promoteValues) {
  2800. value = ByteUtils.toLocalBufferType(buffer.slice(index, index + binarySize));
  2801. }
  2802. else {
  2803. value = new Binary(buffer.slice(index, index + binarySize), subType);
  2804. if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) {
  2805. value = value.toUUID();
  2806. }
  2807. }
  2808. }
  2809. else {
  2810. const _buffer = ByteUtils.allocate(binarySize);
  2811. if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
  2812. binarySize =
  2813. buffer[index++] |
  2814. (buffer[index++] << 8) |
  2815. (buffer[index++] << 16) |
  2816. (buffer[index++] << 24);
  2817. if (binarySize < 0)
  2818. throw new BSONError('Negative binary type element size found for subtype 0x02');
  2819. if (binarySize > totalBinarySize - 4)
  2820. throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
  2821. if (binarySize < totalBinarySize - 4)
  2822. throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
  2823. }
  2824. for (i = 0; i < binarySize; i++) {
  2825. _buffer[i] = buffer[index + i];
  2826. }
  2827. if (promoteBuffers && promoteValues) {
  2828. value = _buffer;
  2829. }
  2830. else {
  2831. value = new Binary(buffer.slice(index, index + binarySize), subType);
  2832. if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) {
  2833. value = value.toUUID();
  2834. }
  2835. }
  2836. }
  2837. index = index + binarySize;
  2838. }
  2839. else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) {
  2840. i = index;
  2841. while (buffer[i] !== 0x00 && i < buffer.length) {
  2842. i++;
  2843. }
  2844. if (i >= buffer.length)
  2845. throw new BSONError('Bad BSON Document: illegal CString');
  2846. const source = ByteUtils.toUTF8(buffer, index, i);
  2847. index = i + 1;
  2848. i = index;
  2849. while (buffer[i] !== 0x00 && i < buffer.length) {
  2850. i++;
  2851. }
  2852. if (i >= buffer.length)
  2853. throw new BSONError('Bad BSON Document: illegal CString');
  2854. const regExpOptions = ByteUtils.toUTF8(buffer, index, i);
  2855. index = i + 1;
  2856. const optionsArray = new Array(regExpOptions.length);
  2857. for (i = 0; i < regExpOptions.length; i++) {
  2858. switch (regExpOptions[i]) {
  2859. case 'm':
  2860. optionsArray[i] = 'm';
  2861. break;
  2862. case 's':
  2863. optionsArray[i] = 'g';
  2864. break;
  2865. case 'i':
  2866. optionsArray[i] = 'i';
  2867. break;
  2868. }
  2869. }
  2870. value = new RegExp(source, optionsArray.join(''));
  2871. }
  2872. else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) {
  2873. i = index;
  2874. while (buffer[i] !== 0x00 && i < buffer.length) {
  2875. i++;
  2876. }
  2877. if (i >= buffer.length)
  2878. throw new BSONError('Bad BSON Document: illegal CString');
  2879. const source = ByteUtils.toUTF8(buffer, index, i);
  2880. index = i + 1;
  2881. i = index;
  2882. while (buffer[i] !== 0x00 && i < buffer.length) {
  2883. i++;
  2884. }
  2885. if (i >= buffer.length)
  2886. throw new BSONError('Bad BSON Document: illegal CString');
  2887. const regExpOptions = ByteUtils.toUTF8(buffer, index, i);
  2888. index = i + 1;
  2889. value = new BSONRegExp(source, regExpOptions);
  2890. }
  2891. else if (elementType === BSON_DATA_SYMBOL) {
  2892. const stringSize = buffer[index++] |
  2893. (buffer[index++] << 8) |
  2894. (buffer[index++] << 16) |
  2895. (buffer[index++] << 24);
  2896. if (stringSize <= 0 ||
  2897. stringSize > buffer.length - index ||
  2898. buffer[index + stringSize - 1] !== 0) {
  2899. throw new BSONError('bad string length in bson');
  2900. }
  2901. const symbol = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
  2902. value = promoteValues ? symbol : new BSONSymbol(symbol);
  2903. index = index + stringSize;
  2904. }
  2905. else if (elementType === BSON_DATA_TIMESTAMP) {
  2906. const i = buffer[index++] +
  2907. buffer[index++] * (1 << 8) +
  2908. buffer[index++] * (1 << 16) +
  2909. buffer[index++] * (1 << 24);
  2910. const t = buffer[index++] +
  2911. buffer[index++] * (1 << 8) +
  2912. buffer[index++] * (1 << 16) +
  2913. buffer[index++] * (1 << 24);
  2914. value = new Timestamp({ i, t });
  2915. }
  2916. else if (elementType === BSON_DATA_MIN_KEY) {
  2917. value = new MinKey();
  2918. }
  2919. else if (elementType === BSON_DATA_MAX_KEY) {
  2920. value = new MaxKey();
  2921. }
  2922. else if (elementType === BSON_DATA_CODE) {
  2923. const stringSize = buffer[index++] |
  2924. (buffer[index++] << 8) |
  2925. (buffer[index++] << 16) |
  2926. (buffer[index++] << 24);
  2927. if (stringSize <= 0 ||
  2928. stringSize > buffer.length - index ||
  2929. buffer[index + stringSize - 1] !== 0) {
  2930. throw new BSONError('bad string length in bson');
  2931. }
  2932. const functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
  2933. value = new Code(functionString);
  2934. index = index + stringSize;
  2935. }
  2936. else if (elementType === BSON_DATA_CODE_W_SCOPE) {
  2937. const totalSize = buffer[index++] |
  2938. (buffer[index++] << 8) |
  2939. (buffer[index++] << 16) |
  2940. (buffer[index++] << 24);
  2941. if (totalSize < 4 + 4 + 4 + 1) {
  2942. throw new BSONError('code_w_scope total size shorter minimum expected length');
  2943. }
  2944. const stringSize = buffer[index++] |
  2945. (buffer[index++] << 8) |
  2946. (buffer[index++] << 16) |
  2947. (buffer[index++] << 24);
  2948. if (stringSize <= 0 ||
  2949. stringSize > buffer.length - index ||
  2950. buffer[index + stringSize - 1] !== 0) {
  2951. throw new BSONError('bad string length in bson');
  2952. }
  2953. const functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
  2954. index = index + stringSize;
  2955. const _index = index;
  2956. const objectSize = buffer[index] |
  2957. (buffer[index + 1] << 8) |
  2958. (buffer[index + 2] << 16) |
  2959. (buffer[index + 3] << 24);
  2960. const scopeObject = deserializeObject(buffer, _index, options, false);
  2961. index = index + objectSize;
  2962. if (totalSize < 4 + 4 + objectSize + stringSize) {
  2963. throw new BSONError('code_w_scope total size is too short, truncating scope');
  2964. }
  2965. if (totalSize > 4 + 4 + objectSize + stringSize) {
  2966. throw new BSONError('code_w_scope total size is too long, clips outer document');
  2967. }
  2968. value = new Code(functionString, scopeObject);
  2969. }
  2970. else if (elementType === BSON_DATA_DBPOINTER) {
  2971. const stringSize = buffer[index++] |
  2972. (buffer[index++] << 8) |
  2973. (buffer[index++] << 16) |
  2974. (buffer[index++] << 24);
  2975. if (stringSize <= 0 ||
  2976. stringSize > buffer.length - index ||
  2977. buffer[index + stringSize - 1] !== 0)
  2978. throw new BSONError('bad string length in bson');
  2979. if (validation != null && validation.utf8) {
  2980. if (!validateUtf8(buffer, index, index + stringSize - 1)) {
  2981. throw new BSONError('Invalid UTF-8 string in BSON document');
  2982. }
  2983. }
  2984. const namespace = ByteUtils.toUTF8(buffer, index, index + stringSize - 1);
  2985. index = index + stringSize;
  2986. const oidBuffer = ByteUtils.allocate(12);
  2987. oidBuffer.set(buffer.subarray(index, index + 12), 0);
  2988. const oid = new ObjectId(oidBuffer);
  2989. index = index + 12;
  2990. value = new DBRef(namespace, oid);
  2991. }
  2992. else {
  2993. throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`);
  2994. }
  2995. if (name === '__proto__') {
  2996. Object.defineProperty(object, name, {
  2997. value,
  2998. writable: true,
  2999. enumerable: true,
  3000. configurable: true
  3001. });
  3002. }
  3003. else {
  3004. object[name] = value;
  3005. }
  3006. }
  3007. if (size !== index - startIndex) {
  3008. if (isArray)
  3009. throw new BSONError('corrupt array bson');
  3010. throw new BSONError('corrupt object bson');
  3011. }
  3012. if (!isPossibleDBRef)
  3013. return object;
  3014. if (isDBRefLike(object)) {
  3015. const copy = Object.assign({}, object);
  3016. delete copy.$ref;
  3017. delete copy.$id;
  3018. delete copy.$db;
  3019. return new DBRef(object.$ref, object.$id, object.$db, copy);
  3020. }
  3021. return object;
  3022. }
  3023. function getValidatedString(buffer, start, end, shouldValidateUtf8) {
  3024. const value = ByteUtils.toUTF8(buffer, start, end);
  3025. if (shouldValidateUtf8) {
  3026. for (let i = 0; i < value.length; i++) {
  3027. if (value.charCodeAt(i) === 0xfffd) {
  3028. if (!validateUtf8(buffer, start, end)) {
  3029. throw new BSONError('Invalid UTF-8 string in BSON document');
  3030. }
  3031. break;
  3032. }
  3033. }
  3034. }
  3035. return value;
  3036. }
  3037. const regexp = /\x00/;
  3038. const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']);
  3039. function serializeString(buffer, key, value, index) {
  3040. buffer[index++] = BSON_DATA_STRING;
  3041. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3042. index = index + numberOfWrittenBytes + 1;
  3043. buffer[index - 1] = 0;
  3044. const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4);
  3045. buffer[index + 3] = ((size + 1) >> 24) & 0xff;
  3046. buffer[index + 2] = ((size + 1) >> 16) & 0xff;
  3047. buffer[index + 1] = ((size + 1) >> 8) & 0xff;
  3048. buffer[index] = (size + 1) & 0xff;
  3049. index = index + 4 + size;
  3050. buffer[index++] = 0;
  3051. return index;
  3052. }
  3053. const NUMBER_SPACE = new DataView(new ArrayBuffer(8), 0, 8);
  3054. const FOUR_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 4);
  3055. const EIGHT_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 8);
  3056. function serializeNumber(buffer, key, value, index) {
  3057. const isNegativeZero = Object.is(value, -0);
  3058. const type = !isNegativeZero &&
  3059. Number.isSafeInteger(value) &&
  3060. value <= BSON_INT32_MAX &&
  3061. value >= BSON_INT32_MIN
  3062. ? BSON_DATA_INT
  3063. : BSON_DATA_NUMBER;
  3064. if (type === BSON_DATA_INT) {
  3065. NUMBER_SPACE.setInt32(0, value, true);
  3066. }
  3067. else {
  3068. NUMBER_SPACE.setFloat64(0, value, true);
  3069. }
  3070. const bytes = type === BSON_DATA_INT ? FOUR_BYTE_VIEW_ON_NUMBER : EIGHT_BYTE_VIEW_ON_NUMBER;
  3071. buffer[index++] = type;
  3072. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3073. index = index + numberOfWrittenBytes;
  3074. buffer[index++] = 0x00;
  3075. buffer.set(bytes, index);
  3076. index += bytes.byteLength;
  3077. return index;
  3078. }
  3079. function serializeBigInt(buffer, key, value, index) {
  3080. buffer[index++] = BSON_DATA_LONG;
  3081. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3082. index += numberOfWrittenBytes;
  3083. buffer[index++] = 0;
  3084. NUMBER_SPACE.setBigInt64(0, value, true);
  3085. buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index);
  3086. index += EIGHT_BYTE_VIEW_ON_NUMBER.byteLength;
  3087. return index;
  3088. }
  3089. function serializeNull(buffer, key, _, index) {
  3090. buffer[index++] = BSON_DATA_NULL;
  3091. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3092. index = index + numberOfWrittenBytes;
  3093. buffer[index++] = 0;
  3094. return index;
  3095. }
  3096. function serializeBoolean(buffer, key, value, index) {
  3097. buffer[index++] = BSON_DATA_BOOLEAN;
  3098. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3099. index = index + numberOfWrittenBytes;
  3100. buffer[index++] = 0;
  3101. buffer[index++] = value ? 1 : 0;
  3102. return index;
  3103. }
  3104. function serializeDate(buffer, key, value, index) {
  3105. buffer[index++] = BSON_DATA_DATE;
  3106. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3107. index = index + numberOfWrittenBytes;
  3108. buffer[index++] = 0;
  3109. const dateInMilis = Long.fromNumber(value.getTime());
  3110. const lowBits = dateInMilis.getLowBits();
  3111. const highBits = dateInMilis.getHighBits();
  3112. buffer[index++] = lowBits & 0xff;
  3113. buffer[index++] = (lowBits >> 8) & 0xff;
  3114. buffer[index++] = (lowBits >> 16) & 0xff;
  3115. buffer[index++] = (lowBits >> 24) & 0xff;
  3116. buffer[index++] = highBits & 0xff;
  3117. buffer[index++] = (highBits >> 8) & 0xff;
  3118. buffer[index++] = (highBits >> 16) & 0xff;
  3119. buffer[index++] = (highBits >> 24) & 0xff;
  3120. return index;
  3121. }
  3122. function serializeRegExp(buffer, key, value, index) {
  3123. buffer[index++] = BSON_DATA_REGEXP;
  3124. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3125. index = index + numberOfWrittenBytes;
  3126. buffer[index++] = 0;
  3127. if (value.source && value.source.match(regexp) != null) {
  3128. throw new BSONError('value ' + value.source + ' must not contain null bytes');
  3129. }
  3130. index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index);
  3131. buffer[index++] = 0x00;
  3132. if (value.ignoreCase)
  3133. buffer[index++] = 0x69;
  3134. if (value.global)
  3135. buffer[index++] = 0x73;
  3136. if (value.multiline)
  3137. buffer[index++] = 0x6d;
  3138. buffer[index++] = 0x00;
  3139. return index;
  3140. }
  3141. function serializeBSONRegExp(buffer, key, value, index) {
  3142. buffer[index++] = BSON_DATA_REGEXP;
  3143. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3144. index = index + numberOfWrittenBytes;
  3145. buffer[index++] = 0;
  3146. if (value.pattern.match(regexp) != null) {
  3147. throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes');
  3148. }
  3149. index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index);
  3150. buffer[index++] = 0x00;
  3151. const sortedOptions = value.options.split('').sort().join('');
  3152. index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index);
  3153. buffer[index++] = 0x00;
  3154. return index;
  3155. }
  3156. function serializeMinMax(buffer, key, value, index) {
  3157. if (value === null) {
  3158. buffer[index++] = BSON_DATA_NULL;
  3159. }
  3160. else if (value._bsontype === 'MinKey') {
  3161. buffer[index++] = BSON_DATA_MIN_KEY;
  3162. }
  3163. else {
  3164. buffer[index++] = BSON_DATA_MAX_KEY;
  3165. }
  3166. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3167. index = index + numberOfWrittenBytes;
  3168. buffer[index++] = 0;
  3169. return index;
  3170. }
  3171. function serializeObjectId(buffer, key, value, index) {
  3172. buffer[index++] = BSON_DATA_OID;
  3173. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3174. index = index + numberOfWrittenBytes;
  3175. buffer[index++] = 0;
  3176. if (isUint8Array(value.id)) {
  3177. buffer.set(value.id.subarray(0, 12), index);
  3178. }
  3179. else {
  3180. throw new BSONError('object [' + JSON.stringify(value) + '] is not a valid ObjectId');
  3181. }
  3182. return index + 12;
  3183. }
  3184. function serializeBuffer(buffer, key, value, index) {
  3185. buffer[index++] = BSON_DATA_BINARY;
  3186. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3187. index = index + numberOfWrittenBytes;
  3188. buffer[index++] = 0;
  3189. const size = value.length;
  3190. buffer[index++] = size & 0xff;
  3191. buffer[index++] = (size >> 8) & 0xff;
  3192. buffer[index++] = (size >> 16) & 0xff;
  3193. buffer[index++] = (size >> 24) & 0xff;
  3194. buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT;
  3195. buffer.set(value, index);
  3196. index = index + size;
  3197. return index;
  3198. }
  3199. function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path) {
  3200. if (path.has(value)) {
  3201. throw new BSONError('Cannot convert circular structure to BSON');
  3202. }
  3203. path.add(value);
  3204. buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT;
  3205. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3206. index = index + numberOfWrittenBytes;
  3207. buffer[index++] = 0;
  3208. const endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
  3209. path.delete(value);
  3210. return endIndex;
  3211. }
  3212. function serializeDecimal128(buffer, key, value, index) {
  3213. buffer[index++] = BSON_DATA_DECIMAL128;
  3214. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3215. index = index + numberOfWrittenBytes;
  3216. buffer[index++] = 0;
  3217. buffer.set(value.bytes.subarray(0, 16), index);
  3218. return index + 16;
  3219. }
  3220. function serializeLong(buffer, key, value, index) {
  3221. buffer[index++] =
  3222. value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP;
  3223. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3224. index = index + numberOfWrittenBytes;
  3225. buffer[index++] = 0;
  3226. const lowBits = value.getLowBits();
  3227. const highBits = value.getHighBits();
  3228. buffer[index++] = lowBits & 0xff;
  3229. buffer[index++] = (lowBits >> 8) & 0xff;
  3230. buffer[index++] = (lowBits >> 16) & 0xff;
  3231. buffer[index++] = (lowBits >> 24) & 0xff;
  3232. buffer[index++] = highBits & 0xff;
  3233. buffer[index++] = (highBits >> 8) & 0xff;
  3234. buffer[index++] = (highBits >> 16) & 0xff;
  3235. buffer[index++] = (highBits >> 24) & 0xff;
  3236. return index;
  3237. }
  3238. function serializeInt32(buffer, key, value, index) {
  3239. value = value.valueOf();
  3240. buffer[index++] = BSON_DATA_INT;
  3241. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3242. index = index + numberOfWrittenBytes;
  3243. buffer[index++] = 0;
  3244. buffer[index++] = value & 0xff;
  3245. buffer[index++] = (value >> 8) & 0xff;
  3246. buffer[index++] = (value >> 16) & 0xff;
  3247. buffer[index++] = (value >> 24) & 0xff;
  3248. return index;
  3249. }
  3250. function serializeDouble(buffer, key, value, index) {
  3251. buffer[index++] = BSON_DATA_NUMBER;
  3252. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3253. index = index + numberOfWrittenBytes;
  3254. buffer[index++] = 0;
  3255. NUMBER_SPACE.setFloat64(0, value.value, true);
  3256. buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index);
  3257. index = index + 8;
  3258. return index;
  3259. }
  3260. function serializeFunction(buffer, key, value, index) {
  3261. buffer[index++] = BSON_DATA_CODE;
  3262. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3263. index = index + numberOfWrittenBytes;
  3264. buffer[index++] = 0;
  3265. const functionString = value.toString();
  3266. const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
  3267. buffer[index] = size & 0xff;
  3268. buffer[index + 1] = (size >> 8) & 0xff;
  3269. buffer[index + 2] = (size >> 16) & 0xff;
  3270. buffer[index + 3] = (size >> 24) & 0xff;
  3271. index = index + 4 + size - 1;
  3272. buffer[index++] = 0;
  3273. return index;
  3274. }
  3275. function serializeCode(buffer, key, value, index, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path) {
  3276. if (value.scope && typeof value.scope === 'object') {
  3277. buffer[index++] = BSON_DATA_CODE_W_SCOPE;
  3278. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3279. index = index + numberOfWrittenBytes;
  3280. buffer[index++] = 0;
  3281. let startIndex = index;
  3282. const functionString = value.code;
  3283. index = index + 4;
  3284. const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
  3285. buffer[index] = codeSize & 0xff;
  3286. buffer[index + 1] = (codeSize >> 8) & 0xff;
  3287. buffer[index + 2] = (codeSize >> 16) & 0xff;
  3288. buffer[index + 3] = (codeSize >> 24) & 0xff;
  3289. buffer[index + 4 + codeSize - 1] = 0;
  3290. index = index + codeSize + 4;
  3291. const endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
  3292. index = endIndex - 1;
  3293. const totalSize = endIndex - startIndex;
  3294. buffer[startIndex++] = totalSize & 0xff;
  3295. buffer[startIndex++] = (totalSize >> 8) & 0xff;
  3296. buffer[startIndex++] = (totalSize >> 16) & 0xff;
  3297. buffer[startIndex++] = (totalSize >> 24) & 0xff;
  3298. buffer[index++] = 0;
  3299. }
  3300. else {
  3301. buffer[index++] = BSON_DATA_CODE;
  3302. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3303. index = index + numberOfWrittenBytes;
  3304. buffer[index++] = 0;
  3305. const functionString = value.code.toString();
  3306. const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
  3307. buffer[index] = size & 0xff;
  3308. buffer[index + 1] = (size >> 8) & 0xff;
  3309. buffer[index + 2] = (size >> 16) & 0xff;
  3310. buffer[index + 3] = (size >> 24) & 0xff;
  3311. index = index + 4 + size - 1;
  3312. buffer[index++] = 0;
  3313. }
  3314. return index;
  3315. }
  3316. function serializeBinary(buffer, key, value, index) {
  3317. buffer[index++] = BSON_DATA_BINARY;
  3318. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3319. index = index + numberOfWrittenBytes;
  3320. buffer[index++] = 0;
  3321. const data = value.buffer;
  3322. let size = value.position;
  3323. if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY)
  3324. size = size + 4;
  3325. buffer[index++] = size & 0xff;
  3326. buffer[index++] = (size >> 8) & 0xff;
  3327. buffer[index++] = (size >> 16) & 0xff;
  3328. buffer[index++] = (size >> 24) & 0xff;
  3329. buffer[index++] = value.sub_type;
  3330. if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
  3331. size = size - 4;
  3332. buffer[index++] = size & 0xff;
  3333. buffer[index++] = (size >> 8) & 0xff;
  3334. buffer[index++] = (size >> 16) & 0xff;
  3335. buffer[index++] = (size >> 24) & 0xff;
  3336. }
  3337. buffer.set(data, index);
  3338. index = index + value.position;
  3339. return index;
  3340. }
  3341. function serializeSymbol(buffer, key, value, index) {
  3342. buffer[index++] = BSON_DATA_SYMBOL;
  3343. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3344. index = index + numberOfWrittenBytes;
  3345. buffer[index++] = 0;
  3346. const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 1;
  3347. buffer[index] = size & 0xff;
  3348. buffer[index + 1] = (size >> 8) & 0xff;
  3349. buffer[index + 2] = (size >> 16) & 0xff;
  3350. buffer[index + 3] = (size >> 24) & 0xff;
  3351. index = index + 4 + size - 1;
  3352. buffer[index++] = 0x00;
  3353. return index;
  3354. }
  3355. function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path) {
  3356. buffer[index++] = BSON_DATA_OBJECT;
  3357. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3358. index = index + numberOfWrittenBytes;
  3359. buffer[index++] = 0;
  3360. let startIndex = index;
  3361. let output = {
  3362. $ref: value.collection || value.namespace,
  3363. $id: value.oid
  3364. };
  3365. if (value.db != null) {
  3366. output.$db = value.db;
  3367. }
  3368. output = Object.assign(output, value.fields);
  3369. const endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions, true, path);
  3370. const size = endIndex - startIndex;
  3371. buffer[startIndex++] = size & 0xff;
  3372. buffer[startIndex++] = (size >> 8) & 0xff;
  3373. buffer[startIndex++] = (size >> 16) & 0xff;
  3374. buffer[startIndex++] = (size >> 24) & 0xff;
  3375. return endIndex;
  3376. }
  3377. function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) {
  3378. if (path == null) {
  3379. if (object == null) {
  3380. buffer[0] = 0x05;
  3381. buffer[1] = 0x00;
  3382. buffer[2] = 0x00;
  3383. buffer[3] = 0x00;
  3384. buffer[4] = 0x00;
  3385. return 5;
  3386. }
  3387. if (Array.isArray(object)) {
  3388. throw new BSONError('serialize does not support an array as the root input');
  3389. }
  3390. if (typeof object !== 'object') {
  3391. throw new BSONError('serialize does not support non-object as the root input');
  3392. }
  3393. else if ('_bsontype' in object && typeof object._bsontype === 'string') {
  3394. throw new BSONError(`BSON types cannot be serialized as a document`);
  3395. }
  3396. else if (isDate(object) ||
  3397. isRegExp(object) ||
  3398. isUint8Array(object) ||
  3399. isAnyArrayBuffer(object)) {
  3400. throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`);
  3401. }
  3402. path = new Set();
  3403. }
  3404. path.add(object);
  3405. let index = startingIndex + 4;
  3406. if (Array.isArray(object)) {
  3407. for (let i = 0; i < object.length; i++) {
  3408. const key = `${i}`;
  3409. let value = object[i];
  3410. if (typeof value?.toBSON === 'function') {
  3411. value = value.toBSON();
  3412. }
  3413. if (typeof value === 'string') {
  3414. index = serializeString(buffer, key, value, index);
  3415. }
  3416. else if (typeof value === 'number') {
  3417. index = serializeNumber(buffer, key, value, index);
  3418. }
  3419. else if (typeof value === 'bigint') {
  3420. index = serializeBigInt(buffer, key, value, index);
  3421. }
  3422. else if (typeof value === 'boolean') {
  3423. index = serializeBoolean(buffer, key, value, index);
  3424. }
  3425. else if (value instanceof Date || isDate(value)) {
  3426. index = serializeDate(buffer, key, value, index);
  3427. }
  3428. else if (value === undefined) {
  3429. index = serializeNull(buffer, key, value, index);
  3430. }
  3431. else if (value === null) {
  3432. index = serializeNull(buffer, key, value, index);
  3433. }
  3434. else if (isUint8Array(value)) {
  3435. index = serializeBuffer(buffer, key, value, index);
  3436. }
  3437. else if (value instanceof RegExp || isRegExp(value)) {
  3438. index = serializeRegExp(buffer, key, value, index);
  3439. }
  3440. else if (typeof value === 'object' && value._bsontype == null) {
  3441. index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  3442. }
  3443. else if (typeof value === 'object' &&
  3444. value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) {
  3445. throw new BSONVersionError();
  3446. }
  3447. else if (value._bsontype === 'ObjectId') {
  3448. index = serializeObjectId(buffer, key, value, index);
  3449. }
  3450. else if (value._bsontype === 'Decimal128') {
  3451. index = serializeDecimal128(buffer, key, value, index);
  3452. }
  3453. else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
  3454. index = serializeLong(buffer, key, value, index);
  3455. }
  3456. else if (value._bsontype === 'Double') {
  3457. index = serializeDouble(buffer, key, value, index);
  3458. }
  3459. else if (typeof value === 'function' && serializeFunctions) {
  3460. index = serializeFunction(buffer, key, value, index);
  3461. }
  3462. else if (value._bsontype === 'Code') {
  3463. index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  3464. }
  3465. else if (value._bsontype === 'Binary') {
  3466. index = serializeBinary(buffer, key, value, index);
  3467. }
  3468. else if (value._bsontype === 'BSONSymbol') {
  3469. index = serializeSymbol(buffer, key, value, index);
  3470. }
  3471. else if (value._bsontype === 'DBRef') {
  3472. index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
  3473. }
  3474. else if (value._bsontype === 'BSONRegExp') {
  3475. index = serializeBSONRegExp(buffer, key, value, index);
  3476. }
  3477. else if (value._bsontype === 'Int32') {
  3478. index = serializeInt32(buffer, key, value, index);
  3479. }
  3480. else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
  3481. index = serializeMinMax(buffer, key, value, index);
  3482. }
  3483. else if (typeof value._bsontype !== 'undefined') {
  3484. throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
  3485. }
  3486. }
  3487. }
  3488. else if (object instanceof Map || isMap(object)) {
  3489. const iterator = object.entries();
  3490. let done = false;
  3491. while (!done) {
  3492. const entry = iterator.next();
  3493. done = !!entry.done;
  3494. if (done)
  3495. continue;
  3496. const key = entry.value[0];
  3497. let value = entry.value[1];
  3498. if (typeof value?.toBSON === 'function') {
  3499. value = value.toBSON();
  3500. }
  3501. const type = typeof value;
  3502. if (typeof key === 'string' && !ignoreKeys.has(key)) {
  3503. if (key.match(regexp) != null) {
  3504. throw new BSONError('key ' + key + ' must not contain null bytes');
  3505. }
  3506. if (checkKeys) {
  3507. if ('$' === key[0]) {
  3508. throw new BSONError('key ' + key + " must not start with '$'");
  3509. }
  3510. else if (~key.indexOf('.')) {
  3511. throw new BSONError('key ' + key + " must not contain '.'");
  3512. }
  3513. }
  3514. }
  3515. if (type === 'string') {
  3516. index = serializeString(buffer, key, value, index);
  3517. }
  3518. else if (type === 'number') {
  3519. index = serializeNumber(buffer, key, value, index);
  3520. }
  3521. else if (type === 'bigint') {
  3522. index = serializeBigInt(buffer, key, value, index);
  3523. }
  3524. else if (type === 'boolean') {
  3525. index = serializeBoolean(buffer, key, value, index);
  3526. }
  3527. else if (value instanceof Date || isDate(value)) {
  3528. index = serializeDate(buffer, key, value, index);
  3529. }
  3530. else if (value === null || (value === undefined && ignoreUndefined === false)) {
  3531. index = serializeNull(buffer, key, value, index);
  3532. }
  3533. else if (isUint8Array(value)) {
  3534. index = serializeBuffer(buffer, key, value, index);
  3535. }
  3536. else if (value instanceof RegExp || isRegExp(value)) {
  3537. index = serializeRegExp(buffer, key, value, index);
  3538. }
  3539. else if (type === 'object' && value._bsontype == null) {
  3540. index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  3541. }
  3542. else if (typeof value === 'object' &&
  3543. value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) {
  3544. throw new BSONVersionError();
  3545. }
  3546. else if (value._bsontype === 'ObjectId') {
  3547. index = serializeObjectId(buffer, key, value, index);
  3548. }
  3549. else if (type === 'object' && value._bsontype === 'Decimal128') {
  3550. index = serializeDecimal128(buffer, key, value, index);
  3551. }
  3552. else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
  3553. index = serializeLong(buffer, key, value, index);
  3554. }
  3555. else if (value._bsontype === 'Double') {
  3556. index = serializeDouble(buffer, key, value, index);
  3557. }
  3558. else if (value._bsontype === 'Code') {
  3559. index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  3560. }
  3561. else if (typeof value === 'function' && serializeFunctions) {
  3562. index = serializeFunction(buffer, key, value, index);
  3563. }
  3564. else if (value._bsontype === 'Binary') {
  3565. index = serializeBinary(buffer, key, value, index);
  3566. }
  3567. else if (value._bsontype === 'BSONSymbol') {
  3568. index = serializeSymbol(buffer, key, value, index);
  3569. }
  3570. else if (value._bsontype === 'DBRef') {
  3571. index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
  3572. }
  3573. else if (value._bsontype === 'BSONRegExp') {
  3574. index = serializeBSONRegExp(buffer, key, value, index);
  3575. }
  3576. else if (value._bsontype === 'Int32') {
  3577. index = serializeInt32(buffer, key, value, index);
  3578. }
  3579. else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
  3580. index = serializeMinMax(buffer, key, value, index);
  3581. }
  3582. else if (typeof value._bsontype !== 'undefined') {
  3583. throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
  3584. }
  3585. }
  3586. }
  3587. else {
  3588. if (typeof object?.toBSON === 'function') {
  3589. object = object.toBSON();
  3590. if (object != null && typeof object !== 'object') {
  3591. throw new BSONError('toBSON function did not return an object');
  3592. }
  3593. }
  3594. for (const key of Object.keys(object)) {
  3595. let value = object[key];
  3596. if (typeof value?.toBSON === 'function') {
  3597. value = value.toBSON();
  3598. }
  3599. const type = typeof value;
  3600. if (typeof key === 'string' && !ignoreKeys.has(key)) {
  3601. if (key.match(regexp) != null) {
  3602. throw new BSONError('key ' + key + ' must not contain null bytes');
  3603. }
  3604. if (checkKeys) {
  3605. if ('$' === key[0]) {
  3606. throw new BSONError('key ' + key + " must not start with '$'");
  3607. }
  3608. else if (~key.indexOf('.')) {
  3609. throw new BSONError('key ' + key + " must not contain '.'");
  3610. }
  3611. }
  3612. }
  3613. if (type === 'string') {
  3614. index = serializeString(buffer, key, value, index);
  3615. }
  3616. else if (type === 'number') {
  3617. index = serializeNumber(buffer, key, value, index);
  3618. }
  3619. else if (type === 'bigint') {
  3620. index = serializeBigInt(buffer, key, value, index);
  3621. }
  3622. else if (type === 'boolean') {
  3623. index = serializeBoolean(buffer, key, value, index);
  3624. }
  3625. else if (value instanceof Date || isDate(value)) {
  3626. index = serializeDate(buffer, key, value, index);
  3627. }
  3628. else if (value === undefined) {
  3629. if (ignoreUndefined === false)
  3630. index = serializeNull(buffer, key, value, index);
  3631. }
  3632. else if (value === null) {
  3633. index = serializeNull(buffer, key, value, index);
  3634. }
  3635. else if (isUint8Array(value)) {
  3636. index = serializeBuffer(buffer, key, value, index);
  3637. }
  3638. else if (value instanceof RegExp || isRegExp(value)) {
  3639. index = serializeRegExp(buffer, key, value, index);
  3640. }
  3641. else if (type === 'object' && value._bsontype == null) {
  3642. index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  3643. }
  3644. else if (typeof value === 'object' &&
  3645. value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) {
  3646. throw new BSONVersionError();
  3647. }
  3648. else if (value._bsontype === 'ObjectId') {
  3649. index = serializeObjectId(buffer, key, value, index);
  3650. }
  3651. else if (type === 'object' && value._bsontype === 'Decimal128') {
  3652. index = serializeDecimal128(buffer, key, value, index);
  3653. }
  3654. else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
  3655. index = serializeLong(buffer, key, value, index);
  3656. }
  3657. else if (value._bsontype === 'Double') {
  3658. index = serializeDouble(buffer, key, value, index);
  3659. }
  3660. else if (value._bsontype === 'Code') {
  3661. index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  3662. }
  3663. else if (typeof value === 'function' && serializeFunctions) {
  3664. index = serializeFunction(buffer, key, value, index);
  3665. }
  3666. else if (value._bsontype === 'Binary') {
  3667. index = serializeBinary(buffer, key, value, index);
  3668. }
  3669. else if (value._bsontype === 'BSONSymbol') {
  3670. index = serializeSymbol(buffer, key, value, index);
  3671. }
  3672. else if (value._bsontype === 'DBRef') {
  3673. index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
  3674. }
  3675. else if (value._bsontype === 'BSONRegExp') {
  3676. index = serializeBSONRegExp(buffer, key, value, index);
  3677. }
  3678. else if (value._bsontype === 'Int32') {
  3679. index = serializeInt32(buffer, key, value, index);
  3680. }
  3681. else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
  3682. index = serializeMinMax(buffer, key, value, index);
  3683. }
  3684. else if (typeof value._bsontype !== 'undefined') {
  3685. throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
  3686. }
  3687. }
  3688. }
  3689. path.delete(object);
  3690. buffer[index++] = 0x00;
  3691. const size = index - startingIndex;
  3692. buffer[startingIndex++] = size & 0xff;
  3693. buffer[startingIndex++] = (size >> 8) & 0xff;
  3694. buffer[startingIndex++] = (size >> 16) & 0xff;
  3695. buffer[startingIndex++] = (size >> 24) & 0xff;
  3696. return index;
  3697. }
  3698. function isBSONType(value) {
  3699. return (value != null &&
  3700. typeof value === 'object' &&
  3701. '_bsontype' in value &&
  3702. typeof value._bsontype === 'string');
  3703. }
  3704. const keysToCodecs = {
  3705. $oid: ObjectId,
  3706. $binary: Binary,
  3707. $uuid: Binary,
  3708. $symbol: BSONSymbol,
  3709. $numberInt: Int32,
  3710. $numberDecimal: Decimal128,
  3711. $numberDouble: Double,
  3712. $numberLong: Long,
  3713. $minKey: MinKey,
  3714. $maxKey: MaxKey,
  3715. $regex: BSONRegExp,
  3716. $regularExpression: BSONRegExp,
  3717. $timestamp: Timestamp
  3718. };
  3719. function deserializeValue(value, options = {}) {
  3720. if (typeof value === 'number') {
  3721. const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN;
  3722. const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN;
  3723. if (options.relaxed || options.legacy) {
  3724. return value;
  3725. }
  3726. if (Number.isInteger(value) && !Object.is(value, -0)) {
  3727. if (in32BitRange) {
  3728. return new Int32(value);
  3729. }
  3730. if (in64BitRange) {
  3731. if (options.useBigInt64) {
  3732. return BigInt(value);
  3733. }
  3734. return Long.fromNumber(value);
  3735. }
  3736. }
  3737. return new Double(value);
  3738. }
  3739. if (value == null || typeof value !== 'object')
  3740. return value;
  3741. if (value.$undefined)
  3742. return null;
  3743. const keys = Object.keys(value).filter(k => k.startsWith('$') && value[k] != null);
  3744. for (let i = 0; i < keys.length; i++) {
  3745. const c = keysToCodecs[keys[i]];
  3746. if (c)
  3747. return c.fromExtendedJSON(value, options);
  3748. }
  3749. if (value.$date != null) {
  3750. const d = value.$date;
  3751. const date = new Date();
  3752. if (options.legacy) {
  3753. if (typeof d === 'number')
  3754. date.setTime(d);
  3755. else if (typeof d === 'string')
  3756. date.setTime(Date.parse(d));
  3757. else if (typeof d === 'bigint')
  3758. date.setTime(Number(d));
  3759. else
  3760. throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
  3761. }
  3762. else {
  3763. if (typeof d === 'string')
  3764. date.setTime(Date.parse(d));
  3765. else if (Long.isLong(d))
  3766. date.setTime(d.toNumber());
  3767. else if (typeof d === 'number' && options.relaxed)
  3768. date.setTime(d);
  3769. else if (typeof d === 'bigint')
  3770. date.setTime(Number(d));
  3771. else
  3772. throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
  3773. }
  3774. return date;
  3775. }
  3776. if (value.$code != null) {
  3777. const copy = Object.assign({}, value);
  3778. if (value.$scope) {
  3779. copy.$scope = deserializeValue(value.$scope);
  3780. }
  3781. return Code.fromExtendedJSON(value);
  3782. }
  3783. if (isDBRefLike(value) || value.$dbPointer) {
  3784. const v = value.$ref ? value : value.$dbPointer;
  3785. if (v instanceof DBRef)
  3786. return v;
  3787. const dollarKeys = Object.keys(v).filter(k => k.startsWith('$'));
  3788. let valid = true;
  3789. dollarKeys.forEach(k => {
  3790. if (['$ref', '$id', '$db'].indexOf(k) === -1)
  3791. valid = false;
  3792. });
  3793. if (valid)
  3794. return DBRef.fromExtendedJSON(v);
  3795. }
  3796. return value;
  3797. }
  3798. function serializeArray(array, options) {
  3799. return array.map((v, index) => {
  3800. options.seenObjects.push({ propertyName: `index ${index}`, obj: null });
  3801. try {
  3802. return serializeValue(v, options);
  3803. }
  3804. finally {
  3805. options.seenObjects.pop();
  3806. }
  3807. });
  3808. }
  3809. function getISOString(date) {
  3810. const isoStr = date.toISOString();
  3811. return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z';
  3812. }
  3813. function serializeValue(value, options) {
  3814. if (value instanceof Map || isMap(value)) {
  3815. const obj = Object.create(null);
  3816. for (const [k, v] of value) {
  3817. if (typeof k !== 'string') {
  3818. throw new BSONError('Can only serialize maps with string keys');
  3819. }
  3820. obj[k] = v;
  3821. }
  3822. return serializeValue(obj, options);
  3823. }
  3824. if ((typeof value === 'object' || typeof value === 'function') && value !== null) {
  3825. const index = options.seenObjects.findIndex(entry => entry.obj === value);
  3826. if (index !== -1) {
  3827. const props = options.seenObjects.map(entry => entry.propertyName);
  3828. const leadingPart = props
  3829. .slice(0, index)
  3830. .map(prop => `${prop} -> `)
  3831. .join('');
  3832. const alreadySeen = props[index];
  3833. const circularPart = ' -> ' +
  3834. props
  3835. .slice(index + 1, props.length - 1)
  3836. .map(prop => `${prop} -> `)
  3837. .join('');
  3838. const current = props[props.length - 1];
  3839. const leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2);
  3840. const dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1);
  3841. throw new BSONError('Converting circular structure to EJSON:\n' +
  3842. ` ${leadingPart}${alreadySeen}${circularPart}${current}\n` +
  3843. ` ${leadingSpace}\\${dashes}/`);
  3844. }
  3845. options.seenObjects[options.seenObjects.length - 1].obj = value;
  3846. }
  3847. if (Array.isArray(value))
  3848. return serializeArray(value, options);
  3849. if (value === undefined)
  3850. return null;
  3851. if (value instanceof Date || isDate(value)) {
  3852. const dateNum = value.getTime(), inRange = dateNum > -1 && dateNum < 253402318800000;
  3853. if (options.legacy) {
  3854. return options.relaxed && inRange
  3855. ? { $date: value.getTime() }
  3856. : { $date: getISOString(value) };
  3857. }
  3858. return options.relaxed && inRange
  3859. ? { $date: getISOString(value) }
  3860. : { $date: { $numberLong: value.getTime().toString() } };
  3861. }
  3862. if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) {
  3863. if (Number.isInteger(value) && !Object.is(value, -0)) {
  3864. if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
  3865. return { $numberInt: value.toString() };
  3866. }
  3867. if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) {
  3868. return { $numberLong: value.toString() };
  3869. }
  3870. }
  3871. return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() };
  3872. }
  3873. if (typeof value === 'bigint') {
  3874. if (!options.relaxed) {
  3875. return { $numberLong: BigInt.asIntN(64, value).toString() };
  3876. }
  3877. return Number(BigInt.asIntN(64, value));
  3878. }
  3879. if (value instanceof RegExp || isRegExp(value)) {
  3880. let flags = value.flags;
  3881. if (flags === undefined) {
  3882. const match = value.toString().match(/[gimuy]*$/);
  3883. if (match) {
  3884. flags = match[0];
  3885. }
  3886. }
  3887. const rx = new BSONRegExp(value.source, flags);
  3888. return rx.toExtendedJSON(options);
  3889. }
  3890. if (value != null && typeof value === 'object')
  3891. return serializeDocument(value, options);
  3892. return value;
  3893. }
  3894. const BSON_TYPE_MAPPINGS = {
  3895. Binary: (o) => new Binary(o.value(), o.sub_type),
  3896. Code: (o) => new Code(o.code, o.scope),
  3897. DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields),
  3898. Decimal128: (o) => new Decimal128(o.bytes),
  3899. Double: (o) => new Double(o.value),
  3900. Int32: (o) => new Int32(o.value),
  3901. Long: (o) => Long.fromBits(o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_),
  3902. MaxKey: () => new MaxKey(),
  3903. MinKey: () => new MinKey(),
  3904. ObjectId: (o) => new ObjectId(o),
  3905. BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options),
  3906. BSONSymbol: (o) => new BSONSymbol(o.value),
  3907. Timestamp: (o) => Timestamp.fromBits(o.low, o.high)
  3908. };
  3909. function serializeDocument(doc, options) {
  3910. if (doc == null || typeof doc !== 'object')
  3911. throw new BSONError('not an object instance');
  3912. const bsontype = doc._bsontype;
  3913. if (typeof bsontype === 'undefined') {
  3914. const _doc = {};
  3915. for (const name of Object.keys(doc)) {
  3916. options.seenObjects.push({ propertyName: name, obj: null });
  3917. try {
  3918. const value = serializeValue(doc[name], options);
  3919. if (name === '__proto__') {
  3920. Object.defineProperty(_doc, name, {
  3921. value,
  3922. writable: true,
  3923. enumerable: true,
  3924. configurable: true
  3925. });
  3926. }
  3927. else {
  3928. _doc[name] = value;
  3929. }
  3930. }
  3931. finally {
  3932. options.seenObjects.pop();
  3933. }
  3934. }
  3935. return _doc;
  3936. }
  3937. else if (doc != null &&
  3938. typeof doc === 'object' &&
  3939. typeof doc._bsontype === 'string' &&
  3940. doc[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) {
  3941. throw new BSONVersionError();
  3942. }
  3943. else if (isBSONType(doc)) {
  3944. let outDoc = doc;
  3945. if (typeof outDoc.toExtendedJSON !== 'function') {
  3946. const mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
  3947. if (!mapper) {
  3948. throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
  3949. }
  3950. outDoc = mapper(outDoc);
  3951. }
  3952. if (bsontype === 'Code' && outDoc.scope) {
  3953. outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options));
  3954. }
  3955. else if (bsontype === 'DBRef' && outDoc.oid) {
  3956. outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options));
  3957. }
  3958. return outDoc.toExtendedJSON(options);
  3959. }
  3960. else {
  3961. throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype);
  3962. }
  3963. }
  3964. function parse(text, options) {
  3965. const ejsonOptions = {
  3966. useBigInt64: options?.useBigInt64 ?? false,
  3967. relaxed: options?.relaxed ?? true,
  3968. legacy: options?.legacy ?? false
  3969. };
  3970. return JSON.parse(text, (key, value) => {
  3971. if (key.indexOf('\x00') !== -1) {
  3972. throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`);
  3973. }
  3974. return deserializeValue(value, ejsonOptions);
  3975. });
  3976. }
  3977. function stringify(value, replacer, space, options) {
  3978. if (space != null && typeof space === 'object') {
  3979. options = space;
  3980. space = 0;
  3981. }
  3982. if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) {
  3983. options = replacer;
  3984. replacer = undefined;
  3985. space = 0;
  3986. }
  3987. const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, {
  3988. seenObjects: [{ propertyName: '(root)', obj: null }]
  3989. });
  3990. const doc = serializeValue(value, serializeOptions);
  3991. return JSON.stringify(doc, replacer, space);
  3992. }
  3993. function EJSONserialize(value, options) {
  3994. options = options || {};
  3995. return JSON.parse(stringify(value, options));
  3996. }
  3997. function EJSONdeserialize(ejson, options) {
  3998. options = options || {};
  3999. return parse(JSON.stringify(ejson), options);
  4000. }
  4001. const EJSON = Object.create(null);
  4002. EJSON.parse = parse;
  4003. EJSON.stringify = stringify;
  4004. EJSON.serialize = EJSONserialize;
  4005. EJSON.deserialize = EJSONdeserialize;
  4006. Object.freeze(EJSON);
  4007. const MAXSIZE = 1024 * 1024 * 17;
  4008. let buffer = ByteUtils.allocate(MAXSIZE);
  4009. function setInternalBufferSize(size) {
  4010. if (buffer.length < size) {
  4011. buffer = ByteUtils.allocate(size);
  4012. }
  4013. }
  4014. function serialize(object, options = {}) {
  4015. const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
  4016. const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  4017. const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  4018. const minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE;
  4019. if (buffer.length < minInternalBufferSize) {
  4020. buffer = ByteUtils.allocate(minInternalBufferSize);
  4021. }
  4022. const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null);
  4023. const finishedBuffer = ByteUtils.allocate(serializationIndex);
  4024. finishedBuffer.set(buffer.subarray(0, serializationIndex), 0);
  4025. return finishedBuffer;
  4026. }
  4027. function serializeWithBufferAndIndex(object, finalBuffer, options = {}) {
  4028. const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
  4029. const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  4030. const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  4031. const startIndex = typeof options.index === 'number' ? options.index : 0;
  4032. const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null);
  4033. finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex);
  4034. return startIndex + serializationIndex - 1;
  4035. }
  4036. function deserialize(buffer, options = {}) {
  4037. return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options);
  4038. }
  4039. function calculateObjectSize(object, options = {}) {
  4040. options = options || {};
  4041. const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  4042. const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  4043. return internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined);
  4044. }
  4045. function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) {
  4046. const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options);
  4047. const bufferData = ByteUtils.toLocalBufferType(data);
  4048. let index = startIndex;
  4049. for (let i = 0; i < numberOfDocuments; i++) {
  4050. const size = bufferData[index] |
  4051. (bufferData[index + 1] << 8) |
  4052. (bufferData[index + 2] << 16) |
  4053. (bufferData[index + 3] << 24);
  4054. internalOptions.index = index;
  4055. documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions);
  4056. index = index + size;
  4057. }
  4058. return index;
  4059. }
  4060. var bson = /*#__PURE__*/Object.freeze({
  4061. __proto__: null,
  4062. BSONError: BSONError,
  4063. BSONRegExp: BSONRegExp,
  4064. BSONRuntimeError: BSONRuntimeError,
  4065. BSONSymbol: BSONSymbol,
  4066. BSONType: BSONType,
  4067. BSONValue: BSONValue,
  4068. BSONVersionError: BSONVersionError,
  4069. Binary: Binary,
  4070. Code: Code,
  4071. DBRef: DBRef,
  4072. Decimal128: Decimal128,
  4073. Double: Double,
  4074. EJSON: EJSON,
  4075. Int32: Int32,
  4076. Long: Long,
  4077. MaxKey: MaxKey,
  4078. MinKey: MinKey,
  4079. ObjectId: ObjectId,
  4080. Timestamp: Timestamp,
  4081. UUID: UUID,
  4082. calculateObjectSize: calculateObjectSize,
  4083. deserialize: deserialize,
  4084. deserializeStream: deserializeStream,
  4085. serialize: serialize,
  4086. serializeWithBufferAndIndex: serializeWithBufferAndIndex,
  4087. setInternalBufferSize: setInternalBufferSize
  4088. });
  4089. exports.BSON = bson;
  4090. exports.BSONError = BSONError;
  4091. exports.BSONRegExp = BSONRegExp;
  4092. exports.BSONRuntimeError = BSONRuntimeError;
  4093. exports.BSONSymbol = BSONSymbol;
  4094. exports.BSONType = BSONType;
  4095. exports.BSONValue = BSONValue;
  4096. exports.BSONVersionError = BSONVersionError;
  4097. exports.Binary = Binary;
  4098. exports.Code = Code;
  4099. exports.DBRef = DBRef;
  4100. exports.Decimal128 = Decimal128;
  4101. exports.Double = Double;
  4102. exports.EJSON = EJSON;
  4103. exports.Int32 = Int32;
  4104. exports.Long = Long;
  4105. exports.MaxKey = MaxKey;
  4106. exports.MinKey = MinKey;
  4107. exports.ObjectId = ObjectId;
  4108. exports.Timestamp = Timestamp;
  4109. exports.UUID = UUID;
  4110. exports.calculateObjectSize = calculateObjectSize;
  4111. exports.deserialize = deserialize;
  4112. exports.deserializeStream = deserializeStream;
  4113. exports.serialize = serialize;
  4114. exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex;
  4115. exports.setInternalBufferSize = setInternalBufferSize;
  4116. //# sourceMappingURL=bson.cjs.map