bson 4.5.2 → 4.6.1

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 (56) hide show
  1. package/bower.json +1 -1
  2. package/bson.d.ts +39 -3
  3. package/dist/bson.browser.esm.js +320 -187
  4. package/dist/bson.browser.esm.js.map +1 -1
  5. package/dist/bson.browser.umd.js +323 -186
  6. package/dist/bson.browser.umd.js.map +1 -1
  7. package/dist/bson.bundle.js +323 -186
  8. package/dist/bson.bundle.js.map +1 -1
  9. package/dist/bson.esm.js +320 -187
  10. package/dist/bson.esm.js.map +1 -1
  11. package/lib/binary.js +11 -6
  12. package/lib/binary.js.map +1 -1
  13. package/lib/bson.js +11 -3
  14. package/lib/bson.js.map +1 -1
  15. package/lib/constants.js +5 -1
  16. package/lib/constants.js.map +1 -1
  17. package/lib/decimal128.js +13 -5
  18. package/lib/decimal128.js.map +1 -1
  19. package/lib/ensure_buffer.js +3 -2
  20. package/lib/ensure_buffer.js.map +1 -1
  21. package/lib/error.js +55 -0
  22. package/lib/error.js.map +1 -0
  23. package/lib/extended_json.js +11 -5
  24. package/lib/extended_json.js.map +1 -1
  25. package/lib/int_32.js +1 -1
  26. package/lib/int_32.js.map +1 -1
  27. package/lib/objectid.js +42 -47
  28. package/lib/objectid.js.map +1 -1
  29. package/lib/parser/calculate_size.js +2 -2
  30. package/lib/parser/calculate_size.js.map +1 -1
  31. package/lib/parser/deserializer.js +131 -53
  32. package/lib/parser/deserializer.js.map +1 -1
  33. package/lib/parser/serializer.js +16 -20
  34. package/lib/parser/serializer.js.map +1 -1
  35. package/lib/regexp.js +9 -2
  36. package/lib/regexp.js.map +1 -1
  37. package/lib/uuid.js +2 -1
  38. package/lib/uuid.js.map +1 -1
  39. package/lib/uuid_utils.js +2 -1
  40. package/lib/uuid_utils.js.map +1 -1
  41. package/package.json +4 -2
  42. package/src/binary.ts +11 -6
  43. package/src/bson.ts +7 -1
  44. package/src/constants.ts +6 -0
  45. package/src/decimal128.ts +12 -5
  46. package/src/ensure_buffer.ts +3 -2
  47. package/src/error.ts +23 -0
  48. package/src/extended_json.ts +13 -5
  49. package/src/int_32.ts +1 -1
  50. package/src/objectid.ts +44 -62
  51. package/src/parser/calculate_size.ts +2 -2
  52. package/src/parser/deserializer.ts +159 -57
  53. package/src/parser/serializer.ts +16 -17
  54. package/src/regexp.ts +14 -2
  55. package/src/uuid.ts +2 -1
  56. package/src/uuid_utils.ts +2 -1
package/dist/bson.esm.js CHANGED
@@ -1,5 +1,96 @@
1
1
  import { Buffer } from 'buffer';
2
2
 
