bson.rn.cjs 155 KB

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