UNPKG

bson

Version:

A bson parser for node.js and the browser

1,514 lines (1,371 loc) 264 kB
import buffer from 'buffer'; var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function unwrapExports (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var require$$0 = {}; // shim for using process in browser var performance = global.performance || {}; performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function () { return new Date().getTime(); }; // generate timestamp or delta var inherits; if (typeof Object.create === 'function') { inherits = function inherits(ctor, superCtor) { // implementation from standard node.js 'util' module ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { inherits = function inherits(ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function TempCtor() {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; }; } var inherits$1 = inherits; // Copyright Joyent, Inc. and other Node contributors. var formatRegExp = /%[sdj%]/g; function format(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function (x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; } // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. function deprecate(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function () { return deprecate(fn, msg).apply(this, arguments); }; } var warned = false; function deprecated() { if (!warned) { { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; } var debugs = {}; var debugEnviron; function debuglog(set) { if (isUndefined(debugEnviron)) debugEnviron = ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = 0; debugs[set] = function () { var msg = format.apply(null, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function () {}; } } return debugs[set]; } /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object _extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold': [1, 22], 'italic': [3, 23], 'underline': [4, 24], 'inverse': [7, 27], 'white': [37, 39], 'grey': [90, 39], 'black': [30, 39], 'blue': [34, 39], 'cyan': [36, 39], 'green': [32, 39], 'magenta': [35, 39], 'red': [31, 39], 'yellow': [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return "\x1B[" + inspect.colors[style][0] + 'm' + str + "\x1B[" + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function (val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function (key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '').replace(/'/g, "\\'").replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function (key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function (line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function (line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var length = output.reduce(function (prev, cur) { if (cur.indexOf('\n') >= 0) ; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } function isBoolean(arg) { return typeof arg === 'boolean'; } function isNull(arg) { return arg === null; } function isNullOrUndefined(arg) { return arg == null; } function isNumber(arg) { return typeof arg === 'number'; } function isString(arg) { return typeof arg === 'string'; } function isSymbol(arg) { return babelHelpers["typeof"](arg) === 'symbol'; } function isUndefined(arg) { return arg === void 0; } function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } function isObject(arg) { return babelHelpers["typeof"](arg) === 'object' && arg !== null; } function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } function isFunction(arg) { return typeof arg === 'function'; } function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || babelHelpers["typeof"](arg) === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } function isBuffer(maybeBuf) { return Buffer.isBuffer(maybeBuf); } function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp$1() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp function log() { console.log('%s - %s', timestamp$1(), format.apply(null, arguments)); } function _extend(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; } function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } var require$$1 = { inherits: inherits$1, _extend: _extend, log: log, isBuffer: isBuffer, isPrimitive: isPrimitive, isFunction: isFunction, isError: isError, isDate: isDate, isObject: isObject, isRegExp: isRegExp, isUndefined: isUndefined, isSymbol: isSymbol, isString: isString, isNumber: isNumber, isNullOrUndefined: isNullOrUndefined, isNull: isNull, isBoolean: isBoolean, isArray: isArray, inspect: inspect, deprecate: deprecate, format: format, debuglog: debuglog }; var utils = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.deprecate = exports.isObjectLike = exports.isDate = exports.haveBuffer = exports.isMap = exports.isRegExp = exports.isBigUInt64Array = exports.isBigInt64Array = exports.isUint8Array = exports.isAnyArrayBuffer = exports.randomBytes = exports.normalizedFunctionString = void 0; /** * Normalizes our expected stringified form of a function across versions of node * @param fn - The function to stringify */ function normalizedFunctionString(fn) { return fn.toString().replace('function(', 'function ('); } exports.normalizedFunctionString = normalizedFunctionString; var isReactNative = typeof commonjsGlobal.navigator === 'object' && commonjsGlobal.navigator.product === 'ReactNative'; var insecureWarning = isReactNative ? 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.' : 'BSON: No cryptographic implementation for random bytes present, falling back to a less secure implementation.'; var insecureRandomBytes = function insecureRandomBytes(size) { console.warn(insecureWarning); var result = buffer.Buffer.alloc(size); for (var i = 0; i < size; ++i) result[i] = Math.floor(Math.random() * 256); return result; }; var detectRandomBytes = function () { if (typeof window !== 'undefined') { // browser crypto implementation(s) var target_1 = window.crypto || window.msCrypto; // allow for IE11 if (target_1 && target_1.getRandomValues) { return function (size) { return target_1.getRandomValues(buffer.Buffer.alloc(size)); }; } } if (typeof commonjsGlobal !== 'undefined' && commonjsGlobal.crypto && commonjsGlobal.crypto.getRandomValues) { // allow for RN packages such as https://www.npmjs.com/package/react-native-get-random-values to populate global return function (size) { return commonjsGlobal.crypto.getRandomValues(buffer.Buffer.alloc(size)); }; } var requiredRandomBytes; try { // eslint-disable-next-line @typescript-eslint/no-var-requires requiredRandomBytes = require$$0.randomBytes; } catch (e) { // keep the fallback } // NOTE: in transpiled cases the above require might return null/undefined return requiredRandomBytes || insecureRandomBytes; }; exports.randomBytes = detectRandomBytes(); function isAnyArrayBuffer(value) { return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); } exports.isAnyArrayBuffer = isAnyArrayBuffer; function isUint8Array(value) { return Object.prototype.toString.call(value) === '[object Uint8Array]'; } exports.isUint8Array = isUint8Array; function isBigInt64Array(value) { return Object.prototype.toString.call(value) === '[object BigInt64Array]'; } exports.isBigInt64Array = isBigInt64Array; function isBigUInt64Array(value) { return Object.prototype.toString.call(value) === '[object BigUint64Array]'; } exports.isBigUInt64Array = isBigUInt64Array; function isRegExp(d) { return Object.prototype.toString.call(d) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isMap(d) { return Object.prototype.toString.call(d) === '[object Map]'; } exports.isMap = isMap; /** Call to check if your environment has `Buffer` */ function haveBuffer() { return typeof commonjsGlobal !== 'undefined' && typeof commonjsGlobal.Buffer !== 'undefined'; } exports.haveBuffer = haveBuffer; // To ensure that 0.4 of node works correctly function isDate(d) { return isObjectLike(d) && Object.prototype.toString.call(d) === '[object Date]'; } exports.isDate = isDate; /** * @internal * this is to solve the `'someKey' in x` problem where x is unknown. * https://github.com/typescript-eslint/typescript-eslint/issues/1071#issuecomment-541955753 */ function isObjectLike(candidate) { return typeof candidate === 'object' && candidate !== null; } exports.isObjectLike = isObjectLike; function deprecate(fn, message) { if (typeof window === 'undefined' && typeof self === 'undefined') { // eslint-disable-next-line @typescript-eslint/no-var-requires return require$$1.deprecate(fn, message); } var warned = false; function deprecated() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (!warned) { console.warn(message); warned = true; } return fn.apply(this, args); } return deprecated; } exports.deprecate = deprecate; }); unwrapExports(utils); utils.deprecate; utils.isObjectLike; utils.isDate; utils.haveBuffer; utils.isMap; utils.isRegExp; utils.isBigUInt64Array; utils.isBigInt64Array; utils.isUint8Array; utils.isAnyArrayBuffer; utils.randomBytes; utils.normalizedFunctionString; var ensure_buffer = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.ensureBuffer = void 0; /** * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer. * * @param potentialBuffer - The potential buffer * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that * wraps a passed in Uint8Array * @throws TypeError If anything other than a Buffer or Uint8Array is passed in */ function ensureBuffer(potentialBuffer) { if (ArrayBuffer.isView(potentialBuffer)) { return buffer.Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); } if (utils.isAnyArrayBuffer(potentialBuffer)) { return buffer.Buffer.from(potentialBuffer); } throw new TypeError('Must use either Buffer or TypedArray'); } exports.ensureBuffer = ensureBuffer; }); unwrapExports(ensure_buffer); ensure_buffer.ensureBuffer; var uuid_utils = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.bufferToUuidHexString = exports.uuidHexStringToBuffer = exports.uuidValidateString = void 0; // Validation regex for v4 uuid (validates with or without dashes) var VALIDATION_REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i; var uuidValidateString = function (str) { return typeof str === 'string' && VALIDATION_REGEX.test(str); }; exports.uuidValidateString = uuidValidateString; var uuidHexStringToBuffer = function (hexString) { if (!exports.uuidValidateString(hexString)) { 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".'); } var sanitizedHexString = hexString.replace(/-/g, ''); return buffer.Buffer.from(sanitizedHexString, 'hex'); }; exports.uuidHexStringToBuffer = uuidHexStringToBuffer; var bufferToUuidHexString = function (buffer, includeDashes) { if (includeDashes === void 0) { includeDashes = true; } return includeDashes ? buffer.toString('hex', 0, 4) + '-' + buffer.toString('hex', 4, 6) + '-' + buffer.toString('hex', 6, 8) + '-' + buffer.toString('hex', 8, 10) + '-' + buffer.toString('hex', 10, 16) : buffer.toString('hex'); }; exports.bufferToUuidHexString = bufferToUuidHexString; }); unwrapExports(uuid_utils); uuid_utils.bufferToUuidHexString; uuid_utils.uuidHexStringToBuffer; uuid_utils.uuidValidateString; var uuid = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.UUID = void 0; var BYTE_LENGTH = 16; var kId = Symbol('id'); /** * A class representation of the BSON UUID type. * @public */ var UUID = /** @class */ (function () { /** * Create an UUID type * * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer. */ function UUID(input) { if (typeof input === 'undefined') { // The most common use case (blank id, new UUID() instance) this.id = UUID.generate(); } else if (input instanceof UUID) { this[kId] = buffer.Buffer.from(input.id); this.__id = input.__id; } else if (ArrayBuffer.isView(input) && input.byteLength === BYTE_LENGTH) { this.id = ensure_buffer.ensureBuffer(input); } else if (typeof input === 'string') { this.id = uuid_utils.uuidHexStringToBuffer(input); } else { 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).'); } } Object.defineProperty(UUID.prototype, "id", { /** * The UUID bytes * @readonly */ get: function () { return this[kId]; }, set: function (value) { this[kId] = value; if (UUID.cacheHexString) { this.__id = uuid_utils.bufferToUuidHexString(value); } }, enumerable: false, configurable: true }); /** * Generate a 16 byte uuid v4 buffer used in UUIDs */ /** * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated) * @param includeDashes - should the string exclude dash-separators. * */ UUID.prototype.toHexString = function (includeDashes) { if (includeDashes === void 0) { includeDashes = true; } if (UUID.cacheHexString && this.__id) { return this.__id; } var uuidHexString = uuid_utils.bufferToUuidHexString(this.id, includeDashes); if (UUID.cacheHexString) { this.__id = uuidHexString; } return uuidHexString; }; /** * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified. * @internal */ UUID.prototype.toString = function (encoding) { return encoding ? this.id.toString(encoding) : this.toHexString(); }; /** * Converts the id into its JSON string representation. A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx * @internal */ UUID.prototype.toJSON = function () { return this.toHexString(); }; /** * Compares the equality of this UUID with `otherID`. * * @param otherId - UUID instance to compare against. */ UUID.prototype.equals = function (otherId) { if (!otherId) { return false; } if (otherId instanceof UUID) { return otherId.id.equals(this.id); } try { return new UUID(otherId).id.equals(this.id); } catch (_a) { return false; } }; /** * Creates a Binary instance from the current UUID. */ UUID.prototype.toBinary = function () { return new binary.Binary(this.id, binary.Binary.SUBTYPE_UUID); }; /** * Generates a populated buffer containing a v4 uuid */ UUID.generate = function () { var bytes = utils.randomBytes(BYTE_LENGTH); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` // Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js bytes[6] = (bytes[6] & 0x0f) | 0x40; bytes[8] = (bytes[8] & 0x3f) | 0x80; return buffer.Buffer.from(bytes); }; /** * Checks if a value is a valid bson UUID * @param input - UUID, string or Buffer to validate. */ UUID.isValid = function (input) { if (!input) { return false; } if (input instanceof UUID) { return true; } if (typeof input === 'string') { return uuid_utils.uuidValidateString(input); } if (utils.isUint8Array(input)) { // check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3) if (input.length !== BYTE_LENGTH) { return false; } try { // get this byte as hex: xxxxxxxx-xxxx-XXxx-xxxx-xxxxxxxxxxxx // check first part as uuid version: xxxxxxxx-xxxx-Xxxx-xxxx-xxxxxxxxxxxx return parseInt(input[6].toString(16)[0], 10) === binary.Binary.SUBTYPE_UUID; } catch (_a) { return false; } } return false; }; /** * Creates an UUID from a hex string representation of an UUID. * @param hexString - 32 or 36 character hex string (dashes excluded/included). */ UUID.createFromHexString = function (hexString) { var buffer = uuid_utils.uuidHexStringToBuffer(hexString); return new UUID(buffer); }; /** * Converts to a string representation of this Id. * * @returns return the 36 character hex string representation. * @internal */ UUID.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { return this.inspect(); }; UUID.prototype.inspect = function () { return "new UUID(\"" + this.toHexString() + "\")"; }; return UUID; }()); exports.UUID = UUID; Object.defineProperty(UUID.prototype, '_bsontype', { value: 'UUID' }); }); unwrapExports(uuid); uuid.UUID; var binary = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.Binary = void 0; /** * A class representation of the BSON Binary type. * @public */ var Binary = /** @class */ (function () { /** * @param buffer - a buffer object containing the binary data. * @param subType - the option binary type. */ function Binary(buffer$1, subType) { if (!(this instanceof Binary)) return new Binary(buffer$1, subType); if (!(buffer$1 == null) && !(typeof buffer$1 === 'string') && !ArrayBuffer.isView(buffer$1) && !(buffer$1 instanceof ArrayBuffer) && !Array.isArray(buffer$1)) { throw new TypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array<number>'); } this.sub_type = subType !== null && subType !== void 0 ? subType : Binary.BSON_BINARY_SUBTYPE_DEFAULT; if (buffer$1 == null) { // create an empty binary buffer this.buffer = buffer.Buffer.alloc(Binary.BUFFER_SIZE); this.position = 0; } else { if (typeof buffer$1 === 'string') { // string this.buffer = buffer.Buffer.from(buffer$1, 'binary'); } else if (Array.isArray(buffer$1)) { // number[] this.buffer = buffer.Buffer.from(buffer$1); } else { // Buffer | TypedArray | ArrayBuffer this.buffer = ensure_buffer.ensureBuffer(buffer$1); } this.position = this.buffer.byteLength; } } /** * Updates this binary with byte_value. * * @param byteValue - a single byte we wish to write. */ Binary.prototype.put = function (byteValue) { // If it's a string and a has more than one character throw an error if (typeof byteValue === 'string' && byteValue.length !== 1) { throw new TypeError('only accepts single character String'); } else if (typeof byteValue !== 'number' && byteValue.length !== 1) throw new TypeError('only accepts single character Uint8Array or Array'); // Decode the byte value once var decodedByte; if (typeof byteValue === 'string') { decodedByte = byteValue.charCodeAt(0); } else if (typeof byteValue === 'number') { decodedByte = byteValue; } else { decodedByte = byteValue[0]; } if (decodedByte < 0 || decodedByte > 255) { throw new TypeError('only accepts number in a valid unsigned byte range 0-255'); } if (this.buffer.length > this.position) { this.buffer[this.position++] = decodedByte; } else { var buffer$1 = buffer.Buffer.alloc(Binary.BUFFER_SIZE + this.buffer.length); // Combine the two buffers together this.buffer.copy(buffer$1, 0, 0, this.buffer.length); this.buffer = buffer$1; this.buffer[this.position++] = decodedByte; } }; /** * Writes a buffer or string to the binary. * * @param sequence - a string or buffer to be written to the Binary BSON object. * @param offset - specify the binary of where to write the content. */ Binary.prototype.write = function (sequence, offset) { offset = typeof offset === 'number' ? offset : this.position; // If the buffer is to small let's extend the buffer if (this.buffer.length < offset + sequence.length) { var buffer$1 = buffer.Buffer.alloc(this.buffer.length + sequence.length); this.buffer.copy(buffer$1, 0, 0, this.buffer.length); // Assign the new buffer this.buffer = buffer$1; } if (ArrayBuffer.isView(sequence)) { this.buffer.set(ensure_buffer.ensureBuffer(sequence), offset); this.position = offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; } else if (typeof sequence === 'string') { this.buffer.write(sequence, offset, sequence.length, 'binary'); this.position = offset + sequence.length > this.position ? offset + sequence.length : this.position; } }; /** * Reads **length** bytes starting at **position**. * * @param position - read from the given position in the Binary. * @param length - the number of bytes to read. */ Binary.prototype.read = function (position, length) { length = length && length > 0 ? length : this.position; // Let's return the data based on the type we have return this.buffer.slice(position, position + length); }; /** * Returns the value of this binary as a string. * @param asRaw - Will skip converting to a string * @remarks * This is handy when calling this function conditionally for some key value pairs and not others */ Binary.prototype.value = function (asRaw) { asRaw = !!asRaw; // Optimize to serialize for the situation where the data == size of buffer if (asRaw && this.buffer.length === this.position) { return this.buffer; } // If it's a node.js buffer object if (asRaw) { return this.buffer.slice(0, this.position); } return this.buffer.toString('binary', 0, this.position); }; /** the length of the binary sequence */ Binary.prototype.length = function () { return this.position; }; /** @internal */ Binary.prototype.toJSON = function () { return this.buffer.toString('base64'); }; /** @internal */ Binary.prototype.toString = function (format) { return this.buffer.toString(format); }; /** @internal */ Binary.prototype.toExtendedJSON = function (options) { options = options || {}; var base64String = this.buffer.toString('base64'); var subType = Number(this.sub_type).toString(16); if (options.legacy) { return { $binary: base64String, $type: subType.length === 1 ? '0' + subType : subType }; } return { $binary: { base64: base64String, subType: subType.length === 1 ? '0' + subType : subType } }; }; /** @internal */ Binary.prototype.toUUID = function () { if (this.sub_type === Binary.SUBTYPE_UUID) { return new uuid.UUID(this.buffer.slice(0, this.position)); } throw new Error("Binary sub_type \"" + this.sub_type + "\" is not supported for converting to UUID. Only \"" + Binary.SUBTYPE_UUID + "\" is currently supported."); }; /** @internal */ Binary.fromExtendedJSON = function (doc, options) { options = options || {}; var data; var type; if ('$binary' in doc) { if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { type = doc.$type ? parseInt(doc.$type, 16) : 0; data = buffer.Buffer.from(doc.$binary, 'base64'); } else { if (typeof doc.$binary !== 'string') { type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; data = buffer.Buffer.from(doc.$binary.base64, 'base64'); } } } else if ('$uuid' in doc) { type = 4; data = uuid_utils.uuidHexStringToBuffer(doc.$uuid); } if (!data) { throw new TypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc)); } return new Binary(data, type); }; /** @internal */ Binary.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { return this.inspect(); }; Binary.prototype.inspect = function () { var asBuffer = this.value(true); return "new Binary(Buffer.from(\"" + asBuffer.toString('hex') + "\", \"hex\"), " + this.sub_type + ")"; }; /** * Binary default subtype * @internal */ Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; /** Initial buffer default size */ Binary.BUFFER_SIZE = 256; /** Default BSON type */ Binary.SUBTYPE_DEFAULT = 0; /** Function BSON type */ Binary.SUBTYPE_FUNCTION = 1; /** Byte Array BSON type */ Binary.SUBTYPE_BYTE_ARRAY = 2; /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */ Binary.SUBTYPE_UUID_OLD = 3; /** UUID BSON type */ Binary.SUBTYPE_UUID = 4; /** MD5 BSON type */ Binary.SUBTYPE_MD5 = 5; /** User BSON type */ Binary.SUBTYPE_USER_DEFINED = 128; return Binary; }()); exports.Binary = Binary; Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' }); }); unwrapExports(binary); binary.Binary; var code = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.Code = void 0; /** * A class representation of the BSON Code type. * @public */ var Code = /** @class */ (function () { /** * @param code - a string or function. * @param scope - an optional scope for the function. */ function Code(code, scope) { if (!(this instanceof Code)) return new Code(code, scope); this.code = code; this.scope = scope; } /** @internal */ Code.prototype.toJSON = function () { return { code: this.code, scope: this.scope }; }; /** @internal */ Code.prototype.toExtendedJSON = function () { if (this.scope) { return { $code: this.code, $scope: this.scope }; } return { $code: this.code }; }; /** @internal */ Code.fromExtendedJSON = function (doc) { return new Code(doc.$code, doc.$scope); }; /** @internal */ Code.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { return this.inspect(); }; Code.prototype.inspect = function () { var codeJson = this.toJSON(); return "new Code(\"" + codeJson.code + "\"" + (codeJson.scope ? ", " + JSON.stringify(codeJson.scope) : '') + ")"; }; return Code; }()); exports.Code = Code; Object.defineProperty(Code.prototype, '_bsontype', { value: 'Code' }); }); unwrapExports(code); code.Code; var db_ref = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.DBRef = exports.isDBRefLike = void 0; /** @internal */ function isDBRefLike(value) { return (utils.isObjectLike(value) && value.$id != null && typeof value.$ref === 'string' && (value.$db == null || typeof value.$db === 'string')); } exports.isDBRefLike = isDBRefLike; /** * A class representation of the BSON DBRef type. * @public */ var DBRef = /** @class */ (function () { /** * @param collection - the collection name. * @param oid - the reference ObjectId. * @param db - optional db name, if omitted the reference is local to the current db. */ function DBRef(collection, oid, db, fields) { if (!(this instanceof DBRef)) return new DBRef(collection, oid, db, fields); // check if namespace has been provided var parts = collection.split('.'); if (parts.length === 2) { db = parts.shift(); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion collection = parts.shift(); } this.collection = collection; this.oid = oid; this.db = db; this.fields = fields || {}; } Object.defineProperty(DBRef.prototype, "namespace", { // Property provided for compatibility with the 1.x parser // the 1.x parser used a "namespace" property, while 4.x uses "collection" /** @internal */ get: function () { return this.collection; }, set: function (value) { this.collection = value; }, enumerable: false, configurable: true }); /** @internal */ DBRef.prototype.toJSON = function () { var o = Object.assign({ $ref: this.collection, $id: this.oid }, this.fields); if (this.db != null) o.$db = this.db; return o; }; /** @internal */ DBRef.prototype.toExtendedJSON = function (options) { options = options || {}; var o = { $ref: this.collection, $id: this.oid }; if (options.legacy) { return o; } if (this.db) o.$db = this.db; o = Object.assign(o, this.fields); return o; }; /** @internal */ DBRef.fromExtendedJSON = function (doc) { var copy = Object.assign({}, doc); delete copy.$ref; delete copy.$id; delete copy.$db; return new DBRef(doc.$ref, doc.$id, doc.$db, copy); }; /** @internal */ DBRef.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { return this.inspect(); }; DBRef.prototype.inspect = function () { // NOTE: if OID is an ObjectId class it will just print the oid string. var oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString(); return "new DBRef(\"" + this.namespace + "\", new ObjectId(\"" + oid + "\")" + (this.db ? ", \"" + this.db + "\"" : '') + ")"; }; return DBRef; }()); exports.DBRef = DBRef; Object.defineProperty(DBRef.prototype, '_bsontype', { value: 'DBRef' }); }); unwrapExports(db_ref); db_ref.DBRef; db_ref.isDBRefLike; var long_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.Long = void 0; /** * wasm optimizations, to do native i64 multiplication and divide */ var wasm = undefined; try { wasm = new WebAssembly.Instance(new WebAssembly.Module( // prettier-ignore new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; } catch (_a) { // no wasm support } var TWO_PWR_16_DBL = 1 << 16; var TWO_PWR_24_DBL = 1 << 24; var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; /** A cache of the Long representations of small integer values. */ var INT_CACHE = {}; /** A cache of the Long representations of small unsigned integer values. */ var UINT_CACHE = {}; /** * A class representing a 64-bit integer * @public * @remarks * The internal representation of a long is the two given signed, 32-bit values. * We use 32-bit pieces because these are the size of integers on which * Javascript performs bit-operations. For operations like addition and * multiplication, we split each number into 16 bit pieces, which can easily be * multiplied within Javascript's floating-point representation without overflow * or change in sign. * In the algorithms below, we frequently reduce the negative case to the * positive case by negating the input(s) and then post-processing the result. * Note that we must ALWAYS check specially whether those values are MIN_VALUE * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as * a positive number, it overflows back into a negative). Not handling this * case would often result in infinite recursion. * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class. */ var Long = /** @class */ (function () { /** * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. * See the from* functions below for more convenient ways of constructing Longs. * * Acceptable signatures are: * - Long(low, high, unsigned?) * - Long(bigint, unsigned?) * - Long(string, unsigned?) * * @param low - The low (signed) 32 bits of the long * @param high - The high (signed) 32 bits of the long * @param unsigned - Whether unsigned or not, defaults to signed */ function Long(low, high, unsigned) { if (low === void 0) { low = 0; } if (!(this instanceof Long)) return new Long(low, high, unsigned); if (typeof low === 'bigint') { Object.assign(this, Long.fromBigInt(low, !!high)); } else if (typeof low === 'string') { Object.assign(this, Long.fromString(low, !!high)); } else { this.low = low | 0; this.high = high | 0; this.unsigned = !!unsigned; } Object.defineProperty(this, '__isLong__', { value: true, configurable: false, writable: false, enumerable: false }); } /** * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. * Each is assumed to use 32 bits. * @param lowBits - The low 32 bits * @param highBits - The high 32 bits * @param unsigned - Whether unsigned or not, defaults to signed * @returns The corresponding Long value */ Long.fromBits = function (lowBits, highBits, unsigned) { return new Long(lowBits, highBits, unsigned); }; /** * Returns a Long representing the given 32 bit integer value. * @param value - The 32 bit integer in question * @param unsigned - Whether unsigned or not, defaults to signed * @returns The corresponding Long value */ Long.fromInt = function (value, unsigned) { var obj, cachedObj, cache; if (unsigned) { value >>>= 0; if ((cache = 0 <= value && value < 256)) { cachedObj = UINT_CACHE[value]; if (cachedObj) return cachedObj; } obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); if (cache) UINT_CACHE[value] = obj; return obj; } else { value |= 0; if ((cache = -128 <= value && value < 128)) { cachedObj = INT_CACHE[value]; if (cachedObj) return cachedObj; } obj = Long.fromBits(value, value < 0 ? -1 : 0, false); if (cache) INT_CACHE[value] = obj; return obj; } }; /** * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. * @param value - The number in question * @param unsigned - Whether unsigned or not, defaults to signed * @returns The corresponding Long value */ Long.fromNumber = function (value, unsigned) { if (isNaN(value)) return unsigned ? Long.UZERO : Long.ZERO; if (unsigned) { if (value < 0) return Long.UZERO; if (value >= TWO_PWR_64_DBL) return Long.MAX_UNSIGNED_VALUE; } else { if (value <= -TWO_PWR_63_DBL) return Long.MIN_VALUE; if (value + 1 >= TWO_PWR_63_DBL) return Long.MAX_VALUE; } if (value < 0) return Long.fromNumber(-value, unsigned).neg(); return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); }; /** * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. * @param value - The number in question * @param unsigned - Whether unsigned or not, defaults to signed * @returns The corresponding Long value */ Long.fromBigInt = function (value, unsigned) { return Long.fromString(value.toString(), unsigned); }; /** * Returns a Long representation of the given string, written using the specified radix. * @param str - The textual representation of the Long * @param unsigned - Whether unsigned or not, defaults to signed * @param radix - The radix in which the text is written (2-36), defaults to 10 *