3
+ /*! *****************************************************************************
4
+ Copyright (c) Microsoft Corporation.
5
+
6
+ Permission to use, copy, modify, and/or distribute this software for any
7
+ purpose with or without fee is hereby granted.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
16
+ ***************************************************************************** */
17
+
18
+ /* global Reflect, Promise */
19
+ var _extendStatics = function extendStatics(d, b) {
20
+ _extendStatics = Object.setPrototypeOf || {
21
+ __proto__: []
22
+ } instanceof Array && function (d, b) {
23
+ d.__proto__ = b;
24
+ } || function (d, b) {
25
+ for (var p in b) {
26
+ if (b.hasOwnProperty(p)) d[p] = b[p];
27
+ }
28
+ };
29
+
30
+ return _extendStatics(d, b);
31
+ };
32
+
33
+ function __extends(d, b) {
34
+ _extendStatics(d, b);
35
+
36
+ function __() {
37
+ this.constructor = d;
38
+ }
39
+
40
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
41
+ }
42
+
43
+ var _assign = function __assign() {
44
+ _assign = Object.assign || function __assign(t) {
45
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
46
+ s = arguments[i];
47
+
48
+ for (var p in s) {
49
+ if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
50
+ }
51
+ }
52
+
53
+ return t;
54
+ };
55
+
56
+ return _assign.apply(this, arguments);
57
+ };
58
+
59
+ /** @public */
60
+ var BSONError = /** @class */ (function (_super) {
61
+ __extends(BSONError, _super);
62
+ function BSONError(message) {
63
+ var _this = _super.call(this, message) || this;
64
+ Object.setPrototypeOf(_this, BSONError.prototype);
65
+ return _this;
66
+ }
67
+ Object.defineProperty(BSONError.prototype, "name", {
68
+ get: function () {
69
+ return 'BSONError';
70
+ },
71
+ enumerable: false,
72
+ configurable: true
73
+ });
74
+ return BSONError;
75
+ }(Error));
76
+ /** @public */
77
+ var BSONTypeError = /** @class */ (function (_super) {
78
+ __extends(BSONTypeError, _super);
79
+ function BSONTypeError(message) {
80
+ var _this = _super.call(this, message) || this;
81
+ Object.setPrototypeOf(_this, BSONTypeError.prototype);
82
+ return _this;
83
+ }
84
+ Object.defineProperty(BSONTypeError.prototype, "name", {
85
+ get: function () {
86
+ return 'BSONTypeError';
87
+ },
88
+ enumerable: false,
89
+ configurable: true
90
+ });
91
+ return BSONTypeError;
92
+ }(TypeError));
93
+
3
94
  function checkForMath(potentialGlobal) {
4
95
  // eslint-disable-next-line eqeqeq
5
96
  return potentialGlobal && potentialGlobal.Math == Math && potentialGlobal;
@@ -111,7 +202,7 @@ function deprecate(fn, message) {
111
202
  * @param potentialBuffer - The potential buffer
112
203
  * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that
113
204
  * wraps a passed in Uint8Array
114
- * @throws TypeError If anything other than a Buffer or Uint8Array is passed in
205
+ * @throws BSONTypeError If anything other than a Buffer or Uint8Array is passed in
115
206
  */
116
207
  function ensureBuffer(potentialBuffer) {
117
208
  if (ArrayBuffer.isView(potentialBuffer)) {
@@ -120,7 +211,7 @@ function ensureBuffer(potentialBuffer) {
120
211
  if (isAnyArrayBuffer(potentialBuffer)) {
121
212
  return Buffer.from(potentialBuffer);
122
213
  }
123
- throw new TypeError('Must use either Buffer or TypedArray');
214
+ throw new BSONTypeError('Must use either Buffer or TypedArray');
124
215
  }
125
216
 
126
217
  // Validation regex for v4 uuid (validates with or without dashes)
@@ -130,7 +221,7 @@ var uuidValidateString = function (str) {
130
221
  };
131
222
  var uuidHexStringToBuffer = function (hexString) {
132
223
  if (!uuidValidateString(hexString)) {
133
- throw new TypeError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".');
224
+ throw new BSONTypeError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".');
134
225
  }
135
226
  var sanitizedHexString = hexString.replace(/-/g, '');
136
227
  return Buffer.from(sanitizedHexString, 'hex');
@@ -178,7 +269,7 @@ var UUID = /** @class */ (function () {
178
269
  this.id = uuidHexStringToBuffer(input);
179
270
  }
180
271
  else {
181
- throw new TypeError('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).');
272
+ throw new BSONTypeError('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).');
182
273
  }
183
274
  }
184
275
  Object.defineProperty(UUID.prototype, "id", {
@@ -336,7 +427,7 @@ var Binary = /** @class */ (function () {
336
427
  !ArrayBuffer.isView(buffer) &&
337
428
  !(buffer instanceof ArrayBuffer) &&
338
429
  !Array.isArray(buffer)) {
339
- throw new TypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array<number>');
430
+ throw new BSONTypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array<number>');
340
431
  }
341
432
  this.sub_type = subType !== null && subType !== void 0 ? subType : Binary.BSON_BINARY_SUBTYPE_DEFAULT;
342
433
  if (buffer == null) {
@@ -368,10 +459,10 @@ var Binary = /** @class */ (function () {
368
459
  Binary.prototype.put = function (byteValue) {
369
460
  // If it's a string and a has more than one character throw an error
370
461
  if (typeof byteValue === 'string' && byteValue.length !== 1) {
371
- throw new TypeError('only accepts single character String');
462
+ throw new BSONTypeError('only accepts single character String');
372
463
  }
373
464
  else if (typeof byteValue !== 'number' && byteValue.length !== 1)
374
- throw new TypeError('only accepts single character Uint8Array or Array');
465
+ throw new BSONTypeError('only accepts single character Uint8Array or Array');
375
466
  // Decode the byte value once
376
467
  var decodedByte;
377
468
  if (typeof byteValue === 'string') {
@@ -384,7 +475,7 @@ var Binary = /** @class */ (function () {
384
475
  decodedByte = byteValue[0];
385
476
  }
386
477
  if (decodedByte < 0 || decodedByte > 255) {
387
- throw new TypeError('only accepts number in a valid unsigned byte range 0-255');
478
+ throw new BSONTypeError('only accepts number in a valid unsigned byte range 0-255');
388
479
  }
389
480
  if (this.buffer.length > this.position) {
390
481
  this.buffer[this.position++] = decodedByte;
@@ -484,7 +575,7 @@ var Binary = /** @class */ (function () {
484
575
  if (this.sub_type === Binary.SUBTYPE_UUID) {
485
576
  return new UUID(this.buffer.slice(0, this.position));
486
577
  }
487
- throw new Error("Binary sub_type \"" + this.sub_type + "\" is not supported for converting to UUID. Only \"" + Binary.SUBTYPE_UUID + "\" is currently supported.");
578
+ throw new BSONError("Binary sub_type \"" + this.sub_type + "\" is not supported for converting to UUID. Only \"" + Binary.SUBTYPE_UUID + "\" is currently supported.");
488
579
  };
489
580
  /** @internal */
490
581
  Binary.fromExtendedJSON = function (doc, options) {
@@ -508,7 +599,7 @@ var Binary = /** @class */ (function () {
508
599
  data = uuidHexStringToBuffer(doc.$uuid);
509
600
  }
510
601
  if (!data) {
511
- throw new TypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc));
602
+ throw new BSONTypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc));
512
603
  }
513
604
  return new Binary(data, type);
514
605
  };
@@ -539,6 +630,10 @@ var Binary = /** @class */ (function () {
539
630
  Binary.SUBTYPE_UUID = 4;
540
631
  /** MD5 BSON type */
541
632
  Binary.SUBTYPE_MD5 = 5;
633
+ /** Encrypted BSON type */
634
+ Binary.SUBTYPE_ENCRYPTED = 6;
635
+ /** Column BSON type */
636
+ Binary.SUBTYPE_COLUMN = 7;
542
637
  /** User BSON type */
543
638
  Binary.SUBTYPE_USER_DEFINED = 128;
544
639
  return Binary;
@@ -1657,7 +1752,7 @@ function lessThan(left, right) {
1657
1752
  return false;
1658
1753
  }
1659
1754
  function invalidErr(string, message) {
1660
- throw new TypeError("\"" + string + "\" is not a valid Decimal128 string - " + message);
1755
+ throw new BSONTypeError("\"" + string + "\" is not a valid Decimal128 string - " + message);
1661
1756
  }
1662
1757
  /**
1663
1758
  * A class representation of the BSON Decimal128 type.
@@ -1674,9 +1769,15 @@ var Decimal128 = /** @class */ (function () {
1674
1769
  if (typeof bytes === 'string') {
1675
1770
  this.bytes = Decimal128.fromString(bytes).bytes;
1676
1771
  }
1677
- else {
1772
+ else if (isUint8Array(bytes)) {
1773
+ if (bytes.byteLength !== 16) {
1774
+ throw new BSONTypeError('Decimal128 must take a Buffer of 16 bytes');
1775
+ }
1678
1776
  this.bytes = bytes;
1679
1777
  }
1778
+ else {
1779
+ throw new BSONTypeError('Decimal128 must take a Buffer or string');
1780
+ }
1680
1781
  }
1681
1782
  /**
1682
1783
  * Create a Decimal128 instance from a string representation
@@ -1724,7 +1825,7 @@ var Decimal128 = /** @class */ (function () {
1724
1825
  // TODO: implementing a custom parsing for this, or refactoring the regex would yield
1725
1826
  // further gains.
1726
1827
  if (representation.length >= 7000) {
1727
- throw new TypeError('' + representation + ' not a valid Decimal128 string');
1828
+ throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
1728
1829
  }
1729
1830
  // Results
1730
1831
  var stringMatch = representation.match(PARSE_STRING_REGEXP);
@@ -1732,7 +1833,7 @@ var Decimal128 = /** @class */ (function () {
1732
1833
  var nanMatch = representation.match(PARSE_NAN_REGEXP);
1733
1834
  // Validate the string
1734
1835
  if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) {
1735
- throw new TypeError('' + representation + ' not a valid Decimal128 string');
1836
+ throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
1736
1837
  }
1737
1838
  if (stringMatch) {
1738
1839
  // full_match = stringMatch[0]
@@ -1794,7 +1895,7 @@ var Decimal128 = /** @class */ (function () {
1794
1895
  index = index + 1;
1795
1896
  }
1796
1897
  if (sawRadix && !nDigitsRead)
1797
- throw new TypeError('' + representation + ' not a valid Decimal128 string');
1898
+ throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
1798
1899
  // Read exponent if exists
1799
1900
  if (representation[index] === 'e' || representation[index] === 'E') {
1800
1901
  // Read exponent digits
@@ -2311,7 +2412,7 @@ var Int32 = /** @class */ (function () {
2311
2412
  if (value instanceof Number) {
2312
2413
  value = value.valueOf();
2313
2414
  }
2314
- this.value = +value;
2415
+ this.value = +value | 0;
2315
2416
  }
2316
2417
  /**
2317
2418
  * Access the number value.
@@ -2417,50 +2518,57 @@ var ObjectId = /** @class */ (function () {
2417
2518
  /**
2418
2519
  * Create an ObjectId type
2419
2520
  *
2420
- * @param id - Can be a 24 character hex string, 12 byte binary Buffer, or a number.
2521
+ * @param inputId - Can be a 24 character hex string, 12 byte binary Buffer, or a number.
2421
2522
  */
2422
- function ObjectId(id) {
2523
+ function ObjectId(inputId) {
2423
2524
  if (!(this instanceof ObjectId))
2424
- return new ObjectId(id);
2425
- // Duck-typing to support ObjectId from different npm packages
2426
- if (id instanceof ObjectId) {
2427
- this[kId] = id.id;
2428
- this.__id = id.__id;
2429
- }
2430
- if (typeof id === 'object' && id && 'id' in id) {
2431
- if ('toHexString' in id && typeof id.toHexString === 'function') {
2432
- this[kId] = Buffer.from(id.toHexString(), 'hex');
2525
+ return new ObjectId(inputId);
2526
+ // workingId is set based on type of input and whether valid id exists for the input
2527
+ var workingId;
2528
+ if (typeof inputId === 'object' && inputId && 'id' in inputId) {
2529
+ if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) {
2530
+ throw new BSONTypeError('Argument passed in must have an id that is of type string or Buffer');
2531
+ }
2532
+ if ('toHexString' in inputId && typeof inputId.toHexString === 'function') {
2533
+ workingId = Buffer.from(inputId.toHexString(), 'hex');
2433
2534
  }
2434
2535
  else {
2435
- this[kId] = typeof id.id === 'string' ? Buffer.from(id.id) : id.id;
2536
+ workingId = inputId.id;
2436
2537
  }
2437
2538
  }
2438
- // The most common use case (blank id, new objectId instance)
2439
- if (id == null || typeof id === 'number') {
2539
+ else {
2540
+ workingId = inputId;
2541
+ }
2542
+ // the following cases use workingId to construct an ObjectId
2543
+ if (workingId == null || typeof workingId === 'number') {
2544
+ // The most common use case (blank id, new objectId instance)
2440
2545
  // Generate a new id
2441
- this[kId] = ObjectId.generate(typeof id === 'number' ? id : undefined);
2442
- // If we are caching the hex string
2443
- if (ObjectId.cacheHexString) {
2444
- this.__id = this.id.toString('hex');
2445
- }
2546
+ this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined);
2446
2547
  }
2447
- if (ArrayBuffer.isView(id) && id.byteLength === 12) {
2448
- this[kId] = ensureBuffer(id);
2548
+ else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) {
2549
+ this[kId] = ensureBuffer(workingId);
2449
2550
  }
2450
- if (typeof id === 'string') {
2451
- if (id.length === 12) {
2452
- var bytes = Buffer.from(id);
2551
+ else if (typeof workingId === 'string') {
2552
+ if (workingId.length === 12) {
2553
+ var bytes = Buffer.from(workingId);
2453
2554
  if (bytes.byteLength === 12) {
2454
2555
  this[kId] = bytes;
2455
2556
  }
2557
+ else {
2558
+ throw new BSONTypeError('Argument passed in must be a string of 12 bytes');
2559
+ }
2456
2560
  }
2457
- else if (id.length === 24 && checkForHexRegExp.test(id)) {
2458
- this[kId] = Buffer.from(id, 'hex');
2561
+ else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) {
2562
+ this[kId] = Buffer.from(workingId, 'hex');
2459
2563
  }
2460
2564
  else {
2461
- throw new TypeError('Argument passed in must be a Buffer or string of 12 bytes or a string of 24 hex characters');
2565
+ throw new BSONTypeError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters');
2462
2566
  }
2463
2567
  }
2568
+ else {
2569
+ throw new BSONTypeError('Argument passed in does not match the accepted types');
2570
+ }
2571
+ // If we are caching the hex string
2464
2572
  if (ObjectId.cacheHexString) {
2465
2573
  this.__id = this.id.toString('hex');
2466
2574
  }
@@ -2524,7 +2632,7 @@ var ObjectId = /** @class */ (function () {
2524
2632
  */
2525
2633
  ObjectId.generate = function (time) {
2526
2634
  if ('number' !== typeof time) {
2527
- time = ~~(Date.now() / 1000);
2635
+ time = Math.floor(Date.now() / 1000);
2528
2636
  }
2529
2637
  var inc = ObjectId.getInc();
2530
2638
  var buffer = Buffer.alloc(12);
@@ -2623,7 +2731,7 @@ var ObjectId = /** @class */ (function () {
2623
2731
  ObjectId.createFromHexString = function (hexString) {
2624
2732
  // Throw an error if it's not a valid setup
2625
2733
  if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) {
2626
- throw new TypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters');
2734
+ throw new BSONTypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters');
2627
2735
  }
2628
2736
  return new ObjectId(Buffer.from(hexString, 'hex'));
2629
2737
  };
@@ -2635,26 +2743,13 @@ var ObjectId = /** @class */ (function () {
2635
2743
  ObjectId.isValid = function (id) {
2636
2744
  if (id == null)
2637
2745
  return false;
2638
- if (typeof id === 'number') {
2639
- return true;
2640
- }
2641
- if (typeof id === 'string') {
2642
- return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id));
2643
- }
2644
- if (id instanceof ObjectId) {
2645
- return true;
2646
- }
2647
- if (isUint8Array(id) && id.length === 12) {
2746
+ try {
2747
+ new ObjectId(id);
2648
2748
  return true;
2649
2749
  }
2650
- // Duck-Typing detection of ObjectId like objects
2651
- if (typeof id === 'object' && 'toHexString' in id && typeof id.toHexString === 'function') {
2652
- if (typeof id.id === 'string') {
2653
- return id.id.length === 12;
2654
- }
2655
- return id.toHexString().length === 24 && checkForHexRegExp.test(id.id.toString('hex'));
2750
+ catch (_a) {
2751
+ return false;
2656
2752
  }
2657
- return false;
2658
2753
  };
2659
2754
  /** @internal */
2660
2755
  ObjectId.prototype.toExtendedJSON = function () {
@@ -2679,7 +2774,7 @@ var ObjectId = /** @class */ (function () {
2679
2774
  return "new ObjectId(\"" + this.toHexString() + "\")";
2680
2775
  };
2681
2776
  /** @internal */
2682
- ObjectId.index = ~~(Math.random() * 0xffffff);
2777
+ ObjectId.index = Math.floor(Math.random() * 0xffffff);
2683
2778
  return ObjectId;
2684
2779
  }());
2685
2780
  // Deprecated methods
@@ -2714,6 +2809,12 @@ var BSONRegExp = /** @class */ (function () {
2714
2809
  return new BSONRegExp(pattern, options);
2715
2810
  this.pattern = pattern;
2716
2811
  this.options = alphabetize(options !== null && options !== void 0 ? options : '');
2812
+ if (this.pattern.indexOf('\x00') !== -1) {
2813
+ throw new BSONError("BSON Regex patterns cannot contain null bytes, found: " + JSON.stringify(this.pattern));
2814
+ }
2815
+ if (this.options.indexOf('\x00') !== -1) {
2816
+ throw new BSONError("BSON Regex options cannot contain null bytes, found: " + JSON.stringify(this.options));
2817
+ }
2717
2818
  // Validate options
2718
2819
  for (var i = 0; i < this.options.length; i++) {
2719
2820
  if (!(this.options[i] === 'i' ||
@@ -2722,7 +2823,7 @@ var BSONRegExp = /** @class */ (function () {
2722
2823
  this.options[i] === 'l' ||
2723
2824
  this.options[i] === 's' ||
2724
2825
  this.options[i] === 'u')) {
2725
- throw new Error("The regular expression option [" + this.options[i] + "] is not supported");
2826
+ throw new BSONError("The regular expression option [" + this.options[i] + "] is not supported");
2726
2827
  }
2727
2828
  }
2728
2829
  }
@@ -2753,7 +2854,7 @@ var BSONRegExp = /** @class */ (function () {
2753
2854
  if ('$regularExpression' in doc) {
2754
2855
  return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options));
2755
2856
  }
2756
- throw new TypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc));
2857
+ throw new BSONTypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc));
2757
2858
  };
2758
2859
  return BSONRegExp;
2759
2860
  }());
@@ -2802,46 +2903,6 @@ var BSONSymbol = /** @class */ (function () {
2802
2903
  }());
2803
2904
  Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' });
2804
2905
 
2805
- /*! *****************************************************************************
2806
- Copyright (c) Microsoft Corporation.
2807
-
2808
- Permission to use, copy, modify, and/or distribute this software for any
2809
- purpose with or without fee is hereby granted.
2810
-
2811
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
2812
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
2813
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
2814
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
2815
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2816
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2817
- PERFORMANCE OF THIS SOFTWARE.
2818
- ***************************************************************************** */
2819
-
2820
- /* global Reflect, Promise */
2821
- var _extendStatics = function extendStatics(d, b) {
2822
- _extendStatics = Object.setPrototypeOf || {
2823
- __proto__: []
2824
- } instanceof Array && function (d, b) {
2825
- d.__proto__ = b;
2826
- } || function (d, b) {
2827
- for (var p in b) {
2828
- if (b.hasOwnProperty(p)) d[p] = b[p];
2829
- }
2830
- };
2831
-
2832
- return _extendStatics(d, b);
2833
- };
2834
-
2835
- function __extends(d, b) {
2836
- _extendStatics(d, b);
2837
-
2838
- function __() {
2839
- this.constructor = d;
2840
- }
2841
-
2842
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
2843
- }
2844
-
2845
2906
  /** @public */
2846
2907
  var LongWithoutOverridesClass = Long;
2847
2908
  /** @public */
@@ -3056,7 +3117,7 @@ function serializeValue(value, options) {
3056
3117
  var current = props[props.length - 1];
3057
3118
  var leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2);
3058
3119
  var dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1);
3059
- throw new TypeError('Converting circular structure to EJSON:\n' +
3120
+ throw new BSONTypeError('Converting circular structure to EJSON:\n' +
3060
3121
  (" " + leadingPart + alreadySeen + circularPart + current + "\n") +
3061
3122
  (" " + leadingSpace + "\\" + dashes + "/"));
3062
3123
  }
@@ -3129,7 +3190,7 @@ var BSON_TYPE_MAPPINGS = {
3129
3190
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
3130
3191
  function serializeDocument(doc, options) {
3131
3192
  if (doc == null || typeof doc !== 'object')
3132
- throw new Error('not an object instance');
3193
+ throw new BSONError('not an object instance');
3133
3194
  var bsontype = doc._bsontype;
3134
3195
  if (typeof bsontype === 'undefined') {
3135
3196
  // It's a regular object. Recursively serialize its property values.
@@ -3156,7 +3217,7 @@ function serializeDocument(doc, options) {
3156
3217
  // Copy the object into this library's version of that type.
3157
3218
  var mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
3158
3219
  if (!mapper) {
3159
- throw new TypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
3220
+ throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
3160
3221
  }
3161
3222
  outDoc = mapper(outDoc);
3162
3223
  }
@@ -3170,7 +3231,7 @@ function serializeDocument(doc, options) {
3170
3231
  return outDoc.toExtendedJSON(options);
3171
3232
  }
3172
3233
  else {
3173
- throw new Error('_bsontype must be a string, but was: ' + typeof bsontype);
3234
+ throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype);
3174
3235
  }
3175
3236
  }
3176
3237
  /**
@@ -3205,7 +3266,12 @@ var EJSON;
3205
3266
  finalOptions.strict = !finalOptions.relaxed;
3206
3267
  if (typeof finalOptions.strict === 'boolean')
3207
3268
  finalOptions.relaxed = !finalOptions.strict;
3208
- return JSON.parse(text, function (_key, value) { return deserializeValue(value, finalOptions); });
3269
+ return JSON.parse(text, function (key, value) {
3270
+ if (key.indexOf('\x00') !== -1) {
3271
+ throw new BSONError("BSON Document field names cannot contain null bytes, found: " + JSON.stringify(key));
3272
+ }
3273
+ return deserializeValue(value, finalOptions);
3274
+ });
3209
3275
  }
3210
3276
  EJSON.parse = parse;
3211
3277
  /**
@@ -3463,6 +3529,10 @@ var BSON_BINARY_SUBTYPE_UUID = 3;
3463
3529
  var BSON_BINARY_SUBTYPE_UUID_NEW = 4;
3464
3530
  /** Binary MD5 Type @internal */
3465
3531
  var BSON_BINARY_SUBTYPE_MD5 = 5;
3532
+ /** Encrypted BSON type @internal */
3533
+ var BSON_BINARY_SUBTYPE_ENCRYPTED = 6;
3534
+ /** Column BSON type @internal */
3535
+ var BSON_BINARY_SUBTYPE_COLUMN = 7;
3466
3536
  /** Binary User Defined Type @internal */
3467
3537
  var BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
3468
3538
 
@@ -3475,7 +3545,7 @@ function calculateObjectSize$1(object, serializeFunctions, ignoreUndefined) {
3475
3545
  }
3476
3546
  else {
3477
3547
  // If we have toBSON defined, override the current object
3478
- if (object.toBSON) {
3548
+ if (typeof (object === null || object === void 0 ? void 0 : object.toBSON) === 'function') {
3479
3549
  object = object.toBSON();
3480
3550
  }
3481
3551
  // Calculate size
@@ -3493,7 +3563,7 @@ value, serializeFunctions, isArray, ignoreUndefined) {
3493
3563
  if (isArray === void 0) { isArray = false; }
3494
3564
  if (ignoreUndefined === void 0) { ignoreUndefined = false; }
3495
3565
  // If we have toBSON defined, override the current object
3496
- if (value && value.toBSON) {
3566
+ if (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === 'function') {
3497
3567
  value = value.toBSON();
3498
3568
  }
3499
3569
  switch (typeof value) {
@@ -3707,20 +3777,20 @@ function deserialize$1(buffer, options, isArray) {
3707
3777
  (buffer[index + 2] << 16) |
3708
3778
  (buffer[index + 3] << 24);
3709
3779
  if (size < 5) {
3710
- throw new Error("bson size must be >= 5, is " + size);
3780
+ throw new BSONError("bson size must be >= 5, is " + size);
3711
3781
  }
3712
3782
  if (options.allowObjectSmallerThanBufferSize && buffer.length < size) {
3713
- throw new Error("buffer length " + buffer.length + " must be >= bson size " + size);
3783
+ throw new BSONError("buffer length " + buffer.length + " must be >= bson size " + size);
3714
3784
  }
3715
3785
  if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) {
3716
- throw new Error("buffer length " + buffer.length + " must === bson size " + size);
3786
+ throw new BSONError("buffer length " + buffer.length + " must === bson size " + size);
3717
3787
  }
3718
3788
  if (size + index > buffer.byteLength) {
3719
- throw new Error("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")");
3789
+ throw new BSONError("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")");
3720
3790
  }
3721
3791
  // Illegal end value
3722
3792
  if (buffer[index + size - 1] !== 0) {
3723
- throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
3793
+ throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
3724
3794
  }
3725
3795
  // Start deserializtion
3726
3796
  return deserializeObject(buffer, index, options, isArray);
@@ -3739,16 +3809,53 @@ function deserializeObject(buffer, index, options, isArray) {
3739
3809
  var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers'];
3740
3810
  var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs'];
3741
3811
  var promoteValues = options['promoteValues'] == null ? true : options['promoteValues'];
3812
+ // Ensures default validation option if none given
3813
+ var validation = options.validation == null ? { utf8: true } : options.validation;
3814
+ // Shows if global utf-8 validation is enabled or disabled
3815
+ var globalUTFValidation = true;
3816
+ // Reflects utf-8 validation setting regardless of global or specific key validation
3817
+ var validationSetting;
3818
+ // Set of keys either to enable or disable validation on
3819
+ var utf8KeysSet = new Set();
3820
+ // Check for boolean uniformity and empty validation option
3821
+ var utf8ValidatedKeys = validation.utf8;
3822
+ if (typeof utf8ValidatedKeys === 'boolean') {
3823
+ validationSetting = utf8ValidatedKeys;
3824
+ }
3825
+ else {
3826
+ globalUTFValidation = false;
3827
+ var utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) {
3828
+ return utf8ValidatedKeys[key];
3829
+ });
3830
+ if (utf8ValidationValues.length === 0) {
3831
+ throw new BSONError('UTF-8 validation setting cannot be empty');
3832
+ }
3833
+ if (typeof utf8ValidationValues[0] !== 'boolean') {
3834
+ throw new BSONError('Invalid UTF-8 validation option, must specify boolean values');
3835
+ }
3836
+ validationSetting = utf8ValidationValues[0];
3837
+ // Ensures boolean uniformity in utf-8 validation (all true or all false)
3838
+ if (!utf8ValidationValues.every(function (item) { return item === validationSetting; })) {
3839
+ throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false');
3840
+ }
3841
+ }
3842
+ // Add keys to set that will either be validated or not based on validationSetting
3843
+ if (!globalUTFValidation) {
3844
+ for (var _i = 0, _a = Object.keys(utf8ValidatedKeys); _i < _a.length; _i++) {
3845
+ var key = _a[_i];
3846
+ utf8KeysSet.add(key);
3847
+ }
3848
+ }
3742
3849
  // Set the start index
3743
3850
  var startIndex = index;
3744
3851
  // Validate that we have at least 4 bytes of buffer
3745
3852
  if (buffer.length < 5)
3746
- throw new Error('corrupt bson message < 5 bytes long');
3853
+ throw new BSONError('corrupt bson message < 5 bytes long');
3747
3854
  // Read the document size
3748
3855
  var size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
3749
3856
  // Ensure buffer is valid size
3750
3857
  if (size < 5 || size > buffer.length)
3751
- throw new Error('corrupt bson message');
3858
+ throw new BSONError('corrupt bson message');
3752
3859
  // Create holding object
3753
3860
  var object = isArray ? [] : {};
3754
3861
  // Used for arrays to skip having to perform utf8 decoding
@@ -3770,8 +3877,17 @@ function deserializeObject(buffer, index, options, isArray) {
3770
3877
  }
3771
3878
  // If are at the end of the buffer there is a problem with the document
3772
3879
  if (i >= buffer.byteLength)
3773
- throw new Error('Bad BSON Document: illegal CString');
3880
+ throw new BSONError('Bad BSON Document: illegal CString');
3881
+ // Represents the key
3774
3882
  var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i);
3883
+ // shouldValidateKey is true if the key should be validated, false otherwise
3884
+ var shouldValidateKey = true;
3885
+ if (globalUTFValidation || utf8KeysSet.has(name)) {
3886
+ shouldValidateKey = validationSetting;
3887
+ }
3888
+ else {
3889
+ shouldValidateKey = !validationSetting;
3890
+ }
3775
3891
  if (isPossibleDBRef !== false && name[0] === '$') {
3776
3892
  isPossibleDBRef = allowedDBRefKeys.test(name);
3777
3893
  }
@@ -3784,17 +3900,10 @@ function deserializeObject(buffer, index, options, isArray) {
3784
3900
  (buffer[index++] << 24);
3785
3901
  if (stringSize <= 0 ||
3786
3902
  stringSize > buffer.length - index ||
3787
- buffer[index + stringSize - 1] !== 0)
3788
- throw new Error('bad string length in bson');
3789
- value = buffer.toString('utf8', index, index + stringSize - 1);
3790
- for (var i_1 = 0; i_1 < value.length; i_1++) {
3791
- if (value.charCodeAt(i_1) === 0xfffd) {
3792
- if (!validateUtf8(buffer, index, index + stringSize - 1)) {
3793
- throw new Error('Invalid UTF-8 string in BSON document');
3794
- }
3795
- break;
3796
- }
3903
+ buffer[index + stringSize - 1] !== 0) {
3904
+ throw new BSONError('bad string length in bson');
3797
3905
  }
3906
+ value = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
3798
3907
  index = index + stringSize;
3799
3908
  }
3800
3909
  else if (elementType === BSON_DATA_OID) {
@@ -3834,7 +3943,7 @@ function deserializeObject(buffer, index, options, isArray) {
3834
3943
  }
3835
3944
  else if (elementType === BSON_DATA_BOOLEAN) {
3836
3945
  if (buffer[index] !== 0 && buffer[index] !== 1)
3837
- throw new Error('illegal boolean type value');
3946
+ throw new BSONError('illegal boolean type value');
3838
3947
  value = buffer[index++] === 1;
3839
3948
  }
3840
3949
  else if (elementType === BSON_DATA_OBJECT) {
@@ -3844,13 +3953,17 @@ function deserializeObject(buffer, index, options, isArray) {
3844
3953
  (buffer[index + 2] << 16) |
3845
3954
  (buffer[index + 3] << 24);
3846
3955
  if (objectSize <= 0 || objectSize > buffer.length - index)
3847
- throw new Error('bad embedded document length in bson');
3956
+ throw new BSONError('bad embedded document length in bson');
3848
3957
  // We have a raw value
3849
3958
  if (raw) {
3850
3959
  value = buffer.slice(index, index + objectSize);
3851
3960
  }
3852
3961
  else {
3853
- value = deserializeObject(buffer, _index, options, false);
3962
+ var objectOptions = options;
3963
+ if (!globalUTFValidation) {
3964
+ objectOptions = _assign(_assign({}, options), { validation: { utf8: shouldValidateKey } });
3965
+ }
3966
+ value = deserializeObject(buffer, _index, objectOptions, false);
3854
3967
  }
3855
3968
  index = index + objectSize;
3856
3969
  }
@@ -3871,12 +3984,15 @@ function deserializeObject(buffer, index, options, isArray) {
3871
3984
  }
3872
3985
  arrayOptions['raw'] = true;
3873
3986
  }
3987
+ if (!globalUTFValidation) {
3988
+ arrayOptions = _assign(_assign({}, arrayOptions), { validation: { utf8: shouldValidateKey } });
3989
+ }
3874
3990
  value = deserializeObject(buffer, _index, arrayOptions, true);
3875
3991
  index = index + objectSize;
3876
3992
  if (buffer[index - 1] !== 0)
3877
- throw new Error('invalid array terminator byte');
3993
+ throw new BSONError('invalid array terminator byte');
3878
3994
  if (index !== stopIndex)
3879
- throw new Error('corrupted array bson');
3995
+ throw new BSONError('corrupted array bson');
3880
3996
  }
3881
3997
  else if (elementType === BSON_DATA_UNDEFINED) {
3882
3998
  value = undefined;
@@ -3932,10 +4048,10 @@ function deserializeObject(buffer, index, options, isArray) {
3932
4048
  var subType = buffer[index++];
3933
4049
  // Did we have a negative binary size, throw
3934
4050
  if (binarySize < 0)
3935
- throw new Error('Negative binary type element size found');
4051
+ throw new BSONError('Negative binary type element size found');
3936
4052
  // Is the length longer than the document
3937
4053
  if (binarySize > buffer.byteLength)
3938
- throw new Error('Binary type size larger than document size');
4054
+ throw new BSONError('Binary type size larger than document size');
3939
4055
  // Decode as raw Buffer object if options specifies it
3940
4056
  if (buffer['slice'] != null) {
3941
4057
  // If we have subtype 2 skip the 4 bytes for the size
@@ -3946,11 +4062,11 @@ function deserializeObject(buffer, index, options, isArray) {
3946
4062
  (buffer[index++] << 16) |
3947
4063
  (buffer[index++] << 24);
3948
4064
  if (binarySize < 0)
3949
- throw new Error('Negative binary type element size found for subtype 0x02');
4065
+ throw new BSONError('Negative binary type element size found for subtype 0x02');
3950
4066
  if (binarySize > totalBinarySize - 4)
3951
- throw new Error('Binary type with subtype 0x02 contains too long binary size');
4067
+ throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
3952
4068
  if (binarySize < totalBinarySize - 4)
3953
- throw new Error('Binary type with subtype 0x02 contains too short binary size');
4069
+ throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
3954
4070
  }
3955
4071
  if (promoteBuffers && promoteValues) {
3956
4072
  value = buffer.slice(index, index + binarySize);
@@ -3969,11 +4085,11 @@ function deserializeObject(buffer, index, options, isArray) {
3969
4085
  (buffer[index++] << 16) |
3970
4086
  (buffer[index++] << 24);
3971
4087
  if (binarySize < 0)
3972
- throw new Error('Negative binary type element size found for subtype 0x02');
4088
+ throw new BSONError('Negative binary type element size found for subtype 0x02');
3973
4089
  if (binarySize > totalBinarySize - 4)
3974
- throw new Error('Binary type with subtype 0x02 contains too long binary size');
4090
+ throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
3975
4091
  if (binarySize < totalBinarySize - 4)
3976
- throw new Error('Binary type with subtype 0x02 contains too short binary size');
4092
+ throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
3977
4093
  }
3978
4094
  // Copy the data
3979
4095
  for (i = 0; i < binarySize; i++) {
@@ -3998,7 +4114,7 @@ function deserializeObject(buffer, index, options, isArray) {
3998
4114
  }
3999
4115
  // If are at the end of the buffer there is a problem with the document
4000
4116
  if (i >= buffer.length)
4001
- throw new Error('Bad BSON Document: illegal CString');
4117
+ throw new BSONError('Bad BSON Document: illegal CString');
4002
4118
  // Return the C string
4003
4119
  var source = buffer.toString('utf8', index, i);
4004
4120
  // Create the regexp
@@ -4011,7 +4127,7 @@ function deserializeObject(buffer, index, options, isArray) {
4011
4127
  }
4012
4128
  // If are at the end of the buffer there is a problem with the document
4013
4129
  if (i >= buffer.length)
4014
- throw new Error('Bad BSON Document: illegal CString');
4130
+ throw new BSONError('Bad BSON Document: illegal CString');
4015
4131
  // Return the C string
4016
4132
  var regExpOptions = buffer.toString('utf8', index, i);
4017
4133
  index = i + 1;
@@ -4042,7 +4158,7 @@ function deserializeObject(buffer, index, options, isArray) {
4042
4158
  }
4043
4159
  // If are at the end of the buffer there is a problem with the document
4044
4160
  if (i >= buffer.length)
4045
- throw new Error('Bad BSON Document: illegal CString');
4161
+ throw new BSONError('Bad BSON Document: illegal CString');
4046
4162
  // Return the C string
4047
4163
  var source = buffer.toString('utf8', index, i);
4048
4164
  index = i + 1;
@@ -4054,7 +4170,7 @@ function deserializeObject(buffer, index, options, isArray) {
4054
4170
  }
4055
4171
  // If are at the end of the buffer there is a problem with the document
4056
4172
  if (i >= buffer.length)
4057
- throw new Error('Bad BSON Document: illegal CString');
4173
+ throw new BSONError('Bad BSON Document: illegal CString');
4058
4174
  // Return the C string
4059
4175
  var regExpOptions = buffer.toString('utf8', index, i);
4060
4176
  index = i + 1;
@@ -4068,9 +4184,10 @@ function deserializeObject(buffer, index, options, isArray) {
4068
4184
  (buffer[index++] << 24);
4069
4185
  if (stringSize <= 0 ||
4070
4186
  stringSize > buffer.length - index ||
4071
- buffer[index + stringSize - 1] !== 0)
4072
- throw new Error('bad string length in bson');
4073
- var symbol = buffer.toString('utf8', index, index + stringSize - 1);
4187
+ buffer[index + stringSize - 1] !== 0) {
4188
+ throw new BSONError('bad string length in bson');
4189
+ }
4190
+ var symbol = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
4074
4191
  value = promoteValues ? symbol : new BSONSymbol(symbol);
4075
4192
  index = index + stringSize;
4076
4193
  }
@@ -4098,9 +4215,10 @@ function deserializeObject(buffer, index, options, isArray) {
4098
4215
  (buffer[index++] << 24);
4099
4216
  if (stringSize <= 0 ||
4100
4217
  stringSize > buffer.length - index ||
4101
- buffer[index + stringSize - 1] !== 0)
4102
- throw new Error('bad string length in bson');
4103
- var functionString = buffer.toString('utf8', index, index + stringSize - 1);
4218
+ buffer[index + stringSize - 1] !== 0) {
4219
+ throw new BSONError('bad string length in bson');
4220
+ }
4221
+ var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
4104
4222
  // If we are evaluating the functions
4105
4223
  if (evalFunctions) {
4106
4224
  // If we have cache enabled let's look for the md5 of the function in the cache
@@ -4125,7 +4243,7 @@ function deserializeObject(buffer, index, options, isArray) {
4125
4243
  (buffer[index++] << 24);
4126
4244
  // Element cannot be shorter than totalSize + stringSize + documentSize + terminator
4127
4245
  if (totalSize < 4 + 4 + 4 + 1) {
4128
- throw new Error('code_w_scope total size shorter minimum expected length');
4246
+ throw new BSONError('code_w_scope total size shorter minimum expected length');
4129
4247
  }
4130
4248
  // Get the code string size
4131
4249
  var stringSize = buffer[index++] |
@@ -4135,10 +4253,11 @@ function deserializeObject(buffer, index, options, isArray) {
4135
4253
  // Check if we have a valid string
4136
4254
  if (stringSize <= 0 ||
4137
4255
  stringSize > buffer.length - index ||
4138
- buffer[index + stringSize - 1] !== 0)
4139
- throw new Error('bad string length in bson');
4256
+ buffer[index + stringSize - 1] !== 0) {
4257
+ throw new BSONError('bad string length in bson');
4258
+ }
4140
4259
  // Javascript function
4141
- var functionString = buffer.toString('utf8', index, index + stringSize - 1);
4260
+ var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
4142
4261
  // Update parse index position
4143
4262
  index = index + stringSize;
4144
4263
  // Parse the element
@@ -4154,11 +4273,11 @@ function deserializeObject(buffer, index, options, isArray) {
4154
4273
  index = index + objectSize;
4155
4274
  // Check if field length is too short
4156
4275
  if (totalSize < 4 + 4 + objectSize + stringSize) {
4157
- throw new Error('code_w_scope total size is too short, truncating scope');
4276
+ throw new BSONError('code_w_scope total size is too short, truncating scope');
4158
4277
  }
4159
4278
  // Check if totalSize field is too long
4160
4279
  if (totalSize > 4 + 4 + objectSize + stringSize) {
4161
- throw new Error('code_w_scope total size is too long, clips outer document');
4280
+ throw new BSONError('code_w_scope total size is too long, clips outer document');
4162
4281
  }
4163
4282
  // If we are evaluating the functions
4164
4283
  if (evalFunctions) {
@@ -4186,10 +4305,12 @@ function deserializeObject(buffer, index, options, isArray) {
4186
4305
  if (stringSize <= 0 ||
4187
4306
  stringSize > buffer.length - index ||
4188
4307
  buffer[index + stringSize - 1] !== 0)
4189
- throw new Error('bad string length in bson');
4308
+ throw new BSONError('bad string length in bson');
4190
4309
  // Namespace
4191
- if (!validateUtf8(buffer, index, index + stringSize - 1)) {
4192
- throw new Error('Invalid UTF-8 string in BSON document');
4310
+ if (validation != null && validation.utf8) {
4311
+ if (!validateUtf8(buffer, index, index + stringSize - 1)) {
4312
+ throw new BSONError('Invalid UTF-8 string in BSON document');
4313
+ }
4193
4314
  }
4194
4315
  var namespace = buffer.toString('utf8', index, index + stringSize - 1);
4195
4316
  // Update parse index position
@@ -4204,7 +4325,7 @@ function deserializeObject(buffer, index, options, isArray) {
4204
4325
  value = new DBRef(namespace, oid);
4205
4326
  }
4206
4327
  else {
4207
- throw new Error('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"');
4328
+ throw new BSONError('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"');
4208
4329
  }
4209
4330
  if (name === '__proto__') {
4210
4331
  Object.defineProperty(object, name, {
@@ -4221,8 +4342,8 @@ function deserializeObject(buffer, index, options, isArray) {
4221
4342
  // Check if the deserialization was against a valid array/object
4222
4343
  if (size !== index - startIndex) {
4223
4344
  if (isArray)
4224
- throw new Error('corrupt array bson');
4225
- throw new Error('corrupt object bson');
4345
+ throw new BSONError('corrupt array bson');
4346
+ throw new BSONError('corrupt object bson');
4226
4347
  }
4227
4348
  // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef
4228
4349
  if (!isPossibleDBRef)
@@ -4251,6 +4372,21 @@ function isolateEval(functionString, functionCache, object) {
4251
4372
  // Set the object
4252
4373
  return functionCache[functionString].bind(object);
4253
4374
  }
4375
+ function getValidatedString(buffer, start, end, shouldValidateUtf8) {
4376
+ var value = buffer.toString('utf8', start, end);
4377
+ // if utf8 validation is on, do the check
4378
+ if (shouldValidateUtf8) {
4379
+ for (var i = 0; i < value.length; i++) {
4380
+ if (value.charCodeAt(i) === 0xfffd) {
4381
+ if (!validateUtf8(buffer, start, end)) {
4382
+ throw new BSONError('Invalid UTF-8 string in BSON document');
4383
+ }
4384
+ break;
4385
+ }
4386
+ }
4387
+ }
4388
+ return value;
4389
+ }
4254
4390
 
4255
4391
  // Copyright (c) 2008, Fair Oaks Labs, Inc.
4256
4392
  function writeIEEE754(buffer, value, offset, endian, mLen, nBytes) {
@@ -4535,7 +4671,7 @@ function serializeObjectId(buffer, key, value, index, isArray) {
4535
4671
  buffer.set(value.id.subarray(0, 12), index);
4536
4672
  }
4537
4673
  else {
4538
- throw new TypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId');
4674
+ throw new BSONTypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId');
4539
4675
  }
4540
4676
  // Adjust index
4541
4677
  return index + 12;
@@ -4574,7 +4710,7 @@ function serializeObject(buffer, key, value, index, checkKeys, depth, serializeF
4574
4710
  if (path === void 0) { path = []; }
4575
4711
  for (var i = 0; i < path.length; i++) {
4576
4712
  if (path[i] === value)
4577
- throw new Error('cyclic dependency detected');
4713
+ throw new BSONError('cyclic dependency detected');
4578
4714
  }
4579
4715
  // Push value to stack
4580
4716
  path.push(value);
@@ -4875,9 +5011,7 @@ function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializ
4875
5011
  var key = '' + i;
4876
5012
  var value = object[i];
4877
5013
  // Is there an override value
4878
- if (value && value.toBSON) {
4879
- if (typeof value.toBSON !== 'function')
4880
- throw new TypeError('toBSON is not a function');
5014
+ if (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === 'function') {
4881
5015
  value = value.toBSON();
4882
5016
  }
4883
5017
  if (typeof value === 'string') {
@@ -4887,7 +5021,7 @@ function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializ
4887
5021
  index = serializeNumber(buffer, key, value, index, true);
4888
5022
  }
4889
5023
  else if (typeof value === 'bigint') {
4890
- throw new TypeError('Unsupported type BigInt, please use Decimal128');
5024
+ throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
4891
5025
  }
4892
5026
  else if (typeof value === 'boolean') {
4893
5027
  index = serializeBoolean(buffer, key, value, index, true);
@@ -4949,7 +5083,7 @@ function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializ
4949
5083
  index = serializeMinMax(buffer, key, value, index, true);
4950
5084
  }
4951
5085
  else if (typeof value['_bsontype'] !== 'undefined') {
4952
- throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
5086
+ throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
4953
5087
  }
4954
5088
  }
4955
5089
  }
@@ -4991,7 +5125,7 @@ function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializ
4991
5125
  index = serializeNumber(buffer, key, value, index);
4992
5126
  }
4993
5127
  else if (type === 'bigint' || isBigInt64Array(value) || isBigUInt64Array(value)) {
4994
- throw new TypeError('Unsupported type BigInt, please use Decimal128');
5128
+ throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
4995
5129
  }
4996
5130
  else if (type === 'boolean') {
4997
5131
  index = serializeBoolean(buffer, key, value, index);
@@ -5048,26 +5182,23 @@ function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializ
5048
5182
  index = serializeMinMax(buffer, key, value, index);
5049
5183
  }
5050
5184
  else if (typeof value['_bsontype'] !== 'undefined') {
5051
- throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
5185
+ throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
5052
5186
  }
5053
5187
  }
5054
5188
  }
5055
5189
  else {
5056
- // Did we provide a custom serialization method
5057
- if (object.toBSON) {
5058
- if (typeof object.toBSON !== 'function')
5059
- throw new TypeError('toBSON is not a function');
5190
+ if (typeof (object === null || object === void 0 ? void 0 : object.toBSON) === 'function') {
5191
+ // Provided a custom serialization method
5060
5192
  object = object.toBSON();
5061
- if (object != null && typeof object !== 'object')
5062
- throw new TypeError('toBSON function did not return an object');
5193
+ if (object != null && typeof object !== 'object') {
5194
+ throw new BSONTypeError('toBSON function did not return an object');
5195
+ }
5063
5196
  }
5064
5197
  // Iterate over all the keys
5065
5198
  for (var key in object) {
5066
5199
  var value = object[key];
5067
5200
  // Is there an override value
5068
- if (value && value.toBSON) {
5069
- if (typeof value.toBSON !== 'function')
5070
- throw new TypeError('toBSON is not a function');
5201
+ if (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === 'function') {
5071
5202
  value = value.toBSON();
5072
5203
  }
5073
5204
  // Check the type of the value
@@ -5095,7 +5226,7 @@ function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializ
5095
5226
  index = serializeNumber(buffer, key, value, index);
5096
5227
  }
5097
5228
  else if (type === 'bigint') {
5098
- throw new TypeError('Unsupported type BigInt, please use Decimal128');
5229
+ throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
5099
5230
  }
5100
5231
  else if (type === 'boolean') {
5101
5232
  index = serializeBoolean(buffer, key, value, index);
@@ -5156,7 +5287,7 @@ function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializ
5156
5287
  index = serializeMinMax(buffer, key, value, index);
5157
5288
  }
5158
5289
  else if (typeof value['_bsontype'] !== 'undefined') {
5159
- throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
5290
+ throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
5160
5291
  }
5161
5292
  }
5162
5293
  }
@@ -5329,9 +5460,11 @@ var BSON = {
5329
5460
  serializeWithBufferAndIndex: serializeWithBufferAndIndex,
5330
5461
  deserialize: deserialize,
5331
5462
  calculateObjectSize: calculateObjectSize,
5332
- deserializeStream: deserializeStream
5463
+ deserializeStream: deserializeStream,
5464
+ BSONError: BSONError,
5465
+ BSONTypeError: BSONTypeError
5333
5466
  };
5334
5467
 
5335
5468
  export default BSON;
5336
- export { BSONRegExp, BSONSymbol, BSON_BINARY_SUBTYPE_BYTE_ARRAY, BSON_BINARY_SUBTYPE_DEFAULT, BSON_BINARY_SUBTYPE_FUNCTION, BSON_BINARY_SUBTYPE_MD5, BSON_BINARY_SUBTYPE_USER_DEFINED, BSON_BINARY_SUBTYPE_UUID, BSON_BINARY_SUBTYPE_UUID_NEW, BSON_DATA_ARRAY, BSON_DATA_BINARY, BSON_DATA_BOOLEAN, BSON_DATA_CODE, BSON_DATA_CODE_W_SCOPE, BSON_DATA_DATE, BSON_DATA_DBPOINTER, BSON_DATA_DECIMAL128, BSON_DATA_INT, BSON_DATA_LONG, BSON_DATA_MAX_KEY, BSON_DATA_MIN_KEY, BSON_DATA_NULL, BSON_DATA_NUMBER, BSON_DATA_OBJECT, BSON_DATA_OID, BSON_DATA_REGEXP, BSON_DATA_STRING, BSON_DATA_SYMBOL, BSON_DATA_TIMESTAMP, BSON_DATA_UNDEFINED, BSON_INT32_MAX, BSON_INT32_MIN, BSON_INT64_MAX, BSON_INT64_MIN, Binary, Code, DBRef, Decimal128, Double, EJSON, Int32, Long, LongWithoutOverridesClass, bsonMap as Map, MaxKey, MinKey, ObjectId as ObjectID, ObjectId, Timestamp, UUID, calculateObjectSize, deserialize, deserializeStream, serialize, serializeWithBufferAndIndex, setInternalBufferSize };
5469
+ export { BSONError, BSONRegExp, BSONSymbol, BSONTypeError, BSON_BINARY_SUBTYPE_BYTE_ARRAY, BSON_BINARY_SUBTYPE_COLUMN, BSON_BINARY_SUBTYPE_DEFAULT, BSON_BINARY_SUBTYPE_ENCRYPTED, BSON_BINARY_SUBTYPE_FUNCTION, BSON_BINARY_SUBTYPE_MD5, BSON_BINARY_SUBTYPE_USER_DEFINED, BSON_BINARY_SUBTYPE_UUID, BSON_BINARY_SUBTYPE_UUID_NEW, BSON_DATA_ARRAY, BSON_DATA_BINARY, BSON_DATA_BOOLEAN, BSON_DATA_CODE, BSON_DATA_CODE_W_SCOPE, BSON_DATA_DATE, BSON_DATA_DBPOINTER, BSON_DATA_DECIMAL128, BSON_DATA_INT, BSON_DATA_LONG, BSON_DATA_MAX_KEY, BSON_DATA_MIN_KEY, BSON_DATA_NULL, BSON_DATA_NUMBER, BSON_DATA_OBJECT, BSON_DATA_OID, BSON_DATA_REGEXP, BSON_DATA_STRING, BSON_DATA_SYMBOL, BSON_DATA_TIMESTAMP, BSON_DATA_UNDEFINED, BSON_INT32_MAX, BSON_INT32_MIN, BSON_INT64_MAX, BSON_INT64_MIN, Binary, Code, DBRef, Decimal128, Double, EJSON, Int32, Long, LongWithoutOverridesClass, bsonMap as Map, MaxKey, MinKey, ObjectId as ObjectID, ObjectId, Timestamp, UUID, calculateObjectSize, deserialize, deserializeStream, serialize, serializeWithBufferAndIndex, setInternalBufferSize };
5337
5470
  //# sourceMappingURL=bson.esm.js.map