bson.mjs 154 KB

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