UNPKG

bson

Version:

A bson parser for node.js and the browser

1,454 lines (1,440 loc) 156 kB
var BSON = (function (exports) { 'use strict'; const BSON_MAJOR_VERSION = 5; const BSON_INT32_MAX = 0x7fffffff; const BSON_INT32_MIN = -0x80000000; const BSON_INT64_MAX = Math.pow(2, 63) - 1; const BSON_INT64_MIN = -Math.pow(2, 63); const JS_INT_MAX = Math.pow(2, 53); const JS_INT_MIN = -Math.pow(2, 53); const BSON_DATA_NUMBER = 1; const BSON_DATA_STRING = 2; const BSON_DATA_OBJECT = 3; const BSON_DATA_ARRAY = 4; const BSON_DATA_BINARY = 5; const BSON_DATA_UNDEFINED = 6; const BSON_DATA_OID = 7; const BSON_DATA_BOOLEAN = 8; const BSON_DATA_DATE = 9; const BSON_DATA_NULL = 10; const BSON_DATA_REGEXP = 11; const BSON_DATA_DBPOINTER = 12; const BSON_DATA_CODE = 13; const BSON_DATA_SYMBOL = 14; const BSON_DATA_CODE_W_SCOPE = 15; const BSON_DATA_INT = 16; const BSON_DATA_TIMESTAMP = 17; const BSON_DATA_LONG = 18; const BSON_DATA_DECIMAL128 = 19; const BSON_DATA_MIN_KEY = 0xff; const BSON_DATA_MAX_KEY = 0x7f; const BSON_BINARY_SUBTYPE_DEFAULT = 0; const BSON_BINARY_SUBTYPE_UUID_NEW = 4; const BSONType = Object.freeze({ double: 1, string: 2, object: 3, array: 4, binData: 5, undefined: 6, objectId: 7, bool: 8, date: 9, null: 10, regex: 11, dbPointer: 12, javascript: 13, symbol: 14, javascriptWithScope: 15, int: 16, timestamp: 17, long: 18, decimal: 19, minKey: -1, maxKey: 127 }); class BSONError extends Error { get bsonError() { return true; } get name() { return 'BSONError'; } constructor(message) { super(message); } static isBSONError(value) { return (value != null && typeof value === 'object' && 'bsonError' in value && value.bsonError === true && 'name' in value && 'message' in value && 'stack' in value); } } class BSONVersionError extends BSONError { get name() { return 'BSONVersionError'; } constructor() { super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.0 or later`); } } class BSONRuntimeError extends BSONError { get name() { return 'BSONRuntimeError'; } constructor(message) { super(message); } } function nodejsMathRandomBytes(byteLength) { return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); } const nodejsRandomBytes = (() => { try { return require('crypto').randomBytes; } catch { return nodejsMathRandomBytes; } })(); const nodeJsByteUtils = { toLocalBufferType(potentialBuffer) { if (Buffer.isBuffer(potentialBuffer)) { return potentialBuffer; } if (ArrayBuffer.isView(potentialBuffer)) { return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); } const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer); if (stringTag === 'ArrayBuffer' || stringTag === 'SharedArrayBuffer' || stringTag === '[object ArrayBuffer]' || stringTag === '[object SharedArrayBuffer]') { return Buffer.from(potentialBuffer); } throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`); }, allocate(size) { return Buffer.alloc(size); }, equals(a, b) { return nodeJsByteUtils.toLocalBufferType(a).equals(b); }, fromNumberArray(array) { return Buffer.from(array); }, fromBase64(base64) { return Buffer.from(base64, 'base64'); }, toBase64(buffer) { return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64'); }, fromISO88591(codePoints) { return Buffer.from(codePoints, 'binary'); }, toISO88591(buffer) { return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary'); }, fromHex(hex) { return Buffer.from(hex, 'hex'); }, toHex(buffer) { return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex'); }, fromUTF8(text) { return Buffer.from(text, 'utf8'); }, toUTF8(buffer) { return nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8'); }, utf8ByteLength(input) { return Buffer.byteLength(input, 'utf8'); }, encodeUTF8Into(buffer, source, byteOffset) { return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8'); }, randomBytes: nodejsRandomBytes }; function isReactNative() { const { navigator } = globalThis; return typeof navigator === 'object' && navigator.product === 'ReactNative'; } function webMathRandomBytes(byteLength) { if (byteLength < 0) { throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`); } return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); } const webRandomBytes = (() => { const { crypto } = globalThis; if (crypto != null && typeof crypto.getRandomValues === 'function') { return (byteLength) => { return crypto.getRandomValues(webByteUtils.allocate(byteLength)); }; } else { if (isReactNative()) { const { console } = globalThis; console?.warn?.('BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.'); } return webMathRandomBytes; } })(); const HEX_DIGIT = /(\d|[a-f])/i; const webByteUtils = { toLocalBufferType(potentialUint8array) { const stringTag = potentialUint8array?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialUint8array); if (stringTag === 'Uint8Array') { return potentialUint8array; } if (ArrayBuffer.isView(potentialUint8array)) { return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength)); } if (stringTag === 'ArrayBuffer' || stringTag === 'SharedArrayBuffer' || stringTag === '[object ArrayBuffer]' || stringTag === '[object SharedArrayBuffer]') { return new Uint8Array(potentialUint8array); } throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`); }, allocate(size) { if (typeof size !== 'number') { throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`); } return new Uint8Array(size); }, equals(a, b) { if (a.byteLength !== b.byteLength) { return false; } for (let i = 0; i < a.byteLength; i++) { if (a[i] !== b[i]) { return false; } } return true; }, fromNumberArray(array) { return Uint8Array.from(array); }, fromBase64(base64) { return Uint8Array.from(atob(base64), c => c.charCodeAt(0)); }, toBase64(uint8array) { return btoa(webByteUtils.toISO88591(uint8array)); }, fromISO88591(codePoints) { return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff); }, toISO88591(uint8array) { return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join(''); }, fromHex(hex) { const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1); const buffer = []; for (let i = 0; i < evenLengthHex.length; i += 2) { const firstDigit = evenLengthHex[i]; const secondDigit = evenLengthHex[i + 1]; if (!HEX_DIGIT.test(firstDigit)) { break; } if (!HEX_DIGIT.test(secondDigit)) { break; } const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16); buffer.push(hexDigit); } return Uint8Array.from(buffer); }, toHex(uint8array) { return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join(''); }, fromUTF8(text) { return new TextEncoder().encode(text); }, toUTF8(uint8array) { return new TextDecoder('utf8', { fatal: false }).decode(uint8array); }, utf8ByteLength(input) { return webByteUtils.fromUTF8(input).byteLength; }, encodeUTF8Into(buffer, source, byteOffset) { const bytes = webByteUtils.fromUTF8(source); buffer.set(bytes, byteOffset); return bytes.byteLength; }, randomBytes: webRandomBytes }; const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true; const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils; class BSONDataView extends DataView { static fromUint8Array(input) { return new DataView(input.buffer, input.byteOffset, input.byteLength); } } const 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; const uuidValidateString = (str) => typeof str === 'string' && VALIDATION_REGEX.test(str); const uuidHexStringToBuffer = (hexString) => { if (!uuidValidateString(hexString)) { throw new BSONError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".'); } const sanitizedHexString = hexString.replace(/-/g, ''); return ByteUtils.fromHex(sanitizedHexString); }; function bufferToUuidHexString(buffer, includeDashes = true) { if (includeDashes) { return [ ByteUtils.toHex(buffer.subarray(0, 4)), ByteUtils.toHex(buffer.subarray(4, 6)), ByteUtils.toHex(buffer.subarray(6, 8)), ByteUtils.toHex(buffer.subarray(8, 10)), ByteUtils.toHex(buffer.subarray(10, 16)) ].join('-'); } return ByteUtils.toHex(buffer); } function isAnyArrayBuffer(value) { return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); } function isUint8Array(value) { return Object.prototype.toString.call(value) === '[object Uint8Array]'; } function isRegExp(d) { return Object.prototype.toString.call(d) === '[object RegExp]'; } function isMap(d) { return Object.prototype.toString.call(d) === '[object Map]'; } function isDate(d) { return Object.prototype.toString.call(d) === '[object Date]'; } class BSONValue { get [Symbol.for('@@mdb.bson.version')]() { return BSON_MAJOR_VERSION; } } class Binary extends BSONValue { get _bsontype() { return 'Binary'; } constructor(buffer, subType) { super(); if (!(buffer == null) && !(typeof buffer === 'string') && !ArrayBuffer.isView(buffer) && !(buffer instanceof ArrayBuffer) && !Array.isArray(buffer)) { throw new BSONError('Binary can only be constructed from string, Buffer, TypedArray, or Array<number>'); } this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT; if (buffer == null) { this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE); this.position = 0; } else { if (typeof buffer === 'string') { this.buffer = ByteUtils.fromISO88591(buffer); } else if (Array.isArray(buffer)) { this.buffer = ByteUtils.fromNumberArray(buffer); } else { this.buffer = ByteUtils.toLocalBufferType(buffer); } this.position = this.buffer.byteLength; } } put(byteValue) { if (typeof byteValue === 'string' && byteValue.length !== 1) { throw new BSONError('only accepts single character String'); } else if (typeof byteValue !== 'number' && byteValue.length !== 1) throw new BSONError('only accepts single character Uint8Array or Array'); let 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 BSONError('only accepts number in a valid unsigned byte range 0-255'); } if (this.buffer.byteLength > this.position) { this.buffer[this.position++] = decodedByte; } else { const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length); newSpace.set(this.buffer, 0); this.buffer = newSpace; this.buffer[this.position++] = decodedByte; } } write(sequence, offset) { offset = typeof offset === 'number' ? offset : this.position; if (this.buffer.byteLength < offset + sequence.length) { const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length); newSpace.set(this.buffer, 0); this.buffer = newSpace; } if (ArrayBuffer.isView(sequence)) { this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset); this.position = offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; } else if (typeof sequence === 'string') { const bytes = ByteUtils.fromISO88591(sequence); this.buffer.set(bytes, offset); this.position = offset + sequence.length > this.position ? offset + sequence.length : this.position; } } read(position, length) { length = length && length > 0 ? length : this.position; return this.buffer.slice(position, position + length); } value(asRaw) { asRaw = !!asRaw; if (asRaw && this.buffer.length === this.position) { return this.buffer; } if (asRaw) { return this.buffer.slice(0, this.position); } return ByteUtils.toISO88591(this.buffer.subarray(0, this.position)); } length() { return this.position; } toJSON() { return ByteUtils.toBase64(this.buffer); } toString(encoding) { if (encoding === 'hex') return ByteUtils.toHex(this.buffer); if (encoding === 'base64') return ByteUtils.toBase64(this.buffer); if (encoding === 'utf8' || encoding === 'utf-8') return ByteUtils.toUTF8(this.buffer); return ByteUtils.toUTF8(this.buffer); } toExtendedJSON(options) { options = options || {}; const base64String = ByteUtils.toBase64(this.buffer); const 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 } }; } toUUID() { if (this.sub_type === Binary.SUBTYPE_UUID) { return new UUID(this.buffer.slice(0, this.position)); } throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.`); } static fromExtendedJSON(doc, options) { options = options || {}; let data; let type; if ('$binary' in doc) { if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { type = doc.$type ? parseInt(doc.$type, 16) : 0; data = ByteUtils.fromBase64(doc.$binary); } else { if (typeof doc.$binary !== 'string') { type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; data = ByteUtils.fromBase64(doc.$binary.base64); } } } else if ('$uuid' in doc) { type = 4; data = uuidHexStringToBuffer(doc.$uuid); } if (!data) { throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`); } return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type); } [Symbol.for('nodejs.util.inspect.custom')]() { return this.inspect(); } inspect() { return `new Binary(Buffer.from("${ByteUtils.toHex(this.buffer)}", "hex"), ${this.sub_type})`; } } Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; Binary.BUFFER_SIZE = 256; Binary.SUBTYPE_DEFAULT = 0; Binary.SUBTYPE_FUNCTION = 1; Binary.SUBTYPE_BYTE_ARRAY = 2; Binary.SUBTYPE_UUID_OLD = 3; Binary.SUBTYPE_UUID = 4; Binary.SUBTYPE_MD5 = 5; Binary.SUBTYPE_ENCRYPTED = 6; Binary.SUBTYPE_COLUMN = 7; Binary.SUBTYPE_USER_DEFINED = 128; const UUID_BYTE_LENGTH = 16; class UUID extends Binary { constructor(input) { let bytes; let hexStr; if (input == null) { bytes = UUID.generate(); } else if (input instanceof UUID) { bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer)); hexStr = input.__id; } else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) { bytes = ByteUtils.toLocalBufferType(input); } else if (typeof input === 'string') { bytes = uuidHexStringToBuffer(input); } else { throw new BSONError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'); } super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW); this.__id = hexStr; } get id() { return this.buffer; } set id(value) { this.buffer = value; if (UUID.cacheHexString) { this.__id = bufferToUuidHexString(value); } } toHexString(includeDashes = true) { if (UUID.cacheHexString && this.__id) { return this.__id; } const uuidHexString = bufferToUuidHexString(this.id, includeDashes); if (UUID.cacheHexString) { this.__id = uuidHexString; } return uuidHexString; } toString(encoding) { if (encoding === 'hex') return ByteUtils.toHex(this.id); if (encoding === 'base64') return ByteUtils.toBase64(this.id); return this.toHexString(); } toJSON() { return this.toHexString(); } equals(otherId) { if (!otherId) { return false; } if (otherId instanceof UUID) { return ByteUtils.equals(otherId.id, this.id); } try { return ByteUtils.equals(new UUID(otherId).id, this.id); } catch { return false; } } toBinary() { return new Binary(this.id, Binary.SUBTYPE_UUID); } static generate() { const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH); bytes[6] = (bytes[6] & 0x0f) | 0x40; bytes[8] = (bytes[8] & 0x3f) | 0x80; return bytes; } static isValid(input) { if (!input) { return false; } if (input instanceof UUID) { return true; } if (typeof input === 'string') { return uuidValidateString(input); } if (isUint8Array(input)) { if (input.byteLength !== UUID_BYTE_LENGTH) { return false; } return (input[6] & 0xf0) === 0x40 && (input[8] & 0x80) === 0x80; } return false; } static createFromHexString(hexString) { const buffer = uuidHexStringToBuffer(hexString); return new UUID(buffer); } [Symbol.for('nodejs.util.inspect.custom')]() { return this.inspect(); } inspect() { return `new UUID("${this.toHexString()}")`; } } class Code extends BSONValue { get _bsontype() { return 'Code'; } constructor(code, scope) { super(); this.code = code.toString(); this.scope = scope ?? null; } toJSON() { if (this.scope != null) { return { code: this.code, scope: this.scope }; } return { code: this.code }; } toExtendedJSON() { if (this.scope) { return { $code: this.code, $scope: this.scope }; } return { $code: this.code }; } static fromExtendedJSON(doc) { return new Code(doc.$code, doc.$scope); } [Symbol.for('nodejs.util.inspect.custom')]() { return this.inspect(); } inspect() { const codeJson = this.toJSON(); return `new Code("${String(codeJson.code)}"${codeJson.scope != null ? `, ${JSON.stringify(codeJson.scope)}` : ''})`; } } function isDBRefLike(value) { return (value != null && typeof value === 'object' && '$id' in value && value.$id != null && '$ref' in value && typeof value.$ref === 'string' && (!('$db' in value) || ('$db' in value && typeof value.$db === 'string'))); } class DBRef extends BSONValue { get _bsontype() { return 'DBRef'; } constructor(collection, oid, db, fields) { super(); const parts = collection.split('.'); if (parts.length === 2) { db = parts.shift(); collection = parts.shift(); } this.collection = collection; this.oid = oid; this.db = db; this.fields = fields || {}; } get namespace() { return this.collection; } set namespace(value) { this.collection = value; } toJSON() { const o = Object.assign({ $ref: this.collection, $id: this.oid }, this.fields); if (this.db != null) o.$db = this.db; return o; } toExtendedJSON(options) { options = options || {}; let 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; } static fromExtendedJSON(doc) { const copy = Object.assign({}, doc); delete copy.$ref; delete copy.$id; delete copy.$db; return new DBRef(doc.$ref, doc.$id, doc.$db, copy); } [Symbol.for('nodejs.util.inspect.custom')]() { return this.inspect(); } inspect() { const oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString(); return `new DBRef("${this.namespace}", new ObjectId("${String(oid)}")${this.db ? `, "${this.db}"` : ''})`; } } let wasm = undefined; try { wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; } catch { } const TWO_PWR_16_DBL = 1 << 16; const TWO_PWR_24_DBL = 1 << 24; const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; const INT_CACHE = {}; const UINT_CACHE = {}; const MAX_INT64_STRING_LENGTH = 20; const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/; class Long extends BSONValue { get _bsontype() { return 'Long'; } get __isLong__() { return true; } constructor(low = 0, high, unsigned) { super(); 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; } } static fromBits(lowBits, highBits, unsigned) { return new Long(lowBits, highBits, unsigned); } static fromInt(value, unsigned) { let 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; } } static fromNumber(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); } static fromBigInt(value, unsigned) { return Long.fromString(value.toString(), unsigned); } static fromString(str, unsigned, radix) { if (str.length === 0) throw new BSONError('empty string'); if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') return Long.ZERO; if (typeof unsigned === 'number') { (radix = unsigned), (unsigned = false); } else { unsigned = !!unsigned; } radix = radix || 10; if (radix < 2 || 36 < radix) throw new BSONError('radix'); let p; if ((p = str.indexOf('-')) > 0) throw new BSONError('interior hyphen'); else if (p === 0) { return Long.fromString(str.substring(1), unsigned, radix).neg(); } const radixToPower = Long.fromNumber(Math.pow(radix, 8)); let result = Long.ZERO; for (let i = 0; i < str.length; i += 8) { const size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); if (size < 8) { const power = Long.fromNumber(Math.pow(radix, size)); result = result.mul(power).add(Long.fromNumber(value)); } else { result = result.mul(radixToPower); result = result.add(Long.fromNumber(value)); } } result.unsigned = unsigned; return result; } static fromBytes(bytes, unsigned, le) { return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); } static fromBytesLE(bytes, unsigned) { return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned); } static fromBytesBE(bytes, unsigned) { return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned); } static isLong(value) { return (value != null && typeof value === 'object' && '__isLong__' in value && value.__isLong__ === true); } static fromValue(val, unsigned) { if (typeof val === 'number') return Long.fromNumber(val, unsigned); if (typeof val === 'string') return Long.fromString(val, unsigned); return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); } add(addend) { if (!Long.isLong(addend)) addend = Long.fromValue(addend); const a48 = this.high >>> 16; const a32 = this.high & 0xffff; const a16 = this.low >>> 16; const a00 = this.low & 0xffff; const b48 = addend.high >>> 16; const b32 = addend.high & 0xffff; const b16 = addend.low >>> 16; const b00 = addend.low & 0xffff; let c48 = 0, c32 = 0, c16 = 0, c00 = 0; c00 += a00 + b00; c16 += c00 >>> 16; c00 &= 0xffff; c16 += a16 + b16; c32 += c16 >>> 16; c16 &= 0xffff; c32 += a32 + b32; c48 += c32 >>> 16; c32 &= 0xffff; c48 += a48 + b48; c48 &= 0xffff; return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); } and(other) { if (!Long.isLong(other)) other = Long.fromValue(other); return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); } compare(other) { if (!Long.isLong(other)) other = Long.fromValue(other); if (this.eq(other)) return 0; const thisNeg = this.isNegative(), otherNeg = other.isNegative(); if (thisNeg && !otherNeg) return -1; if (!thisNeg && otherNeg) return 1; if (!this.unsigned) return this.sub(other).isNegative() ? -1 : 1; return other.high >>> 0 > this.high >>> 0 || (other.high === this.high && other.low >>> 0 > this.low >>> 0) ? -1 : 1; } comp(other) { return this.compare(other); } divide(divisor) { if (!Long.isLong(divisor)) divisor = Long.fromValue(divisor); if (divisor.isZero()) throw new BSONError('division by zero'); if (wasm) { if (!this.unsigned && this.high === -0x80000000 && divisor.low === -1 && divisor.high === -1) { return this; } const low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high); return Long.fromBits(low, wasm.get_high(), this.unsigned); } if (this.isZero()) return this.unsigned ? Long.UZERO : Long.ZERO; let approx, rem, res; if (!this.unsigned) { if (this.eq(Long.MIN_VALUE)) { if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) return Long.MIN_VALUE; else if (divisor.eq(Long.MIN_VALUE)) return Long.ONE; else { const halfThis = this.shr(1); approx = halfThis.div(divisor).shl(1); if (approx.eq(Long.ZERO)) { return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; } else { rem = this.sub(divisor.mul(approx)); res = approx.add(rem.div(divisor)); return res; } } } else if (divisor.eq(Long.MIN_VALUE)) return this.unsigned ? Long.UZERO : Long.ZERO; if (this.isNegative()) { if (divisor.isNegative()) return this.neg().div(divisor.neg()); return this.neg().div(divisor).neg(); } else if (divisor.isNegative()) return this.div(divisor.neg()).neg(); res = Long.ZERO; } else { if (!divisor.unsigned) divisor = divisor.toUnsigned(); if (divisor.gt(this)) return Long.UZERO; if (divisor.gt(this.shru(1))) return Long.UONE; res = Long.UZERO; } rem = this; while (rem.gte(divisor)) { approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); const log2 = Math.ceil(Math.log(approx) / Math.LN2); const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); let approxRes = Long.fromNumber(approx); let approxRem = approxRes.mul(divisor); while (approxRem.isNegative() || approxRem.gt(rem)) { approx -= delta; approxRes = Long.fromNumber(approx, this.unsigned); approxRem = approxRes.mul(divisor); } if (approxRes.isZero()) approxRes = Long.ONE; res = res.add(approxRes); rem = rem.sub(approxRem); } return res; } div(divisor) { return this.divide(divisor); } equals(other) { if (!Long.isLong(other)) other = Long.fromValue(other); if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) return false; return this.high === other.high && this.low === other.low; } eq(other) { return this.equals(other); } getHighBits() { return this.high; } getHighBitsUnsigned() { return this.high >>> 0; } getLowBits() { return this.low; } getLowBitsUnsigned() { return this.low >>> 0; } getNumBitsAbs() { if (this.isNegative()) { return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); } const val = this.high !== 0 ? this.high : this.low; let bit; for (bit = 31; bit > 0; bit--) if ((val & (1 << bit)) !== 0) break; return this.high !== 0 ? bit + 33 : bit + 1; } greaterThan(other) { return this.comp(other) > 0; } gt(other) { return this.greaterThan(other); } greaterThanOrEqual(other) { return this.comp(other) >= 0; } gte(other) { return this.greaterThanOrEqual(other); } ge(other) { return this.greaterThanOrEqual(other); } isEven() { return (this.low & 1) === 0; } isNegative() { return !this.unsigned && this.high < 0; } isOdd() { return (this.low & 1) === 1; } isPositive() { return this.unsigned || this.high >= 0; } isZero() { return this.high === 0 && this.low === 0; } lessThan(other) { return this.comp(other) < 0; } lt(other) { return this.lessThan(other); } lessThanOrEqual(other) { return this.comp(other) <= 0; } lte(other) { return this.lessThanOrEqual(other); } modulo(divisor) { if (!Long.isLong(divisor)) divisor = Long.fromValue(divisor); if (wasm) { const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high); return Long.fromBits(low, wasm.get_high(), this.unsigned); } return this.sub(this.div(divisor).mul(divisor)); } mod(divisor) { return this.modulo(divisor); } rem(divisor) { return this.modulo(divisor); } multiply(multiplier) { if (this.isZero()) return Long.ZERO; if (!Long.isLong(multiplier)) multiplier = Long.fromValue(multiplier); if (wasm) { const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); return Long.fromBits(low, wasm.get_high(), this.unsigned); } if (multiplier.isZero()) return Long.ZERO; if (this.eq(Long.MIN_VALUE)) return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; if (multiplier.eq(Long.MIN_VALUE)) return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; if (this.isNegative()) { if (multiplier.isNegative()) return this.neg().mul(multiplier.neg()); else return this.neg().mul(multiplier).neg(); } else if (multiplier.isNegative()) return this.mul(multiplier.neg()).neg(); if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); const a48 = this.high >>> 16; const a32 = this.high & 0xffff; const a16 = this.low >>> 16; const a00 = this.low & 0xffff; const b48 = multiplier.high >>> 16; const b32 = multiplier.high & 0xffff; const b16 = multiplier.low >>> 16; const b00 = multiplier.low & 0xffff; let c48 = 0, c32 = 0, c16 = 0, c00 = 0; c00 += a00 * b00; c16 += c00 >>> 16; c00 &= 0xffff; c16 += a16 * b00; c32 += c16 >>> 16; c16 &= 0xffff; c16 += a00 * b16; c32 += c16 >>> 16; c16 &= 0xffff; c32 += a32 * b00; c48 += c32 >>> 16; c32 &= 0xffff; c32 += a16 * b16; c48 += c32 >>> 16; c32 &= 0xffff; c32 += a00 * b32; c48 += c32 >>> 16; c32 &= 0xffff; c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; c48 &= 0xffff; return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); } mul(multiplier) { return this.multiply(multiplier); } negate() { if (!this.unsigned && this.eq(Long.MIN_VALUE)) return Long.MIN_VALUE; return this.not().add(Long.ONE); } neg() { return this.negate(); } not() { return Long.fromBits(~this.low, ~this.high, this.unsigned); } notEquals(other) { return !this.equals(other); } neq(other) { return this.notEquals(other); } ne(other) { return this.notEquals(other); } or(other) { if (!Long.isLong(other)) other = Long.fromValue(other); return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); } shiftLeft(numBits) { if (Long.isLong(numBits)) numBits = numBits.toInt(); if ((numBits &= 63) === 0) return this; else if (numBits < 32) return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned); else return Long.fromBits(0, this.low << (numBits - 32), this.unsigned); } shl(numBits) { return this.shiftLeft(numBits); } shiftRight(numBits) { if (Long.isLong(numBits)) numBits = numBits.toInt(); if ((numBits &= 63) === 0) return this; else if (numBits < 32) return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned); else return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); } shr(numBits) { return this.shiftRight(numBits); } shiftRightUnsigned(numBits) { if (Long.isLong(numBits)) numBits = numBits.toInt(); numBits &= 63; if (numBits === 0) return this; else { const high = this.high; if (numBits < 32) { const low = this.low; return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned); } else if (numBits === 32) return Long.fromBits(high, 0, this.unsigned); else return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned); } } shr_u(numBits) { return this.shiftRightUnsigned(numBits); } shru(numBits) { return this.shiftRightUnsigned(numBits); } subtract(subtrahend) { if (!Long.isLong(subtrahend)) subtrahend = Long.fromValue(subtrahend); return this.add(subtrahend.neg()); } sub(subtrahend) { return this.subtract(subtrahend); } toInt() { return this.unsigned ? this.low >>> 0 : this.low; } toNumber() { if (this.unsigned) return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); return this.high * TWO_PWR_32_DBL + (this.low >>> 0); } toBigInt() { return BigInt(this.toString()); } toBytes(le) { return le ? this.toBytesLE() : this.toBytesBE(); } toBytesLE() { const hi = this.high, lo = this.low; return [ lo & 0xff, (lo >>> 8) & 0xff, (lo >>> 16) & 0xff, lo >>> 24, hi & 0xff, (hi >>> 8) & 0xff, (hi >>> 16) & 0xff, hi >>> 24 ]; } toBytesBE() { const hi = this.high, lo = this.low; return [ hi >>> 24, (hi >>> 16) & 0xff, (hi >>> 8) & 0xff, hi & 0xff, lo >>> 24, (lo >>> 16) & 0xff, (lo >>> 8) & 0xff, lo & 0xff ]; } toSigned() { if (!this.unsigned) return this; return Long.fromBits(this.low, this.high, false); } toString(radix) { radix = radix || 10; if (radix < 2 || 36 < radix) throw new BSONError('radix'); if (this.isZero()) return '0'; if (this.isNegative()) { if (this.eq(Long.MIN_VALUE)) { const radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); return div.toString(radix) + rem1.toInt().toString(radix); } else return '-' + this.neg().toString(radix); } const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); let rem = this; let result = ''; while (true) { const remDiv = rem.div(radixToPower); const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; let digits = intval.toString(radix); rem = remDiv; if (rem.isZero()) { return digits + result; } else { while (digits.length < 6) digits = '0' + digits; result = '' + digits + result; } } } toUnsigned() { if (this.unsigned) return this; return Long.fromBits(this.low, this.high, true); } xor(other) { if (!Long.isLong(other)) other = Long.fromValue(other); return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); } eqz() { return this.isZero(); } le(other) { return this.lessThanOrEqual(other); } toExtendedJSON(options) { if (options && options.relaxed) return this.toNumber(); return { $numberLong: this.toString() }; } static fromExtendedJSON(doc, options) { const { useBigInt64 = false, relaxed = true } = { ...options }; if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) { throw new BSONError('$numberLong string is too long'); } if (!DECIMAL_REG_EX.test(doc.$numberLong)) { throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`); } if (useBigInt64) { const bigIntResult = BigInt(doc.$numberLong); return BigInt.asIntN(64, bigIntResult); } const longResult = Long.fromString(doc.$numberLong); if (relaxed) { return longResult.toNumber(); } return longResult; } [Symbol.for('nodejs.util.inspect.custom')]() { return this.inspect(); } inspect() { return `new Long("${this.toString()}"${this.unsigned ? ', true' : ''})`; } } Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); Long.ZERO = Long.fromInt(0); Long.UZERO = Long.fromInt(0, true); Long.ONE = Long.fromInt(1); Long.UONE = Long.fromInt(1, true); Long.NEG_ONE = Long.fromInt(-1); Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; const PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; const PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; const EXPONENT_MAX = 6111; const EXPONENT_MIN = -6176; const EXPONENT_BIAS = 6176; const MAX_DIGITS = 34; const NAN_BUFFER = ByteUtils.fromNumberArray([ 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ].reverse()); const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([ 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ].reverse()); const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([ 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ].reverse()); const EXPONENT_REGEX = /^([-+])?(\d+)?$/; const COMBINATION_MASK = 0x1f; const EXPONENT_MASK = 0x3fff; const COMBINATION_INFINITY = 30; const COMBINATION_NAN = 31; function isDigit(value) { return !isNaN(parseInt(value, 10)); } function divideu128(value) { const DIVISOR = Long.fromNumber(1000 * 1000 * 1000); let _rem = Long.fromNumber(0); if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { return { quotient: value, rem: _rem }; } for (let i = 0; i <= 3; i++) { _rem = _rem.shiftLeft(32); _rem = _rem.add(new Long(value.parts[i], 0)); value.parts[i] = _rem.div(DIVISOR).low; _rem = _rem.modulo(DIVISOR); } return { quotient: value, rem: _rem }; } function multiply64x2(left, right) { if (!left && !right) { return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; } const leftHigh = left.shiftRightUnsigned(32); const leftLow = new Long(left.getLowBits(), 0); const rightHigh = right.shiftRightUnsigned(32); const rightLow = new Long(right.getLowBits(), 0); let productHigh = leftHigh.multiply(rightHigh); let productMid = leftHigh.multiply(rightLow); const productMid2 = leftLow.multiply(rightHigh); let productLow = leftLow.multiply(rightLow); productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); productMid = new Long(productMid.getLowBits(), 0) .add(productMid2) .add(productLow.shiftRightUnsigned(32)); productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); return { high: productHigh, low: productLow }; } function lessThan(left, right) { const uhleft = left.high >>> 0; const uhright = right.high >>> 0; if (uhleft < uhright) { return true; } else if (uhleft === uhright) { const ulleft = left.low >>> 0; const ulright = right.low >>> 0; if (ulleft < ulright) return true; } return false; } function invalidErr(string, message) { throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`); } class Decimal128 extends BSONValue { get _bsontype() { return 'Decimal128'; } constructor(bytes) { super(); if (typeof bytes === 'string') { this.bytes = Decimal128.fromString(bytes).bytes; } else if (isUint8Array(bytes)) { if (bytes.byteLength !== 16) { throw new BSONError('Decimal128 must take a Buffer of 16 bytes'); } this.bytes = bytes; } else { throw new BSONError('Decimal128 must take a Buffer or string'); } } static fromString(representation) { let isNegative = false; let sawRadix = false; let foundNonZero = false; let significantDigits = 0; let nDigitsRead = 0; let nDigits = 0;