bson.cjs 155 KB

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