bson
Version:
A bson parser for node.js and the browser
1,366 lines (1,351 loc) • 176 kB
JavaScript
const TypedArrayPrototypeGetSymbolToStringTag = (() => {
const g = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
return (value) => g.call(value);
})();
function isUint8Array(value) {
return TypedArrayPrototypeGetSymbolToStringTag(value) === 'Uint8Array';
}
function isAnyArrayBuffer(value) {
return (typeof value === 'object' &&
value != null &&
Symbol.toStringTag in value &&
(value[Symbol.toStringTag] === 'ArrayBuffer' ||
value[Symbol.toStringTag] === 'SharedArrayBuffer'));
}
function isRegExp(regexp) {
return regexp instanceof RegExp || Object.prototype.toString.call(regexp) === '[object RegExp]';
}
function isMap(value) {
return (typeof value === 'object' &&
value != null &&
Symbol.toStringTag in value &&
value[Symbol.toStringTag] === 'Map');
}
function isDate(date) {
return date instanceof Date || Object.prototype.toString.call(date) === '[object Date]';
}
function defaultInspect(x, _options) {
return JSON.stringify(x, (k, v) => {
if (typeof v === 'bigint') {
return { $numberLong: `${v}` };
}
else if (isMap(v)) {
return Object.fromEntries(v);
}
return v;
});
}
function getStylizeFunction(options) {
const stylizeExists = options != null &&
typeof options === 'object' &&
'stylize' in options &&
typeof options.stylize === 'function';
if (stylizeExists) {
return options.stylize;
}
}
const BSON_MAJOR_VERSION = 6;
const BSON_VERSION_SYMBOL = Symbol.for('@@mdb.bson.version');
const BSON_INT32_MAX = 0x7fffffff;
const BSON_INT32_MIN = -2147483648;
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, options) {
super(message, options);
}
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}.x.x`);
}
}
class BSONRuntimeError extends BSONError {
get name() {
return 'BSONRuntimeError';
}
constructor(message) {
super(message);
}
}
class BSONOffsetError extends BSONError {
get name() {
return 'BSONOffsetError';
}
constructor(message, offset, options) {
super(`${message}. offset: ${offset}`, options);
this.offset = offset;
}
}
let TextDecoderFatal;
let TextDecoderNonFatal;
function parseUtf8(buffer, start, end, fatal) {
if (fatal) {
TextDecoderFatal ??= new TextDecoder('utf8', { fatal: true });
try {
return TextDecoderFatal.decode(buffer.subarray(start, end));
}
catch (cause) {
throw new BSONError('Invalid UTF-8 string in BSON document', { cause });
}
}
TextDecoderNonFatal ??= new TextDecoder('utf8', { fatal: false });
return TextDecoderNonFatal.decode(buffer.subarray(start, end));
}
function tryReadBasicLatin(uint8array, start, end) {
if (uint8array.length === 0) {
return '';
}
const stringByteLength = end - start;
if (stringByteLength === 0) {
return '';
}
if (stringByteLength > 20) {
return null;
}
if (stringByteLength === 1 && uint8array[start] < 128) {
return String.fromCharCode(uint8array[start]);
}
if (stringByteLength === 2 && uint8array[start] < 128 && uint8array[start + 1] < 128) {
return String.fromCharCode(uint8array[start]) + String.fromCharCode(uint8array[start + 1]);
}
if (stringByteLength === 3 &&
uint8array[start] < 128 &&
uint8array[start + 1] < 128 &&
uint8array[start + 2] < 128) {
return (String.fromCharCode(uint8array[start]) +
String.fromCharCode(uint8array[start + 1]) +
String.fromCharCode(uint8array[start + 2]));
}
const latinBytes = [];
for (let i = start; i < end; i++) {
const byte = uint8array[i];
if (byte > 127) {
return null;
}
latinBytes.push(byte);
}
return String.fromCharCode(...latinBytes);
}
function tryWriteBasicLatin(destination, source, offset) {
if (source.length === 0)
return 0;
if (source.length > 25)
return null;
if (destination.length - offset < source.length)
return null;
for (let charOffset = 0, destinationOffset = offset; charOffset < source.length; charOffset++, destinationOffset++) {
const char = source.charCodeAt(charOffset);
if (char > 127)
return null;
destination[destinationOffset] = char;
}
return source.length;
}
function nodejsMathRandomBytes(byteLength) {
return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
}
const nodejsRandomBytes = 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 the passed potentialBuffer.`);
},
allocate(size) {
return Buffer.alloc(size);
},
allocateUnsafe(size) {
return Buffer.allocUnsafe(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');
},
toUTF8(buffer, start, end, fatal) {
const basicLatin = end - start <= 20 ? tryReadBasicLatin(buffer, start, end) : null;
if (basicLatin != null) {
return basicLatin;
}
const string = nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8', start, end);
if (fatal) {
for (let i = 0; i < string.length; i++) {
if (string.charCodeAt(i) === 0xfffd) {
parseUtf8(buffer, start, end, true);
break;
}
}
}
return string;
},
utf8ByteLength(input) {
return Buffer.byteLength(input, 'utf8');
},
encodeUTF8Into(buffer, source, byteOffset) {
const latinBytesWritten = tryWriteBasicLatin(buffer, source, byteOffset);
if (latinBytesWritten != null) {
return latinBytesWritten;
}
return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8');
},
randomBytes: nodejsRandomBytes,
swap32(buffer) {
return nodeJsByteUtils.toLocalBufferType(buffer).swap32();
}
};
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 passed potentialBuffer.`);
},
allocate(size) {
if (typeof size !== 'number') {
throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`);
}
return new Uint8Array(size);
},
allocateUnsafe(size) {
return webByteUtils.allocate(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('');
},
toUTF8(uint8array, start, end, fatal) {
const basicLatin = end - start <= 20 ? tryReadBasicLatin(uint8array, start, end) : null;
if (basicLatin != null) {
return basicLatin;
}
return parseUtf8(uint8array, start, end, fatal);
},
utf8ByteLength(input) {
return new TextEncoder().encode(input).byteLength;
},
encodeUTF8Into(uint8array, source, byteOffset) {
const bytes = new TextEncoder().encode(source);
uint8array.set(bytes, byteOffset);
return bytes.byteLength;
},
randomBytes: webRandomBytes,
swap32(buffer) {
if (buffer.length % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits');
}
for (let i = 0; i < buffer.length; i += 4) {
const byte0 = buffer[i];
const byte1 = buffer[i + 1];
const byte2 = buffer[i + 2];
const byte3 = buffer[i + 3];
buffer[i] = byte3;
buffer[i + 1] = byte2;
buffer[i + 2] = byte1;
buffer[i + 3] = byte0;
}
return buffer;
}
};
const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true;
const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils;
class BSONValue {
get [BSON_VERSION_SYMBOL]() {
return BSON_MAJOR_VERSION;
}
[Symbol.for('nodejs.util.inspect.custom')](depth, options, inspect) {
return this.inspect(depth, options, inspect);
}
}
const FLOAT = new Float64Array(1);
const FLOAT_BYTES = new Uint8Array(FLOAT.buffer, 0, 8);
FLOAT[0] = -1;
const isBigEndian = FLOAT_BYTES[7] === 0;
const NumberUtils = {
isBigEndian,
getNonnegativeInt32LE(source, offset) {
if (source[offset + 3] > 127) {
throw new RangeError(`Size cannot be negative at offset: ${offset}`);
}
return (source[offset] |
(source[offset + 1] << 8) |
(source[offset + 2] << 16) |
(source[offset + 3] << 24));
},
getInt32LE(source, offset) {
return (source[offset] |
(source[offset + 1] << 8) |
(source[offset + 2] << 16) |
(source[offset + 3] << 24));
},
getUint32LE(source, offset) {
return (source[offset] +
source[offset + 1] * 256 +
source[offset + 2] * 65536 +
source[offset + 3] * 16777216);
},
getUint32BE(source, offset) {
return (source[offset + 3] +
source[offset + 2] * 256 +
source[offset + 1] * 65536 +
source[offset] * 16777216);
},
getBigInt64LE(source, offset) {
const hi = BigInt(source[offset + 4] +
source[offset + 5] * 256 +
source[offset + 6] * 65536 +
(source[offset + 7] << 24));
const lo = BigInt(source[offset] +
source[offset + 1] * 256 +
source[offset + 2] * 65536 +
source[offset + 3] * 16777216);
return (hi << BigInt(32)) + lo;
},
getFloat64LE: isBigEndian
? (source, offset) => {
FLOAT_BYTES[7] = source[offset];
FLOAT_BYTES[6] = source[offset + 1];
FLOAT_BYTES[5] = source[offset + 2];
FLOAT_BYTES[4] = source[offset + 3];
FLOAT_BYTES[3] = source[offset + 4];
FLOAT_BYTES[2] = source[offset + 5];
FLOAT_BYTES[1] = source[offset + 6];
FLOAT_BYTES[0] = source[offset + 7];
return FLOAT[0];
}
: (source, offset) => {
FLOAT_BYTES[0] = source[offset];
FLOAT_BYTES[1] = source[offset + 1];
FLOAT_BYTES[2] = source[offset + 2];
FLOAT_BYTES[3] = source[offset + 3];
FLOAT_BYTES[4] = source[offset + 4];
FLOAT_BYTES[5] = source[offset + 5];
FLOAT_BYTES[6] = source[offset + 6];
FLOAT_BYTES[7] = source[offset + 7];
return FLOAT[0];
},
setInt32BE(destination, offset, value) {
destination[offset + 3] = value;
value >>>= 8;
destination[offset + 2] = value;
value >>>= 8;
destination[offset + 1] = value;
value >>>= 8;
destination[offset] = value;
return 4;
},
setInt32LE(destination, offset, value) {
destination[offset] = value;
value >>>= 8;
destination[offset + 1] = value;
value >>>= 8;
destination[offset + 2] = value;
value >>>= 8;
destination[offset + 3] = value;
return 4;
},
setBigInt64LE(destination, offset, value) {
const mask32bits = BigInt(0xffff_ffff);
let lo = Number(value & mask32bits);
destination[offset] = lo;
lo >>= 8;
destination[offset + 1] = lo;
lo >>= 8;
destination[offset + 2] = lo;
lo >>= 8;
destination[offset + 3] = lo;
let hi = Number((value >> BigInt(32)) & mask32bits);
destination[offset + 4] = hi;
hi >>= 8;
destination[offset + 5] = hi;
hi >>= 8;
destination[offset + 6] = hi;
hi >>= 8;
destination[offset + 7] = hi;
return 8;
},
setFloat64LE: isBigEndian
? (destination, offset, value) => {
FLOAT[0] = value;
destination[offset] = FLOAT_BYTES[7];
destination[offset + 1] = FLOAT_BYTES[6];
destination[offset + 2] = FLOAT_BYTES[5];
destination[offset + 3] = FLOAT_BYTES[4];
destination[offset + 4] = FLOAT_BYTES[3];
destination[offset + 5] = FLOAT_BYTES[2];
destination[offset + 6] = FLOAT_BYTES[1];
destination[offset + 7] = FLOAT_BYTES[0];
return 8;
}
: (destination, offset, value) => {
FLOAT[0] = value;
destination[offset] = FLOAT_BYTES[0];
destination[offset + 1] = FLOAT_BYTES[1];
destination[offset + 2] = FLOAT_BYTES[2];
destination[offset + 3] = FLOAT_BYTES[3];
destination[offset + 4] = FLOAT_BYTES[4];
destination[offset + 5] = FLOAT_BYTES[5];
destination[offset + 6] = FLOAT_BYTES[6];
destination[offset + 7] = FLOAT_BYTES[7];
return 8;
}
};
class Binary extends BSONValue {
get _bsontype() {
return 'Binary';
}
constructor(buffer, subType) {
super();
if (!(buffer == null) &&
typeof buffer === 'string' &&
!ArrayBuffer.isView(buffer) &&
!isAnyArrayBuffer(buffer) &&
!Array.isArray(buffer)) {
throw new BSONError('Binary can only be constructed from Uint8Array or number[]');
}
this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT;
if (buffer == null) {
this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE);
this.position = 0;
}
else {
this.buffer = Array.isArray(buffer)
? ByteUtils.fromNumberArray(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') {
throw new BSONError('input cannot be string');
}
}
read(position, length) {
length = length && length > 0 ? length : this.position;
const end = position + length;
return this.buffer.subarray(position, end > this.position ? this.position : end);
}
value() {
return this.buffer.length === this.position
? this.buffer
: this.buffer.subarray(0, this.position);
}
length() {
return this.position;
}
toJSON() {
return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
}
toString(encoding) {
if (encoding === 'hex')
return ByteUtils.toHex(this.buffer.subarray(0, this.position));
if (encoding === 'base64')
return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
if (encoding === 'utf8' || encoding === 'utf-8')
return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
}
toExtendedJSON(options) {
options = options || {};
if (this.sub_type === Binary.SUBTYPE_VECTOR) {
validateBinaryVector(this);
}
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.subarray(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 createFromHexString(hex, subType) {
return new Binary(ByteUtils.fromHex(hex), subType);
}
static createFromBase64(base64, subType) {
return new Binary(ByteUtils.fromBase64(base64), subType);
}
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 = UUID.bytesFromString(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);
}
inspect(depth, options, inspect) {
inspect ??= defaultInspect;
const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position));
const base64Arg = inspect(base64, options);
const subTypeArg = inspect(this.sub_type, options);
return `Binary.createFromBase64(${base64Arg}, ${subTypeArg})`;
}
toInt8Array() {
if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
throw new BSONError('Binary sub_type is not Vector');
}
if (this.buffer[0] !== Binary.VECTOR_TYPE.Int8) {
throw new BSONError('Binary datatype field is not Int8');
}
validateBinaryVector(this);
return new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
}
toFloat32Array() {
if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
throw new BSONError('Binary sub_type is not Vector');
}
if (this.buffer[0] !== Binary.VECTOR_TYPE.Float32) {
throw new BSONError('Binary datatype field is not Float32');
}
validateBinaryVector(this);
const floatBytes = new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
if (NumberUtils.isBigEndian)
ByteUtils.swap32(floatBytes);
return new Float32Array(floatBytes.buffer);
}
toPackedBits() {
if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
throw new BSONError('Binary sub_type is not Vector');
}
if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) {
throw new BSONError('Binary datatype field is not packed bit');
}
validateBinaryVector(this);
return new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
}
toBits() {
if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
throw new BSONError('Binary sub_type is not Vector');
}
if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) {
throw new BSONError('Binary datatype field is not packed bit');
}
validateBinaryVector(this);
const byteCount = this.length() - 2;
const bitCount = byteCount * 8 - this.buffer[1];
const bits = new Int8Array(bitCount);
for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {
const byteOffset = (bitOffset / 8) | 0;
const byte = this.buffer[byteOffset + 2];
const shift = 7 - (bitOffset % 8);
const bit = (byte >> shift) & 1;
bits[bitOffset] = bit;
}
return bits;
}
static fromInt8Array(array) {
const buffer = ByteUtils.allocate(array.byteLength + 2);
buffer[0] = Binary.VECTOR_TYPE.Int8;
buffer[1] = 0;
const intBytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
buffer.set(intBytes, 2);
const bin = new this(buffer, this.SUBTYPE_VECTOR);
validateBinaryVector(bin);
return bin;
}
static fromFloat32Array(array) {
const binaryBytes = ByteUtils.allocate(array.byteLength + 2);
binaryBytes[0] = Binary.VECTOR_TYPE.Float32;
binaryBytes[1] = 0;
const floatBytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
binaryBytes.set(floatBytes, 2);
if (NumberUtils.isBigEndian)
ByteUtils.swap32(new Uint8Array(binaryBytes.buffer, 2));
const bin = new this(binaryBytes, this.SUBTYPE_VECTOR);
validateBinaryVector(bin);
return bin;
}
static fromPackedBits(array, padding = 0) {
const buffer = ByteUtils.allocate(array.byteLength + 2);
buffer[0] = Binary.VECTOR_TYPE.PackedBit;
buffer[1] = padding;
buffer.set(array, 2);
const bin = new this(buffer, this.SUBTYPE_VECTOR);
validateBinaryVector(bin);
return bin;
}
static fromBits(bits) {
const byteLength = (bits.length + 7) >>> 3;
const bytes = new Uint8Array(byteLength + 2);
bytes[0] = Binary.VECTOR_TYPE.PackedBit;
const remainder = bits.length % 8;
bytes[1] = remainder === 0 ? 0 : 8 - remainder;
for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {
const byteOffset = bitOffset >>> 3;
const bit = bits[bitOffset];
if (bit !== 0 && bit !== 1) {
throw new BSONError(`Invalid bit value at ${bitOffset}: must be 0 or 1, found ${bits[bitOffset]}`);
}
if (bit === 0)
continue;
const shift = 7 - (bitOffset % 8);
bytes[byteOffset + 2] |= bit << shift;
}
return new this(bytes, Binary.SUBTYPE_VECTOR);
}
}
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_SENSITIVE = 8;
Binary.SUBTYPE_VECTOR = 9;
Binary.SUBTYPE_USER_DEFINED = 128;
Binary.VECTOR_TYPE = Object.freeze({
Int8: 0x03,
Float32: 0x27,
PackedBit: 0x10
});
function validateBinaryVector(vector) {
if (vector.sub_type !== Binary.SUBTYPE_VECTOR)
return;
const size = vector.position;
const datatype = vector.buffer[0];
const padding = vector.buffer[1];
if ((datatype === Binary.VECTOR_TYPE.Float32 || datatype === Binary.VECTOR_TYPE.Int8) &&
padding !== 0) {
throw new BSONError('Invalid Vector: padding must be zero for int8 and float32 vectors');
}
if (datatype === Binary.VECTOR_TYPE.Float32) {
if (size !== 0 && size - 2 !== 0 && (size - 2) % 4 !== 0) {
throw new BSONError('Invalid Vector: Float32 vector must contain a multiple of 4 bytes');
}
}
if (datatype === Binary.VECTOR_TYPE.PackedBit && padding !== 0 && size === 2) {
throw new BSONError('Invalid Vector: padding must be zero for packed bit vectors that are empty');
}
if (datatype === Binary.VECTOR_TYPE.PackedBit && padding > 7) {
throw new BSONError(`Invalid Vector: padding must be a value between 0 and 7. found: ${padding}`);
}
}
const UUID_BYTE_LENGTH = 16;
const UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i;
const UUID_WITH_DASHES = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;
class UUID extends Binary {
constructor(input) {
let bytes;
if (input == null) {
bytes = UUID.generate();
}
else if (input instanceof UUID) {
bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));
}
else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) {
bytes = ByteUtils.toLocalBufferType(input);
}
else if (typeof input === 'string') {
bytes = UUID.bytesFromString(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);
}
get id() {
return this.buffer;
}
set id(value) {
this.buffer = value;
}
toHexString(includeDashes = true) {
if (includeDashes) {
return [
ByteUtils.toHex(this.buffer.subarray(0, 4)),
ByteUtils.toHex(this.buffer.subarray(4, 6)),
ByteUtils.toHex(this.buffer.subarray(6, 8)),
ByteUtils.toHex(this.buffer.subarray(8, 10)),
ByteUtils.toHex(this.buffer.subarray(10, 16))
].join('-');
}
return ByteUtils.toHex(this.buffer);
}
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 (typeof input === 'string') {
return UUID.isValidUUIDString(input);
}
if (isUint8Array(input)) {
return input.byteLength === UUID_BYTE_LENGTH;
}
return (input._bsontype === 'Binary' &&
input.sub_type === this.SUBTYPE_UUID &&
input.buffer.byteLength === 16);
}
static createFromHexString(hexString) {
const buffer = UUID.bytesFromString(hexString);
return new UUID(buffer);
}
static createFromBase64(base64) {
return new UUID(ByteUtils.fromBase64(base64));
}
static bytesFromString(representation) {
if (!UUID.isValidUUIDString(representation)) {
throw new BSONError('UUID string representation must be 32 hex digits or canonical hyphenated representation');
}
return ByteUtils.fromHex(representation.replace(/-/g, ''));
}
static isValidUUIDString(representation) {
return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation);
}
inspect(depth, options, inspect) {
inspect ??= defaultInspect;
return `new UUID(${inspect(this.toHexString(), options)})`;
}
}
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);
}
inspect(depth, options, inspect) {
inspect ??= defaultInspect;
let parametersString = inspect(this.code, options);
const multiLineFn = parametersString.includes('\n');
if (this.scope != null) {
parametersString += `,${multiLineFn ? '\n' : ' '}${inspect(this.scope, options)}`;
}
const endingNewline = multiLineFn && this.scope === null;
return `new Code(${multiLineFn ? '\n' : ''}${parametersString}${endingNewline ? '\n' : ''})`;
}
}
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);
}
inspect(depth, options, inspect) {
inspect ??= defaultInspect;
const args = [
inspect(this.namespace, options),
inspect(this.oid, options),
...(this.db ? [inspect(this.db, options)] : []),
...(Object.keys(this.fields).length > 0 ? [inspect(this.fields, options)] : [])
];
args[1] = inspect === defaultInspect ? `new ObjectId(${args[1]})` : args[1];
return `new DBRef(${args.join(', ')})`;
}
}
function removeLeadingZerosAndExplicitPlus(str) {
if (str === '') {
return str;
}
let startIndex = 0;
const isNegative = str[startIndex] === '-';
const isExplicitlyPositive = str[startIndex] === '+';
if (isExplicitlyPositive || isNegative) {
startIndex += 1;
}
let foundInsignificantZero = false;
for (; startIndex < str.length && str[startIndex] === '0'; ++startIndex) {
foundInsignificantZero = true;
}
if (!foundInsignificantZero) {
return isExplicitlyPositive ? str.slice(1) : str;
}
return `${isNegative ? '-' : ''}${str.length === startIndex ? '0' : str.slice(startIndex)}`;
}
function validateStringCharacters(str, radix) {
radix = radix ?? 10;
const validCharacters = '0123456789abcdefghijklmnopqrstuvwxyz'.slice(0, radix);
const regex = new RegExp(`[^-+${validCharacters}]`, 'i');
return regex.test(str) ? false : str;
}
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(lowOrValue = 0, highOrUnsigned, unsigned) {
super();
const unsignedBool = typeof highOrUnsigned === 'boolean' ? highOrUnsigned : Boolean(unsigned);
const high = typeof highOrUnsigned === 'number' ? highOrUnsigned : 0;
const res = typeof lowOrValue === 'string'
? Long.fromString(lowOrValue, unsignedBool)
: typeof lowOrValue === 'bigint'
? Long.fromBigInt(lowOrValue, unsignedBool)
: { low: lowOrValue | 0, high: high | 0, unsigned: unsignedBool };
this.low = res.low;
this.high = res.high;
this.unsigned = res.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 <= -9223372036854776e3)
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) {
const FROM_BIGINT_BIT_MASK = BigInt(0xffffffff);
const FROM_BIGINT_BIT_SHIFT = BigInt(32);
return new Long(Number(value & FROM_BIGINT_BIT_MASK), Number((value >> FROM_BIGINT_BIT_SHIFT) & FROM_BIGINT_BIT_MASK), unsigned);
}
static _fromString(str, unsigned, radix) {
if (str.length === 0)
throw new BSONError('empty string');
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 fromStringStrict(str, unsignedOrRadix, radix) {
let unsigned = false;
if (typeof unsignedOrRadix === 'number') {
(radix = unsignedOrRadix), (unsignedOrRadix = false);
}
else {
unsigned = !!unsignedOrRadix;
}
radix ??= 10;
if (str.trim() !== str) {
throw new BSONError(`Input: '${str}' contains leading and/or trailing whitespace`);
}
if (!validateStringCharacters(str, radix)) {
throw new BSONError(`Input: '${str}' contains invalid characters for radix: ${radix}`);
}
const cleanedStr = removeLeadingZerosAndExplicitPlus(str);
const result = Long._fromString(cleanedStr, unsigned, radix);
if (result.toString(radix).toLowerCase() !== cleanedStr.toLowerCase()) {
throw new BSONError(`Input: ${str} is not representable as ${result.unsigned ? 'an unsigned' : 'a signed'} 64-bit Long ${radix != null ? `with radix: ${radix}` : ''}`);
}
return result;
}
static fromString(str, unsignedOrRadix, radix) {
let unsigned = false;
if (typeof unsignedOrRadix === 'number') {
(radix = unsignedOrRadix), (unsignedOrRadix = false);
}
else {
unsigned = !!unsignedOrRadix;
}
radix ??= 10;
if (str === 'NaN' && radix < 24) {
return Long.ZERO;
}
else if ((str === 'Infinity' || str === '+Infinity' || str === '-Infinity') && radix < 35) {
return Long.ZERO;
}
return Long._fromString(str, unsigned, radix);
}
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 === -2147483648 &&
divisor.low === -1 &&
divisor.high === -1) {
return this;
}