bson.bundle.js 155 KB

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