bson 5.3.0 → 5.5.0

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