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
@@ -2034,6 +2034,97 @@ var BSON = (function (exports) {
2034
2034
  buffer$1.INSPECT_MAX_BYTES;
2035
2035
  buffer$1.kMaxLength;
2036
2036
 
2037
+ /*! *****************************************************************************
2038
+ Copyright (c) Microsoft Corporation.
2039
+
2040
+ Permission to use, copy, modify, and/or distribute this software for any
2041
+ purpose with or without fee is hereby granted.
2042
+
2043
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
2044
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
2045
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
2046
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
2047
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2048
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2049
+ PERFORMANCE OF THIS SOFTWARE.
2050
+ ***************************************************************************** */
2051
+
2052
+ /* global Reflect, Promise */
2053
+ var _extendStatics = function extendStatics(d, b) {
2054
+ _extendStatics = Object.setPrototypeOf || {
2055
+ __proto__: []
2056
+ } instanceof Array && function (d, b) {
2057
+ d.__proto__ = b;
2058
+ } || function (d, b) {
2059
+ for (var p in b) {
2060
+ if (b.hasOwnProperty(p)) d[p] = b[p];
2061
+ }
2062
+ };
2063
+
2064
+ return _extendStatics(d, b);
2065
+ };
2066
+
2067
+ function __extends(d, b) {
2068
+ _extendStatics(d, b);
2069
+
2070
+ function __() {
2071
+ this.constructor = d;
2072
+ }
2073
+
2074
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
2075
+ }
2076
+
2077
+ var _assign = function __assign() {
2078
+ _assign = Object.assign || function __assign(t) {
2079
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
2080
+ s = arguments[i];
2081
+
2082
+ for (var p in s) {
2083
+ if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
2084
+ }
2085
+ }
2086
+
2087
+ return t;
2088
+ };
2089
+
2090
+ return _assign.apply(this, arguments);
2091
+ };
2092
+
2093
+ /** @public */
2094
+ var BSONError = /** @class */ (function (_super) {
2095
+ __extends(BSONError, _super);
2096
+ function BSONError(message) {
2097
+ var _this = _super.call(this, message) || this;
2098
+ Object.setPrototypeOf(_this, BSONError.prototype);
2099
+ return _this;
2100
+ }
2101
+ Object.defineProperty(BSONError.prototype, "name", {
2102
+ get: function () {
2103
+ return 'BSONError';
2104
+ },
2105
+ enumerable: false,
2106
+ configurable: true
2107
+ });
2108
+ return BSONError;
2109
+ }(Error));
2110
+ /** @public */
2111
+ var BSONTypeError = /** @class */ (function (_super) {
2112
+ __extends(BSONTypeError, _super);
2113
+ function BSONTypeError(message) {
2114
+ var _this = _super.call(this, message) || this;
2115
+ Object.setPrototypeOf(_this, BSONTypeError.prototype);
2116
+ return _this;
2117
+ }
2118
+ Object.defineProperty(BSONTypeError.prototype, "name", {
2119
+ get: function () {
2120
+ return 'BSONTypeError';
2121
+ },
2122
+ enumerable: false,
2123
+ configurable: true
2124
+ });
2125
+ return BSONTypeError;
2126
+ }(TypeError));
2127
+
2037
2128
  function checkForMath(potentialGlobal) {
2038
2129
  // eslint-disable-next-line eqeqeq
2039
2130
  return potentialGlobal && potentialGlobal.Math == Math && potentialGlobal;
@@ -2145,7 +2236,7 @@ var BSON = (function (exports) {
2145
2236
  * @param potentialBuffer - The potential buffer
2146
2237
  * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that
2147
2238
  * wraps a passed in Uint8Array
2148
- * @throws TypeError If anything other than a Buffer or Uint8Array is passed in
2239
+ * @throws BSONTypeError If anything other than a Buffer or Uint8Array is passed in
2149
2240
  */
2150
2241
  function ensureBuffer(potentialBuffer) {
2151
2242
  if (ArrayBuffer.isView(potentialBuffer)) {
@@ -2154,7 +2245,7 @@ var BSON = (function (exports) {
2154
2245
  if (isAnyArrayBuffer(potentialBuffer)) {
2155
2246
  return buffer_1.from(potentialBuffer);
2156
2247
  }
2157
- throw new TypeError('Must use either Buffer or TypedArray');
2248
+ throw new BSONTypeError('Must use either Buffer or TypedArray');
2158
2249
  }
2159
2250
 
2160
2251
  // Validation regex for v4 uuid (validates with or without dashes)
@@ -2164,7 +2255,7 @@ var BSON = (function (exports) {
2164
2255
  };
2165
2256
  var uuidHexStringToBuffer = function (hexString) {
2166
2257
  if (!uuidValidateString(hexString)) {
2167
- 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".');
2258
+ 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".');
2168
2259
  }
2169
2260
  var sanitizedHexString = hexString.replace(/-/g, '');
2170
2261
  return buffer_1.from(sanitizedHexString, 'hex');
@@ -2212,7 +2303,7 @@ var BSON = (function (exports) {
2212
2303
  this.id = uuidHexStringToBuffer(input);
2213
2304
  }
2214
2305
  else {
2215
- 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).');
2306
+ 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).');
2216
2307
  }
2217
2308
  }
2218
2309
  Object.defineProperty(UUID.prototype, "id", {
@@ -2370,7 +2461,7 @@ var BSON = (function (exports) {
2370
2461
  !ArrayBuffer.isView(buffer) &&
2371
2462
  !(buffer instanceof ArrayBuffer) &&
2372
2463
  !Array.isArray(buffer)) {
2373
- throw new TypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array<number>');
2464
+ throw new BSONTypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array<number>');
2374
2465
  }
2375
2466
  this.sub_type = subType !== null && subType !== void 0 ? subType : Binary.BSON_BINARY_SUBTYPE_DEFAULT;
2376
2467
  if (buffer == null) {
@@ -2402,10 +2493,10 @@ var BSON = (function (exports) {
2402
2493
  Binary.prototype.put = function (byteValue) {
2403
2494
  // If it's a string and a has more than one character throw an error
2404
2495
  if (typeof byteValue === 'string' && byteValue.length !== 1) {
2405
- throw new TypeError('only accepts single character String');
2496
+ throw new BSONTypeError('only accepts single character String');
2406
2497
  }
2407
2498
  else if (typeof byteValue !== 'number' && byteValue.length !== 1)
2408
- throw new TypeError('only accepts single character Uint8Array or Array');
2499
+ throw new BSONTypeError('only accepts single character Uint8Array or Array');
2409
2500
  // Decode the byte value once
2410
2501
  var decodedByte;
2411
2502
  if (typeof byteValue === 'string') {
@@ -2418,7 +2509,7 @@ var BSON = (function (exports) {
2418
2509
  decodedByte = byteValue[0];
2419
2510
  }
2420
2511
  if (decodedByte < 0 || decodedByte > 255) {
2421
- throw new TypeError('only accepts number in a valid unsigned byte range 0-255');
2512
+ throw new BSONTypeError('only accepts number in a valid unsigned byte range 0-255');
2422
2513
  }
2423
2514
  if (this.buffer.length > this.position) {
2424
2515
  this.buffer[this.position++] = decodedByte;
@@ -2518,7 +2609,7 @@ var BSON = (function (exports) {
2518
2609
  if (this.sub_type === Binary.SUBTYPE_UUID) {
2519
2610
  return new UUID(this.buffer.slice(0, this.position));
2520
2611
  }
2521
- throw new Error("Binary sub_type \"" + this.sub_type + "\" is not supported for converting to UUID. Only \"" + Binary.SUBTYPE_UUID + "\" is currently supported.");
2612
+ throw new BSONError("Binary sub_type \"" + this.sub_type + "\" is not supported for converting to UUID. Only \"" + Binary.SUBTYPE_UUID + "\" is currently supported.");
2522
2613
  };
2523
2614
  /** @internal */
2524
2615
  Binary.fromExtendedJSON = function (doc, options) {
@@ -2542,7 +2633,7 @@ var BSON = (function (exports) {
2542
2633
  data = uuidHexStringToBuffer(doc.$uuid);
2543
2634
  }
2544
2635
  if (!data) {
2545
- throw new TypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc));
2636
+ throw new BSONTypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc));
2546
2637
  }
2547
2638
  return new Binary(data, type);
2548
2639
  };
@@ -2573,6 +2664,10 @@ var BSON = (function (exports) {
2573
2664
  Binary.SUBTYPE_UUID = 4;
2574
2665
  /** MD5 BSON type */
2575
2666
  Binary.SUBTYPE_MD5 = 5;
2667
+ /** Encrypted BSON type */
2668
+ Binary.SUBTYPE_ENCRYPTED = 6;
2669
+ /** Column BSON type */
2670
+ Binary.SUBTYPE_COLUMN = 7;
2576
2671
  /** User BSON type */
2577
2672
  Binary.SUBTYPE_USER_DEFINED = 128;
2578
2673
  return Binary;
@@ -3691,7 +3786,7 @@ var BSON = (function (exports) {
3691
3786
  return false;
3692
3787
  }
3693
3788
  function invalidErr(string, message) {
3694
- throw new TypeError("\"" + string + "\" is not a valid Decimal128 string - " + message);
3789
+ throw new BSONTypeError("\"" + string + "\" is not a valid Decimal128 string - " + message);
3695
3790
  }
3696
3791
  /**
3697
3792
  * A class representation of the BSON Decimal128 type.
@@ -3708,9 +3803,15 @@ var BSON = (function (exports) {
3708
3803
  if (typeof bytes === 'string') {
3709
3804
  this.bytes = Decimal128.fromString(bytes).bytes;
3710
3805
  }
3711
- else {
3806
+ else if (isUint8Array(bytes)) {
3807
+ if (bytes.byteLength !== 16) {
3808
+ throw new BSONTypeError('Decimal128 must take a Buffer of 16 bytes');
3809
+ }
3712
3810
  this.bytes = bytes;
3713
3811
  }
3812
+ else {
3813
+ throw new BSONTypeError('Decimal128 must take a Buffer or string');
3814
+ }
3714
3815
  }
3715
3816
  /**
3716
3817
  * Create a Decimal128 instance from a string representation
@@ -3758,7 +3859,7 @@ var BSON = (function (exports) {
3758
3859
  // TODO: implementing a custom parsing for this, or refactoring the regex would yield
3759
3860
  // further gains.
3760
3861
  if (representation.length >= 7000) {
3761
- throw new TypeError('' + representation + ' not a valid Decimal128 string');
3862
+ throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
3762
3863
  }
3763
3864
  // Results
3764
3865
  var stringMatch = representation.match(PARSE_STRING_REGEXP);
@@ -3766,7 +3867,7 @@ var BSON = (function (exports) {
3766
3867
  var nanMatch = representation.match(PARSE_NAN_REGEXP);
3767
3868
  // Validate the string
3768
3869
  if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) {
3769
- throw new TypeError('' + representation + ' not a valid Decimal128 string');
3870
+ throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
3770
3871
  }
3771
3872
  if (stringMatch) {
3772
3873
  // full_match = stringMatch[0]
@@ -3828,7 +3929,7 @@ var BSON = (function (exports) {
3828
3929
  index = index + 1;
3829
3930
  }
3830
3931
  if (sawRadix && !nDigitsRead)
3831
- throw new TypeError('' + representation + ' not a valid Decimal128 string');
3932
+ throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
3832
3933
  // Read exponent if exists
3833
3934
  if (representation[index] === 'e' || representation[index] === 'E') {
3834
3935
  // Read exponent digits
@@ -4345,7 +4446,7 @@ var BSON = (function (exports) {
4345
4446
  if (value instanceof Number) {
4346
4447
  value = value.valueOf();
4347
4448
  }
4348
- this.value = +value;
4449
+ this.value = +value | 0;
4349
4450
  }
4350
4451
  /**
4351
4452
  * Access the number value.
@@ -4451,50 +4552,57 @@ var BSON = (function (exports) {
4451
4552
  /**
4452
4553
  * Create an ObjectId type
4453
4554
  *
4454
- * @param id - Can be a 24 character hex string, 12 byte binary Buffer, or a number.
4555
+ * @param inputId - Can be a 24 character hex string, 12 byte binary Buffer, or a number.
4455
4556
  */
4456
- function ObjectId(id) {
4557
+ function ObjectId(inputId) {
4457
4558
  if (!(this instanceof ObjectId))
4458
- return new ObjectId(id);
4459
- // Duck-typing to support ObjectId from different npm packages
4460
- if (id instanceof ObjectId) {
4461
- this[kId] = id.id;
4462
- this.__id = id.__id;
4463
- }
4464
- if (typeof id === 'object' && id && 'id' in id) {
4465
- if ('toHexString' in id && typeof id.toHexString === 'function') {
4466
- this[kId] = buffer_1.from(id.toHexString(), 'hex');
4559
+ return new ObjectId(inputId);
4560
+ // workingId is set based on type of input and whether valid id exists for the input
4561
+ var workingId;
4562
+ if (typeof inputId === 'object' && inputId && 'id' in inputId) {
4563
+ if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) {
4564
+ throw new BSONTypeError('Argument passed in must have an id that is of type string or Buffer');
4565
+ }
4566
+ if ('toHexString' in inputId && typeof inputId.toHexString === 'function') {
4567
+ workingId = buffer_1.from(inputId.toHexString(), 'hex');
4467
4568
  }
4468
4569
  else {
4469
- this[kId] = typeof id.id === 'string' ? buffer_1.from(id.id) : id.id;
4570
+ workingId = inputId.id;
4470
4571
  }
4471
4572
  }
4472
- // The most common use case (blank id, new objectId instance)
4473
- if (id == null || typeof id === 'number') {
4573
+ else {
4574
+ workingId = inputId;
4575
+ }
4576
+ // the following cases use workingId to construct an ObjectId
4577
+ if (workingId == null || typeof workingId === 'number') {
4578
+ // The most common use case (blank id, new objectId instance)
4474
4579
  // Generate a new id
4475
- this[kId] = ObjectId.generate(typeof id === 'number' ? id : undefined);
4476
- // If we are caching the hex string
4477
- if (ObjectId.cacheHexString) {
4478
- this.__id = this.id.toString('hex');
4479
- }
4580
+ this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined);
4480
4581
  }
4481
- if (ArrayBuffer.isView(id) && id.byteLength === 12) {
4482
- this[kId] = ensureBuffer(id);
4582
+ else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) {
4583
+ this[kId] = ensureBuffer(workingId);
4483
4584
  }
4484
- if (typeof id === 'string') {
4485
- if (id.length === 12) {
4486
- var bytes = buffer_1.from(id);
4585
+ else if (typeof workingId === 'string') {
4586
+ if (workingId.length === 12) {
4587
+ var bytes = buffer_1.from(workingId);
4487
4588
  if (bytes.byteLength === 12) {
4488
4589
  this[kId] = bytes;
4489
4590
  }
4591
+ else {
4592
+ throw new BSONTypeError('Argument passed in must be a string of 12 bytes');
4593
+ }
4490
4594
  }
4491
- else if (id.length === 24 && checkForHexRegExp.test(id)) {
4492
- this[kId] = buffer_1.from(id, 'hex');
4595
+ else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) {
4596
+ this[kId] = buffer_1.from(workingId, 'hex');
4493
4597
  }
4494
4598
  else {
4495
- throw new TypeError('Argument passed in must be a Buffer or string of 12 bytes or a string of 24 hex characters');
4599
+ throw new BSONTypeError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters');
4496
4600
  }
4497
4601
  }
4602
+ else {
4603
+ throw new BSONTypeError('Argument passed in does not match the accepted types');
4604
+ }
4605
+ // If we are caching the hex string
4498
4606
  if (ObjectId.cacheHexString) {
4499
4607
  this.__id = this.id.toString('hex');
4500
4608
  }
@@ -4558,7 +4666,7 @@ var BSON = (function (exports) {
4558
4666
  */
4559
4667
  ObjectId.generate = function (time) {
4560
4668
  if ('number' !== typeof time) {
4561
- time = ~~(Date.now() / 1000);
4669
+ time = Math.floor(Date.now() / 1000);
4562
4670
  }
4563
4671
  var inc = ObjectId.getInc();
4564
4672
  var buffer = buffer_1.alloc(12);
@@ -4657,7 +4765,7 @@ var BSON = (function (exports) {
4657
4765
  ObjectId.createFromHexString = function (hexString) {
4658
4766
  // Throw an error if it's not a valid setup
4659
4767
  if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) {
4660
- throw new TypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters');
4768
+ throw new BSONTypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters');
4661
4769
  }
4662
4770
  return new ObjectId(buffer_1.from(hexString, 'hex'));
4663
4771
  };
@@ -4669,26 +4777,13 @@ var BSON = (function (exports) {
4669
4777
  ObjectId.isValid = function (id) {
4670
4778
  if (id == null)
4671
4779
  return false;
4672
- if (typeof id === 'number') {
4673
- return true;
4674
- }
4675
- if (typeof id === 'string') {
4676
- return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id));
4677
- }
4678
- if (id instanceof ObjectId) {
4679
- return true;
4680
- }
4681
- if (isUint8Array(id) && id.length === 12) {
4780
+ try {
4781
+ new ObjectId(id);
4682
4782
  return true;
4683
4783
  }
4684
- // Duck-Typing detection of ObjectId like objects
4685
- if (typeof id === 'object' && 'toHexString' in id && typeof id.toHexString === 'function') {
4686
- if (typeof id.id === 'string') {
4687
- return id.id.length === 12;
4688
- }
4689
- return id.toHexString().length === 24 && checkForHexRegExp.test(id.id.toString('hex'));
4784
+ catch (_a) {
4785
+ return false;
4690
4786
  }
4691
- return false;
4692
4787
  };
4693
4788
  /** @internal */
4694
4789
  ObjectId.prototype.toExtendedJSON = function () {
@@ -4713,7 +4808,7 @@ var BSON = (function (exports) {
4713
4808
  return "new ObjectId(\"" + this.toHexString() + "\")";
4714
4809
  };
4715
4810
  /** @internal */
4716
- ObjectId.index = ~~(Math.random() * 0xffffff);
4811
+ ObjectId.index = Math.floor(Math.random() * 0xffffff);
4717
4812
  return ObjectId;
4718
4813
  }());
4719
4814
  // Deprecated methods
@@ -4748,6 +4843,12 @@ var BSON = (function (exports) {
4748
4843
  return new BSONRegExp(pattern, options);
4749
4844
  this.pattern = pattern;
4750
4845
  this.options = alphabetize(options !== null && options !== void 0 ? options : '');
4846
+ if (this.pattern.indexOf('\x00') !== -1) {
4847
+ throw new BSONError("BSON Regex patterns cannot contain null bytes, found: " + JSON.stringify(this.pattern));
4848
+ }
4849
+ if (this.options.indexOf('\x00') !== -1) {
4850
+ throw new BSONError("BSON Regex options cannot contain null bytes, found: " + JSON.stringify(this.options));
4851
+ }
4751
4852
  // Validate options
4752
4853
  for (var i = 0; i < this.options.length; i++) {
4753
4854
  if (!(this.options[i] === 'i' ||
@@ -4756,7 +4857,7 @@ var BSON = (function (exports) {
4756
4857
  this.options[i] === 'l' ||
4757
4858
  this.options[i] === 's' ||
4758
4859
  this.options[i] === 'u')) {
4759
- throw new Error("The regular expression option [" + this.options[i] + "] is not supported");
4860
+ throw new BSONError("The regular expression option [" + this.options[i] + "] is not supported");
4760
4861
  }
4761
4862
  }
4762
4863
  }
@@ -4787,7 +4888,7 @@ var BSON = (function (exports) {
4787
4888
  if ('$regularExpression' in doc) {
4788
4889
  return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options));
4789
4890
  }
4790
- throw new TypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc));
4891
+ throw new BSONTypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc));
4791
4892
  };
4792
4893
  return BSONRegExp;
4793
4894
  }());
@@ -4836,46 +4937,6 @@ var BSON = (function (exports) {
4836
4937
  }());
4837
4938
  Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' });
4838
4939
 
4839
- /*! *****************************************************************************
4840
- Copyright (c) Microsoft Corporation.
4841
-
4842
- Permission to use, copy, modify, and/or distribute this software for any
4843
- purpose with or without fee is hereby granted.
4844
-
4845
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
4846
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
4847
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
4848
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
4849
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4850
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4851
- PERFORMANCE OF THIS SOFTWARE.
4852
- ***************************************************************************** */
4853
-
4854
- /* global Reflect, Promise */
4855
- var _extendStatics = function extendStatics(d, b) {
4856
- _extendStatics = Object.setPrototypeOf || {
4857
- __proto__: []
4858
- } instanceof Array && function (d, b) {
4859
- d.__proto__ = b;
4860
- } || function (d, b) {
4861
- for (var p in b) {
4862
- if (b.hasOwnProperty(p)) d[p] = b[p];
4863
- }
4864
- };
4865
-
4866
- return _extendStatics(d, b);
4867
- };
4868
-
4869
- function __extends(d, b) {
4870
- _extendStatics(d, b);
4871
-
4872
- function __() {
4873
- this.constructor = d;
4874
- }
4875
-
4876
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
4877
- }
4878
-
4879
4940
  /** @public */
4880
4941
  var LongWithoutOverridesClass = Long;
4881
4942
  /** @public */
@@ -5090,7 +5151,7 @@ var BSON = (function (exports) {
5090
5151
  var current = props[props.length - 1];
5091
5152
  var leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2);
5092
5153
  var dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1);
5093
- throw new TypeError('Converting circular structure to EJSON:\n' +
5154
+ throw new BSONTypeError('Converting circular structure to EJSON:\n' +
5094
5155
  (" " + leadingPart + alreadySeen + circularPart + current + "\n") +
5095
5156
  (" " + leadingSpace + "\\" + dashes + "/"));
5096
5157
  }
@@ -5163,7 +5224,7 @@ var BSON = (function (exports) {
5163
5224
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
5164
5225
  function serializeDocument(doc, options) {
5165
5226
  if (doc == null || typeof doc !== 'object')
5166
- throw new Error('not an object instance');
5227
+ throw new BSONError('not an object instance');
5167
5228
  var bsontype = doc._bsontype;
5168
5229
  if (typeof bsontype === 'undefined') {
5169
5230
  // It's a regular object. Recursively serialize its property values.
@@ -5190,7 +5251,7 @@ var BSON = (function (exports) {
5190
5251
  // Copy the object into this library's version of that type.
5191
5252
  var mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
5192
5253
  if (!mapper) {
5193
- throw new TypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
5254
+ throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
5194
5255
  }
5195
5256
  outDoc = mapper(outDoc);
5196
5257
  }
@@ -5204,7 +5265,7 @@ var BSON = (function (exports) {
5204
5265
  return outDoc.toExtendedJSON(options);
5205
5266
  }
5206
5267
  else {
5207
- throw new Error('_bsontype must be a string, but was: ' + typeof bsontype);
5268
+ throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype);
5208
5269
  }
5209
5270
  }
5210
5271
  /**
@@ -5239,7 +5300,12 @@ var BSON = (function (exports) {
5239
5300
  finalOptions.strict = !finalOptions.relaxed;
5240
5301
  if (typeof finalOptions.strict === 'boolean')
5241
5302
  finalOptions.relaxed = !finalOptions.strict;
5242
- return JSON.parse(text, function (_key, value) { return deserializeValue(value, finalOptions); });
5303
+ return JSON.parse(text, function (key, value) {
5304
+ if (key.indexOf('\x00') !== -1) {
5305
+ throw new BSONError("BSON Document field names cannot contain null bytes, found: " + JSON.stringify(key));
5306
+ }
5307
+ return deserializeValue(value, finalOptions);
5308
+ });
5243
5309
  }
5244
5310
  EJSON.parse = parse;
5245
5311
  /**
@@ -5497,6 +5563,10 @@ var BSON = (function (exports) {
5497
5563
  var BSON_BINARY_SUBTYPE_UUID_NEW = 4;
5498
5564
  /** Binary MD5 Type @internal */
5499
5565
  var BSON_BINARY_SUBTYPE_MD5 = 5;
5566
+ /** Encrypted BSON type @internal */
5567
+ var BSON_BINARY_SUBTYPE_ENCRYPTED = 6;
5568
+ /** Column BSON type @internal */
5569
+ var BSON_BINARY_SUBTYPE_COLUMN = 7;
5500
5570
  /** Binary User Defined Type @internal */
5501
5571
  var BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
5502
5572
 
@@ -5509,7 +5579,7 @@ var BSON = (function (exports) {
5509
5579
  }
5510
5580
  else {
5511
5581
  // If we have toBSON defined, override the current object
5512
- if (object.toBSON) {
5582
+ if (typeof (object === null || object === void 0 ? void 0 : object.toBSON) === 'function') {
5513
5583
  object = object.toBSON();
5514
5584
  }
5515
5585
  // Calculate size
@@ -5527,7 +5597,7 @@ var BSON = (function (exports) {
5527
5597
  if (isArray === void 0) { isArray = false; }
5528
5598
  if (ignoreUndefined === void 0) { ignoreUndefined = false; }
5529
5599
  // If we have toBSON defined, override the current object
5530
- if (value && value.toBSON) {
5600
+ if (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === 'function') {
5531
5601
  value = value.toBSON();
5532
5602
  }
5533
5603
  switch (typeof value) {
@@ -5741,20 +5811,20 @@ var BSON = (function (exports) {
5741
5811
  (buffer[index + 2] << 16) |
5742
5812
  (buffer[index + 3] << 24);
5743
5813
  if (size < 5) {
5744
- throw new Error("bson size must be >= 5, is " + size);
5814
+ throw new BSONError("bson size must be >= 5, is " + size);
5745
5815
  }
5746
5816
  if (options.allowObjectSmallerThanBufferSize && buffer.length < size) {
5747
- throw new Error("buffer length " + buffer.length + " must be >= bson size " + size);
5817
+ throw new BSONError("buffer length " + buffer.length + " must be >= bson size " + size);
5748
5818
  }
5749
5819
  if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) {
5750
- throw new Error("buffer length " + buffer.length + " must === bson size " + size);
5820
+ throw new BSONError("buffer length " + buffer.length + " must === bson size " + size);
5751
5821
  }
5752
5822
  if (size + index > buffer.byteLength) {
5753
- throw new Error("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")");
5823
+ throw new BSONError("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")");
5754
5824
  }
5755
5825
  // Illegal end value
5756
5826
  if (buffer[index + size - 1] !== 0) {
5757
- throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
5827
+ throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
5758
5828
  }
5759
5829
  // Start deserializtion
5760
5830
  return deserializeObject(buffer, index, options, isArray);
@@ -5773,16 +5843,53 @@ var BSON = (function (exports) {
5773
5843
  var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers'];
5774
5844
  var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs'];
5775
5845
  var promoteValues = options['promoteValues'] == null ? true : options['promoteValues'];
5846
+ // Ensures default validation option if none given
5847
+ var validation = options.validation == null ? { utf8: true } : options.validation;
5848
+ // Shows if global utf-8 validation is enabled or disabled
5849
+ var globalUTFValidation = true;
5850
+ // Reflects utf-8 validation setting regardless of global or specific key validation
5851
+ var validationSetting;
5852
+ // Set of keys either to enable or disable validation on
5853
+ var utf8KeysSet = new Set();
5854
+ // Check for boolean uniformity and empty validation option
5855
+ var utf8ValidatedKeys = validation.utf8;
5856
+ if (typeof utf8ValidatedKeys === 'boolean') {
5857
+ validationSetting = utf8ValidatedKeys;
5858
+ }
5859
+ else {
5860
+ globalUTFValidation = false;
5861
+ var utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) {
5862
+ return utf8ValidatedKeys[key];
5863
+ });
5864
+ if (utf8ValidationValues.length === 0) {
5865
+ throw new BSONError('UTF-8 validation setting cannot be empty');
5866
+ }
5867
+ if (typeof utf8ValidationValues[0] !== 'boolean') {
5868
+ throw new BSONError('Invalid UTF-8 validation option, must specify boolean values');
5869
+ }
5870
+ validationSetting = utf8ValidationValues[0];
5871
+ // Ensures boolean uniformity in utf-8 validation (all true or all false)
5872
+ if (!utf8ValidationValues.every(function (item) { return item === validationSetting; })) {
5873
+ throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false');
5874
+ }
5875
+ }
5876
+ // Add keys to set that will either be validated or not based on validationSetting
5877
+ if (!globalUTFValidation) {
5878
+ for (var _i = 0, _a = Object.keys(utf8ValidatedKeys); _i < _a.length; _i++) {
5879
+ var key = _a[_i];
5880
+ utf8KeysSet.add(key);
5881
+ }
5882
+ }
5776
5883
  // Set the start index
5777
5884
  var startIndex = index;
5778
5885
  // Validate that we have at least 4 bytes of buffer
5779
5886
  if (buffer.length < 5)
5780
- throw new Error('corrupt bson message < 5 bytes long');
5887
+ throw new BSONError('corrupt bson message < 5 bytes long');
5781
5888
  // Read the document size
5782
5889
  var size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
5783
5890
  // Ensure buffer is valid size
5784
5891
  if (size < 5 || size > buffer.length)
5785
- throw new Error('corrupt bson message');
5892
+ throw new BSONError('corrupt bson message');
5786
5893
  // Create holding object
5787
5894
  var object = isArray ? [] : {};
5788
5895
  // Used for arrays to skip having to perform utf8 decoding
@@ -5804,8 +5911,17 @@ var BSON = (function (exports) {
5804
5911
  }
5805
5912
  // If are at the end of the buffer there is a problem with the document
5806
5913
  if (i >= buffer.byteLength)
5807
- throw new Error('Bad BSON Document: illegal CString');
5914
+ throw new BSONError('Bad BSON Document: illegal CString');
5915
+ // Represents the key
5808
5916
  var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i);
5917
+ // shouldValidateKey is true if the key should be validated, false otherwise
5918
+ var shouldValidateKey = true;
5919
+ if (globalUTFValidation || utf8KeysSet.has(name)) {
5920
+ shouldValidateKey = validationSetting;
5921
+ }
5922
+ else {
5923
+ shouldValidateKey = !validationSetting;
5924
+ }
5809
5925
  if (isPossibleDBRef !== false && name[0] === '$') {
5810
5926
  isPossibleDBRef = allowedDBRefKeys.test(name);
5811
5927
  }
@@ -5818,17 +5934,10 @@ var BSON = (function (exports) {
5818
5934
  (buffer[index++] << 24);
5819
5935
  if (stringSize <= 0 ||
5820
5936
  stringSize > buffer.length - index ||
5821
- buffer[index + stringSize - 1] !== 0)
5822
- throw new Error('bad string length in bson');
5823
- value = buffer.toString('utf8', index, index + stringSize - 1);
5824
- for (var i_1 = 0; i_1 < value.length; i_1++) {
5825
- if (value.charCodeAt(i_1) === 0xfffd) {
5826
- if (!validateUtf8(buffer, index, index + stringSize - 1)) {
5827
- throw new Error('Invalid UTF-8 string in BSON document');
5828
- }
5829
- break;
5830
- }
5937
+ buffer[index + stringSize - 1] !== 0) {
5938
+ throw new BSONError('bad string length in bson');
5831
5939
  }
5940
+ value = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
5832
5941
  index = index + stringSize;
5833
5942
  }
5834
5943
  else if (elementType === BSON_DATA_OID) {
@@ -5868,7 +5977,7 @@ var BSON = (function (exports) {
5868
5977
  }
5869
5978
  else if (elementType === BSON_DATA_BOOLEAN) {
5870
5979
  if (buffer[index] !== 0 && buffer[index] !== 1)
5871
- throw new Error('illegal boolean type value');
5980
+ throw new BSONError('illegal boolean type value');
5872
5981
  value = buffer[index++] === 1;
5873
5982
  }
5874
5983
  else if (elementType === BSON_DATA_OBJECT) {
@@ -5878,13 +5987,17 @@ var BSON = (function (exports) {
5878
5987
  (buffer[index + 2] << 16) |
5879
5988
  (buffer[index + 3] << 24);
5880
5989
  if (objectSize <= 0 || objectSize > buffer.length - index)
5881
- throw new Error('bad embedded document length in bson');
5990
+ throw new BSONError('bad embedded document length in bson');
5882
5991
  // We have a raw value
5883
5992
  if (raw) {
5884
5993
  value = buffer.slice(index, index + objectSize);
5885
5994
  }
5886
5995
  else {
5887
- value = deserializeObject(buffer, _index, options, false);
5996
+ var objectOptions = options;
5997
+ if (!globalUTFValidation) {
5998
+ objectOptions = _assign(_assign({}, options), { validation: { utf8: shouldValidateKey } });
5999
+ }
6000
+ value = deserializeObject(buffer, _index, objectOptions, false);
5888
6001
  }
5889
6002
  index = index + objectSize;
5890
6003
  }
@@ -5905,12 +6018,15 @@ var BSON = (function (exports) {
5905
6018
  }
5906
6019
  arrayOptions['raw'] = true;
5907
6020
  }
6021
+ if (!globalUTFValidation) {
6022
+ arrayOptions = _assign(_assign({}, arrayOptions), { validation: { utf8: shouldValidateKey } });
6023
+ }
5908
6024
  value = deserializeObject(buffer, _index, arrayOptions, true);
5909
6025
  index = index + objectSize;
5910
6026
  if (buffer[index - 1] !== 0)
5911
- throw new Error('invalid array terminator byte');
6027
+ throw new BSONError('invalid array terminator byte');
5912
6028
  if (index !== stopIndex)
5913
- throw new Error('corrupted array bson');
6029
+ throw new BSONError('corrupted array bson');
5914
6030
  }
5915
6031
  else if (elementType === BSON_DATA_UNDEFINED) {
5916
6032
  value = undefined;
@@ -5966,10 +6082,10 @@ var BSON = (function (exports) {
5966
6082
  var subType = buffer[index++];
5967
6083
  // Did we have a negative binary size, throw
5968
6084
  if (binarySize < 0)
5969
- throw new Error('Negative binary type element size found');
6085
+ throw new BSONError('Negative binary type element size found');
5970
6086
  // Is the length longer than the document
5971
6087
  if (binarySize > buffer.byteLength)
5972
- throw new Error('Binary type size larger than document size');
6088
+ throw new BSONError('Binary type size larger than document size');
5973
6089
  // Decode as raw Buffer object if options specifies it
5974
6090
  if (buffer['slice'] != null) {
5975
6091
  // If we have subtype 2 skip the 4 bytes for the size
@@ -5980,11 +6096,11 @@ var BSON = (function (exports) {
5980
6096
  (buffer[index++] << 16) |
5981
6097
  (buffer[index++] << 24);
5982
6098
  if (binarySize < 0)
5983
- throw new Error('Negative binary type element size found for subtype 0x02');
6099
+ throw new BSONError('Negative binary type element size found for subtype 0x02');
5984
6100
  if (binarySize > totalBinarySize - 4)
5985
- throw new Error('Binary type with subtype 0x02 contains too long binary size');
6101
+ throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
5986
6102
  if (binarySize < totalBinarySize - 4)
5987
- throw new Error('Binary type with subtype 0x02 contains too short binary size');
6103
+ throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
5988
6104
  }
5989
6105
  if (promoteBuffers && promoteValues) {
5990
6106
  value = buffer.slice(index, index + binarySize);
@@ -6003,11 +6119,11 @@ var BSON = (function (exports) {
6003
6119
  (buffer[index++] << 16) |
6004
6120
  (buffer[index++] << 24);
6005
6121
  if (binarySize < 0)
6006
- throw new Error('Negative binary type element size found for subtype 0x02');
6122
+ throw new BSONError('Negative binary type element size found for subtype 0x02');
6007
6123
  if (binarySize > totalBinarySize - 4)
6008
- throw new Error('Binary type with subtype 0x02 contains too long binary size');
6124
+ throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
6009
6125
  if (binarySize < totalBinarySize - 4)
6010
- throw new Error('Binary type with subtype 0x02 contains too short binary size');
6126
+ throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
6011
6127
  }
6012
6128
  // Copy the data
6013
6129
  for (i = 0; i < binarySize; i++) {
@@ -6032,7 +6148,7 @@ var BSON = (function (exports) {
6032
6148
  }
6033
6149
  // If are at the end of the buffer there is a problem with the document
6034
6150
  if (i >= buffer.length)
6035
- throw new Error('Bad BSON Document: illegal CString');
6151
+ throw new BSONError('Bad BSON Document: illegal CString');
6036
6152
  // Return the C string
6037
6153
  var source = buffer.toString('utf8', index, i);
6038
6154
  // Create the regexp
@@ -6045,7 +6161,7 @@ var BSON = (function (exports) {
6045
6161
  }
6046
6162
  // If are at the end of the buffer there is a problem with the document
6047
6163
  if (i >= buffer.length)
6048
- throw new Error('Bad BSON Document: illegal CString');
6164
+ throw new BSONError('Bad BSON Document: illegal CString');
6049
6165
  // Return the C string
6050
6166
  var regExpOptions = buffer.toString('utf8', index, i);
6051
6167
  index = i + 1;
@@ -6076,7 +6192,7 @@ var BSON = (function (exports) {
6076
6192
  }
6077
6193
  // If are at the end of the buffer there is a problem with the document
6078
6194
  if (i >= buffer.length)
6079
- throw new Error('Bad BSON Document: illegal CString');
6195
+ throw new BSONError('Bad BSON Document: illegal CString');
6080
6196
  // Return the C string
6081
6197
  var source = buffer.toString('utf8', index, i);
6082
6198
  index = i + 1;
@@ -6088,7 +6204,7 @@ var BSON = (function (exports) {
6088
6204
  }
6089
6205
  // If are at the end of the buffer there is a problem with the document
6090
6206
  if (i >= buffer.length)
6091
- throw new Error('Bad BSON Document: illegal CString');
6207
+ throw new BSONError('Bad BSON Document: illegal CString');
6092
6208
  // Return the C string
6093
6209
  var regExpOptions = buffer.toString('utf8', index, i);
6094
6210
  index = i + 1;
@@ -6102,9 +6218,10 @@ var BSON = (function (exports) {
6102
6218
  (buffer[index++] << 24);
6103
6219
  if (stringSize <= 0 ||
6104
6220
  stringSize > buffer.length - index ||
6105
- buffer[index + stringSize - 1] !== 0)
6106
- throw new Error('bad string length in bson');
6107
- var symbol = buffer.toString('utf8', index, index + stringSize - 1);
6221
+ buffer[index + stringSize - 1] !== 0) {
6222
+ throw new BSONError('bad string length in bson');
6223
+ }
6224
+ var symbol = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
6108
6225
  value = promoteValues ? symbol : new BSONSymbol(symbol);
6109
6226
  index = index + stringSize;
6110
6227
  }
@@ -6132,9 +6249,10 @@ var BSON = (function (exports) {
6132
6249
  (buffer[index++] << 24);
6133
6250
  if (stringSize <= 0 ||
6134
6251
  stringSize > buffer.length - index ||
6135
- buffer[index + stringSize - 1] !== 0)
6136
- throw new Error('bad string length in bson');
6137
- var functionString = buffer.toString('utf8', index, index + stringSize - 1);
6252
+ buffer[index + stringSize - 1] !== 0) {
6253
+ throw new BSONError('bad string length in bson');
6254
+ }
6255
+ var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
6138
6256
  // If we are evaluating the functions
6139
6257
  if (evalFunctions) {
6140
6258
  // If we have cache enabled let's look for the md5 of the function in the cache
@@ -6159,7 +6277,7 @@ var BSON = (function (exports) {
6159
6277
  (buffer[index++] << 24);
6160
6278
  // Element cannot be shorter than totalSize + stringSize + documentSize + terminator
6161
6279
  if (totalSize < 4 + 4 + 4 + 1) {
6162
- throw new Error('code_w_scope total size shorter minimum expected length');
6280
+ throw new BSONError('code_w_scope total size shorter minimum expected length');
6163
6281
  }
6164
6282
  // Get the code string size
6165
6283
  var stringSize = buffer[index++] |
@@ -6169,10 +6287,11 @@ var BSON = (function (exports) {
6169
6287
  // Check if we have a valid string
6170
6288
  if (stringSize <= 0 ||
6171
6289
  stringSize > buffer.length - index ||
6172
- buffer[index + stringSize - 1] !== 0)
6173
- throw new Error('bad string length in bson');
6290
+ buffer[index + stringSize - 1] !== 0) {
6291
+ throw new BSONError('bad string length in bson');
6292
+ }
6174
6293
  // Javascript function
6175
- var functionString = buffer.toString('utf8', index, index + stringSize - 1);
6294
+ var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
6176
6295
  // Update parse index position
6177
6296
  index = index + stringSize;
6178
6297
  // Parse the element
@@ -6188,11 +6307,11 @@ var BSON = (function (exports) {
6188
6307
  index = index + objectSize;
6189
6308
  // Check if field length is too short
6190
6309
  if (totalSize < 4 + 4 + objectSize + stringSize) {
6191
- throw new Error('code_w_scope total size is too short, truncating scope');
6310
+ throw new BSONError('code_w_scope total size is too short, truncating scope');
6192
6311
  }
6193
6312
  // Check if totalSize field is too long
6194
6313
  if (totalSize > 4 + 4 + objectSize + stringSize) {
6195
- throw new Error('code_w_scope total size is too long, clips outer document');
6314
+ throw new BSONError('code_w_scope total size is too long, clips outer document');
6196
6315
  }
6197
6316
  // If we are evaluating the functions
6198
6317
  if (evalFunctions) {
@@ -6220,10 +6339,12 @@ var BSON = (function (exports) {
6220
6339
  if (stringSize <= 0 ||
6221
6340
  stringSize > buffer.length - index ||
6222
6341
  buffer[index + stringSize - 1] !== 0)
6223
- throw new Error('bad string length in bson');
6342
+ throw new BSONError('bad string length in bson');
6224
6343
  // Namespace
6225
- if (!validateUtf8(buffer, index, index + stringSize - 1)) {
6226
- throw new Error('Invalid UTF-8 string in BSON document');
6344
+ if (validation != null && validation.utf8) {
6345
+ if (!validateUtf8(buffer, index, index + stringSize - 1)) {
6346
+ throw new BSONError('Invalid UTF-8 string in BSON document');
6347
+ }
6227
6348
  }
6228
6349
  var namespace = buffer.toString('utf8', index, index + stringSize - 1);
6229
6350
  // Update parse index position
@@ -6238,7 +6359,7 @@ var BSON = (function (exports) {
6238
6359
  value = new DBRef(namespace, oid);
6239
6360
  }
6240
6361
  else {
6241
- throw new Error('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"');
6362
+ throw new BSONError('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"');
6242
6363
  }
6243
6364
  if (name === '__proto__') {
6244
6365
  Object.defineProperty(object, name, {
@@ -6255,8 +6376,8 @@ var BSON = (function (exports) {
6255
6376
  // Check if the deserialization was against a valid array/object
6256
6377
  if (size !== index - startIndex) {
6257
6378
  if (isArray)
6258
- throw new Error('corrupt array bson');
6259
- throw new Error('corrupt object bson');
6379
+ throw new BSONError('corrupt array bson');
6380
+ throw new BSONError('corrupt object bson');
6260
6381
  }
6261
6382
  // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef
6262
6383
  if (!isPossibleDBRef)
@@ -6285,6 +6406,21 @@ var BSON = (function (exports) {
6285
6406
  // Set the object
6286
6407
  return functionCache[functionString].bind(object);
6287
6408
  }
6409
+ function getValidatedString(buffer, start, end, shouldValidateUtf8) {
6410
+ var value = buffer.toString('utf8', start, end);
6411
+ // if utf8 validation is on, do the check
6412
+ if (shouldValidateUtf8) {
6413
+ for (var i = 0; i < value.length; i++) {
6414
+ if (value.charCodeAt(i) === 0xfffd) {
6415
+ if (!validateUtf8(buffer, start, end)) {
6416
+ throw new BSONError('Invalid UTF-8 string in BSON document');
6417
+ }
6418
+ break;
6419
+ }
6420
+ }
6421
+ }
6422
+ return value;
6423
+ }
6288
6424
 
6289
6425
  // Copyright (c) 2008, Fair Oaks Labs, Inc.
6290
6426
  function writeIEEE754(buffer, value, offset, endian, mLen, nBytes) {
@@ -6569,7 +6705,7 @@ var BSON = (function (exports) {
6569
6705
  buffer.set(value.id.subarray(0, 12), index);
6570
6706
  }
6571
6707
  else {
6572
- throw new TypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId');
6708
+ throw new BSONTypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId');
6573
6709
  }
6574
6710
  // Adjust index
6575
6711
  return index + 12;
@@ -6608,7 +6744,7 @@ var BSON = (function (exports) {
6608
6744
  if (path === void 0) { path = []; }
6609
6745
  for (var i = 0; i < path.length; i++) {
6610
6746
  if (path[i] === value)
6611
- throw new Error('cyclic dependency detected');
6747
+ throw new BSONError('cyclic dependency detected');
6612
6748
  }
6613
6749
  // Push value to stack
6614
6750
  path.push(value);
@@ -6909,9 +7045,7 @@ var BSON = (function (exports) {
6909
7045
  var key = '' + i;
6910
7046
  var value = object[i];
6911
7047
  // Is there an override value
6912
- if (value && value.toBSON) {
6913
- if (typeof value.toBSON !== 'function')
6914
- throw new TypeError('toBSON is not a function');
7048
+ if (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === 'function') {
6915
7049
  value = value.toBSON();
6916
7050
  }
6917
7051
  if (typeof value === 'string') {
@@ -6921,7 +7055,7 @@ var BSON = (function (exports) {
6921
7055
  index = serializeNumber(buffer, key, value, index, true);
6922
7056
  }
6923
7057
  else if (typeof value === 'bigint') {
6924
- throw new TypeError('Unsupported type BigInt, please use Decimal128');
7058
+ throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
6925
7059
  }
6926
7060
  else if (typeof value === 'boolean') {
6927
7061
  index = serializeBoolean(buffer, key, value, index, true);
@@ -6983,7 +7117,7 @@ var BSON = (function (exports) {
6983
7117
  index = serializeMinMax(buffer, key, value, index, true);
6984
7118
  }
6985
7119
  else if (typeof value['_bsontype'] !== 'undefined') {
6986
- throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
7120
+ throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
6987
7121
  }
6988
7122
  }
6989
7123
  }
@@ -7025,7 +7159,7 @@ var BSON = (function (exports) {
7025
7159
  index = serializeNumber(buffer, key, value, index);
7026
7160
  }
7027
7161
  else if (type === 'bigint' || isBigInt64Array(value) || isBigUInt64Array(value)) {
7028
- throw new TypeError('Unsupported type BigInt, please use Decimal128');
7162
+ throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
7029
7163
  }
7030
7164
  else if (type === 'boolean') {
7031
7165
  index = serializeBoolean(buffer, key, value, index);
@@ -7082,26 +7216,23 @@ var BSON = (function (exports) {
7082
7216
  index = serializeMinMax(buffer, key, value, index);
7083
7217
  }
7084
7218
  else if (typeof value['_bsontype'] !== 'undefined') {
7085
- throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
7219
+ throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
7086
7220
  }
7087
7221
  }
7088
7222
  }
7089
7223
  else {
7090
- // Did we provide a custom serialization method
7091
- if (object.toBSON) {
7092
- if (typeof object.toBSON !== 'function')
7093
- throw new TypeError('toBSON is not a function');
7224
+ if (typeof (object === null || object === void 0 ? void 0 : object.toBSON) === 'function') {
7225
+ // Provided a custom serialization method
7094
7226
  object = object.toBSON();
7095
- if (object != null && typeof object !== 'object')
7096
- throw new TypeError('toBSON function did not return an object');
7227
+ if (object != null && typeof object !== 'object') {
7228
+ throw new BSONTypeError('toBSON function did not return an object');
7229
+ }
7097
7230
  }
7098
7231
  // Iterate over all the keys
7099
7232
  for (var key in object) {
7100
7233
  var value = object[key];
7101
7234
  // Is there an override value
7102
- if (value && value.toBSON) {
7103
- if (typeof value.toBSON !== 'function')
7104
- throw new TypeError('toBSON is not a function');
7235
+ if (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === 'function') {
7105
7236
  value = value.toBSON();
7106
7237
  }
7107
7238
  // Check the type of the value
@@ -7129,7 +7260,7 @@ var BSON = (function (exports) {
7129
7260
  index = serializeNumber(buffer, key, value, index);
7130
7261
  }
7131
7262
  else if (type === 'bigint') {
7132
- throw new TypeError('Unsupported type BigInt, please use Decimal128');
7263
+ throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
7133
7264
  }
7134
7265
  else if (type === 'boolean') {
7135
7266
  index = serializeBoolean(buffer, key, value, index);
@@ -7190,7 +7321,7 @@ var BSON = (function (exports) {
7190
7321
  index = serializeMinMax(buffer, key, value, index);
7191
7322
  }
7192
7323
  else if (typeof value['_bsontype'] !== 'undefined') {
7193
- throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
7324
+ throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
7194
7325
  }
7195
7326
  }
7196
7327
  }
@@ -7363,13 +7494,19 @@ var BSON = (function (exports) {
7363
7494
  serializeWithBufferAndIndex: serializeWithBufferAndIndex,
7364
7495
  deserialize: deserialize,
7365
7496
  calculateObjectSize: calculateObjectSize,
7366
- deserializeStream: deserializeStream
7497
+ deserializeStream: deserializeStream,
7498
+ BSONError: BSONError,
7499
+ BSONTypeError: BSONTypeError
7367
7500
  };
7368
7501
 
7502
+ exports.BSONError = BSONError;
7369
7503
  exports.BSONRegExp = BSONRegExp;
7370
7504
  exports.BSONSymbol = BSONSymbol;
7505
+ exports.BSONTypeError = BSONTypeError;
7371
7506
  exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = BSON_BINARY_SUBTYPE_BYTE_ARRAY;
7507
+ exports.BSON_BINARY_SUBTYPE_COLUMN = BSON_BINARY_SUBTYPE_COLUMN;
7372
7508
  exports.BSON_BINARY_SUBTYPE_DEFAULT = BSON_BINARY_SUBTYPE_DEFAULT;
7509
+ exports.BSON_BINARY_SUBTYPE_ENCRYPTED = BSON_BINARY_SUBTYPE_ENCRYPTED;
7373
7510
  exports.BSON_BINARY_SUBTYPE_FUNCTION = BSON_BINARY_SUBTYPE_FUNCTION;
7374
7511
  exports.BSON_BINARY_SUBTYPE_MD5 = BSON_BINARY_SUBTYPE_MD5;
7375
7512
  exports.BSON_BINARY_SUBTYPE_USER_DEFINED = BSON_BINARY_SUBTYPE_USER_DEFINED;