regexp.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.BSONRegExp = void 0;
  4. function alphabetize(str) {
  5. return str.split('').sort().join('');
  6. }
  7. /**
  8. * A class representation of the BSON RegExp type.
  9. * @public
  10. */
  11. var BSONRegExp = /** @class */ (function () {
  12. /**
  13. * @param pattern - The regular expression pattern to match
  14. * @param options - The regular expression options
  15. */
  16. function BSONRegExp(pattern, options) {
  17. if (!(this instanceof BSONRegExp))
  18. return new BSONRegExp(pattern, options);
  19. this.pattern = pattern;
  20. this.options = alphabetize(options !== null && options !== void 0 ? options : '');
  21. // Validate options
  22. for (var i = 0; i < this.options.length; i++) {
  23. if (!(this.options[i] === 'i' ||
  24. this.options[i] === 'm' ||
  25. this.options[i] === 'x' ||
  26. this.options[i] === 'l' ||
  27. this.options[i] === 's' ||
  28. this.options[i] === 'u')) {
  29. throw new Error("The regular expression option [" + this.options[i] + "] is not supported");
  30. }
  31. }
  32. }
  33. BSONRegExp.parseOptions = function (options) {
  34. return options ? options.split('').sort().join('') : '';
  35. };
  36. /** @internal */
  37. BSONRegExp.prototype.toExtendedJSON = function (options) {
  38. options = options || {};
  39. if (options.legacy) {
  40. return { $regex: this.pattern, $options: this.options };
  41. }
  42. return { $regularExpression: { pattern: this.pattern, options: this.options } };
  43. };
  44. /** @internal */
  45. BSONRegExp.fromExtendedJSON = function (doc) {
  46. if ('$regex' in doc) {
  47. if (typeof doc.$regex !== 'string') {
  48. // This is for $regex query operators that have extended json values.
  49. if (doc.$regex._bsontype === 'BSONRegExp') {
  50. return doc;
  51. }
  52. }
  53. else {
  54. return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options));
  55. }
  56. }
  57. if ('$regularExpression' in doc) {
  58. return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options));
  59. }
  60. throw new TypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc));
  61. };
  62. return BSONRegExp;
  63. }());
  64. exports.BSONRegExp = BSONRegExp;
  65. Object.defineProperty(BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' });
  66. //# sourceMappingURL=regexp.js.map