@phonecheck/phone-number-validator-js
Version:
Validate, parse, and enrich international phone numbers — geocoding, carrier lookup, and timezone resolution. Sync (Node) + async (serverless) APIs, platform adapters, and a CLI.
1,634 lines (1,529 loc) • 388 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
/**
* tiny-lru
*
* @copyright 2026 Jason Mulligan <jason.mulligan@avoidwork.com>
* @license BSD-3-Clause
* @version 13.0.0
*/
/**
* A high-performance Least Recently Used (LRU) cache implementation with optional TTL support.
* Items are automatically evicted when the cache reaches its maximum size,
* removing the least recently used items first. All core operations (get, set, delete) are O(1).
*
* @class LRU
*/
class LRU {
#stats;
#onEvict;
/**
* Creates a new LRU cache instance.
* Note: Constructor does not validate parameters. Use lru() factory function for parameter validation.
*
* @constructor
* @param {number} [max=0] - Maximum number of items to store. 0 means unlimited.
* @param {number} [ttl=0] - Time to live in milliseconds. 0 means no expiration.
* @param {boolean} [resetTTL=false] - Whether to reset TTL when updating existing items via set().
*/
constructor(max = 0, ttl = 0, resetTTL = false) {
this.first = null;
this.items = Object.create(null);
this.last = null;
this.max = max;
this.resetTTL = resetTTL;
this.size = 0;
this.ttl = ttl;
this.#stats = { hits: 0, misses: 0, sets: 0, deletes: 0, evictions: 0 };
this.#onEvict = null;
}
/**
* Removes all items from the cache.
*
* @returns {LRU} The LRU instance for method chaining.
*/
clear() {
for (let x = this.first; x !== null; ) {
const next = x.next;
x.prev = null;
x.next = null;
x = next;
}
this.first = null;
this.items = Object.create(null);
this.last = null;
this.size = 0;
this.#stats.hits = 0;
this.#stats.misses = 0;
this.#stats.sets = 0;
this.#stats.deletes = 0;
this.#stats.evictions = 0;
return this;
}
/**
* Removes an item from the cache by key.
*
* @param {string} key - The key of the item to delete.
* @returns {LRU} The LRU instance for method chaining.
*/
delete(key) {
const item = this.items[key];
if (item !== undefined) {
delete this.items[key];
this.size--;
this.#stats.deletes++;
this.#unlink(item);
item.prev = null;
item.next = null;
}
return this;
}
/**
* Returns an array of [key, value] pairs for the specified keys.
* When no keys provided, returns all entries in LRU order.
* When keys provided, order matches the input array.
*
* @param {string[]} [keys=this.keys()] - Array of keys to get entries for. Defaults to all keys.
* @returns {Array<Array<*>>} Array of [key, value] pairs.
*/
entries(keys) {
if (keys === undefined) {
keys = this.keys();
}
const result = Array.from({ length: keys.length });
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const item = this.items[key];
result[i] = [key, item !== undefined ? item.value : undefined];
}
return result;
}
/**
* Removes the least recently used item from the cache.
*
* @returns {LRU} The LRU instance for method chaining.
*/
evict() {
if (this.size === 0) {
return this;
}
const item = this.first;
delete this.items[item.key];
this.#stats.evictions++;
if (--this.size === 0) {
this.first = null;
this.last = null;
} else {
this.#unlink(item);
}
item.prev = null;
item.next = null;
if (this.#onEvict !== null) {
this.#onEvict({
key: item.key,
value: item.value,
expiry: item.expiry,
});
}
return this;
}
/**
* Returns the expiration timestamp for a given key.
*
* @param {string} key - The key to check expiration for.
* @returns {number|undefined} The expiration timestamp in milliseconds, or undefined if key doesn't exist.
*/
expiresAt(key) {
const item = this.items[key];
return item !== undefined ? item.expiry : undefined;
}
/**
* Checks if an item has expired.
*
* @param {Object} item - The cache item to check.
* @returns {boolean} True if the item has expired, false otherwise.
* @private
*/
#isExpired(item) {
if (this.ttl === 0 || item.expiry === 0) {
return false;
}
return item.expiry <= Date.now();
}
/**
* Retrieves a value from the cache by key without updating LRU order.
* Note: Does not perform TTL checks or remove expired items.
*
* @param {string} key - The key to retrieve.
* @returns {*} The value associated with the key, or undefined if not found.
*/
peek(key) {
const item = this.items[key];
return item !== undefined ? item.value : undefined;
}
/**
* Retrieves a value from the cache by key. Updates the item's position to most recently used.
*
* @param {string} key - The key to retrieve.
* @returns {*} The value associated with the key, or undefined if not found or expired.
*/
get(key) {
const item = this.items[key];
if (item !== undefined) {
if (!this.#isExpired(item)) {
this.moveToEnd(item);
this.#stats.hits++;
return item.value;
}
this.delete(key);
this.#stats.misses++;
return undefined;
}
this.#stats.misses++;
return undefined;
}
/**
* Checks if a key exists in the cache.
*
* @param {string} key - The key to check for.
* @returns {boolean} True if the key exists and is not expired, false otherwise.
*/
has(key) {
const item = this.items[key];
return item !== undefined && !this.#isExpired(item);
}
/**
* Unlinks an item from the doubly-linked list.
* Updates first/last pointers if needed.
* Does NOT clear the item's prev/next pointers or delete from items map.
*
* @private
*/
#unlink(item) {
if (item.prev !== null) {
item.prev.next = item.next;
}
if (item.next !== null) {
item.next.prev = item.prev;
}
if (this.first === item) {
this.first = item.next;
}
if (this.last === item) {
this.last = item.prev;
}
}
/**
* Efficiently moves an item to the end of the LRU list (most recently used position).
* This is an internal optimization method that avoids the overhead of the full set() operation
* when only LRU position needs to be updated.
*
* @param {Object} item - The cache item with prev/next pointers to reposition.
* @private
*/
moveToEnd(item) {
if (this.last === item) {
return;
}
this.#unlink(item);
item.prev = this.last;
item.next = null;
this.last.next = item;
this.last = item;
}
/**
* Returns an array of all keys in the cache, ordered from least to most recently used.
*
* @returns {string[]} Array of keys in LRU order.
*/
keys() {
const result = Array.from({ length: this.size });
let x = this.first;
let i = 0;
while (x !== null) {
result[i++] = x.key;
x = x.next;
}
return result;
}
/**
* Sets a value in the cache and returns any evicted item.
*
* @param {string} key - The key to set.
* @param {*} value - The value to store.
* @returns {Object|null} The evicted item (if any) with shape {key, value, expiry}, or null.
*/
setWithEvicted(key, value) {
let evicted = null;
let item = this.items[key];
if (item !== undefined) {
item.value = value;
if (this.resetTTL) {
item.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl;
}
this.moveToEnd(item);
} else {
if (this.max > 0 && this.size === this.max) {
evicted = {
key: this.first.key,
value: this.first.value,
expiry: this.first.expiry,
};
this.evict();
}
item = this.items[key] = {
expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl,
key: key,
prev: this.last,
next: null,
value,
};
if (++this.size === 1) {
this.first = item;
} else {
this.last.next = item;
}
this.last = item;
}
this.#stats.sets++;
return evicted;
}
/**
* Sets a value in the cache. Updates the item's position to most recently used.
*
* @param {string} key - The key to set.
* @param {*} value - The value to store.
* @returns {LRU} The LRU instance for method chaining.
*/
set(key, value) {
let item = this.items[key];
if (item !== undefined) {
item.value = value;
if (this.resetTTL) {
item.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl;
}
this.moveToEnd(item);
} else {
if (this.max > 0 && this.size === this.max) {
this.evict();
}
item = this.items[key] = {
expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl,
key: key,
prev: this.last,
next: null,
value,
};
if (++this.size === 1) {
this.first = item;
} else {
this.last.next = item;
}
this.last = item;
}
this.#stats.sets++;
return this;
}
/**
* Returns an array of all values in the cache for the specified keys.
* When no keys provided, returns all values in LRU order.
* When keys provided, order matches the input array.
*
* @param {string[]} [keys] - Array of keys to get values for. Defaults to all keys.
* @returns {Array<*>} Array of values corresponding to the keys.
*/
values(keys) {
if (keys === undefined) {
const result = Array.from({ length: this.size });
let i = 0;
for (let x = this.first; x !== null; x = x.next) {
result[i++] = x.value;
}
return result;
}
const result = Array.from({ length: keys.length });
for (let i = 0; i < keys.length; i++) {
const item = this.items[keys[i]];
result[i] = item !== undefined ? item.value : undefined;
}
return result;
}
/**
* Iterate over cache items in LRU order (least to most recent).
* Note: This method directly accesses items from the linked list without calling
* get() or peek(), so it does not update LRU order or check TTL expiration during iteration.
*
* @param {function(*, any, LRU): void} callback - Function to call for each item. Signature: callback(value, key, cache)
* @param {Object} [thisArg] - Value to use as `this` when executing callback.
* @returns {LRU} The LRU instance for method chaining.
*/
forEach(callback, thisArg) {
for (let x = this.first; x !== null; x = x.next) {
callback.call(thisArg, x.value, x.key, this);
}
return this;
}
/**
* Batch retrieve multiple items.
*
* @param {string[]} keys - Array of keys to retrieve.
* @returns {Object} Object mapping keys to values (undefined for missing/expired keys).
*/
getMany(keys) {
const result = Object.create(null);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
result[key] = this.get(key);
}
return result;
}
/**
* Batch existence check - returns true if ALL keys exist.
*
* @param {string[]} keys - Array of keys to check.
* @returns {boolean} True if all keys exist and are not expired.
*/
hasAll(keys) {
for (let i = 0; i < keys.length; i++) {
if (!this.has(keys[i])) {
return false;
}
}
return true;
}
/**
* Batch existence check - returns true if ANY key exists.
*
* @param {string[]} keys - Array of keys to check.
* @returns {boolean} True if any key exists and is not expired.
*/
hasAny(keys) {
for (let i = 0; i < keys.length; i++) {
if (this.has(keys[i])) {
return true;
}
}
return false;
}
/**
* Remove expired items without affecting LRU order.
* Unlike get(), this does not move items to the end.
*
* @returns {number} Number of expired items removed.
*/
cleanup() {
if (this.ttl === 0 || this.size === 0) {
return 0;
}
let removed = 0;
for (let x = this.first; x !== null; ) {
const next = x.next;
if (this.#isExpired(x)) {
const key = x.key;
if (this.items[key] !== undefined) {
delete this.items[key];
this.size--;
removed++;
this.#unlink(x);
x.prev = null;
x.next = null;
}
}
x = next;
}
if (removed > 0) {
this.#rebuildList();
}
return removed;
}
/**
* Serialize cache to JSON-compatible format.
*
* @returns {Array<{key: any, value: *, expiry: number}>} Array of cache items.
*/
toJSON() {
const result = [];
for (let x = this.first; x !== null; x = x.next) {
result.push({
key: x.key,
value: x.value,
expiry: x.expiry,
});
}
return result;
}
/**
* Get cache statistics.
*
* @returns {Object} Statistics object with hits, misses, sets, deletes, evictions counts.
*/
stats() {
return { ...this.#stats };
}
/**
* Register callback for evicted items.
*
* @param {function(Object): void} callback - Function called when item is evicted. Receives {key, value, expiry}.
* @returns {LRU} The LRU instance for method chaining.
*/
onEvict(callback) {
if (typeof callback !== "function") {
throw new TypeError("onEvict callback must be a function");
}
this.#onEvict = callback;
return this;
}
/**
* Get counts of items by TTL status.
*
* @returns {Object} Object with valid, expired, and noTTL counts.
*/
sizeByTTL() {
if (this.ttl === 0) {
return { valid: this.size, expired: 0, noTTL: this.size };
}
const now = Date.now();
let valid = 0;
let expired = 0;
let noTTL = 0;
for (let x = this.first; x !== null; x = x.next) {
if (x.expiry === 0) {
noTTL++;
valid++;
} else if (x.expiry > now) {
valid++;
} else {
expired++;
}
}
return { valid, expired, noTTL };
}
/**
* Get keys filtered by TTL status.
*
* @returns {Object} Object with valid, expired, and noTTL arrays of keys.
*/
keysByTTL() {
if (this.ttl === 0) {
return { valid: this.keys(), expired: [], noTTL: this.keys() };
}
const now = Date.now();
const valid = [];
const expired = [];
const noTTL = [];
for (let x = this.first; x !== null; x = x.next) {
if (x.expiry === 0) {
valid.push(x.key);
noTTL.push(x.key);
} else if (x.expiry > now) {
valid.push(x.key);
} else {
expired.push(x.key);
}
}
return { valid, expired, noTTL };
}
/**
* Get values filtered by TTL status.
*
* @returns {Object} Object with valid, expired, and noTTL arrays of values.
*/
valuesByTTL() {
const keysByTTL = this.keysByTTL();
return {
valid: this.values(keysByTTL.valid),
expired: this.values(keysByTTL.expired),
noTTL: this.values(keysByTTL.noTTL),
};
}
/**
* Rebuild the doubly-linked list after cleanup by deleting expired items.
* This removes nodes that were deleted during cleanup.
*
* @private
*/
#rebuildList() {
if (this.size === 0) {
this.first = null;
this.last = null;
return;
}
const keys = this.keys();
this.first = null;
this.last = null;
for (let i = 0; i < keys.length; i++) {
const item = this.items[keys[i]];
if (item !== null && item !== undefined) {
if (this.first === null) {
this.first = item;
item.prev = null;
} else {
item.prev = this.last;
this.last.next = item;
}
item.next = null;
this.last = item;
}
}
}
}
/**
* Factory function to create a new LRU cache instance with parameter validation.
*
* @function lru
* @param {number} [max=1000] - Maximum number of items to store. Must be >= 0. Use 0 for unlimited size.
* @param {number} [ttl=0] - Time to live in milliseconds. Must be >= 0. Use 0 for no expiration.
* @param {boolean} [resetTTL=false] - Whether to reset TTL when updating existing items via set().
* @returns {LRU} A new LRU cache instance.
* @throws {TypeError} When parameters are invalid (negative numbers or wrong types).
*/
function lru(max = 1000, ttl = 0, resetTTL = false) {
if (isNaN(max) || max < 0) {
throw new TypeError("Invalid max value");
}
if (isNaN(ttl) || ttl < 0) {
throw new TypeError("Invalid ttl value");
}
if (typeof resetTTL !== "boolean") {
throw new TypeError("Invalid resetTTL value");
}
return new LRU(max, ttl, resetTTL);
}
const DEFAULT_CACHE_SIZE = 100;
let cache = lru(DEFAULT_CACHE_SIZE);
let maxSize = DEFAULT_CACHE_SIZE;
function cacheGet(key) {
return cache.get(key);
}
function cacheSet(key, value) {
cache.set(key, value);
}
function clearCache() {
cache.clear();
}
function getCacheStats() {
return { size: cache.size, maxSize };
}
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 = 7;
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_UUID_NEW = 4;
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';
}
offset;
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)));
}
function nodejsSecureRandomBytes(byteLength) {
return crypto.getRandomValues(nodeJsByteUtils.allocate(byteLength));
}
const nodejsRandomBytes = (() => {
const { crypto } = globalThis;
if (crypto != null && typeof crypto.getRandomValues === 'function') {
return nodejsSecureRandomBytes;
}
else {
return nodejsMathRandomBytes;
}
})();
const nodeJsByteUtils = {
isUint8Array: isUint8Array,
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);
},
compare(a, b) {
return nodeJsByteUtils.toLocalBufferType(a).compare(b);
},
concat(list) {
return Buffer.concat(list);
},
copy(source, target, targetStart, sourceStart, sourceEnd) {
return nodeJsByteUtils
.toLocalBufferType(source)
.copy(target, targetStart ?? 0, sourceStart ?? 0, sourceEnd ?? source.length);
},
equals(a, b) {
return nodeJsByteUtils.toLocalBufferType(a).equals(b);
},
fromNumberArray(array) {
return Buffer.from(array);
},
fromBase64(base64) {
return Buffer.from(base64, 'base64');
},
fromUTF8(utf8) {
return Buffer.from(utf8, 'utf8');
},
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 = {
isUint8Array: isUint8Array,
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);
},
compare(uint8Array, otherUint8Array) {
if (uint8Array === otherUint8Array)
return 0;
const len = Math.min(uint8Array.length, otherUint8Array.length);
for (let i = 0; i < len; i++) {
if (uint8Array[i] < otherUint8Array[i])
return -1;
if (uint8Array[i] > otherUint8Array[i])
return 1;
}
if (uint8Array.length < otherUint8Array.length)
return -1;
if (uint8Array.length > otherUint8Array.length)
return 1;
return 0;
},
concat(uint8Arrays) {
if (uint8Arrays.length === 0)
return webByteUtils.allocate(0);
let totalLength = 0;
for (const uint8Array of uint8Arrays) {
totalLength += uint8Array.length;
}
const result = webByteUtils.allocate(totalLength);
let offset = 0;
for (const uint8Array of uint8Arrays) {
result.set(uint8Array, offset);
offset += uint8Array.length;
}
return result;
},
copy(source, target, targetStart, sourceStart, sourceEnd) {
if (sourceEnd !== undefined && sourceEnd < 0) {
throw new RangeError(`The value of "sourceEnd" is out of range. It must be >= 0. Received ${sourceEnd}`);
}
sourceEnd = sourceEnd ?? source.length;
if (sourceStart !== undefined && (sourceStart < 0 || sourceStart > sourceEnd)) {
throw new RangeError(`The value of "sourceStart" is out of range. It must be >= 0 and <= ${sourceEnd}. Received ${sourceStart}`);
}
sourceStart = sourceStart ?? 0;
if (targetStart !== undefined && targetStart < 0) {
throw new RangeError(`The value of "targetStart" is out of range. It must be >= 0. Received ${targetStart}`);
}
targetStart = targetStart ?? 0;
const srcSlice = source.subarray(sourceStart, sourceEnd);
const maxLen = Math.min(srcSlice.length, target.length - targetStart);
if (maxLen <= 0) {
return 0;
}
target.set(srcSlice.subarray(0, maxLen), targetStart);
return maxLen;
},
equals(uint8Array, otherUint8Array) {
if (uint8Array.byteLength !== otherUint8Array.byteLength) {
return false;
}
for (let i = 0; i < uint8Array.byteLength; i++) {
if (uint8Array[i] !== otherUint8Array[i]) {
return false;
}
}
return true;
},
fromNumberArray(array) {
return Uint8Array.from(array);
},
fromBase64(base64) {
return Uint8Array.from(atob(base64), c => c.charCodeAt(0));
},
fromUTF8(utf8) {
return new TextEncoder().encode(utf8);
},
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;
const bsonType = Symbol.for('@@mdb.bson.type');
class BSONValue {
get [bsonType]() {
return this._bsontype;
}
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 << 32n) + 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 = 0xffffffffn;
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 >> 32n) & 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';
}
static BSON_BINARY_SUBTYPE_DEFAULT = 0;
static BUFFER_SIZE = 256;
static SUBTYPE_DEFAULT = 0;
static SUBTYPE_FUNCTION = 1;
static SUBTYPE_BYTE_ARRAY = 2;
static SUBTYPE_UUID_OLD = 3;
static SUBTYPE_UUID = 4;
static SUBTYPE_MD5 = 5;
static SUBTYPE_ENCRYPTED = 6;
static SUBTYPE_COLUMN = 7;
static SUBTYPE_SENSITIVE = 8;
static SUBTYPE_VECTOR = 9;
static SUBTYPE_USER_DEFINED = 128;
static VECTOR_TYPE = Object.freeze({
Int8: 0x03,
Float32: 0x27,
PackedBit: 0x10
});
buffer;
sub_type;
position;
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);
}
}
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