var __getOwnPropNames = Object.getOwnPropertyNames; var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; // netlify/functions/node_modules/bson/lib/bson.cjs var require_bson = __commonJS({ "netlify/functions/node_modules/bson/lib/bson.cjs"(exports2) { "use strict"; var 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(regexp2) { return regexp2 instanceof RegExp || Object.prototype.toString.call(regexp2) === "[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; } } var BSON_MAJOR_VERSION = 6; var BSON_VERSION_SYMBOL = Symbol.for("@@mdb.bson.version"); var BSON_INT32_MAX = 2147483647; var BSON_INT32_MIN = -2147483648; var BSON_INT64_MAX = Math.pow(2, 63) - 1; var BSON_INT64_MIN = -Math.pow(2, 63); var JS_INT_MAX = Math.pow(2, 53); var JS_INT_MIN = -Math.pow(2, 53); var BSON_DATA_NUMBER = 1; var BSON_DATA_STRING = 2; var BSON_DATA_OBJECT = 3; var BSON_DATA_ARRAY = 4; var BSON_DATA_BINARY = 5; var BSON_DATA_UNDEFINED = 6; var BSON_DATA_OID = 7; var BSON_DATA_BOOLEAN = 8; var BSON_DATA_DATE = 9; var BSON_DATA_NULL = 10; var BSON_DATA_REGEXP = 11; var BSON_DATA_DBPOINTER = 12; var BSON_DATA_CODE = 13; var BSON_DATA_SYMBOL = 14; var BSON_DATA_CODE_W_SCOPE = 15; var BSON_DATA_INT = 16; var BSON_DATA_TIMESTAMP = 17; var BSON_DATA_LONG = 18; var BSON_DATA_DECIMAL128 = 19; var BSON_DATA_MIN_KEY = 255; var BSON_DATA_MAX_KEY = 127; var BSON_BINARY_SUBTYPE_DEFAULT = 0; var BSON_BINARY_SUBTYPE_UUID_NEW = 4; var 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 }); var BSONError = class 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; } }; var BSONVersionError = class extends BSONError { get name() { return "BSONVersionError"; } constructor() { super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`); } }; var BSONRuntimeError = class extends BSONError { get name() { return "BSONRuntimeError"; } constructor(message) { super(message); } }; var BSONOffsetError = class extends BSONError { get name() { return "BSONOffsetError"; } constructor(message, offset, options) { super(`${message}. offset: ${offset}`, options); this.offset = offset; } }; var TextDecoderFatal; var TextDecoderNonFatal; function parseUtf8(buffer2, start, end, fatal) { if (fatal) { TextDecoderFatal ??= new TextDecoder("utf8", { fatal: true }); try { return TextDecoderFatal.decode(buffer2.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(buffer2.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))); } var nodejsRandomBytes = (() => { try { return require("crypto").randomBytes; } catch { return nodejsMathRandomBytes; } })(); var 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(buffer2) { return nodeJsByteUtils.toLocalBufferType(buffer2).toString("base64"); }, fromISO88591(codePoints) { return Buffer.from(codePoints, "binary"); }, toISO88591(buffer2) { return nodeJsByteUtils.toLocalBufferType(buffer2).toString("binary"); }, fromHex(hex) { return Buffer.from(hex, "hex"); }, toHex(buffer2) { return nodeJsByteUtils.toLocalBufferType(buffer2).toString("hex"); }, toUTF8(buffer2, start, end, fatal) { const basicLatin = end - start <= 20 ? tryReadBasicLatin(buffer2, start, end) : null; if (basicLatin != null) { return basicLatin; } const string = nodeJsByteUtils.toLocalBufferType(buffer2).toString("utf8", start, end); if (fatal) { for (let i = 0; i < string.length; i++) { if (string.charCodeAt(i) === 65533) { parseUtf8(buffer2, start, end, true); break; } } } return string; }, utf8ByteLength(input) { return Buffer.byteLength(input, "utf8"); }, encodeUTF8Into(buffer2, source, byteOffset) { const latinBytesWritten = tryWriteBasicLatin(buffer2, source, byteOffset); if (latinBytesWritten != null) { return latinBytesWritten; } return nodeJsByteUtils.toLocalBufferType(buffer2).write(source, byteOffset, void 0, "utf8"); }, randomBytes: nodejsRandomBytes, swap32(buffer2) { return nodeJsByteUtils.toLocalBufferType(buffer2).swap32(); } }; function isReactNative() { const { navigator: navigator2 } = globalThis; return typeof navigator2 === "object" && navigator2.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))); } var webRandomBytes = (() => { const { crypto } = globalThis; if (crypto != null && typeof crypto.getRandomValues === "function") { return (byteLength) => { return crypto.getRandomValues(webByteUtils.allocate(byteLength)); }; } else { if (isReactNative()) { const { console: console2 } = globalThis; console2?.warn?.("BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values."); } return webMathRandomBytes; } })(); var HEX_DIGIT = /(\d|[a-f])/i; var 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) & 255); }, 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 buffer2 = []; 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); buffer2.push(hexDigit); } return Uint8Array.from(buffer2); }, 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(buffer2) { if (buffer2.length % 4 !== 0) { throw new RangeError("Buffer size must be a multiple of 32-bits"); } for (let i = 0; i < buffer2.length; i += 4) { const byte0 = buffer2[i]; const byte1 = buffer2[i + 1]; const byte2 = buffer2[i + 2]; const byte3 = buffer2[i + 3]; buffer2[i] = byte3; buffer2[i + 1] = byte2; buffer2[i + 2] = byte1; buffer2[i + 3] = byte0; } return buffer2; } }; var hasGlobalBuffer = typeof Buffer === "function" && Buffer.prototype?._isBuffer !== true; var ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils; var BSONValue = class { get [BSON_VERSION_SYMBOL]() { return BSON_MAJOR_VERSION; } [Symbol.for("nodejs.util.inspect.custom")](depth, options, inspect) { return this.inspect(depth, options, inspect); } }; var FLOAT = new Float64Array(1); var FLOAT_BYTES = new Uint8Array(FLOAT.buffer, 0, 8); FLOAT[0] = -1; var isBigEndian = FLOAT_BYTES[7] === 0; var 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(4294967295); 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; } }; var Binary = class _Binary extends BSONValue { get _bsontype() { return "Binary"; } constructor(buffer2, subType) { super(); if (!(buffer2 == null) && typeof buffer2 === "string" && !ArrayBuffer.isView(buffer2) && !isAnyArrayBuffer(buffer2) && !Array.isArray(buffer2)) { throw new BSONError("Binary can only be constructed from Uint8Array or number[]"); } this.sub_type = subType ?? _Binary.BSON_BINARY_SUBTYPE_DEFAULT; if (buffer2 == null) { this.buffer = ByteUtils.allocate(_Binary.BUFFER_SIZE); this.position = 0; } else { this.buffer = Array.isArray(buffer2) ? ByteUtils.fromNumberArray(buffer2) : ByteUtils.toLocalBufferType(buffer2); 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 buffer2 = ByteUtils.allocate(array.byteLength + 2); buffer2[0] = _Binary.VECTOR_TYPE.Int8; buffer2[1] = 0; const intBytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength); buffer2.set(intBytes, 2); const bin = new this(buffer2, 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 buffer2 = ByteUtils.allocate(array.byteLength + 2); buffer2[0] = _Binary.VECTOR_TYPE.PackedBit; buffer2[1] = padding; buffer2.set(array, 2); const bin = new this(buffer2, 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: 3, Float32: 39, PackedBit: 16 }); 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}`); } } var UUID_BYTE_LENGTH = 16; var UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i; var UUID_WITH_DASHES = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i; var UUID = 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] & 15 | 64; bytes[8] = bytes[8] & 63 | 128; 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 buffer2 = _UUID.bytesFromString(hexString); return new _UUID(buffer2); } 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)})`; } }; var Code = 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"); } var DBRef = 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; } var wasm = void 0; 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 { } var TWO_PWR_16_DBL = 1 << 16; var TWO_PWR_24_DBL = 1 << 24; var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; var INT_CACHE = {}; var UINT_CACHE = {}; var MAX_INT64_STRING_LENGTH = 20; var DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/; var Long = 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(4294967295); 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 & 65535; const a16 = this.low >>> 16; const a00 = this.low & 65535; const b48 = addend.high >>> 16; const b32 = addend.high & 65535; const b16 = addend.low >>> 16; const b00 = addend.low & 65535; let c48 = 0, c32 = 0, c16 = 0, c00 = 0; c00 += a00 + b00; c16 += c00 >>> 16; c00 &= 65535; c16 += a16 + b16; c32 += c16 >>> 16; c16 &= 65535; c32 += a32 + b32; c48 += c32 >>> 16; c32 &= 65535; c48 += a48 + b48; c48 &= 65535; 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; } 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 & 65535; const a16 = this.low >>> 16; const a00 = this.low & 65535; const b48 = multiplier.high >>> 16; const b32 = multiplier.high & 65535; const b16 = multiplier.low >>> 16; const b00 = multiplier.low & 65535; let c48 = 0, c32 = 0, c16 = 0, c00 = 0; c00 += a00 * b00; c16 += c00 >>> 16; c00 &= 65535; c16 += a16 * b00; c32 += c16 >>> 16; c16 &= 65535; c16 += a00 * b16; c32 += c16 >>> 16; c16 &= 65535; c32 += a32 * b00; c48 += c32 >>> 16; c32 &= 65535; c32 += a16 * b16; c48 += c32 >>> 16; c32 &= 65535; c32 += a00 * b32; c48 += c32 >>> 16; c32 &= 65535; c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; c48 &= 65535; 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 & 255, lo >>> 8 & 255, lo >>> 16 & 255, lo >>> 24, hi & 255, hi >>> 8 & 255, hi >>> 16 & 255, hi >>> 24 ]; } toBytesBE() { const hi = this.high, lo = this.low; return [ hi >>> 24, hi >>> 16 & 255, hi >>> 8 & 255, hi & 255, lo >>> 24, lo >>> 16 & 255, lo >>> 8 & 255, lo & 255 ]; } 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; } inspect(depth, options, inspect) { inspect ??= defaultInspect; const longVal = inspect(this.toString(), options); const unsignedVal = this.unsigned ? `, ${inspect(this.unsigned, options)}` : ""; return `new Long(${longVal}${unsignedVal})`; } }; Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); Long.MAX_UNSIGNED_VALUE = Long.fromBits(4294967295 | 0, 4294967295 | 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(4294967295 | 0, 2147483647 | 0, false); Long.MIN_VALUE = Long.fromBits(0, 2147483648 | 0, false); var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; var EXPONENT_MAX = 6111; var EXPONENT_MIN = -6176; var EXPONENT_BIAS = 6176; var MAX_DIGITS = 34; var NAN_BUFFER = ByteUtils.fromNumberArray([ 124, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ].reverse()); var INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([ 248, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ].reverse()); var INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([ 120, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ].reverse()); var EXPONENT_REGEX = /^([-+])?(\d+)?$/; var COMBINATION_MASK = 31; var EXPONENT_MASK = 16383; var COMBINATION_INFINITY = 30; var COMBINATION_NAN = 31; function isDigit(value) { return !isNaN(parseInt(value, 10)); } function divideu128(value) { const DIVISOR = Long.fromNumber(1e3 * 1e3 * 1e3); 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}`); } var Decimal128 = class _Decimal128 extends BSONValue { get _bsontype() { return "Decimal128"; } constructor(bytes) { super(); if (typeof bytes === "string") { this.bytes = _Decimal128.fromString(bytes).bytes; } else if (bytes instanceof Uint8Array || 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) { return _Decimal128._fromString(representation, { allowRounding: false }); } static fromStringWithRounding(representation) { return _Decimal128._fromString(representation, { allowRounding: true }); } static _fromString(representation, options) { let isNegative = false; let sawSign = false; let sawRadix = false; let foundNonZero = false; let significantDigits = 0; let nDigitsRead = 0; let nDigits = 0; let radixPosition = 0; let firstNonZero = 0; const digits = [0]; let nDigitsStored = 0; let digitsInsert = 0; let lastDigit = 0; let exponent = 0; let significandHigh = new Long(0, 0); let significandLow = new Long(0, 0); let biasedExponent = 0; let index = 0; if (representation.length >= 7e3) { throw new BSONError("" + representation + " not a valid Decimal128 string"); } const stringMatch = representation.match(PARSE_STRING_REGEXP); const infMatch = representation.match(PARSE_INF_REGEXP); const nanMatch = representation.match(PARSE_NAN_REGEXP); if (!stringMatch && !infMatch && !nanMatch || representation.length === 0) { throw new BSONError("" + representation + " not a valid Decimal128 string"); } if (stringMatch) { const unsignedNumber = stringMatch[2]; const e = stringMatch[4]; const expSign = stringMatch[5]; const expNumber = stringMatch[6]; if (e && expNumber === void 0) invalidErr(representation, "missing exponent power"); if (e && unsignedNumber === void 0) invalidErr(representation, "missing exponent base"); if (e === void 0 && (expSign || expNumber)) { invalidErr(representation, "missing e before exponent"); } } if (representation[index] === "+" || representation[index] === "-") { sawSign = true; isNegative = representation[index++] === "-"; } if (!isDigit(representation[index]) && representation[index] !== ".") { if (representation[index] === "i" || representation[index] === "I") { return new _Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); } else if (representation[index] === "N") { return new _Decimal128(NAN_BUFFER); } } while (isDigit(representation[index]) || representation[index] === ".") { if (representation[index] === ".") { if (sawRadix) invalidErr(representation, "contains multiple periods"); sawRadix = true; index = index + 1; continue; } if (nDigitsStored < MAX_DIGITS) { if (representation[index] !== "0" || foundNonZero) { if (!foundNonZero) { firstNonZero = nDigitsRead; } foundNonZero = true; digits[digitsInsert++] = parseInt(representation[index], 10); nDigitsStored = nDigitsStored + 1; } } if (foundNonZero) nDigits = nDigits + 1; if (sawRadix) radixPosition = radixPosition + 1; nDigitsRead = nDigitsRead + 1; index = index + 1; } if (sawRadix && !nDigitsRead) throw new BSONError("" + representation + " not a valid Decimal128 string"); if (representation[index] === "e" || representation[index] === "E") { const match = representation.substr(++index).match(EXPONENT_REGEX); if (!match || !match[2]) return new _Decimal128(NAN_BUFFER); exponent = parseInt(match[0], 10); index = index + match[0].length; } if (representation[index]) return new _Decimal128(NAN_BUFFER); if (!nDigitsStored) { digits[0] = 0; nDigits = 1; nDigitsStored = 1; significantDigits = 0; } else { lastDigit = nDigitsStored - 1; significantDigits = nDigits; if (significantDigits !== 1) { while (representation[firstNonZero + significantDigits - 1 + Number(sawSign) + Number(sawRadix)] === "0") { significantDigits = significantDigits - 1; } } } if (exponent <= radixPosition && radixPosition > exponent + (1 << 14)) { exponent = EXPONENT_MIN; } else { exponent = exponent - radixPosition; } while (exponent > EXPONENT_MAX) { lastDigit = lastDigit + 1; if (lastDigit >= MAX_DIGITS) { if (significantDigits === 0) { exponent = EXPONENT_MAX; break; } invalidErr(representation, "overflow"); } exponent = exponent - 1; } if (options.allowRounding) { while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { if (lastDigit === 0 && significantDigits < nDigitsStored) { exponent = EXPONENT_MIN; significantDigits = 0; break; } if (nDigitsStored < nDigits) { nDigits = nDigits - 1; } else { lastDigit = lastDigit - 1; } if (exponent < EXPONENT_MAX) { exponent = exponent + 1; } else { const digitsString = digits.join(""); if (digitsString.match(/^0+$/)) { exponent = EXPONENT_MAX; break; } invalidErr(representation, "overflow"); } } if (lastDigit + 1 < significantDigits) { let endOfString = nDigitsRead; if (sawRadix) { firstNonZero = firstNonZero + 1; endOfString = endOfString + 1; } if (sawSign) { firstNonZero = firstNonZero + 1; endOfString = endOfString + 1; } const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); let roundBit = 0; if (roundDigit >= 5) { roundBit = 1; if (roundDigit === 5) { roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; for (let i = firstNonZero + lastDigit + 2; i < endOfString; i++) { if (parseInt(representation[i], 10)) { roundBit = 1; break; } } } } if (roundBit) { let dIdx = lastDigit; for (; dIdx >= 0; dIdx--) { if (++digits[dIdx] > 9) { digits[dIdx] = 0; if (dIdx === 0) { if (exponent < EXPONENT_MAX) { exponent = exponent + 1; digits[dIdx] = 1; } else { return new _Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); } } } else { break; } } } } } else { while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { if (lastDigit === 0) { if (significantDigits === 0) { exponent = EXPONENT_MIN; break; } invalidErr(representation, "exponent underflow"); } if (nDigitsStored < nDigits) { if (representation[nDigits - 1 + Number(sawSign) + Number(sawRadix)] !== "0" && significantDigits !== 0) { invalidErr(representation, "inexact rounding"); } nDigits = nDigits - 1; } else { if (digits[lastDigit] !== 0) { invalidErr(representation, "inexact rounding"); } lastDigit = lastDigit - 1; } if (exponent < EXPONENT_MAX) { exponent = exponent + 1; } else { invalidErr(representation, "overflow"); } } if (lastDigit + 1 < significantDigits) { if (sawRadix) { firstNonZero = firstNonZero + 1; } if (sawSign) { firstNonZero = firstNonZero + 1; } const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); if (roundDigit !== 0) { invalidErr(representation, "inexact rounding"); } } } significandHigh = Long.fromNumber(0); significandLow = Long.fromNumber(0); if (significantDigits === 0) { significandHigh = Long.fromNumber(0); significandLow = Long.fromNumber(0); } else if (lastDigit < 17) { let dIdx = 0; significandLow = Long.fromNumber(digits[dIdx++]); significandHigh = new Long(0, 0); for (; dIdx <= lastDigit; dIdx++) { significandLow = significandLow.multiply(Long.fromNumber(10)); significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); } } else { let dIdx = 0; significandHigh = Long.fromNumber(digits[dIdx++]); for (; dIdx <= lastDigit - 17; dIdx++) { significandHigh = significandHigh.multiply(Long.fromNumber(10)); significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); } significandLow = Long.fromNumber(digits[dIdx++]); for (; dIdx <= lastDigit; dIdx++) { significandLow = significandLow.multiply(Long.fromNumber(10)); significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); } } const significand = multiply64x2(significandHigh, Long.fromString("100000000000000000")); significand.low = significand.low.add(significandLow); if (lessThan(significand.low, significandLow)) { significand.high = significand.high.add(Long.fromNumber(1)); } biasedExponent = exponent + EXPONENT_BIAS; const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) { dec.high = dec.high.or(Long.fromNumber(3).shiftLeft(61)); dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(16383).shiftLeft(47))); dec.high = dec.high.or(significand.high.and(Long.fromNumber(140737488355327))); } else { dec.high = dec.high.or(Long.fromNumber(biasedExponent & 16383).shiftLeft(49)); dec.high = dec.high.or(significand.high.and(Long.fromNumber(562949953421311))); } dec.low = significand.low; if (isNegative) { dec.high = dec.high.or(Long.fromString("9223372036854775808")); } const buffer2 = ByteUtils.allocateUnsafe(16); index = 0; buffer2[index++] = dec.low.low & 255; buffer2[index++] = dec.low.low >> 8 & 255; buffer2[index++] = dec.low.low >> 16 & 255; buffer2[index++] = dec.low.low >> 24 & 255; buffer2[index++] = dec.low.high & 255; buffer2[index++] = dec.low.high >> 8 & 255; buffer2[index++] = dec.low.high >> 16 & 255; buffer2[index++] = dec.low.high >> 24 & 255; buffer2[index++] = dec.high.low & 255; buffer2[index++] = dec.high.low >> 8 & 255; buffer2[index++] = dec.high.low >> 16 & 255; buffer2[index++] = dec.high.low >> 24 & 255; buffer2[index++] = dec.high.high & 255; buffer2[index++] = dec.high.high >> 8 & 255; buffer2[index++] = dec.high.high >> 16 & 255; buffer2[index++] = dec.high.high >> 24 & 255; return new _Decimal128(buffer2); } toString() { let biased_exponent; let significand_digits = 0; const significand = new Array(36); for (let i = 0; i < significand.length; i++) significand[i] = 0; let index = 0; let is_zero = false; let significand_msb; let significand128 = { parts: [0, 0, 0, 0] }; let j, k; const string = []; index = 0; const buffer2 = this.bytes; const low = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24; const midl = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24; const midh = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24; const high = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24; index = 0; const dec = { low: new Long(low, midl), high: new Long(midh, high) }; if (dec.high.lessThan(Long.ZERO)) { string.push("-"); } const combination = high >> 26 & COMBINATION_MASK; if (combination >> 3 === 3) { if (combination === COMBINATION_INFINITY) { return string.join("") + "Infinity"; } else if (combination === COMBINATION_NAN) { return "NaN"; } else { biased_exponent = high >> 15 & EXPONENT_MASK; significand_msb = 8 + (high >> 14 & 1); } } else { significand_msb = high >> 14 & 7; biased_exponent = high >> 17 & EXPONENT_MASK; } const exponent = biased_exponent - EXPONENT_BIAS; significand128.parts[0] = (high & 16383) + ((significand_msb & 15) << 14); significand128.parts[1] = midh; significand128.parts[2] = midl; significand128.parts[3] = low; if (significand128.parts[0] === 0 && significand128.parts[1] === 0 && significand128.parts[2] === 0 && significand128.parts[3] === 0) { is_zero = true; } else { for (k = 3; k >= 0; k--) { let least_digits = 0; const result = divideu128(significand128); significand128 = result.quotient; least_digits = result.rem.low; if (!least_digits) continue; for (j = 8; j >= 0; j--) { significand[k * 9 + j] = least_digits % 10; least_digits = Math.floor(least_digits / 10); } } } if (is_zero) { significand_digits = 1; significand[index] = 0; } else { significand_digits = 36; while (!significand[index]) { significand_digits = significand_digits - 1; index = index + 1; } } const scientific_exponent = significand_digits - 1 + exponent; if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { if (significand_digits > 34) { string.push(`${0}`); if (exponent > 0) string.push(`E+${exponent}`); else if (exponent < 0) string.push(`E${exponent}`); return string.join(""); } string.push(`${significand[index++]}`); significand_digits = significand_digits - 1; if (significand_digits) { string.push("."); } for (let i = 0; i < significand_digits; i++) { string.push(`${significand[index++]}`); } string.push("E"); if (scientific_exponent > 0) { string.push(`+${scientific_exponent}`); } else { string.push(`${scientific_exponent}`); } } else { if (exponent >= 0) { for (let i = 0; i < significand_digits; i++) { string.push(`${significand[index++]}`); } } else { let radix_position = significand_digits + exponent; if (radix_position > 0) { for (let i = 0; i < radix_position; i++) { string.push(`${significand[index++]}`); } } else { string.push("0"); } string.push("."); while (radix_position++ < 0) { string.push("0"); } for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { string.push(`${significand[index++]}`); } } } return string.join(""); } toJSON() { return { $numberDecimal: this.toString() }; } toExtendedJSON() { return { $numberDecimal: this.toString() }; } static fromExtendedJSON(doc) { return _Decimal128.fromString(doc.$numberDecimal); } inspect(depth, options, inspect) { inspect ??= defaultInspect; const d128string = inspect(this.toString(), options); return `new Decimal128(${d128string})`; } }; var Double = class _Double extends BSONValue { get _bsontype() { return "Double"; } constructor(value) { super(); if (value instanceof Number) { value = value.valueOf(); } this.value = +value; } static fromString(value) { const coercedValue = Number(value); if (value === "NaN") return new _Double(NaN); if (value === "Infinity") return new _Double(Infinity); if (value === "-Infinity") return new _Double(-Infinity); if (!Number.isFinite(coercedValue)) { throw new BSONError(`Input: ${value} is not representable as a Double`); } if (value.trim() !== value) { throw new BSONError(`Input: '${value}' contains whitespace`); } if (value === "") { throw new BSONError(`Input is an empty string`); } if (/[^-0-9.+eE]/.test(value)) { throw new BSONError(`Input: '${value}' is not in decimal or exponential notation`); } return new _Double(coercedValue); } valueOf() { return this.value; } toJSON() { return this.value; } toString(radix) { return this.value.toString(radix); } toExtendedJSON(options) { if (options && (options.legacy || options.relaxed && isFinite(this.value))) { return this.value; } if (Object.is(Math.sign(this.value), -0)) { return { $numberDouble: "-0.0" }; } return { $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString() }; } static fromExtendedJSON(doc, options) { const doubleValue = parseFloat(doc.$numberDouble); return options && options.relaxed ? doubleValue : new _Double(doubleValue); } inspect(depth, options, inspect) { inspect ??= defaultInspect; return `new Double(${inspect(this.value, options)})`; } }; var Int32 = class _Int32 extends BSONValue { get _bsontype() { return "Int32"; } constructor(value) { super(); if (value instanceof Number) { value = value.valueOf(); } this.value = +value | 0; } static fromString(value) { const cleanedValue = removeLeadingZerosAndExplicitPlus(value); const coercedValue = Number(value); if (BSON_INT32_MAX < coercedValue) { throw new BSONError(`Input: '${value}' is larger than the maximum value for Int32`); } else if (BSON_INT32_MIN > coercedValue) { throw new BSONError(`Input: '${value}' is smaller than the minimum value for Int32`); } else if (!Number.isSafeInteger(coercedValue)) { throw new BSONError(`Input: '${value}' is not a safe integer`); } else if (coercedValue.toString() !== cleanedValue) { throw new BSONError(`Input: '${value}' is not a valid Int32 string`); } return new _Int32(coercedValue); } valueOf() { return this.value; } toString(radix) { return this.value.toString(radix); } toJSON() { return this.value; } toExtendedJSON(options) { if (options && (options.relaxed || options.legacy)) return this.value; return { $numberInt: this.value.toString() }; } static fromExtendedJSON(doc, options) { return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new _Int32(doc.$numberInt); } inspect(depth, options, inspect) { inspect ??= defaultInspect; return `new Int32(${inspect(this.value, options)})`; } }; var MaxKey = class _MaxKey extends BSONValue { get _bsontype() { return "MaxKey"; } toExtendedJSON() { return { $maxKey: 1 }; } static fromExtendedJSON() { return new _MaxKey(); } inspect() { return "new MaxKey()"; } }; var MinKey = class _MinKey extends BSONValue { get _bsontype() { return "MinKey"; } toExtendedJSON() { return { $minKey: 1 }; } static fromExtendedJSON() { return new _MinKey(); } inspect() { return "new MinKey()"; } }; var PROCESS_UNIQUE = null; var __idCache = /* @__PURE__ */ new WeakMap(); var ObjectId2 = class _ObjectId extends BSONValue { get _bsontype() { return "ObjectId"; } constructor(inputId) { super(); let workingId; if (typeof inputId === "object" && inputId && "id" in inputId) { if (typeof inputId.id !== "string" && !ArrayBuffer.isView(inputId.id)) { throw new BSONError("Argument passed in must have an id that is of type string or Buffer"); } if ("toHexString" in inputId && typeof inputId.toHexString === "function") { workingId = ByteUtils.fromHex(inputId.toHexString()); } else { workingId = inputId.id; } } else { workingId = inputId; } if (workingId == null || typeof workingId === "number") { this.buffer = _ObjectId.generate(typeof workingId === "number" ? workingId : void 0); } else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { this.buffer = ByteUtils.toLocalBufferType(workingId); } else if (typeof workingId === "string") { if (_ObjectId.validateHexString(workingId)) { this.buffer = ByteUtils.fromHex(workingId); if (_ObjectId.cacheHexString) { __idCache.set(this, workingId); } } else { throw new BSONError("input must be a 24 character hex string, 12 byte Uint8Array, or an integer"); } } else { throw new BSONError("Argument passed in does not match the accepted types"); } } get id() { return this.buffer; } set id(value) { this.buffer = value; if (_ObjectId.cacheHexString) { __idCache.set(this, ByteUtils.toHex(value)); } } static validateHexString(string) { if (string?.length !== 24) return false; for (let i = 0; i < 24; i++) { const char = string.charCodeAt(i); if (char >= 48 && char <= 57 || char >= 97 && char <= 102 || char >= 65 && char <= 70) { continue; } return false; } return true; } toHexString() { if (_ObjectId.cacheHexString) { const __id = __idCache.get(this); if (__id) return __id; } const hexString = ByteUtils.toHex(this.id); if (_ObjectId.cacheHexString) { __idCache.set(this, hexString); } return hexString; } static getInc() { return _ObjectId.index = (_ObjectId.index + 1) % 16777215; } static generate(time) { if ("number" !== typeof time) { time = Math.floor(Date.now() / 1e3); } const inc = _ObjectId.getInc(); const buffer2 = ByteUtils.allocateUnsafe(12); NumberUtils.setInt32BE(buffer2, 0, time); if (PROCESS_UNIQUE === null) { PROCESS_UNIQUE = ByteUtils.randomBytes(5); } buffer2[4] = PROCESS_UNIQUE[0]; buffer2[5] = PROCESS_UNIQUE[1]; buffer2[6] = PROCESS_UNIQUE[2]; buffer2[7] = PROCESS_UNIQUE[3]; buffer2[8] = PROCESS_UNIQUE[4]; buffer2[11] = inc & 255; buffer2[10] = inc >> 8 & 255; buffer2[9] = inc >> 16 & 255; return buffer2; } toString(encoding) { if (encoding === "base64") return ByteUtils.toBase64(this.id); if (encoding === "hex") return this.toHexString(); return this.toHexString(); } toJSON() { return this.toHexString(); } static is(variable) { return variable != null && typeof variable === "object" && "_bsontype" in variable && variable._bsontype === "ObjectId"; } equals(otherId) { if (otherId === void 0 || otherId === null) { return false; } if (_ObjectId.is(otherId)) { return this.buffer[11] === otherId.buffer[11] && ByteUtils.equals(this.buffer, otherId.buffer); } if (typeof otherId === "string") { return otherId.toLowerCase() === this.toHexString(); } if (typeof otherId === "object" && typeof otherId.toHexString === "function") { const otherIdString = otherId.toHexString(); const thisIdString = this.toHexString(); return typeof otherIdString === "string" && otherIdString.toLowerCase() === thisIdString; } return false; } getTimestamp() { const timestamp = /* @__PURE__ */ new Date(); const time = NumberUtils.getUint32BE(this.buffer, 0); timestamp.setTime(Math.floor(time) * 1e3); return timestamp; } static createPk() { return new _ObjectId(); } serializeInto(uint8array, index) { uint8array[index] = this.buffer[0]; uint8array[index + 1] = this.buffer[1]; uint8array[index + 2] = this.buffer[2]; uint8array[index + 3] = this.buffer[3]; uint8array[index + 4] = this.buffer[4]; uint8array[index + 5] = this.buffer[5]; uint8array[index + 6] = this.buffer[6]; uint8array[index + 7] = this.buffer[7]; uint8array[index + 8] = this.buffer[8]; uint8array[index + 9] = this.buffer[9]; uint8array[index + 10] = this.buffer[10]; uint8array[index + 11] = this.buffer[11]; return 12; } static createFromTime(time) { const buffer2 = ByteUtils.allocate(12); for (let i = 11; i >= 4; i--) buffer2[i] = 0; NumberUtils.setInt32BE(buffer2, 0, time); return new _ObjectId(buffer2); } static createFromHexString(hexString) { if (hexString?.length !== 24) { throw new BSONError("hex string must be 24 characters"); } return new _ObjectId(ByteUtils.fromHex(hexString)); } static createFromBase64(base64) { if (base64?.length !== 16) { throw new BSONError("base64 string must be 16 characters"); } return new _ObjectId(ByteUtils.fromBase64(base64)); } static isValid(id) { if (id == null) return false; if (typeof id === "string") return _ObjectId.validateHexString(id); try { new _ObjectId(id); return true; } catch { return false; } } toExtendedJSON() { if (this.toHexString) return { $oid: this.toHexString() }; return { $oid: this.toString("hex") }; } static fromExtendedJSON(doc) { return new _ObjectId(doc.$oid); } isCached() { return _ObjectId.cacheHexString && __idCache.has(this); } inspect(depth, options, inspect) { inspect ??= defaultInspect; return `new ObjectId(${inspect(this.toHexString(), options)})`; } }; ObjectId2.index = Math.floor(Math.random() * 16777215); function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) { let totalLength = 4 + 1; if (Array.isArray(object)) { for (let i = 0; i < object.length; i++) { totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); } } else { if (typeof object?.toBSON === "function") { object = object.toBSON(); } for (const key of Object.keys(object)) { totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); } } return totalLength; } function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) { if (typeof value?.toBSON === "function") { value = value.toBSON(); } switch (typeof value) { case "string": return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1; case "number": if (Math.floor(value) === value && value >= JS_INT_MIN && value <= JS_INT_MAX) { if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1); } else { return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); } } else { return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); } case "undefined": if (isArray || !ignoreUndefined) return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; return 0; case "boolean": return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1); case "object": if (value != null && typeof value._bsontype === "string" && value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) { throw new BSONVersionError(); } else if (value == null || value._bsontype === "MinKey" || value._bsontype === "MaxKey") { return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; } else if (value._bsontype === "ObjectId") { return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1); } else if (value instanceof Date || isDate(value)) { return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); } else if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer || isAnyArrayBuffer(value)) { return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength; } else if (value._bsontype === "Long" || value._bsontype === "Double" || value._bsontype === "Timestamp") { return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); } else if (value._bsontype === "Decimal128") { return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1); } else if (value._bsontype === "Code") { if (value.scope != null && Object.keys(value.scope).length > 0) { return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + 4 + 4 + ByteUtils.utf8ByteLength(value.code.toString()) + 1 + internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); } else { return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + 4 + ByteUtils.utf8ByteLength(value.code.toString()) + 1; } } else if (value._bsontype === "Binary") { const binary = value; if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1 + 4); } else { return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1); } } else if (value._bsontype === "Symbol") { return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + ByteUtils.utf8ByteLength(value.value) + 4 + 1 + 1; } else if (value._bsontype === "DBRef") { const ordered_values = Object.assign({ $ref: value.collection, $id: value.oid }, value.fields); if (value.db != null) { ordered_values["$db"] = value.db; } return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); } else if (value instanceof RegExp || isRegExp(value)) { return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + ByteUtils.utf8ByteLength(value.source) + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; } else if (value._bsontype === "BSONRegExp") { return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + ByteUtils.utf8ByteLength(value.pattern) + 1 + ByteUtils.utf8ByteLength(value.options) + 1; } else { return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1; } case "function": if (serializeFunctions) { return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + 4 + ByteUtils.utf8ByteLength(value.toString()) + 1; } return 0; case "bigint": return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); case "symbol": return 0; default: throw new BSONError(`Unrecognized JS type: ${typeof value}`); } } function alphabetize(str) { return str.split("").sort().join(""); } var BSONRegExp = class _BSONRegExp extends BSONValue { get _bsontype() { return "BSONRegExp"; } constructor(pattern, options) { super(); this.pattern = pattern; this.options = alphabetize(options ?? ""); if (this.pattern.indexOf("\0") !== -1) { throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`); } if (this.options.indexOf("\0") !== -1) { throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`); } for (let i = 0; i < this.options.length; i++) { if (!(this.options[i] === "i" || this.options[i] === "m" || this.options[i] === "x" || this.options[i] === "l" || this.options[i] === "s" || this.options[i] === "u")) { throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`); } } } static parseOptions(options) { return options ? options.split("").sort().join("") : ""; } toExtendedJSON(options) { options = options || {}; if (options.legacy) { return { $regex: this.pattern, $options: this.options }; } return { $regularExpression: { pattern: this.pattern, options: this.options } }; } static fromExtendedJSON(doc) { if ("$regex" in doc) { if (typeof doc.$regex !== "string") { if (doc.$regex._bsontype === "BSONRegExp") { return doc; } } else { return new _BSONRegExp(doc.$regex, _BSONRegExp.parseOptions(doc.$options)); } } if ("$regularExpression" in doc) { return new _BSONRegExp(doc.$regularExpression.pattern, _BSONRegExp.parseOptions(doc.$regularExpression.options)); } throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`); } inspect(depth, options, inspect) { const stylize = getStylizeFunction(options) ?? ((v) => v); inspect ??= defaultInspect; const pattern = stylize(inspect(this.pattern), "regexp"); const flags = stylize(inspect(this.options), "regexp"); return `new BSONRegExp(${pattern}, ${flags})`; } }; var BSONSymbol = class _BSONSymbol extends BSONValue { get _bsontype() { return "BSONSymbol"; } constructor(value) { super(); this.value = value; } valueOf() { return this.value; } toString() { return this.value; } toJSON() { return this.value; } toExtendedJSON() { return { $symbol: this.value }; } static fromExtendedJSON(doc) { return new _BSONSymbol(doc.$symbol); } inspect(depth, options, inspect) { inspect ??= defaultInspect; return `new BSONSymbol(${inspect(this.value, options)})`; } }; var LongWithoutOverridesClass = Long; var Timestamp = class _Timestamp extends LongWithoutOverridesClass { get _bsontype() { return "Timestamp"; } get i() { return this.low >>> 0; } get t() { return this.high >>> 0; } constructor(low) { if (low == null) { super(0, 0, true); } else if (typeof low === "bigint") { super(low, true); } else if (Long.isLong(low)) { super(low.low, low.high, true); } else if (typeof low === "object" && "t" in low && "i" in low) { if (typeof low.t !== "number" && (typeof low.t !== "object" || low.t._bsontype !== "Int32")) { throw new BSONError("Timestamp constructed from { t, i } must provide t as a number"); } if (typeof low.i !== "number" && (typeof low.i !== "object" || low.i._bsontype !== "Int32")) { throw new BSONError("Timestamp constructed from { t, i } must provide i as a number"); } const t = Number(low.t); const i = Number(low.i); if (t < 0 || Number.isNaN(t)) { throw new BSONError("Timestamp constructed from { t, i } must provide a positive t"); } if (i < 0 || Number.isNaN(i)) { throw new BSONError("Timestamp constructed from { t, i } must provide a positive i"); } if (t > 4294967295) { throw new BSONError("Timestamp constructed from { t, i } must provide t equal or less than uint32 max"); } if (i > 4294967295) { throw new BSONError("Timestamp constructed from { t, i } must provide i equal or less than uint32 max"); } super(i, t, true); } else { throw new BSONError("A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }"); } } toJSON() { return { $timestamp: this.toString() }; } static fromInt(value) { return new _Timestamp(Long.fromInt(value, true)); } static fromNumber(value) { return new _Timestamp(Long.fromNumber(value, true)); } static fromBits(lowBits, highBits) { return new _Timestamp({ i: lowBits, t: highBits }); } static fromString(str, optRadix) { return new _Timestamp(Long.fromString(str, true, optRadix)); } toExtendedJSON() { return { $timestamp: { t: this.t, i: this.i } }; } static fromExtendedJSON(doc) { const i = Long.isLong(doc.$timestamp.i) ? doc.$timestamp.i.getLowBitsUnsigned() : doc.$timestamp.i; const t = Long.isLong(doc.$timestamp.t) ? doc.$timestamp.t.getLowBitsUnsigned() : doc.$timestamp.t; return new _Timestamp({ t, i }); } inspect(depth, options, inspect) { inspect ??= defaultInspect; const t = inspect(this.t, options); const i = inspect(this.i, options); return `new Timestamp({ t: ${t}, i: ${i} })`; } }; Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE; var JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX); var JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN); function internalDeserialize(buffer2, options, isArray) { options = options == null ? {} : options; const index = options && options.index ? options.index : 0; const size = NumberUtils.getInt32LE(buffer2, index); if (size < 5) { throw new BSONError(`bson size must be >= 5, is ${size}`); } if (options.allowObjectSmallerThanBufferSize && buffer2.length < size) { throw new BSONError(`buffer length ${buffer2.length} must be >= bson size ${size}`); } if (!options.allowObjectSmallerThanBufferSize && buffer2.length !== size) { throw new BSONError(`buffer length ${buffer2.length} must === bson size ${size}`); } if (size + index > buffer2.byteLength) { throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer2.byteLength})`); } if (buffer2[index + size - 1] !== 0) { throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); } return deserializeObject(buffer2, index, options, isArray); } var allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; function deserializeObject(buffer2, index, options, isArray = false) { const fieldsAsRaw = options["fieldsAsRaw"] == null ? null : options["fieldsAsRaw"]; const raw = options["raw"] == null ? false : options["raw"]; const bsonRegExp = typeof options["bsonRegExp"] === "boolean" ? options["bsonRegExp"] : false; const promoteBuffers = options.promoteBuffers ?? false; const promoteLongs = options.promoteLongs ?? true; const promoteValues = options.promoteValues ?? true; const useBigInt64 = options.useBigInt64 ?? false; if (useBigInt64 && !promoteValues) { throw new BSONError("Must either request bigint or Long for int64 deserialization"); } if (useBigInt64 && !promoteLongs) { throw new BSONError("Must either request bigint or Long for int64 deserialization"); } const validation = options.validation == null ? { utf8: true } : options.validation; let globalUTFValidation = true; let validationSetting; let utf8KeysSet; const utf8ValidatedKeys = validation.utf8; if (typeof utf8ValidatedKeys === "boolean") { validationSetting = utf8ValidatedKeys; } else { globalUTFValidation = false; const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function(key) { return utf8ValidatedKeys[key]; }); if (utf8ValidationValues.length === 0) { throw new BSONError("UTF-8 validation setting cannot be empty"); } if (typeof utf8ValidationValues[0] !== "boolean") { throw new BSONError("Invalid UTF-8 validation option, must specify boolean values"); } validationSetting = utf8ValidationValues[0]; if (!utf8ValidationValues.every((item) => item === validationSetting)) { throw new BSONError("Invalid UTF-8 validation option - keys must be all true or all false"); } } if (!globalUTFValidation) { utf8KeysSet = /* @__PURE__ */ new Set(); for (const key of Object.keys(utf8ValidatedKeys)) { utf8KeysSet.add(key); } } const startIndex = index; if (buffer2.length < 5) throw new BSONError("corrupt bson message < 5 bytes long"); const size = NumberUtils.getInt32LE(buffer2, index); index += 4; if (size < 5 || size > buffer2.length) throw new BSONError("corrupt bson message"); const object = isArray ? [] : {}; let arrayIndex = 0; let isPossibleDBRef = isArray ? false : null; while (true) { const elementType = buffer2[index++]; if (elementType === 0) break; let i = index; while (buffer2[i] !== 0 && i < buffer2.length) { i++; } if (i >= buffer2.byteLength) throw new BSONError("Bad BSON Document: illegal CString"); const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer2, index, i, false); let shouldValidateKey = true; if (globalUTFValidation || utf8KeysSet?.has(name)) { shouldValidateKey = validationSetting; } else { shouldValidateKey = !validationSetting; } if (isPossibleDBRef !== false && name[0] === "$") { isPossibleDBRef = allowedDBRefKeys.test(name); } let value; index = i + 1; if (elementType === BSON_DATA_STRING) { const stringSize = NumberUtils.getInt32LE(buffer2, index); index += 4; if (stringSize <= 0 || stringSize > buffer2.length - index || buffer2[index + stringSize - 1] !== 0) { throw new BSONError("bad string length in bson"); } value = ByteUtils.toUTF8(buffer2, index, index + stringSize - 1, shouldValidateKey); index = index + stringSize; } else if (elementType === BSON_DATA_OID) { const oid = ByteUtils.allocateUnsafe(12); for (let i2 = 0; i2 < 12; i2++) oid[i2] = buffer2[index + i2]; value = new ObjectId2(oid); index = index + 12; } else if (elementType === BSON_DATA_INT && promoteValues === false) { value = new Int32(NumberUtils.getInt32LE(buffer2, index)); index += 4; } else if (elementType === BSON_DATA_INT) { value = NumberUtils.getInt32LE(buffer2, index); index += 4; } else if (elementType === BSON_DATA_NUMBER) { value = NumberUtils.getFloat64LE(buffer2, index); index += 8; if (promoteValues === false) value = new Double(value); } else if (elementType === BSON_DATA_DATE) { const lowBits = NumberUtils.getInt32LE(buffer2, index); const highBits = NumberUtils.getInt32LE(buffer2, index + 4); index += 8; value = new Date(new Long(lowBits, highBits).toNumber()); } else if (elementType === BSON_DATA_BOOLEAN) { if (buffer2[index] !== 0 && buffer2[index] !== 1) throw new BSONError("illegal boolean type value"); value = buffer2[index++] === 1; } else if (elementType === BSON_DATA_OBJECT) { const _index = index; const objectSize = NumberUtils.getInt32LE(buffer2, index); if (objectSize <= 0 || objectSize > buffer2.length - index) throw new BSONError("bad embedded document length in bson"); if (raw) { value = buffer2.subarray(index, index + objectSize); } else { let objectOptions = options; if (!globalUTFValidation) { objectOptions = { ...options, validation: { utf8: shouldValidateKey } }; } value = deserializeObject(buffer2, _index, objectOptions, false); } index = index + objectSize; } else if (elementType === BSON_DATA_ARRAY) { const _index = index; const objectSize = NumberUtils.getInt32LE(buffer2, index); let arrayOptions = options; const stopIndex = index + objectSize; if (fieldsAsRaw && fieldsAsRaw[name]) { arrayOptions = { ...options, raw: true }; } if (!globalUTFValidation) { arrayOptions = { ...arrayOptions, validation: { utf8: shouldValidateKey } }; } value = deserializeObject(buffer2, _index, arrayOptions, true); index = index + objectSize; if (buffer2[index - 1] !== 0) throw new BSONError("invalid array terminator byte"); if (index !== stopIndex) throw new BSONError("corrupted array bson"); } else if (elementType === BSON_DATA_UNDEFINED) { value = void 0; } else if (elementType === BSON_DATA_NULL) { value = null; } else if (elementType === BSON_DATA_LONG) { if (useBigInt64) { value = NumberUtils.getBigInt64LE(buffer2, index); index += 8; } else { const lowBits = NumberUtils.getInt32LE(buffer2, index); const highBits = NumberUtils.getInt32LE(buffer2, index + 4); index += 8; const long = new Long(lowBits, highBits); if (promoteLongs && promoteValues === true) { value = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; } else { value = long; } } } else if (elementType === BSON_DATA_DECIMAL128) { const bytes = ByteUtils.allocateUnsafe(16); for (let i2 = 0; i2 < 16; i2++) bytes[i2] = buffer2[index + i2]; index = index + 16; value = new Decimal128(bytes); } else if (elementType === BSON_DATA_BINARY) { let binarySize = NumberUtils.getInt32LE(buffer2, index); index += 4; const totalBinarySize = binarySize; const subType = buffer2[index++]; if (binarySize < 0) throw new BSONError("Negative binary type element size found"); if (binarySize > buffer2.byteLength) throw new BSONError("Binary type size larger than document size"); if (subType === Binary.SUBTYPE_BYTE_ARRAY) { binarySize = NumberUtils.getInt32LE(buffer2, index); index += 4; if (binarySize < 0) throw new BSONError("Negative binary type element size found for subtype 0x02"); if (binarySize > totalBinarySize - 4) throw new BSONError("Binary type with subtype 0x02 contains too long binary size"); if (binarySize < totalBinarySize - 4) throw new BSONError("Binary type with subtype 0x02 contains too short binary size"); } if (promoteBuffers && promoteValues) { value = ByteUtils.toLocalBufferType(buffer2.subarray(index, index + binarySize)); } else { value = new Binary(buffer2.subarray(index, index + binarySize), subType); if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) { value = value.toUUID(); } } index = index + binarySize; } else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { i = index; while (buffer2[i] !== 0 && i < buffer2.length) { i++; } if (i >= buffer2.length) throw new BSONError("Bad BSON Document: illegal CString"); const source = ByteUtils.toUTF8(buffer2, index, i, false); index = i + 1; i = index; while (buffer2[i] !== 0 && i < buffer2.length) { i++; } if (i >= buffer2.length) throw new BSONError("Bad BSON Document: illegal CString"); const regExpOptions = ByteUtils.toUTF8(buffer2, index, i, false); index = i + 1; const optionsArray = new Array(regExpOptions.length); for (i = 0; i < regExpOptions.length; i++) { switch (regExpOptions[i]) { case "m": optionsArray[i] = "m"; break; case "s": optionsArray[i] = "g"; break; case "i": optionsArray[i] = "i"; break; } } value = new RegExp(source, optionsArray.join("")); } else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) { i = index; while (buffer2[i] !== 0 && i < buffer2.length) { i++; } if (i >= buffer2.length) throw new BSONError("Bad BSON Document: illegal CString"); const source = ByteUtils.toUTF8(buffer2, index, i, false); index = i + 1; i = index; while (buffer2[i] !== 0 && i < buffer2.length) { i++; } if (i >= buffer2.length) throw new BSONError("Bad BSON Document: illegal CString"); const regExpOptions = ByteUtils.toUTF8(buffer2, index, i, false); index = i + 1; value = new BSONRegExp(source, regExpOptions); } else if (elementType === BSON_DATA_SYMBOL) { const stringSize = NumberUtils.getInt32LE(buffer2, index); index += 4; if (stringSize <= 0 || stringSize > buffer2.length - index || buffer2[index + stringSize - 1] !== 0) { throw new BSONError("bad string length in bson"); } const symbol = ByteUtils.toUTF8(buffer2, index, index + stringSize - 1, shouldValidateKey); value = promoteValues ? symbol : new BSONSymbol(symbol); index = index + stringSize; } else if (elementType === BSON_DATA_TIMESTAMP) { value = new Timestamp({ i: NumberUtils.getUint32LE(buffer2, index), t: NumberUtils.getUint32LE(buffer2, index + 4) }); index += 8; } else if (elementType === BSON_DATA_MIN_KEY) { value = new MinKey(); } else if (elementType === BSON_DATA_MAX_KEY) { value = new MaxKey(); } else if (elementType === BSON_DATA_CODE) { const stringSize = NumberUtils.getInt32LE(buffer2, index); index += 4; if (stringSize <= 0 || stringSize > buffer2.length - index || buffer2[index + stringSize - 1] !== 0) { throw new BSONError("bad string length in bson"); } const functionString = ByteUtils.toUTF8(buffer2, index, index + stringSize - 1, shouldValidateKey); value = new Code(functionString); index = index + stringSize; } else if (elementType === BSON_DATA_CODE_W_SCOPE) { const totalSize = NumberUtils.getInt32LE(buffer2, index); index += 4; if (totalSize < 4 + 4 + 4 + 1) { throw new BSONError("code_w_scope total size shorter minimum expected length"); } const stringSize = NumberUtils.getInt32LE(buffer2, index); index += 4; if (stringSize <= 0 || stringSize > buffer2.length - index || buffer2[index + stringSize - 1] !== 0) { throw new BSONError("bad string length in bson"); } const functionString = ByteUtils.toUTF8(buffer2, index, index + stringSize - 1, shouldValidateKey); index = index + stringSize; const _index = index; const objectSize = NumberUtils.getInt32LE(buffer2, index); const scopeObject = deserializeObject(buffer2, _index, options, false); index = index + objectSize; if (totalSize < 4 + 4 + objectSize + stringSize) { throw new BSONError("code_w_scope total size is too short, truncating scope"); } if (totalSize > 4 + 4 + objectSize + stringSize) { throw new BSONError("code_w_scope total size is too long, clips outer document"); } value = new Code(functionString, scopeObject); } else if (elementType === BSON_DATA_DBPOINTER) { const stringSize = NumberUtils.getInt32LE(buffer2, index); index += 4; if (stringSize <= 0 || stringSize > buffer2.length - index || buffer2[index + stringSize - 1] !== 0) throw new BSONError("bad string length in bson"); const namespace = ByteUtils.toUTF8(buffer2, index, index + stringSize - 1, shouldValidateKey); index = index + stringSize; const oidBuffer = ByteUtils.allocateUnsafe(12); for (let i2 = 0; i2 < 12; i2++) oidBuffer[i2] = buffer2[index + i2]; const oid = new ObjectId2(oidBuffer); index = index + 12; value = new DBRef(namespace, oid); } else { throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`); } if (name === "__proto__") { Object.defineProperty(object, name, { value, writable: true, enumerable: true, configurable: true }); } else { object[name] = value; } } if (size !== index - startIndex) { if (isArray) throw new BSONError("corrupt array bson"); throw new BSONError("corrupt object bson"); } if (!isPossibleDBRef) return object; if (isDBRefLike(object)) { const copy = Object.assign({}, object); delete copy.$ref; delete copy.$id; delete copy.$db; return new DBRef(object.$ref, object.$id, object.$db, copy); } return object; } var regexp = /\x00/; var ignoreKeys = /* @__PURE__ */ new Set(["$db", "$ref", "$id", "$clusterTime"]); function serializeString(buffer2, key, value, index) { buffer2[index++] = BSON_DATA_STRING; const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index); index = index + numberOfWrittenBytes + 1; buffer2[index - 1] = 0; const size = ByteUtils.encodeUTF8Into(buffer2, value, index + 4); NumberUtils.setInt32LE(buffer2, index, size + 1); index = index + 4 + size; buffer2[index++] = 0; return index; } function serializeNumber(buffer2, key, value, index) { const isNegativeZero = Object.is(value, -0); const type = !isNegativeZero && Number.isSafeInteger(value) && value <= BSON_INT32_MAX && value >= BSON_INT32_MIN ? BSON_DATA_INT : BSON_DATA_NUMBER; buffer2[index++] = type; const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index); index = index + numberOfWrittenBytes; buffer2[index++] = 0; if (type === BSON_DATA_INT) { index += NumberUtils.setInt32LE(buffer2, index, value); } else { index += NumberUtils.setFloat64LE(buffer2, index, value); } return index; } function serializeBigInt(buffer2, key, value, index) { buffer2[index++] = BSON_DATA_LONG; const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index); index += numberOfWrittenBytes; buffer2[index++] = 0; index += NumberUtils.setBigInt64LE(buffer2, index, value); return index; } function serializeNull(buffer2, key, _, index) { buffer2[index++] = BSON_DATA_NULL; const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index); index = index + numberOfWrittenBytes; buffer2[index++] = 0; return index; } function serializeBoolean(buffer2, key, value, index) { buffer2[index++] = BSON_DATA_BOOLEAN; const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index); index = index + numberOfWrittenBytes; buffer2[index++] = 0; buffer2[index++] = value ? 1 : 0; return index; } function serializeDate(buffer2, key, value, index) { buffer2[index++] = BSON_DATA_DATE; const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index); index = index + numberOfWrittenBytes; buffer2[index++] = 0; const dateInMilis = Long.fromNumber(value.getTime()); const lowBits = dateInMilis.getLowBits(); const highBits = dateInMilis.getHighBits(); index += NumberUtils.setInt32LE(buffer2, index, lowBits); index += NumberUtils.setInt32LE(buffer2, index, highBits); return index; } function serializeRegExp(buffer2, key, value, index) { buffer2[index++] = BSON_DATA_REGEXP; const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index); index = index + numberOfWrittenBytes; buffer2[index++] = 0; if (value.source && value.source.match(regexp) != null) { throw new BSONError("value " + value.source + " must not contain null bytes"); } index = index + ByteUtils.encodeUTF8Into(buffer2, value.source, index); buffer2[index++] = 0; if (value.ignoreCase) buffer2[index++] = 105; if (value.global) buffer2[index++] = 115; if (value.multiline) buffer2[index++] = 109; buffer2[index++] = 0; return index; } function serializeBSONRegExp(buffer2, key, value, index) { buffer2[index++] = BSON_DATA_REGEXP; const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index); index = index + numberOfWrittenBytes; buffer2[index++] = 0; if (value.pattern.match(regexp) != null) { throw new BSONError("pattern " + value.pattern + " must not contain null bytes"); } index = index + ByteUtils.encodeUTF8Into(buffer2, value.pattern, index); buffer2[index++] = 0; const sortedOptions = value.options.split("").sort().join(""); index = index + ByteUtils.encodeUTF8Into(buffer2, sortedOptions, index); buffer2[index++] = 0; return index; } function serializeMinMax(buffer2, key, value, index) { if (value === null) { buffer2[index++] = BSON_DATA_NULL; } else if (value._bsontype === "MinKey") { buffer2[index++] = BSON_DATA_MIN_KEY; } else { buffer2[index++] = BSON_DATA_MAX_KEY; } const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index); index = index + numberOfWrittenBytes; buffer2[index++] = 0; return index; } function serializeObjectId(buffer2, key, value, index) { buffer2[index++] = BSON_DATA_OID; const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index); index = index + numberOfWrittenBytes; buffer2[index++] = 0; index += value.serializeInto(buffer2, index); return index; } function serializeBuffer(buffer2, key, value, index) { buffer2[index++] = BSON_DATA_BINARY; const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index); index = index + numberOfWrittenBytes; buffer2[index++] = 0; const size = value.length; index += NumberUtils.setInt32LE(buffer2, index, size); buffer2[index++] = BSON_BINARY_SUBTYPE_DEFAULT; if (size <= 16) { for (let i = 0; i < size; i++) buffer2[index + i] = value[i]; } else { buffer2.set(value, index); } index = index + size; return index; } function serializeObject(buffer2, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path) { if (path.has(value)) { throw new BSONError("Cannot convert circular structure to BSON"); } path.add(value); buffer2[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT; const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index); index = index + numberOfWrittenBytes; buffer2[index++] = 0; const endIndex = serializeInto(buffer2, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); path.delete(value); return endIndex; } function serializeDecimal128(buffer2, key, value, index) { buffer2[index++] = BSON_DATA_DECIMAL128; const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index); index = index + numberOfWrittenBytes; buffer2[index++] = 0; for (let i = 0; i < 16; i++) buffer2[index + i] = value.bytes[i]; return index + 16; } function serializeLong(buffer2, key, value, index) { buffer2[index++] = value._bsontype === "Long" ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP; const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index); index = index + numberOfWrittenBytes; buffer2[index++] = 0; const lowBits = value.getLowBits(); const highBits = value.getHighBits(); index += NumberUtils.setInt32LE(buffer2, index, lowBits); index += NumberUtils.setInt32LE(buffer2, index, highBits); return index; } function serializeInt32(buffer2, key, value, index) { value = value.valueOf(); buffer2[index++] = BSON_DATA_INT; const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index); index = index + numberOfWrittenBytes; buffer2[index++] = 0; index += NumberUtils.setInt32LE(buffer2, index, value); return index; } function serializeDouble(buffer2, key, value, index) { buffer2[index++] = BSON_DATA_NUMBER; const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index); index = index + numberOfWrittenBytes; buffer2[index++] = 0; index += NumberUtils.setFloat64LE(buffer2, index, value.value); return index; } function serializeFunction(buffer2, key, value, index) { buffer2[index++] = BSON_DATA_CODE; const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index); index = index + numberOfWrittenBytes; buffer2[index++] = 0; const functionString = value.toString(); const size = ByteUtils.encodeUTF8Into(buffer2, functionString, index + 4) + 1; NumberUtils.setInt32LE(buffer2, index, size); index = index + 4 + size - 1; buffer2[index++] = 0; return index; } function serializeCode(buffer2, key, value, index, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path) { if (value.scope && typeof value.scope === "object") { buffer2[index++] = BSON_DATA_CODE_W_SCOPE; const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index); index = index + numberOfWrittenBytes; buffer2[index++] = 0; let startIndex = index; const functionString = value.code; index = index + 4; const codeSize = ByteUtils.encodeUTF8Into(buffer2, functionString, index + 4) + 1; NumberUtils.setInt32LE(buffer2, index, codeSize); buffer2[index + 4 + codeSize - 1] = 0; index = index + codeSize + 4; const endIndex = serializeInto(buffer2, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); index = endIndex - 1; const totalSize = endIndex - startIndex; startIndex += NumberUtils.setInt32LE(buffer2, startIndex, totalSize); buffer2[index++] = 0; } else { buffer2[index++] = BSON_DATA_CODE; const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index); index = index + numberOfWrittenBytes; buffer2[index++] = 0; const functionString = value.code.toString(); const size = ByteUtils.encodeUTF8Into(buffer2, functionString, index + 4) + 1; NumberUtils.setInt32LE(buffer2, index, size); index = index + 4 + size - 1; buffer2[index++] = 0; } return index; } function serializeBinary(buffer2, key, value, index) { buffer2[index++] = BSON_DATA_BINARY; const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index); index = index + numberOfWrittenBytes; buffer2[index++] = 0; const data = value.buffer; let size = value.position; if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; index += NumberUtils.setInt32LE(buffer2, index, size); buffer2[index++] = value.sub_type; if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { size = size - 4; index += NumberUtils.setInt32LE(buffer2, index, size); } if (value.sub_type === Binary.SUBTYPE_VECTOR) { validateBinaryVector(value); } if (size <= 16) { for (let i = 0; i < size; i++) buffer2[index + i] = data[i]; } else { buffer2.set(data, index); } index = index + value.position; return index; } function serializeSymbol(buffer2, key, value, index) { buffer2[index++] = BSON_DATA_SYMBOL; const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index); index = index + numberOfWrittenBytes; buffer2[index++] = 0; const size = ByteUtils.encodeUTF8Into(buffer2, value.value, index + 4) + 1; NumberUtils.setInt32LE(buffer2, index, size); index = index + 4 + size - 1; buffer2[index++] = 0; return index; } function serializeDBRef(buffer2, key, value, index, depth, serializeFunctions, path) { buffer2[index++] = BSON_DATA_OBJECT; const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index); index = index + numberOfWrittenBytes; buffer2[index++] = 0; let startIndex = index; let output = { $ref: value.collection || value.namespace, $id: value.oid }; if (value.db != null) { output.$db = value.db; } output = Object.assign(output, value.fields); const endIndex = serializeInto(buffer2, output, false, index, depth + 1, serializeFunctions, true, path); const size = endIndex - startIndex; startIndex += NumberUtils.setInt32LE(buffer2, index, size); return endIndex; } function serializeInto(buffer2, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { if (path == null) { if (object == null) { buffer2[0] = 5; buffer2[1] = 0; buffer2[2] = 0; buffer2[3] = 0; buffer2[4] = 0; return 5; } if (Array.isArray(object)) { throw new BSONError("serialize does not support an array as the root input"); } if (typeof object !== "object") { throw new BSONError("serialize does not support non-object as the root input"); } else if ("_bsontype" in object && typeof object._bsontype === "string") { throw new BSONError(`BSON types cannot be serialized as a document`); } else if (isDate(object) || isRegExp(object) || isUint8Array(object) || isAnyArrayBuffer(object)) { throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`); } path = /* @__PURE__ */ new Set(); } path.add(object); let index = startingIndex + 4; if (Array.isArray(object)) { for (let i = 0; i < object.length; i++) { const key = `${i}`; let value = object[i]; if (typeof value?.toBSON === "function") { value = value.toBSON(); } const type = typeof value; if (value === void 0) { index = serializeNull(buffer2, key, value, index); } else if (value === null) { index = serializeNull(buffer2, key, value, index); } else if (type === "string") { index = serializeString(buffer2, key, value, index); } else if (type === "number") { index = serializeNumber(buffer2, key, value, index); } else if (type === "bigint") { index = serializeBigInt(buffer2, key, value, index); } else if (type === "boolean") { index = serializeBoolean(buffer2, key, value, index); } else if (type === "object" && value._bsontype == null) { if (value instanceof Date || isDate(value)) { index = serializeDate(buffer2, key, value, index); } else if (value instanceof Uint8Array || isUint8Array(value)) { index = serializeBuffer(buffer2, key, value, index); } else if (value instanceof RegExp || isRegExp(value)) { index = serializeRegExp(buffer2, key, value, index); } else { index = serializeObject(buffer2, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); } } else if (type === "object") { if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) { throw new BSONVersionError(); } else if (value._bsontype === "ObjectId") { index = serializeObjectId(buffer2, key, value, index); } else if (value._bsontype === "Decimal128") { index = serializeDecimal128(buffer2, key, value, index); } else if (value._bsontype === "Long" || value._bsontype === "Timestamp") { index = serializeLong(buffer2, key, value, index); } else if (value._bsontype === "Double") { index = serializeDouble(buffer2, key, value, index); } else if (value._bsontype === "Code") { index = serializeCode(buffer2, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); } else if (value._bsontype === "Binary") { index = serializeBinary(buffer2, key, value, index); } else if (value._bsontype === "BSONSymbol") { index = serializeSymbol(buffer2, key, value, index); } else if (value._bsontype === "DBRef") { index = serializeDBRef(buffer2, key, value, index, depth, serializeFunctions, path); } else if (value._bsontype === "BSONRegExp") { index = serializeBSONRegExp(buffer2, key, value, index); } else if (value._bsontype === "Int32") { index = serializeInt32(buffer2, key, value, index); } else if (value._bsontype === "MinKey" || value._bsontype === "MaxKey") { index = serializeMinMax(buffer2, key, value, index); } else if (typeof value._bsontype !== "undefined") { throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); } } else if (type === "function" && serializeFunctions) { index = serializeFunction(buffer2, key, value, index); } } } else if (object instanceof Map || isMap(object)) { const iterator = object.entries(); let done = false; while (!done) { const entry = iterator.next(); done = !!entry.done; if (done) continue; const key = entry.value ? entry.value[0] : void 0; let value = entry.value ? entry.value[1] : void 0; if (typeof value?.toBSON === "function") { value = value.toBSON(); } const type = typeof value; if (typeof key === "string" && !ignoreKeys.has(key)) { if (key.match(regexp) != null) { throw new BSONError("key " + key + " must not contain null bytes"); } if (checkKeys) { if ("$" === key[0]) { throw new BSONError("key " + key + " must not start with '$'"); } else if (key.includes(".")) { throw new BSONError("key " + key + " must not contain '.'"); } } } if (value === void 0) { if (ignoreUndefined === false) index = serializeNull(buffer2, key, value, index); } else if (value === null) { index = serializeNull(buffer2, key, value, index); } else if (type === "string") { index = serializeString(buffer2, key, value, index); } else if (type === "number") { index = serializeNumber(buffer2, key, value, index); } else if (type === "bigint") { index = serializeBigInt(buffer2, key, value, index); } else if (type === "boolean") { index = serializeBoolean(buffer2, key, value, index); } else if (type === "object" && value._bsontype == null) { if (value instanceof Date || isDate(value)) { index = serializeDate(buffer2, key, value, index); } else if (value instanceof Uint8Array || isUint8Array(value)) { index = serializeBuffer(buffer2, key, value, index); } else if (value instanceof RegExp || isRegExp(value)) { index = serializeRegExp(buffer2, key, value, index); } else { index = serializeObject(buffer2, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); } } else if (type === "object") { if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) { throw new BSONVersionError(); } else if (value._bsontype === "ObjectId") { index = serializeObjectId(buffer2, key, value, index); } else if (value._bsontype === "Decimal128") { index = serializeDecimal128(buffer2, key, value, index); } else if (value._bsontype === "Long" || value._bsontype === "Timestamp") { index = serializeLong(buffer2, key, value, index); } else if (value._bsontype === "Double") { index = serializeDouble(buffer2, key, value, index); } else if (value._bsontype === "Code") { index = serializeCode(buffer2, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); } else if (value._bsontype === "Binary") { index = serializeBinary(buffer2, key, value, index); } else if (value._bsontype === "BSONSymbol") { index = serializeSymbol(buffer2, key, value, index); } else if (value._bsontype === "DBRef") { index = serializeDBRef(buffer2, key, value, index, depth, serializeFunctions, path); } else if (value._bsontype === "BSONRegExp") { index = serializeBSONRegExp(buffer2, key, value, index); } else if (value._bsontype === "Int32") { index = serializeInt32(buffer2, key, value, index); } else if (value._bsontype === "MinKey" || value._bsontype === "MaxKey") { index = serializeMinMax(buffer2, key, value, index); } else if (typeof value._bsontype !== "undefined") { throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); } } else if (type === "function" && serializeFunctions) { index = serializeFunction(buffer2, key, value, index); } } } else { if (typeof object?.toBSON === "function") { object = object.toBSON(); if (object != null && typeof object !== "object") { throw new BSONError("toBSON function did not return an object"); } } for (const key of Object.keys(object)) { let value = object[key]; if (typeof value?.toBSON === "function") { value = value.toBSON(); } const type = typeof value; if (typeof key === "string" && !ignoreKeys.has(key)) { if (key.match(regexp) != null) { throw new BSONError("key " + key + " must not contain null bytes"); } if (checkKeys) { if ("$" === key[0]) { throw new BSONError("key " + key + " must not start with '$'"); } else if (key.includes(".")) { throw new BSONError("key " + key + " must not contain '.'"); } } } if (value === void 0) { if (ignoreUndefined === false) index = serializeNull(buffer2, key, value, index); } else if (value === null) { index = serializeNull(buffer2, key, value, index); } else if (type === "string") { index = serializeString(buffer2, key, value, index); } else if (type === "number") { index = serializeNumber(buffer2, key, value, index); } else if (type === "bigint") { index = serializeBigInt(buffer2, key, value, index); } else if (type === "boolean") { index = serializeBoolean(buffer2, key, value, index); } else if (type === "object" && value._bsontype == null) { if (value instanceof Date || isDate(value)) { index = serializeDate(buffer2, key, value, index); } else if (value instanceof Uint8Array || isUint8Array(value)) { index = serializeBuffer(buffer2, key, value, index); } else if (value instanceof RegExp || isRegExp(value)) { index = serializeRegExp(buffer2, key, value, index); } else { index = serializeObject(buffer2, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); } } else if (type === "object") { if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) { throw new BSONVersionError(); } else if (value._bsontype === "ObjectId") { index = serializeObjectId(buffer2, key, value, index); } else if (value._bsontype === "Decimal128") { index = serializeDecimal128(buffer2, key, value, index); } else if (value._bsontype === "Long" || value._bsontype === "Timestamp") { index = serializeLong(buffer2, key, value, index); } else if (value._bsontype === "Double") { index = serializeDouble(buffer2, key, value, index); } else if (value._bsontype === "Code") { index = serializeCode(buffer2, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); } else if (value._bsontype === "Binary") { index = serializeBinary(buffer2, key, value, index); } else if (value._bsontype === "BSONSymbol") { index = serializeSymbol(buffer2, key, value, index); } else if (value._bsontype === "DBRef") { index = serializeDBRef(buffer2, key, value, index, depth, serializeFunctions, path); } else if (value._bsontype === "BSONRegExp") { index = serializeBSONRegExp(buffer2, key, value, index); } else if (value._bsontype === "Int32") { index = serializeInt32(buffer2, key, value, index); } else if (value._bsontype === "MinKey" || value._bsontype === "MaxKey") { index = serializeMinMax(buffer2, key, value, index); } else if (typeof value._bsontype !== "undefined") { throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); } } else if (type === "function" && serializeFunctions) { index = serializeFunction(buffer2, key, value, index); } } } path.delete(object); buffer2[index++] = 0; const size = index - startingIndex; startingIndex += NumberUtils.setInt32LE(buffer2, startingIndex, size); return index; } function isBSONType(value) { return value != null && typeof value === "object" && "_bsontype" in value && typeof value._bsontype === "string"; } var keysToCodecs = { $oid: ObjectId2, $binary: Binary, $uuid: Binary, $symbol: BSONSymbol, $numberInt: Int32, $numberDecimal: Decimal128, $numberDouble: Double, $numberLong: Long, $minKey: MinKey, $maxKey: MaxKey, $regex: BSONRegExp, $regularExpression: BSONRegExp, $timestamp: Timestamp }; function deserializeValue(value, options = {}) { if (typeof value === "number") { const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN; const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN; if (options.relaxed || options.legacy) { return value; } if (Number.isInteger(value) && !Object.is(value, -0)) { if (in32BitRange) { return new Int32(value); } if (in64BitRange) { if (options.useBigInt64) { return BigInt(value); } return Long.fromNumber(value); } } return new Double(value); } if (value == null || typeof value !== "object") return value; if (value.$undefined) return null; const keys = Object.keys(value).filter((k) => k.startsWith("$") && value[k] != null); for (let i = 0; i < keys.length; i++) { const c = keysToCodecs[keys[i]]; if (c) return c.fromExtendedJSON(value, options); } if (value.$date != null) { const d = value.$date; const date = /* @__PURE__ */ new Date(); if (options.legacy) { if (typeof d === "number") date.setTime(d); else if (typeof d === "string") date.setTime(Date.parse(d)); else if (typeof d === "bigint") date.setTime(Number(d)); else throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`); } else { if (typeof d === "string") date.setTime(Date.parse(d)); else if (Long.isLong(d)) date.setTime(d.toNumber()); else if (typeof d === "number" && options.relaxed) date.setTime(d); else if (typeof d === "bigint") date.setTime(Number(d)); else throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`); } return date; } if (value.$code != null) { const copy = Object.assign({}, value); if (value.$scope) { copy.$scope = deserializeValue(value.$scope); } return Code.fromExtendedJSON(value); } if (isDBRefLike(value) || value.$dbPointer) { const v = value.$ref ? value : value.$dbPointer; if (v instanceof DBRef) return v; const dollarKeys = Object.keys(v).filter((k) => k.startsWith("$")); let valid = true; dollarKeys.forEach((k) => { if (["$ref", "$id", "$db"].indexOf(k) === -1) valid = false; }); if (valid) return DBRef.fromExtendedJSON(v); } return value; } function serializeArray(array, options) { return array.map((v, index) => { options.seenObjects.push({ propertyName: `index ${index}`, obj: null }); try { return serializeValue(v, options); } finally { options.seenObjects.pop(); } }); } function getISOString(date) { const isoStr = date.toISOString(); return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + "Z"; } function serializeValue(value, options) { if (value instanceof Map || isMap(value)) { const obj = /* @__PURE__ */ Object.create(null); for (const [k, v] of value) { if (typeof k !== "string") { throw new BSONError("Can only serialize maps with string keys"); } obj[k] = v; } return serializeValue(obj, options); } if ((typeof value === "object" || typeof value === "function") && value !== null) { const index = options.seenObjects.findIndex((entry) => entry.obj === value); if (index !== -1) { const props = options.seenObjects.map((entry) => entry.propertyName); const leadingPart = props.slice(0, index).map((prop) => `${prop} -> `).join(""); const alreadySeen = props[index]; const circularPart = " -> " + props.slice(index + 1, props.length - 1).map((prop) => `${prop} -> `).join(""); const current = props[props.length - 1]; const leadingSpace = " ".repeat(leadingPart.length + alreadySeen.length / 2); const dashes = "-".repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1); throw new BSONError(`Converting circular structure to EJSON: ${leadingPart}${alreadySeen}${circularPart}${current} ${leadingSpace}\\${dashes}/`); } options.seenObjects[options.seenObjects.length - 1].obj = value; } if (Array.isArray(value)) return serializeArray(value, options); if (value === void 0) return null; if (value instanceof Date || isDate(value)) { const dateNum = value.getTime(), inRange = dateNum > -1 && dateNum < 2534023188e5; if (options.legacy) { return options.relaxed && inRange ? { $date: value.getTime() } : { $date: getISOString(value) }; } return options.relaxed && inRange ? { $date: getISOString(value) } : { $date: { $numberLong: value.getTime().toString() } }; } if (typeof value === "number" && (!options.relaxed || !isFinite(value))) { if (Number.isInteger(value) && !Object.is(value, -0)) { if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { return { $numberInt: value.toString() }; } if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) { return { $numberLong: value.toString() }; } } return { $numberDouble: Object.is(value, -0) ? "-0.0" : value.toString() }; } if (typeof value === "bigint") { if (!options.relaxed) { return { $numberLong: BigInt.asIntN(64, value).toString() }; } return Number(BigInt.asIntN(64, value)); } if (value instanceof RegExp || isRegExp(value)) { let flags = value.flags; if (flags === void 0) { const match = value.toString().match(/[gimuy]*$/); if (match) { flags = match[0]; } } const rx = new BSONRegExp(value.source, flags); return rx.toExtendedJSON(options); } if (value != null && typeof value === "object") return serializeDocument(value, options); return value; } var BSON_TYPE_MAPPINGS = { Binary: (o) => new Binary(o.value(), o.sub_type), Code: (o) => new Code(o.code, o.scope), DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields), Decimal128: (o) => new Decimal128(o.bytes), Double: (o) => new Double(o.value), Int32: (o) => new Int32(o.value), Long: (o) => Long.fromBits(o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_), MaxKey: () => new MaxKey(), MinKey: () => new MinKey(), ObjectId: (o) => new ObjectId2(o), BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options), BSONSymbol: (o) => new BSONSymbol(o.value), Timestamp: (o) => Timestamp.fromBits(o.low, o.high) }; function serializeDocument(doc, options) { if (doc == null || typeof doc !== "object") throw new BSONError("not an object instance"); const bsontype = doc._bsontype; if (typeof bsontype === "undefined") { const _doc = {}; for (const name of Object.keys(doc)) { options.seenObjects.push({ propertyName: name, obj: null }); try { const value = serializeValue(doc[name], options); if (name === "__proto__") { Object.defineProperty(_doc, name, { value, writable: true, enumerable: true, configurable: true }); } else { _doc[name] = value; } } finally { options.seenObjects.pop(); } } return _doc; } else if (doc != null && typeof doc === "object" && typeof doc._bsontype === "string" && doc[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) { throw new BSONVersionError(); } else if (isBSONType(doc)) { let outDoc = doc; if (typeof outDoc.toExtendedJSON !== "function") { const mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; if (!mapper) { throw new BSONError("Unrecognized or invalid _bsontype: " + doc._bsontype); } outDoc = mapper(outDoc); } if (bsontype === "Code" && outDoc.scope) { outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options)); } else if (bsontype === "DBRef" && outDoc.oid) { outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options)); } return outDoc.toExtendedJSON(options); } else { throw new BSONError("_bsontype must be a string, but was: " + typeof bsontype); } } function parse(text, options) { const ejsonOptions = { useBigInt64: options?.useBigInt64 ?? false, relaxed: options?.relaxed ?? true, legacy: options?.legacy ?? false }; return JSON.parse(text, (key, value) => { if (key.indexOf("\0") !== -1) { throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`); } return deserializeValue(value, ejsonOptions); }); } function stringify(value, replacer, space, options) { if (space != null && typeof space === "object") { options = space; space = 0; } if (replacer != null && typeof replacer === "object" && !Array.isArray(replacer)) { options = replacer; replacer = void 0; space = 0; } const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { seenObjects: [{ propertyName: "(root)", obj: null }] }); const doc = serializeValue(value, serializeOptions); return JSON.stringify(doc, replacer, space); } function EJSONserialize(value, options) { options = options || {}; return JSON.parse(stringify(value, options)); } function EJSONdeserialize(ejson, options) { options = options || {}; return parse(JSON.stringify(ejson), options); } var EJSON = /* @__PURE__ */ Object.create(null); EJSON.parse = parse; EJSON.stringify = stringify; EJSON.serialize = EJSONserialize; EJSON.deserialize = EJSONdeserialize; Object.freeze(EJSON); var BSONElementType = { 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: 255, maxKey: 127 }; function getSize(source, offset) { try { return NumberUtils.getNonnegativeInt32LE(source, offset); } catch (cause) { throw new BSONOffsetError("BSON size cannot be negative", offset, { cause }); } } function findNull(bytes, offset) { let nullTerminatorOffset = offset; for (; bytes[nullTerminatorOffset] !== 0; nullTerminatorOffset++) ; if (nullTerminatorOffset === bytes.length - 1) { throw new BSONOffsetError("Null terminator not found", offset); } return nullTerminatorOffset; } function parseToElements(bytes, startOffset = 0) { startOffset ??= 0; if (bytes.length < 5) { throw new BSONOffsetError(`Input must be at least 5 bytes, got ${bytes.length} bytes`, startOffset); } const documentSize = getSize(bytes, startOffset); if (documentSize > bytes.length - startOffset) { throw new BSONOffsetError(`Parsed documentSize (${documentSize} bytes) does not match input length (${bytes.length} bytes)`, startOffset); } if (bytes[startOffset + documentSize - 1] !== 0) { throw new BSONOffsetError("BSON documents must end in 0x00", startOffset + documentSize); } const elements = []; let offset = startOffset + 4; while (offset <= documentSize + startOffset) { const type = bytes[offset]; offset += 1; if (type === 0) { if (offset - startOffset !== documentSize) { throw new BSONOffsetError(`Invalid 0x00 type byte`, offset); } break; } const nameOffset = offset; const nameLength = findNull(bytes, offset) - nameOffset; offset += nameLength + 1; let length; if (type === BSONElementType.double || type === BSONElementType.long || type === BSONElementType.date || type === BSONElementType.timestamp) { length = 8; } else if (type === BSONElementType.int) { length = 4; } else if (type === BSONElementType.objectId) { length = 12; } else if (type === BSONElementType.decimal) { length = 16; } else if (type === BSONElementType.bool) { length = 1; } else if (type === BSONElementType.null || type === BSONElementType.undefined || type === BSONElementType.maxKey || type === BSONElementType.minKey) { length = 0; } else if (type === BSONElementType.regex) { length = findNull(bytes, findNull(bytes, offset) + 1) + 1 - offset; } else if (type === BSONElementType.object || type === BSONElementType.array || type === BSONElementType.javascriptWithScope) { length = getSize(bytes, offset); } else if (type === BSONElementType.string || type === BSONElementType.binData || type === BSONElementType.dbPointer || type === BSONElementType.javascript || type === BSONElementType.symbol) { length = getSize(bytes, offset) + 4; if (type === BSONElementType.binData) { length += 1; } if (type === BSONElementType.dbPointer) { length += 12; } } else { throw new BSONOffsetError(`Invalid 0x${type.toString(16).padStart(2, "0")} type byte`, offset); } if (length > documentSize) { throw new BSONOffsetError("value reports length larger than document", offset); } elements.push([type, nameOffset, nameLength, offset, length]); offset += length; } return elements; } var onDemand = /* @__PURE__ */ Object.create(null); onDemand.parseToElements = parseToElements; onDemand.ByteUtils = ByteUtils; onDemand.NumberUtils = NumberUtils; Object.freeze(onDemand); var MAXSIZE = 1024 * 1024 * 17; var buffer = ByteUtils.allocate(MAXSIZE); function setInternalBufferSize(size) { if (buffer.length < size) { buffer = ByteUtils.allocate(size); } } function serialize(object, options = {}) { const checkKeys = typeof options.checkKeys === "boolean" ? options.checkKeys : false; const serializeFunctions = typeof options.serializeFunctions === "boolean" ? options.serializeFunctions : false; const ignoreUndefined = typeof options.ignoreUndefined === "boolean" ? options.ignoreUndefined : true; const minInternalBufferSize = typeof options.minInternalBufferSize === "number" ? options.minInternalBufferSize : MAXSIZE; if (buffer.length < minInternalBufferSize) { buffer = ByteUtils.allocate(minInternalBufferSize); } const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); const finishedBuffer = ByteUtils.allocateUnsafe(serializationIndex); finishedBuffer.set(buffer.subarray(0, serializationIndex), 0); return finishedBuffer; } function serializeWithBufferAndIndex(object, finalBuffer, options = {}) { const checkKeys = typeof options.checkKeys === "boolean" ? options.checkKeys : false; const serializeFunctions = typeof options.serializeFunctions === "boolean" ? options.serializeFunctions : false; const ignoreUndefined = typeof options.ignoreUndefined === "boolean" ? options.ignoreUndefined : true; const startIndex = typeof options.index === "number" ? options.index : 0; const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex); return startIndex + serializationIndex - 1; } function deserialize(buffer2, options = {}) { return internalDeserialize(ByteUtils.toLocalBufferType(buffer2), options); } function calculateObjectSize(object, options = {}) { options = options || {}; const serializeFunctions = typeof options.serializeFunctions === "boolean" ? options.serializeFunctions : false; const ignoreUndefined = typeof options.ignoreUndefined === "boolean" ? options.ignoreUndefined : true; return internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined); } function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); const bufferData = ByteUtils.toLocalBufferType(data); let index = startIndex; for (let i = 0; i < numberOfDocuments; i++) { const size = NumberUtils.getInt32LE(bufferData, index); internalOptions.index = index; documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions); index = index + size; } return index; } var bson = /* @__PURE__ */ Object.freeze({ __proto__: null, BSONError, BSONOffsetError, BSONRegExp, BSONRuntimeError, BSONSymbol, BSONType, BSONValue, BSONVersionError, Binary, Code, DBRef, Decimal128, Double, EJSON, Int32, Long, MaxKey, MinKey, ObjectId: ObjectId2, Timestamp, UUID, calculateObjectSize, deserialize, deserializeStream, onDemand, serialize, serializeWithBufferAndIndex, setInternalBufferSize }); exports2.BSON = bson; exports2.BSONError = BSONError; exports2.BSONOffsetError = BSONOffsetError; exports2.BSONRegExp = BSONRegExp; exports2.BSONRuntimeError = BSONRuntimeError; exports2.BSONSymbol = BSONSymbol; exports2.BSONType = BSONType; exports2.BSONValue = BSONValue; exports2.BSONVersionError = BSONVersionError; exports2.Binary = Binary; exports2.Code = Code; exports2.DBRef = DBRef; exports2.Decimal128 = Decimal128; exports2.Double = Double; exports2.EJSON = EJSON; exports2.Int32 = Int32; exports2.Long = Long; exports2.MaxKey = MaxKey; exports2.MinKey = MinKey; exports2.ObjectId = ObjectId2; exports2.Timestamp = Timestamp; exports2.UUID = UUID; exports2.calculateObjectSize = calculateObjectSize; exports2.deserialize = deserialize; exports2.deserializeStream = deserializeStream; exports2.onDemand = onDemand; exports2.serialize = serialize; exports2.serializeWithBufferAndIndex = serializeWithBufferAndIndex; exports2.setInternalBufferSize = setInternalBufferSize; } }); // netlify/functions/node_modules/mongodb/lib/bson.js var require_bson2 = __commonJS({ "netlify/functions/node_modules/mongodb/lib/bson.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.toUTF8 = exports2.getBigInt64LE = exports2.getFloat64LE = exports2.getInt32LE = exports2.UUID = exports2.Timestamp = exports2.serialize = exports2.ObjectId = exports2.MinKey = exports2.MaxKey = exports2.Long = exports2.Int32 = exports2.EJSON = exports2.Double = exports2.deserialize = exports2.Decimal128 = exports2.DBRef = exports2.Code = exports2.calculateObjectSize = exports2.BSONType = exports2.BSONSymbol = exports2.BSONRegExp = exports2.BSONError = exports2.BSON = exports2.Binary = void 0; exports2.parseToElementsToArray = parseToElementsToArray; exports2.pluckBSONSerializeOptions = pluckBSONSerializeOptions; exports2.resolveBSONOptions = resolveBSONOptions; exports2.parseUtf8ValidationOption = parseUtf8ValidationOption; var bson_1 = require_bson(); var bson_2 = require_bson(); Object.defineProperty(exports2, "Binary", { enumerable: true, get: function() { return bson_2.Binary; } }); Object.defineProperty(exports2, "BSON", { enumerable: true, get: function() { return bson_2.BSON; } }); Object.defineProperty(exports2, "BSONError", { enumerable: true, get: function() { return bson_2.BSONError; } }); Object.defineProperty(exports2, "BSONRegExp", { enumerable: true, get: function() { return bson_2.BSONRegExp; } }); Object.defineProperty(exports2, "BSONSymbol", { enumerable: true, get: function() { return bson_2.BSONSymbol; } }); Object.defineProperty(exports2, "BSONType", { enumerable: true, get: function() { return bson_2.BSONType; } }); Object.defineProperty(exports2, "calculateObjectSize", { enumerable: true, get: function() { return bson_2.calculateObjectSize; } }); Object.defineProperty(exports2, "Code", { enumerable: true, get: function() { return bson_2.Code; } }); Object.defineProperty(exports2, "DBRef", { enumerable: true, get: function() { return bson_2.DBRef; } }); Object.defineProperty(exports2, "Decimal128", { enumerable: true, get: function() { return bson_2.Decimal128; } }); Object.defineProperty(exports2, "deserialize", { enumerable: true, get: function() { return bson_2.deserialize; } }); Object.defineProperty(exports2, "Double", { enumerable: true, get: function() { return bson_2.Double; } }); Object.defineProperty(exports2, "EJSON", { enumerable: true, get: function() { return bson_2.EJSON; } }); Object.defineProperty(exports2, "Int32", { enumerable: true, get: function() { return bson_2.Int32; } }); Object.defineProperty(exports2, "Long", { enumerable: true, get: function() { return bson_2.Long; } }); Object.defineProperty(exports2, "MaxKey", { enumerable: true, get: function() { return bson_2.MaxKey; } }); Object.defineProperty(exports2, "MinKey", { enumerable: true, get: function() { return bson_2.MinKey; } }); Object.defineProperty(exports2, "ObjectId", { enumerable: true, get: function() { return bson_2.ObjectId; } }); Object.defineProperty(exports2, "serialize", { enumerable: true, get: function() { return bson_2.serialize; } }); Object.defineProperty(exports2, "Timestamp", { enumerable: true, get: function() { return bson_2.Timestamp; } }); Object.defineProperty(exports2, "UUID", { enumerable: true, get: function() { return bson_2.UUID; } }); function parseToElementsToArray(bytes, offset) { const res = bson_1.BSON.onDemand.parseToElements(bytes, offset); return Array.isArray(res) ? res : [...res]; } exports2.getInt32LE = bson_1.BSON.onDemand.NumberUtils.getInt32LE; exports2.getFloat64LE = bson_1.BSON.onDemand.NumberUtils.getFloat64LE; exports2.getBigInt64LE = bson_1.BSON.onDemand.NumberUtils.getBigInt64LE; exports2.toUTF8 = bson_1.BSON.onDemand.ByteUtils.toUTF8; function pluckBSONSerializeOptions(options) { const { fieldsAsRaw, useBigInt64, promoteValues, promoteBuffers, promoteLongs, serializeFunctions, ignoreUndefined, bsonRegExp, raw, enableUtf8Validation } = options; return { fieldsAsRaw, useBigInt64, promoteValues, promoteBuffers, promoteLongs, serializeFunctions, ignoreUndefined, bsonRegExp, raw, enableUtf8Validation }; } function resolveBSONOptions(options, parent) { const parentOptions = parent?.bsonOptions; return { raw: options?.raw ?? parentOptions?.raw ?? false, useBigInt64: options?.useBigInt64 ?? parentOptions?.useBigInt64 ?? false, promoteLongs: options?.promoteLongs ?? parentOptions?.promoteLongs ?? true, promoteValues: options?.promoteValues ?? parentOptions?.promoteValues ?? true, promoteBuffers: options?.promoteBuffers ?? parentOptions?.promoteBuffers ?? false, ignoreUndefined: options?.ignoreUndefined ?? parentOptions?.ignoreUndefined ?? false, bsonRegExp: options?.bsonRegExp ?? parentOptions?.bsonRegExp ?? false, serializeFunctions: options?.serializeFunctions ?? parentOptions?.serializeFunctions ?? false, fieldsAsRaw: options?.fieldsAsRaw ?? parentOptions?.fieldsAsRaw ?? {}, enableUtf8Validation: options?.enableUtf8Validation ?? parentOptions?.enableUtf8Validation ?? true }; } function parseUtf8ValidationOption(options) { const enableUtf8Validation = options?.enableUtf8Validation; if (enableUtf8Validation === false) { return { utf8: false }; } return { utf8: { writeErrors: false } }; } } }); // netlify/functions/node_modules/mongodb/lib/error.js var require_error = __commonJS({ "netlify/functions/node_modules/mongodb/lib/error.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.MongoWriteConcernError = exports2.MongoServerSelectionError = exports2.MongoSystemError = exports2.MongoMissingDependencyError = exports2.MongoMissingCredentialsError = exports2.MongoCompatibilityError = exports2.MongoInvalidArgumentError = exports2.MongoParseError = exports2.MongoNetworkTimeoutError = exports2.MongoNetworkError = exports2.MongoClientClosedError = exports2.MongoTopologyClosedError = exports2.MongoCursorExhaustedError = exports2.MongoServerClosedError = exports2.MongoCursorInUseError = exports2.MongoOperationTimeoutError = exports2.MongoUnexpectedServerResponseError = exports2.MongoGridFSChunkError = exports2.MongoGridFSStreamError = exports2.MongoTailableCursorError = exports2.MongoChangeStreamError = exports2.MongoClientBulkWriteExecutionError = exports2.MongoClientBulkWriteCursorError = exports2.MongoClientBulkWriteError = exports2.MongoGCPError = exports2.MongoAzureError = exports2.MongoOIDCError = exports2.MongoAWSError = exports2.MongoKerberosError = exports2.MongoExpiredSessionError = exports2.MongoTransactionError = exports2.MongoNotConnectedError = exports2.MongoDecompressionError = exports2.MongoBatchReExecutionError = exports2.MongoStalePrimaryError = exports2.MongoRuntimeError = exports2.MongoAPIError = exports2.MongoDriverError = exports2.MongoServerError = exports2.MongoError = exports2.MongoErrorLabel = exports2.GET_MORE_RESUMABLE_CODES = exports2.MONGODB_ERROR_CODES = exports2.NODE_IS_RECOVERING_ERROR_MESSAGE = exports2.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE = exports2.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE = void 0; exports2.needsRetryableWriteLabel = needsRetryableWriteLabel; exports2.isRetryableWriteError = isRetryableWriteError; exports2.isRetryableReadError = isRetryableReadError; exports2.isNodeShuttingDownError = isNodeShuttingDownError; exports2.isSDAMUnrecoverableError = isSDAMUnrecoverableError; exports2.isNetworkTimeoutError = isNetworkTimeoutError; exports2.isResumableError = isResumableError; exports2.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE = new RegExp("not master", "i"); exports2.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE = new RegExp("not master or secondary", "i"); exports2.NODE_IS_RECOVERING_ERROR_MESSAGE = new RegExp("node is recovering", "i"); exports2.MONGODB_ERROR_CODES = Object.freeze({ HostUnreachable: 6, HostNotFound: 7, AuthenticationFailed: 18, NetworkTimeout: 89, ShutdownInProgress: 91, PrimarySteppedDown: 189, ExceededTimeLimit: 262, SocketException: 9001, NotWritablePrimary: 10107, InterruptedAtShutdown: 11600, InterruptedDueToReplStateChange: 11602, NotPrimaryNoSecondaryOk: 13435, NotPrimaryOrSecondary: 13436, StaleShardVersion: 63, StaleEpoch: 150, StaleConfig: 13388, RetryChangeStream: 234, FailedToSatisfyReadPreference: 133, CursorNotFound: 43, LegacyNotPrimary: 10058, // WriteConcernTimeout is WriteConcernFailed on pre-8.1 servers WriteConcernTimeout: 64, NamespaceNotFound: 26, IllegalOperation: 20, MaxTimeMSExpired: 50, UnknownReplWriteConcern: 79, UnsatisfiableWriteConcern: 100, Reauthenticate: 391, ReadConcernMajorityNotAvailableYet: 134 }); exports2.GET_MORE_RESUMABLE_CODES = /* @__PURE__ */ new Set([ exports2.MONGODB_ERROR_CODES.HostUnreachable, exports2.MONGODB_ERROR_CODES.HostNotFound, exports2.MONGODB_ERROR_CODES.NetworkTimeout, exports2.MONGODB_ERROR_CODES.ShutdownInProgress, exports2.MONGODB_ERROR_CODES.PrimarySteppedDown, exports2.MONGODB_ERROR_CODES.ExceededTimeLimit, exports2.MONGODB_ERROR_CODES.SocketException, exports2.MONGODB_ERROR_CODES.NotWritablePrimary, exports2.MONGODB_ERROR_CODES.InterruptedAtShutdown, exports2.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, exports2.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, exports2.MONGODB_ERROR_CODES.NotPrimaryOrSecondary, exports2.MONGODB_ERROR_CODES.StaleShardVersion, exports2.MONGODB_ERROR_CODES.StaleEpoch, exports2.MONGODB_ERROR_CODES.StaleConfig, exports2.MONGODB_ERROR_CODES.RetryChangeStream, exports2.MONGODB_ERROR_CODES.FailedToSatisfyReadPreference, exports2.MONGODB_ERROR_CODES.CursorNotFound ]); exports2.MongoErrorLabel = Object.freeze({ RetryableWriteError: "RetryableWriteError", TransientTransactionError: "TransientTransactionError", UnknownTransactionCommitResult: "UnknownTransactionCommitResult", ResumableChangeStreamError: "ResumableChangeStreamError", HandshakeError: "HandshakeError", ResetPool: "ResetPool", PoolRequstedRetry: "PoolRequstedRetry", InterruptInUseConnections: "InterruptInUseConnections", NoWritesPerformed: "NoWritesPerformed" }); function isAggregateError(e) { return e != null && typeof e === "object" && "errors" in e && Array.isArray(e.errors); } var MongoError = class extends Error { get errorLabels() { return Array.from(this.errorLabelSet); } /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message, options) { super(message, options); this.errorLabelSet = /* @__PURE__ */ new Set(); } /** @internal */ static buildErrorMessage(e) { if (typeof e === "string") { return e; } if (isAggregateError(e) && e.message.length === 0) { return e.errors.length === 0 ? "AggregateError has an empty errors array. Please check the `cause` property for more information." : e.errors.map(({ message }) => message).join(", "); } return e != null && typeof e === "object" && "message" in e && typeof e.message === "string" ? e.message : "empty error message"; } get name() { return "MongoError"; } /** Legacy name for server error responses */ get errmsg() { return this.message; } /** * Checks the error to see if it has an error label * * @param label - The error label to check for * @returns returns true if the error has the provided error label */ hasErrorLabel(label) { return this.errorLabelSet.has(label); } addErrorLabel(label) { this.errorLabelSet.add(label); } }; exports2.MongoError = MongoError; var MongoServerError = class extends MongoError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message) { super(message.message || message.errmsg || message.$err || "n/a"); if (message.errorLabels) { for (const label of message.errorLabels) this.addErrorLabel(label); } this.errorResponse = message; for (const name in message) { if (name !== "errorLabels" && name !== "errmsg" && name !== "message" && name !== "errorResponse") { this[name] = message[name]; } } } get name() { return "MongoServerError"; } }; exports2.MongoServerError = MongoServerError; var MongoDriverError = class extends MongoError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message, options) { super(message, options); } get name() { return "MongoDriverError"; } }; exports2.MongoDriverError = MongoDriverError; var MongoAPIError = class extends MongoDriverError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message, options) { super(message, options); } get name() { return "MongoAPIError"; } }; exports2.MongoAPIError = MongoAPIError; var MongoRuntimeError = class extends MongoDriverError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message, options) { super(message, options); } get name() { return "MongoRuntimeError"; } }; exports2.MongoRuntimeError = MongoRuntimeError; var MongoStalePrimaryError = class extends MongoRuntimeError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message, options) { super(message, options); } get name() { return "MongoStalePrimaryError"; } }; exports2.MongoStalePrimaryError = MongoStalePrimaryError; var MongoBatchReExecutionError = class extends MongoAPIError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message = "This batch has already been executed, create new batch to execute") { super(message); } get name() { return "MongoBatchReExecutionError"; } }; exports2.MongoBatchReExecutionError = MongoBatchReExecutionError; var MongoDecompressionError = class extends MongoRuntimeError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message) { super(message); } get name() { return "MongoDecompressionError"; } }; exports2.MongoDecompressionError = MongoDecompressionError; var MongoNotConnectedError = class extends MongoAPIError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message) { super(message); } get name() { return "MongoNotConnectedError"; } }; exports2.MongoNotConnectedError = MongoNotConnectedError; var MongoTransactionError = class extends MongoAPIError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message) { super(message); } get name() { return "MongoTransactionError"; } }; exports2.MongoTransactionError = MongoTransactionError; var MongoExpiredSessionError = class extends MongoAPIError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message = "Cannot use a session that has ended") { super(message); } get name() { return "MongoExpiredSessionError"; } }; exports2.MongoExpiredSessionError = MongoExpiredSessionError; var MongoKerberosError = class extends MongoRuntimeError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message) { super(message); } get name() { return "MongoKerberosError"; } }; exports2.MongoKerberosError = MongoKerberosError; var MongoAWSError = class extends MongoRuntimeError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message, options) { super(message, options); } get name() { return "MongoAWSError"; } }; exports2.MongoAWSError = MongoAWSError; var MongoOIDCError = class extends MongoRuntimeError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message) { super(message); } get name() { return "MongoOIDCError"; } }; exports2.MongoOIDCError = MongoOIDCError; var MongoAzureError = class extends MongoOIDCError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message) { super(message); } get name() { return "MongoAzureError"; } }; exports2.MongoAzureError = MongoAzureError; var MongoGCPError = class extends MongoOIDCError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message) { super(message); } get name() { return "MongoGCPError"; } }; exports2.MongoGCPError = MongoGCPError; var MongoClientBulkWriteError = class extends MongoServerError { /** * Initialize the client bulk write error. * @param message - The error message. */ constructor(message) { super(message); this.writeConcernErrors = []; this.writeErrors = /* @__PURE__ */ new Map(); } get name() { return "MongoClientBulkWriteError"; } }; exports2.MongoClientBulkWriteError = MongoClientBulkWriteError; var MongoClientBulkWriteCursorError = class extends MongoRuntimeError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message) { super(message); } get name() { return "MongoClientBulkWriteCursorError"; } }; exports2.MongoClientBulkWriteCursorError = MongoClientBulkWriteCursorError; var MongoClientBulkWriteExecutionError = class extends MongoRuntimeError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message) { super(message); } get name() { return "MongoClientBulkWriteExecutionError"; } }; exports2.MongoClientBulkWriteExecutionError = MongoClientBulkWriteExecutionError; var MongoChangeStreamError = class extends MongoRuntimeError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message) { super(message); } get name() { return "MongoChangeStreamError"; } }; exports2.MongoChangeStreamError = MongoChangeStreamError; var MongoTailableCursorError = class extends MongoAPIError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message = "Tailable cursor does not support this operation") { super(message); } get name() { return "MongoTailableCursorError"; } }; exports2.MongoTailableCursorError = MongoTailableCursorError; var MongoGridFSStreamError = class extends MongoRuntimeError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message) { super(message); } get name() { return "MongoGridFSStreamError"; } }; exports2.MongoGridFSStreamError = MongoGridFSStreamError; var MongoGridFSChunkError = class extends MongoRuntimeError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message) { super(message); } get name() { return "MongoGridFSChunkError"; } }; exports2.MongoGridFSChunkError = MongoGridFSChunkError; var MongoUnexpectedServerResponseError = class extends MongoRuntimeError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message, options) { super(message, options); } get name() { return "MongoUnexpectedServerResponseError"; } }; exports2.MongoUnexpectedServerResponseError = MongoUnexpectedServerResponseError; var MongoOperationTimeoutError = class extends MongoDriverError { get name() { return "MongoOperationTimeoutError"; } }; exports2.MongoOperationTimeoutError = MongoOperationTimeoutError; var MongoCursorInUseError = class extends MongoAPIError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message = "Cursor is already initialized") { super(message); } get name() { return "MongoCursorInUseError"; } }; exports2.MongoCursorInUseError = MongoCursorInUseError; var MongoServerClosedError = class extends MongoAPIError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message = "Server is closed") { super(message); } get name() { return "MongoServerClosedError"; } }; exports2.MongoServerClosedError = MongoServerClosedError; var MongoCursorExhaustedError = class extends MongoAPIError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message) { super(message || "Cursor is exhausted"); } get name() { return "MongoCursorExhaustedError"; } }; exports2.MongoCursorExhaustedError = MongoCursorExhaustedError; var MongoTopologyClosedError = class extends MongoAPIError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message = "Topology is closed") { super(message); } get name() { return "MongoTopologyClosedError"; } }; exports2.MongoTopologyClosedError = MongoTopologyClosedError; var MongoClientClosedError = class extends MongoAPIError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor() { super("Operation interrupted because client was closed"); } get name() { return "MongoClientClosedError"; } }; exports2.MongoClientClosedError = MongoClientClosedError; var MongoNetworkError = class extends MongoError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message, options) { super(message, { cause: options?.cause }); this.beforeHandshake = !!options?.beforeHandshake; } get name() { return "MongoNetworkError"; } }; exports2.MongoNetworkError = MongoNetworkError; var MongoNetworkTimeoutError = class extends MongoNetworkError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message, options) { super(message, options); } get name() { return "MongoNetworkTimeoutError"; } }; exports2.MongoNetworkTimeoutError = MongoNetworkTimeoutError; var MongoParseError = class extends MongoDriverError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message) { super(message); } get name() { return "MongoParseError"; } }; exports2.MongoParseError = MongoParseError; var MongoInvalidArgumentError = class extends MongoAPIError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message, options) { super(message, options); } get name() { return "MongoInvalidArgumentError"; } }; exports2.MongoInvalidArgumentError = MongoInvalidArgumentError; var MongoCompatibilityError = class extends MongoAPIError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message) { super(message); } get name() { return "MongoCompatibilityError"; } }; exports2.MongoCompatibilityError = MongoCompatibilityError; var MongoMissingCredentialsError = class extends MongoAPIError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message) { super(message); } get name() { return "MongoMissingCredentialsError"; } }; exports2.MongoMissingCredentialsError = MongoMissingCredentialsError; var MongoMissingDependencyError = class extends MongoAPIError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message, options) { super(message, options); this.dependencyName = options.dependencyName; } get name() { return "MongoMissingDependencyError"; } }; exports2.MongoMissingDependencyError = MongoMissingDependencyError; var MongoSystemError = class extends MongoError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message, reason) { if (reason && reason.error) { super(MongoError.buildErrorMessage(reason.error.message || reason.error), { cause: reason.error }); } else { super(message); } if (reason) { this.reason = reason; } this.code = reason.error?.code; } get name() { return "MongoSystemError"; } }; exports2.MongoSystemError = MongoSystemError; var MongoServerSelectionError = class extends MongoSystemError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message, reason) { super(message, reason); } get name() { return "MongoServerSelectionError"; } }; exports2.MongoServerSelectionError = MongoServerSelectionError; var MongoWriteConcernError = class extends MongoServerError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(result) { super({ ...result.writeConcernError, ...result }); this.errInfo = result.writeConcernError.errInfo; this.result = result; } get name() { return "MongoWriteConcernError"; } }; exports2.MongoWriteConcernError = MongoWriteConcernError; var RETRYABLE_READ_ERROR_CODES = /* @__PURE__ */ new Set([ exports2.MONGODB_ERROR_CODES.HostUnreachable, exports2.MONGODB_ERROR_CODES.HostNotFound, exports2.MONGODB_ERROR_CODES.NetworkTimeout, exports2.MONGODB_ERROR_CODES.ShutdownInProgress, exports2.MONGODB_ERROR_CODES.PrimarySteppedDown, exports2.MONGODB_ERROR_CODES.SocketException, exports2.MONGODB_ERROR_CODES.NotWritablePrimary, exports2.MONGODB_ERROR_CODES.InterruptedAtShutdown, exports2.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, exports2.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, exports2.MONGODB_ERROR_CODES.NotPrimaryOrSecondary, exports2.MONGODB_ERROR_CODES.ExceededTimeLimit, exports2.MONGODB_ERROR_CODES.ReadConcernMajorityNotAvailableYet ]); var RETRYABLE_WRITE_ERROR_CODES = RETRYABLE_READ_ERROR_CODES; function needsRetryableWriteLabel(error, maxWireVersion, serverType) { if (error instanceof MongoNetworkError) { return true; } if (error instanceof MongoError) { if ((maxWireVersion >= 9 || isRetryableWriteError(error)) && !error.hasErrorLabel(exports2.MongoErrorLabel.HandshakeError)) { return false; } } if (error instanceof MongoWriteConcernError) { if (serverType === "Mongos" && maxWireVersion < 9) { return RETRYABLE_WRITE_ERROR_CODES.has(error.result.code ?? 0); } const code = error.result.writeConcernError.code ?? Number(error.code); return RETRYABLE_WRITE_ERROR_CODES.has(Number.isNaN(code) ? 0 : code); } if (error instanceof MongoError) { return RETRYABLE_WRITE_ERROR_CODES.has(Number(error.code)); } const isNotWritablePrimaryError2 = exports2.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(error.message); if (isNotWritablePrimaryError2) { return true; } const isNodeIsRecoveringError = exports2.NODE_IS_RECOVERING_ERROR_MESSAGE.test(error.message); if (isNodeIsRecoveringError) { return true; } return false; } function isRetryableWriteError(error) { return error.hasErrorLabel(exports2.MongoErrorLabel.RetryableWriteError) || error.hasErrorLabel(exports2.MongoErrorLabel.PoolRequstedRetry); } function isRetryableReadError(error) { const hasRetryableErrorCode = typeof error.code === "number" ? RETRYABLE_READ_ERROR_CODES.has(error.code) : false; if (hasRetryableErrorCode) { return true; } if (error instanceof MongoNetworkError) { return true; } const isNotWritablePrimaryError2 = exports2.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(error.message); if (isNotWritablePrimaryError2) { return true; } const isNodeIsRecoveringError = exports2.NODE_IS_RECOVERING_ERROR_MESSAGE.test(error.message); if (isNodeIsRecoveringError) { return true; } return false; } var SDAM_RECOVERING_CODES = /* @__PURE__ */ new Set([ exports2.MONGODB_ERROR_CODES.ShutdownInProgress, exports2.MONGODB_ERROR_CODES.PrimarySteppedDown, exports2.MONGODB_ERROR_CODES.InterruptedAtShutdown, exports2.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, exports2.MONGODB_ERROR_CODES.NotPrimaryOrSecondary ]); var SDAM_NOT_PRIMARY_CODES = /* @__PURE__ */ new Set([ exports2.MONGODB_ERROR_CODES.NotWritablePrimary, exports2.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, exports2.MONGODB_ERROR_CODES.LegacyNotPrimary ]); var SDAM_NODE_SHUTTING_DOWN_ERROR_CODES = /* @__PURE__ */ new Set([ exports2.MONGODB_ERROR_CODES.InterruptedAtShutdown, exports2.MONGODB_ERROR_CODES.ShutdownInProgress ]); function isRecoveringError(err) { if (typeof err.code === "number") { return SDAM_RECOVERING_CODES.has(err.code); } return exports2.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE.test(err.message) || exports2.NODE_IS_RECOVERING_ERROR_MESSAGE.test(err.message); } function isNotWritablePrimaryError(err) { if (typeof err.code === "number") { return SDAM_NOT_PRIMARY_CODES.has(err.code); } if (isRecoveringError(err)) { return false; } return exports2.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(err.message); } function isNodeShuttingDownError(err) { return !!(typeof err.code === "number" && SDAM_NODE_SHUTTING_DOWN_ERROR_CODES.has(err.code)); } function isSDAMUnrecoverableError(error) { if (error instanceof MongoParseError || error == null) { return true; } return isRecoveringError(error) || isNotWritablePrimaryError(error); } function isNetworkTimeoutError(err) { return !!(err instanceof MongoNetworkError && err.message.match(/timed out/)); } function isResumableError(error, wireVersion) { if (error == null || !(error instanceof MongoError)) { return false; } if (error instanceof MongoNetworkError) { return true; } if (wireVersion != null && wireVersion >= 9) { if (error.code === exports2.MONGODB_ERROR_CODES.CursorNotFound) { return true; } return error.hasErrorLabel(exports2.MongoErrorLabel.ResumableChangeStreamError); } if (typeof error.code === "number") { return exports2.GET_MORE_RESUMABLE_CODES.has(error.code); } return false; } } }); // netlify/functions/node_modules/mongodb/lib/constants.js var require_constants = __commonJS({ "netlify/functions/node_modules/mongodb/lib/constants.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.END = exports2.CHANGE = exports2.INIT = exports2.MORE = exports2.RESPONSE = exports2.SERVER_HEARTBEAT_FAILED = exports2.SERVER_HEARTBEAT_SUCCEEDED = exports2.SERVER_HEARTBEAT_STARTED = exports2.COMMAND_FAILED = exports2.COMMAND_SUCCEEDED = exports2.COMMAND_STARTED = exports2.CLUSTER_TIME_RECEIVED = exports2.CONNECTION_CHECKED_IN = exports2.CONNECTION_CHECKED_OUT = exports2.CONNECTION_CHECK_OUT_FAILED = exports2.CONNECTION_CHECK_OUT_STARTED = exports2.CONNECTION_CLOSED = exports2.CONNECTION_READY = exports2.CONNECTION_CREATED = exports2.CONNECTION_POOL_READY = exports2.CONNECTION_POOL_CLEARED = exports2.CONNECTION_POOL_CLOSED = exports2.CONNECTION_POOL_CREATED = exports2.WAITING_FOR_SUITABLE_SERVER = exports2.SERVER_SELECTION_SUCCEEDED = exports2.SERVER_SELECTION_FAILED = exports2.SERVER_SELECTION_STARTED = exports2.TOPOLOGY_DESCRIPTION_CHANGED = exports2.TOPOLOGY_CLOSED = exports2.TOPOLOGY_OPENING = exports2.SERVER_DESCRIPTION_CHANGED = exports2.SERVER_CLOSED = exports2.SERVER_OPENING = exports2.DESCRIPTION_RECEIVED = exports2.UNPINNED = exports2.PINNED = exports2.MESSAGE = exports2.ENDED = exports2.CLOSED = exports2.CONNECT = exports2.OPEN = exports2.CLOSE = exports2.TIMEOUT = exports2.ERROR = exports2.SYSTEM_JS_COLLECTION = exports2.SYSTEM_COMMAND_COLLECTION = exports2.SYSTEM_USER_COLLECTION = exports2.SYSTEM_PROFILE_COLLECTION = exports2.SYSTEM_INDEX_COLLECTION = exports2.SYSTEM_NAMESPACE_COLLECTION = void 0; exports2.kDecoratedKeys = exports2.kDecorateResult = exports2.LEGACY_HELLO_COMMAND_CAMEL_CASE = exports2.LEGACY_HELLO_COMMAND = exports2.MONGO_CLIENT_EVENTS = exports2.LOCAL_SERVER_EVENTS = exports2.SERVER_RELAY_EVENTS = exports2.APM_EVENTS = exports2.TOPOLOGY_EVENTS = exports2.CMAP_EVENTS = exports2.HEARTBEAT_EVENTS = exports2.RESUME_TOKEN_CHANGED = void 0; exports2.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces"; exports2.SYSTEM_INDEX_COLLECTION = "system.indexes"; exports2.SYSTEM_PROFILE_COLLECTION = "system.profile"; exports2.SYSTEM_USER_COLLECTION = "system.users"; exports2.SYSTEM_COMMAND_COLLECTION = "$cmd"; exports2.SYSTEM_JS_COLLECTION = "system.js"; exports2.ERROR = "error"; exports2.TIMEOUT = "timeout"; exports2.CLOSE = "close"; exports2.OPEN = "open"; exports2.CONNECT = "connect"; exports2.CLOSED = "closed"; exports2.ENDED = "ended"; exports2.MESSAGE = "message"; exports2.PINNED = "pinned"; exports2.UNPINNED = "unpinned"; exports2.DESCRIPTION_RECEIVED = "descriptionReceived"; exports2.SERVER_OPENING = "serverOpening"; exports2.SERVER_CLOSED = "serverClosed"; exports2.SERVER_DESCRIPTION_CHANGED = "serverDescriptionChanged"; exports2.TOPOLOGY_OPENING = "topologyOpening"; exports2.TOPOLOGY_CLOSED = "topologyClosed"; exports2.TOPOLOGY_DESCRIPTION_CHANGED = "topologyDescriptionChanged"; exports2.SERVER_SELECTION_STARTED = "serverSelectionStarted"; exports2.SERVER_SELECTION_FAILED = "serverSelectionFailed"; exports2.SERVER_SELECTION_SUCCEEDED = "serverSelectionSucceeded"; exports2.WAITING_FOR_SUITABLE_SERVER = "waitingForSuitableServer"; exports2.CONNECTION_POOL_CREATED = "connectionPoolCreated"; exports2.CONNECTION_POOL_CLOSED = "connectionPoolClosed"; exports2.CONNECTION_POOL_CLEARED = "connectionPoolCleared"; exports2.CONNECTION_POOL_READY = "connectionPoolReady"; exports2.CONNECTION_CREATED = "connectionCreated"; exports2.CONNECTION_READY = "connectionReady"; exports2.CONNECTION_CLOSED = "connectionClosed"; exports2.CONNECTION_CHECK_OUT_STARTED = "connectionCheckOutStarted"; exports2.CONNECTION_CHECK_OUT_FAILED = "connectionCheckOutFailed"; exports2.CONNECTION_CHECKED_OUT = "connectionCheckedOut"; exports2.CONNECTION_CHECKED_IN = "connectionCheckedIn"; exports2.CLUSTER_TIME_RECEIVED = "clusterTimeReceived"; exports2.COMMAND_STARTED = "commandStarted"; exports2.COMMAND_SUCCEEDED = "commandSucceeded"; exports2.COMMAND_FAILED = "commandFailed"; exports2.SERVER_HEARTBEAT_STARTED = "serverHeartbeatStarted"; exports2.SERVER_HEARTBEAT_SUCCEEDED = "serverHeartbeatSucceeded"; exports2.SERVER_HEARTBEAT_FAILED = "serverHeartbeatFailed"; exports2.RESPONSE = "response"; exports2.MORE = "more"; exports2.INIT = "init"; exports2.CHANGE = "change"; exports2.END = "end"; exports2.RESUME_TOKEN_CHANGED = "resumeTokenChanged"; exports2.HEARTBEAT_EVENTS = Object.freeze([ exports2.SERVER_HEARTBEAT_STARTED, exports2.SERVER_HEARTBEAT_SUCCEEDED, exports2.SERVER_HEARTBEAT_FAILED ]); exports2.CMAP_EVENTS = Object.freeze([ exports2.CONNECTION_POOL_CREATED, exports2.CONNECTION_POOL_READY, exports2.CONNECTION_POOL_CLEARED, exports2.CONNECTION_POOL_CLOSED, exports2.CONNECTION_CREATED, exports2.CONNECTION_READY, exports2.CONNECTION_CLOSED, exports2.CONNECTION_CHECK_OUT_STARTED, exports2.CONNECTION_CHECK_OUT_FAILED, exports2.CONNECTION_CHECKED_OUT, exports2.CONNECTION_CHECKED_IN ]); exports2.TOPOLOGY_EVENTS = Object.freeze([ exports2.SERVER_OPENING, exports2.SERVER_CLOSED, exports2.SERVER_DESCRIPTION_CHANGED, exports2.TOPOLOGY_OPENING, exports2.TOPOLOGY_CLOSED, exports2.TOPOLOGY_DESCRIPTION_CHANGED, exports2.ERROR, exports2.TIMEOUT, exports2.CLOSE ]); exports2.APM_EVENTS = Object.freeze([ exports2.COMMAND_STARTED, exports2.COMMAND_SUCCEEDED, exports2.COMMAND_FAILED ]); exports2.SERVER_RELAY_EVENTS = Object.freeze([ exports2.SERVER_HEARTBEAT_STARTED, exports2.SERVER_HEARTBEAT_SUCCEEDED, exports2.SERVER_HEARTBEAT_FAILED, exports2.COMMAND_STARTED, exports2.COMMAND_SUCCEEDED, exports2.COMMAND_FAILED, ...exports2.CMAP_EVENTS ]); exports2.LOCAL_SERVER_EVENTS = Object.freeze([ exports2.CONNECT, exports2.DESCRIPTION_RECEIVED, exports2.CLOSED, exports2.ENDED ]); exports2.MONGO_CLIENT_EVENTS = Object.freeze([ ...exports2.CMAP_EVENTS, ...exports2.APM_EVENTS, ...exports2.TOPOLOGY_EVENTS, ...exports2.HEARTBEAT_EVENTS ]); exports2.LEGACY_HELLO_COMMAND = "ismaster"; exports2.LEGACY_HELLO_COMMAND_CAMEL_CASE = "isMaster"; exports2.kDecorateResult = Symbol.for("@@mdb.decorateDecryptionResult"); exports2.kDecoratedKeys = Symbol.for("@@mdb.decryptedKeys"); } }); // netlify/functions/node_modules/mongodb/lib/cmap/wire_protocol/constants.js var require_constants2 = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/wire_protocol/constants.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.OP_MSG = exports2.OP_COMPRESSED = exports2.OP_DELETE = exports2.OP_QUERY = exports2.OP_INSERT = exports2.OP_UPDATE = exports2.OP_REPLY = exports2.MIN_SUPPORTED_QE_SERVER_VERSION = exports2.MIN_SUPPORTED_QE_WIRE_VERSION = exports2.MAX_SUPPORTED_WIRE_VERSION = exports2.MIN_SUPPORTED_WIRE_VERSION = exports2.MAX_SUPPORTED_SERVER_VERSION = exports2.MIN_SUPPORTED_SERVER_VERSION = void 0; exports2.MIN_SUPPORTED_SERVER_VERSION = "4.2"; exports2.MAX_SUPPORTED_SERVER_VERSION = "8.0"; exports2.MIN_SUPPORTED_WIRE_VERSION = 8; exports2.MAX_SUPPORTED_WIRE_VERSION = 25; exports2.MIN_SUPPORTED_QE_WIRE_VERSION = 21; exports2.MIN_SUPPORTED_QE_SERVER_VERSION = "7.0"; exports2.OP_REPLY = 1; exports2.OP_UPDATE = 2001; exports2.OP_INSERT = 2002; exports2.OP_QUERY = 2004; exports2.OP_DELETE = 2006; exports2.OP_COMPRESSED = 2012; exports2.OP_MSG = 2013; } }); // netlify/functions/node_modules/mongodb/lib/read_concern.js var require_read_concern = __commonJS({ "netlify/functions/node_modules/mongodb/lib/read_concern.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ReadConcern = exports2.ReadConcernLevel = void 0; exports2.ReadConcernLevel = Object.freeze({ local: "local", majority: "majority", linearizable: "linearizable", available: "available", snapshot: "snapshot" }); var ReadConcern = class _ReadConcern { /** Constructs a ReadConcern from the read concern level.*/ constructor(level) { this.level = exports2.ReadConcernLevel[level] ?? level; } /** * Construct a ReadConcern given an options object. * * @param options - The options object from which to extract the write concern. */ static fromOptions(options) { if (options == null) { return; } if (options.readConcern) { const { readConcern } = options; if (readConcern instanceof _ReadConcern) { return readConcern; } else if (typeof readConcern === "string") { return new _ReadConcern(readConcern); } else if ("level" in readConcern && readConcern.level) { return new _ReadConcern(readConcern.level); } } if (options.level) { return new _ReadConcern(options.level); } return; } static get MAJORITY() { return exports2.ReadConcernLevel.majority; } static get AVAILABLE() { return exports2.ReadConcernLevel.available; } static get LINEARIZABLE() { return exports2.ReadConcernLevel.linearizable; } static get SNAPSHOT() { return exports2.ReadConcernLevel.snapshot; } toJSON() { return { level: this.level }; } }; exports2.ReadConcern = ReadConcern; } }); // netlify/functions/node_modules/mongodb/lib/read_preference.js var require_read_preference = __commonJS({ "netlify/functions/node_modules/mongodb/lib/read_preference.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ReadPreference = exports2.ReadPreferenceMode = void 0; var error_1 = require_error(); exports2.ReadPreferenceMode = Object.freeze({ primary: "primary", primaryPreferred: "primaryPreferred", secondary: "secondary", secondaryPreferred: "secondaryPreferred", nearest: "nearest" }); var ReadPreference = class _ReadPreference { /** * @param mode - A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) * @param tags - A tag set used to target reads to members with the specified tag(s). tagSet is not available if using read preference mode primary. * @param options - Additional read preference options */ constructor(mode, tags, options) { if (!_ReadPreference.isValid(mode)) { throw new error_1.MongoInvalidArgumentError(`Invalid read preference mode ${JSON.stringify(mode)}`); } if (options == null && typeof tags === "object" && !Array.isArray(tags)) { options = tags; tags = void 0; } else if (tags && !Array.isArray(tags)) { throw new error_1.MongoInvalidArgumentError("ReadPreference tags must be an array"); } this.mode = mode; this.tags = tags; this.hedge = options?.hedge; this.maxStalenessSeconds = void 0; this.minWireVersion = void 0; options = options ?? {}; if (options.maxStalenessSeconds != null) { if (options.maxStalenessSeconds <= 0) { throw new error_1.MongoInvalidArgumentError("maxStalenessSeconds must be a positive integer"); } this.maxStalenessSeconds = options.maxStalenessSeconds; this.minWireVersion = 5; } if (this.mode === _ReadPreference.PRIMARY) { if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) { throw new error_1.MongoInvalidArgumentError("Primary read preference cannot be combined with tags"); } if (this.maxStalenessSeconds) { throw new error_1.MongoInvalidArgumentError("Primary read preference cannot be combined with maxStalenessSeconds"); } if (this.hedge) { throw new error_1.MongoInvalidArgumentError("Primary read preference cannot be combined with hedge"); } } } // Support the deprecated `preference` property introduced in the porcelain layer get preference() { return this.mode; } static fromString(mode) { return new _ReadPreference(mode); } /** * Construct a ReadPreference given an options object. * * @param options - The options object from which to extract the read preference. */ static fromOptions(options) { if (!options) return; const readPreference = options.readPreference ?? options.session?.transaction.options.readPreference; const readPreferenceTags = options.readPreferenceTags; if (readPreference == null) { return; } if (typeof readPreference === "string") { return new _ReadPreference(readPreference, readPreferenceTags, { maxStalenessSeconds: options.maxStalenessSeconds, hedge: options.hedge }); } else if (!(readPreference instanceof _ReadPreference) && typeof readPreference === "object") { const mode = readPreference.mode || readPreference.preference; if (mode && typeof mode === "string") { return new _ReadPreference(mode, readPreference.tags ?? readPreferenceTags, { maxStalenessSeconds: readPreference.maxStalenessSeconds, hedge: options.hedge }); } } if (readPreferenceTags) { readPreference.tags = readPreferenceTags; } return readPreference; } /** * Replaces options.readPreference with a ReadPreference instance */ static translate(options) { if (options.readPreference == null) return options; const r = options.readPreference; if (typeof r === "string") { options.readPreference = new _ReadPreference(r); } else if (r && !(r instanceof _ReadPreference) && typeof r === "object") { const mode = r.mode || r.preference; if (mode && typeof mode === "string") { options.readPreference = new _ReadPreference(mode, r.tags, { maxStalenessSeconds: r.maxStalenessSeconds }); } } else if (!(r instanceof _ReadPreference)) { throw new error_1.MongoInvalidArgumentError(`Invalid read preference: ${r}`); } return options; } /** * Validate if a mode is legal * * @param mode - The string representing the read preference mode. */ static isValid(mode) { const VALID_MODES = /* @__PURE__ */ new Set([ _ReadPreference.PRIMARY, _ReadPreference.PRIMARY_PREFERRED, _ReadPreference.SECONDARY, _ReadPreference.SECONDARY_PREFERRED, _ReadPreference.NEAREST, null ]); return VALID_MODES.has(mode); } /** * Validate if a mode is legal * * @param mode - The string representing the read preference mode. */ isValid(mode) { return _ReadPreference.isValid(typeof mode === "string" ? mode : this.mode); } /** * Indicates that this readPreference needs the "SecondaryOk" bit when sent over the wire * @see https://www.mongodb.com/docs/manual/reference/mongodb-wire-protocol/#op-query */ secondaryOk() { const NEEDS_SECONDARYOK = /* @__PURE__ */ new Set([ _ReadPreference.PRIMARY_PREFERRED, _ReadPreference.SECONDARY, _ReadPreference.SECONDARY_PREFERRED, _ReadPreference.NEAREST ]); return NEEDS_SECONDARYOK.has(this.mode); } /** * Check if the two ReadPreferences are equivalent * * @param readPreference - The read preference with which to check equality */ equals(readPreference) { return readPreference.mode === this.mode; } /** Return JSON representation */ toJSON() { const readPreference = { mode: this.mode }; if (Array.isArray(this.tags)) readPreference.tags = this.tags; if (this.maxStalenessSeconds) readPreference.maxStalenessSeconds = this.maxStalenessSeconds; if (this.hedge) readPreference.hedge = this.hedge; return readPreference; } }; exports2.ReadPreference = ReadPreference; ReadPreference.PRIMARY = exports2.ReadPreferenceMode.primary; ReadPreference.PRIMARY_PREFERRED = exports2.ReadPreferenceMode.primaryPreferred; ReadPreference.SECONDARY = exports2.ReadPreferenceMode.secondary; ReadPreference.SECONDARY_PREFERRED = exports2.ReadPreferenceMode.secondaryPreferred; ReadPreference.NEAREST = exports2.ReadPreferenceMode.nearest; ReadPreference.primary = new ReadPreference(exports2.ReadPreferenceMode.primary); ReadPreference.primaryPreferred = new ReadPreference(exports2.ReadPreferenceMode.primaryPreferred); ReadPreference.secondary = new ReadPreference(exports2.ReadPreferenceMode.secondary); ReadPreference.secondaryPreferred = new ReadPreference(exports2.ReadPreferenceMode.secondaryPreferred); ReadPreference.nearest = new ReadPreference(exports2.ReadPreferenceMode.nearest); } }); // netlify/functions/node_modules/mongodb/lib/sdam/common.js var require_common = __commonJS({ "netlify/functions/node_modules/mongodb/lib/sdam/common.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ServerType = exports2.TopologyType = exports2.STATE_CONNECTED = exports2.STATE_CONNECTING = exports2.STATE_CLOSED = exports2.STATE_CLOSING = void 0; exports2._advanceClusterTime = _advanceClusterTime; exports2.STATE_CLOSING = "closing"; exports2.STATE_CLOSED = "closed"; exports2.STATE_CONNECTING = "connecting"; exports2.STATE_CONNECTED = "connected"; exports2.TopologyType = Object.freeze({ Single: "Single", ReplicaSetNoPrimary: "ReplicaSetNoPrimary", ReplicaSetWithPrimary: "ReplicaSetWithPrimary", Sharded: "Sharded", Unknown: "Unknown", LoadBalanced: "LoadBalanced" }); exports2.ServerType = Object.freeze({ Standalone: "Standalone", Mongos: "Mongos", PossiblePrimary: "PossiblePrimary", RSPrimary: "RSPrimary", RSSecondary: "RSSecondary", RSArbiter: "RSArbiter", RSOther: "RSOther", RSGhost: "RSGhost", Unknown: "Unknown", LoadBalancer: "LoadBalancer" }); function _advanceClusterTime(entity, $clusterTime) { if (entity.clusterTime == null) { entity.clusterTime = $clusterTime; } else { if ($clusterTime.clusterTime.greaterThan(entity.clusterTime.clusterTime)) { entity.clusterTime = $clusterTime; } } } } }); // netlify/functions/node_modules/mongodb/lib/cmap/wire_protocol/on_demand/document.js var require_document = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/wire_protocol/on_demand/document.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.OnDemandDocument = void 0; var bson_1 = require_bson2(); var BSONElementOffset = { type: 0, nameOffset: 1, nameLength: 2, offset: 3, length: 4 }; var OnDemandDocument = class _OnDemandDocument { constructor(bson, offset = 0, isArray = false, elements) { this.cache = /* @__PURE__ */ Object.create(null); this.indexFound = /* @__PURE__ */ Object.create(null); this.bson = bson; this.offset = offset; this.isArray = isArray; this.elements = elements ?? (0, bson_1.parseToElementsToArray)(this.bson, offset); } /** Only supports basic latin strings */ isElementName(name, element) { const nameLength = element[BSONElementOffset.nameLength]; const nameOffset = element[BSONElementOffset.nameOffset]; if (name.length !== nameLength) return false; const nameEnd = nameOffset + nameLength; for (let byteIndex = nameOffset, charIndex = 0; charIndex < name.length && byteIndex < nameEnd; charIndex++, byteIndex++) { if (this.bson[byteIndex] !== name.charCodeAt(charIndex)) return false; } return true; } /** * Seeks into the elements array for an element matching the given name. * * @remarks * Caching: * - Caches the existence of a property making subsequent look ups for non-existent properties return immediately * - Caches names mapped to elements to avoid reiterating the array and comparing the name again * - Caches the index at which an element has been found to prevent rechecking against elements already determined to belong to another name * * @param name - a basic latin string name of a BSON element * @returns */ getElement(name) { const cachedElement = this.cache[name]; if (cachedElement === false) return null; if (cachedElement != null) { return cachedElement; } if (typeof name === "number") { if (this.isArray) { if (name < this.elements.length) { const element = this.elements[name]; const cachedElement2 = { element, value: void 0 }; this.cache[name] = cachedElement2; this.indexFound[name] = true; return cachedElement2; } else { return null; } } else { return null; } } for (let index = 0; index < this.elements.length; index++) { const element = this.elements[index]; if (!(index in this.indexFound) && this.isElementName(name, element)) { const cachedElement2 = { element, value: void 0 }; this.cache[name] = cachedElement2; this.indexFound[index] = true; return cachedElement2; } } this.cache[name] = false; return null; } toJSValue(element, as) { const type = element[BSONElementOffset.type]; const offset = element[BSONElementOffset.offset]; const length = element[BSONElementOffset.length]; if (as !== type) { return null; } switch (as) { case bson_1.BSONType.null: case bson_1.BSONType.undefined: return null; case bson_1.BSONType.double: return (0, bson_1.getFloat64LE)(this.bson, offset); case bson_1.BSONType.int: return (0, bson_1.getInt32LE)(this.bson, offset); case bson_1.BSONType.long: return (0, bson_1.getBigInt64LE)(this.bson, offset); case bson_1.BSONType.bool: return Boolean(this.bson[offset]); case bson_1.BSONType.objectId: return new bson_1.ObjectId(this.bson.subarray(offset, offset + 12)); case bson_1.BSONType.timestamp: return new bson_1.Timestamp((0, bson_1.getBigInt64LE)(this.bson, offset)); case bson_1.BSONType.string: return (0, bson_1.toUTF8)(this.bson, offset + 4, offset + length - 1, false); case bson_1.BSONType.binData: { const totalBinarySize = (0, bson_1.getInt32LE)(this.bson, offset); const subType = this.bson[offset + 4]; if (subType === 2) { const subType2BinarySize = (0, bson_1.getInt32LE)(this.bson, offset + 1 + 4); if (subType2BinarySize < 0) throw new bson_1.BSONError("Negative binary type element size found for subtype 0x02"); if (subType2BinarySize > totalBinarySize - 4) throw new bson_1.BSONError("Binary type with subtype 0x02 contains too long binary size"); if (subType2BinarySize < totalBinarySize - 4) throw new bson_1.BSONError("Binary type with subtype 0x02 contains too short binary size"); return new bson_1.Binary(this.bson.subarray(offset + 1 + 4 + 4, offset + 1 + 4 + 4 + subType2BinarySize), 2); } return new bson_1.Binary(this.bson.subarray(offset + 1 + 4, offset + 1 + 4 + totalBinarySize), subType); } case bson_1.BSONType.date: return new Date(Number((0, bson_1.getBigInt64LE)(this.bson, offset))); case bson_1.BSONType.object: return new _OnDemandDocument(this.bson, offset); case bson_1.BSONType.array: return new _OnDemandDocument(this.bson, offset, true); default: throw new bson_1.BSONError(`Unsupported BSON type: ${as}`); } } /** * Returns the number of elements in this BSON document */ size() { return this.elements.length; } /** * Checks for the existence of an element by name. * * @remarks * Uses `getElement` with the expectation that will populate caches such that a `has` call * followed by a `getElement` call will not repeat the cost paid by the first look up. * * @param name - element name */ has(name) { const cachedElement = this.cache[name]; if (cachedElement === false) return false; if (cachedElement != null) return true; return this.getElement(name) != null; } get(name, as, required) { const element = this.getElement(name); if (element == null) { if (required === true) { throw new bson_1.BSONError(`BSON element "${name}" is missing`); } else { return null; } } if (element.value == null) { const value = this.toJSValue(element.element, as); if (value == null) { if (required === true) { throw new bson_1.BSONError(`BSON element "${name}" is missing`); } else { return null; } } element.value = value; } return element.value; } getNumber(name, required) { const maybeBool = this.get(name, bson_1.BSONType.bool); const bool = maybeBool == null ? null : maybeBool ? 1 : 0; const maybeLong = this.get(name, bson_1.BSONType.long); const long = maybeLong == null ? null : Number(maybeLong); const result = bool ?? long ?? this.get(name, bson_1.BSONType.int) ?? this.get(name, bson_1.BSONType.double); if (required === true && result == null) { throw new bson_1.BSONError(`BSON element "${name}" is missing`); } return result; } /** * Deserialize this object, DOES NOT cache result so avoid multiple invocations * @param options - BSON deserialization options */ toObject(options) { return (0, bson_1.deserialize)(this.bson, { ...options, index: this.offset, allowObjectSmallerThanBufferSize: true }); } /** Returns this document's bytes only */ toBytes() { const size = (0, bson_1.getInt32LE)(this.bson, this.offset); return this.bson.subarray(this.offset, this.offset + size); } }; exports2.OnDemandDocument = OnDemandDocument; } }); // netlify/functions/node_modules/mongodb/lib/cmap/wire_protocol/responses.js var require_responses = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/wire_protocol/responses.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ClientBulkWriteCursorResponse = exports2.ExplainedCursorResponse = exports2.CursorResponse = exports2.MongoDBResponse = void 0; exports2.isErrorResponse = isErrorResponse; var bson_1 = require_bson2(); var error_1 = require_error(); var utils_1 = require_utils(); var document_1 = require_document(); var BSONElementOffset = { type: 0, nameOffset: 1, nameLength: 2, offset: 3, length: 4 }; function isErrorResponse(bson, elements) { for (let eIdx = 0; eIdx < elements.length; eIdx++) { const element = elements[eIdx]; if (element[BSONElementOffset.nameLength] === 2) { const nameOffset = element[BSONElementOffset.nameOffset]; if (bson[nameOffset] === 111 && bson[nameOffset + 1] === 107) { const valueOffset = element[BSONElementOffset.offset]; const valueLength = element[BSONElementOffset.length]; for (let i = valueOffset; i < valueOffset + valueLength; i++) { if (bson[i] !== 0) return false; } return true; } } } return true; } var MongoDBResponse = class _MongoDBResponse extends document_1.OnDemandDocument { get(name, as, required) { try { return super.get(name, as, required); } catch (cause) { throw new error_1.MongoUnexpectedServerResponseError(cause.message, { cause }); } } static is(value) { return value instanceof _MongoDBResponse; } static make(bson) { const elements = (0, bson_1.parseToElementsToArray)(bson, 0); const isError = isErrorResponse(bson, elements); return isError ? new _MongoDBResponse(bson, 0, false, elements) : new this(bson, 0, false, elements); } /** * Returns true iff: * - ok is 0 and the top-level code === 50 * - ok is 1 and the writeErrors array contains a code === 50 * - ok is 1 and the writeConcern object contains a code === 50 */ get isMaxTimeExpiredError() { const isTopLevel = this.ok === 0 && this.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired; if (isTopLevel) return true; if (this.ok === 0) return false; const isWriteConcern = this.get("writeConcernError", bson_1.BSONType.object)?.getNumber("code") === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired; if (isWriteConcern) return true; const writeErrors = this.get("writeErrors", bson_1.BSONType.array); if (writeErrors?.size()) { for (let i = 0; i < writeErrors.size(); i++) { const isWriteError = writeErrors.get(i, bson_1.BSONType.object)?.getNumber("code") === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired; if (isWriteError) return true; } } return false; } /** * Drivers can safely assume that the `recoveryToken` field is always a BSON document but drivers MUST NOT modify the * contents of the document. */ get recoveryToken() { return this.get("recoveryToken", bson_1.BSONType.object)?.toObject({ promoteValues: false, promoteLongs: false, promoteBuffers: false, validation: { utf8: true } }) ?? null; } /** * The server creates a cursor in response to a snapshot find/aggregate command and reports atClusterTime within the cursor field in the response. * For the distinct command the server adds a top-level atClusterTime field to the response. * The atClusterTime field represents the timestamp of the read and is guaranteed to be majority committed. */ get atClusterTime() { return this.get("cursor", bson_1.BSONType.object)?.get("atClusterTime", bson_1.BSONType.timestamp) ?? this.get("atClusterTime", bson_1.BSONType.timestamp); } get operationTime() { return this.get("operationTime", bson_1.BSONType.timestamp); } /** Normalizes whatever BSON value is "ok" to a JS number 1 or 0. */ get ok() { return this.getNumber("ok") ? 1 : 0; } get $err() { return this.get("$err", bson_1.BSONType.string); } get errmsg() { return this.get("errmsg", bson_1.BSONType.string); } get code() { return this.getNumber("code"); } get $clusterTime() { if (!("clusterTime" in this)) { const clusterTimeDoc = this.get("$clusterTime", bson_1.BSONType.object); if (clusterTimeDoc == null) { this.clusterTime = null; return null; } const clusterTime = clusterTimeDoc.get("clusterTime", bson_1.BSONType.timestamp, true); const signature = clusterTimeDoc.get("signature", bson_1.BSONType.object)?.toObject(); this.clusterTime = { clusterTime, signature }; } return this.clusterTime ?? null; } toObject(options) { const exactBSONOptions = { ...(0, bson_1.pluckBSONSerializeOptions)(options ?? {}), validation: (0, bson_1.parseUtf8ValidationOption)(options) }; return super.toObject(exactBSONOptions); } }; exports2.MongoDBResponse = MongoDBResponse; MongoDBResponse.empty = new MongoDBResponse(new Uint8Array([13, 0, 0, 0, 16, 111, 107, 0, 1, 0, 0, 0, 0])); var CursorResponse = class _CursorResponse extends MongoDBResponse { constructor() { super(...arguments); this._batch = null; this.iterated = 0; this._encryptedBatch = null; } /** * This supports a feature of the FindCursor. * It is an optimization to avoid an extra getMore when the limit has been reached */ static get emptyGetMore() { return new _CursorResponse((0, bson_1.serialize)({ ok: 1, cursor: { id: 0n, nextBatch: [] } })); } static is(value) { return value instanceof _CursorResponse || value === _CursorResponse.emptyGetMore; } get cursor() { return this.get("cursor", bson_1.BSONType.object, true); } get id() { try { return bson_1.Long.fromBigInt(this.cursor.get("id", bson_1.BSONType.long, true)); } catch (cause) { throw new error_1.MongoUnexpectedServerResponseError(cause.message, { cause }); } } get ns() { const namespace = this.cursor.get("ns", bson_1.BSONType.string); if (namespace != null) return (0, utils_1.ns)(namespace); return null; } get length() { return Math.max(this.batchSize - this.iterated, 0); } get encryptedBatch() { if (this.encryptedResponse == null) return null; if (this._encryptedBatch != null) return this._encryptedBatch; const cursor = this.encryptedResponse?.get("cursor", bson_1.BSONType.object); if (cursor?.has("firstBatch")) this._encryptedBatch = cursor.get("firstBatch", bson_1.BSONType.array, true); else if (cursor?.has("nextBatch")) this._encryptedBatch = cursor.get("nextBatch", bson_1.BSONType.array, true); else throw new error_1.MongoUnexpectedServerResponseError("Cursor document did not contain a batch"); return this._encryptedBatch; } get batch() { if (this._batch != null) return this._batch; const cursor = this.cursor; if (cursor.has("firstBatch")) this._batch = cursor.get("firstBatch", bson_1.BSONType.array, true); else if (cursor.has("nextBatch")) this._batch = cursor.get("nextBatch", bson_1.BSONType.array, true); else throw new error_1.MongoUnexpectedServerResponseError("Cursor document did not contain a batch"); return this._batch; } get batchSize() { return this.batch?.size(); } get postBatchResumeToken() { return this.cursor.get("postBatchResumeToken", bson_1.BSONType.object)?.toObject({ promoteValues: false, promoteLongs: false, promoteBuffers: false, validation: { utf8: true } }) ?? null; } shift(options) { if (this.iterated >= this.batchSize) { return null; } const result = this.batch.get(this.iterated, bson_1.BSONType.object, true) ?? null; const encryptedResult = this.encryptedBatch?.get(this.iterated, bson_1.BSONType.object, true) ?? null; this.iterated += 1; if (options?.raw) { return result.toBytes(); } else { const object = result.toObject(options); if (encryptedResult) { (0, utils_1.decorateDecryptionResult)(object, encryptedResult.toObject(options), true); } return object; } } clear() { this.iterated = this.batchSize; } }; exports2.CursorResponse = CursorResponse; var ExplainedCursorResponse = class extends CursorResponse { constructor() { super(...arguments); this.isExplain = true; this._length = 1; } get id() { return bson_1.Long.fromBigInt(0n); } get batchSize() { return 0; } get ns() { return null; } get length() { return this._length; } shift(options) { if (this._length === 0) return null; this._length -= 1; return this.toObject(options); } }; exports2.ExplainedCursorResponse = ExplainedCursorResponse; var ClientBulkWriteCursorResponse = class extends CursorResponse { get insertedCount() { return this.get("nInserted", bson_1.BSONType.int, true); } get upsertedCount() { return this.get("nUpserted", bson_1.BSONType.int, true); } get matchedCount() { return this.get("nMatched", bson_1.BSONType.int, true); } get modifiedCount() { return this.get("nModified", bson_1.BSONType.int, true); } get deletedCount() { return this.get("nDeleted", bson_1.BSONType.int, true); } get writeConcernError() { return this.get("writeConcernError", bson_1.BSONType.object, false); } }; exports2.ClientBulkWriteCursorResponse = ClientBulkWriteCursorResponse; } }); // netlify/functions/node_modules/mongodb/lib/write_concern.js var require_write_concern = __commonJS({ "netlify/functions/node_modules/mongodb/lib/write_concern.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.WriteConcern = exports2.WRITE_CONCERN_KEYS = void 0; exports2.throwIfWriteConcernError = throwIfWriteConcernError; var responses_1 = require_responses(); var error_1 = require_error(); exports2.WRITE_CONCERN_KEYS = ["w", "wtimeout", "j", "journal", "fsync"]; var WriteConcern = class _WriteConcern { /** * Constructs a WriteConcern from the write concern properties. * @param w - request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags. * @param wtimeoutMS - specify a time limit to prevent write operations from blocking indefinitely * @param journal - request acknowledgment that the write operation has been written to the on-disk journal * @param fsync - equivalent to the j option. Is deprecated and will be removed in the next major version. */ constructor(w, wtimeoutMS, journal, fsync) { if (w != null) { if (!Number.isNaN(Number(w))) { this.w = Number(w); } else { this.w = w; } } if (wtimeoutMS != null) { this.wtimeoutMS = this.wtimeout = wtimeoutMS; } if (journal != null) { this.journal = this.j = journal; } if (fsync != null) { this.journal = this.j = fsync ? true : false; } } /** * Apply a write concern to a command document. Will modify and return the command. */ static apply(command, writeConcern) { const wc = {}; if (writeConcern.w != null) wc.w = writeConcern.w; if (writeConcern.wtimeoutMS != null) wc.wtimeout = writeConcern.wtimeoutMS; if (writeConcern.journal != null) wc.j = writeConcern.j; command.writeConcern = wc; return command; } /** Construct a WriteConcern given an options object. */ static fromOptions(options, inherit) { if (options == null) return void 0; inherit = inherit ?? {}; let opts; if (typeof options === "string" || typeof options === "number") { opts = { w: options }; } else if (options instanceof _WriteConcern) { opts = options; } else { opts = options.writeConcern; } const parentOpts = inherit instanceof _WriteConcern ? inherit : inherit.writeConcern; const mergedOpts = { ...parentOpts, ...opts }; const { w = void 0, wtimeout = void 0, j = void 0, fsync = void 0, journal = void 0, wtimeoutMS = void 0 } = mergedOpts; if (w != null || wtimeout != null || wtimeoutMS != null || j != null || journal != null || fsync != null) { return new _WriteConcern(w, wtimeout ?? wtimeoutMS, j ?? journal, fsync); } return void 0; } }; exports2.WriteConcern = WriteConcern; function throwIfWriteConcernError(response) { if (typeof response === "object" && response != null) { const writeConcernError = responses_1.MongoDBResponse.is(response) && response.has("writeConcernError") ? response.toObject() : !responses_1.MongoDBResponse.is(response) && "writeConcernError" in response ? response : null; if (writeConcernError != null) { throw new error_1.MongoWriteConcernError(writeConcernError); } } } } }); // netlify/functions/node_modules/mongodb/lib/utils.js var require_utils = __commonJS({ "netlify/functions/node_modules/mongodb/lib/utils.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.kDispose = exports2.randomBytes = exports2.COSMOS_DB_MSG = exports2.DOCUMENT_DB_MSG = exports2.COSMOS_DB_CHECK = exports2.DOCUMENT_DB_CHECK = exports2.MONGODB_WARNING_CODE = exports2.DEFAULT_PK_FACTORY = exports2.HostAddress = exports2.BufferPool = exports2.List = exports2.MongoDBCollectionNamespace = exports2.MongoDBNamespace = exports2.ByteUtils = void 0; exports2.isUint8Array = isUint8Array; exports2.hostMatchesWildcards = hostMatchesWildcards; exports2.normalizeHintField = normalizeHintField; exports2.isObject = isObject; exports2.mergeOptions = mergeOptions; exports2.filterOptions = filterOptions; exports2.applyRetryableWrites = applyRetryableWrites; exports2.isPromiseLike = isPromiseLike; exports2.decorateWithCollation = decorateWithCollation; exports2.decorateWithReadConcern = decorateWithReadConcern; exports2.getTopology = getTopology; exports2.ns = ns; exports2.makeCounter = makeCounter; exports2.uuidV4 = uuidV4; exports2.maxWireVersion = maxWireVersion; exports2.arrayStrictEqual = arrayStrictEqual; exports2.errorStrictEqual = errorStrictEqual; exports2.makeStateMachine = makeStateMachine; exports2.now = now; exports2.calculateDurationInMs = calculateDurationInMs; exports2.hasAtomicOperators = hasAtomicOperators; exports2.resolveTimeoutOptions = resolveTimeoutOptions; exports2.resolveOptions = resolveOptions; exports2.isSuperset = isSuperset; exports2.isHello = isHello; exports2.setDifference = setDifference; exports2.isRecord = isRecord; exports2.emitWarning = emitWarning; exports2.emitWarningOnce = emitWarningOnce; exports2.enumToString = enumToString; exports2.supportsRetryableWrites = supportsRetryableWrites; exports2.shuffle = shuffle; exports2.commandSupportsReadConcern = commandSupportsReadConcern; exports2.compareObjectId = compareObjectId; exports2.parseInteger = parseInteger; exports2.parseUnsignedInteger = parseUnsignedInteger; exports2.checkParentDomainMatch = checkParentDomainMatch; exports2.get = get; exports2.request = request; exports2.isHostMatch = isHostMatch; exports2.promiseWithResolvers = promiseWithResolvers; exports2.squashError = squashError; exports2.once = once; exports2.maybeAddIdToDocuments = maybeAddIdToDocuments; exports2.fileIsAccessible = fileIsAccessible; exports2.csotMin = csotMin; exports2.noop = noop; exports2.decorateDecryptionResult = decorateDecryptionResult; exports2.addAbortListener = addAbortListener; exports2.abortable = abortable; var crypto = require("crypto"); var fs_1 = require("fs"); var http = require("http"); var timers_1 = require("timers"); var url = require("url"); var url_1 = require("url"); var util_1 = require("util"); var bson_1 = require_bson2(); var constants_1 = require_constants2(); var constants_2 = require_constants(); var error_1 = require_error(); var read_concern_1 = require_read_concern(); var read_preference_1 = require_read_preference(); var common_1 = require_common(); var write_concern_1 = require_write_concern(); exports2.ByteUtils = { toLocalBufferType(buffer) { return Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength); }, equals(seqA, seqB) { return exports2.ByteUtils.toLocalBufferType(seqA).equals(seqB); }, compare(seqA, seqB) { return exports2.ByteUtils.toLocalBufferType(seqA).compare(seqB); }, toBase64(uint8array) { return exports2.ByteUtils.toLocalBufferType(uint8array).toString("base64"); } }; function isUint8Array(value) { return value != null && typeof value === "object" && Symbol.toStringTag in value && value[Symbol.toStringTag] === "Uint8Array"; } function hostMatchesWildcards(host, wildcards) { for (const wildcard of wildcards) { if (host === wildcard || wildcard.startsWith("*.") && host?.endsWith(wildcard.substring(2, wildcard.length)) || wildcard.startsWith("*/") && host?.endsWith(wildcard.substring(2, wildcard.length))) { return true; } } return false; } function normalizeHintField(hint) { let finalHint = void 0; if (typeof hint === "string") { finalHint = hint; } else if (Array.isArray(hint)) { finalHint = {}; hint.forEach((param) => { finalHint[param] = 1; }); } else if (hint != null && typeof hint === "object") { finalHint = {}; for (const name in hint) { finalHint[name] = hint[name]; } } return finalHint; } var TO_STRING = (object) => Object.prototype.toString.call(object); function isObject(arg) { return "[object Object]" === TO_STRING(arg); } function mergeOptions(target, source) { return { ...target, ...source }; } function filterOptions(options, names) { const filterOptions2 = {}; for (const name in options) { if (names.includes(name)) { filterOptions2[name] = options[name]; } } return filterOptions2; } function applyRetryableWrites(target, db) { if (db && db.s.options?.retryWrites) { target.retryWrites = true; } return target; } function isPromiseLike(value) { return value != null && typeof value === "object" && "then" in value && typeof value.then === "function"; } function decorateWithCollation(command, target, options) { const capabilities = getTopology(target).capabilities; if (options.collation && typeof options.collation === "object") { if (capabilities && capabilities.commandsTakeCollation) { command.collation = options.collation; } else { throw new error_1.MongoCompatibilityError(`Current topology does not support collation`); } } } function decorateWithReadConcern(command, coll, options) { if (options && options.session && options.session.inTransaction()) { return; } const readConcern = Object.assign({}, command.readConcern || {}); if (coll.s.readConcern) { Object.assign(readConcern, coll.s.readConcern); } if (Object.keys(readConcern).length > 0) { Object.assign(command, { readConcern }); } } function getTopology(provider) { if ("topology" in provider && provider.topology) { return provider.topology; } else if ("client" in provider && provider.client.topology) { return provider.client.topology; } throw new error_1.MongoNotConnectedError("MongoClient must be connected to perform this operation"); } function ns(ns2) { return MongoDBNamespace.fromString(ns2); } var MongoDBNamespace = class _MongoDBNamespace { /** * Create a namespace object * * @param db - database name * @param collection - collection name */ constructor(db, collection) { this.db = db; this.collection = collection === "" ? void 0 : collection; } toString() { return this.collection ? `${this.db}.${this.collection}` : this.db; } withCollection(collection) { return new MongoDBCollectionNamespace(this.db, collection); } static fromString(namespace) { if (typeof namespace !== "string" || namespace === "") { throw new error_1.MongoRuntimeError(`Cannot parse namespace from "${namespace}"`); } const [db, ...collectionParts] = namespace.split("."); const collection = collectionParts.join("."); return new _MongoDBNamespace(db, collection === "" ? void 0 : collection); } }; exports2.MongoDBNamespace = MongoDBNamespace; var MongoDBCollectionNamespace = class extends MongoDBNamespace { constructor(db, collection) { super(db, collection); this.collection = collection; } static fromString(namespace) { return super.fromString(namespace); } }; exports2.MongoDBCollectionNamespace = MongoDBCollectionNamespace; function* makeCounter(seed = 0) { let count = seed; while (true) { const newCount = count; count += 1; yield newCount; } } function uuidV4() { const result = crypto.randomBytes(16); result[6] = result[6] & 15 | 64; result[8] = result[8] & 63 | 128; return result; } function maxWireVersion(topologyOrServer) { if (topologyOrServer) { if (topologyOrServer.loadBalanced || topologyOrServer.serverApi?.version) { return constants_1.MAX_SUPPORTED_WIRE_VERSION; } if (topologyOrServer.hello) { return topologyOrServer.hello.maxWireVersion; } if ("lastHello" in topologyOrServer && typeof topologyOrServer.lastHello === "function") { const lastHello = topologyOrServer.lastHello(); if (lastHello) { return lastHello.maxWireVersion; } } if (topologyOrServer.description && "maxWireVersion" in topologyOrServer.description && topologyOrServer.description.maxWireVersion != null) { return topologyOrServer.description.maxWireVersion; } } return 0; } function arrayStrictEqual(arr, arr2) { if (!Array.isArray(arr) || !Array.isArray(arr2)) { return false; } return arr.length === arr2.length && arr.every((elt, idx) => elt === arr2[idx]); } function errorStrictEqual(lhs, rhs) { if (lhs === rhs) { return true; } if (!lhs || !rhs) { return lhs === rhs; } if (lhs == null && rhs != null || lhs != null && rhs == null) { return false; } if (lhs.constructor.name !== rhs.constructor.name) { return false; } if (lhs.message !== rhs.message) { return false; } return true; } function makeStateMachine(stateTable) { return function stateTransition(target, newState) { const legalStates = stateTable[target.s.state]; if (legalStates && legalStates.indexOf(newState) < 0) { throw new error_1.MongoRuntimeError(`illegal state transition from [${target.s.state}] => [${newState}], allowed: [${legalStates}]`); } target.emit("stateChanged", target.s.state, newState); target.s.state = newState; }; } function now() { const hrtime = process.hrtime(); return Math.floor(hrtime[0] * 1e3 + hrtime[1] / 1e6); } function calculateDurationInMs(started) { if (typeof started !== "number") { return -1; } const elapsed = now() - started; return elapsed < 0 ? 0 : elapsed; } function hasAtomicOperators(doc, options) { if (Array.isArray(doc)) { for (const document2 of doc) { if (hasAtomicOperators(document2)) { return true; } } return false; } const keys = Object.keys(doc); if (options?.ignoreUndefined) { let allUndefined = true; for (const key of keys) { if (doc[key] !== void 0) { allUndefined = false; break; } } if (allUndefined) { throw new error_1.MongoInvalidArgumentError("Update operations require that all atomic operators have defined values, but none were provided."); } } return keys.length > 0 && keys[0][0] === "$"; } function resolveTimeoutOptions(client, options) { const { socketTimeoutMS, serverSelectionTimeoutMS, waitQueueTimeoutMS, timeoutMS } = client.s.options; return { socketTimeoutMS, serverSelectionTimeoutMS, waitQueueTimeoutMS, timeoutMS, ...options }; } function resolveOptions(parent, options) { const result = Object.assign({}, options, (0, bson_1.resolveBSONOptions)(options, parent)); const timeoutMS = options?.timeoutMS ?? parent?.timeoutMS; const session = options?.session; if (!session?.inTransaction()) { const readConcern = read_concern_1.ReadConcern.fromOptions(options) ?? parent?.readConcern; if (readConcern) { result.readConcern = readConcern; } let writeConcern = write_concern_1.WriteConcern.fromOptions(options) ?? parent?.writeConcern; if (writeConcern) { if (timeoutMS != null) { writeConcern = write_concern_1.WriteConcern.fromOptions({ writeConcern: { ...writeConcern, wtimeout: void 0, wtimeoutMS: void 0 } }); } result.writeConcern = writeConcern; } } result.timeoutMS = timeoutMS; const readPreference = read_preference_1.ReadPreference.fromOptions(options) ?? parent?.readPreference; if (readPreference) { result.readPreference = readPreference; } const isConvenientTransaction = session?.explicit && session?.timeoutContext != null; if (isConvenientTransaction && options?.timeoutMS != null) { throw new error_1.MongoInvalidArgumentError("An operation cannot be given a timeoutMS setting when inside a withTransaction call that has a timeoutMS setting"); } return result; } function isSuperset(set, subset) { set = Array.isArray(set) ? new Set(set) : set; subset = Array.isArray(subset) ? new Set(subset) : subset; for (const elem of subset) { if (!set.has(elem)) { return false; } } return true; } function isHello(doc) { return doc[constants_2.LEGACY_HELLO_COMMAND] || doc.hello ? true : false; } function setDifference(setA, setB) { const difference = new Set(setA); for (const elem of setB) { difference.delete(elem); } return difference; } var HAS_OWN = (object, prop) => Object.prototype.hasOwnProperty.call(object, prop); function isRecord(value, requiredKeys = void 0) { if (!isObject(value)) { return false; } const ctor = value.constructor; if (ctor && ctor.prototype) { if (!isObject(ctor.prototype)) { return false; } if (!HAS_OWN(ctor.prototype, "isPrototypeOf")) { return false; } } if (requiredKeys) { const keys = Object.keys(value); return isSuperset(keys, requiredKeys); } return true; } var List = class { get length() { return this.count; } get [Symbol.toStringTag]() { return "List"; } constructor() { this.count = 0; this.head = { next: null, prev: null, value: null }; this.head.next = this.head; this.head.prev = this.head; } toArray() { return Array.from(this); } toString() { return `head <=> ${this.toArray().join(" <=> ")} <=> head`; } *[Symbol.iterator]() { for (const node of this.nodes()) { yield node.value; } } *nodes() { let ptr = this.head.next; while (ptr !== this.head) { const { next } = ptr; yield ptr; ptr = next; } } /** Insert at end of list */ push(value) { this.count += 1; const newNode = { next: this.head, prev: this.head.prev, value }; this.head.prev.next = newNode; this.head.prev = newNode; } /** Inserts every item inside an iterable instead of the iterable itself */ pushMany(iterable) { for (const value of iterable) { this.push(value); } } /** Insert at front of list */ unshift(value) { this.count += 1; const newNode = { next: this.head.next, prev: this.head, value }; this.head.next.prev = newNode; this.head.next = newNode; } remove(node) { if (node === this.head || this.length === 0) { return null; } this.count -= 1; const prevNode = node.prev; const nextNode = node.next; prevNode.next = nextNode; nextNode.prev = prevNode; return node.value; } /** Removes the first node at the front of the list */ shift() { return this.remove(this.head.next); } /** Removes the last node at the end of the list */ pop() { return this.remove(this.head.prev); } /** Iterates through the list and removes nodes where filter returns true */ prune(filter) { for (const node of this.nodes()) { if (filter(node.value)) { this.remove(node); } } } clear() { this.count = 0; this.head.next = this.head; this.head.prev = this.head; } /** Returns the first item in the list, does not remove */ first() { return this.head.next.value; } /** Returns the last item in the list, does not remove */ last() { return this.head.prev.value; } }; exports2.List = List; var BufferPool = class { constructor() { this.buffers = new List(); this.totalByteLength = 0; } get length() { return this.totalByteLength; } /** Adds a buffer to the internal buffer pool list */ append(buffer) { this.buffers.push(buffer); this.totalByteLength += buffer.length; } /** * If BufferPool contains 4 bytes or more construct an int32 from the leading bytes, * otherwise return null. Size can be negative, caller should error check. */ getInt32() { if (this.totalByteLength < 4) { return null; } const firstBuffer = this.buffers.first(); if (firstBuffer != null && firstBuffer.byteLength >= 4) { return firstBuffer.readInt32LE(0); } const top4Bytes = this.read(4); const value = top4Bytes.readInt32LE(0); this.totalByteLength += 4; this.buffers.unshift(top4Bytes); return value; } /** Reads the requested number of bytes, optionally consuming them */ read(size) { if (typeof size !== "number" || size < 0) { throw new error_1.MongoInvalidArgumentError('Argument "size" must be a non-negative number'); } if (size > this.totalByteLength) { return Buffer.alloc(0); } const result = Buffer.allocUnsafe(size); for (let bytesRead = 0; bytesRead < size; ) { const buffer = this.buffers.shift(); if (buffer == null) { break; } const bytesRemaining = size - bytesRead; const bytesReadable = Math.min(bytesRemaining, buffer.byteLength); const bytes = buffer.subarray(0, bytesReadable); result.set(bytes, bytesRead); bytesRead += bytesReadable; this.totalByteLength -= bytesReadable; if (bytesReadable < buffer.byteLength) { this.buffers.unshift(buffer.subarray(bytesReadable)); } } return result; } }; exports2.BufferPool = BufferPool; var HostAddress = class _HostAddress { constructor(hostString) { this.host = void 0; this.port = void 0; this.socketPath = void 0; this.isIPv6 = false; const escapedHost = hostString.split(" ").join("%20"); if (escapedHost.endsWith(".sock")) { this.socketPath = decodeURIComponent(escapedHost); return; } const urlString = `iLoveJS://${escapedHost}`; let url2; try { url2 = new url_1.URL(urlString); } catch (urlError) { const runtimeError = new error_1.MongoRuntimeError(`Unable to parse ${escapedHost} with URL`); runtimeError.cause = urlError; throw runtimeError; } const hostname = url2.hostname; const port = url2.port; let normalized = decodeURIComponent(hostname).toLowerCase(); if (normalized.startsWith("[") && normalized.endsWith("]")) { this.isIPv6 = true; normalized = normalized.substring(1, hostname.length - 1); } this.host = normalized.toLowerCase(); if (typeof port === "number") { this.port = port; } else if (typeof port === "string" && port !== "") { this.port = Number.parseInt(port, 10); } else { this.port = 27017; } if (this.port === 0) { throw new error_1.MongoParseError("Invalid port (zero) with hostname"); } Object.freeze(this); } [Symbol.for("nodejs.util.inspect.custom")]() { return this.inspect(); } inspect() { return `new HostAddress('${this.toString()}')`; } toString() { if (typeof this.host === "string") { if (this.isIPv6) { return `[${this.host}]:${this.port}`; } return `${this.host}:${this.port}`; } return `${this.socketPath}`; } static fromString(s) { return new _HostAddress(s); } static fromHostPort(host, port) { if (host.includes(":")) { host = `[${host}]`; } return _HostAddress.fromString(`${host}:${port}`); } static fromSrvRecord({ name, port }) { return _HostAddress.fromHostPort(name, port); } toHostPort() { if (this.socketPath) { return { host: this.socketPath, port: 0 }; } const host = this.host ?? ""; const port = this.port ?? 0; return { host, port }; } }; exports2.HostAddress = HostAddress; exports2.DEFAULT_PK_FACTORY = { // We prefer not to rely on ObjectId having a createPk method createPk() { return new bson_1.ObjectId(); } }; exports2.MONGODB_WARNING_CODE = "MONGODB DRIVER"; function emitWarning(message) { return process.emitWarning(message, { code: exports2.MONGODB_WARNING_CODE }); } var emittedWarnings = /* @__PURE__ */ new Set(); function emitWarningOnce(message) { if (!emittedWarnings.has(message)) { emittedWarnings.add(message); return emitWarning(message); } } function enumToString(en) { return Object.values(en).join(", "); } function supportsRetryableWrites(server) { if (!server) { return false; } if (server.loadBalanced) { return true; } if (server.description.logicalSessionTimeoutMinutes != null) { if (server.description.type !== common_1.ServerType.Standalone) { return true; } } return false; } function shuffle(sequence, limit = 0) { const items = Array.from(sequence); if (limit > items.length) { throw new error_1.MongoRuntimeError("Limit must be less than the number of items"); } let remainingItemsToShuffle = items.length; const lowerBound = limit % items.length === 0 ? 1 : items.length - limit; while (remainingItemsToShuffle > lowerBound) { const randomIndex = Math.floor(Math.random() * remainingItemsToShuffle); remainingItemsToShuffle -= 1; const swapHold = items[remainingItemsToShuffle]; items[remainingItemsToShuffle] = items[randomIndex]; items[randomIndex] = swapHold; } return limit % items.length === 0 ? items : items.slice(lowerBound); } function commandSupportsReadConcern(command) { if (command.aggregate || command.count || command.distinct || command.find || command.geoNear) { return true; } return false; } function compareObjectId(oid1, oid2) { if (oid1 == null && oid2 == null) { return 0; } if (oid1 == null) { return -1; } if (oid2 == null) { return 1; } return exports2.ByteUtils.compare(oid1.id, oid2.id); } function parseInteger(value) { if (typeof value === "number") return Math.trunc(value); const parsedValue = Number.parseInt(String(value), 10); return Number.isNaN(parsedValue) ? null : parsedValue; } function parseUnsignedInteger(value) { const parsedInt = parseInteger(value); return parsedInt != null && parsedInt >= 0 ? parsedInt : null; } function checkParentDomainMatch(address, srvHost) { const normalizedAddress = address.endsWith(".") ? address.slice(0, address.length - 1) : address; const normalizedSrvHost = srvHost.endsWith(".") ? srvHost.slice(0, srvHost.length - 1) : srvHost; const allCharacterBeforeFirstDot = /^.*?\./; const srvIsLessThanThreeParts = normalizedSrvHost.split(".").length < 3; const addressDomain = `.${normalizedAddress.replace(allCharacterBeforeFirstDot, "")}`; let srvHostDomain = srvIsLessThanThreeParts ? normalizedSrvHost : `.${normalizedSrvHost.replace(allCharacterBeforeFirstDot, "")}`; if (!srvHostDomain.startsWith(".")) { srvHostDomain = "." + srvHostDomain; } if (srvIsLessThanThreeParts && normalizedAddress.split(".").length <= normalizedSrvHost.split(".").length) { throw new error_1.MongoAPIError("Server record does not have at least one more domain level than parent URI"); } if (!addressDomain.endsWith(srvHostDomain)) { throw new error_1.MongoAPIError("Server record does not share hostname with parent URI"); } } function get(url2, options = {}) { return new Promise((resolve, reject) => { let timeoutId; const request2 = http.get(url2, options, (response) => { response.setEncoding("utf8"); let body = ""; response.on("data", (chunk) => body += chunk); response.on("end", () => { (0, timers_1.clearTimeout)(timeoutId); resolve({ status: response.statusCode, body }); }); }).on("error", (error) => { (0, timers_1.clearTimeout)(timeoutId); reject(error); }).end(); timeoutId = (0, timers_1.setTimeout)(() => { request2.destroy(new error_1.MongoNetworkTimeoutError(`request timed out after 10 seconds`)); }, 1e4); }); } async function request(uri, options = {}) { return await new Promise((resolve, reject) => { const requestOptions = { method: "GET", timeout: 1e4, json: true, ...url.parse(uri), ...options }; const req = http.request(requestOptions, (res) => { res.setEncoding("utf8"); let data = ""; res.on("data", (d) => { data += d; }); res.once("end", () => { if (options.json === false) { resolve(data); return; } try { const parsed = JSON.parse(data); resolve(parsed); } catch { reject(new error_1.MongoRuntimeError(`Invalid JSON response: "${data}"`)); } }); }); req.once("timeout", () => req.destroy(new error_1.MongoNetworkTimeoutError(`Network request to ${uri} timed out after ${options.timeout} ms`))); req.once("error", (error) => reject(error)); req.end(); }); } exports2.DOCUMENT_DB_CHECK = /(\.docdb\.amazonaws\.com$)|(\.docdb-elastic\.amazonaws\.com$)/; exports2.COSMOS_DB_CHECK = /\.cosmos\.azure\.com$/; exports2.DOCUMENT_DB_MSG = "You appear to be connected to a DocumentDB cluster. For more information regarding feature compatibility and support please visit https://www.mongodb.com/supportability/documentdb"; exports2.COSMOS_DB_MSG = "You appear to be connected to a CosmosDB cluster. For more information regarding feature compatibility and support please visit https://www.mongodb.com/supportability/cosmosdb"; function isHostMatch(match, host) { return host && match.test(host.toLowerCase()) ? true : false; } function promiseWithResolvers() { let resolve; let reject; const promise = new Promise(function withResolversExecutor(promiseResolve, promiseReject) { resolve = promiseResolve; reject = promiseReject; }); return { promise, resolve, reject }; } function squashError(_error) { return; } exports2.randomBytes = (0, util_1.promisify)(crypto.randomBytes); async function once(ee, name, options) { options?.signal?.throwIfAborted(); const { promise, resolve, reject } = promiseWithResolvers(); const onEvent = (data) => resolve(data); const onError = (error) => reject(error); const abortListener = addAbortListener(options?.signal, function() { reject(this.reason); }); ee.once(name, onEvent).once("error", onError); try { return await promise; } finally { ee.off(name, onEvent); ee.off("error", onError); abortListener?.[exports2.kDispose](); } } function maybeAddIdToDocuments(coll, docOrDocs, options) { const forceServerObjectId = typeof options.forceServerObjectId === "boolean" ? options.forceServerObjectId : coll.s.db.options?.forceServerObjectId; if (forceServerObjectId === true) { return docOrDocs; } const transform = (doc) => { if (doc._id == null) { doc._id = coll.s.pkFactory.createPk(); } return doc; }; return Array.isArray(docOrDocs) ? docOrDocs.map(transform) : transform(docOrDocs); } async function fileIsAccessible(fileName, mode) { try { await fs_1.promises.access(fileName, mode); return true; } catch { return false; } } function csotMin(duration1, duration2) { if (duration1 === 0) return duration2; if (duration2 === 0) return duration1; return Math.min(duration1, duration2); } function noop() { return; } function decorateDecryptionResult(decrypted, original, isTopLevelDecorateCall = true) { if (isTopLevelDecorateCall) { if (Buffer.isBuffer(original)) { original = (0, bson_1.deserialize)(original); } if (Buffer.isBuffer(decrypted)) { throw new error_1.MongoRuntimeError("Expected result of decryption to be deserialized BSON object"); } } if (!decrypted || typeof decrypted !== "object") return; for (const k of Object.keys(decrypted)) { const originalValue = original[k]; if (originalValue && originalValue._bsontype === "Binary" && originalValue.sub_type === 6) { if (!decrypted[constants_2.kDecoratedKeys]) { Object.defineProperty(decrypted, constants_2.kDecoratedKeys, { value: [], configurable: true, enumerable: false, writable: false }); } decrypted[constants_2.kDecoratedKeys].push(k); continue; } decorateDecryptionResult(decrypted[k], originalValue, false); } } exports2.kDispose = Symbol.dispose ?? Symbol("dispose"); function addAbortListener(signal, listener) { if (signal == null) return; signal.addEventListener("abort", listener, { once: true }); return { [exports2.kDispose]: () => signal.removeEventListener("abort", listener) }; } async function abortable(promise, { signal }) { if (signal == null) { return await promise; } const { promise: aborted, reject } = promiseWithResolvers(); const abortListener = signal.aborted ? reject(signal.reason) : addAbortListener(signal, function() { reject(this.reason); }); try { return await Promise.race([promise, aborted]); } finally { abortListener?.[exports2.kDispose](); } } } }); // netlify/functions/node_modules/mongodb/lib/mongo_logger.js var require_mongo_logger = __commonJS({ "netlify/functions/node_modules/mongodb/lib/mongo_logger.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.MongoLogger = exports2.MongoLoggableComponent = exports2.SEVERITY_LEVEL_MAP = exports2.DEFAULT_MAX_DOCUMENT_LENGTH = exports2.SeverityLevel = void 0; exports2.parseSeverityFromString = parseSeverityFromString; exports2.createStdioLogger = createStdioLogger; exports2.stringifyWithMaxLen = stringifyWithMaxLen; exports2.defaultLogTransform = defaultLogTransform; var util_1 = require("util"); var bson_1 = require_bson2(); var constants_1 = require_constants(); var utils_1 = require_utils(); exports2.SeverityLevel = Object.freeze({ EMERGENCY: "emergency", ALERT: "alert", CRITICAL: "critical", ERROR: "error", WARNING: "warn", NOTICE: "notice", INFORMATIONAL: "info", DEBUG: "debug", TRACE: "trace", OFF: "off" }); exports2.DEFAULT_MAX_DOCUMENT_LENGTH = 1e3; var SeverityLevelMap = class extends Map { constructor(entries) { const newEntries = []; for (const [level, value] of entries) { newEntries.push([value, level]); } newEntries.push(...entries); super(newEntries); } getNumericSeverityLevel(severity) { return this.get(severity); } getSeverityLevelName(level) { return this.get(level); } }; exports2.SEVERITY_LEVEL_MAP = new SeverityLevelMap([ [exports2.SeverityLevel.OFF, -Infinity], [exports2.SeverityLevel.EMERGENCY, 0], [exports2.SeverityLevel.ALERT, 1], [exports2.SeverityLevel.CRITICAL, 2], [exports2.SeverityLevel.ERROR, 3], [exports2.SeverityLevel.WARNING, 4], [exports2.SeverityLevel.NOTICE, 5], [exports2.SeverityLevel.INFORMATIONAL, 6], [exports2.SeverityLevel.DEBUG, 7], [exports2.SeverityLevel.TRACE, 8] ]); exports2.MongoLoggableComponent = Object.freeze({ COMMAND: "command", TOPOLOGY: "topology", SERVER_SELECTION: "serverSelection", CONNECTION: "connection", CLIENT: "client" }); function parseSeverityFromString(s) { const validSeverities = Object.values(exports2.SeverityLevel); const lowerSeverity = s?.toLowerCase(); if (lowerSeverity != null && validSeverities.includes(lowerSeverity)) { return lowerSeverity; } return null; } function createStdioLogger(stream) { return { write: (0, util_1.promisify)((log, cb) => { const logLine = (0, util_1.inspect)(log, { compact: true, breakLength: Infinity }); stream.write(`${logLine} `, "utf-8", cb); return; }) }; } function resolveLogPath({ MONGODB_LOG_PATH }, { mongodbLogPath }) { if (typeof mongodbLogPath === "string" && /^stderr$/i.test(mongodbLogPath)) { return { mongodbLogPath: createStdioLogger(process.stderr), mongodbLogPathIsStdErr: true }; } if (typeof mongodbLogPath === "string" && /^stdout$/i.test(mongodbLogPath)) { return { mongodbLogPath: createStdioLogger(process.stdout), mongodbLogPathIsStdErr: false }; } if (typeof mongodbLogPath === "object" && typeof mongodbLogPath?.write === "function") { return { mongodbLogPath, mongodbLogPathIsStdErr: false }; } if (MONGODB_LOG_PATH && /^stderr$/i.test(MONGODB_LOG_PATH)) { return { mongodbLogPath: createStdioLogger(process.stderr), mongodbLogPathIsStdErr: true }; } if (MONGODB_LOG_PATH && /^stdout$/i.test(MONGODB_LOG_PATH)) { return { mongodbLogPath: createStdioLogger(process.stdout), mongodbLogPathIsStdErr: false }; } return { mongodbLogPath: createStdioLogger(process.stderr), mongodbLogPathIsStdErr: true }; } function resolveSeverityConfiguration(clientOption, environmentOption, defaultSeverity) { return parseSeverityFromString(clientOption) ?? parseSeverityFromString(environmentOption) ?? defaultSeverity; } function compareSeverity(s0, s1) { const s0Num = exports2.SEVERITY_LEVEL_MAP.getNumericSeverityLevel(s0); const s1Num = exports2.SEVERITY_LEVEL_MAP.getNumericSeverityLevel(s1); return s0Num < s1Num ? -1 : s0Num > s1Num ? 1 : 0; } function stringifyWithMaxLen(value, maxDocumentLength, options = {}) { let strToTruncate = ""; let currentLength = 0; const maxDocumentLengthEnsurer = function maxDocumentLengthEnsurer2(key, value2) { if (currentLength >= maxDocumentLength) { return void 0; } if (key === "") { currentLength += 1; return value2; } currentLength += key.length + 4; if (value2 == null) return value2; switch (typeof value2) { case "string": currentLength += value2.length + 2; break; case "number": case "bigint": currentLength += String(value2).length; break; case "boolean": currentLength += value2 ? 4 : 5; break; case "object": if ((0, utils_1.isUint8Array)(value2)) { currentLength += 22 + value2.byteLength + value2.byteLength * 0.33 + 18 | 0; } else if ("_bsontype" in value2) { const v = value2; switch (v._bsontype) { case "Int32": currentLength += String(v.value).length; break; case "Double": currentLength += (v.value | 0) === v.value ? String(v.value).length + 2 : String(v.value).length; break; case "Long": currentLength += v.toString().length; break; case "ObjectId": currentLength += 35; break; case "MaxKey": case "MinKey": currentLength += 13; break; case "Binary": currentLength += 22 + value2.position + value2.position * 0.33 + 18 | 0; break; case "Timestamp": currentLength += 19 + String(v.t).length + 5 + String(v.i).length + 2; break; case "Code": if (v.scope == null) { currentLength += v.code.length + 10 + 2; } else { currentLength += v.code.length + 10 + 11; } break; case "BSONRegExp": currentLength += 34 + v.pattern.length + 13 + v.options.length + 3; break; } } } return value2; }; if (typeof value === "string") { strToTruncate = value; } else if (typeof value === "function") { strToTruncate = value.name; } else { try { if (maxDocumentLength !== 0) { strToTruncate = bson_1.EJSON.stringify(value, maxDocumentLengthEnsurer, 0, options); } else { strToTruncate = bson_1.EJSON.stringify(value, options); } } catch (e) { strToTruncate = `Extended JSON serialization failed with: ${e.message}`; } } if (maxDocumentLength !== 0 && strToTruncate.length > maxDocumentLength && strToTruncate.charCodeAt(maxDocumentLength - 1) !== strToTruncate.codePointAt(maxDocumentLength - 1)) { maxDocumentLength--; if (maxDocumentLength === 0) { return ""; } } return maxDocumentLength !== 0 && strToTruncate.length > maxDocumentLength ? `${strToTruncate.slice(0, maxDocumentLength)}...` : strToTruncate; } function isLogConvertible(obj) { const objAsLogConvertible = obj; return objAsLogConvertible.toLog !== void 0 && typeof objAsLogConvertible.toLog === "function"; } function attachServerSelectionFields(log, serverSelectionEvent, maxDocumentLength = exports2.DEFAULT_MAX_DOCUMENT_LENGTH) { const { selector, operation, topologyDescription, message } = serverSelectionEvent; log.selector = stringifyWithMaxLen(selector, maxDocumentLength); log.operation = operation; log.topologyDescription = stringifyWithMaxLen(topologyDescription, maxDocumentLength); log.message = message; return log; } function attachCommandFields(log, commandEvent) { log.commandName = commandEvent.commandName; log.requestId = commandEvent.requestId; log.driverConnectionId = commandEvent.connectionId; const { host, port } = utils_1.HostAddress.fromString(commandEvent.address).toHostPort(); log.serverHost = host; log.serverPort = port; if (commandEvent?.serviceId) { log.serviceId = commandEvent.serviceId.toHexString(); } log.databaseName = commandEvent.databaseName; log.serverConnectionId = commandEvent.serverConnectionId; return log; } function attachConnectionFields(log, event) { const { host, port } = utils_1.HostAddress.fromString(event.address).toHostPort(); log.serverHost = host; log.serverPort = port; return log; } function attachSDAMFields(log, sdamEvent) { log.topologyId = sdamEvent.topologyId; return log; } function attachServerHeartbeatFields(log, serverHeartbeatEvent) { const { awaited, connectionId } = serverHeartbeatEvent; log.awaited = awaited; log.driverConnectionId = serverHeartbeatEvent.connectionId; const { host, port } = utils_1.HostAddress.fromString(connectionId).toHostPort(); log.serverHost = host; log.serverPort = port; return log; } function defaultLogTransform(logObject, maxDocumentLength = exports2.DEFAULT_MAX_DOCUMENT_LENGTH) { let log = /* @__PURE__ */ Object.create(null); switch (logObject.name) { case constants_1.SERVER_SELECTION_STARTED: log = attachServerSelectionFields(log, logObject, maxDocumentLength); return log; case constants_1.SERVER_SELECTION_FAILED: log = attachServerSelectionFields(log, logObject, maxDocumentLength); log.failure = logObject.failure?.message; return log; case constants_1.SERVER_SELECTION_SUCCEEDED: log = attachServerSelectionFields(log, logObject, maxDocumentLength); log.serverHost = logObject.serverHost; log.serverPort = logObject.serverPort; return log; case constants_1.WAITING_FOR_SUITABLE_SERVER: log = attachServerSelectionFields(log, logObject, maxDocumentLength); log.remainingTimeMS = logObject.remainingTimeMS; return log; case constants_1.COMMAND_STARTED: log = attachCommandFields(log, logObject); log.message = "Command started"; log.command = stringifyWithMaxLen(logObject.command, maxDocumentLength, { relaxed: true }); log.databaseName = logObject.databaseName; return log; case constants_1.COMMAND_SUCCEEDED: log = attachCommandFields(log, logObject); log.message = "Command succeeded"; log.durationMS = logObject.duration; log.reply = stringifyWithMaxLen(logObject.reply, maxDocumentLength, { relaxed: true }); return log; case constants_1.COMMAND_FAILED: log = attachCommandFields(log, logObject); log.message = "Command failed"; log.durationMS = logObject.duration; log.failure = logObject.failure?.message ?? "(redacted)"; return log; case constants_1.CONNECTION_POOL_CREATED: log = attachConnectionFields(log, logObject); log.message = "Connection pool created"; if (logObject.options) { const { maxIdleTimeMS, minPoolSize, maxPoolSize, maxConnecting, waitQueueTimeoutMS } = logObject.options; log = { ...log, maxIdleTimeMS, minPoolSize, maxPoolSize, maxConnecting, waitQueueTimeoutMS }; } return log; case constants_1.CONNECTION_POOL_READY: log = attachConnectionFields(log, logObject); log.message = "Connection pool ready"; return log; case constants_1.CONNECTION_POOL_CLEARED: log = attachConnectionFields(log, logObject); log.message = "Connection pool cleared"; if (logObject.serviceId?._bsontype === "ObjectId") { log.serviceId = logObject.serviceId?.toHexString(); } return log; case constants_1.CONNECTION_POOL_CLOSED: log = attachConnectionFields(log, logObject); log.message = "Connection pool closed"; return log; case constants_1.CONNECTION_CREATED: log = attachConnectionFields(log, logObject); log.message = "Connection created"; log.driverConnectionId = logObject.connectionId; return log; case constants_1.CONNECTION_READY: log = attachConnectionFields(log, logObject); log.message = "Connection ready"; log.driverConnectionId = logObject.connectionId; log.durationMS = logObject.durationMS; return log; case constants_1.CONNECTION_CLOSED: log = attachConnectionFields(log, logObject); log.message = "Connection closed"; log.driverConnectionId = logObject.connectionId; switch (logObject.reason) { case "stale": log.reason = "Connection became stale because the pool was cleared"; break; case "idle": log.reason = "Connection has been available but unused for longer than the configured max idle time"; break; case "error": log.reason = "An error occurred while using the connection"; if (logObject.error) { log.error = logObject.error; } break; case "poolClosed": log.reason = "Connection pool was closed"; break; default: log.reason = `Unknown close reason: ${logObject.reason}`; } return log; case constants_1.CONNECTION_CHECK_OUT_STARTED: log = attachConnectionFields(log, logObject); log.message = "Connection checkout started"; return log; case constants_1.CONNECTION_CHECK_OUT_FAILED: log = attachConnectionFields(log, logObject); log.message = "Connection checkout failed"; switch (logObject.reason) { case "poolClosed": log.reason = "Connection pool was closed"; break; case "timeout": log.reason = "Wait queue timeout elapsed without a connection becoming available"; break; case "connectionError": log.reason = "An error occurred while trying to establish a new connection"; if (logObject.error) { log.error = logObject.error; } break; default: log.reason = `Unknown close reason: ${logObject.reason}`; } log.durationMS = logObject.durationMS; return log; case constants_1.CONNECTION_CHECKED_OUT: log = attachConnectionFields(log, logObject); log.message = "Connection checked out"; log.driverConnectionId = logObject.connectionId; log.durationMS = logObject.durationMS; return log; case constants_1.CONNECTION_CHECKED_IN: log = attachConnectionFields(log, logObject); log.message = "Connection checked in"; log.driverConnectionId = logObject.connectionId; return log; case constants_1.SERVER_OPENING: log = attachSDAMFields(log, logObject); log = attachConnectionFields(log, logObject); log.message = "Starting server monitoring"; return log; case constants_1.SERVER_CLOSED: log = attachSDAMFields(log, logObject); log = attachConnectionFields(log, logObject); log.message = "Stopped server monitoring"; return log; case constants_1.SERVER_HEARTBEAT_STARTED: log = attachSDAMFields(log, logObject); log = attachServerHeartbeatFields(log, logObject); log.message = "Server heartbeat started"; return log; case constants_1.SERVER_HEARTBEAT_SUCCEEDED: log = attachSDAMFields(log, logObject); log = attachServerHeartbeatFields(log, logObject); log.message = "Server heartbeat succeeded"; log.durationMS = logObject.duration; log.serverConnectionId = logObject.serverConnectionId; log.reply = stringifyWithMaxLen(logObject.reply, maxDocumentLength, { relaxed: true }); return log; case constants_1.SERVER_HEARTBEAT_FAILED: log = attachSDAMFields(log, logObject); log = attachServerHeartbeatFields(log, logObject); log.message = "Server heartbeat failed"; log.durationMS = logObject.duration; log.failure = logObject.failure?.message; return log; case constants_1.TOPOLOGY_OPENING: log = attachSDAMFields(log, logObject); log.message = "Starting topology monitoring"; return log; case constants_1.TOPOLOGY_CLOSED: log = attachSDAMFields(log, logObject); log.message = "Stopped topology monitoring"; return log; case constants_1.TOPOLOGY_DESCRIPTION_CHANGED: log = attachSDAMFields(log, logObject); log.message = "Topology description changed"; log.previousDescription = log.reply = stringifyWithMaxLen(logObject.previousDescription, maxDocumentLength); log.newDescription = log.reply = stringifyWithMaxLen(logObject.newDescription, maxDocumentLength); return log; default: for (const [key, value] of Object.entries(logObject)) { if (value != null) log[key] = value; } } return log; } var MongoLogger = class { constructor(options) { this.pendingLog = null; this.error = this.log.bind(this, "error"); this.warn = this.log.bind(this, "warn"); this.info = this.log.bind(this, "info"); this.debug = this.log.bind(this, "debug"); this.trace = this.log.bind(this, "trace"); this.componentSeverities = options.componentSeverities; this.maxDocumentLength = options.maxDocumentLength; this.logDestination = options.logDestination; this.logDestinationIsStdErr = options.logDestinationIsStdErr; this.severities = this.createLoggingSeverities(); } createLoggingSeverities() { const severities = Object(); for (const component of Object.values(exports2.MongoLoggableComponent)) { severities[component] = {}; for (const severityLevel of Object.values(exports2.SeverityLevel)) { severities[component][severityLevel] = compareSeverity(severityLevel, this.componentSeverities[component]) <= 0; } } return severities; } turnOffSeverities() { for (const component of Object.values(exports2.MongoLoggableComponent)) { this.componentSeverities[component] = exports2.SeverityLevel.OFF; for (const severityLevel of Object.values(exports2.SeverityLevel)) { this.severities[component][severityLevel] = false; } } } logWriteFailureHandler(error) { if (this.logDestinationIsStdErr) { this.turnOffSeverities(); this.clearPendingLog(); return; } this.logDestination = createStdioLogger(process.stderr); this.logDestinationIsStdErr = true; this.clearPendingLog(); this.error(exports2.MongoLoggableComponent.CLIENT, { toLog: function() { return { message: "User input for mongodbLogPath is now invalid. Logging is halted.", error: error.message }; } }); this.turnOffSeverities(); this.clearPendingLog(); } clearPendingLog() { this.pendingLog = null; } willLog(component, severity) { if (severity === exports2.SeverityLevel.OFF) return false; return this.severities[component][severity]; } log(severity, component, message) { if (!this.willLog(component, severity)) return; let logMessage = { t: /* @__PURE__ */ new Date(), c: component, s: severity }; if (typeof message === "string") { logMessage.message = message; } else if (typeof message === "object") { if (isLogConvertible(message)) { logMessage = { ...logMessage, ...message.toLog() }; } else { logMessage = { ...logMessage, ...defaultLogTransform(message, this.maxDocumentLength) }; } } if ((0, utils_1.isPromiseLike)(this.pendingLog)) { this.pendingLog = this.pendingLog.then(() => this.logDestination.write(logMessage)).then(this.clearPendingLog.bind(this), this.logWriteFailureHandler.bind(this)); return; } try { const logResult = this.logDestination.write(logMessage); if ((0, utils_1.isPromiseLike)(logResult)) { this.pendingLog = logResult.then(this.clearPendingLog.bind(this), this.logWriteFailureHandler.bind(this)); } } catch (error) { this.logWriteFailureHandler(error); } } /** * Merges options set through environment variables and the MongoClient, preferring environment * variables when both are set, and substituting defaults for values not set. Options set in * constructor take precedence over both environment variables and MongoClient options. * * @remarks * When parsing component severity levels, invalid values are treated as unset and replaced with * the default severity. * * @param envOptions - options set for the logger from the environment * @param clientOptions - options set for the logger in the MongoClient options * @returns a MongoLoggerOptions object to be used when instantiating a new MongoLogger */ static resolveOptions(envOptions, clientOptions) { const resolvedLogPath = resolveLogPath(envOptions, clientOptions); const combinedOptions = { ...envOptions, ...clientOptions, mongodbLogPath: resolvedLogPath.mongodbLogPath, mongodbLogPathIsStdErr: resolvedLogPath.mongodbLogPathIsStdErr }; const defaultSeverity = resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.default, combinedOptions.MONGODB_LOG_ALL, exports2.SeverityLevel.OFF); return { componentSeverities: { command: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.command, combinedOptions.MONGODB_LOG_COMMAND, defaultSeverity), topology: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.topology, combinedOptions.MONGODB_LOG_TOPOLOGY, defaultSeverity), serverSelection: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.serverSelection, combinedOptions.MONGODB_LOG_SERVER_SELECTION, defaultSeverity), connection: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.connection, combinedOptions.MONGODB_LOG_CONNECTION, defaultSeverity), client: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.client, combinedOptions.MONGODB_LOG_CLIENT, defaultSeverity), default: defaultSeverity }, maxDocumentLength: combinedOptions.mongodbLogMaxDocumentLength ?? (0, utils_1.parseUnsignedInteger)(combinedOptions.MONGODB_LOG_MAX_DOCUMENT_LENGTH) ?? 1e3, logDestination: combinedOptions.mongodbLogPath, logDestinationIsStdErr: combinedOptions.mongodbLogPathIsStdErr }; } }; exports2.MongoLogger = MongoLogger; } }); // netlify/functions/node_modules/mongodb/lib/mongo_types.js var require_mongo_types = __commonJS({ "netlify/functions/node_modules/mongodb/lib/mongo_types.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.CancellationToken = exports2.TypedEventEmitter = void 0; var events_1 = require("events"); var mongo_logger_1 = require_mongo_logger(); var utils_1 = require_utils(); var TypedEventEmitter = class extends events_1.EventEmitter { /** @internal */ emitAndLog(event, ...args) { this.emit(event, ...args); if (this.component) this.mongoLogger?.debug(this.component, args[0]); } /** @internal */ emitAndLogHeartbeat(event, topologyId, serverConnectionId, ...args) { this.emit(event, ...args); if (this.component) { const loggableHeartbeatEvent = { topologyId, serverConnectionId: serverConnectionId ?? null, ...args[0] }; this.mongoLogger?.debug(this.component, loggableHeartbeatEvent); } } /** @internal */ emitAndLogCommand(monitorCommands, event, databaseName, connectionEstablished, ...args) { if (monitorCommands) { this.emit(event, ...args); } if (connectionEstablished) { const loggableCommandEvent = { databaseName, ...args[0] }; this.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.COMMAND, loggableCommandEvent); } } }; exports2.TypedEventEmitter = TypedEventEmitter; var CancellationToken = class extends TypedEventEmitter { constructor(...args) { super(...args); this.on("error", utils_1.noop); } }; exports2.CancellationToken = CancellationToken; } }); // netlify/functions/node_modules/mongodb/lib/sdam/server_selection.js var require_server_selection = __commonJS({ "netlify/functions/node_modules/mongodb/lib/sdam/server_selection.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.MIN_SECONDARY_WRITE_WIRE_VERSION = void 0; exports2.writableServerSelector = writableServerSelector; exports2.sameServerSelector = sameServerSelector; exports2.secondaryWritableServerSelector = secondaryWritableServerSelector; exports2.readPreferenceServerSelector = readPreferenceServerSelector; var error_1 = require_error(); var read_preference_1 = require_read_preference(); var common_1 = require_common(); var IDLE_WRITE_PERIOD = 1e4; var SMALLEST_MAX_STALENESS_SECONDS = 90; exports2.MIN_SECONDARY_WRITE_WIRE_VERSION = 13; function writableServerSelector() { return function writableServer(topologyDescription, servers) { return latencyWindowReducer(topologyDescription, servers.filter((s) => s.isWritable)); }; } function sameServerSelector(description) { return function sameServerSelector2(topologyDescription, servers) { if (!description) return []; return servers.filter((sd) => { return sd.address === description.address && sd.type !== common_1.ServerType.Unknown; }); }; } function secondaryWritableServerSelector(wireVersion, readPreference) { if (!readPreference || !wireVersion || wireVersion && wireVersion < exports2.MIN_SECONDARY_WRITE_WIRE_VERSION) { return readPreferenceServerSelector(read_preference_1.ReadPreference.primary); } return readPreferenceServerSelector(readPreference); } function maxStalenessReducer(readPreference, topologyDescription, servers) { if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) { return servers; } const maxStaleness = readPreference.maxStalenessSeconds; const maxStalenessVariance = (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1e3; if (maxStaleness < maxStalenessVariance) { throw new error_1.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${maxStalenessVariance} seconds`); } if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) { throw new error_1.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds`); } if (topologyDescription.type === common_1.TopologyType.ReplicaSetWithPrimary) { const primary = Array.from(topologyDescription.servers.values()).filter(primaryFilter)[0]; return servers.reduce((result, server) => { const stalenessMS = server.lastUpdateTime - server.lastWriteDate - (primary.lastUpdateTime - primary.lastWriteDate) + topologyDescription.heartbeatFrequencyMS; const staleness = stalenessMS / 1e3; const maxStalenessSeconds = readPreference.maxStalenessSeconds ?? 0; if (staleness <= maxStalenessSeconds) { result.push(server); } return result; }, []); } if (topologyDescription.type === common_1.TopologyType.ReplicaSetNoPrimary) { if (servers.length === 0) { return servers; } const sMax = servers.reduce((max, s) => s.lastWriteDate > max.lastWriteDate ? s : max); return servers.reduce((result, server) => { const stalenessMS = sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS; const staleness = stalenessMS / 1e3; const maxStalenessSeconds = readPreference.maxStalenessSeconds ?? 0; if (staleness <= maxStalenessSeconds) { result.push(server); } return result; }, []); } return servers; } function tagSetMatch(tagSet, serverTags) { const keys = Object.keys(tagSet); const serverTagKeys = Object.keys(serverTags); for (let i = 0; i < keys.length; ++i) { const key = keys[i]; if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) { return false; } } return true; } function tagSetReducer(readPreference, servers) { if (readPreference.tags == null || Array.isArray(readPreference.tags) && readPreference.tags.length === 0) { return servers; } for (let i = 0; i < readPreference.tags.length; ++i) { const tagSet = readPreference.tags[i]; const serversMatchingTagset = servers.reduce((matched, server) => { if (tagSetMatch(tagSet, server.tags)) matched.push(server); return matched; }, []); if (serversMatchingTagset.length) { return serversMatchingTagset; } } return []; } function latencyWindowReducer(topologyDescription, servers) { const low = servers.reduce((min, server) => Math.min(server.roundTripTime, min), Infinity); const high = low + topologyDescription.localThresholdMS; return servers.reduce((result, server) => { if (server.roundTripTime <= high && server.roundTripTime >= low) result.push(server); return result; }, []); } function primaryFilter(server) { return server.type === common_1.ServerType.RSPrimary; } function secondaryFilter(server) { return server.type === common_1.ServerType.RSSecondary; } function nearestFilter(server) { return server.type === common_1.ServerType.RSSecondary || server.type === common_1.ServerType.RSPrimary; } function knownFilter(server) { return server.type !== common_1.ServerType.Unknown; } function loadBalancerFilter(server) { return server.type === common_1.ServerType.LoadBalancer; } function readPreferenceServerSelector(readPreference) { if (!readPreference.isValid()) { throw new error_1.MongoInvalidArgumentError("Invalid read preference specified"); } return function readPreferenceServers(topologyDescription, servers, deprioritized = []) { const commonWireVersion = topologyDescription.commonWireVersion; if (commonWireVersion && readPreference.minWireVersion && readPreference.minWireVersion > commonWireVersion) { throw new error_1.MongoCompatibilityError(`Minimum wire version '${readPreference.minWireVersion}' required, but found '${commonWireVersion}'`); } if (topologyDescription.type === common_1.TopologyType.LoadBalanced) { return servers.filter(loadBalancerFilter); } if (topologyDescription.type === common_1.TopologyType.Unknown) { return []; } if (topologyDescription.type === common_1.TopologyType.Single) { return latencyWindowReducer(topologyDescription, servers.filter(knownFilter)); } if (topologyDescription.type === common_1.TopologyType.Sharded) { const filtered = servers.filter((server) => { return !deprioritized.includes(server); }); const selectable = filtered.length > 0 ? filtered : deprioritized; return latencyWindowReducer(topologyDescription, selectable.filter(knownFilter)); } const mode = readPreference.mode; if (mode === read_preference_1.ReadPreference.PRIMARY) { return servers.filter(primaryFilter); } if (mode === read_preference_1.ReadPreference.PRIMARY_PREFERRED) { const result = servers.filter(primaryFilter); if (result.length) { return result; } } const filter = mode === read_preference_1.ReadPreference.NEAREST ? nearestFilter : secondaryFilter; const selectedServers = latencyWindowReducer(topologyDescription, tagSetReducer(readPreference, maxStalenessReducer(readPreference, topologyDescription, servers.filter(filter)))); if (mode === read_preference_1.ReadPreference.SECONDARY_PREFERRED && selectedServers.length === 0) { return servers.filter(primaryFilter); } return selectedServers; }; } } }); // netlify/functions/node_modules/mongodb/lib/timeout.js var require_timeout = __commonJS({ "netlify/functions/node_modules/mongodb/lib/timeout.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.LegacyTimeoutContext = exports2.CSOTTimeoutContext = exports2.TimeoutContext = exports2.Timeout = exports2.TimeoutError = void 0; var timers_1 = require("timers"); var error_1 = require_error(); var utils_1 = require_utils(); var TimeoutError = class extends Error { get name() { return "TimeoutError"; } constructor(message, options) { super(message, options); this.duration = options.duration; } static is(error) { return error != null && typeof error === "object" && "name" in error && error.name === "TimeoutError"; } }; exports2.TimeoutError = TimeoutError; var Timeout = class _Timeout extends Promise { get remainingTime() { if (this.timedOut) return 0; if (this.duration === 0) return Infinity; return this.start + this.duration - Math.trunc(performance.now()); } get timeElapsed() { return Math.trunc(performance.now()) - this.start; } /** Create a new timeout that expires in `duration` ms */ constructor(executor = () => null, options) { const duration = options?.duration ?? 0; const unref = !!options?.unref; const rejection = options?.rejection; if (duration < 0) { throw new error_1.MongoInvalidArgumentError("Cannot create a Timeout with a negative duration"); } let reject; super((_, promiseReject) => { reject = promiseReject; executor(utils_1.noop, promiseReject); }); this.ended = null; this.timedOut = false; this.cleared = false; this.duration = duration; this.start = Math.trunc(performance.now()); if (rejection == null && this.duration > 0) { this.id = (0, timers_1.setTimeout)(() => { this.ended = Math.trunc(performance.now()); this.timedOut = true; reject(new TimeoutError(`Expired after ${duration}ms`, { duration })); }, this.duration); if (typeof this.id.unref === "function" && unref) { this.id.unref(); } } else if (rejection != null) { this.ended = Math.trunc(performance.now()); this.timedOut = true; reject(rejection); } } /** * Clears the underlying timeout. This method is idempotent */ clear() { (0, timers_1.clearTimeout)(this.id); this.id = void 0; this.timedOut = false; this.cleared = true; } throwIfExpired() { if (this.timedOut) { this.then(void 0, utils_1.squashError); throw new TimeoutError("Timed out", { duration: this.duration }); } } static expires(duration, unref) { return new _Timeout(void 0, { duration, unref }); } static reject(rejection) { return new _Timeout(void 0, { duration: 0, unref: true, rejection }); } }; exports2.Timeout = Timeout; function isLegacyTimeoutContextOptions(v) { return v != null && typeof v === "object" && "serverSelectionTimeoutMS" in v && typeof v.serverSelectionTimeoutMS === "number" && "waitQueueTimeoutMS" in v && typeof v.waitQueueTimeoutMS === "number"; } function isCSOTTimeoutContextOptions(v) { return v != null && typeof v === "object" && "serverSelectionTimeoutMS" in v && typeof v.serverSelectionTimeoutMS === "number" && "timeoutMS" in v && typeof v.timeoutMS === "number"; } var TimeoutContext = class { static create(options) { if (options.session?.timeoutContext != null) return options.session?.timeoutContext; if (isCSOTTimeoutContextOptions(options)) return new CSOTTimeoutContext(options); else if (isLegacyTimeoutContextOptions(options)) return new LegacyTimeoutContext(options); else throw new error_1.MongoRuntimeError("Unrecognized options"); } }; exports2.TimeoutContext = TimeoutContext; var CSOTTimeoutContext = class _CSOTTimeoutContext extends TimeoutContext { constructor(options) { super(); this.minRoundTripTime = 0; this.start = Math.trunc(performance.now()); this.timeoutMS = options.timeoutMS; this.serverSelectionTimeoutMS = options.serverSelectionTimeoutMS; this.socketTimeoutMS = options.socketTimeoutMS; this.clearServerSelectionTimeout = false; } get maxTimeMS() { return this.remainingTimeMS - this.minRoundTripTime; } get remainingTimeMS() { const timePassed = Math.trunc(performance.now()) - this.start; return this.timeoutMS <= 0 ? Infinity : this.timeoutMS - timePassed; } csotEnabled() { return true; } get serverSelectionTimeout() { if (typeof this._serverSelectionTimeout !== "object" || this._serverSelectionTimeout?.cleared) { const { remainingTimeMS, serverSelectionTimeoutMS } = this; if (remainingTimeMS <= 0) return Timeout.reject(new error_1.MongoOperationTimeoutError(`Timed out in server selection after ${this.timeoutMS}ms`)); const usingServerSelectionTimeoutMS = serverSelectionTimeoutMS !== 0 && (0, utils_1.csotMin)(remainingTimeMS, serverSelectionTimeoutMS) === serverSelectionTimeoutMS; if (usingServerSelectionTimeoutMS) { this._serverSelectionTimeout = Timeout.expires(serverSelectionTimeoutMS); } else { if (remainingTimeMS > 0 && Number.isFinite(remainingTimeMS)) { this._serverSelectionTimeout = Timeout.expires(remainingTimeMS); } else { this._serverSelectionTimeout = null; } } } return this._serverSelectionTimeout; } get connectionCheckoutTimeout() { if (typeof this._connectionCheckoutTimeout !== "object" || this._connectionCheckoutTimeout?.cleared) { if (typeof this._serverSelectionTimeout === "object") { this._connectionCheckoutTimeout = this._serverSelectionTimeout; } else { throw new error_1.MongoRuntimeError("Unreachable. If you are seeing this error, please file a ticket on the NODE driver project on Jira"); } } return this._connectionCheckoutTimeout; } get timeoutForSocketWrite() { const { remainingTimeMS } = this; if (!Number.isFinite(remainingTimeMS)) return null; if (remainingTimeMS > 0) return Timeout.expires(remainingTimeMS); return Timeout.reject(new error_1.MongoOperationTimeoutError("Timed out before socket write")); } get timeoutForSocketRead() { const { remainingTimeMS } = this; if (!Number.isFinite(remainingTimeMS)) return null; if (remainingTimeMS > 0) return Timeout.expires(remainingTimeMS); return Timeout.reject(new error_1.MongoOperationTimeoutError("Timed out before socket read")); } refresh() { this.start = Math.trunc(performance.now()); this.minRoundTripTime = 0; this._serverSelectionTimeout?.clear(); this._connectionCheckoutTimeout?.clear(); } clear() { this._serverSelectionTimeout?.clear(); this._connectionCheckoutTimeout?.clear(); } /** * @internal * Throws a MongoOperationTimeoutError if the context has expired. * If the context has not expired, returns the `remainingTimeMS` **/ getRemainingTimeMSOrThrow(message) { const { remainingTimeMS } = this; if (remainingTimeMS <= 0) throw new error_1.MongoOperationTimeoutError(message ?? `Expired after ${this.timeoutMS}ms`); return remainingTimeMS; } /** * @internal * This method is intended to be used in situations where concurrent operation are on the same deadline, but cannot share a single `TimeoutContext` instance. * Returns a new instance of `CSOTTimeoutContext` constructed with identical options, but setting the `start` property to `this.start`. */ clone() { const timeoutContext = new _CSOTTimeoutContext({ timeoutMS: this.timeoutMS, serverSelectionTimeoutMS: this.serverSelectionTimeoutMS }); timeoutContext.start = this.start; return timeoutContext; } refreshed() { return new _CSOTTimeoutContext(this); } addMaxTimeMSToCommand(command, options) { if (options.omitMaxTimeMS) return; const maxTimeMS = this.remainingTimeMS - this.minRoundTripTime; if (maxTimeMS > 0 && Number.isFinite(maxTimeMS)) command.maxTimeMS = maxTimeMS; } getSocketTimeoutMS() { return 0; } }; exports2.CSOTTimeoutContext = CSOTTimeoutContext; var LegacyTimeoutContext = class _LegacyTimeoutContext extends TimeoutContext { constructor(options) { super(); this.options = options; this.clearServerSelectionTimeout = true; } csotEnabled() { return false; } get serverSelectionTimeout() { if (this.options.serverSelectionTimeoutMS != null && this.options.serverSelectionTimeoutMS > 0) return Timeout.expires(this.options.serverSelectionTimeoutMS); return null; } get connectionCheckoutTimeout() { if (this.options.waitQueueTimeoutMS != null && this.options.waitQueueTimeoutMS > 0) return Timeout.expires(this.options.waitQueueTimeoutMS); return null; } get timeoutForSocketWrite() { return null; } get timeoutForSocketRead() { return null; } refresh() { return; } clear() { return; } get maxTimeMS() { return null; } refreshed() { return new _LegacyTimeoutContext(this.options); } addMaxTimeMSToCommand(_command, _options) { } getSocketTimeoutMS() { return this.options.socketTimeoutMS; } }; exports2.LegacyTimeoutContext = LegacyTimeoutContext; } }); // netlify/functions/node_modules/mongodb/lib/operations/operation.js var require_operation = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/operation.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.AbstractOperation = exports2.Aspect = void 0; exports2.defineAspects = defineAspects; var bson_1 = require_bson2(); var read_preference_1 = require_read_preference(); exports2.Aspect = { READ_OPERATION: Symbol("READ_OPERATION"), WRITE_OPERATION: Symbol("WRITE_OPERATION"), RETRYABLE: Symbol("RETRYABLE"), EXPLAINABLE: Symbol("EXPLAINABLE"), SKIP_COLLATION: Symbol("SKIP_COLLATION"), CURSOR_CREATING: Symbol("CURSOR_CREATING"), MUST_SELECT_SAME_SERVER: Symbol("MUST_SELECT_SAME_SERVER"), COMMAND_BATCHING: Symbol("COMMAND_BATCHING") }; var AbstractOperation = class { constructor(options = {}) { this.readPreference = this.hasAspect(exports2.Aspect.WRITE_OPERATION) ? read_preference_1.ReadPreference.primary : read_preference_1.ReadPreference.fromOptions(options) ?? read_preference_1.ReadPreference.primary; this.bsonOptions = (0, bson_1.resolveBSONOptions)(options); this._session = options.session != null ? options.session : void 0; this.options = options; this.bypassPinningCheck = !!options.bypassPinningCheck; this.trySecondaryWrite = false; } hasAspect(aspect) { const ctor = this.constructor; if (ctor.aspects == null) { return false; } return ctor.aspects.has(aspect); } // Make sure the session is not writable from outside this class. get session() { return this._session; } clearSession() { this._session = void 0; } resetBatch() { return true; } get canRetryRead() { return this.hasAspect(exports2.Aspect.RETRYABLE) && this.hasAspect(exports2.Aspect.READ_OPERATION); } get canRetryWrite() { return this.hasAspect(exports2.Aspect.RETRYABLE) && this.hasAspect(exports2.Aspect.WRITE_OPERATION); } }; exports2.AbstractOperation = AbstractOperation; function defineAspects(operation, aspects) { if (!Array.isArray(aspects) && !(aspects instanceof Set)) { aspects = [aspects]; } aspects = new Set(aspects); Object.defineProperty(operation, "aspects", { value: aspects, writable: false }); return aspects; } } }); // netlify/functions/node_modules/mongodb/lib/operations/execute_operation.js var require_execute_operation = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/execute_operation.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.executeOperation = executeOperation; var error_1 = require_error(); var read_preference_1 = require_read_preference(); var server_selection_1 = require_server_selection(); var timeout_1 = require_timeout(); var utils_1 = require_utils(); var operation_1 = require_operation(); var MMAPv1_RETRY_WRITES_ERROR_CODE = error_1.MONGODB_ERROR_CODES.IllegalOperation; var MMAPv1_RETRY_WRITES_ERROR_MESSAGE = "This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string."; async function executeOperation(client, operation, timeoutContext) { if (!(operation instanceof operation_1.AbstractOperation)) { throw new error_1.MongoRuntimeError("This method requires a valid operation instance"); } const topology = client.topology == null ? await (0, utils_1.abortable)(autoConnect(client), operation.options) : client.topology; let session = operation.session; let owner; if (session == null) { owner = Symbol(); session = client.startSession({ owner, explicit: false }); } else if (session.hasEnded) { throw new error_1.MongoExpiredSessionError("Use of expired sessions is not permitted"); } else if (session.snapshotEnabled && !topology.capabilities.supportsSnapshotReads) { throw new error_1.MongoCompatibilityError("Snapshot reads require MongoDB 5.0 or later"); } else if (session.client !== client) { throw new error_1.MongoInvalidArgumentError("ClientSession must be from the same MongoClient"); } const readPreference = operation.readPreference ?? read_preference_1.ReadPreference.primary; const inTransaction = !!session?.inTransaction(); const hasReadAspect = operation.hasAspect(operation_1.Aspect.READ_OPERATION); if (inTransaction && !readPreference.equals(read_preference_1.ReadPreference.primary) && (hasReadAspect || operation.commandName === "runCommand")) { throw new error_1.MongoTransactionError(`Read preference in a transaction must be primary, not: ${readPreference.mode}`); } if (session?.isPinned && session.transaction.isCommitted && !operation.bypassPinningCheck) { session.unpin(); } timeoutContext ??= timeout_1.TimeoutContext.create({ session, serverSelectionTimeoutMS: client.s.options.serverSelectionTimeoutMS, waitQueueTimeoutMS: client.s.options.waitQueueTimeoutMS, timeoutMS: operation.options.timeoutMS }); try { return await tryOperation(operation, { topology, timeoutContext, session, readPreference }); } finally { if (session?.owner != null && session.owner === owner) { await session.endSession(); } } } async function autoConnect(client) { if (client.topology == null) { if (client.s.hasBeenClosed) { throw new error_1.MongoNotConnectedError("Client must be connected before running operations"); } client.s.options.__skipPingOnConnect = true; try { await client.connect(); if (client.topology == null) { throw new error_1.MongoRuntimeError("client.connect did not create a topology but also did not throw"); } return client.topology; } finally { delete client.s.options.__skipPingOnConnect; } } return client.topology; } async function tryOperation(operation, { topology, timeoutContext, session, readPreference }) { let selector; if (operation.hasAspect(operation_1.Aspect.MUST_SELECT_SAME_SERVER)) { selector = (0, server_selection_1.sameServerSelector)(operation.server?.description); } else if (operation.trySecondaryWrite) { selector = (0, server_selection_1.secondaryWritableServerSelector)(topology.commonWireVersion, readPreference); } else { selector = readPreference; } let server = await topology.selectServer(selector, { session, operationName: operation.commandName, timeoutContext, signal: operation.options.signal }); const hasReadAspect = operation.hasAspect(operation_1.Aspect.READ_OPERATION); const hasWriteAspect = operation.hasAspect(operation_1.Aspect.WRITE_OPERATION); const inTransaction = session?.inTransaction() ?? false; const willRetryRead = topology.s.options.retryReads && !inTransaction && operation.canRetryRead; const willRetryWrite = topology.s.options.retryWrites && !inTransaction && (0, utils_1.supportsRetryableWrites)(server) && operation.canRetryWrite; const willRetry = operation.hasAspect(operation_1.Aspect.RETRYABLE) && session != null && (hasReadAspect && willRetryRead || hasWriteAspect && willRetryWrite); if (hasWriteAspect && willRetryWrite && session != null) { operation.options.willRetryWrite = true; session.incrementTransactionNumber(); } const maxTries = willRetry ? timeoutContext.csotEnabled() ? Infinity : 2 : 1; let previousOperationError; let previousServer; for (let tries = 0; tries < maxTries; tries++) { if (previousOperationError) { if (hasWriteAspect && previousOperationError.code === MMAPv1_RETRY_WRITES_ERROR_CODE) { throw new error_1.MongoServerError({ message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, originalError: previousOperationError }); } if (operation.hasAspect(operation_1.Aspect.COMMAND_BATCHING) && !operation.canRetryWrite) { throw previousOperationError; } if (hasWriteAspect && !(0, error_1.isRetryableWriteError)(previousOperationError)) throw previousOperationError; if (hasReadAspect && !(0, error_1.isRetryableReadError)(previousOperationError)) throw previousOperationError; if (previousOperationError instanceof error_1.MongoNetworkError && operation.hasAspect(operation_1.Aspect.CURSOR_CREATING) && session != null && session.isPinned && !session.inTransaction()) { session.unpin({ force: true, forceClear: true }); } server = await topology.selectServer(selector, { session, operationName: operation.commandName, previousServer, signal: operation.options.signal }); if (hasWriteAspect && !(0, utils_1.supportsRetryableWrites)(server)) { throw new error_1.MongoUnexpectedServerResponseError("Selected server does not support retryable writes"); } } try { if (tries > 0 && operation.hasAspect(operation_1.Aspect.COMMAND_BATCHING)) { operation.resetBatch(); } return await operation.execute(server, session, timeoutContext); } catch (operationError) { if (!(operationError instanceof error_1.MongoError)) throw operationError; if (previousOperationError != null && operationError.hasErrorLabel(error_1.MongoErrorLabel.NoWritesPerformed)) { throw previousOperationError; } previousServer = server.description; previousOperationError = operationError; timeoutContext.clear(); } } throw previousOperationError ?? new error_1.MongoRuntimeError("Tried to propagate retryability error, but no error was found."); } } }); // netlify/functions/node_modules/mongodb/lib/operations/get_more.js var require_get_more = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/get_more.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.GetMoreOperation = void 0; var responses_1 = require_responses(); var error_1 = require_error(); var utils_1 = require_utils(); var operation_1 = require_operation(); var GetMoreOperation = class extends operation_1.AbstractOperation { constructor(ns, cursorId, server, options) { super(options); this.options = options; this.ns = ns; this.cursorId = cursorId; this.server = server; } get commandName() { return "getMore"; } /** * Although there is a server already associated with the get more operation, the signature * for execute passes a server so we will just use that one. */ async execute(server, _session, timeoutContext) { if (server !== this.server) { throw new error_1.MongoRuntimeError("Getmore must run on the same server operation began on"); } if (this.cursorId == null || this.cursorId.isZero()) { throw new error_1.MongoRuntimeError("Unable to iterate cursor with no id"); } const collection = this.ns.collection; if (collection == null) { throw new error_1.MongoRuntimeError("A collection name must be determined before getMore"); } const getMoreCmd = { getMore: this.cursorId, collection }; if (typeof this.options.batchSize === "number") { getMoreCmd.batchSize = Math.abs(this.options.batchSize); } if (typeof this.options.maxAwaitTimeMS === "number") { getMoreCmd.maxTimeMS = this.options.maxAwaitTimeMS; } if (this.options.comment !== void 0 && (0, utils_1.maxWireVersion)(server) >= 9) { getMoreCmd.comment = this.options.comment; } const commandOptions = { returnFieldSelector: null, documentsReturnedIn: "nextBatch", timeoutContext, ...this.options }; return await server.command(this.ns, getMoreCmd, commandOptions, responses_1.CursorResponse); } }; exports2.GetMoreOperation = GetMoreOperation; (0, operation_1.defineAspects)(GetMoreOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.MUST_SELECT_SAME_SERVER]); } }); // netlify/functions/node_modules/mongodb/lib/operations/kill_cursors.js var require_kill_cursors = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/kill_cursors.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.KillCursorsOperation = void 0; var error_1 = require_error(); var utils_1 = require_utils(); var operation_1 = require_operation(); var KillCursorsOperation = class extends operation_1.AbstractOperation { constructor(cursorId, ns, server, options) { super(options); this.ns = ns; this.cursorId = cursorId; this.server = server; } get commandName() { return "killCursors"; } async execute(server, session, timeoutContext) { if (server !== this.server) { throw new error_1.MongoRuntimeError("Killcursor must run on the same server operation began on"); } const killCursors = this.ns.collection; if (killCursors == null) { throw new error_1.MongoRuntimeError("A collection name must be determined before killCursors"); } const killCursorsCommand = { killCursors, cursors: [this.cursorId] }; try { await server.command(this.ns, killCursorsCommand, { session, timeoutContext }); } catch (error) { (0, utils_1.squashError)(error); } } }; exports2.KillCursorsOperation = KillCursorsOperation; (0, operation_1.defineAspects)(KillCursorsOperation, [operation_1.Aspect.MUST_SELECT_SAME_SERVER]); } }); // netlify/functions/node_modules/mongodb/lib/bulk/ordered.js var require_ordered = __commonJS({ "netlify/functions/node_modules/mongodb/lib/bulk/ordered.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.OrderedBulkOperation = void 0; var BSON = require_bson2(); var error_1 = require_error(); var common_1 = require_common2(); var OrderedBulkOperation = class extends common_1.BulkOperationBase { /** @internal */ constructor(collection, options) { super(collection, options, true); } addToOperationsList(batchType, document2) { const bsonSize = BSON.calculateObjectSize(document2, { checkKeys: false, // Since we don't know what the user selected for BSON options here, // err on the safe side, and check the size with ignoreUndefined: false. ignoreUndefined: false }); if (bsonSize >= this.s.maxBsonObjectSize) throw new error_1.MongoInvalidArgumentError(`Document is larger than the maximum size ${this.s.maxBsonObjectSize}`); if (this.s.currentBatch == null) { this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); } const maxKeySize = this.s.maxKeySize; if ( // New batch if we exceed the max batch op size this.s.currentBatchSize + 1 >= this.s.maxWriteBatchSize || // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc, // since we can't sent an empty batch this.s.currentBatchSize > 0 && this.s.currentBatchSizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes || // New batch if the new op does not have the same op type as the current batch this.s.currentBatch.batchType !== batchType ) { this.s.batches.push(this.s.currentBatch); this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); this.s.currentBatchSize = 0; this.s.currentBatchSizeBytes = 0; } if (batchType === common_1.BatchType.INSERT) { this.s.bulkResult.insertedIds.push({ index: this.s.currentIndex, _id: document2._id }); } if (Array.isArray(document2)) { throw new error_1.MongoInvalidArgumentError("Operation passed in cannot be an Array"); } this.s.currentBatch.originalIndexes.push(this.s.currentIndex); this.s.currentBatch.operations.push(document2); this.s.currentBatchSize += 1; this.s.currentBatchSizeBytes += maxKeySize + bsonSize; this.s.currentIndex += 1; return this; } }; exports2.OrderedBulkOperation = OrderedBulkOperation; } }); // netlify/functions/node_modules/mongodb/lib/bulk/unordered.js var require_unordered = __commonJS({ "netlify/functions/node_modules/mongodb/lib/bulk/unordered.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.UnorderedBulkOperation = void 0; var BSON = require_bson2(); var error_1 = require_error(); var common_1 = require_common2(); var UnorderedBulkOperation = class extends common_1.BulkOperationBase { /** @internal */ constructor(collection, options) { super(collection, options, false); } handleWriteError(writeResult) { if (this.s.batches.length) { return; } return super.handleWriteError(writeResult); } addToOperationsList(batchType, document2) { const bsonSize = BSON.calculateObjectSize(document2, { checkKeys: false, // Since we don't know what the user selected for BSON options here, // err on the safe side, and check the size with ignoreUndefined: false. ignoreUndefined: false }); if (bsonSize >= this.s.maxBsonObjectSize) { throw new error_1.MongoInvalidArgumentError(`Document is larger than the maximum size ${this.s.maxBsonObjectSize}`); } this.s.currentBatch = void 0; if (batchType === common_1.BatchType.INSERT) { this.s.currentBatch = this.s.currentInsertBatch; } else if (batchType === common_1.BatchType.UPDATE) { this.s.currentBatch = this.s.currentUpdateBatch; } else if (batchType === common_1.BatchType.DELETE) { this.s.currentBatch = this.s.currentRemoveBatch; } const maxKeySize = this.s.maxKeySize; if (this.s.currentBatch == null) { this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); } if ( // New batch if we exceed the max batch op size this.s.currentBatch.size + 1 >= this.s.maxWriteBatchSize || // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc, // since we can't sent an empty batch this.s.currentBatch.size > 0 && this.s.currentBatch.sizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes || // New batch if the new op does not have the same op type as the current batch this.s.currentBatch.batchType !== batchType ) { this.s.batches.push(this.s.currentBatch); this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); } if (Array.isArray(document2)) { throw new error_1.MongoInvalidArgumentError("Operation passed in cannot be an Array"); } this.s.currentBatch.operations.push(document2); this.s.currentBatch.originalIndexes.push(this.s.currentIndex); this.s.currentIndex = this.s.currentIndex + 1; if (batchType === common_1.BatchType.INSERT) { this.s.currentInsertBatch = this.s.currentBatch; this.s.bulkResult.insertedIds.push({ index: this.s.bulkResult.insertedIds.length, _id: document2._id }); } else if (batchType === common_1.BatchType.UPDATE) { this.s.currentUpdateBatch = this.s.currentBatch; } else if (batchType === common_1.BatchType.DELETE) { this.s.currentRemoveBatch = this.s.currentBatch; } this.s.currentBatch.size += 1; this.s.currentBatch.sizeBytes += maxKeySize + bsonSize; return this; } }; exports2.UnorderedBulkOperation = UnorderedBulkOperation; } }); // netlify/functions/node_modules/mongodb/lib/operations/aggregate.js var require_aggregate = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/aggregate.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.AggregateOperation = exports2.DB_AGGREGATE_COLLECTION = void 0; var responses_1 = require_responses(); var error_1 = require_error(); var utils_1 = require_utils(); var write_concern_1 = require_write_concern(); var command_1 = require_command(); var operation_1 = require_operation(); exports2.DB_AGGREGATE_COLLECTION = 1; var MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT = 8; var AggregateOperation = class extends command_1.CommandOperation { constructor(ns, pipeline, options) { super(void 0, { ...options, dbName: ns.db }); this.options = { ...options }; this.target = ns.collection || exports2.DB_AGGREGATE_COLLECTION; this.pipeline = pipeline; this.hasWriteStage = false; if (typeof options?.out === "string") { this.pipeline = this.pipeline.concat({ $out: options.out }); this.hasWriteStage = true; } else if (pipeline.length > 0) { const finalStage = pipeline[pipeline.length - 1]; if (finalStage.$out || finalStage.$merge) { this.hasWriteStage = true; } } if (this.hasWriteStage) { this.trySecondaryWrite = true; } else { delete this.options.writeConcern; } if (this.explain && this.writeConcern) { throw new error_1.MongoInvalidArgumentError('Option "explain" cannot be used on an aggregate call with writeConcern'); } if (options?.cursor != null && typeof options.cursor !== "object") { throw new error_1.MongoInvalidArgumentError("Cursor options must be an object"); } } get commandName() { return "aggregate"; } get canRetryRead() { return !this.hasWriteStage; } addToPipeline(stage) { this.pipeline.push(stage); } async execute(server, session, timeoutContext) { const options = this.options; const serverWireVersion = (0, utils_1.maxWireVersion)(server); const command = { aggregate: this.target, pipeline: this.pipeline }; if (this.hasWriteStage && serverWireVersion < MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT) { this.readConcern = void 0; } if (this.hasWriteStage && this.writeConcern) { write_concern_1.WriteConcern.apply(command, this.writeConcern); } if (options.bypassDocumentValidation === true) { command.bypassDocumentValidation = options.bypassDocumentValidation; } if (typeof options.allowDiskUse === "boolean") { command.allowDiskUse = options.allowDiskUse; } if (options.hint) { command.hint = options.hint; } if (options.let) { command.let = options.let; } if (options.comment !== void 0) { command.comment = options.comment; } command.cursor = options.cursor || {}; if (options.batchSize && !this.hasWriteStage) { command.cursor.batchSize = options.batchSize; } return await super.executeCommand(server, session, command, timeoutContext, this.explain ? responses_1.ExplainedCursorResponse : responses_1.CursorResponse); } }; exports2.AggregateOperation = AggregateOperation; (0, operation_1.defineAspects)(AggregateOperation, [ operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE, operation_1.Aspect.EXPLAINABLE, operation_1.Aspect.CURSOR_CREATING ]); } }); // netlify/functions/node_modules/mongodb/lib/cursor/aggregation_cursor.js var require_aggregation_cursor = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cursor/aggregation_cursor.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.AggregationCursor = void 0; var error_1 = require_error(); var explain_1 = require_explain(); var aggregate_1 = require_aggregate(); var execute_operation_1 = require_execute_operation(); var utils_1 = require_utils(); var abstract_cursor_1 = require_abstract_cursor(); var AggregationCursor = class _AggregationCursor extends explain_1.ExplainableCursor { /** @internal */ constructor(client, namespace, pipeline = [], options = {}) { super(client, namespace, options); this.pipeline = pipeline; this.aggregateOptions = options; const lastStage = this.pipeline[this.pipeline.length - 1]; if (this.cursorOptions.timeoutMS != null && this.cursorOptions.timeoutMode === abstract_cursor_1.CursorTimeoutMode.ITERATION && (lastStage?.$merge != null || lastStage?.$out != null)) throw new error_1.MongoAPIError("Cannot use $out or $merge stage with ITERATION timeoutMode"); } clone() { const clonedOptions = (0, utils_1.mergeOptions)({}, this.aggregateOptions); delete clonedOptions.session; return new _AggregationCursor(this.client, this.namespace, this.pipeline, { ...clonedOptions }); } map(transform) { return super.map(transform); } /** @internal */ async _initialize(session) { const options = { ...this.aggregateOptions, ...this.cursorOptions, session, signal: this.signal }; if (options.explain) { try { (0, explain_1.validateExplainTimeoutOptions)(options, explain_1.Explain.fromOptions(options)); } catch { throw new error_1.MongoAPIError("timeoutMS cannot be used with explain when explain is specified in aggregateOptions"); } } const aggregateOperation = new aggregate_1.AggregateOperation(this.namespace, this.pipeline, options); const response = await (0, execute_operation_1.executeOperation)(this.client, aggregateOperation, this.timeoutContext); return { server: aggregateOperation.server, session, response }; } async explain(verbosity, options) { const { explain, timeout } = this.resolveExplainTimeoutOptions(verbosity, options); return (await (0, execute_operation_1.executeOperation)(this.client, new aggregate_1.AggregateOperation(this.namespace, this.pipeline, { ...this.aggregateOptions, // NOTE: order matters here, we may need to refine this ...this.cursorOptions, ...timeout, explain: explain ?? true }))).shift(this.deserializationOptions); } addStage(stage) { this.throwIfInitialized(); if (this.cursorOptions.timeoutMS != null && this.cursorOptions.timeoutMode === abstract_cursor_1.CursorTimeoutMode.ITERATION && (stage.$out != null || stage.$merge != null)) { throw new error_1.MongoAPIError("Cannot use $out or $merge stage with ITERATION timeoutMode"); } this.pipeline.push(stage); return this; } group($group) { return this.addStage({ $group }); } /** Add a limit stage to the aggregation pipeline */ limit($limit) { return this.addStage({ $limit }); } /** Add a match stage to the aggregation pipeline */ match($match) { return this.addStage({ $match }); } /** Add an out stage to the aggregation pipeline */ out($out) { return this.addStage({ $out }); } /** * Add a project stage to the aggregation pipeline * * @remarks * In order to strictly type this function you must provide an interface * that represents the effect of your projection on the result documents. * * By default chaining a projection to your cursor changes the returned type to the generic {@link Document} type. * You should specify a parameterized type to have assertions on your final results. * * @example * ```typescript * // Best way * const docs: AggregationCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); * // Flexible way * const docs: AggregationCursor = cursor.project({ _id: 0, a: true }); * ``` * * @remarks * In order to strictly type this function you must provide an interface * that represents the effect of your projection on the result documents. * * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, * it **does not** return a new instance of a cursor. This means when calling project, * you should always assign the result to a new variable in order to get a correctly typed cursor variable. * Take note of the following example: * * @example * ```typescript * const cursor: AggregationCursor<{ a: number; b: string }> = coll.aggregate([]); * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); * * // or always use chaining and save the final cursor * * const cursor = coll.aggregate().project<{ a: string }>({ * _id: 0, * a: { $convert: { input: '$a', to: 'string' } * }}); * ``` */ project($project) { return this.addStage({ $project }); } /** Add a lookup stage to the aggregation pipeline */ lookup($lookup) { return this.addStage({ $lookup }); } /** Add a redact stage to the aggregation pipeline */ redact($redact) { return this.addStage({ $redact }); } /** Add a skip stage to the aggregation pipeline */ skip($skip) { return this.addStage({ $skip }); } /** Add a sort stage to the aggregation pipeline */ sort($sort) { return this.addStage({ $sort }); } /** Add a unwind stage to the aggregation pipeline */ unwind($unwind) { return this.addStage({ $unwind }); } /** Add a geoNear stage to the aggregation pipeline */ geoNear($geoNear) { return this.addStage({ $geoNear }); } }; exports2.AggregationCursor = AggregationCursor; } }); // netlify/functions/node_modules/mongodb/lib/operations/count.js var require_count = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/count.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.CountOperation = void 0; var command_1 = require_command(); var operation_1 = require_operation(); var CountOperation = class extends command_1.CommandOperation { constructor(namespace, filter, options) { super({ s: { namespace } }, options); this.options = options; this.collectionName = namespace.collection; this.query = filter; } get commandName() { return "count"; } async execute(server, session, timeoutContext) { const options = this.options; const cmd = { count: this.collectionName, query: this.query }; if (typeof options.limit === "number") { cmd.limit = options.limit; } if (typeof options.skip === "number") { cmd.skip = options.skip; } if (options.hint != null) { cmd.hint = options.hint; } if (typeof options.maxTimeMS === "number") { cmd.maxTimeMS = options.maxTimeMS; } const result = await super.executeCommand(server, session, cmd, timeoutContext); return result ? result.n : 0; } }; exports2.CountOperation = CountOperation; (0, operation_1.defineAspects)(CountOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE]); } }); // netlify/functions/node_modules/mongodb/lib/sort.js var require_sort = __commonJS({ "netlify/functions/node_modules/mongodb/lib/sort.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.formatSort = formatSort; var error_1 = require_error(); function prepareDirection(direction = 1) { const value = `${direction}`.toLowerCase(); if (isMeta(direction)) return direction; switch (value) { case "ascending": case "asc": case "1": return 1; case "descending": case "desc": case "-1": return -1; default: throw new error_1.MongoInvalidArgumentError(`Invalid sort direction: ${JSON.stringify(direction)}`); } } function isMeta(t) { return typeof t === "object" && t != null && "$meta" in t && typeof t.$meta === "string"; } function isPair(t) { if (Array.isArray(t) && t.length === 2) { try { prepareDirection(t[1]); return true; } catch { return false; } } return false; } function isDeep(t) { return Array.isArray(t) && Array.isArray(t[0]); } function isMap(t) { return t instanceof Map && t.size > 0; } function isReadonlyArray(value) { return Array.isArray(value); } function pairToMap(v) { return /* @__PURE__ */ new Map([[`${v[0]}`, prepareDirection([v[1]])]]); } function deepToMap(t) { const sortEntries = t.map(([k, v]) => [`${k}`, prepareDirection(v)]); return new Map(sortEntries); } function stringsToMap(t) { const sortEntries = t.map((key) => [`${key}`, 1]); return new Map(sortEntries); } function objectToMap(t) { const sortEntries = Object.entries(t).map(([k, v]) => [ `${k}`, prepareDirection(v) ]); return new Map(sortEntries); } function mapToMap(t) { const sortEntries = Array.from(t).map(([k, v]) => [ `${k}`, prepareDirection(v) ]); return new Map(sortEntries); } function formatSort(sort, direction) { if (sort == null) return void 0; if (typeof sort === "string") return /* @__PURE__ */ new Map([[sort, prepareDirection(direction)]]); if (typeof sort !== "object") { throw new error_1.MongoInvalidArgumentError(`Invalid sort format: ${JSON.stringify(sort)} Sort must be a valid object`); } if (!isReadonlyArray(sort)) { if (isMap(sort)) return mapToMap(sort); if (Object.keys(sort).length) return objectToMap(sort); return void 0; } if (!sort.length) return void 0; if (isDeep(sort)) return deepToMap(sort); if (isPair(sort)) return pairToMap(sort); return stringsToMap(sort); } } }); // netlify/functions/node_modules/mongodb/lib/operations/find.js var require_find = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/find.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.FindOperation = void 0; var responses_1 = require_responses(); var error_1 = require_error(); var explain_1 = require_explain(); var read_concern_1 = require_read_concern(); var sort_1 = require_sort(); var utils_1 = require_utils(); var command_1 = require_command(); var operation_1 = require_operation(); var FindOperation = class extends command_1.CommandOperation { constructor(ns, filter = {}, options = {}) { super(void 0, options); this.options = { ...options }; delete this.options.writeConcern; this.ns = ns; if (typeof filter !== "object" || Array.isArray(filter)) { throw new error_1.MongoInvalidArgumentError("Query filter must be a plain object or ObjectId"); } this.filter = filter != null && filter._bsontype === "ObjectId" ? { _id: filter } : filter; } get commandName() { return "find"; } async execute(server, session, timeoutContext) { this.server = server; const options = this.options; let findCommand = makeFindCommand(this.ns, this.filter, options); if (this.explain) { (0, explain_1.validateExplainTimeoutOptions)(this.options, this.explain); findCommand = (0, explain_1.decorateWithExplain)(findCommand, this.explain); } return await server.command(this.ns, findCommand, { ...this.options, ...this.bsonOptions, documentsReturnedIn: "firstBatch", session, timeoutContext }, this.explain ? responses_1.ExplainedCursorResponse : responses_1.CursorResponse); } }; exports2.FindOperation = FindOperation; function makeFindCommand(ns, filter, options) { const findCommand = { find: ns.collection, filter }; if (options.sort) { findCommand.sort = (0, sort_1.formatSort)(options.sort); } if (options.projection) { let projection = options.projection; if (projection && Array.isArray(projection)) { projection = projection.length ? projection.reduce((result, field) => { result[field] = 1; return result; }, {}) : { _id: 1 }; } findCommand.projection = projection; } if (options.hint) { findCommand.hint = (0, utils_1.normalizeHintField)(options.hint); } if (typeof options.skip === "number") { findCommand.skip = options.skip; } if (typeof options.limit === "number") { if (options.limit < 0) { findCommand.limit = -options.limit; findCommand.singleBatch = true; } else { findCommand.limit = options.limit; } } if (typeof options.batchSize === "number") { if (options.batchSize < 0) { if (options.limit && options.limit !== 0 && Math.abs(options.batchSize) < Math.abs(options.limit)) { findCommand.limit = -options.batchSize; } findCommand.singleBatch = true; } else { findCommand.batchSize = options.batchSize; } } if (typeof options.singleBatch === "boolean") { findCommand.singleBatch = options.singleBatch; } if (options.comment !== void 0) { findCommand.comment = options.comment; } if (typeof options.maxTimeMS === "number") { findCommand.maxTimeMS = options.maxTimeMS; } const readConcern = read_concern_1.ReadConcern.fromOptions(options); if (readConcern) { findCommand.readConcern = readConcern.toJSON(); } if (options.max) { findCommand.max = options.max; } if (options.min) { findCommand.min = options.min; } if (typeof options.returnKey === "boolean") { findCommand.returnKey = options.returnKey; } if (typeof options.showRecordId === "boolean") { findCommand.showRecordId = options.showRecordId; } if (typeof options.tailable === "boolean") { findCommand.tailable = options.tailable; } if (typeof options.oplogReplay === "boolean") { findCommand.oplogReplay = options.oplogReplay; } if (typeof options.timeout === "boolean") { findCommand.noCursorTimeout = !options.timeout; } else if (typeof options.noCursorTimeout === "boolean") { findCommand.noCursorTimeout = options.noCursorTimeout; } if (typeof options.awaitData === "boolean") { findCommand.awaitData = options.awaitData; } if (typeof options.allowPartialResults === "boolean") { findCommand.allowPartialResults = options.allowPartialResults; } if (options.collation) { findCommand.collation = options.collation; } if (typeof options.allowDiskUse === "boolean") { findCommand.allowDiskUse = options.allowDiskUse; } if (options.let) { findCommand.let = options.let; } return findCommand; } (0, operation_1.defineAspects)(FindOperation, [ operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE, operation_1.Aspect.EXPLAINABLE, operation_1.Aspect.CURSOR_CREATING ]); } }); // netlify/functions/node_modules/mongodb/lib/cursor/find_cursor.js var require_find_cursor = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cursor/find_cursor.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.FindCursor = exports2.FLAGS = void 0; var responses_1 = require_responses(); var error_1 = require_error(); var explain_1 = require_explain(); var count_1 = require_count(); var execute_operation_1 = require_execute_operation(); var find_1 = require_find(); var sort_1 = require_sort(); var utils_1 = require_utils(); exports2.FLAGS = [ "tailable", "oplogReplay", "noCursorTimeout", "awaitData", "exhaust", "partial" ]; var FindCursor = class _FindCursor extends explain_1.ExplainableCursor { /** @internal */ constructor(client, namespace, filter = {}, options = {}) { super(client, namespace, options); this.numReturned = 0; this.cursorFilter = filter; this.findOptions = options; if (options.sort != null) { this.findOptions.sort = (0, sort_1.formatSort)(options.sort); } } clone() { const clonedOptions = (0, utils_1.mergeOptions)({}, this.findOptions); delete clonedOptions.session; return new _FindCursor(this.client, this.namespace, this.cursorFilter, { ...clonedOptions }); } map(transform) { return super.map(transform); } /** @internal */ async _initialize(session) { const options = { ...this.findOptions, // NOTE: order matters here, we may need to refine this ...this.cursorOptions, session, signal: this.signal }; if (options.explain) { try { (0, explain_1.validateExplainTimeoutOptions)(options, explain_1.Explain.fromOptions(options)); } catch { throw new error_1.MongoAPIError("timeoutMS cannot be used with explain when explain is specified in findOptions"); } } const findOperation = new find_1.FindOperation(this.namespace, this.cursorFilter, options); const response = await (0, execute_operation_1.executeOperation)(this.client, findOperation, this.timeoutContext); this.numReturned = response.batchSize; return { server: findOperation.server, session, response }; } /** @internal */ async getMore(batchSize) { const numReturned = this.numReturned; if (numReturned) { const limit = this.findOptions.limit; batchSize = limit && limit > 0 && numReturned + batchSize > limit ? limit - numReturned : batchSize; if (batchSize <= 0) { try { await this.close(); } catch (error) { (0, utils_1.squashError)(error); } return responses_1.CursorResponse.emptyGetMore; } } const response = await super.getMore(batchSize); this.numReturned = this.numReturned + response.batchSize; return response; } /** * Get the count of documents for this cursor * @deprecated Use `collection.estimatedDocumentCount` or `collection.countDocuments` instead */ async count(options) { (0, utils_1.emitWarningOnce)("cursor.count is deprecated and will be removed in the next major version, please use `collection.estimatedDocumentCount` or `collection.countDocuments` instead "); if (typeof options === "boolean") { throw new error_1.MongoInvalidArgumentError("Invalid first parameter to count"); } return await (0, execute_operation_1.executeOperation)(this.client, new count_1.CountOperation(this.namespace, this.cursorFilter, { ...this.findOptions, // NOTE: order matters here, we may need to refine this ...this.cursorOptions, ...options })); } async explain(verbosity, options) { const { explain, timeout } = this.resolveExplainTimeoutOptions(verbosity, options); return (await (0, execute_operation_1.executeOperation)(this.client, new find_1.FindOperation(this.namespace, this.cursorFilter, { ...this.findOptions, // NOTE: order matters here, we may need to refine this ...this.cursorOptions, ...timeout, explain: explain ?? true }))).shift(this.deserializationOptions); } /** Set the cursor query */ filter(filter) { this.throwIfInitialized(); this.cursorFilter = filter; return this; } /** * Set the cursor hint * * @param hint - If specified, then the query system will only consider plans using the hinted index. */ hint(hint) { this.throwIfInitialized(); this.findOptions.hint = hint; return this; } /** * Set the cursor min * * @param min - Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. */ min(min) { this.throwIfInitialized(); this.findOptions.min = min; return this; } /** * Set the cursor max * * @param max - Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. */ max(max) { this.throwIfInitialized(); this.findOptions.max = max; return this; } /** * Set the cursor returnKey. * If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. * If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. * * @param value - the returnKey value. */ returnKey(value) { this.throwIfInitialized(); this.findOptions.returnKey = value; return this; } /** * Modifies the output of a query by adding a field $recordId to matching documents. $recordId is the internal key which uniquely identifies a document in a collection. * * @param value - The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. */ showRecordId(value) { this.throwIfInitialized(); this.findOptions.showRecordId = value; return this; } /** * Add a query modifier to the cursor query * * @param name - The query modifier (must start with $, such as $orderby etc) * @param value - The modifier value. */ addQueryModifier(name, value) { this.throwIfInitialized(); if (name[0] !== "$") { throw new error_1.MongoInvalidArgumentError(`${name} is not a valid query modifier`); } const field = name.substr(1); switch (field) { case "comment": this.findOptions.comment = value; break; case "explain": this.findOptions.explain = value; break; case "hint": this.findOptions.hint = value; break; case "max": this.findOptions.max = value; break; case "maxTimeMS": this.findOptions.maxTimeMS = value; break; case "min": this.findOptions.min = value; break; case "orderby": this.findOptions.sort = (0, sort_1.formatSort)(value); break; case "query": this.cursorFilter = value; break; case "returnKey": this.findOptions.returnKey = value; break; case "showDiskLoc": this.findOptions.showRecordId = value; break; default: throw new error_1.MongoInvalidArgumentError(`Invalid query modifier: ${name}`); } return this; } /** * Add a comment to the cursor query allowing for tracking the comment in the log. * * @param value - The comment attached to this query. */ comment(value) { this.throwIfInitialized(); this.findOptions.comment = value; return this; } /** * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) * * @param value - Number of milliseconds to wait before aborting the tailed query. */ maxAwaitTimeMS(value) { this.throwIfInitialized(); if (typeof value !== "number") { throw new error_1.MongoInvalidArgumentError("Argument for maxAwaitTimeMS must be a number"); } this.findOptions.maxAwaitTimeMS = value; return this; } /** * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) * * @param value - Number of milliseconds to wait before aborting the query. */ maxTimeMS(value) { this.throwIfInitialized(); if (typeof value !== "number") { throw new error_1.MongoInvalidArgumentError("Argument for maxTimeMS must be a number"); } this.findOptions.maxTimeMS = value; return this; } /** * Add a project stage to the aggregation pipeline * * @remarks * In order to strictly type this function you must provide an interface * that represents the effect of your projection on the result documents. * * By default chaining a projection to your cursor changes the returned type to the generic * {@link Document} type. * You should specify a parameterized type to have assertions on your final results. * * @example * ```typescript * // Best way * const docs: FindCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); * // Flexible way * const docs: FindCursor = cursor.project({ _id: 0, a: true }); * ``` * * @remarks * * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, * it **does not** return a new instance of a cursor. This means when calling project, * you should always assign the result to a new variable in order to get a correctly typed cursor variable. * Take note of the following example: * * @example * ```typescript * const cursor: FindCursor<{ a: number; b: string }> = coll.find(); * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); * * // or always use chaining and save the final cursor * * const cursor = coll.find().project<{ a: string }>({ * _id: 0, * a: { $convert: { input: '$a', to: 'string' } * }}); * ``` */ project(value) { this.throwIfInitialized(); this.findOptions.projection = value; return this; } /** * Sets the sort order of the cursor query. * * @param sort - The key or keys set for the sort. * @param direction - The direction of the sorting (1 or -1). */ sort(sort, direction) { this.throwIfInitialized(); if (this.findOptions.tailable) { throw new error_1.MongoTailableCursorError("Tailable cursor does not support sorting"); } this.findOptions.sort = (0, sort_1.formatSort)(sort, direction); return this; } /** * Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher) * * @remarks * {@link https://www.mongodb.com/docs/manual/reference/command/find/#find-cmd-allowdiskuse | find command allowDiskUse documentation} */ allowDiskUse(allow = true) { this.throwIfInitialized(); if (!this.findOptions.sort) { throw new error_1.MongoInvalidArgumentError('Option "allowDiskUse" requires a sort specification'); } if (!allow) { this.findOptions.allowDiskUse = false; return this; } this.findOptions.allowDiskUse = true; return this; } /** * Set the collation options for the cursor. * * @param value - The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). */ collation(value) { this.throwIfInitialized(); this.findOptions.collation = value; return this; } /** * Set the limit for the cursor. * * @param value - The limit for the cursor query. */ limit(value) { this.throwIfInitialized(); if (this.findOptions.tailable) { throw new error_1.MongoTailableCursorError("Tailable cursor does not support limit"); } if (typeof value !== "number") { throw new error_1.MongoInvalidArgumentError('Operation "limit" requires an integer'); } this.findOptions.limit = value; return this; } /** * Set the skip for the cursor. * * @param value - The skip for the cursor query. */ skip(value) { this.throwIfInitialized(); if (this.findOptions.tailable) { throw new error_1.MongoTailableCursorError("Tailable cursor does not support skip"); } if (typeof value !== "number") { throw new error_1.MongoInvalidArgumentError('Operation "skip" requires an integer'); } this.findOptions.skip = value; return this; } }; exports2.FindCursor = FindCursor; } }); // netlify/functions/node_modules/mongodb/lib/operations/indexes.js var require_indexes = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/indexes.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ListIndexesOperation = exports2.DropIndexOperation = exports2.CreateIndexesOperation = void 0; var responses_1 = require_responses(); var error_1 = require_error(); var utils_1 = require_utils(); var command_1 = require_command(); var operation_1 = require_operation(); var VALID_INDEX_OPTIONS = /* @__PURE__ */ new Set([ "background", "unique", "name", "partialFilterExpression", "sparse", "hidden", "expireAfterSeconds", "storageEngine", "collation", "version", // text indexes "weights", "default_language", "language_override", "textIndexVersion", // 2d-sphere indexes "2dsphereIndexVersion", // 2d indexes "bits", "min", "max", // geoHaystack Indexes "bucketSize", // wildcard indexes "wildcardProjection" ]); function isIndexDirection(x) { return typeof x === "number" || x === "2d" || x === "2dsphere" || x === "text" || x === "geoHaystack"; } function isSingleIndexTuple(t) { return Array.isArray(t) && t.length === 2 && isIndexDirection(t[1]); } function constructIndexDescriptionMap(indexSpec) { const key = /* @__PURE__ */ new Map(); const indexSpecs = !Array.isArray(indexSpec) || isSingleIndexTuple(indexSpec) ? [indexSpec] : indexSpec; for (const spec of indexSpecs) { if (typeof spec === "string") { key.set(spec, 1); } else if (Array.isArray(spec)) { key.set(spec[0], spec[1] ?? 1); } else if (spec instanceof Map) { for (const [property, value] of spec) { key.set(property, value); } } else if ((0, utils_1.isObject)(spec)) { for (const [property, value] of Object.entries(spec)) { key.set(property, value); } } } return key; } function resolveIndexDescription(description) { const validProvidedOptions = Object.entries(description).filter(([optionName]) => VALID_INDEX_OPTIONS.has(optionName)); return Object.fromEntries( // we support the `version` option, but the `createIndexes` command expects it to be the `v` validProvidedOptions.map(([name, value]) => name === "version" ? ["v", value] : [name, value]) ); } var CreateIndexesOperation = class _CreateIndexesOperation extends command_1.CommandOperation { constructor(parent, collectionName, indexes, options) { super(parent, options); this.options = options ?? {}; this.collectionName = collectionName; this.indexes = indexes.map((userIndex) => { const key = userIndex.key instanceof Map ? userIndex.key : new Map(Object.entries(userIndex.key)); const name = userIndex.name ?? Array.from(key).flat().join("_"); const validIndexOptions = resolveIndexDescription(userIndex); return { ...validIndexOptions, name, key }; }); } static fromIndexDescriptionArray(parent, collectionName, indexes, options) { return new _CreateIndexesOperation(parent, collectionName, indexes, options); } static fromIndexSpecification(parent, collectionName, indexSpec, options = {}) { const key = constructIndexDescriptionMap(indexSpec); const description = { ...options, key }; return new _CreateIndexesOperation(parent, collectionName, [description], options); } get commandName() { return "createIndexes"; } async execute(server, session, timeoutContext) { const options = this.options; const indexes = this.indexes; const serverWireVersion = (0, utils_1.maxWireVersion)(server); const cmd = { createIndexes: this.collectionName, indexes }; if (options.commitQuorum != null) { if (serverWireVersion < 9) { throw new error_1.MongoCompatibilityError("Option `commitQuorum` for `createIndexes` not supported on servers < 4.4"); } cmd.commitQuorum = options.commitQuorum; } this.options.collation = void 0; await super.executeCommand(server, session, cmd, timeoutContext); const indexNames = indexes.map((index) => index.name || ""); return indexNames; } }; exports2.CreateIndexesOperation = CreateIndexesOperation; var DropIndexOperation = class extends command_1.CommandOperation { constructor(collection, indexName, options) { super(collection, options); this.options = options ?? {}; this.collection = collection; this.indexName = indexName; } get commandName() { return "dropIndexes"; } async execute(server, session, timeoutContext) { const cmd = { dropIndexes: this.collection.collectionName, index: this.indexName }; return await super.executeCommand(server, session, cmd, timeoutContext); } }; exports2.DropIndexOperation = DropIndexOperation; var ListIndexesOperation = class extends command_1.CommandOperation { constructor(collection, options) { super(collection, options); this.options = { ...options }; delete this.options.writeConcern; this.collectionNamespace = collection.s.namespace; } get commandName() { return "listIndexes"; } async execute(server, session, timeoutContext) { const serverWireVersion = (0, utils_1.maxWireVersion)(server); const cursor = this.options.batchSize ? { batchSize: this.options.batchSize } : {}; const command = { listIndexes: this.collectionNamespace.collection, cursor }; if (serverWireVersion >= 9 && this.options.comment !== void 0) { command.comment = this.options.comment; } return await super.executeCommand(server, session, command, timeoutContext, responses_1.CursorResponse); } }; exports2.ListIndexesOperation = ListIndexesOperation; (0, operation_1.defineAspects)(ListIndexesOperation, [ operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE, operation_1.Aspect.CURSOR_CREATING ]); (0, operation_1.defineAspects)(CreateIndexesOperation, [operation_1.Aspect.WRITE_OPERATION]); (0, operation_1.defineAspects)(DropIndexOperation, [operation_1.Aspect.WRITE_OPERATION]); } }); // netlify/functions/node_modules/mongodb/lib/cursor/list_indexes_cursor.js var require_list_indexes_cursor = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cursor/list_indexes_cursor.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ListIndexesCursor = void 0; var execute_operation_1 = require_execute_operation(); var indexes_1 = require_indexes(); var abstract_cursor_1 = require_abstract_cursor(); var ListIndexesCursor = class _ListIndexesCursor extends abstract_cursor_1.AbstractCursor { constructor(collection, options) { super(collection.client, collection.s.namespace, options); this.parent = collection; this.options = options; } clone() { return new _ListIndexesCursor(this.parent, { ...this.options, ...this.cursorOptions }); } /** @internal */ async _initialize(session) { const operation = new indexes_1.ListIndexesOperation(this.parent, { ...this.cursorOptions, ...this.options, session }); const response = await (0, execute_operation_1.executeOperation)(this.parent.client, operation, this.timeoutContext); return { server: operation.server, session, response }; } }; exports2.ListIndexesCursor = ListIndexesCursor; } }); // netlify/functions/node_modules/mongodb/lib/cursor/list_search_indexes_cursor.js var require_list_search_indexes_cursor = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cursor/list_search_indexes_cursor.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ListSearchIndexesCursor = void 0; var aggregation_cursor_1 = require_aggregation_cursor(); var ListSearchIndexesCursor = class extends aggregation_cursor_1.AggregationCursor { /** @internal */ constructor({ fullNamespace: ns, client }, name, options = {}) { const pipeline = name == null ? [{ $listSearchIndexes: {} }] : [{ $listSearchIndexes: { name } }]; super(client, ns, pipeline, options); } }; exports2.ListSearchIndexesCursor = ListSearchIndexesCursor; } }); // netlify/functions/node_modules/mongodb/lib/operations/bulk_write.js var require_bulk_write = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/bulk_write.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.BulkWriteOperation = void 0; var operation_1 = require_operation(); var BulkWriteOperation = class extends operation_1.AbstractOperation { constructor(collection, operations, options) { super(options); this.options = options; this.collection = collection; this.operations = operations; } get commandName() { return "bulkWrite"; } async execute(server, session, timeoutContext) { const coll = this.collection; const operations = this.operations; const options = { ...this.options, ...this.bsonOptions, readPreference: this.readPreference, timeoutContext }; const bulk = options.ordered === false ? coll.initializeUnorderedBulkOp(options) : coll.initializeOrderedBulkOp(options); for (let i = 0; i < operations.length; i++) { bulk.raw(operations[i]); } return await bulk.execute({ ...options, session }); } }; exports2.BulkWriteOperation = BulkWriteOperation; (0, operation_1.defineAspects)(BulkWriteOperation, [operation_1.Aspect.WRITE_OPERATION]); } }); // netlify/functions/node_modules/mongodb/lib/operations/distinct.js var require_distinct = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/distinct.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.DistinctOperation = void 0; var utils_1 = require_utils(); var command_1 = require_command(); var operation_1 = require_operation(); var DistinctOperation = class extends command_1.CommandOperation { /** * Construct a Distinct operation. * * @param collection - Collection instance. * @param key - Field of the document to find distinct values for. * @param query - The query for filtering the set of documents to which we apply the distinct filter. * @param options - Optional settings. See Collection.prototype.distinct for a list of options. */ constructor(collection, key, query, options) { super(collection, options); this.options = options ?? {}; this.collection = collection; this.key = key; this.query = query; } get commandName() { return "distinct"; } async execute(server, session, timeoutContext) { const coll = this.collection; const key = this.key; const query = this.query; const options = this.options; const cmd = { distinct: coll.collectionName, key, query }; if (typeof options.maxTimeMS === "number") { cmd.maxTimeMS = options.maxTimeMS; } if (typeof options.comment !== "undefined") { cmd.comment = options.comment; } if (options.hint != null) { cmd.hint = options.hint; } (0, utils_1.decorateWithReadConcern)(cmd, coll, options); (0, utils_1.decorateWithCollation)(cmd, coll, options); const result = await super.executeCommand(server, session, cmd, timeoutContext); return this.explain ? result : result.values; } }; exports2.DistinctOperation = DistinctOperation; (0, operation_1.defineAspects)(DistinctOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE, operation_1.Aspect.EXPLAINABLE]); } }); // netlify/functions/node_modules/mongodb/lib/operations/drop.js var require_drop = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/drop.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.DropDatabaseOperation = exports2.DropCollectionOperation = void 0; var error_1 = require_error(); var command_1 = require_command(); var operation_1 = require_operation(); var DropCollectionOperation = class _DropCollectionOperation extends command_1.CommandOperation { constructor(db, name, options = {}) { super(db, options); this.db = db; this.options = options; this.name = name; } get commandName() { return "drop"; } async execute(server, session, timeoutContext) { const db = this.db; const options = this.options; const name = this.name; const encryptedFieldsMap = db.client.s.options.autoEncryption?.encryptedFieldsMap; let encryptedFields = options.encryptedFields ?? encryptedFieldsMap?.[`${db.databaseName}.${name}`]; if (!encryptedFields && encryptedFieldsMap) { const listCollectionsResult = await db.listCollections({ name }, { nameOnly: false }).toArray(); encryptedFields = listCollectionsResult?.[0]?.options?.encryptedFields; } if (encryptedFields) { const escCollection = encryptedFields.escCollection || `enxcol_.${name}.esc`; const ecocCollection = encryptedFields.ecocCollection || `enxcol_.${name}.ecoc`; for (const collectionName of [escCollection, ecocCollection]) { const dropOp = new _DropCollectionOperation(db, collectionName); try { await dropOp.executeWithoutEncryptedFieldsCheck(server, session, timeoutContext); } catch (err) { if (!(err instanceof error_1.MongoServerError) || err.code !== error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { throw err; } } } } return await this.executeWithoutEncryptedFieldsCheck(server, session, timeoutContext); } async executeWithoutEncryptedFieldsCheck(server, session, timeoutContext) { await super.executeCommand(server, session, { drop: this.name }, timeoutContext); return true; } }; exports2.DropCollectionOperation = DropCollectionOperation; var DropDatabaseOperation = class extends command_1.CommandOperation { constructor(db, options) { super(db, options); this.options = options; } get commandName() { return "dropDatabase"; } async execute(server, session, timeoutContext) { await super.executeCommand(server, session, { dropDatabase: 1 }, timeoutContext); return true; } }; exports2.DropDatabaseOperation = DropDatabaseOperation; (0, operation_1.defineAspects)(DropCollectionOperation, [operation_1.Aspect.WRITE_OPERATION]); (0, operation_1.defineAspects)(DropDatabaseOperation, [operation_1.Aspect.WRITE_OPERATION]); } }); // netlify/functions/node_modules/mongodb/lib/operations/estimated_document_count.js var require_estimated_document_count = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/estimated_document_count.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.EstimatedDocumentCountOperation = void 0; var command_1 = require_command(); var operation_1 = require_operation(); var EstimatedDocumentCountOperation = class extends command_1.CommandOperation { constructor(collection, options = {}) { super(collection, options); this.options = options; this.collectionName = collection.collectionName; } get commandName() { return "count"; } async execute(server, session, timeoutContext) { const cmd = { count: this.collectionName }; if (typeof this.options.maxTimeMS === "number") { cmd.maxTimeMS = this.options.maxTimeMS; } if (this.options.comment !== void 0) { cmd.comment = this.options.comment; } const response = await super.executeCommand(server, session, cmd, timeoutContext); return response?.n || 0; } }; exports2.EstimatedDocumentCountOperation = EstimatedDocumentCountOperation; (0, operation_1.defineAspects)(EstimatedDocumentCountOperation, [ operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE, operation_1.Aspect.CURSOR_CREATING ]); } }); // netlify/functions/node_modules/mongodb/lib/operations/find_and_modify.js var require_find_and_modify = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/find_and_modify.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.FindOneAndUpdateOperation = exports2.FindOneAndReplaceOperation = exports2.FindOneAndDeleteOperation = exports2.FindAndModifyOperation = exports2.ReturnDocument = void 0; var error_1 = require_error(); var read_preference_1 = require_read_preference(); var sort_1 = require_sort(); var utils_1 = require_utils(); var command_1 = require_command(); var operation_1 = require_operation(); exports2.ReturnDocument = Object.freeze({ BEFORE: "before", AFTER: "after" }); function configureFindAndModifyCmdBaseUpdateOpts(cmdBase, options) { cmdBase.new = options.returnDocument === exports2.ReturnDocument.AFTER; cmdBase.upsert = options.upsert === true; if (options.bypassDocumentValidation === true) { cmdBase.bypassDocumentValidation = options.bypassDocumentValidation; } return cmdBase; } var FindAndModifyOperation = class extends command_1.CommandOperation { constructor(collection, query, options) { super(collection, options); this.options = options ?? {}; this.cmdBase = { remove: false, new: false, upsert: false }; options.includeResultMetadata ??= false; const sort = (0, sort_1.formatSort)(options.sort); if (sort) { this.cmdBase.sort = sort; } if (options.projection) { this.cmdBase.fields = options.projection; } if (options.maxTimeMS) { this.cmdBase.maxTimeMS = options.maxTimeMS; } if (options.writeConcern) { this.cmdBase.writeConcern = options.writeConcern; } if (options.let) { this.cmdBase.let = options.let; } if (options.comment !== void 0) { this.cmdBase.comment = options.comment; } this.readPreference = read_preference_1.ReadPreference.primary; this.collection = collection; this.query = query; } get commandName() { return "findAndModify"; } async execute(server, session, timeoutContext) { const coll = this.collection; const query = this.query; const options = { ...this.options, ...this.bsonOptions }; const cmd = { findAndModify: coll.collectionName, query, ...this.cmdBase }; (0, utils_1.decorateWithCollation)(cmd, coll, options); if (options.hint) { const unacknowledgedWrite = this.writeConcern?.w === 0; if (unacknowledgedWrite || (0, utils_1.maxWireVersion)(server) < 8) { throw new error_1.MongoCompatibilityError("The current topology does not support a hint on findAndModify commands"); } cmd.hint = options.hint; } const result = await super.executeCommand(server, session, cmd, timeoutContext); return options.includeResultMetadata ? result : result.value ?? null; } }; exports2.FindAndModifyOperation = FindAndModifyOperation; var FindOneAndDeleteOperation = class extends FindAndModifyOperation { constructor(collection, filter, options) { if (filter == null || typeof filter !== "object") { throw new error_1.MongoInvalidArgumentError('Argument "filter" must be an object'); } super(collection, filter, options); this.cmdBase.remove = true; } }; exports2.FindOneAndDeleteOperation = FindOneAndDeleteOperation; var FindOneAndReplaceOperation = class extends FindAndModifyOperation { constructor(collection, filter, replacement, options) { if (filter == null || typeof filter !== "object") { throw new error_1.MongoInvalidArgumentError('Argument "filter" must be an object'); } if (replacement == null || typeof replacement !== "object") { throw new error_1.MongoInvalidArgumentError('Argument "replacement" must be an object'); } if ((0, utils_1.hasAtomicOperators)(replacement)) { throw new error_1.MongoInvalidArgumentError("Replacement document must not contain atomic operators"); } super(collection, filter, options); this.cmdBase.update = replacement; configureFindAndModifyCmdBaseUpdateOpts(this.cmdBase, options); } }; exports2.FindOneAndReplaceOperation = FindOneAndReplaceOperation; var FindOneAndUpdateOperation = class extends FindAndModifyOperation { constructor(collection, filter, update, options) { if (filter == null || typeof filter !== "object") { throw new error_1.MongoInvalidArgumentError('Argument "filter" must be an object'); } if (update == null || typeof update !== "object") { throw new error_1.MongoInvalidArgumentError('Argument "update" must be an object'); } if (!(0, utils_1.hasAtomicOperators)(update, options)) { throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators"); } super(collection, filter, options); this.cmdBase.update = update; configureFindAndModifyCmdBaseUpdateOpts(this.cmdBase, options); if (options.arrayFilters) { this.cmdBase.arrayFilters = options.arrayFilters; } } }; exports2.FindOneAndUpdateOperation = FindOneAndUpdateOperation; (0, operation_1.defineAspects)(FindAndModifyOperation, [ operation_1.Aspect.WRITE_OPERATION, operation_1.Aspect.RETRYABLE, operation_1.Aspect.EXPLAINABLE ]); } }); // netlify/functions/node_modules/mongodb/lib/operations/insert.js var require_insert = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/insert.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.InsertManyOperation = exports2.InsertOneOperation = exports2.InsertOperation = void 0; var error_1 = require_error(); var utils_1 = require_utils(); var write_concern_1 = require_write_concern(); var bulk_write_1 = require_bulk_write(); var command_1 = require_command(); var operation_1 = require_operation(); var InsertOperation = class extends command_1.CommandOperation { constructor(ns, documents, options) { super(void 0, options); this.options = { ...options, checkKeys: options.checkKeys ?? false }; this.ns = ns; this.documents = documents; } get commandName() { return "insert"; } async execute(server, session, timeoutContext) { const options = this.options ?? {}; const ordered = typeof options.ordered === "boolean" ? options.ordered : true; const command = { insert: this.ns.collection, documents: this.documents, ordered }; if (typeof options.bypassDocumentValidation === "boolean") { command.bypassDocumentValidation = options.bypassDocumentValidation; } if (options.comment !== void 0) { command.comment = options.comment; } return await super.executeCommand(server, session, command, timeoutContext); } }; exports2.InsertOperation = InsertOperation; var InsertOneOperation = class extends InsertOperation { constructor(collection, doc, options) { super(collection.s.namespace, (0, utils_1.maybeAddIdToDocuments)(collection, [doc], options), options); } async execute(server, session, timeoutContext) { const res = await super.execute(server, session, timeoutContext); if (res.code) throw new error_1.MongoServerError(res); if (res.writeErrors) { throw new error_1.MongoServerError(res.writeErrors[0]); } return { acknowledged: this.writeConcern?.w !== 0, insertedId: this.documents[0]._id }; } }; exports2.InsertOneOperation = InsertOneOperation; var InsertManyOperation = class extends operation_1.AbstractOperation { constructor(collection, docs, options) { super(options); if (!Array.isArray(docs)) { throw new error_1.MongoInvalidArgumentError('Argument "docs" must be an array of documents'); } this.options = options; this.collection = collection; this.docs = docs; } get commandName() { return "insert"; } async execute(server, session, timeoutContext) { const coll = this.collection; const options = { ...this.options, ...this.bsonOptions, readPreference: this.readPreference }; const writeConcern = write_concern_1.WriteConcern.fromOptions(options); const bulkWriteOperation = new bulk_write_1.BulkWriteOperation(coll, this.docs.map((document2) => ({ insertOne: { document: document2 } })), options); try { const res = await bulkWriteOperation.execute(server, session, timeoutContext); return { acknowledged: writeConcern?.w !== 0, insertedCount: res.insertedCount, insertedIds: res.insertedIds }; } catch (err) { if (err && err.message === "Operation must be an object with an operation key") { throw new error_1.MongoInvalidArgumentError("Collection.insertMany() cannot be called with an array that has null/undefined values"); } throw err; } } }; exports2.InsertManyOperation = InsertManyOperation; (0, operation_1.defineAspects)(InsertOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION]); (0, operation_1.defineAspects)(InsertOneOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION]); (0, operation_1.defineAspects)(InsertManyOperation, [operation_1.Aspect.WRITE_OPERATION]); } }); // netlify/functions/node_modules/mongodb/lib/operations/is_capped.js var require_is_capped = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/is_capped.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.IsCappedOperation = void 0; var error_1 = require_error(); var operation_1 = require_operation(); var IsCappedOperation = class extends operation_1.AbstractOperation { constructor(collection, options) { super(options); this.options = options; this.collection = collection; } get commandName() { return "listCollections"; } async execute(server, session) { const coll = this.collection; const [collection] = await coll.s.db.listCollections({ name: coll.collectionName }, { ...this.options, nameOnly: false, readPreference: this.readPreference, session }).toArray(); if (collection == null || collection.options == null) { throw new error_1.MongoAPIError(`collection ${coll.namespace} not found`); } return !!collection.options?.capped; } }; exports2.IsCappedOperation = IsCappedOperation; } }); // netlify/functions/node_modules/mongodb/lib/operations/options_operation.js var require_options_operation = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/options_operation.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.OptionsOperation = void 0; var error_1 = require_error(); var operation_1 = require_operation(); var OptionsOperation = class extends operation_1.AbstractOperation { constructor(collection, options) { super(options); this.options = options; this.collection = collection; } get commandName() { return "listCollections"; } async execute(server, session) { const coll = this.collection; const [collection] = await coll.s.db.listCollections({ name: coll.collectionName }, { ...this.options, nameOnly: false, readPreference: this.readPreference, session }).toArray(); if (collection == null || collection.options == null) { throw new error_1.MongoAPIError(`collection ${coll.namespace} not found`); } return collection.options; } }; exports2.OptionsOperation = OptionsOperation; } }); // netlify/functions/node_modules/mongodb/lib/operations/rename.js var require_rename = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/rename.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.RenameOperation = void 0; var collection_1 = require_collection(); var utils_1 = require_utils(); var command_1 = require_command(); var operation_1 = require_operation(); var RenameOperation = class extends command_1.CommandOperation { constructor(collection, newName, options) { super(collection, options); this.collection = collection; this.newName = newName; this.options = options; this.ns = new utils_1.MongoDBNamespace("admin", "$cmd"); } get commandName() { return "renameCollection"; } async execute(server, session, timeoutContext) { const renameCollection = this.collection.namespace; const toCollection = this.collection.s.namespace.withCollection(this.newName).toString(); const dropTarget = typeof this.options.dropTarget === "boolean" ? this.options.dropTarget : false; const command = { renameCollection, to: toCollection, dropTarget }; await super.executeCommand(server, session, command, timeoutContext); return new collection_1.Collection(this.collection.s.db, this.newName, this.collection.s.options); } }; exports2.RenameOperation = RenameOperation; (0, operation_1.defineAspects)(RenameOperation, [operation_1.Aspect.WRITE_OPERATION]); } }); // netlify/functions/node_modules/mongodb/lib/operations/search_indexes/create.js var require_create = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/search_indexes/create.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.CreateSearchIndexesOperation = void 0; var operation_1 = require_operation(); var CreateSearchIndexesOperation = class extends operation_1.AbstractOperation { constructor(collection, descriptions) { super(); this.collection = collection; this.descriptions = descriptions; } get commandName() { return "createSearchIndexes"; } async execute(server, session, timeoutContext) { const namespace = this.collection.fullNamespace; const command = { createSearchIndexes: namespace.collection, indexes: this.descriptions }; const res = await server.command(namespace, command, { session, timeoutContext }); const indexesCreated = res?.indexesCreated ?? []; return indexesCreated.map(({ name }) => name); } }; exports2.CreateSearchIndexesOperation = CreateSearchIndexesOperation; } }); // netlify/functions/node_modules/mongodb/lib/operations/search_indexes/drop.js var require_drop2 = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/search_indexes/drop.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.DropSearchIndexOperation = void 0; var error_1 = require_error(); var operation_1 = require_operation(); var DropSearchIndexOperation = class extends operation_1.AbstractOperation { constructor(collection, name) { super(); this.collection = collection; this.name = name; } get commandName() { return "dropSearchIndex"; } async execute(server, session, timeoutContext) { const namespace = this.collection.fullNamespace; const command = { dropSearchIndex: namespace.collection }; if (typeof this.name === "string") { command.name = this.name; } try { await server.command(namespace, command, { session, timeoutContext }); } catch (error) { const isNamespaceNotFoundError = error instanceof error_1.MongoServerError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound; if (!isNamespaceNotFoundError) { throw error; } } } }; exports2.DropSearchIndexOperation = DropSearchIndexOperation; } }); // netlify/functions/node_modules/mongodb/lib/operations/search_indexes/update.js var require_update = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/search_indexes/update.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.UpdateSearchIndexOperation = void 0; var operation_1 = require_operation(); var UpdateSearchIndexOperation = class extends operation_1.AbstractOperation { constructor(collection, name, definition) { super(); this.collection = collection; this.name = name; this.definition = definition; } get commandName() { return "updateSearchIndex"; } async execute(server, session, timeoutContext) { const namespace = this.collection.fullNamespace; const command = { updateSearchIndex: namespace.collection, name: this.name, definition: this.definition }; await server.command(namespace, command, { session, timeoutContext }); return; } }; exports2.UpdateSearchIndexOperation = UpdateSearchIndexOperation; } }); // netlify/functions/node_modules/mongodb/lib/operations/update.js var require_update2 = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/update.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ReplaceOneOperation = exports2.UpdateManyOperation = exports2.UpdateOneOperation = exports2.UpdateOperation = void 0; exports2.makeUpdateStatement = makeUpdateStatement; var error_1 = require_error(); var sort_1 = require_sort(); var utils_1 = require_utils(); var command_1 = require_command(); var operation_1 = require_operation(); var UpdateOperation = class extends command_1.CommandOperation { constructor(ns, statements, options) { super(void 0, options); this.options = options; this.ns = ns; this.statements = statements; } get commandName() { return "update"; } get canRetryWrite() { if (super.canRetryWrite === false) { return false; } return this.statements.every((op) => op.multi == null || op.multi === false); } async execute(server, session, timeoutContext) { const options = this.options ?? {}; const ordered = typeof options.ordered === "boolean" ? options.ordered : true; const command = { update: this.ns.collection, updates: this.statements, ordered }; if (typeof options.bypassDocumentValidation === "boolean") { command.bypassDocumentValidation = options.bypassDocumentValidation; } if (options.let) { command.let = options.let; } if (options.comment !== void 0) { command.comment = options.comment; } const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; if (unacknowledgedWrite) { if (this.statements.find((o) => o.hint)) { throw new error_1.MongoCompatibilityError(`hint is not supported with unacknowledged writes`); } } const res = await super.executeCommand(server, session, command, timeoutContext); return res; } }; exports2.UpdateOperation = UpdateOperation; var UpdateOneOperation = class extends UpdateOperation { constructor(collection, filter, update, options) { super(collection.s.namespace, [makeUpdateStatement(filter, update, { ...options, multi: false })], options); if (!(0, utils_1.hasAtomicOperators)(update, options)) { throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators"); } } async execute(server, session, timeoutContext) { const res = await super.execute(server, session, timeoutContext); if (this.explain != null) return res; if (res.code) throw new error_1.MongoServerError(res); if (res.writeErrors) throw new error_1.MongoServerError(res.writeErrors[0]); return { acknowledged: this.writeConcern?.w !== 0, modifiedCount: res.nModified ?? res.n, upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n }; } }; exports2.UpdateOneOperation = UpdateOneOperation; var UpdateManyOperation = class extends UpdateOperation { constructor(collection, filter, update, options) { super(collection.s.namespace, [makeUpdateStatement(filter, update, { ...options, multi: true })], options); if (!(0, utils_1.hasAtomicOperators)(update, options)) { throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators"); } } async execute(server, session, timeoutContext) { const res = await super.execute(server, session, timeoutContext); if (this.explain != null) return res; if (res.code) throw new error_1.MongoServerError(res); if (res.writeErrors) throw new error_1.MongoServerError(res.writeErrors[0]); return { acknowledged: this.writeConcern?.w !== 0, modifiedCount: res.nModified ?? res.n, upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n }; } }; exports2.UpdateManyOperation = UpdateManyOperation; var ReplaceOneOperation = class extends UpdateOperation { constructor(collection, filter, replacement, options) { super(collection.s.namespace, [makeUpdateStatement(filter, replacement, { ...options, multi: false })], options); if ((0, utils_1.hasAtomicOperators)(replacement)) { throw new error_1.MongoInvalidArgumentError("Replacement document must not contain atomic operators"); } } async execute(server, session, timeoutContext) { const res = await super.execute(server, session, timeoutContext); if (this.explain != null) return res; if (res.code) throw new error_1.MongoServerError(res); if (res.writeErrors) throw new error_1.MongoServerError(res.writeErrors[0]); return { acknowledged: this.writeConcern?.w !== 0, modifiedCount: res.nModified ?? res.n, upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n }; } }; exports2.ReplaceOneOperation = ReplaceOneOperation; function makeUpdateStatement(filter, update, options) { if (filter == null || typeof filter !== "object") { throw new error_1.MongoInvalidArgumentError("Selector must be a valid JavaScript object"); } if (update == null || typeof update !== "object") { throw new error_1.MongoInvalidArgumentError("Document must be a valid JavaScript object"); } const op = { q: filter, u: update }; if (typeof options.upsert === "boolean") { op.upsert = options.upsert; } if (options.multi) { op.multi = options.multi; } if (options.hint) { op.hint = options.hint; } if (options.arrayFilters) { op.arrayFilters = options.arrayFilters; } if (options.collation) { op.collation = options.collation; } if (!options.multi && options.sort != null) { op.sort = (0, sort_1.formatSort)(options.sort); } return op; } (0, operation_1.defineAspects)(UpdateOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION, operation_1.Aspect.SKIP_COLLATION]); (0, operation_1.defineAspects)(UpdateOneOperation, [ operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION, operation_1.Aspect.EXPLAINABLE, operation_1.Aspect.SKIP_COLLATION ]); (0, operation_1.defineAspects)(UpdateManyOperation, [ operation_1.Aspect.WRITE_OPERATION, operation_1.Aspect.EXPLAINABLE, operation_1.Aspect.SKIP_COLLATION ]); (0, operation_1.defineAspects)(ReplaceOneOperation, [ operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION, operation_1.Aspect.SKIP_COLLATION ]); } }); // netlify/functions/node_modules/mongodb/lib/collection.js var require_collection = __commonJS({ "netlify/functions/node_modules/mongodb/lib/collection.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.Collection = void 0; var bson_1 = require_bson2(); var ordered_1 = require_ordered(); var unordered_1 = require_unordered(); var change_stream_1 = require_change_stream(); var aggregation_cursor_1 = require_aggregation_cursor(); var find_cursor_1 = require_find_cursor(); var list_indexes_cursor_1 = require_list_indexes_cursor(); var list_search_indexes_cursor_1 = require_list_search_indexes_cursor(); var error_1 = require_error(); var bulk_write_1 = require_bulk_write(); var count_1 = require_count(); var delete_1 = require_delete(); var distinct_1 = require_distinct(); var drop_1 = require_drop(); var estimated_document_count_1 = require_estimated_document_count(); var execute_operation_1 = require_execute_operation(); var find_and_modify_1 = require_find_and_modify(); var indexes_1 = require_indexes(); var insert_1 = require_insert(); var is_capped_1 = require_is_capped(); var options_operation_1 = require_options_operation(); var rename_1 = require_rename(); var create_1 = require_create(); var drop_2 = require_drop2(); var update_1 = require_update(); var update_2 = require_update2(); var read_concern_1 = require_read_concern(); var read_preference_1 = require_read_preference(); var utils_1 = require_utils(); var write_concern_1 = require_write_concern(); var Collection = class { /** * Create a new Collection instance * @internal */ constructor(db, name, options) { this.s = { db, options, namespace: new utils_1.MongoDBCollectionNamespace(db.databaseName, name), pkFactory: db.options?.pkFactory ?? utils_1.DEFAULT_PK_FACTORY, readPreference: read_preference_1.ReadPreference.fromOptions(options), bsonOptions: (0, bson_1.resolveBSONOptions)(options, db), readConcern: read_concern_1.ReadConcern.fromOptions(options), writeConcern: write_concern_1.WriteConcern.fromOptions(options) }; this.client = db.client; } /** * The name of the database this collection belongs to */ get dbName() { return this.s.namespace.db; } /** * The name of this collection */ get collectionName() { return this.s.namespace.collection; } /** * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}` */ get namespace() { return this.fullNamespace.toString(); } /** * @internal * * The `MongoDBNamespace` for the collection. */ get fullNamespace() { return this.s.namespace; } /** * The current readConcern of the collection. If not explicitly defined for * this collection, will be inherited from the parent DB */ get readConcern() { if (this.s.readConcern == null) { return this.s.db.readConcern; } return this.s.readConcern; } /** * The current readPreference of the collection. If not explicitly defined for * this collection, will be inherited from the parent DB */ get readPreference() { if (this.s.readPreference == null) { return this.s.db.readPreference; } return this.s.readPreference; } get bsonOptions() { return this.s.bsonOptions; } /** * The current writeConcern of the collection. If not explicitly defined for * this collection, will be inherited from the parent DB */ get writeConcern() { if (this.s.writeConcern == null) { return this.s.db.writeConcern; } return this.s.writeConcern; } /** The current index hint for the collection */ get hint() { return this.s.collectionHint; } set hint(v) { this.s.collectionHint = (0, utils_1.normalizeHintField)(v); } get timeoutMS() { return this.s.options.timeoutMS; } /** * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, * one will be added to each of the documents missing it by the driver, mutating the document. This behavior * can be overridden by setting the **forceServerObjectId** flag. * * @param doc - The document to insert * @param options - Optional settings for the command */ async insertOne(doc, options) { return await (0, execute_operation_1.executeOperation)(this.client, new insert_1.InsertOneOperation(this, doc, (0, utils_1.resolveOptions)(this, options))); } /** * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, * one will be added to each of the documents missing it by the driver, mutating the document. This behavior * can be overridden by setting the **forceServerObjectId** flag. * * @param docs - The documents to insert * @param options - Optional settings for the command */ async insertMany(docs, options) { return await (0, execute_operation_1.executeOperation)(this.client, new insert_1.InsertManyOperation(this, docs, (0, utils_1.resolveOptions)(this, options ?? { ordered: true }))); } /** * Perform a bulkWrite operation without a fluent API * * Legal operation types are * - `insertOne` * - `replaceOne` * - `updateOne` * - `updateMany` * - `deleteOne` * - `deleteMany` * * If documents passed in do not contain the **_id** field, * one will be added to each of the documents missing it by the driver, mutating the document. This behavior * can be overridden by setting the **forceServerObjectId** flag. * * @param operations - Bulk operations to perform * @param options - Optional settings for the command * @throws MongoDriverError if operations is not an array */ async bulkWrite(operations, options) { if (!Array.isArray(operations)) { throw new error_1.MongoInvalidArgumentError('Argument "operations" must be an array of documents'); } return await (0, execute_operation_1.executeOperation)(this.client, new bulk_write_1.BulkWriteOperation(this, operations, (0, utils_1.resolveOptions)(this, options ?? { ordered: true }))); } /** * Update a single document in a collection * * The value of `update` can be either: * - UpdateFilter - A document that contains update operator expressions, * - Document[] - an aggregation pipeline. * * @param filter - The filter used to select the document to update * @param update - The modifications to apply * @param options - Optional settings for the command */ async updateOne(filter, update, options) { return await (0, execute_operation_1.executeOperation)(this.client, new update_2.UpdateOneOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options))); } /** * Replace a document in a collection with another document * * @param filter - The filter used to select the document to replace * @param replacement - The Document that replaces the matching document * @param options - Optional settings for the command */ async replaceOne(filter, replacement, options) { return await (0, execute_operation_1.executeOperation)(this.client, new update_2.ReplaceOneOperation(this, filter, replacement, (0, utils_1.resolveOptions)(this, options))); } /** * Update multiple documents in a collection * * The value of `update` can be either: * - UpdateFilter - A document that contains update operator expressions, * - Document[] - an aggregation pipeline. * * @param filter - The filter used to select the document to update * @param update - The modifications to apply * @param options - Optional settings for the command */ async updateMany(filter, update, options) { return await (0, execute_operation_1.executeOperation)(this.client, new update_2.UpdateManyOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options))); } /** * Delete a document from a collection * * @param filter - The filter used to select the document to remove * @param options - Optional settings for the command */ async deleteOne(filter = {}, options = {}) { return await (0, execute_operation_1.executeOperation)(this.client, new delete_1.DeleteOneOperation(this, filter, (0, utils_1.resolveOptions)(this, options))); } /** * Delete multiple documents from a collection * * @param filter - The filter used to select the documents to remove * @param options - Optional settings for the command */ async deleteMany(filter = {}, options = {}) { return await (0, execute_operation_1.executeOperation)(this.client, new delete_1.DeleteManyOperation(this, filter, (0, utils_1.resolveOptions)(this, options))); } /** * Rename the collection. * * @remarks * This operation does not inherit options from the Db or MongoClient. * * @param newName - New name of of the collection. * @param options - Optional settings for the command */ async rename(newName, options) { return await (0, execute_operation_1.executeOperation)(this.client, new rename_1.RenameOperation(this, newName, (0, utils_1.resolveOptions)(void 0, { ...options, readPreference: read_preference_1.ReadPreference.PRIMARY }))); } /** * Drop the collection from the database, removing it permanently. New accesses will create a new collection. * * @param options - Optional settings for the command */ async drop(options) { return await (0, execute_operation_1.executeOperation)(this.client, new drop_1.DropCollectionOperation(this.s.db, this.collectionName, options)); } async findOne(filter = {}, options = {}) { const cursor = this.find(filter, options).limit(-1).batchSize(1); const res = await cursor.next(); await cursor.close(); return res; } find(filter = {}, options = {}) { return new find_cursor_1.FindCursor(this.client, this.s.namespace, filter, (0, utils_1.resolveOptions)(this, options)); } /** * Returns the options of the collection. * * @param options - Optional settings for the command */ async options(options) { return await (0, execute_operation_1.executeOperation)(this.client, new options_operation_1.OptionsOperation(this, (0, utils_1.resolveOptions)(this, options))); } /** * Returns if the collection is a capped collection * * @param options - Optional settings for the command */ async isCapped(options) { return await (0, execute_operation_1.executeOperation)(this.client, new is_capped_1.IsCappedOperation(this, (0, utils_1.resolveOptions)(this, options))); } /** * Creates an index on the db and collection collection. * * @param indexSpec - The field name or index specification to create an index for * @param options - Optional settings for the command * * @example * ```ts * const collection = client.db('foo').collection('bar'); * * await collection.createIndex({ a: 1, b: -1 }); * * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes * await collection.createIndex([ [c, 1], [d, -1] ]); * * // Equivalent to { e: 1 } * await collection.createIndex('e'); * * // Equivalent to { f: 1, g: 1 } * await collection.createIndex(['f', 'g']) * * // Equivalent to { h: 1, i: -1 } * await collection.createIndex([ { h: 1 }, { i: -1 } ]); * * // Equivalent to { j: 1, k: -1, l: 2d } * await collection.createIndex(['j', ['k', -1], { l: '2d' }]) * ``` */ async createIndex(indexSpec, options) { const indexes = await (0, execute_operation_1.executeOperation)(this.client, indexes_1.CreateIndexesOperation.fromIndexSpecification(this, this.collectionName, indexSpec, (0, utils_1.resolveOptions)(this, options))); return indexes[0]; } /** * Creates multiple indexes in the collection, this method is only supported for * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported * error. * * **Note**: Unlike {@link Collection#createIndex| createIndex}, this function takes in raw index specifications. * Index specifications are defined {@link https://www.mongodb.com/docs/manual/reference/command/createIndexes/| here}. * * @param indexSpecs - An array of index specifications to be created * @param options - Optional settings for the command * * @example * ```ts * const collection = client.db('foo').collection('bar'); * await collection.createIndexes([ * // Simple index on field fizz * { * key: { fizz: 1 }, * } * // wildcard index * { * key: { '$**': 1 } * }, * // named index on darmok and jalad * { * key: { darmok: 1, jalad: -1 } * name: 'tanagra' * } * ]); * ``` */ async createIndexes(indexSpecs, options) { return await (0, execute_operation_1.executeOperation)(this.client, indexes_1.CreateIndexesOperation.fromIndexDescriptionArray(this, this.collectionName, indexSpecs, (0, utils_1.resolveOptions)(this, { ...options, maxTimeMS: void 0 }))); } /** * Drops an index from this collection. * * @param indexName - Name of the index to drop. * @param options - Optional settings for the command */ async dropIndex(indexName, options) { return await (0, execute_operation_1.executeOperation)(this.client, new indexes_1.DropIndexOperation(this, indexName, { ...(0, utils_1.resolveOptions)(this, options), readPreference: read_preference_1.ReadPreference.primary })); } /** * Drops all indexes from this collection. * * @param options - Optional settings for the command */ async dropIndexes(options) { try { await (0, execute_operation_1.executeOperation)(this.client, new indexes_1.DropIndexOperation(this, "*", (0, utils_1.resolveOptions)(this, options))); return true; } catch (error) { if (error instanceof error_1.MongoOperationTimeoutError) throw error; return false; } } /** * Get the list of all indexes information for the collection. * * @param options - Optional settings for the command */ listIndexes(options) { return new list_indexes_cursor_1.ListIndexesCursor(this, (0, utils_1.resolveOptions)(this, options)); } /** * Checks if one or more indexes exist on the collection, fails on first non-existing index * * @param indexes - One or more index names to check. * @param options - Optional settings for the command */ async indexExists(indexes, options) { const indexNames = Array.isArray(indexes) ? indexes : [indexes]; const allIndexes = new Set(await this.listIndexes(options).map(({ name }) => name).toArray()); return indexNames.every((name) => allIndexes.has(name)); } async indexInformation(options) { return await this.indexes({ ...options, full: options?.full ?? false }); } /** * Gets an estimate of the count of documents in a collection using collection metadata. * This will always run a count command on all server versions. * * due to an oversight in versions 5.0.0-5.0.8 of MongoDB, the count command, * which estimatedDocumentCount uses in its implementation, was not included in v1 of * the Stable API, and so users of the Stable API with estimatedDocumentCount are * recommended to upgrade their server version to 5.0.9+ or set apiStrict: false to avoid * encountering errors. * * @see {@link https://www.mongodb.com/docs/manual/reference/command/count/#behavior|Count: Behavior} * @param options - Optional settings for the command */ async estimatedDocumentCount(options) { return await (0, execute_operation_1.executeOperation)(this.client, new estimated_document_count_1.EstimatedDocumentCountOperation(this, (0, utils_1.resolveOptions)(this, options))); } /** * Gets the number of documents matching the filter. * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount| estimatedDocumentCount}. * * Due to countDocuments using the $match aggregation pipeline stage, certain query operators cannot be used in countDocuments. This includes the $where and $near query operators, among others. Details can be found in the documentation for the $match aggregation pipeline stage. * * **Note**: When migrating from {@link Collection#count| count} to {@link Collection#countDocuments| countDocuments} * the following query operators must be replaced: * * | Operator | Replacement | * | -------- | ----------- | * | `$where` | [`$expr`][1] | * | `$near` | [`$geoWithin`][2] with [`$center`][3] | * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] | * * [1]: https://www.mongodb.com/docs/manual/reference/operator/query/expr/ * [2]: https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/ * [3]: https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center * [4]: https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere * * @param filter - The filter for the count * @param options - Optional settings for the command * * @see https://www.mongodb.com/docs/manual/reference/operator/query/expr/ * @see https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/ * @see https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center * @see https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere */ async countDocuments(filter = {}, options = {}) { const pipeline = []; pipeline.push({ $match: filter }); if (typeof options.skip === "number") { pipeline.push({ $skip: options.skip }); } if (typeof options.limit === "number") { pipeline.push({ $limit: options.limit }); } pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } }); const cursor = this.aggregate(pipeline, options); const doc = await cursor.next(); await cursor.close(); return doc?.n ?? 0; } async distinct(key, filter = {}, options = {}) { return await (0, execute_operation_1.executeOperation)(this.client, new distinct_1.DistinctOperation(this, key, filter, (0, utils_1.resolveOptions)(this, options))); } async indexes(options) { const indexes = await this.listIndexes(options).toArray(); const full = options?.full ?? true; if (full) { return indexes; } const object = Object.fromEntries(indexes.map(({ name, key }) => [name, Object.entries(key)])); return object; } async findOneAndDelete(filter, options) { return await (0, execute_operation_1.executeOperation)(this.client, new find_and_modify_1.FindOneAndDeleteOperation(this, filter, (0, utils_1.resolveOptions)(this, options))); } async findOneAndReplace(filter, replacement, options) { return await (0, execute_operation_1.executeOperation)(this.client, new find_and_modify_1.FindOneAndReplaceOperation(this, filter, replacement, (0, utils_1.resolveOptions)(this, options))); } async findOneAndUpdate(filter, update, options) { return await (0, execute_operation_1.executeOperation)(this.client, new find_and_modify_1.FindOneAndUpdateOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options))); } /** * Execute an aggregation framework pipeline against the collection, needs MongoDB \>= 2.2 * * @param pipeline - An array of aggregation pipelines to execute * @param options - Optional settings for the command */ aggregate(pipeline = [], options) { if (!Array.isArray(pipeline)) { throw new error_1.MongoInvalidArgumentError('Argument "pipeline" must be an array of aggregation stages'); } return new aggregation_cursor_1.AggregationCursor(this.client, this.s.namespace, pipeline, (0, utils_1.resolveOptions)(this, options)); } /** * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. * * @remarks * watch() accepts two generic arguments for distinct use cases: * - The first is to override the schema that may be defined for this specific collection * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument * @example * By just providing the first argument I can type the change to be `ChangeStreamDocument<{ _id: number }>` * ```ts * collection.watch<{ _id: number }>() * .on('change', change => console.log(change._id.toFixed(4))); * ``` * * @example * Passing a second argument provides a way to reflect the type changes caused by an advanced pipeline. * Here, we are using a pipeline to have MongoDB filter for insert changes only and add a comment. * No need start from scratch on the ChangeStreamInsertDocument type! * By using an intersection we can save time and ensure defaults remain the same type! * ```ts * collection * .watch & { comment: string }>([ * { $addFields: { comment: 'big changes' } }, * { $match: { operationType: 'insert' } } * ]) * .on('change', change => { * change.comment.startsWith('big'); * change.operationType === 'insert'; * // No need to narrow in code because the generics did that for us! * expectType(change.fullDocument); * }); * ``` * * @remarks * When `timeoutMS` is configured for a change stream, it will have different behaviour depending * on whether the change stream is in iterator mode or emitter mode. In both cases, a change * stream will time out if it does not receive a change event within `timeoutMS` of the last change * event. * * Note that if a change stream is consistently timing out when watching a collection, database or * client that is being changed, then this may be due to the server timing out before it can finish * processing the existing oplog. To address this, restart the change stream with a higher * `timeoutMS`. * * If the change stream times out the initial aggregate operation to establish the change stream on * the server, then the client will close the change stream. If the getMore calls to the server * time out, then the change stream will be left open, but will throw a MongoOperationTimeoutError * when in iterator mode and emit an error event that returns a MongoOperationTimeoutError in * emitter mode. * * To determine whether or not the change stream is still open following a timeout, check the * {@link ChangeStream.closed} getter. * * @example * In iterator mode, if a next() call throws a timeout error, it will attempt to resume the change stream. * The next call can just be retried after this succeeds. * ```ts * const changeStream = collection.watch([], { timeoutMS: 100 }); * try { * await changeStream.next(); * } catch (e) { * if (e instanceof MongoOperationTimeoutError && !changeStream.closed) { * await changeStream.next(); * } * throw e; * } * ``` * * @example * In emitter mode, if the change stream goes `timeoutMS` without emitting a change event, it will * emit an error event that returns a MongoOperationTimeoutError, but will not close the change * stream unless the resume attempt fails. There is no need to re-establish change listeners as * this will automatically continue emitting change events once the resume attempt completes. * * ```ts * const changeStream = collection.watch([], { timeoutMS: 100 }); * changeStream.on('change', console.log); * changeStream.on('error', e => { * if (e instanceof MongoOperationTimeoutError && !changeStream.closed) { * // do nothing * } else { * changeStream.close(); * } * }); * ``` * * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. * @param options - Optional settings for the command * @typeParam TLocal - Type of the data being detected by the change stream * @typeParam TChange - Type of the whole change stream document emitted */ watch(pipeline = [], options = {}) { if (!Array.isArray(pipeline)) { options = pipeline; pipeline = []; } return new change_stream_1.ChangeStream(this, pipeline, (0, utils_1.resolveOptions)(this, options)); } /** * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. * * @throws MongoNotConnectedError * @remarks * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation. * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting. */ initializeUnorderedBulkOp(options) { return new unordered_1.UnorderedBulkOperation(this, (0, utils_1.resolveOptions)(this, options)); } /** * Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types. * * @throws MongoNotConnectedError * @remarks * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation. * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting. */ initializeOrderedBulkOp(options) { return new ordered_1.OrderedBulkOperation(this, (0, utils_1.resolveOptions)(this, options)); } /** * An estimated count of matching documents in the db to a filter. * * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments| countDocuments}. * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount| estimatedDocumentCount}. * * @deprecated use {@link Collection#countDocuments| countDocuments} or {@link Collection#estimatedDocumentCount| estimatedDocumentCount} instead * * @param filter - The filter for the count. * @param options - Optional settings for the command */ async count(filter = {}, options = {}) { return await (0, execute_operation_1.executeOperation)(this.client, new count_1.CountOperation(this.fullNamespace, filter, (0, utils_1.resolveOptions)(this, options))); } listSearchIndexes(indexNameOrOptions, options) { options = typeof indexNameOrOptions === "object" ? indexNameOrOptions : options == null ? {} : options; const indexName = indexNameOrOptions == null ? null : typeof indexNameOrOptions === "object" ? null : indexNameOrOptions; return new list_search_indexes_cursor_1.ListSearchIndexesCursor(this, indexName, options); } /** * Creates a single search index for the collection. * * @param description - The index description for the new search index. * @returns A promise that resolves to the name of the new search index. * * @remarks Only available when used against a 7.0+ Atlas cluster. */ async createSearchIndex(description) { const [index] = await this.createSearchIndexes([description]); return index; } /** * Creates multiple search indexes for the current collection. * * @param descriptions - An array of `SearchIndexDescription`s for the new search indexes. * @returns A promise that resolves to an array of the newly created search index names. * * @remarks Only available when used against a 7.0+ Atlas cluster. * @returns */ async createSearchIndexes(descriptions) { return await (0, execute_operation_1.executeOperation)(this.client, new create_1.CreateSearchIndexesOperation(this, descriptions)); } /** * Deletes a search index by index name. * * @param name - The name of the search index to be deleted. * * @remarks Only available when used against a 7.0+ Atlas cluster. */ async dropSearchIndex(name) { return await (0, execute_operation_1.executeOperation)(this.client, new drop_2.DropSearchIndexOperation(this, name)); } /** * Updates a search index by replacing the existing index definition with the provided definition. * * @param name - The name of the search index to update. * @param definition - The new search index definition. * * @remarks Only available when used against a 7.0+ Atlas cluster. */ async updateSearchIndex(name, definition) { return await (0, execute_operation_1.executeOperation)(this.client, new update_1.UpdateSearchIndexOperation(this, name, definition)); } }; exports2.Collection = Collection; } }); // netlify/functions/node_modules/mongodb/lib/cursor/change_stream_cursor.js var require_change_stream_cursor = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cursor/change_stream_cursor.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ChangeStreamCursor = void 0; var change_stream_1 = require_change_stream(); var constants_1 = require_constants(); var aggregate_1 = require_aggregate(); var execute_operation_1 = require_execute_operation(); var utils_1 = require_utils(); var abstract_cursor_1 = require_abstract_cursor(); var ChangeStreamCursor = class _ChangeStreamCursor extends abstract_cursor_1.AbstractCursor { constructor(client, namespace, pipeline = [], options = {}) { super(client, namespace, { ...options, tailable: true, awaitData: true }); this.pipeline = pipeline; this.changeStreamCursorOptions = options; this._resumeToken = null; this.startAtOperationTime = options.startAtOperationTime ?? null; if (options.startAfter) { this.resumeToken = options.startAfter; } else if (options.resumeAfter) { this.resumeToken = options.resumeAfter; } } set resumeToken(token) { this._resumeToken = token; this.emit(change_stream_1.ChangeStream.RESUME_TOKEN_CHANGED, token); } get resumeToken() { return this._resumeToken; } get resumeOptions() { const options = { ...this.changeStreamCursorOptions }; for (const key of ["resumeAfter", "startAfter", "startAtOperationTime"]) { delete options[key]; } if (this.resumeToken != null) { if (this.changeStreamCursorOptions.startAfter && !this.hasReceived) { options.startAfter = this.resumeToken; } else { options.resumeAfter = this.resumeToken; } } else if (this.startAtOperationTime != null && (0, utils_1.maxWireVersion)(this.server) >= 7) { options.startAtOperationTime = this.startAtOperationTime; } return options; } cacheResumeToken(resumeToken) { if (this.bufferedCount() === 0 && this.postBatchResumeToken) { this.resumeToken = this.postBatchResumeToken; } else { this.resumeToken = resumeToken; } this.hasReceived = true; } _processBatch(response) { const { postBatchResumeToken } = response; if (postBatchResumeToken) { this.postBatchResumeToken = postBatchResumeToken; if (response.batchSize === 0) { this.resumeToken = postBatchResumeToken; } } } clone() { return new _ChangeStreamCursor(this.client, this.namespace, this.pipeline, { ...this.cursorOptions }); } async _initialize(session) { const aggregateOperation = new aggregate_1.AggregateOperation(this.namespace, this.pipeline, { ...this.cursorOptions, ...this.changeStreamCursorOptions, session }); const response = await (0, execute_operation_1.executeOperation)(session.client, aggregateOperation, this.timeoutContext); const server = aggregateOperation.server; this.maxWireVersion = (0, utils_1.maxWireVersion)(server); if (this.startAtOperationTime == null && this.changeStreamCursorOptions.resumeAfter == null && this.changeStreamCursorOptions.startAfter == null && this.maxWireVersion >= 7) { this.startAtOperationTime = response.operationTime; } this._processBatch(response); this.emit(constants_1.INIT, response); this.emit(constants_1.RESPONSE); return { server, session, response }; } async getMore(batchSize) { const response = await super.getMore(batchSize); this.maxWireVersion = (0, utils_1.maxWireVersion)(this.server); this._processBatch(response); this.emit(change_stream_1.ChangeStream.MORE, response); this.emit(change_stream_1.ChangeStream.RESPONSE); return response; } }; exports2.ChangeStreamCursor = ChangeStreamCursor; } }); // netlify/functions/node_modules/mongodb/lib/operations/list_databases.js var require_list_databases = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/list_databases.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ListDatabasesOperation = void 0; var utils_1 = require_utils(); var command_1 = require_command(); var operation_1 = require_operation(); var ListDatabasesOperation = class extends command_1.CommandOperation { constructor(db, options) { super(db, options); this.options = options ?? {}; this.ns = new utils_1.MongoDBNamespace("admin", "$cmd"); } get commandName() { return "listDatabases"; } async execute(server, session, timeoutContext) { const cmd = { listDatabases: 1 }; if (typeof this.options.nameOnly === "boolean") { cmd.nameOnly = this.options.nameOnly; } if (this.options.filter) { cmd.filter = this.options.filter; } if (typeof this.options.authorizedDatabases === "boolean") { cmd.authorizedDatabases = this.options.authorizedDatabases; } if ((0, utils_1.maxWireVersion)(server) >= 9 && this.options.comment !== void 0) { cmd.comment = this.options.comment; } return await super.executeCommand(server, session, cmd, timeoutContext); } }; exports2.ListDatabasesOperation = ListDatabasesOperation; (0, operation_1.defineAspects)(ListDatabasesOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE]); } }); // netlify/functions/node_modules/mongodb/lib/operations/remove_user.js var require_remove_user = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/remove_user.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.RemoveUserOperation = void 0; var command_1 = require_command(); var operation_1 = require_operation(); var RemoveUserOperation = class extends command_1.CommandOperation { constructor(db, username, options) { super(db, options); this.options = options; this.username = username; } get commandName() { return "dropUser"; } async execute(server, session, timeoutContext) { await super.executeCommand(server, session, { dropUser: this.username }, timeoutContext); return true; } }; exports2.RemoveUserOperation = RemoveUserOperation; (0, operation_1.defineAspects)(RemoveUserOperation, [operation_1.Aspect.WRITE_OPERATION]); } }); // netlify/functions/node_modules/mongodb/lib/operations/run_command.js var require_run_command = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/run_command.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.RunAdminCommandOperation = exports2.RunCommandOperation = void 0; var utils_1 = require_utils(); var operation_1 = require_operation(); var RunCommandOperation = class extends operation_1.AbstractOperation { constructor(parent, command, options) { super(options); this.command = command; this.options = options; this.ns = parent.s.namespace.withCollection("$cmd"); } get commandName() { return "runCommand"; } async execute(server, session, timeoutContext) { this.server = server; const res = await server.command(this.ns, this.command, { ...this.options, readPreference: this.readPreference, session, timeoutContext }, this.options.responseType); return res; } }; exports2.RunCommandOperation = RunCommandOperation; var RunAdminCommandOperation = class extends operation_1.AbstractOperation { constructor(command, options) { super(options); this.command = command; this.options = options; this.ns = new utils_1.MongoDBNamespace("admin", "$cmd"); } get commandName() { return "runCommand"; } async execute(server, session, timeoutContext) { this.server = server; const res = await server.command(this.ns, this.command, { ...this.options, readPreference: this.readPreference, session, timeoutContext }); return res; } }; exports2.RunAdminCommandOperation = RunAdminCommandOperation; } }); // netlify/functions/node_modules/mongodb/lib/operations/validate_collection.js var require_validate_collection = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/validate_collection.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ValidateCollectionOperation = void 0; var error_1 = require_error(); var command_1 = require_command(); var ValidateCollectionOperation = class extends command_1.CommandOperation { constructor(admin, collectionName, options) { const command = { validate: collectionName }; const keys = Object.keys(options); for (let i = 0; i < keys.length; i++) { if (Object.prototype.hasOwnProperty.call(options, keys[i]) && keys[i] !== "session") { command[keys[i]] = options[keys[i]]; } } super(admin.s.db, options); this.options = options; this.command = command; this.collectionName = collectionName; } get commandName() { return "validate"; } async execute(server, session, timeoutContext) { const collectionName = this.collectionName; const doc = await super.executeCommand(server, session, this.command, timeoutContext); if (doc.result != null && typeof doc.result !== "string") throw new error_1.MongoUnexpectedServerResponseError("Error with validation data"); if (doc.result != null && doc.result.match(/exception|corrupt/) != null) throw new error_1.MongoUnexpectedServerResponseError(`Invalid collection ${collectionName}`); if (doc.valid != null && !doc.valid) throw new error_1.MongoUnexpectedServerResponseError(`Invalid collection ${collectionName}`); return doc; } }; exports2.ValidateCollectionOperation = ValidateCollectionOperation; } }); // netlify/functions/node_modules/mongodb/lib/admin.js var require_admin = __commonJS({ "netlify/functions/node_modules/mongodb/lib/admin.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.Admin = void 0; var bson_1 = require_bson2(); var execute_operation_1 = require_execute_operation(); var list_databases_1 = require_list_databases(); var remove_user_1 = require_remove_user(); var run_command_1 = require_run_command(); var validate_collection_1 = require_validate_collection(); var Admin = class { /** * Create a new Admin instance * @internal */ constructor(db) { this.s = { db }; } /** * Execute a command * * The driver will ensure the following fields are attached to the command sent to the server: * - `lsid` - sourced from an implicit session or options.session * - `$readPreference` - defaults to primary or can be configured by options.readPreference * - `$db` - sourced from the name of this database * * If the client has a serverApi setting: * - `apiVersion` * - `apiStrict` * - `apiDeprecationErrors` * * When in a transaction: * - `readConcern` - sourced from readConcern set on the TransactionOptions * - `writeConcern` - sourced from writeConcern set on the TransactionOptions * * Attaching any of the above fields to the command will have no effect as the driver will overwrite the value. * * @param command - The command to execute * @param options - Optional settings for the command */ async command(command, options) { return await (0, execute_operation_1.executeOperation)(this.s.db.client, new run_command_1.RunAdminCommandOperation(command, { ...(0, bson_1.resolveBSONOptions)(options), session: options?.session, readPreference: options?.readPreference, timeoutMS: options?.timeoutMS ?? this.s.db.timeoutMS })); } /** * Retrieve the server build information * * @param options - Optional settings for the command */ async buildInfo(options) { return await this.command({ buildinfo: 1 }, options); } /** * Retrieve the server build information * * @param options - Optional settings for the command */ async serverInfo(options) { return await this.command({ buildinfo: 1 }, options); } /** * Retrieve this db's server status. * * @param options - Optional settings for the command */ async serverStatus(options) { return await this.command({ serverStatus: 1 }, options); } /** * Ping the MongoDB server and retrieve results * * @param options - Optional settings for the command */ async ping(options) { return await this.command({ ping: 1 }, options); } /** * Remove a user from a database * * @param username - The username to remove * @param options - Optional settings for the command */ async removeUser(username, options) { return await (0, execute_operation_1.executeOperation)(this.s.db.client, new remove_user_1.RemoveUserOperation(this.s.db, username, { dbName: "admin", ...options })); } /** * Validate an existing collection * * @param collectionName - The name of the collection to validate. * @param options - Optional settings for the command */ async validateCollection(collectionName, options = {}) { return await (0, execute_operation_1.executeOperation)(this.s.db.client, new validate_collection_1.ValidateCollectionOperation(this, collectionName, options)); } /** * List the available databases * * @param options - Optional settings for the command */ async listDatabases(options) { return await (0, execute_operation_1.executeOperation)(this.s.db.client, new list_databases_1.ListDatabasesOperation(this.s.db, { timeoutMS: this.s.db.timeoutMS, ...options })); } /** * Get ReplicaSet status * * @param options - Optional settings for the command */ async replSetGetStatus(options) { return await this.command({ replSetGetStatus: 1 }, options); } }; exports2.Admin = Admin; } }); // netlify/functions/node_modules/mongodb/lib/operations/list_collections.js var require_list_collections = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/list_collections.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ListCollectionsOperation = void 0; var responses_1 = require_responses(); var utils_1 = require_utils(); var command_1 = require_command(); var operation_1 = require_operation(); var ListCollectionsOperation = class extends command_1.CommandOperation { constructor(db, filter, options) { super(db, options); this.options = { ...options }; delete this.options.writeConcern; this.db = db; this.filter = filter; this.nameOnly = !!this.options.nameOnly; this.authorizedCollections = !!this.options.authorizedCollections; if (typeof this.options.batchSize === "number") { this.batchSize = this.options.batchSize; } } get commandName() { return "listCollections"; } async execute(server, session, timeoutContext) { return await super.executeCommand(server, session, this.generateCommand((0, utils_1.maxWireVersion)(server)), timeoutContext, responses_1.CursorResponse); } /* This is here for the purpose of unit testing the final command that gets sent. */ generateCommand(wireVersion) { const command = { listCollections: 1, filter: this.filter, cursor: this.batchSize ? { batchSize: this.batchSize } : {}, nameOnly: this.nameOnly, authorizedCollections: this.authorizedCollections }; if (wireVersion >= 9 && this.options.comment !== void 0) { command.comment = this.options.comment; } return command; } }; exports2.ListCollectionsOperation = ListCollectionsOperation; (0, operation_1.defineAspects)(ListCollectionsOperation, [ operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE, operation_1.Aspect.CURSOR_CREATING ]); } }); // netlify/functions/node_modules/mongodb/lib/cursor/list_collections_cursor.js var require_list_collections_cursor = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cursor/list_collections_cursor.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ListCollectionsCursor = void 0; var execute_operation_1 = require_execute_operation(); var list_collections_1 = require_list_collections(); var abstract_cursor_1 = require_abstract_cursor(); var ListCollectionsCursor = class _ListCollectionsCursor extends abstract_cursor_1.AbstractCursor { constructor(db, filter, options) { super(db.client, db.s.namespace, options); this.parent = db; this.filter = filter; this.options = options; } clone() { return new _ListCollectionsCursor(this.parent, this.filter, { ...this.options, ...this.cursorOptions }); } /** @internal */ async _initialize(session) { const operation = new list_collections_1.ListCollectionsOperation(this.parent, this.filter, { ...this.cursorOptions, ...this.options, session, signal: this.signal }); const response = await (0, execute_operation_1.executeOperation)(this.parent.client, operation, this.timeoutContext); return { server: operation.server, session, response }; } }; exports2.ListCollectionsCursor = ListCollectionsCursor; } }); // netlify/functions/node_modules/mongodb/lib/cursor/run_command_cursor.js var require_run_command_cursor = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cursor/run_command_cursor.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.RunCommandCursor = void 0; var responses_1 = require_responses(); var error_1 = require_error(); var execute_operation_1 = require_execute_operation(); var get_more_1 = require_get_more(); var run_command_1 = require_run_command(); var utils_1 = require_utils(); var abstract_cursor_1 = require_abstract_cursor(); var RunCommandCursor = class extends abstract_cursor_1.AbstractCursor { /** * Controls the `getMore.comment` field * @param comment - any BSON value */ setComment(comment) { this.getMoreOptions.comment = comment; return this; } /** * Controls the `getMore.maxTimeMS` field. Only valid when cursor is tailable await * @param maxTimeMS - the number of milliseconds to wait for new data */ setMaxTimeMS(maxTimeMS) { this.getMoreOptions.maxAwaitTimeMS = maxTimeMS; return this; } /** * Controls the `getMore.batchSize` field * @param batchSize - the number documents to return in the `nextBatch` */ setBatchSize(batchSize) { this.getMoreOptions.batchSize = batchSize; return this; } /** Unsupported for RunCommandCursor */ clone() { throw new error_1.MongoAPIError("Clone not supported, create a new cursor with db.runCursorCommand"); } /** Unsupported for RunCommandCursor: readConcern must be configured directly on command document */ withReadConcern(_) { throw new error_1.MongoAPIError("RunCommandCursor does not support readConcern it must be attached to the command being run"); } /** Unsupported for RunCommandCursor: various cursor flags must be configured directly on command document */ addCursorFlag(_, __) { throw new error_1.MongoAPIError("RunCommandCursor does not support cursor flags, they must be attached to the command being run"); } /** * Unsupported for RunCommandCursor: maxTimeMS must be configured directly on command document */ maxTimeMS(_) { throw new error_1.MongoAPIError("maxTimeMS must be configured on the command document directly, to configure getMore.maxTimeMS use cursor.setMaxTimeMS()"); } /** Unsupported for RunCommandCursor: batchSize must be configured directly on command document */ batchSize(_) { throw new error_1.MongoAPIError("batchSize must be configured on the command document directly, to configure getMore.batchSize use cursor.setBatchSize()"); } /** @internal */ constructor(db, command, options = {}) { super(db.client, (0, utils_1.ns)(db.namespace), options); this.getMoreOptions = {}; this.db = db; this.command = Object.freeze({ ...command }); } /** @internal */ async _initialize(session) { const operation = new run_command_1.RunCommandOperation(this.db, this.command, { ...this.cursorOptions, session, readPreference: this.cursorOptions.readPreference, responseType: responses_1.CursorResponse }); const response = await (0, execute_operation_1.executeOperation)(this.client, operation, this.timeoutContext); return { server: operation.server, session, response }; } /** @internal */ async getMore(_batchSize) { if (!this.session) { throw new error_1.MongoRuntimeError("Unexpected null session. A cursor creating command should have set this"); } const getMoreOperation = new get_more_1.GetMoreOperation(this.namespace, this.id, this.server, { ...this.cursorOptions, session: this.session, ...this.getMoreOptions }); return await (0, execute_operation_1.executeOperation)(this.client, getMoreOperation, this.timeoutContext); } }; exports2.RunCommandCursor = RunCommandCursor; } }); // netlify/functions/node_modules/mongodb/lib/operations/collections.js var require_collections = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/collections.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.CollectionsOperation = void 0; var collection_1 = require_collection(); var operation_1 = require_operation(); var CollectionsOperation = class extends operation_1.AbstractOperation { constructor(db, options) { super(options); this.options = options; this.db = db; } get commandName() { return "listCollections"; } async execute(server, session) { const documents = await this.db.listCollections({}, { ...this.options, nameOnly: true, readPreference: this.readPreference, session }).toArray(); const collections = []; for (const { name } of documents) { if (!name.includes("$")) { collections.push(new collection_1.Collection(this.db, name, this.db.s.options)); } } return collections; } }; exports2.CollectionsOperation = CollectionsOperation; } }); // netlify/functions/node_modules/mongodb/lib/operations/create_collection.js var require_create_collection = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/create_collection.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.CreateCollectionOperation = void 0; var constants_1 = require_constants2(); var collection_1 = require_collection(); var error_1 = require_error(); var command_1 = require_command(); var indexes_1 = require_indexes(); var operation_1 = require_operation(); var ILLEGAL_COMMAND_FIELDS = /* @__PURE__ */ new Set([ "w", "wtimeout", "timeoutMS", "j", "fsync", "autoIndexId", "pkFactory", "raw", "readPreference", "session", "readConcern", "writeConcern", "raw", "fieldsAsRaw", "useBigInt64", "promoteLongs", "promoteValues", "promoteBuffers", "bsonRegExp", "serializeFunctions", "ignoreUndefined", "enableUtf8Validation" ]); var INVALID_QE_VERSION = "Driver support of Queryable Encryption is incompatible with server. Upgrade server to use Queryable Encryption."; var CreateCollectionOperation = class _CreateCollectionOperation extends command_1.CommandOperation { constructor(db, name, options = {}) { super(db, options); this.options = options; this.db = db; this.name = name; } get commandName() { return "create"; } async execute(server, session, timeoutContext) { const db = this.db; const name = this.name; const options = this.options; const encryptedFields = options.encryptedFields ?? db.client.s.options.autoEncryption?.encryptedFieldsMap?.[`${db.databaseName}.${name}`]; if (encryptedFields) { if (!server.loadBalanced && server.description.maxWireVersion < constants_1.MIN_SUPPORTED_QE_WIRE_VERSION) { throw new error_1.MongoCompatibilityError(`${INVALID_QE_VERSION} The minimum server version required is ${constants_1.MIN_SUPPORTED_QE_SERVER_VERSION}`); } const escCollection = encryptedFields.escCollection ?? `enxcol_.${name}.esc`; const ecocCollection = encryptedFields.ecocCollection ?? `enxcol_.${name}.ecoc`; for (const collectionName of [escCollection, ecocCollection]) { const createOp = new _CreateCollectionOperation(db, collectionName, { clusteredIndex: { key: { _id: 1 }, unique: true } }); await createOp.executeWithoutEncryptedFieldsCheck(server, session, timeoutContext); } if (!options.encryptedFields) { this.options = { ...this.options, encryptedFields }; } } const coll = await this.executeWithoutEncryptedFieldsCheck(server, session, timeoutContext); if (encryptedFields) { const createIndexOp = indexes_1.CreateIndexesOperation.fromIndexSpecification(db, name, { __safeContent__: 1 }, {}); await createIndexOp.execute(server, session, timeoutContext); } return coll; } async executeWithoutEncryptedFieldsCheck(server, session, timeoutContext) { const db = this.db; const name = this.name; const options = this.options; const cmd = { create: name }; for (const n in options) { if (options[n] != null && typeof options[n] !== "function" && !ILLEGAL_COMMAND_FIELDS.has(n)) { cmd[n] = options[n]; } } await super.executeCommand(server, session, cmd, timeoutContext); return new collection_1.Collection(db, name, options); } }; exports2.CreateCollectionOperation = CreateCollectionOperation; (0, operation_1.defineAspects)(CreateCollectionOperation, [operation_1.Aspect.WRITE_OPERATION]); } }); // netlify/functions/node_modules/mongodb/lib/operations/profiling_level.js var require_profiling_level = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/profiling_level.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ProfilingLevelOperation = void 0; var error_1 = require_error(); var command_1 = require_command(); var ProfilingLevelOperation = class extends command_1.CommandOperation { constructor(db, options) { super(db, options); this.options = options; } get commandName() { return "profile"; } async execute(server, session, timeoutContext) { const doc = await super.executeCommand(server, session, { profile: -1 }, timeoutContext); if (doc.ok === 1) { const was = doc.was; if (was === 0) return "off"; if (was === 1) return "slow_only"; if (was === 2) return "all"; throw new error_1.MongoUnexpectedServerResponseError(`Illegal profiling level value ${was}`); } else { throw new error_1.MongoUnexpectedServerResponseError("Error with profile command"); } } }; exports2.ProfilingLevelOperation = ProfilingLevelOperation; } }); // netlify/functions/node_modules/mongodb/lib/operations/set_profiling_level.js var require_set_profiling_level = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/set_profiling_level.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.SetProfilingLevelOperation = exports2.ProfilingLevel = void 0; var error_1 = require_error(); var utils_1 = require_utils(); var command_1 = require_command(); var levelValues = /* @__PURE__ */ new Set(["off", "slow_only", "all"]); exports2.ProfilingLevel = Object.freeze({ off: "off", slowOnly: "slow_only", all: "all" }); var SetProfilingLevelOperation = class extends command_1.CommandOperation { constructor(db, level, options) { super(db, options); this.options = options; switch (level) { case exports2.ProfilingLevel.off: this.profile = 0; break; case exports2.ProfilingLevel.slowOnly: this.profile = 1; break; case exports2.ProfilingLevel.all: this.profile = 2; break; default: this.profile = 0; break; } this.level = level; } get commandName() { return "profile"; } async execute(server, session, timeoutContext) { const level = this.level; if (!levelValues.has(level)) { throw new error_1.MongoInvalidArgumentError(`Profiling level must be one of "${(0, utils_1.enumToString)(exports2.ProfilingLevel)}"`); } await super.executeCommand(server, session, { profile: this.profile }, timeoutContext); return level; } }; exports2.SetProfilingLevelOperation = SetProfilingLevelOperation; } }); // netlify/functions/node_modules/mongodb/lib/operations/stats.js var require_stats = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/stats.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.DbStatsOperation = void 0; var command_1 = require_command(); var operation_1 = require_operation(); var DbStatsOperation = class extends command_1.CommandOperation { constructor(db, options) { super(db, options); this.options = options; } get commandName() { return "dbStats"; } async execute(server, session, timeoutContext) { const command = { dbStats: true }; if (this.options.scale != null) { command.scale = this.options.scale; } return await super.executeCommand(server, session, command, timeoutContext); } }; exports2.DbStatsOperation = DbStatsOperation; (0, operation_1.defineAspects)(DbStatsOperation, [operation_1.Aspect.READ_OPERATION]); } }); // netlify/functions/node_modules/mongodb/lib/db.js var require_db = __commonJS({ "netlify/functions/node_modules/mongodb/lib/db.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.Db = void 0; var admin_1 = require_admin(); var bson_1 = require_bson2(); var change_stream_1 = require_change_stream(); var collection_1 = require_collection(); var CONSTANTS = require_constants(); var aggregation_cursor_1 = require_aggregation_cursor(); var list_collections_cursor_1 = require_list_collections_cursor(); var run_command_cursor_1 = require_run_command_cursor(); var error_1 = require_error(); var collections_1 = require_collections(); var create_collection_1 = require_create_collection(); var drop_1 = require_drop(); var execute_operation_1 = require_execute_operation(); var indexes_1 = require_indexes(); var profiling_level_1 = require_profiling_level(); var remove_user_1 = require_remove_user(); var rename_1 = require_rename(); var run_command_1 = require_run_command(); var set_profiling_level_1 = require_set_profiling_level(); var stats_1 = require_stats(); var read_concern_1 = require_read_concern(); var read_preference_1 = require_read_preference(); var utils_1 = require_utils(); var write_concern_1 = require_write_concern(); var DB_OPTIONS_ALLOW_LIST = [ "writeConcern", "readPreference", "readPreferenceTags", "native_parser", "forceServerObjectId", "pkFactory", "serializeFunctions", "raw", "authSource", "ignoreUndefined", "readConcern", "retryMiliSeconds", "numberOfRetries", "useBigInt64", "promoteBuffers", "promoteLongs", "bsonRegExp", "enableUtf8Validation", "promoteValues", "compression", "retryWrites", "timeoutMS" ]; var Db = class { /** * Creates a new Db instance. * * Db name cannot contain a dot, the server may apply more restrictions when an operation is run. * * @param client - The MongoClient for the database. * @param databaseName - The name of the database this instance represents. * @param options - Optional settings for Db construction. */ constructor(client, databaseName, options) { options = options ?? {}; options = (0, utils_1.filterOptions)(options, DB_OPTIONS_ALLOW_LIST); if (typeof databaseName === "string" && databaseName.includes(".")) { throw new error_1.MongoInvalidArgumentError(`Database names cannot contain the character '.'`); } this.s = { // Options options, // Unpack read preference readPreference: read_preference_1.ReadPreference.fromOptions(options), // Merge bson options bsonOptions: (0, bson_1.resolveBSONOptions)(options, client), // Set up the primary key factory or fallback to ObjectId pkFactory: options?.pkFactory ?? utils_1.DEFAULT_PK_FACTORY, // ReadConcern readConcern: read_concern_1.ReadConcern.fromOptions(options), writeConcern: write_concern_1.WriteConcern.fromOptions(options), // Namespace namespace: new utils_1.MongoDBNamespace(databaseName) }; this.client = client; } get databaseName() { return this.s.namespace.db; } // Options get options() { return this.s.options; } /** * Check if a secondary can be used (because the read preference is *not* set to primary) */ get secondaryOk() { return this.s.readPreference?.preference !== "primary" || false; } get readConcern() { return this.s.readConcern; } /** * The current readPreference of the Db. If not explicitly defined for * this Db, will be inherited from the parent MongoClient */ get readPreference() { if (this.s.readPreference == null) { return this.client.readPreference; } return this.s.readPreference; } get bsonOptions() { return this.s.bsonOptions; } // get the write Concern get writeConcern() { return this.s.writeConcern; } get namespace() { return this.s.namespace.toString(); } get timeoutMS() { return this.s.options?.timeoutMS; } /** * Create a new collection on a server with the specified options. Use this to create capped collections. * More information about command options available at https://www.mongodb.com/docs/manual/reference/command/create/ * * Collection namespace validation is performed server-side. * * @param name - The name of the collection to create * @param options - Optional settings for the command */ async createCollection(name, options) { return await (0, execute_operation_1.executeOperation)(this.client, new create_collection_1.CreateCollectionOperation(this, name, (0, utils_1.resolveOptions)(this, options))); } /** * Execute a command * * @remarks * This command does not inherit options from the MongoClient. * * The driver will ensure the following fields are attached to the command sent to the server: * - `lsid` - sourced from an implicit session or options.session * - `$readPreference` - defaults to primary or can be configured by options.readPreference * - `$db` - sourced from the name of this database * * If the client has a serverApi setting: * - `apiVersion` * - `apiStrict` * - `apiDeprecationErrors` * * When in a transaction: * - `readConcern` - sourced from readConcern set on the TransactionOptions * - `writeConcern` - sourced from writeConcern set on the TransactionOptions * * Attaching any of the above fields to the command will have no effect as the driver will overwrite the value. * * @param command - The command to run * @param options - Optional settings for the command */ async command(command, options) { return await (0, execute_operation_1.executeOperation)(this.client, new run_command_1.RunCommandOperation(this, command, (0, utils_1.resolveOptions)(void 0, { ...(0, bson_1.resolveBSONOptions)(options), timeoutMS: options?.timeoutMS ?? this.timeoutMS, session: options?.session, readPreference: options?.readPreference, signal: options?.signal }))); } /** * Execute an aggregation framework pipeline against the database. * * @param pipeline - An array of aggregation stages to be executed * @param options - Optional settings for the command */ aggregate(pipeline = [], options) { return new aggregation_cursor_1.AggregationCursor(this.client, this.s.namespace, pipeline, (0, utils_1.resolveOptions)(this, options)); } /** Return the Admin db instance */ admin() { return new admin_1.Admin(this); } /** * Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly. * * Collection namespace validation is performed server-side. * * @param name - the collection name we wish to access. * @returns return the new Collection instance */ collection(name, options = {}) { if (typeof options === "function") { throw new error_1.MongoInvalidArgumentError("The callback form of this helper has been removed."); } return new collection_1.Collection(this, name, (0, utils_1.resolveOptions)(this, options)); } /** * Get all the db statistics. * * @param options - Optional settings for the command */ async stats(options) { return await (0, execute_operation_1.executeOperation)(this.client, new stats_1.DbStatsOperation(this, (0, utils_1.resolveOptions)(this, options))); } listCollections(filter = {}, options = {}) { return new list_collections_cursor_1.ListCollectionsCursor(this, filter, (0, utils_1.resolveOptions)(this, options)); } /** * Rename a collection. * * @remarks * This operation does not inherit options from the MongoClient. * * @param fromCollection - Name of current collection to rename * @param toCollection - New name of of the collection * @param options - Optional settings for the command */ async renameCollection(fromCollection, toCollection, options) { return await (0, execute_operation_1.executeOperation)(this.client, new rename_1.RenameOperation(this.collection(fromCollection), toCollection, (0, utils_1.resolveOptions)(void 0, { ...options, new_collection: true, readPreference: read_preference_1.ReadPreference.primary }))); } /** * Drop a collection from the database, removing it permanently. New accesses will create a new collection. * * @param name - Name of collection to drop * @param options - Optional settings for the command */ async dropCollection(name, options) { return await (0, execute_operation_1.executeOperation)(this.client, new drop_1.DropCollectionOperation(this, name, (0, utils_1.resolveOptions)(this, options))); } /** * Drop a database, removing it permanently from the server. * * @param options - Optional settings for the command */ async dropDatabase(options) { return await (0, execute_operation_1.executeOperation)(this.client, new drop_1.DropDatabaseOperation(this, (0, utils_1.resolveOptions)(this, options))); } /** * Fetch all collections for the current db. * * @param options - Optional settings for the command */ async collections(options) { return await (0, execute_operation_1.executeOperation)(this.client, new collections_1.CollectionsOperation(this, (0, utils_1.resolveOptions)(this, options))); } /** * Creates an index on the db and collection. * * @param name - Name of the collection to create the index on. * @param indexSpec - Specify the field to index, or an index specification * @param options - Optional settings for the command */ async createIndex(name, indexSpec, options) { const indexes = await (0, execute_operation_1.executeOperation)(this.client, indexes_1.CreateIndexesOperation.fromIndexSpecification(this, name, indexSpec, options)); return indexes[0]; } /** * Remove a user from a database * * @param username - The username to remove * @param options - Optional settings for the command */ async removeUser(username, options) { return await (0, execute_operation_1.executeOperation)(this.client, new remove_user_1.RemoveUserOperation(this, username, (0, utils_1.resolveOptions)(this, options))); } /** * Set the current profiling level of MongoDB * * @param level - The new profiling level (off, slow_only, all). * @param options - Optional settings for the command */ async setProfilingLevel(level, options) { return await (0, execute_operation_1.executeOperation)(this.client, new set_profiling_level_1.SetProfilingLevelOperation(this, level, (0, utils_1.resolveOptions)(this, options))); } /** * Retrieve the current profiling Level for MongoDB * * @param options - Optional settings for the command */ async profilingLevel(options) { return await (0, execute_operation_1.executeOperation)(this.client, new profiling_level_1.ProfilingLevelOperation(this, (0, utils_1.resolveOptions)(this, options))); } async indexInformation(name, options) { return await this.collection(name).indexInformation((0, utils_1.resolveOptions)(this, options)); } /** * Create a new Change Stream, watching for new changes (insertions, updates, * replacements, deletions, and invalidations) in this database. Will ignore all * changes to system collections. * * @remarks * watch() accepts two generic arguments for distinct use cases: * - The first is to provide the schema that may be defined for all the collections within this database * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument * * @remarks * When `timeoutMS` is configured for a change stream, it will have different behaviour depending * on whether the change stream is in iterator mode or emitter mode. In both cases, a change * stream will time out if it does not receive a change event within `timeoutMS` of the last change * event. * * Note that if a change stream is consistently timing out when watching a collection, database or * client that is being changed, then this may be due to the server timing out before it can finish * processing the existing oplog. To address this, restart the change stream with a higher * `timeoutMS`. * * If the change stream times out the initial aggregate operation to establish the change stream on * the server, then the client will close the change stream. If the getMore calls to the server * time out, then the change stream will be left open, but will throw a MongoOperationTimeoutError * when in iterator mode and emit an error event that returns a MongoOperationTimeoutError in * emitter mode. * * To determine whether or not the change stream is still open following a timeout, check the * {@link ChangeStream.closed} getter. * * @example * In iterator mode, if a next() call throws a timeout error, it will attempt to resume the change stream. * The next call can just be retried after this succeeds. * ```ts * const changeStream = collection.watch([], { timeoutMS: 100 }); * try { * await changeStream.next(); * } catch (e) { * if (e instanceof MongoOperationTimeoutError && !changeStream.closed) { * await changeStream.next(); * } * throw e; * } * ``` * * @example * In emitter mode, if the change stream goes `timeoutMS` without emitting a change event, it will * emit an error event that returns a MongoOperationTimeoutError, but will not close the change * stream unless the resume attempt fails. There is no need to re-establish change listeners as * this will automatically continue emitting change events once the resume attempt completes. * * ```ts * const changeStream = collection.watch([], { timeoutMS: 100 }); * changeStream.on('change', console.log); * changeStream.on('error', e => { * if (e instanceof MongoOperationTimeoutError && !changeStream.closed) { * // do nothing * } else { * changeStream.close(); * } * }); * ``` * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. * @param options - Optional settings for the command * @typeParam TSchema - Type of the data being detected by the change stream * @typeParam TChange - Type of the whole change stream document emitted */ watch(pipeline = [], options = {}) { if (!Array.isArray(pipeline)) { options = pipeline; pipeline = []; } return new change_stream_1.ChangeStream(this, pipeline, (0, utils_1.resolveOptions)(this, options)); } /** * A low level cursor API providing basic driver functionality: * - ClientSession management * - ReadPreference for server selection * - Running getMores automatically when a local batch is exhausted * * @param command - The command that will start a cursor on the server. * @param options - Configurations for running the command, bson options will apply to getMores */ runCursorCommand(command, options) { return new run_command_cursor_1.RunCommandCursor(this, command, options); } }; exports2.Db = Db; Db.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION; Db.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION; Db.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION; Db.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION; Db.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION; Db.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION; } }); // netlify/functions/node_modules/mongodb/lib/change_stream.js var require_change_stream = __commonJS({ "netlify/functions/node_modules/mongodb/lib/change_stream.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ChangeStream = void 0; var collection_1 = require_collection(); var constants_1 = require_constants(); var abstract_cursor_1 = require_abstract_cursor(); var change_stream_cursor_1 = require_change_stream_cursor(); var db_1 = require_db(); var error_1 = require_error(); var mongo_client_1 = require_mongo_client(); var mongo_types_1 = require_mongo_types(); var resource_management_1 = require_resource_management(); var timeout_1 = require_timeout(); var utils_1 = require_utils(); var CHANGE_STREAM_OPTIONS = [ "resumeAfter", "startAfter", "startAtOperationTime", "fullDocument", "fullDocumentBeforeChange", "showExpandedEvents" ]; var CHANGE_DOMAIN_TYPES = { COLLECTION: Symbol("Collection"), DATABASE: Symbol("Database"), CLUSTER: Symbol("Cluster") }; var CHANGE_STREAM_EVENTS = [constants_1.RESUME_TOKEN_CHANGED, constants_1.END, constants_1.CLOSE]; var NO_RESUME_TOKEN_ERROR = "A change stream document has been received that lacks a resume token (_id)."; var CHANGESTREAM_CLOSED_ERROR = "ChangeStream is closed"; var ChangeStream = class _ChangeStream extends mongo_types_1.TypedEventEmitter { /** @internal */ async asyncDispose() { await this.close(); } /** * @internal * * @param parent - The parent object that created this change stream * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents */ constructor(parent, pipeline = [], options = {}) { super(); this.pipeline = pipeline; this.options = { ...options }; let serverSelectionTimeoutMS; delete this.options.writeConcern; if (parent instanceof collection_1.Collection) { this.type = CHANGE_DOMAIN_TYPES.COLLECTION; serverSelectionTimeoutMS = parent.s.db.client.options.serverSelectionTimeoutMS; } else if (parent instanceof db_1.Db) { this.type = CHANGE_DOMAIN_TYPES.DATABASE; serverSelectionTimeoutMS = parent.client.options.serverSelectionTimeoutMS; } else if (parent instanceof mongo_client_1.MongoClient) { this.type = CHANGE_DOMAIN_TYPES.CLUSTER; serverSelectionTimeoutMS = parent.options.serverSelectionTimeoutMS; } else { throw new error_1.MongoChangeStreamError("Parent provided to ChangeStream constructor must be an instance of Collection, Db, or MongoClient"); } this.contextOwner = Symbol(); this.parent = parent; this.namespace = parent.s.namespace; if (!this.options.readPreference && parent.readPreference) { this.options.readPreference = parent.readPreference; } this.cursor = this._createChangeStreamCursor(options); this.isClosed = false; this.mode = false; this.on("newListener", (eventName) => { if (eventName === "change" && this.cursor && this.listenerCount("change") === 0) { this._streamEvents(this.cursor); } }); this.on("removeListener", (eventName) => { if (eventName === "change" && this.listenerCount("change") === 0 && this.cursor) { this.cursorStream?.removeAllListeners("data"); } }); if (this.options.timeoutMS != null) { this.timeoutContext = new timeout_1.CSOTTimeoutContext({ timeoutMS: this.options.timeoutMS, serverSelectionTimeoutMS }); } } /** The cached resume token that is used to resume after the most recently returned change. */ get resumeToken() { return this.cursor?.resumeToken; } /** Check if there is any document still available in the Change Stream */ async hasNext() { this._setIsIterator(); this.timeoutContext?.refresh(); try { while (true) { try { const hasNext = await this.cursor.hasNext(); return hasNext; } catch (error) { try { await this._processErrorIteratorMode(error, this.cursor.id != null); } catch (error2) { if (error2 instanceof error_1.MongoOperationTimeoutError && this.cursor.id == null) { throw error2; } try { await this.close(); } catch (error3) { (0, utils_1.squashError)(error3); } throw error2; } } } } finally { this.timeoutContext?.clear(); } } /** Get the next available document from the Change Stream. */ async next() { this._setIsIterator(); this.timeoutContext?.refresh(); try { while (true) { try { const change = await this.cursor.next(); const processedChange = this._processChange(change ?? null); return processedChange; } catch (error) { try { await this._processErrorIteratorMode(error, this.cursor.id != null); } catch (error2) { if (error2 instanceof error_1.MongoOperationTimeoutError && this.cursor.id == null) { throw error2; } try { await this.close(); } catch (error3) { (0, utils_1.squashError)(error3); } throw error2; } } } } finally { this.timeoutContext?.clear(); } } /** * Try to get the next available document from the Change Stream's cursor or `null` if an empty batch is returned */ async tryNext() { this._setIsIterator(); this.timeoutContext?.refresh(); try { while (true) { try { const change = await this.cursor.tryNext(); return change ?? null; } catch (error) { try { await this._processErrorIteratorMode(error, this.cursor.id != null); } catch (error2) { if (error2 instanceof error_1.MongoOperationTimeoutError && this.cursor.id == null) throw error2; try { await this.close(); } catch (error3) { (0, utils_1.squashError)(error3); } throw error2; } } } } finally { this.timeoutContext?.clear(); } } async *[Symbol.asyncIterator]() { if (this.closed) { return; } try { while (true) { yield await this.next(); } } finally { try { await this.close(); } catch (error) { (0, utils_1.squashError)(error); } } } /** Is the cursor closed */ get closed() { return this.isClosed || this.cursor.closed; } /** * Frees the internal resources used by the change stream. */ async close() { this.timeoutContext?.clear(); this.timeoutContext = void 0; this.isClosed = true; const cursor = this.cursor; try { await cursor.close(); } finally { this._endStream(); } } /** * Return a modified Readable stream including a possible transform method. * * NOTE: When using a Stream to process change stream events, the stream will * NOT automatically resume in the case a resumable error is encountered. * * @throws MongoChangeStreamError if the underlying cursor or the change stream is closed */ stream(options) { if (this.closed) { throw new error_1.MongoChangeStreamError(CHANGESTREAM_CLOSED_ERROR); } this.streamOptions = options; return this.cursor.stream(options); } /** @internal */ _setIsEmitter() { if (this.mode === "iterator") { throw new error_1.MongoAPIError("ChangeStream cannot be used as an EventEmitter after being used as an iterator"); } this.mode = "emitter"; } /** @internal */ _setIsIterator() { if (this.mode === "emitter") { throw new error_1.MongoAPIError("ChangeStream cannot be used as an iterator after being used as an EventEmitter"); } this.mode = "iterator"; } /** * Create a new change stream cursor based on self's configuration * @internal */ _createChangeStreamCursor(options) { const changeStreamStageOptions = (0, utils_1.filterOptions)(options, CHANGE_STREAM_OPTIONS); if (this.type === CHANGE_DOMAIN_TYPES.CLUSTER) { changeStreamStageOptions.allChangesForCluster = true; } const pipeline = [{ $changeStream: changeStreamStageOptions }, ...this.pipeline]; const client = this.type === CHANGE_DOMAIN_TYPES.CLUSTER ? this.parent : this.type === CHANGE_DOMAIN_TYPES.DATABASE ? this.parent.client : this.type === CHANGE_DOMAIN_TYPES.COLLECTION ? this.parent.client : null; if (client == null) { throw new error_1.MongoRuntimeError(`Changestream type should only be one of cluster, database, collection. Found ${this.type.toString()}`); } const changeStreamCursor = new change_stream_cursor_1.ChangeStreamCursor(client, this.namespace, pipeline, { ...options, timeoutContext: this.timeoutContext ? new abstract_cursor_1.CursorTimeoutContext(this.timeoutContext, this.contextOwner) : void 0 }); for (const event of CHANGE_STREAM_EVENTS) { changeStreamCursor.on(event, (e) => this.emit(event, e)); } if (this.listenerCount(_ChangeStream.CHANGE) > 0) { this._streamEvents(changeStreamCursor); } return changeStreamCursor; } /** @internal */ _closeEmitterModeWithError(error) { this.emit(_ChangeStream.ERROR, error); this.close().then(void 0, utils_1.squashError); } /** @internal */ _streamEvents(cursor) { this._setIsEmitter(); const stream = this.cursorStream ?? cursor.stream(); this.cursorStream = stream; stream.on("data", (change) => { try { const processedChange = this._processChange(change); this.emit(_ChangeStream.CHANGE, processedChange); } catch (error) { this.emit(_ChangeStream.ERROR, error); } this.timeoutContext?.refresh(); }); stream.on("error", (error) => this._processErrorStreamMode(error, this.cursor.id != null)); } /** @internal */ _endStream() { this.cursorStream?.removeAllListeners("data"); this.cursorStream?.removeAllListeners("close"); this.cursorStream?.removeAllListeners("end"); this.cursorStream?.destroy(); this.cursorStream = void 0; } /** @internal */ _processChange(change) { if (this.isClosed) { throw new error_1.MongoAPIError(CHANGESTREAM_CLOSED_ERROR); } if (change == null) { throw new error_1.MongoRuntimeError(CHANGESTREAM_CLOSED_ERROR); } if (change && !change._id) { throw new error_1.MongoChangeStreamError(NO_RESUME_TOKEN_ERROR); } this.cursor.cacheResumeToken(change._id); this.options.startAtOperationTime = void 0; return change; } /** @internal */ _processErrorStreamMode(changeStreamError, cursorInitialized) { if (this.isClosed) return; if (cursorInitialized && ((0, error_1.isResumableError)(changeStreamError, this.cursor.maxWireVersion) || changeStreamError instanceof error_1.MongoOperationTimeoutError)) { this._endStream(); this.cursor.close().then(() => this._resume(changeStreamError), (e) => { (0, utils_1.squashError)(e); return this._resume(changeStreamError); }).then(() => { if (changeStreamError instanceof error_1.MongoOperationTimeoutError) this.emit(_ChangeStream.ERROR, changeStreamError); }, () => this._closeEmitterModeWithError(changeStreamError)); } else { this._closeEmitterModeWithError(changeStreamError); } } /** @internal */ async _processErrorIteratorMode(changeStreamError, cursorInitialized) { if (this.isClosed) { throw new error_1.MongoAPIError(CHANGESTREAM_CLOSED_ERROR); } if (cursorInitialized && ((0, error_1.isResumableError)(changeStreamError, this.cursor.maxWireVersion) || changeStreamError instanceof error_1.MongoOperationTimeoutError)) { try { await this.cursor.close(); } catch (error) { (0, utils_1.squashError)(error); } await this._resume(changeStreamError); if (changeStreamError instanceof error_1.MongoOperationTimeoutError) throw changeStreamError; } else { try { await this.close(); } catch (error) { (0, utils_1.squashError)(error); } throw changeStreamError; } } async _resume(changeStreamError) { this.timeoutContext?.refresh(); const topology = (0, utils_1.getTopology)(this.parent); try { await topology.selectServer(this.cursor.readPreference, { operationName: "reconnect topology in change stream", timeoutContext: this.timeoutContext }); this.cursor = this._createChangeStreamCursor(this.cursor.resumeOptions); } catch { await this.close(); throw changeStreamError; } } }; exports2.ChangeStream = ChangeStream; ChangeStream.RESPONSE = constants_1.RESPONSE; ChangeStream.MORE = constants_1.MORE; ChangeStream.INIT = constants_1.INIT; ChangeStream.CLOSE = constants_1.CLOSE; ChangeStream.CHANGE = constants_1.CHANGE; ChangeStream.END = constants_1.END; ChangeStream.ERROR = constants_1.ERROR; ChangeStream.RESUME_TOKEN_CHANGED = constants_1.RESUME_TOKEN_CHANGED; (0, resource_management_1.configureResourceManagement)(ChangeStream.prototype); } }); // netlify/functions/node_modules/mongodb/lib/deps.js var require_deps = __commonJS({ "netlify/functions/node_modules/mongodb/lib/deps.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.aws4 = void 0; exports2.getKerberos = getKerberos; exports2.getZstdLibrary = getZstdLibrary; exports2.getAwsCredentialProvider = getAwsCredentialProvider; exports2.getGcpMetadata = getGcpMetadata; exports2.getSnappy = getSnappy; exports2.getSocks = getSocks; exports2.getMongoDBClientEncryption = getMongoDBClientEncryption; var error_1 = require_error(); function makeErrorModule(error) { const props = error ? { kModuleError: error } : {}; return new Proxy(props, { get: (_, key) => { if (key === "kModuleError") { return error; } throw error; }, set: () => { throw error; } }); } function getKerberos() { let kerberos; try { kerberos = require("kerberos"); } catch (error) { kerberos = makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `kerberos` not found. Please install it to enable kerberos authentication", { cause: error, dependencyName: "kerberos" })); } return kerberos; } function getZstdLibrary() { let ZStandard; try { ZStandard = require("@mongodb-js/zstd"); } catch (error) { ZStandard = makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `@mongodb-js/zstd` not found. Please install it to enable zstd compression", { cause: error, dependencyName: "zstd" })); } return ZStandard; } function getAwsCredentialProvider() { try { const credentialProvider = require("@aws-sdk/credential-providers"); return credentialProvider; } catch (error) { return makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `@aws-sdk/credential-providers` not found. Please install it to enable getting aws credentials via the official sdk.", { cause: error, dependencyName: "@aws-sdk/credential-providers" })); } } function getGcpMetadata() { try { const credentialProvider = require("gcp-metadata"); return credentialProvider; } catch (error) { return makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `gcp-metadata` not found. Please install it to enable getting gcp credentials via the official sdk.", { cause: error, dependencyName: "gcp-metadata" })); } } function getSnappy() { try { const value = require("snappy"); return value; } catch (error) { const kModuleError = new error_1.MongoMissingDependencyError("Optional module `snappy` not found. Please install it to enable snappy compression", { cause: error, dependencyName: "snappy" }); return { kModuleError }; } } function getSocks() { try { const value = require("socks"); return value; } catch (error) { const kModuleError = new error_1.MongoMissingDependencyError("Optional module `socks` not found. Please install it to connections over a SOCKS5 proxy", { cause: error, dependencyName: "socks" }); return { kModuleError }; } } exports2.aws4 = loadAws4(); function loadAws4() { let aws4; try { aws4 = require("aws4"); } catch (error) { aws4 = makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `aws4` not found. Please install it to enable AWS authentication", { cause: error, dependencyName: "aws4" })); } return aws4; } function getMongoDBClientEncryption() { let mongodbClientEncryption = null; try { mongodbClientEncryption = require("mongodb-client-encryption"); } catch (error) { const kModuleError = new error_1.MongoMissingDependencyError("Optional module `mongodb-client-encryption` not found. Please install it to use auto encryption or ClientEncryption.", { cause: error, dependencyName: "mongodb-client-encryption" }); return { kModuleError }; } return mongodbClientEncryption; } } }); // netlify/functions/node_modules/mongodb/lib/cmap/auth/auth_provider.js var require_auth_provider = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/auth/auth_provider.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.AuthProvider = exports2.AuthContext = void 0; var error_1 = require_error(); var AuthContext = class { constructor(connection, credentials, options) { this.reauthenticating = false; this.connection = connection; this.credentials = credentials; this.options = options; } }; exports2.AuthContext = AuthContext; var AuthProvider = class { /** * Prepare the handshake document before the initial handshake. * * @param handshakeDoc - The document used for the initial handshake on a connection * @param authContext - Context for authentication flow */ async prepare(handshakeDoc, _authContext) { return handshakeDoc; } /** * Reauthenticate. * @param context - The shared auth context. */ async reauth(context) { if (context.reauthenticating) { throw new error_1.MongoRuntimeError("Reauthentication already in progress."); } try { context.reauthenticating = true; await this.auth(context); } finally { context.reauthenticating = false; } } }; exports2.AuthProvider = AuthProvider; } }); // netlify/functions/node_modules/mongodb/lib/cmap/auth/gssapi.js var require_gssapi = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/auth/gssapi.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.GSSAPI = exports2.GSSAPICanonicalizationValue = void 0; exports2.performGSSAPICanonicalizeHostName = performGSSAPICanonicalizeHostName; exports2.resolveCname = resolveCname; var dns = require("dns"); var deps_1 = require_deps(); var error_1 = require_error(); var utils_1 = require_utils(); var auth_provider_1 = require_auth_provider(); exports2.GSSAPICanonicalizationValue = Object.freeze({ on: true, off: false, none: "none", forward: "forward", forwardAndReverse: "forwardAndReverse" }); async function externalCommand(connection, command) { const response = await connection.command((0, utils_1.ns)("$external.$cmd"), command); return response; } var krb; var GSSAPI = class extends auth_provider_1.AuthProvider { async auth(authContext) { const { connection, credentials } = authContext; if (credentials == null) { throw new error_1.MongoMissingCredentialsError("Credentials required for GSSAPI authentication"); } const { username } = credentials; const client = await makeKerberosClient(authContext); const payload = await client.step(""); const saslStartResponse = await externalCommand(connection, saslStart(payload)); const negotiatedPayload = await negotiate(client, 10, saslStartResponse.payload); const saslContinueResponse = await externalCommand(connection, saslContinue(negotiatedPayload, saslStartResponse.conversationId)); const finalizePayload = await finalize(client, username, saslContinueResponse.payload); await externalCommand(connection, { saslContinue: 1, conversationId: saslContinueResponse.conversationId, payload: finalizePayload }); } }; exports2.GSSAPI = GSSAPI; async function makeKerberosClient(authContext) { const { hostAddress } = authContext.options; const { credentials } = authContext; if (!hostAddress || typeof hostAddress.host !== "string" || !credentials) { throw new error_1.MongoInvalidArgumentError("Connection must have host and port and credentials defined."); } loadKrb(); if ("kModuleError" in krb) { throw krb["kModuleError"]; } const { initializeClient } = krb; const { username, password } = credentials; const mechanismProperties = credentials.mechanismProperties; const serviceName = mechanismProperties.SERVICE_NAME ?? "mongodb"; const host = await performGSSAPICanonicalizeHostName(hostAddress.host, mechanismProperties); const initOptions = {}; if (password != null) { Object.assign(initOptions, { user: username, password }); } const spnHost = mechanismProperties.SERVICE_HOST ?? host; let spn = `${serviceName}${process.platform === "win32" ? "/" : "@"}${spnHost}`; if ("SERVICE_REALM" in mechanismProperties) { spn = `${spn}@${mechanismProperties.SERVICE_REALM}`; } return await initializeClient(spn, initOptions); } function saslStart(payload) { return { saslStart: 1, mechanism: "GSSAPI", payload, autoAuthorize: 1 }; } function saslContinue(payload, conversationId) { return { saslContinue: 1, conversationId, payload }; } async function negotiate(client, retries, payload) { try { const response = await client.step(payload); return response || ""; } catch (error) { if (retries === 0) { throw error; } return await negotiate(client, retries - 1, payload); } } async function finalize(client, user, payload) { const response = await client.unwrap(payload); return await client.wrap(response || "", { user }); } async function performGSSAPICanonicalizeHostName(host, mechanismProperties) { const mode = mechanismProperties.CANONICALIZE_HOST_NAME; if (!mode || mode === exports2.GSSAPICanonicalizationValue.none) { return host; } if (mode === exports2.GSSAPICanonicalizationValue.on || mode === exports2.GSSAPICanonicalizationValue.forwardAndReverse) { const { address } = await dns.promises.lookup(host); try { const results = await dns.promises.resolvePtr(address); return results.length > 0 ? results[0] : host; } catch { return await resolveCname(host); } } else { return await resolveCname(host); } } async function resolveCname(host) { try { const results = await dns.promises.resolveCname(host); return results.length > 0 ? results[0] : host; } catch { return host; } } function loadKrb() { if (!krb) { krb = (0, deps_1.getKerberos)(); } } } }); // netlify/functions/node_modules/mongodb/lib/cmap/auth/providers.js var require_providers = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/auth/providers.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.AUTH_MECHS_AUTH_SRC_EXTERNAL = exports2.AuthMechanism = void 0; exports2.AuthMechanism = Object.freeze({ MONGODB_AWS: "MONGODB-AWS", MONGODB_CR: "MONGODB-CR", MONGODB_DEFAULT: "DEFAULT", MONGODB_GSSAPI: "GSSAPI", MONGODB_PLAIN: "PLAIN", MONGODB_SCRAM_SHA1: "SCRAM-SHA-1", MONGODB_SCRAM_SHA256: "SCRAM-SHA-256", MONGODB_X509: "MONGODB-X509", MONGODB_OIDC: "MONGODB-OIDC" }); exports2.AUTH_MECHS_AUTH_SRC_EXTERNAL = /* @__PURE__ */ new Set([ exports2.AuthMechanism.MONGODB_GSSAPI, exports2.AuthMechanism.MONGODB_AWS, exports2.AuthMechanism.MONGODB_OIDC, exports2.AuthMechanism.MONGODB_X509 ]); } }); // netlify/functions/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js var require_mongo_credentials = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.MongoCredentials = exports2.DEFAULT_ALLOWED_HOSTS = void 0; var error_1 = require_error(); var gssapi_1 = require_gssapi(); var providers_1 = require_providers(); function getDefaultAuthMechanism(hello) { if (hello) { if (Array.isArray(hello.saslSupportedMechs)) { return hello.saslSupportedMechs.includes(providers_1.AuthMechanism.MONGODB_SCRAM_SHA256) ? providers_1.AuthMechanism.MONGODB_SCRAM_SHA256 : providers_1.AuthMechanism.MONGODB_SCRAM_SHA1; } } return providers_1.AuthMechanism.MONGODB_SCRAM_SHA256; } var ALLOWED_ENVIRONMENT_NAMES = [ "test", "azure", "gcp", "k8s" ]; var ALLOWED_HOSTS_ERROR = "Auth mechanism property ALLOWED_HOSTS must be an array of strings."; exports2.DEFAULT_ALLOWED_HOSTS = [ "*.mongodb.net", "*.mongodb-qa.net", "*.mongodb-dev.net", "*.mongodbgov.net", "localhost", "127.0.0.1", "::1" ]; var TOKEN_RESOURCE_MISSING_ERROR = "TOKEN_RESOURCE must be set in the auth mechanism properties when ENVIRONMENT is azure or gcp."; var MongoCredentials = class _MongoCredentials { constructor(options) { this.username = options.username ?? ""; this.password = options.password; this.source = options.source; if (!this.source && options.db) { this.source = options.db; } this.mechanism = options.mechanism || providers_1.AuthMechanism.MONGODB_DEFAULT; this.mechanismProperties = options.mechanismProperties || {}; if (this.mechanism.match(/MONGODB-AWS/i)) { if (!this.username && process.env.AWS_ACCESS_KEY_ID) { this.username = process.env.AWS_ACCESS_KEY_ID; } if (!this.password && process.env.AWS_SECRET_ACCESS_KEY) { this.password = process.env.AWS_SECRET_ACCESS_KEY; } if (this.mechanismProperties.AWS_SESSION_TOKEN == null && process.env.AWS_SESSION_TOKEN != null) { this.mechanismProperties = { ...this.mechanismProperties, AWS_SESSION_TOKEN: process.env.AWS_SESSION_TOKEN }; } } if (this.mechanism === providers_1.AuthMechanism.MONGODB_OIDC && !this.mechanismProperties.ALLOWED_HOSTS) { this.mechanismProperties = { ...this.mechanismProperties, ALLOWED_HOSTS: exports2.DEFAULT_ALLOWED_HOSTS }; } Object.freeze(this.mechanismProperties); Object.freeze(this); } /** Determines if two MongoCredentials objects are equivalent */ equals(other) { return this.mechanism === other.mechanism && this.username === other.username && this.password === other.password && this.source === other.source; } /** * If the authentication mechanism is set to "default", resolves the authMechanism * based on the server version and server supported sasl mechanisms. * * @param hello - A hello response from the server */ resolveAuthMechanism(hello) { if (this.mechanism.match(/DEFAULT/i)) { return new _MongoCredentials({ username: this.username, password: this.password, source: this.source, mechanism: getDefaultAuthMechanism(hello), mechanismProperties: this.mechanismProperties }); } return this; } validate() { if ((this.mechanism === providers_1.AuthMechanism.MONGODB_GSSAPI || this.mechanism === providers_1.AuthMechanism.MONGODB_PLAIN || this.mechanism === providers_1.AuthMechanism.MONGODB_SCRAM_SHA1 || this.mechanism === providers_1.AuthMechanism.MONGODB_SCRAM_SHA256) && !this.username) { throw new error_1.MongoMissingCredentialsError(`Username required for mechanism '${this.mechanism}'`); } if (this.mechanism === providers_1.AuthMechanism.MONGODB_OIDC) { if (this.username && this.mechanismProperties.ENVIRONMENT && this.mechanismProperties.ENVIRONMENT !== "azure") { throw new error_1.MongoInvalidArgumentError(`username and ENVIRONMENT '${this.mechanismProperties.ENVIRONMENT}' may not be used together for mechanism '${this.mechanism}'.`); } if (this.username && this.password) { throw new error_1.MongoInvalidArgumentError(`No password is allowed in ENVIRONMENT '${this.mechanismProperties.ENVIRONMENT}' for '${this.mechanism}'.`); } if ((this.mechanismProperties.ENVIRONMENT === "azure" || this.mechanismProperties.ENVIRONMENT === "gcp") && !this.mechanismProperties.TOKEN_RESOURCE) { throw new error_1.MongoInvalidArgumentError(TOKEN_RESOURCE_MISSING_ERROR); } if (this.mechanismProperties.ENVIRONMENT && !ALLOWED_ENVIRONMENT_NAMES.includes(this.mechanismProperties.ENVIRONMENT)) { throw new error_1.MongoInvalidArgumentError(`Currently only a ENVIRONMENT in ${ALLOWED_ENVIRONMENT_NAMES.join(",")} is supported for mechanism '${this.mechanism}'.`); } if (!this.mechanismProperties.ENVIRONMENT && !this.mechanismProperties.OIDC_CALLBACK && !this.mechanismProperties.OIDC_HUMAN_CALLBACK) { throw new error_1.MongoInvalidArgumentError(`Either a ENVIRONMENT, OIDC_CALLBACK, or OIDC_HUMAN_CALLBACK must be specified for mechanism '${this.mechanism}'.`); } if (this.mechanismProperties.ALLOWED_HOSTS) { const hosts = this.mechanismProperties.ALLOWED_HOSTS; if (!Array.isArray(hosts)) { throw new error_1.MongoInvalidArgumentError(ALLOWED_HOSTS_ERROR); } for (const host of hosts) { if (typeof host !== "string") { throw new error_1.MongoInvalidArgumentError(ALLOWED_HOSTS_ERROR); } } } } if (providers_1.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(this.mechanism)) { if (this.source != null && this.source !== "$external") { throw new error_1.MongoAPIError(`Invalid source '${this.source}' for mechanism '${this.mechanism}' specified.`); } } if (this.mechanism === providers_1.AuthMechanism.MONGODB_PLAIN && this.source == null) { throw new error_1.MongoAPIError("PLAIN Authentication Mechanism needs an auth source"); } if (this.mechanism === providers_1.AuthMechanism.MONGODB_X509 && this.password != null) { if (this.password === "") { Reflect.set(this, "password", void 0); return; } throw new error_1.MongoAPIError(`Password not allowed for mechanism MONGODB-X509`); } const canonicalization = this.mechanismProperties.CANONICALIZE_HOST_NAME ?? false; if (!Object.values(gssapi_1.GSSAPICanonicalizationValue).includes(canonicalization)) { throw new error_1.MongoAPIError(`Invalid CANONICALIZE_HOST_NAME value: ${canonicalization}`); } } static merge(creds, options) { return new _MongoCredentials({ username: options.username ?? creds?.username ?? "", password: options.password ?? creds?.password ?? "", mechanism: options.mechanism ?? creds?.mechanism ?? providers_1.AuthMechanism.MONGODB_DEFAULT, mechanismProperties: options.mechanismProperties ?? creds?.mechanismProperties ?? {}, source: options.source ?? options.db ?? creds?.source ?? "admin" }); } }; exports2.MongoCredentials = MongoCredentials; } }); // netlify/functions/node_modules/mongodb/package.json var require_package = __commonJS({ "netlify/functions/node_modules/mongodb/package.json"(exports2, module2) { module2.exports = { name: "mongodb", version: "6.18.0", description: "The official MongoDB driver for Node.js", main: "lib/index.js", files: [ "lib", "src", "etc/prepare.js", "mongodb.d.ts", "tsconfig.json" ], types: "mongodb.d.ts", repository: { type: "git", url: "git@github.com:mongodb/node-mongodb-native.git" }, keywords: [ "mongodb", "driver", "official" ], author: { name: "The MongoDB NodeJS Team", email: "dbx-node@mongodb.com" }, dependencies: { "@mongodb-js/saslprep": "^1.1.9", bson: "^6.10.4", "mongodb-connection-string-url": "^3.0.0" }, peerDependencies: { "@aws-sdk/credential-providers": "^3.188.0", "@mongodb-js/zstd": "^1.1.0 || ^2.0.0", "gcp-metadata": "^5.2.0", kerberos: "^2.0.1", "mongodb-client-encryption": ">=6.0.0 <7", snappy: "^7.2.2", socks: "^2.7.1" }, peerDependenciesMeta: { "@aws-sdk/credential-providers": { optional: true }, "@mongodb-js/zstd": { optional: true }, kerberos: { optional: true }, snappy: { optional: true }, "mongodb-client-encryption": { optional: true }, "gcp-metadata": { optional: true }, socks: { optional: true } }, devDependencies: { "@aws-sdk/credential-providers": "^3.632.0", "@iarna/toml": "^2.2.5", "@istanbuljs/nyc-config-typescript": "^1.0.2", "@microsoft/api-extractor": "^7.52.5", "@microsoft/tsdoc-config": "^0.17.1", "@mongodb-js/zstd": "^2.0.1", "@types/chai": "^4.3.17", "@types/chai-subset": "^1.3.5", "@types/express": "^5.0.1", "@types/kerberos": "^1.1.5", "@types/mocha": "^10.0.9", "@types/node": "^22.15.3", "@types/saslprep": "^1.0.3", "@types/semver": "^7.7.0", "@types/sinon": "^17.0.4", "@types/sinon-chai": "^4.0.0", "@types/whatwg-url": "^13.0.0", "@typescript-eslint/eslint-plugin": "^8.31.1", "@typescript-eslint/parser": "^8.31.1", chai: "^4.4.1", "chai-subset": "^1.6.0", chalk: "^4.1.2", eslint: "^9.25.1", "eslint-config-prettier": "^10.1.2", "eslint-plugin-mocha": "^10.4.1", "eslint-plugin-prettier": "^5.2.3", "eslint-plugin-simple-import-sort": "^12.1.1", "eslint-plugin-tsdoc": "^0.4.0", "eslint-plugin-unused-imports": "^4.1.4", express: "^5.1.0", "gcp-metadata": "^5.3.0", "js-yaml": "^4.1.0", mocha: "^10.8.2", "mocha-sinon": "^2.1.2", "mongodb-client-encryption": "^6.4.0", "mongodb-legacy": "^6.1.3", nyc: "^15.1.0", prettier: "^3.5.3", semver: "^7.7.0", sinon: "^18.0.1", "sinon-chai": "^3.7.0", snappy: "^7.2.2", socks: "^2.8.1", "source-map-support": "^0.5.21", "ts-node": "^10.9.2", tsd: "^0.32.0", typescript: "5.8.3", "typescript-cached-transpile": "^0.0.6", "v8-heapsnapshot": "^1.3.1", yargs: "^17.7.2" }, license: "Apache-2.0", engines: { node: ">=16.20.1" }, bugs: { url: "https://jira.mongodb.org/projects/NODE/issues/" }, homepage: "https://github.com/mongodb/node-mongodb-native", scripts: { "build:evergreen": "node .evergreen/generate_evergreen_tasks.js", "build:ts": "node ./node_modules/typescript/bin/tsc", "build:dts": "npm run build:ts && api-extractor run && node etc/clean_definition_files.cjs && ESLINT_USE_FLAT_CONFIG=false eslint --no-ignore --fix mongodb.d.ts lib/beta.d.ts", "build:docs": "./etc/docs/build.ts", "build:typedoc": "typedoc", "build:nightly": "node ./.github/scripts/nightly.mjs", "check:bench": "npm --prefix test/benchmarks/driver_bench start", "check:coverage": "nyc npm run test:all", "check:integration-coverage": "nyc npm run check:test", "check:lambda": "nyc mocha --config test/mocha_lambda.js test/integration/node-specific/examples/handler.test.js", "check:lambda:aws": "nyc mocha --config test/mocha_lambda.js test/integration/node-specific/examples/aws_handler.test.js", "check:lint": "npm run build:dts && npm run check:dts && npm run check:eslint && npm run check:tsd", "check:eslint": "npm run build:dts && ESLINT_USE_FLAT_CONFIG=false eslint -v && ESLINT_USE_FLAT_CONFIG=false eslint --max-warnings=0 --ext '.js,.ts' src test", "check:tsd": "tsd --version && tsd", "check:dependencies": "mocha test/action/dependency.test.ts", "check:dts": "node ./node_modules/typescript/bin/tsc --noEmit mongodb.d.ts && tsd", "check:search-indexes": "nyc mocha --config test/mocha_mongodb.js test/manual/search-index-management.prose.test.ts", "check:test": "mocha --config test/mocha_mongodb.js test/integration", "check:unit": "nyc mocha test/unit", "check:ts": "node ./node_modules/typescript/bin/tsc -v && node ./node_modules/typescript/bin/tsc --noEmit", "check:atlas": "nyc mocha --config test/manual/mocharc.js test/manual/atlas_connectivity.test.ts", "check:resource-management": "nyc mocha --config test/manual/mocharc.js test/manual/resource_management.test.ts", "check:drivers-atlas-testing": "nyc mocha --config test/mocha_mongodb.js test/atlas/drivers_atlas_testing.test.ts", "check:adl": "nyc mocha --config test/mocha_mongodb.js test/manual/atlas-data-lake-testing", "check:aws": "nyc mocha --config test/mocha_mongodb.js test/integration/auth/mongodb_aws.test.ts", "check:oidc-auth": "nyc mocha --config test/mocha_mongodb.js test/integration/auth/auth.spec.test.ts", "check:oidc-test": "nyc mocha --config test/mocha_mongodb.js test/integration/auth/mongodb_oidc.prose.test.ts", "check:oidc-azure": "nyc mocha --config test/mocha_mongodb.js test/integration/auth/mongodb_oidc_azure.prose.05.test.ts", "check:oidc-gcp": "nyc mocha --config test/mocha_mongodb.js test/integration/auth/mongodb_oidc_gcp.prose.06.test.ts", "check:oidc-k8s": "nyc mocha --config test/mocha_mongodb.js test/integration/auth/mongodb_oidc_k8s.prose.07.test.ts", "check:kerberos": "nyc mocha --config test/manual/mocharc.js test/manual/kerberos.test.ts", "check:tls": "nyc mocha --config test/manual/mocharc.js test/manual/tls_support.test.ts", "check:ldap": "nyc mocha --config test/manual/mocharc.js test/manual/ldap.test.ts", "check:socks5": "nyc mocha --config test/manual/mocharc.js test/manual/socks5.test.ts", "check:csfle": "nyc mocha --config test/mocha_mongodb.js test/integration/client-side-encryption", "check:snappy": "nyc mocha test/unit/assorted/snappy.test.js", "check:x509": "nyc mocha test/manual/x509_auth.test.ts", "fix:eslint": "npm run check:eslint -- --fix", prepare: "node etc/prepare.js", "preview:docs": "ts-node etc/docs/preview.ts", test: "npm run check:lint && npm run test:all", "test:all": "npm run check:unit && npm run check:test", "update:docs": "npm run build:docs -- --yes" }, tsd: { directory: "test/types", compilerOptions: { strict: true, target: "esnext", module: "commonjs", moduleResolution: "node" } } }; } }); // netlify/functions/node_modules/mongodb/lib/cmap/handshake/client_metadata.js var require_client_metadata = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/handshake/client_metadata.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.LimitedSizeDocument = void 0; exports2.makeClientMetadata = makeClientMetadata; exports2.addContainerMetadata = addContainerMetadata; exports2.getFAASEnv = getFAASEnv; var os = require("os"); var process2 = require("process"); var bson_1 = require_bson2(); var error_1 = require_error(); var utils_1 = require_utils(); var NODE_DRIVER_VERSION = require_package().version; var LimitedSizeDocument = class { constructor(maxSize) { this.document = /* @__PURE__ */ new Map(); this.documentSize = 5; this.maxSize = maxSize; } /** Only adds key/value if the bsonByteLength is less than MAX_SIZE */ ifItFitsItSits(key, value) { const newElementSize = bson_1.BSON.serialize((/* @__PURE__ */ new Map()).set(key, value)).byteLength - 5; if (newElementSize + this.documentSize > this.maxSize) { return false; } this.documentSize += newElementSize; this.document.set(key, value); return true; } toObject() { return bson_1.BSON.deserialize(bson_1.BSON.serialize(this.document), { promoteLongs: false, promoteBuffers: false, promoteValues: false, useBigInt64: false }); } }; exports2.LimitedSizeDocument = LimitedSizeDocument; function makeClientMetadata(options) { const metadataDocument = new LimitedSizeDocument(512); const { appName = "" } = options; if (appName.length > 0) { const name2 = Buffer.byteLength(appName, "utf8") <= 128 ? options.appName : Buffer.from(appName, "utf8").subarray(0, 128).toString("utf8"); metadataDocument.ifItFitsItSits("application", { name: name2 }); } const { name = "", version = "", platform = "" } = options.driverInfo; const driverInfo = { name: name.length > 0 ? `nodejs|${name}` : "nodejs", version: version.length > 0 ? `${NODE_DRIVER_VERSION}|${version}` : NODE_DRIVER_VERSION }; if (options.additionalDriverInfo == null) { throw new error_1.MongoRuntimeError("Client options `additionalDriverInfo` must always default to an empty array"); } for (const { name: n = "", version: v = "" } of options.additionalDriverInfo) { if (n.length > 0) { driverInfo.name = `${driverInfo.name}|${n}`; } if (v.length > 0) { driverInfo.version = `${driverInfo.version}|${v}`; } } if (!metadataDocument.ifItFitsItSits("driver", driverInfo)) { throw new error_1.MongoInvalidArgumentError("Unable to include driverInfo name and version, metadata cannot exceed 512 bytes"); } let runtimeInfo = getRuntimeInfo(); if (platform.length > 0) { runtimeInfo = `${runtimeInfo}|${platform}`; } for (const { platform: p = "" } of options.additionalDriverInfo) { if (p.length > 0) { runtimeInfo = `${runtimeInfo}|${p}`; } } if (!metadataDocument.ifItFitsItSits("platform", runtimeInfo)) { throw new error_1.MongoInvalidArgumentError("Unable to include driverInfo platform, metadata cannot exceed 512 bytes"); } const osInfo = (/* @__PURE__ */ new Map()).set("name", process2.platform).set("architecture", process2.arch).set("version", os.release()).set("type", os.type()); if (!metadataDocument.ifItFitsItSits("os", osInfo)) { for (const key of osInfo.keys()) { osInfo.delete(key); if (osInfo.size === 0) break; if (metadataDocument.ifItFitsItSits("os", osInfo)) break; } } const faasEnv = getFAASEnv(); if (faasEnv != null) { if (!metadataDocument.ifItFitsItSits("env", faasEnv)) { for (const key of faasEnv.keys()) { faasEnv.delete(key); if (faasEnv.size === 0) break; if (metadataDocument.ifItFitsItSits("env", faasEnv)) break; } } } return metadataDocument.toObject(); } var dockerPromise; async function getContainerMetadata() { const containerMetadata = {}; dockerPromise ??= (0, utils_1.fileIsAccessible)("/.dockerenv"); const isDocker = await dockerPromise; const { KUBERNETES_SERVICE_HOST = "" } = process2.env; const isKubernetes = KUBERNETES_SERVICE_HOST.length > 0 ? true : false; if (isDocker) containerMetadata.runtime = "docker"; if (isKubernetes) containerMetadata.orchestrator = "kubernetes"; return containerMetadata; } async function addContainerMetadata(originalMetadata) { const containerMetadata = await getContainerMetadata(); if (Object.keys(containerMetadata).length === 0) return originalMetadata; const extendedMetadata = new LimitedSizeDocument(512); const extendedEnvMetadata = { ...originalMetadata?.env, container: containerMetadata }; for (const [key, val] of Object.entries(originalMetadata)) { if (key !== "env") { extendedMetadata.ifItFitsItSits(key, val); } else { if (!extendedMetadata.ifItFitsItSits("env", extendedEnvMetadata)) { extendedMetadata.ifItFitsItSits("env", val); } } } if (!("env" in originalMetadata)) { extendedMetadata.ifItFitsItSits("env", extendedEnvMetadata); } return extendedMetadata.toObject(); } function getFAASEnv() { const { AWS_EXECUTION_ENV = "", AWS_LAMBDA_RUNTIME_API = "", FUNCTIONS_WORKER_RUNTIME = "", K_SERVICE = "", FUNCTION_NAME = "", VERCEL = "", AWS_LAMBDA_FUNCTION_MEMORY_SIZE = "", AWS_REGION = "", FUNCTION_MEMORY_MB = "", FUNCTION_REGION = "", FUNCTION_TIMEOUT_SEC = "", VERCEL_REGION = "" } = process2.env; const isAWSFaaS = AWS_EXECUTION_ENV.startsWith("AWS_Lambda_") || AWS_LAMBDA_RUNTIME_API.length > 0; const isAzureFaaS = FUNCTIONS_WORKER_RUNTIME.length > 0; const isGCPFaaS = K_SERVICE.length > 0 || FUNCTION_NAME.length > 0; const isVercelFaaS = VERCEL.length > 0; const faasEnv = /* @__PURE__ */ new Map(); if (isVercelFaaS && !(isAzureFaaS || isGCPFaaS)) { if (VERCEL_REGION.length > 0) { faasEnv.set("region", VERCEL_REGION); } faasEnv.set("name", "vercel"); return faasEnv; } if (isAWSFaaS && !(isAzureFaaS || isGCPFaaS || isVercelFaaS)) { if (AWS_REGION.length > 0) { faasEnv.set("region", AWS_REGION); } if (AWS_LAMBDA_FUNCTION_MEMORY_SIZE.length > 0 && Number.isInteger(+AWS_LAMBDA_FUNCTION_MEMORY_SIZE)) { faasEnv.set("memory_mb", new bson_1.Int32(AWS_LAMBDA_FUNCTION_MEMORY_SIZE)); } faasEnv.set("name", "aws.lambda"); return faasEnv; } if (isAzureFaaS && !(isGCPFaaS || isAWSFaaS || isVercelFaaS)) { faasEnv.set("name", "azure.func"); return faasEnv; } if (isGCPFaaS && !(isAzureFaaS || isAWSFaaS || isVercelFaaS)) { if (FUNCTION_REGION.length > 0) { faasEnv.set("region", FUNCTION_REGION); } if (FUNCTION_MEMORY_MB.length > 0 && Number.isInteger(+FUNCTION_MEMORY_MB)) { faasEnv.set("memory_mb", new bson_1.Int32(FUNCTION_MEMORY_MB)); } if (FUNCTION_TIMEOUT_SEC.length > 0 && Number.isInteger(+FUNCTION_TIMEOUT_SEC)) { faasEnv.set("timeout_sec", new bson_1.Int32(FUNCTION_TIMEOUT_SEC)); } faasEnv.set("name", "gcp.func"); return faasEnv; } return null; } function getRuntimeInfo() { if ("Deno" in globalThis) { const version = typeof Deno?.version?.deno === "string" ? Deno?.version?.deno : "0.0.0-unknown"; return `Deno v${version}, ${os.endianness()}`; } if ("Bun" in globalThis) { const version = typeof Bun?.version === "string" ? Bun?.version : "0.0.0-unknown"; return `Bun v${version}, ${os.endianness()}`; } return `Node.js ${process2.version}, ${os.endianness()}`; } } }); // netlify/functions/node_modules/webidl-conversions/lib/index.js var require_lib = __commonJS({ "netlify/functions/node_modules/webidl-conversions/lib/index.js"(exports2) { "use strict"; function makeException(ErrorType, message, options) { if (options.globals) { ErrorType = options.globals[ErrorType.name]; } return new ErrorType(`${options.context ? options.context : "Value"} ${message}.`); } function toNumber(value, options) { if (typeof value === "bigint") { throw makeException(TypeError, "is a BigInt which cannot be converted to a number", options); } if (!options.globals) { return Number(value); } return options.globals.Number(value); } function evenRound(x) { if (x > 0 && x % 1 === 0.5 && (x & 1) === 0 || x < 0 && x % 1 === -0.5 && (x & 1) === 1) { return censorNegativeZero(Math.floor(x)); } return censorNegativeZero(Math.round(x)); } function integerPart(n) { return censorNegativeZero(Math.trunc(n)); } function sign(x) { return x < 0 ? -1 : 1; } function modulo(x, y) { const signMightNotMatch = x % y; if (sign(y) !== sign(signMightNotMatch)) { return signMightNotMatch + y; } return signMightNotMatch; } function censorNegativeZero(x) { return x === 0 ? 0 : x; } function createIntegerConversion(bitLength, { unsigned }) { let lowerBound, upperBound; if (unsigned) { lowerBound = 0; upperBound = 2 ** bitLength - 1; } else { lowerBound = -(2 ** (bitLength - 1)); upperBound = 2 ** (bitLength - 1) - 1; } const twoToTheBitLength = 2 ** bitLength; const twoToOneLessThanTheBitLength = 2 ** (bitLength - 1); return (value, options = {}) => { let x = toNumber(value, options); x = censorNegativeZero(x); if (options.enforceRange) { if (!Number.isFinite(x)) { throw makeException(TypeError, "is not a finite number", options); } x = integerPart(x); if (x < lowerBound || x > upperBound) { throw makeException( TypeError, `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`, options ); } return x; } if (!Number.isNaN(x) && options.clamp) { x = Math.min(Math.max(x, lowerBound), upperBound); x = evenRound(x); return x; } if (!Number.isFinite(x) || x === 0) { return 0; } x = integerPart(x); if (x >= lowerBound && x <= upperBound) { return x; } x = modulo(x, twoToTheBitLength); if (!unsigned && x >= twoToOneLessThanTheBitLength) { return x - twoToTheBitLength; } return x; }; } function createLongLongConversion(bitLength, { unsigned }) { const upperBound = Number.MAX_SAFE_INTEGER; const lowerBound = unsigned ? 0 : Number.MIN_SAFE_INTEGER; const asBigIntN = unsigned ? BigInt.asUintN : BigInt.asIntN; return (value, options = {}) => { let x = toNumber(value, options); x = censorNegativeZero(x); if (options.enforceRange) { if (!Number.isFinite(x)) { throw makeException(TypeError, "is not a finite number", options); } x = integerPart(x); if (x < lowerBound || x > upperBound) { throw makeException( TypeError, `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`, options ); } return x; } if (!Number.isNaN(x) && options.clamp) { x = Math.min(Math.max(x, lowerBound), upperBound); x = evenRound(x); return x; } if (!Number.isFinite(x) || x === 0) { return 0; } let xBigInt = BigInt(integerPart(x)); xBigInt = asBigIntN(bitLength, xBigInt); return Number(xBigInt); }; } exports2.any = (value) => { return value; }; exports2.undefined = () => { return void 0; }; exports2.boolean = (value) => { return Boolean(value); }; exports2.byte = createIntegerConversion(8, { unsigned: false }); exports2.octet = createIntegerConversion(8, { unsigned: true }); exports2.short = createIntegerConversion(16, { unsigned: false }); exports2["unsigned short"] = createIntegerConversion(16, { unsigned: true }); exports2.long = createIntegerConversion(32, { unsigned: false }); exports2["unsigned long"] = createIntegerConversion(32, { unsigned: true }); exports2["long long"] = createLongLongConversion(64, { unsigned: false }); exports2["unsigned long long"] = createLongLongConversion(64, { unsigned: true }); exports2.double = (value, options = {}) => { const x = toNumber(value, options); if (!Number.isFinite(x)) { throw makeException(TypeError, "is not a finite floating-point value", options); } return x; }; exports2["unrestricted double"] = (value, options = {}) => { const x = toNumber(value, options); return x; }; exports2.float = (value, options = {}) => { const x = toNumber(value, options); if (!Number.isFinite(x)) { throw makeException(TypeError, "is not a finite floating-point value", options); } if (Object.is(x, -0)) { return x; } const y = Math.fround(x); if (!Number.isFinite(y)) { throw makeException(TypeError, "is outside the range of a single-precision floating-point value", options); } return y; }; exports2["unrestricted float"] = (value, options = {}) => { const x = toNumber(value, options); if (isNaN(x)) { return x; } if (Object.is(x, -0)) { return x; } return Math.fround(x); }; exports2.DOMString = (value, options = {}) => { if (options.treatNullAsEmptyString && value === null) { return ""; } if (typeof value === "symbol") { throw makeException(TypeError, "is a symbol, which cannot be converted to a string", options); } const StringCtor = options.globals ? options.globals.String : String; return StringCtor(value); }; exports2.ByteString = (value, options = {}) => { const x = exports2.DOMString(value, options); let c; for (let i = 0; (c = x.codePointAt(i)) !== void 0; ++i) { if (c > 255) { throw makeException(TypeError, "is not a valid ByteString", options); } } return x; }; exports2.USVString = (value, options = {}) => { const S = exports2.DOMString(value, options); const n = S.length; const U = []; for (let i = 0; i < n; ++i) { const c = S.charCodeAt(i); if (c < 55296 || c > 57343) { U.push(String.fromCodePoint(c)); } else if (56320 <= c && c <= 57343) { U.push(String.fromCodePoint(65533)); } else if (i === n - 1) { U.push(String.fromCodePoint(65533)); } else { const d = S.charCodeAt(i + 1); if (56320 <= d && d <= 57343) { const a = c & 1023; const b = d & 1023; U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b)); ++i; } else { U.push(String.fromCodePoint(65533)); } } } return U.join(""); }; exports2.object = (value, options = {}) => { if (value === null || typeof value !== "object" && typeof value !== "function") { throw makeException(TypeError, "is not an object", options); } return value; }; var abByteLengthGetter = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get; var sabByteLengthGetter = typeof SharedArrayBuffer === "function" ? Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, "byteLength").get : null; function isNonSharedArrayBuffer(value) { try { abByteLengthGetter.call(value); return true; } catch { return false; } } function isSharedArrayBuffer(value) { try { sabByteLengthGetter.call(value); return true; } catch { return false; } } function isArrayBufferDetached(value) { try { new Uint8Array(value); return false; } catch { return true; } } exports2.ArrayBuffer = (value, options = {}) => { if (!isNonSharedArrayBuffer(value)) { if (options.allowShared && !isSharedArrayBuffer(value)) { throw makeException(TypeError, "is not an ArrayBuffer or SharedArrayBuffer", options); } throw makeException(TypeError, "is not an ArrayBuffer", options); } if (isArrayBufferDetached(value)) { throw makeException(TypeError, "is a detached ArrayBuffer", options); } return value; }; var dvByteLengthGetter = Object.getOwnPropertyDescriptor(DataView.prototype, "byteLength").get; exports2.DataView = (value, options = {}) => { try { dvByteLengthGetter.call(value); } catch (e) { throw makeException(TypeError, "is not a DataView", options); } if (!options.allowShared && isSharedArrayBuffer(value.buffer)) { throw makeException(TypeError, "is backed by a SharedArrayBuffer, which is not allowed", options); } if (isArrayBufferDetached(value.buffer)) { throw makeException(TypeError, "is backed by a detached ArrayBuffer", options); } return value; }; var typedArrayNameGetter = Object.getOwnPropertyDescriptor( Object.getPrototypeOf(Uint8Array).prototype, Symbol.toStringTag ).get; [ Int8Array, Int16Array, Int32Array, Uint8Array, Uint16Array, Uint32Array, Uint8ClampedArray, Float32Array, Float64Array ].forEach((func) => { const { name } = func; const article = /^[AEIOU]/u.test(name) ? "an" : "a"; exports2[name] = (value, options = {}) => { if (!ArrayBuffer.isView(value) || typedArrayNameGetter.call(value) !== name) { throw makeException(TypeError, `is not ${article} ${name} object`, options); } if (!options.allowShared && isSharedArrayBuffer(value.buffer)) { throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", options); } if (isArrayBufferDetached(value.buffer)) { throw makeException(TypeError, "is a view on a detached ArrayBuffer", options); } return value; }; }); exports2.ArrayBufferView = (value, options = {}) => { if (!ArrayBuffer.isView(value)) { throw makeException(TypeError, "is not a view on an ArrayBuffer or SharedArrayBuffer", options); } if (!options.allowShared && isSharedArrayBuffer(value.buffer)) { throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", options); } if (isArrayBufferDetached(value.buffer)) { throw makeException(TypeError, "is a view on a detached ArrayBuffer", options); } return value; }; exports2.BufferSource = (value, options = {}) => { if (ArrayBuffer.isView(value)) { if (!options.allowShared && isSharedArrayBuffer(value.buffer)) { throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", options); } if (isArrayBufferDetached(value.buffer)) { throw makeException(TypeError, "is a view on a detached ArrayBuffer", options); } return value; } if (!options.allowShared && !isNonSharedArrayBuffer(value)) { throw makeException(TypeError, "is not an ArrayBuffer or a view on one", options); } if (options.allowShared && !isSharedArrayBuffer(value) && !isNonSharedArrayBuffer(value)) { throw makeException(TypeError, "is not an ArrayBuffer, SharedArrayBuffer, or a view on one", options); } if (isArrayBufferDetached(value)) { throw makeException(TypeError, "is a detached ArrayBuffer", options); } return value; }; exports2.DOMTimeStamp = exports2["unsigned long long"]; } }); // netlify/functions/node_modules/whatwg-url/lib/utils.js var require_utils2 = __commonJS({ "netlify/functions/node_modules/whatwg-url/lib/utils.js"(exports2, module2) { "use strict"; function isObject(value) { return typeof value === "object" && value !== null || typeof value === "function"; } var hasOwn = Function.prototype.call.bind(Object.prototype.hasOwnProperty); function define2(target, source) { for (const key of Reflect.ownKeys(source)) { const descriptor = Reflect.getOwnPropertyDescriptor(source, key); if (descriptor && !Reflect.defineProperty(target, key, descriptor)) { throw new TypeError(`Cannot redefine property: ${String(key)}`); } } } function newObjectInRealm(globalObject, object) { const ctorRegistry = initCtorRegistry(globalObject); return Object.defineProperties( Object.create(ctorRegistry["%Object.prototype%"]), Object.getOwnPropertyDescriptors(object) ); } var wrapperSymbol = Symbol("wrapper"); var implSymbol = Symbol("impl"); var sameObjectCaches = Symbol("SameObject caches"); var ctorRegistrySymbol = Symbol.for("[webidl2js] constructor registry"); var AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype); function initCtorRegistry(globalObject) { if (hasOwn(globalObject, ctorRegistrySymbol)) { return globalObject[ctorRegistrySymbol]; } const ctorRegistry = /* @__PURE__ */ Object.create(null); ctorRegistry["%Object.prototype%"] = globalObject.Object.prototype; ctorRegistry["%IteratorPrototype%"] = Object.getPrototypeOf( Object.getPrototypeOf(new globalObject.Array()[Symbol.iterator]()) ); try { ctorRegistry["%AsyncIteratorPrototype%"] = Object.getPrototypeOf( Object.getPrototypeOf( globalObject.eval("(async function* () {})").prototype ) ); } catch { ctorRegistry["%AsyncIteratorPrototype%"] = AsyncIteratorPrototype; } globalObject[ctorRegistrySymbol] = ctorRegistry; return ctorRegistry; } function getSameObject(wrapper, prop, creator) { if (!wrapper[sameObjectCaches]) { wrapper[sameObjectCaches] = /* @__PURE__ */ Object.create(null); } if (prop in wrapper[sameObjectCaches]) { return wrapper[sameObjectCaches][prop]; } wrapper[sameObjectCaches][prop] = creator(); return wrapper[sameObjectCaches][prop]; } function wrapperForImpl(impl) { return impl ? impl[wrapperSymbol] : null; } function implForWrapper(wrapper) { return wrapper ? wrapper[implSymbol] : null; } function tryWrapperForImpl(impl) { const wrapper = wrapperForImpl(impl); return wrapper ? wrapper : impl; } function tryImplForWrapper(wrapper) { const impl = implForWrapper(wrapper); return impl ? impl : wrapper; } var iterInternalSymbol = Symbol("internal"); function isArrayIndexPropName(P) { if (typeof P !== "string") { return false; } const i = P >>> 0; if (i === 2 ** 32 - 1) { return false; } const s = `${i}`; if (P !== s) { return false; } return true; } var byteLengthGetter = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get; function isArrayBuffer(value) { try { byteLengthGetter.call(value); return true; } catch (e) { return false; } } function iteratorResult([key, value], kind) { let result; switch (kind) { case "key": result = key; break; case "value": result = value; break; case "key+value": result = [key, value]; break; } return { value: result, done: false }; } var supportsPropertyIndex = Symbol("supports property index"); var supportedPropertyIndices = Symbol("supported property indices"); var supportsPropertyName = Symbol("supports property name"); var supportedPropertyNames = Symbol("supported property names"); var indexedGet = Symbol("indexed property get"); var indexedSetNew = Symbol("indexed property set new"); var indexedSetExisting = Symbol("indexed property set existing"); var namedGet = Symbol("named property get"); var namedSetNew = Symbol("named property set new"); var namedSetExisting = Symbol("named property set existing"); var namedDelete = Symbol("named property delete"); var asyncIteratorNext = Symbol("async iterator get the next iteration result"); var asyncIteratorReturn = Symbol("async iterator return steps"); var asyncIteratorInit = Symbol("async iterator initialization steps"); var asyncIteratorEOI = Symbol("async iterator end of iteration"); module2.exports = exports2 = { isObject, hasOwn, define: define2, newObjectInRealm, wrapperSymbol, implSymbol, getSameObject, ctorRegistrySymbol, initCtorRegistry, wrapperForImpl, implForWrapper, tryWrapperForImpl, tryImplForWrapper, iterInternalSymbol, isArrayBuffer, isArrayIndexPropName, supportsPropertyIndex, supportedPropertyIndices, supportsPropertyName, supportedPropertyNames, indexedGet, indexedSetNew, indexedSetExisting, namedGet, namedSetNew, namedSetExisting, namedDelete, asyncIteratorNext, asyncIteratorReturn, asyncIteratorInit, asyncIteratorEOI, iteratorResult }; } }); // netlify/functions/node_modules/punycode/punycode.js var require_punycode = __commonJS({ "netlify/functions/node_modules/punycode/punycode.js"(exports2, module2) { "use strict"; var maxInt = 2147483647; var base = 36; var tMin = 1; var tMax = 26; var skew = 38; var damp = 700; var initialBias = 72; var initialN = 128; var delimiter = "-"; var regexPunycode = /^xn--/; var regexNonASCII = /[^\0-\x7F]/; var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; var errors = { "overflow": "Overflow: input needs wider integers to process", "not-basic": "Illegal input >= 0x80 (not a basic code point)", "invalid-input": "Invalid input" }; var baseMinusTMin = base - tMin; var floor = Math.floor; var stringFromCharCode = String.fromCharCode; function error(type) { throw new RangeError(errors[type]); } function map(array, callback) { const result = []; let length = array.length; while (length--) { result[length] = callback(array[length]); } return result; } function mapDomain(domain, callback) { const parts = domain.split("@"); let result = ""; if (parts.length > 1) { result = parts[0] + "@"; domain = parts[1]; } domain = domain.replace(regexSeparators, "."); const labels = domain.split("."); const encoded = map(labels, callback).join("."); return result + encoded; } function ucs2decode(string) { const output = []; let counter = 0; const length = string.length; while (counter < length) { const value = string.charCodeAt(counter++); if (value >= 55296 && value <= 56319 && counter < length) { const extra = string.charCodeAt(counter++); if ((extra & 64512) == 56320) { output.push(((value & 1023) << 10) + (extra & 1023) + 65536); } else { output.push(value); counter--; } } else { output.push(value); } } return output; } var ucs2encode = (codePoints) => String.fromCodePoint(...codePoints); var basicToDigit = function(codePoint) { if (codePoint >= 48 && codePoint < 58) { return 26 + (codePoint - 48); } if (codePoint >= 65 && codePoint < 91) { return codePoint - 65; } if (codePoint >= 97 && codePoint < 123) { return codePoint - 97; } return base; }; var digitToBasic = function(digit, flag) { return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); }; var adapt = function(delta, numPoints, firstTime) { let k = 0; delta = firstTime ? floor(delta / damp) : delta >> 1; delta += floor(delta / numPoints); for (; delta > baseMinusTMin * tMax >> 1; k += base) { delta = floor(delta / baseMinusTMin); } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); }; var decode = function(input) { const output = []; const inputLength = input.length; let i = 0; let n = initialN; let bias = initialBias; let basic = input.lastIndexOf(delimiter); if (basic < 0) { basic = 0; } for (let j = 0; j < basic; ++j) { if (input.charCodeAt(j) >= 128) { error("not-basic"); } output.push(input.charCodeAt(j)); } for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; ) { const oldi = i; for (let w = 1, k = base; ; k += base) { if (index >= inputLength) { error("invalid-input"); } const digit = basicToDigit(input.charCodeAt(index++)); if (digit >= base) { error("invalid-input"); } if (digit > floor((maxInt - i) / w)) { error("overflow"); } i += digit * w; const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; if (digit < t) { break; } const baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error("overflow"); } w *= baseMinusT; } const out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0); if (floor(i / out) > maxInt - n) { error("overflow"); } n += floor(i / out); i %= out; output.splice(i++, 0, n); } return String.fromCodePoint(...output); }; var encode = function(input) { const output = []; input = ucs2decode(input); const inputLength = input.length; let n = initialN; let delta = 0; let bias = initialBias; for (const currentValue of input) { if (currentValue < 128) { output.push(stringFromCharCode(currentValue)); } } const basicLength = output.length; let handledCPCount = basicLength; if (basicLength) { output.push(delimiter); } while (handledCPCount < inputLength) { let m = maxInt; for (const currentValue of input) { if (currentValue >= n && currentValue < m) { m = currentValue; } } const handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error("overflow"); } delta += (m - n) * handledCPCountPlusOne; n = m; for (const currentValue of input) { if (currentValue < n && ++delta > maxInt) { error("overflow"); } if (currentValue === n) { let q = delta; for (let k = base; ; k += base) { const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; if (q < t) { break; } const qMinusT = q - t; const baseMinusT = base - t; output.push( stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) ); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength); delta = 0; ++handledCPCount; } } ++delta; ++n; } return output.join(""); }; var toUnicode = function(input) { return mapDomain(input, function(string) { return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; }); }; var toASCII = function(input) { return mapDomain(input, function(string) { return regexNonASCII.test(string) ? "xn--" + encode(string) : string; }); }; var punycode = { /** * A string representing the current Punycode.js version number. * @memberOf punycode * @type String */ "version": "2.3.1", /** * An object of methods to convert from JavaScript's internal character * representation (UCS-2) to Unicode code points, and back. * @see * @memberOf punycode * @type Object */ "ucs2": { "decode": ucs2decode, "encode": ucs2encode }, "decode": decode, "encode": encode, "toASCII": toASCII, "toUnicode": toUnicode }; module2.exports = punycode; } }); // netlify/functions/node_modules/tr46/lib/regexes.js var require_regexes = __commonJS({ "netlify/functions/node_modules/tr46/lib/regexes.js"(exports2, module2) { "use strict"; var combiningMarks = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10D69}-\u{10D6D}\u{10EAB}\u{10EAC}\u{10EFC}-\u{10EFF}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11000}-\u{11002}\u{11038}-\u{11046}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11082}\u{110B0}-\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{11134}\u{11145}\u{11146}\u{11173}\u{11180}-\u{11182}\u{111B3}-\u{111C0}\u{111C9}-\u{111CC}\u{111CE}\u{111CF}\u{1122C}-\u{11237}\u{1123E}\u{11241}\u{112DF}-\u{112EA}\u{11300}-\u{11303}\u{1133B}\u{1133C}\u{1133E}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11357}\u{11362}\u{11363}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{113B8}-\u{113C0}\u{113C2}\u{113C5}\u{113C7}-\u{113CA}\u{113CC}-\u{113D0}\u{113D2}\u{113E1}\u{113E2}\u{11435}-\u{11446}\u{1145E}\u{114B0}-\u{114C3}\u{115AF}-\u{115B5}\u{115B8}-\u{115C0}\u{115DC}\u{115DD}\u{11630}-\u{11640}\u{116AB}-\u{116B7}\u{1171D}-\u{1172B}\u{1182C}-\u{1183A}\u{11930}-\u{11935}\u{11937}\u{11938}\u{1193B}-\u{1193E}\u{11940}\u{11942}\u{11943}\u{119D1}-\u{119D7}\u{119DA}-\u{119E0}\u{119E4}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A39}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A5B}\u{11A8A}-\u{11A99}\u{11C2F}-\u{11C36}\u{11C38}-\u{11C3F}\u{11C92}-\u{11CA7}\u{11CA9}-\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D8A}-\u{11D8E}\u{11D90}\u{11D91}\u{11D93}-\u{11D97}\u{11EF3}-\u{11EF6}\u{11F00}\u{11F01}\u{11F03}\u{11F34}-\u{11F3A}\u{11F3E}-\u{11F42}\u{11F5A}\u{13440}\u{13447}-\u{13455}\u{1611E}-\u{1612F}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F51}-\u{16F87}\u{16F8F}-\u{16F92}\u{16FE4}\u{16FF0}\u{16FF1}\u{1BC9D}\u{1BC9E}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D165}-\u{1D169}\u{1D16D}-\u{1D172}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E08F}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E4EC}-\u{1E4EF}\u{1E5EE}\u{1E5EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]/u; var combiningClassVirama = /[\u094D\u09CD\u0A4D\u0ACD\u0B4D\u0BCD\u0C4D\u0CCD\u0D3B\u0D3C\u0D4D\u0DCA\u0E3A\u0EBA\u0F84\u1039\u103A\u1714\u1715\u1734\u17D2\u1A60\u1B44\u1BAA\u1BAB\u1BF2\u1BF3\u2D7F\uA806\uA82C\uA8C4\uA953\uA9C0\uAAF6\uABED\u{10A3F}\u{11046}\u{11070}\u{1107F}\u{110B9}\u{11133}\u{11134}\u{111C0}\u{11235}\u{112EA}\u{1134D}\u{113CE}-\u{113D0}\u{11442}\u{114C2}\u{115BF}\u{1163F}\u{116B6}\u{1172B}\u{11839}\u{1193D}\u{1193E}\u{119E0}\u{11A34}\u{11A47}\u{11A99}\u{11C3F}\u{11D44}\u{11D45}\u{11D97}\u{11F41}\u{11F42}\u{1612F}]/u; var validZWNJ = /[\u0620\u0626\u0628\u062A-\u062E\u0633-\u063F\u0641-\u0647\u0649\u064A\u066E\u066F\u0678-\u0687\u069A-\u06BF\u06C1\u06C2\u06CC\u06CE\u06D0\u06D1\u06FA-\u06FC\u06FF\u0712-\u0714\u071A-\u071D\u071F-\u0727\u0729\u072B\u072D\u072E\u074E-\u0758\u075C-\u076A\u076D-\u0770\u0772\u0775-\u0777\u077A-\u077F\u07CA-\u07EA\u0841-\u0845\u0848\u084A-\u0853\u0855\u0860\u0862-\u0865\u0868\u0886\u0889-\u088D\u08A0-\u08A9\u08AF\u08B0\u08B3-\u08B8\u08BA-\u08C8\u1807\u1820-\u1878\u1887-\u18A8\u18AA\uA840-\uA872\u{10AC0}-\u{10AC4}\u{10ACD}\u{10AD3}-\u{10ADC}\u{10ADE}-\u{10AE0}\u{10AEB}-\u{10AEE}\u{10B80}\u{10B82}\u{10B86}-\u{10B88}\u{10B8A}\u{10B8B}\u{10B8D}\u{10B90}\u{10BAD}\u{10BAE}\u{10D00}-\u{10D21}\u{10D23}\u{10EC3}\u{10EC4}\u{10F30}-\u{10F32}\u{10F34}-\u{10F44}\u{10F51}-\u{10F53}\u{10F70}-\u{10F73}\u{10F76}-\u{10F81}\u{10FB0}\u{10FB2}\u{10FB3}\u{10FB8}\u{10FBB}\u{10FBC}\u{10FBE}\u{10FBF}\u{10FC1}\u{10FC4}\u{10FCA}\u{10FCB}\u{1E900}-\u{1E943}][\xAD\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u061C\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u070F\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3C\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CBF\u0CC6\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732\u1733\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DFF\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA82C\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFEFF\uFFF9-\uFFFB\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10D69}-\u{10D6D}\u{10EAB}\u{10EAC}\u{10EFC}-\u{10EFF}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11001}\u{11038}-\u{11046}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{11241}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{113BB}-\u{113C0}\u{113CE}\u{113D0}\u{113D2}\u{113E1}\u{113E2}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C3F}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{11F00}\u{11F01}\u{11F36}-\u{11F3A}\u{11F40}\u{11F42}\u{11F5A}\u{13430}-\u{13440}\u{13447}-\u{13455}\u{1611E}-\u{16129}\u{1612D}-\u{1612F}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E08F}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E4EC}-\u{1E4EF}\u{1E5EE}\u{1E5EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94B}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*\u200C[\xAD\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u061C\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u070F\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3C\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CBF\u0CC6\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732\u1733\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DFF\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA82C\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFEFF\uFFF9-\uFFFB\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10D69}-\u{10D6D}\u{10EAB}\u{10EAC}\u{10EFC}-\u{10EFF}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11001}\u{11038}-\u{11046}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{11241}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{113BB}-\u{113C0}\u{113CE}\u{113D0}\u{113D2}\u{113E1}\u{113E2}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C3F}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{11F00}\u{11F01}\u{11F36}-\u{11F3A}\u{11F40}\u{11F42}\u{11F5A}\u{13430}-\u{13440}\u{13447}-\u{13455}\u{1611E}-\u{16129}\u{1612D}-\u{1612F}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E08F}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E4EC}-\u{1E4EF}\u{1E5EE}\u{1E5EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94B}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*[\u0620\u0622-\u063F\u0641-\u064A\u066E\u066F\u0671-\u0673\u0675-\u06D3\u06D5\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u077F\u07CA-\u07EA\u0840-\u0858\u0860\u0862-\u0865\u0867-\u086A\u0870-\u0882\u0886\u0889-\u088E\u08A0-\u08AC\u08AE-\u08C8\u1807\u1820-\u1878\u1887-\u18A8\u18AA\uA840-\uA871\u{10AC0}-\u{10AC5}\u{10AC7}\u{10AC9}\u{10ACA}\u{10ACE}-\u{10AD6}\u{10AD8}-\u{10AE1}\u{10AE4}\u{10AEB}-\u{10AEF}\u{10B80}-\u{10B91}\u{10BA9}-\u{10BAE}\u{10D01}-\u{10D23}\u{10EC2}-\u{10EC4}\u{10F30}-\u{10F44}\u{10F51}-\u{10F54}\u{10F70}-\u{10F81}\u{10FB0}\u{10FB2}-\u{10FB6}\u{10FB8}-\u{10FBF}\u{10FC1}-\u{10FC4}\u{10FC9}\u{10FCA}\u{1E900}-\u{1E943}]/u; var bidiDomain = /[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0600-\u0605\u0608\u060B\u060D\u061B-\u064A\u0660-\u0669\u066B-\u066F\u0671-\u06D5\u06DD\u06E5\u06E6\u06EE\u06EF\u06FA-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u0870-\u088E\u0890\u0891\u08A0-\u08C9\u08E2\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10D30}-\u{10D39}\u{10D40}-\u{10D65}\u{10D6F}-\u{10D85}\u{10D8E}\u{10D8F}\u{10E60}-\u{10E7E}\u{10E80}-\u{10EA9}\u{10EAD}\u{10EB0}\u{10EB1}\u{10EC2}-\u{10EC4}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10F70}-\u{10F81}\u{10F86}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}]/u; var bidiS1LTR = /[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02BB-\u02C1\u02D0\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0482\u048A-\u052F\u0531-\u0556\u0559-\u0589\u0903-\u0939\u093B\u093D-\u0940\u0949-\u094C\u094E-\u0950\u0958-\u0961\u0964-\u0980\u0982\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD-\u09C0\u09C7\u09C8\u09CB\u09CC\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09FA\u09FC\u09FD\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3E-\u0A40\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A76\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD-\u0AC0\u0AC9\u0ACB\u0ACC\u0AD0\u0AE0\u0AE1\u0AE6-\u0AF0\u0AF9\u0B02\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B3E\u0B40\u0B47\u0B48\u0B4B\u0B4C\u0B57\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE\u0BBF\u0BC1\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCC\u0BD0\u0BD7\u0BE6-\u0BF2\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C41-\u0C44\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C66-\u0C6F\u0C77\u0C7F\u0C80\u0C82-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD-\u0CC4\u0CC6-\u0CC8\u0CCA\u0CCB\u0CD5\u0CD6\u0CDD\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1-\u0CF3\u0D02-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D40\u0D46-\u0D48\u0D4A-\u0D4C\u0D4E\u0D4F\u0D54-\u0D61\u0D66-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCF-\u0DD1\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E4F-\u0E5B\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F17\u0F1A-\u0F34\u0F36\u0F38\u0F3E-\u0F47\u0F49-\u0F6C\u0F7F\u0F85\u0F88-\u0F8C\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FDA\u1000-\u102C\u1031\u1038\u103B\u103C\u103F-\u1057\u105A-\u105D\u1061-\u1070\u1075-\u1081\u1083\u1084\u1087-\u108C\u108E-\u109C\u109E-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1360-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u167F\u1681-\u169A\u16A0-\u16F8\u1700-\u1711\u1715\u171F-\u1731\u1734-\u1736\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17B6\u17BE-\u17C5\u17C7\u17C8\u17D4-\u17DA\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1923-\u1926\u1929-\u192B\u1930\u1931\u1933-\u1938\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A19\u1A1A\u1A1E-\u1A55\u1A57\u1A61\u1A63\u1A64\u1A6D-\u1A72\u1A80-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1B04-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B4C\u1B4E-\u1B6A\u1B74-\u1B7F\u1B82-\u1BA1\u1BA6\u1BA7\u1BAA\u1BAE-\u1BE5\u1BE7\u1BEA-\u1BEC\u1BEE\u1BF2\u1BF3\u1BFC-\u1C2B\u1C34\u1C35\u1C3B-\u1C49\u1C4D-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD3\u1CE1\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5-\u1CF7\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200E\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u214F\u2160-\u2188\u2336-\u237A\u2395\u249C-\u24E9\u26AC\u2800-\u28FF\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u302E\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31BF\u31F0-\u321C\u3220-\u324F\u3260-\u327B\u327F-\u32B0\u32C0-\u32CB\u32D0-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA60C\uA610-\uA62B\uA640-\uA66E\uA680-\uA69D\uA6A0-\uA6EF\uA6F2-\uA6F7\uA722-\uA787\uA789-\uA7CD\uA7D0\uA7D1\uA7D3\uA7D5-\uA7DC\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA824\uA827\uA830-\uA837\uA840-\uA873\uA880-\uA8C3\uA8CE-\uA8D9\uA8F2-\uA8FE\uA900-\uA925\uA92E-\uA946\uA952\uA953\uA95F-\uA97C\uA983-\uA9B2\uA9B4\uA9B5\uA9BA\uA9BB\uA9BE-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA2F\uAA30\uAA33\uAA34\uAA40-\uAA42\uAA44-\uAA4B\uAA4D\uAA50-\uAA59\uAA5C-\uAA7B\uAA7D-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAAEB\uAAEE-\uAAF5\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB69\uAB70-\uABE4\uABE6\uABE7\uABE9-\uABEC\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1013F}\u{1018D}\u{1018E}\u{101D0}-\u{101FC}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{10375}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}-\u{1057A}\u{1057C}-\u{1058A}\u{1058C}-\u{10592}\u{10594}\u{10595}\u{10597}-\u{105A1}\u{105A3}-\u{105B1}\u{105B3}-\u{105B9}\u{105BB}\u{105BC}\u{105C0}-\u{105F3}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{10780}-\u{10785}\u{10787}-\u{107B0}\u{107B2}-\u{107BA}\u{11000}\u{11002}-\u{11037}\u{11047}-\u{1104D}\u{11066}-\u{1106F}\u{11071}\u{11072}\u{11075}\u{11082}-\u{110B2}\u{110B7}\u{110B8}\u{110BB}-\u{110C1}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11103}-\u{11126}\u{1112C}\u{11136}-\u{11147}\u{11150}-\u{11172}\u{11174}-\u{11176}\u{11182}-\u{111B5}\u{111BF}-\u{111C8}\u{111CD}\u{111CE}\u{111D0}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1122E}\u{11232}\u{11233}\u{11235}\u{11238}-\u{1123D}\u{1123F}\u{11240}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112DE}\u{112E0}-\u{112E2}\u{112F0}-\u{112F9}\u{11302}\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133D}-\u{1133F}\u{11341}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11380}-\u{11389}\u{1138B}\u{1138E}\u{11390}-\u{113B5}\u{113B7}-\u{113BA}\u{113C2}\u{113C5}\u{113C7}-\u{113CA}\u{113CC}\u{113CD}\u{113CF}\u{113D1}\u{113D3}-\u{113D5}\u{113D7}\u{113D8}\u{11400}-\u{11437}\u{11440}\u{11441}\u{11445}\u{11447}-\u{1145B}\u{1145D}\u{1145F}-\u{11461}\u{11480}-\u{114B2}\u{114B9}\u{114BB}-\u{114BE}\u{114C1}\u{114C4}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B1}\u{115B8}-\u{115BB}\u{115BE}\u{115C1}-\u{115DB}\u{11600}-\u{11632}\u{1163B}\u{1163C}\u{1163E}\u{11641}-\u{11644}\u{11650}-\u{11659}\u{11680}-\u{116AA}\u{116AC}\u{116AE}\u{116AF}\u{116B6}\u{116B8}\u{116B9}\u{116C0}-\u{116C9}\u{116D0}-\u{116E3}\u{11700}-\u{1171A}\u{1171E}\u{11720}\u{11721}\u{11726}\u{11730}-\u{11746}\u{11800}-\u{1182E}\u{11838}\u{1183B}\u{118A0}-\u{118F2}\u{118FF}-\u{11906}\u{11909}\u{1190C}-\u{11913}\u{11915}\u{11916}\u{11918}-\u{11935}\u{11937}\u{11938}\u{1193D}\u{1193F}-\u{11942}\u{11944}-\u{11946}\u{11950}-\u{11959}\u{119A0}-\u{119A7}\u{119AA}-\u{119D3}\u{119DC}-\u{119DF}\u{119E1}-\u{119E4}\u{11A00}\u{11A07}\u{11A08}\u{11A0B}-\u{11A32}\u{11A39}\u{11A3A}\u{11A3F}-\u{11A46}\u{11A50}\u{11A57}\u{11A58}\u{11A5C}-\u{11A89}\u{11A97}\u{11A9A}-\u{11AA2}\u{11AB0}-\u{11AF8}\u{11B00}-\u{11B09}\u{11BC0}-\u{11BE1}\u{11BF0}-\u{11BF9}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C2F}\u{11C3E}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11CA9}\u{11CB1}\u{11CB4}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D30}\u{11D46}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D93}\u{11D94}\u{11D96}\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF2}\u{11EF5}-\u{11EF8}\u{11F02}-\u{11F10}\u{11F12}-\u{11F35}\u{11F3E}\u{11F3F}\u{11F41}\u{11F43}-\u{11F59}\u{11FB0}\u{11FC0}-\u{11FD4}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{12F90}-\u{12FF2}\u{13000}-\u{1343F}\u{13441}-\u{13446}\u{13460}-\u{143FA}\u{14400}-\u{14646}\u{16100}-\u{1611D}\u{1612A}-\u{1612C}\u{16130}-\u{16139}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}-\u{16ABE}\u{16AC0}-\u{16AC9}\u{16AD0}-\u{16AED}\u{16AF5}\u{16B00}-\u{16B2F}\u{16B37}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16D40}-\u{16D79}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F50}-\u{16F87}\u{16F93}-\u{16F9F}\u{16FE0}\u{16FE1}\u{16FE3}\u{16FF0}\u{16FF1}\u{17000}-\u{187F7}\u{18800}-\u{18CD5}\u{18CFF}-\u{18D08}\u{1AFF0}-\u{1AFF3}\u{1AFF5}-\u{1AFFB}\u{1AFFD}\u{1AFFE}\u{1B000}-\u{1B122}\u{1B132}\u{1B150}-\u{1B152}\u{1B155}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}\u{1BC9F}\u{1CCD6}-\u{1CCEF}\u{1CF50}-\u{1CFC3}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D166}\u{1D16A}-\u{1D172}\u{1D183}\u{1D184}\u{1D18C}-\u{1D1A9}\u{1D1AE}-\u{1D1E8}\u{1D2C0}-\u{1D2D3}\u{1D2E0}-\u{1D2F3}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D6C0}\u{1D6C2}-\u{1D6DA}\u{1D6DC}-\u{1D6FA}\u{1D6FC}-\u{1D714}\u{1D716}-\u{1D734}\u{1D736}-\u{1D74E}\u{1D750}-\u{1D76E}\u{1D770}-\u{1D788}\u{1D78A}-\u{1D7A8}\u{1D7AA}-\u{1D7C2}\u{1D7C4}-\u{1D7CB}\u{1D800}-\u{1D9FF}\u{1DA37}-\u{1DA3A}\u{1DA6D}-\u{1DA74}\u{1DA76}-\u{1DA83}\u{1DA85}-\u{1DA8B}\u{1DF00}-\u{1DF1E}\u{1DF25}-\u{1DF2A}\u{1E030}-\u{1E06D}\u{1E100}-\u{1E12C}\u{1E137}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E290}-\u{1E2AD}\u{1E2C0}-\u{1E2EB}\u{1E2F0}-\u{1E2F9}\u{1E4D0}-\u{1E4EB}\u{1E4F0}-\u{1E4F9}\u{1E5D0}-\u{1E5ED}\u{1E5F0}-\u{1E5FA}\u{1E5FF}\u{1E7E0}-\u{1E7E6}\u{1E7E8}-\u{1E7EB}\u{1E7ED}\u{1E7EE}\u{1E7F0}-\u{1E7FE}\u{1F110}-\u{1F12E}\u{1F130}-\u{1F169}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{20000}-\u{2A6DF}\u{2A700}-\u{2B739}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2EBF0}-\u{2EE5D}\u{2F800}-\u{2FA1D}\u{30000}-\u{3134A}\u{31350}-\u{323AF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/u; var bidiS1RTL = /[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0608\u060B\u060D\u061B-\u064A\u066D-\u066F\u0671-\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u0870-\u088E\u08A0-\u08C9\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10D4A}-\u{10D65}\u{10D6F}-\u{10D85}\u{10D8E}\u{10D8F}\u{10E80}-\u{10EA9}\u{10EAD}\u{10EB0}\u{10EB1}\u{10EC2}-\u{10EC4}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10F70}-\u{10F81}\u{10F86}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}]/u; var bidiS2 = /^[\0-\x08\x0E-\x1B!-@\[-`\{-\x84\x86-\xA9\xAB-\xB4\xB6-\xB9\xBB-\xBF\xD7\xF7\u02B9\u02BA\u02C2-\u02CF\u02D2-\u02DF\u02E5-\u02ED\u02EF-\u036F\u0374\u0375\u037E\u0384\u0385\u0387\u03F6\u0483-\u0489\u058A\u058D-\u058F\u0591-\u05C7\u05D0-\u05EA\u05EF-\u05F4\u0600-\u070D\u070F-\u074A\u074D-\u07B1\u07C0-\u07FA\u07FD-\u082D\u0830-\u083E\u0840-\u085B\u085E\u0860-\u086A\u0870-\u088E\u0890\u0891\u0897-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09F2\u09F3\u09FB\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AF1\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0BF3-\u0BFA\u0C00\u0C04\u0C3C\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C78-\u0C7E\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E3F\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0F18\u0F19\u0F35\u0F37\u0F39-\u0F3D\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1390-\u1399\u1400\u169B\u169C\u1712-\u1714\u1732\u1733\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DB\u17DD\u17F0-\u17F9\u1800-\u180F\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1940\u1944\u1945\u19DE-\u19FF\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DFF\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u200B-\u200D\u200F-\u2027\u202F-\u205E\u2060-\u2064\u206A-\u2070\u2074-\u207E\u2080-\u208E\u20A0-\u20C0\u20D0-\u20F0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u2150-\u215F\u2189-\u218B\u2190-\u2335\u237B-\u2394\u2396-\u2429\u2440-\u244A\u2460-\u249B\u24EA-\u26AB\u26AD-\u27FF\u2900-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2CEF-\u2CF1\u2CF9-\u2CFF\u2D7F\u2DE0-\u2E5D\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3001-\u3004\u3008-\u3020\u302A-\u302D\u3030\u3036\u3037\u303D-\u303F\u3099-\u309C\u30A0\u30FB\u31C0-\u31E5\u31EF\u321D\u321E\u3250-\u325F\u327C-\u327E\u32B1-\u32BF\u32CC-\u32CF\u3377-\u337A\u33DE\u33DF\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA60D-\uA60F\uA66F-\uA67F\uA69E\uA69F\uA6F0\uA6F1\uA700-\uA721\uA788\uA802\uA806\uA80B\uA825\uA826\uA828-\uA82C\uA838\uA839\uA874-\uA877\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uAB6A\uAB6B\uABE5\uABE8\uABED\uFB1D-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD8F\uFD92-\uFDC7\uFDCF\uFDF0-\uFE19\uFE20-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFE70-\uFE74\uFE76-\uFEFC\uFEFF\uFF01-\uFF20\uFF3B-\uFF40\uFF5B-\uFF65\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFF9-\uFFFD\u{10101}\u{10140}-\u{1018C}\u{10190}-\u{1019C}\u{101A0}\u{101FD}\u{102E0}-\u{102FB}\u{10376}-\u{1037A}\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{1091F}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A38}-\u{10A3A}\u{10A3F}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE6}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B39}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D27}\u{10D30}-\u{10D39}\u{10D40}-\u{10D65}\u{10D69}-\u{10D85}\u{10D8E}\u{10D8F}\u{10E60}-\u{10E7E}\u{10E80}-\u{10EA9}\u{10EAB}-\u{10EAD}\u{10EB0}\u{10EB1}\u{10EC2}-\u{10EC4}\u{10EFC}-\u{10F27}\u{10F30}-\u{10F59}\u{10F70}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{11001}\u{11038}-\u{11046}\u{11052}-\u{11065}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{11241}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{113BB}-\u{113C0}\u{113CE}\u{113D0}\u{113D2}\u{113E1}\u{113E2}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{11660}-\u{1166C}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{11F00}\u{11F01}\u{11F36}-\u{11F3A}\u{11F40}\u{11F42}\u{11F5A}\u{11FD5}-\u{11FF1}\u{13440}\u{13447}-\u{13455}\u{1611E}-\u{16129}\u{1612D}-\u{1612F}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE2}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1CC00}-\u{1CCD5}\u{1CCF0}-\u{1CCF9}\u{1CD00}-\u{1CEB3}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D1E9}\u{1D1EA}\u{1D200}-\u{1D245}\u{1D300}-\u{1D356}\u{1D6C1}\u{1D6DB}\u{1D6FB}\u{1D715}\u{1D735}\u{1D74F}\u{1D76F}\u{1D789}\u{1D7A9}\u{1D7C3}\u{1D7CE}-\u{1D7FF}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E08F}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E2FF}\u{1E4EC}-\u{1E4EF}\u{1E5EE}\u{1E5EF}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8D6}\u{1E900}-\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}\u{1EEF0}\u{1EEF1}\u{1F000}-\u{1F02B}\u{1F030}-\u{1F093}\u{1F0A0}-\u{1F0AE}\u{1F0B1}-\u{1F0BF}\u{1F0C1}-\u{1F0CF}\u{1F0D1}-\u{1F0F5}\u{1F100}-\u{1F10F}\u{1F12F}\u{1F16A}-\u{1F16F}\u{1F1AD}\u{1F260}-\u{1F265}\u{1F300}-\u{1F6D7}\u{1F6DC}-\u{1F6EC}\u{1F6F0}-\u{1F6FC}\u{1F700}-\u{1F776}\u{1F77B}-\u{1F7D9}\u{1F7E0}-\u{1F7EB}\u{1F7F0}\u{1F800}-\u{1F80B}\u{1F810}-\u{1F847}\u{1F850}-\u{1F859}\u{1F860}-\u{1F887}\u{1F890}-\u{1F8AD}\u{1F8B0}-\u{1F8BB}\u{1F8C0}\u{1F8C1}\u{1F900}-\u{1FA53}\u{1FA60}-\u{1FA6D}\u{1FA70}-\u{1FA7C}\u{1FA80}-\u{1FA89}\u{1FA8F}-\u{1FAC6}\u{1FACE}-\u{1FADC}\u{1FADF}-\u{1FAE9}\u{1FAF0}-\u{1FAF8}\u{1FB00}-\u{1FB92}\u{1FB94}-\u{1FBF9}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*$/u; var bidiS3 = /[0-9\xB2\xB3\xB9\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0600-\u0605\u0608\u060B\u060D\u061B-\u064A\u0660-\u0669\u066B-\u066F\u0671-\u06D5\u06DD\u06E5\u06E6\u06EE-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u0870-\u088E\u0890\u0891\u08A0-\u08C9\u08E2\u200F\u2070\u2074-\u2079\u2080-\u2089\u2488-\u249B\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\u{102E1}-\u{102FB}\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10D30}-\u{10D39}\u{10D40}-\u{10D65}\u{10D6F}-\u{10D85}\u{10D8E}\u{10D8F}\u{10E60}-\u{10E7E}\u{10E80}-\u{10EA9}\u{10EAD}\u{10EB0}\u{10EB1}\u{10EC2}-\u{10EC4}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10F70}-\u{10F81}\u{10F86}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{1CCF0}-\u{1CCF9}\u{1D7CE}-\u{1D7FF}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}\u{1F100}-\u{1F10A}\u{1FBF0}-\u{1FBF9}][\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3C\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732\u1733\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA82C\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10D69}-\u{10D6D}\u{10EAB}\u{10EAC}\u{10EFC}-\u{10EFF}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11001}\u{11038}-\u{11046}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{11241}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{113BB}-\u{113C0}\u{113CE}\u{113D0}\u{113D2}\u{113E1}\u{113E2}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{11F00}\u{11F01}\u{11F36}-\u{11F3A}\u{11F40}\u{11F42}\u{11F5A}\u{13440}\u{13447}-\u{13455}\u{1611E}-\u{16129}\u{1612D}-\u{1612F}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D167}-\u{1D169}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E08F}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E4EC}-\u{1E4EF}\u{1E5EE}\u{1E5EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]*$/u; var bidiS4EN = /[0-9\xB2\xB3\xB9\u06F0-\u06F9\u2070\u2074-\u2079\u2080-\u2089\u2488-\u249B\uFF10-\uFF19\u{102E1}-\u{102FB}\u{1CCF0}-\u{1CCF9}\u{1D7CE}-\u{1D7FF}\u{1F100}-\u{1F10A}\u{1FBF0}-\u{1FBF9}]/u; var bidiS4AN = /[\u0600-\u0605\u0660-\u0669\u066B\u066C\u06DD\u0890\u0891\u08E2\u{10D30}-\u{10D39}\u{10D40}-\u{10D49}\u{10E60}-\u{10E7E}]/u; var bidiS5 = /^[\0-\x08\x0E-\x1B!-\x84\x86-\u0377\u037A-\u037F\u0384-\u038A\u038C\u038E-\u03A1\u03A3-\u052F\u0531-\u0556\u0559-\u058A\u058D-\u058F\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0606\u0607\u0609\u060A\u060C\u060E-\u061A\u064B-\u065F\u066A\u0670\u06D6-\u06DC\u06DE-\u06E4\u06E7-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07F6-\u07F9\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09FE\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A76\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AF1\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B77\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BFA\u0C00-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3C-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C5D\u0C60-\u0C63\u0C66-\u0C6F\u0C77-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDD\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1-\u0CF3\u0D00-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4F\u0D54-\u0D63\u0D66-\u0D7F\u0D81-\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E3A\u0E3F-\u0E5B\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECE\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F47\u0F49-\u0F6C\u0F71-\u0F97\u0F99-\u0FBC\u0FBE-\u0FCC\u0FCE-\u0FDA\u1000-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u137C\u1380-\u1399\u13A0-\u13F5\u13F8-\u13FD\u1400-\u167F\u1681-\u169C\u16A0-\u16F8\u1700-\u1715\u171F-\u1736\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17DD\u17E0-\u17E9\u17F0-\u17F9\u1800-\u1819\u1820-\u1878\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1940\u1944-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u19DE-\u1A1B\u1A1E-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1AB0-\u1ACE\u1B00-\u1B4C\u1B4E-\u1BF3\u1BFC-\u1C37\u1C3B-\u1C49\u1C4D-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD0-\u1CFA\u1D00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FC4\u1FC6-\u1FD3\u1FD6-\u1FDB\u1FDD-\u1FEF\u1FF2-\u1FF4\u1FF6-\u1FFE\u200B-\u200E\u2010-\u2027\u202F-\u205E\u2060-\u2064\u206A-\u2071\u2074-\u208E\u2090-\u209C\u20A0-\u20C0\u20D0-\u20F0\u2100-\u218B\u2190-\u2429\u2440-\u244A\u2460-\u2B73\u2B76-\u2B95\u2B97-\u2CF3\u2CF9-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2E5D\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3001-\u303F\u3041-\u3096\u3099-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31E5\u31EF-\u321E\u3220-\uA48C\uA490-\uA4C6\uA4D0-\uA62B\uA640-\uA6F7\uA700-\uA7CD\uA7D0\uA7D1\uA7D3\uA7D5-\uA7DC\uA7F2-\uA82C\uA830-\uA839\uA840-\uA877\uA880-\uA8C5\uA8CE-\uA8D9\uA8E0-\uA953\uA95F-\uA97C\uA980-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA5C-\uAAC2\uAADB-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB6B\uAB70-\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1E\uFB29\uFD3E-\uFD4F\uFDCF\uFDFD-\uFE19\uFE20-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFEFF\uFF01-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFF9-\uFFFD\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}-\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1018E}\u{10190}-\u{1019C}\u{101A0}\u{101D0}-\u{101FD}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{102E0}-\u{102FB}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{1037A}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}-\u{1057A}\u{1057C}-\u{1058A}\u{1058C}-\u{10592}\u{10594}\u{10595}\u{10597}-\u{105A1}\u{105A3}-\u{105B1}\u{105B3}-\u{105B9}\u{105BB}\u{105BC}\u{105C0}-\u{105F3}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{10780}-\u{10785}\u{10787}-\u{107B0}\u{107B2}-\u{107BA}\u{1091F}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10B39}-\u{10B3F}\u{10D24}-\u{10D27}\u{10D69}-\u{10D6E}\u{10EAB}\u{10EAC}\u{10EFC}-\u{10EFF}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11000}-\u{1104D}\u{11052}-\u{11075}\u{1107F}-\u{110C2}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11100}-\u{11134}\u{11136}-\u{11147}\u{11150}-\u{11176}\u{11180}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{11241}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112EA}\u{112F0}-\u{112F9}\u{11300}-\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133B}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11380}-\u{11389}\u{1138B}\u{1138E}\u{11390}-\u{113B5}\u{113B7}-\u{113C0}\u{113C2}\u{113C5}\u{113C7}-\u{113CA}\u{113CC}-\u{113D5}\u{113D7}\u{113D8}\u{113E1}\u{113E2}\u{11400}-\u{1145B}\u{1145D}-\u{11461}\u{11480}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B5}\u{115B8}-\u{115DD}\u{11600}-\u{11644}\u{11650}-\u{11659}\u{11660}-\u{1166C}\u{11680}-\u{116B9}\u{116C0}-\u{116C9}\u{116D0}-\u{116E3}\u{11700}-\u{1171A}\u{1171D}-\u{1172B}\u{11730}-\u{11746}\u{11800}-\u{1183B}\u{118A0}-\u{118F2}\u{118FF}-\u{11906}\u{11909}\u{1190C}-\u{11913}\u{11915}\u{11916}\u{11918}-\u{11935}\u{11937}\u{11938}\u{1193B}-\u{11946}\u{11950}-\u{11959}\u{119A0}-\u{119A7}\u{119AA}-\u{119D7}\u{119DA}-\u{119E4}\u{11A00}-\u{11A47}\u{11A50}-\u{11AA2}\u{11AB0}-\u{11AF8}\u{11B00}-\u{11B09}\u{11BC0}-\u{11BE1}\u{11BF0}-\u{11BF9}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C36}\u{11C38}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11C92}-\u{11CA7}\u{11CA9}-\u{11CB6}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D47}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D90}\u{11D91}\u{11D93}-\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF8}\u{11F00}-\u{11F10}\u{11F12}-\u{11F3A}\u{11F3E}-\u{11F5A}\u{11FB0}\u{11FC0}-\u{11FF1}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{12F90}-\u{12FF2}\u{13000}-\u{13455}\u{13460}-\u{143FA}\u{14400}-\u{14646}\u{16100}-\u{16139}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}-\u{16ABE}\u{16AC0}-\u{16AC9}\u{16AD0}-\u{16AED}\u{16AF0}-\u{16AF5}\u{16B00}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16D40}-\u{16D79}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F4F}-\u{16F87}\u{16F8F}-\u{16F9F}\u{16FE0}-\u{16FE4}\u{16FF0}\u{16FF1}\u{17000}-\u{187F7}\u{18800}-\u{18CD5}\u{18CFF}-\u{18D08}\u{1AFF0}-\u{1AFF3}\u{1AFF5}-\u{1AFFB}\u{1AFFD}\u{1AFFE}\u{1B000}-\u{1B122}\u{1B132}\u{1B150}-\u{1B152}\u{1B155}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}-\u{1BCA3}\u{1CC00}-\u{1CCF9}\u{1CD00}-\u{1CEB3}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1CF50}-\u{1CFC3}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D1EA}\u{1D200}-\u{1D245}\u{1D2C0}-\u{1D2D3}\u{1D2E0}-\u{1D2F3}\u{1D300}-\u{1D356}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D7CB}\u{1D7CE}-\u{1DA8B}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1DF00}-\u{1DF1E}\u{1DF25}-\u{1DF2A}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E030}-\u{1E06D}\u{1E08F}\u{1E100}-\u{1E12C}\u{1E130}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E290}-\u{1E2AE}\u{1E2C0}-\u{1E2F9}\u{1E2FF}\u{1E4D0}-\u{1E4F9}\u{1E5D0}-\u{1E5FA}\u{1E5FF}\u{1E7E0}-\u{1E7E6}\u{1E7E8}-\u{1E7EB}\u{1E7ED}\u{1E7EE}\u{1E7F0}-\u{1E7FE}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{1EEF0}\u{1EEF1}\u{1F000}-\u{1F02B}\u{1F030}-\u{1F093}\u{1F0A0}-\u{1F0AE}\u{1F0B1}-\u{1F0BF}\u{1F0C1}-\u{1F0CF}\u{1F0D1}-\u{1F0F5}\u{1F100}-\u{1F1AD}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{1F260}-\u{1F265}\u{1F300}-\u{1F6D7}\u{1F6DC}-\u{1F6EC}\u{1F6F0}-\u{1F6FC}\u{1F700}-\u{1F776}\u{1F77B}-\u{1F7D9}\u{1F7E0}-\u{1F7EB}\u{1F7F0}\u{1F800}-\u{1F80B}\u{1F810}-\u{1F847}\u{1F850}-\u{1F859}\u{1F860}-\u{1F887}\u{1F890}-\u{1F8AD}\u{1F8B0}-\u{1F8BB}\u{1F8C0}\u{1F8C1}\u{1F900}-\u{1FA53}\u{1FA60}-\u{1FA6D}\u{1FA70}-\u{1FA7C}\u{1FA80}-\u{1FA89}\u{1FA8F}-\u{1FAC6}\u{1FACE}-\u{1FADC}\u{1FADF}-\u{1FAE9}\u{1FAF0}-\u{1FAF8}\u{1FB00}-\u{1FB92}\u{1FB94}-\u{1FBF9}\u{20000}-\u{2A6DF}\u{2A700}-\u{2B739}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2EBF0}-\u{2EE5D}\u{2F800}-\u{2FA1D}\u{30000}-\u{3134A}\u{31350}-\u{323AF}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]*$/u; var bidiS6 = /[0-9A-Za-z\xAA\xB2\xB3\xB5\xB9\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02BB-\u02C1\u02D0\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0482\u048A-\u052F\u0531-\u0556\u0559-\u0589\u06F0-\u06F9\u0903-\u0939\u093B\u093D-\u0940\u0949-\u094C\u094E-\u0950\u0958-\u0961\u0964-\u0980\u0982\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD-\u09C0\u09C7\u09C8\u09CB\u09CC\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09FA\u09FC\u09FD\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3E-\u0A40\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A76\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD-\u0AC0\u0AC9\u0ACB\u0ACC\u0AD0\u0AE0\u0AE1\u0AE6-\u0AF0\u0AF9\u0B02\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B3E\u0B40\u0B47\u0B48\u0B4B\u0B4C\u0B57\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE\u0BBF\u0BC1\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCC\u0BD0\u0BD7\u0BE6-\u0BF2\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C41-\u0C44\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C66-\u0C6F\u0C77\u0C7F\u0C80\u0C82-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD-\u0CC4\u0CC6-\u0CC8\u0CCA\u0CCB\u0CD5\u0CD6\u0CDD\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1-\u0CF3\u0D02-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D40\u0D46-\u0D48\u0D4A-\u0D4C\u0D4E\u0D4F\u0D54-\u0D61\u0D66-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCF-\u0DD1\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E4F-\u0E5B\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F17\u0F1A-\u0F34\u0F36\u0F38\u0F3E-\u0F47\u0F49-\u0F6C\u0F7F\u0F85\u0F88-\u0F8C\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FDA\u1000-\u102C\u1031\u1038\u103B\u103C\u103F-\u1057\u105A-\u105D\u1061-\u1070\u1075-\u1081\u1083\u1084\u1087-\u108C\u108E-\u109C\u109E-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1360-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u167F\u1681-\u169A\u16A0-\u16F8\u1700-\u1711\u1715\u171F-\u1731\u1734-\u1736\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17B6\u17BE-\u17C5\u17C7\u17C8\u17D4-\u17DA\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1923-\u1926\u1929-\u192B\u1930\u1931\u1933-\u1938\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A19\u1A1A\u1A1E-\u1A55\u1A57\u1A61\u1A63\u1A64\u1A6D-\u1A72\u1A80-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1B04-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B4C\u1B4E-\u1B6A\u1B74-\u1B7F\u1B82-\u1BA1\u1BA6\u1BA7\u1BAA\u1BAE-\u1BE5\u1BE7\u1BEA-\u1BEC\u1BEE\u1BF2\u1BF3\u1BFC-\u1C2B\u1C34\u1C35\u1C3B-\u1C49\u1C4D-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD3\u1CE1\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5-\u1CF7\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200E\u2070\u2071\u2074-\u2079\u207F-\u2089\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u214F\u2160-\u2188\u2336-\u237A\u2395\u2488-\u24E9\u26AC\u2800-\u28FF\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u302E\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31BF\u31F0-\u321C\u3220-\u324F\u3260-\u327B\u327F-\u32B0\u32C0-\u32CB\u32D0-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA60C\uA610-\uA62B\uA640-\uA66E\uA680-\uA69D\uA6A0-\uA6EF\uA6F2-\uA6F7\uA722-\uA787\uA789-\uA7CD\uA7D0\uA7D1\uA7D3\uA7D5-\uA7DC\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA824\uA827\uA830-\uA837\uA840-\uA873\uA880-\uA8C3\uA8CE-\uA8D9\uA8F2-\uA8FE\uA900-\uA925\uA92E-\uA946\uA952\uA953\uA95F-\uA97C\uA983-\uA9B2\uA9B4\uA9B5\uA9BA\uA9BB\uA9BE-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA2F\uAA30\uAA33\uAA34\uAA40-\uAA42\uAA44-\uAA4B\uAA4D\uAA50-\uAA59\uAA5C-\uAA7B\uAA7D-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAAEB\uAAEE-\uAAF5\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB69\uAB70-\uABE4\uABE6\uABE7\uABE9-\uABEC\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1013F}\u{1018D}\u{1018E}\u{101D0}-\u{101FC}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{102E1}-\u{102FB}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{10375}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}-\u{1057A}\u{1057C}-\u{1058A}\u{1058C}-\u{10592}\u{10594}\u{10595}\u{10597}-\u{105A1}\u{105A3}-\u{105B1}\u{105B3}-\u{105B9}\u{105BB}\u{105BC}\u{105C0}-\u{105F3}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{10780}-\u{10785}\u{10787}-\u{107B0}\u{107B2}-\u{107BA}\u{11000}\u{11002}-\u{11037}\u{11047}-\u{1104D}\u{11066}-\u{1106F}\u{11071}\u{11072}\u{11075}\u{11082}-\u{110B2}\u{110B7}\u{110B8}\u{110BB}-\u{110C1}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11103}-\u{11126}\u{1112C}\u{11136}-\u{11147}\u{11150}-\u{11172}\u{11174}-\u{11176}\u{11182}-\u{111B5}\u{111BF}-\u{111C8}\u{111CD}\u{111CE}\u{111D0}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1122E}\u{11232}\u{11233}\u{11235}\u{11238}-\u{1123D}\u{1123F}\u{11240}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112DE}\u{112E0}-\u{112E2}\u{112F0}-\u{112F9}\u{11302}\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133D}-\u{1133F}\u{11341}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11380}-\u{11389}\u{1138B}\u{1138E}\u{11390}-\u{113B5}\u{113B7}-\u{113BA}\u{113C2}\u{113C5}\u{113C7}-\u{113CA}\u{113CC}\u{113CD}\u{113CF}\u{113D1}\u{113D3}-\u{113D5}\u{113D7}\u{113D8}\u{11400}-\u{11437}\u{11440}\u{11441}\u{11445}\u{11447}-\u{1145B}\u{1145D}\u{1145F}-\u{11461}\u{11480}-\u{114B2}\u{114B9}\u{114BB}-\u{114BE}\u{114C1}\u{114C4}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B1}\u{115B8}-\u{115BB}\u{115BE}\u{115C1}-\u{115DB}\u{11600}-\u{11632}\u{1163B}\u{1163C}\u{1163E}\u{11641}-\u{11644}\u{11650}-\u{11659}\u{11680}-\u{116AA}\u{116AC}\u{116AE}\u{116AF}\u{116B6}\u{116B8}\u{116B9}\u{116C0}-\u{116C9}\u{116D0}-\u{116E3}\u{11700}-\u{1171A}\u{1171E}\u{11720}\u{11721}\u{11726}\u{11730}-\u{11746}\u{11800}-\u{1182E}\u{11838}\u{1183B}\u{118A0}-\u{118F2}\u{118FF}-\u{11906}\u{11909}\u{1190C}-\u{11913}\u{11915}\u{11916}\u{11918}-\u{11935}\u{11937}\u{11938}\u{1193D}\u{1193F}-\u{11942}\u{11944}-\u{11946}\u{11950}-\u{11959}\u{119A0}-\u{119A7}\u{119AA}-\u{119D3}\u{119DC}-\u{119DF}\u{119E1}-\u{119E4}\u{11A00}\u{11A07}\u{11A08}\u{11A0B}-\u{11A32}\u{11A39}\u{11A3A}\u{11A3F}-\u{11A46}\u{11A50}\u{11A57}\u{11A58}\u{11A5C}-\u{11A89}\u{11A97}\u{11A9A}-\u{11AA2}\u{11AB0}-\u{11AF8}\u{11B00}-\u{11B09}\u{11BC0}-\u{11BE1}\u{11BF0}-\u{11BF9}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C2F}\u{11C3E}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11CA9}\u{11CB1}\u{11CB4}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D30}\u{11D46}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D93}\u{11D94}\u{11D96}\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF2}\u{11EF5}-\u{11EF8}\u{11F02}-\u{11F10}\u{11F12}-\u{11F35}\u{11F3E}\u{11F3F}\u{11F41}\u{11F43}-\u{11F59}\u{11FB0}\u{11FC0}-\u{11FD4}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{12F90}-\u{12FF2}\u{13000}-\u{1343F}\u{13441}-\u{13446}\u{13460}-\u{143FA}\u{14400}-\u{14646}\u{16100}-\u{1611D}\u{1612A}-\u{1612C}\u{16130}-\u{16139}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}-\u{16ABE}\u{16AC0}-\u{16AC9}\u{16AD0}-\u{16AED}\u{16AF5}\u{16B00}-\u{16B2F}\u{16B37}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16D40}-\u{16D79}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F50}-\u{16F87}\u{16F93}-\u{16F9F}\u{16FE0}\u{16FE1}\u{16FE3}\u{16FF0}\u{16FF1}\u{17000}-\u{187F7}\u{18800}-\u{18CD5}\u{18CFF}-\u{18D08}\u{1AFF0}-\u{1AFF3}\u{1AFF5}-\u{1AFFB}\u{1AFFD}\u{1AFFE}\u{1B000}-\u{1B122}\u{1B132}\u{1B150}-\u{1B152}\u{1B155}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}\u{1BC9F}\u{1CCD6}-\u{1CCF9}\u{1CF50}-\u{1CFC3}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D166}\u{1D16A}-\u{1D172}\u{1D183}\u{1D184}\u{1D18C}-\u{1D1A9}\u{1D1AE}-\u{1D1E8}\u{1D2C0}-\u{1D2D3}\u{1D2E0}-\u{1D2F3}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D6C0}\u{1D6C2}-\u{1D6DA}\u{1D6DC}-\u{1D6FA}\u{1D6FC}-\u{1D714}\u{1D716}-\u{1D734}\u{1D736}-\u{1D74E}\u{1D750}-\u{1D76E}\u{1D770}-\u{1D788}\u{1D78A}-\u{1D7A8}\u{1D7AA}-\u{1D7C2}\u{1D7C4}-\u{1D7CB}\u{1D7CE}-\u{1D9FF}\u{1DA37}-\u{1DA3A}\u{1DA6D}-\u{1DA74}\u{1DA76}-\u{1DA83}\u{1DA85}-\u{1DA8B}\u{1DF00}-\u{1DF1E}\u{1DF25}-\u{1DF2A}\u{1E030}-\u{1E06D}\u{1E100}-\u{1E12C}\u{1E137}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E290}-\u{1E2AD}\u{1E2C0}-\u{1E2EB}\u{1E2F0}-\u{1E2F9}\u{1E4D0}-\u{1E4EB}\u{1E4F0}-\u{1E4F9}\u{1E5D0}-\u{1E5ED}\u{1E5F0}-\u{1E5FA}\u{1E5FF}\u{1E7E0}-\u{1E7E6}\u{1E7E8}-\u{1E7EB}\u{1E7ED}\u{1E7EE}\u{1E7F0}-\u{1E7FE}\u{1F100}-\u{1F10A}\u{1F110}-\u{1F12E}\u{1F130}-\u{1F169}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{1FBF0}-\u{1FBF9}\u{20000}-\u{2A6DF}\u{2A700}-\u{2B739}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2EBF0}-\u{2EE5D}\u{2F800}-\u{2FA1D}\u{30000}-\u{3134A}\u{31350}-\u{323AF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}][\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3C\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732\u1733\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA82C\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10D69}-\u{10D6D}\u{10EAB}\u{10EAC}\u{10EFC}-\u{10EFF}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11001}\u{11038}-\u{11046}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{11241}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{113BB}-\u{113C0}\u{113CE}\u{113D0}\u{113D2}\u{113E1}\u{113E2}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{11F00}\u{11F01}\u{11F36}-\u{11F3A}\u{11F40}\u{11F42}\u{11F5A}\u{13440}\u{13447}-\u{13455}\u{1611E}-\u{16129}\u{1612D}-\u{1612F}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D167}-\u{1D169}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E08F}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E4EC}-\u{1E4EF}\u{1E5EE}\u{1E5EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]*$/u; module2.exports = { combiningMarks, combiningClassVirama, validZWNJ, bidiDomain, bidiS1LTR, bidiS1RTL, bidiS2, bidiS3, bidiS4EN, bidiS4AN, bidiS5, bidiS6 }; } }); // netlify/functions/node_modules/tr46/lib/mappingTable.json var require_mappingTable = __commonJS({ "netlify/functions/node_modules/tr46/lib/mappingTable.json"(exports2, module2) { module2.exports = [[[0, 44], 2], [[45, 46], 2], [47, 2], [[48, 57], 2], [[58, 64], 2], [65, 1, "a"], [66, 1, "b"], [67, 1, "c"], [68, 1, "d"], [69, 1, "e"], [70, 1, "f"], [71, 1, "g"], [72, 1, "h"], [73, 1, "i"], [74, 1, "j"], [75, 1, "k"], [76, 1, "l"], [77, 1, "m"], [78, 1, "n"], [79, 1, "o"], [80, 1, "p"], [81, 1, "q"], [82, 1, "r"], [83, 1, "s"], [84, 1, "t"], [85, 1, "u"], [86, 1, "v"], [87, 1, "w"], [88, 1, "x"], [89, 1, "y"], [90, 1, "z"], [[91, 96], 2], [[97, 122], 2], [[123, 127], 2], [[128, 159], 3], [160, 1, " "], [[161, 167], 2], [168, 1, " \u0308"], [169, 2], [170, 1, "a"], [[171, 172], 2], [173, 7], [174, 2], [175, 1, " \u0304"], [[176, 177], 2], [178, 1, "2"], [179, 1, "3"], [180, 1, " \u0301"], [181, 1, "\u03BC"], [182, 2], [183, 2], [184, 1, " \u0327"], [185, 1, "1"], [186, 1, "o"], [187, 2], [188, 1, "1\u20444"], [189, 1, "1\u20442"], [190, 1, "3\u20444"], [191, 2], [192, 1, "\xE0"], [193, 1, "\xE1"], [194, 1, "\xE2"], [195, 1, "\xE3"], [196, 1, "\xE4"], [197, 1, "\xE5"], [198, 1, "\xE6"], [199, 1, "\xE7"], [200, 1, "\xE8"], [201, 1, "\xE9"], [202, 1, "\xEA"], [203, 1, "\xEB"], [204, 1, "\xEC"], [205, 1, "\xED"], [206, 1, "\xEE"], [207, 1, "\xEF"], [208, 1, "\xF0"], [209, 1, "\xF1"], [210, 1, "\xF2"], [211, 1, "\xF3"], [212, 1, "\xF4"], [213, 1, "\xF5"], [214, 1, "\xF6"], [215, 2], [216, 1, "\xF8"], [217, 1, "\xF9"], [218, 1, "\xFA"], [219, 1, "\xFB"], [220, 1, "\xFC"], [221, 1, "\xFD"], [222, 1, "\xFE"], [223, 6, "ss"], [[224, 246], 2], [247, 2], [[248, 255], 2], [256, 1, "\u0101"], [257, 2], [258, 1, "\u0103"], [259, 2], [260, 1, "\u0105"], [261, 2], [262, 1, "\u0107"], [263, 2], [264, 1, "\u0109"], [265, 2], [266, 1, "\u010B"], [267, 2], [268, 1, "\u010D"], [269, 2], [270, 1, "\u010F"], [271, 2], [272, 1, "\u0111"], [273, 2], [274, 1, "\u0113"], [275, 2], [276, 1, "\u0115"], [277, 2], [278, 1, "\u0117"], [279, 2], [280, 1, "\u0119"], [281, 2], [282, 1, "\u011B"], [283, 2], [284, 1, "\u011D"], [285, 2], [286, 1, "\u011F"], [287, 2], [288, 1, "\u0121"], [289, 2], [290, 1, "\u0123"], [291, 2], [292, 1, "\u0125"], [293, 2], [294, 1, "\u0127"], [295, 2], [296, 1, "\u0129"], [297, 2], [298, 1, "\u012B"], [299, 2], [300, 1, "\u012D"], [301, 2], [302, 1, "\u012F"], [303, 2], [304, 1, "i\u0307"], [305, 2], [[306, 307], 1, "ij"], [308, 1, "\u0135"], [309, 2], [310, 1, "\u0137"], [[311, 312], 2], [313, 1, "\u013A"], [314, 2], [315, 1, "\u013C"], [316, 2], [317, 1, "\u013E"], [318, 2], [[319, 320], 1, "l\xB7"], [321, 1, "\u0142"], [322, 2], [323, 1, "\u0144"], [324, 2], [325, 1, "\u0146"], [326, 2], [327, 1, "\u0148"], [328, 2], [329, 1, "\u02BCn"], [330, 1, "\u014B"], [331, 2], [332, 1, "\u014D"], [333, 2], [334, 1, "\u014F"], [335, 2], [336, 1, "\u0151"], [337, 2], [338, 1, "\u0153"], [339, 2], [340, 1, "\u0155"], [341, 2], [342, 1, "\u0157"], [343, 2], [344, 1, "\u0159"], [345, 2], [346, 1, "\u015B"], [347, 2], [348, 1, "\u015D"], [349, 2], [350, 1, "\u015F"], [351, 2], [352, 1, "\u0161"], [353, 2], [354, 1, "\u0163"], [355, 2], [356, 1, "\u0165"], [357, 2], [358, 1, "\u0167"], [359, 2], [360, 1, "\u0169"], [361, 2], [362, 1, "\u016B"], [363, 2], [364, 1, "\u016D"], [365, 2], [366, 1, "\u016F"], [367, 2], [368, 1, "\u0171"], [369, 2], [370, 1, "\u0173"], [371, 2], [372, 1, "\u0175"], [373, 2], [374, 1, "\u0177"], [375, 2], [376, 1, "\xFF"], [377, 1, "\u017A"], [378, 2], [379, 1, "\u017C"], [380, 2], [381, 1, "\u017E"], [382, 2], [383, 1, "s"], [384, 2], [385, 1, "\u0253"], [386, 1, "\u0183"], [387, 2], [388, 1, "\u0185"], [389, 2], [390, 1, "\u0254"], [391, 1, "\u0188"], [392, 2], [393, 1, "\u0256"], [394, 1, "\u0257"], [395, 1, "\u018C"], [[396, 397], 2], [398, 1, "\u01DD"], [399, 1, "\u0259"], [400, 1, "\u025B"], [401, 1, "\u0192"], [402, 2], [403, 1, "\u0260"], [404, 1, "\u0263"], [405, 2], [406, 1, "\u0269"], [407, 1, "\u0268"], [408, 1, "\u0199"], [[409, 411], 2], [412, 1, "\u026F"], [413, 1, "\u0272"], [414, 2], [415, 1, "\u0275"], [416, 1, "\u01A1"], [417, 2], [418, 1, "\u01A3"], [419, 2], [420, 1, "\u01A5"], [421, 2], [422, 1, "\u0280"], [423, 1, "\u01A8"], [424, 2], [425, 1, "\u0283"], [[426, 427], 2], [428, 1, "\u01AD"], [429, 2], [430, 1, "\u0288"], [431, 1, "\u01B0"], [432, 2], [433, 1, "\u028A"], [434, 1, "\u028B"], [435, 1, "\u01B4"], [436, 2], [437, 1, "\u01B6"], [438, 2], [439, 1, "\u0292"], [440, 1, "\u01B9"], [[441, 443], 2], [444, 1, "\u01BD"], [[445, 451], 2], [[452, 454], 1, "d\u017E"], [[455, 457], 1, "lj"], [[458, 460], 1, "nj"], [461, 1, "\u01CE"], [462, 2], [463, 1, "\u01D0"], [464, 2], [465, 1, "\u01D2"], [466, 2], [467, 1, "\u01D4"], [468, 2], [469, 1, "\u01D6"], [470, 2], [471, 1, "\u01D8"], [472, 2], [473, 1, "\u01DA"], [474, 2], [475, 1, "\u01DC"], [[476, 477], 2], [478, 1, "\u01DF"], [479, 2], [480, 1, "\u01E1"], [481, 2], [482, 1, "\u01E3"], [483, 2], [484, 1, "\u01E5"], [485, 2], [486, 1, "\u01E7"], [487, 2], [488, 1, "\u01E9"], [489, 2], [490, 1, "\u01EB"], [491, 2], [492, 1, "\u01ED"], [493, 2], [494, 1, "\u01EF"], [[495, 496], 2], [[497, 499], 1, "dz"], [500, 1, "\u01F5"], [501, 2], [502, 1, "\u0195"], [503, 1, "\u01BF"], [504, 1, "\u01F9"], [505, 2], [506, 1, "\u01FB"], [507, 2], [508, 1, "\u01FD"], [509, 2], [510, 1, "\u01FF"], [511, 2], [512, 1, "\u0201"], [513, 2], [514, 1, "\u0203"], [515, 2], [516, 1, "\u0205"], [517, 2], [518, 1, "\u0207"], [519, 2], [520, 1, "\u0209"], [521, 2], [522, 1, "\u020B"], [523, 2], [524, 1, "\u020D"], [525, 2], [526, 1, "\u020F"], [527, 2], [528, 1, "\u0211"], [529, 2], [530, 1, "\u0213"], [531, 2], [532, 1, "\u0215"], [533, 2], [534, 1, "\u0217"], [535, 2], [536, 1, "\u0219"], [537, 2], [538, 1, "\u021B"], [539, 2], [540, 1, "\u021D"], [541, 2], [542, 1, "\u021F"], [543, 2], [544, 1, "\u019E"], [545, 2], [546, 1, "\u0223"], [547, 2], [548, 1, "\u0225"], [549, 2], [550, 1, "\u0227"], [551, 2], [552, 1, "\u0229"], [553, 2], [554, 1, "\u022B"], [555, 2], [556, 1, "\u022D"], [557, 2], [558, 1, "\u022F"], [559, 2], [560, 1, "\u0231"], [561, 2], [562, 1, "\u0233"], [563, 2], [[564, 566], 2], [[567, 569], 2], [570, 1, "\u2C65"], [571, 1, "\u023C"], [572, 2], [573, 1, "\u019A"], [574, 1, "\u2C66"], [[575, 576], 2], [577, 1, "\u0242"], [578, 2], [579, 1, "\u0180"], [580, 1, "\u0289"], [581, 1, "\u028C"], [582, 1, "\u0247"], [583, 2], [584, 1, "\u0249"], [585, 2], [586, 1, "\u024B"], [587, 2], [588, 1, "\u024D"], [589, 2], [590, 1, "\u024F"], [591, 2], [[592, 680], 2], [[681, 685], 2], [[686, 687], 2], [688, 1, "h"], [689, 1, "\u0266"], [690, 1, "j"], [691, 1, "r"], [692, 1, "\u0279"], [693, 1, "\u027B"], [694, 1, "\u0281"], [695, 1, "w"], [696, 1, "y"], [[697, 705], 2], [[706, 709], 2], [[710, 721], 2], [[722, 727], 2], [728, 1, " \u0306"], [729, 1, " \u0307"], [730, 1, " \u030A"], [731, 1, " \u0328"], [732, 1, " \u0303"], [733, 1, " \u030B"], [734, 2], [735, 2], [736, 1, "\u0263"], [737, 1, "l"], [738, 1, "s"], [739, 1, "x"], [740, 1, "\u0295"], [[741, 745], 2], [[746, 747], 2], [748, 2], [749, 2], [750, 2], [[751, 767], 2], [[768, 831], 2], [832, 1, "\u0300"], [833, 1, "\u0301"], [834, 2], [835, 1, "\u0313"], [836, 1, "\u0308\u0301"], [837, 1, "\u03B9"], [[838, 846], 2], [847, 7], [[848, 855], 2], [[856, 860], 2], [[861, 863], 2], [[864, 865], 2], [866, 2], [[867, 879], 2], [880, 1, "\u0371"], [881, 2], [882, 1, "\u0373"], [883, 2], [884, 1, "\u02B9"], [885, 2], [886, 1, "\u0377"], [887, 2], [[888, 889], 3], [890, 1, " \u03B9"], [[891, 893], 2], [894, 1, ";"], [895, 1, "\u03F3"], [[896, 899], 3], [900, 1, " \u0301"], [901, 1, " \u0308\u0301"], [902, 1, "\u03AC"], [903, 1, "\xB7"], [904, 1, "\u03AD"], [905, 1, "\u03AE"], [906, 1, "\u03AF"], [907, 3], [908, 1, "\u03CC"], [909, 3], [910, 1, "\u03CD"], [911, 1, "\u03CE"], [912, 2], [913, 1, "\u03B1"], [914, 1, "\u03B2"], [915, 1, "\u03B3"], [916, 1, "\u03B4"], [917, 1, "\u03B5"], [918, 1, "\u03B6"], [919, 1, "\u03B7"], [920, 1, "\u03B8"], [921, 1, "\u03B9"], [922, 1, "\u03BA"], [923, 1, "\u03BB"], [924, 1, "\u03BC"], [925, 1, "\u03BD"], [926, 1, "\u03BE"], [927, 1, "\u03BF"], [928, 1, "\u03C0"], [929, 1, "\u03C1"], [930, 3], [931, 1, "\u03C3"], [932, 1, "\u03C4"], [933, 1, "\u03C5"], [934, 1, "\u03C6"], [935, 1, "\u03C7"], [936, 1, "\u03C8"], [937, 1, "\u03C9"], [938, 1, "\u03CA"], [939, 1, "\u03CB"], [[940, 961], 2], [962, 6, "\u03C3"], [[963, 974], 2], [975, 1, "\u03D7"], [976, 1, "\u03B2"], [977, 1, "\u03B8"], [978, 1, "\u03C5"], [979, 1, "\u03CD"], [980, 1, "\u03CB"], [981, 1, "\u03C6"], [982, 1, "\u03C0"], [983, 2], [984, 1, "\u03D9"], [985, 2], [986, 1, "\u03DB"], [987, 2], [988, 1, "\u03DD"], [989, 2], [990, 1, "\u03DF"], [991, 2], [992, 1, "\u03E1"], [993, 2], [994, 1, "\u03E3"], [995, 2], [996, 1, "\u03E5"], [997, 2], [998, 1, "\u03E7"], [999, 2], [1e3, 1, "\u03E9"], [1001, 2], [1002, 1, "\u03EB"], [1003, 2], [1004, 1, "\u03ED"], [1005, 2], [1006, 1, "\u03EF"], [1007, 2], [1008, 1, "\u03BA"], [1009, 1, "\u03C1"], [1010, 1, "\u03C3"], [1011, 2], [1012, 1, "\u03B8"], [1013, 1, "\u03B5"], [1014, 2], [1015, 1, "\u03F8"], [1016, 2], [1017, 1, "\u03C3"], [1018, 1, "\u03FB"], [1019, 2], [1020, 2], [1021, 1, "\u037B"], [1022, 1, "\u037C"], [1023, 1, "\u037D"], [1024, 1, "\u0450"], [1025, 1, "\u0451"], [1026, 1, "\u0452"], [1027, 1, "\u0453"], [1028, 1, "\u0454"], [1029, 1, "\u0455"], [1030, 1, "\u0456"], [1031, 1, "\u0457"], [1032, 1, "\u0458"], [1033, 1, "\u0459"], [1034, 1, "\u045A"], [1035, 1, "\u045B"], [1036, 1, "\u045C"], [1037, 1, "\u045D"], [1038, 1, "\u045E"], [1039, 1, "\u045F"], [1040, 1, "\u0430"], [1041, 1, "\u0431"], [1042, 1, "\u0432"], [1043, 1, "\u0433"], [1044, 1, "\u0434"], [1045, 1, "\u0435"], [1046, 1, "\u0436"], [1047, 1, "\u0437"], [1048, 1, "\u0438"], [1049, 1, "\u0439"], [1050, 1, "\u043A"], [1051, 1, "\u043B"], [1052, 1, "\u043C"], [1053, 1, "\u043D"], [1054, 1, "\u043E"], [1055, 1, "\u043F"], [1056, 1, "\u0440"], [1057, 1, "\u0441"], [1058, 1, "\u0442"], [1059, 1, "\u0443"], [1060, 1, "\u0444"], [1061, 1, "\u0445"], [1062, 1, "\u0446"], [1063, 1, "\u0447"], [1064, 1, "\u0448"], [1065, 1, "\u0449"], [1066, 1, "\u044A"], [1067, 1, "\u044B"], [1068, 1, "\u044C"], [1069, 1, "\u044D"], [1070, 1, "\u044E"], [1071, 1, "\u044F"], [[1072, 1103], 2], [1104, 2], [[1105, 1116], 2], [1117, 2], [[1118, 1119], 2], [1120, 1, "\u0461"], [1121, 2], [1122, 1, "\u0463"], [1123, 2], [1124, 1, "\u0465"], [1125, 2], [1126, 1, "\u0467"], [1127, 2], [1128, 1, "\u0469"], [1129, 2], [1130, 1, "\u046B"], [1131, 2], [1132, 1, "\u046D"], [1133, 2], [1134, 1, "\u046F"], [1135, 2], [1136, 1, "\u0471"], [1137, 2], [1138, 1, "\u0473"], [1139, 2], [1140, 1, "\u0475"], [1141, 2], [1142, 1, "\u0477"], [1143, 2], [1144, 1, "\u0479"], [1145, 2], [1146, 1, "\u047B"], [1147, 2], [1148, 1, "\u047D"], [1149, 2], [1150, 1, "\u047F"], [1151, 2], [1152, 1, "\u0481"], [1153, 2], [1154, 2], [[1155, 1158], 2], [1159, 2], [[1160, 1161], 2], [1162, 1, "\u048B"], [1163, 2], [1164, 1, "\u048D"], [1165, 2], [1166, 1, "\u048F"], [1167, 2], [1168, 1, "\u0491"], [1169, 2], [1170, 1, "\u0493"], [1171, 2], [1172, 1, "\u0495"], [1173, 2], [1174, 1, "\u0497"], [1175, 2], [1176, 1, "\u0499"], [1177, 2], [1178, 1, "\u049B"], [1179, 2], [1180, 1, "\u049D"], [1181, 2], [1182, 1, "\u049F"], [1183, 2], [1184, 1, "\u04A1"], [1185, 2], [1186, 1, "\u04A3"], [1187, 2], [1188, 1, "\u04A5"], [1189, 2], [1190, 1, "\u04A7"], [1191, 2], [1192, 1, "\u04A9"], [1193, 2], [1194, 1, "\u04AB"], [1195, 2], [1196, 1, "\u04AD"], [1197, 2], [1198, 1, "\u04AF"], [1199, 2], [1200, 1, "\u04B1"], [1201, 2], [1202, 1, "\u04B3"], [1203, 2], [1204, 1, "\u04B5"], [1205, 2], [1206, 1, "\u04B7"], [1207, 2], [1208, 1, "\u04B9"], [1209, 2], [1210, 1, "\u04BB"], [1211, 2], [1212, 1, "\u04BD"], [1213, 2], [1214, 1, "\u04BF"], [1215, 2], [1216, 1, "\u04CF"], [1217, 1, "\u04C2"], [1218, 2], [1219, 1, "\u04C4"], [1220, 2], [1221, 1, "\u04C6"], [1222, 2], [1223, 1, "\u04C8"], [1224, 2], [1225, 1, "\u04CA"], [1226, 2], [1227, 1, "\u04CC"], [1228, 2], [1229, 1, "\u04CE"], [1230, 2], [1231, 2], [1232, 1, "\u04D1"], [1233, 2], [1234, 1, "\u04D3"], [1235, 2], [1236, 1, "\u04D5"], [1237, 2], [1238, 1, "\u04D7"], [1239, 2], [1240, 1, "\u04D9"], [1241, 2], [1242, 1, "\u04DB"], [1243, 2], [1244, 1, "\u04DD"], [1245, 2], [1246, 1, "\u04DF"], [1247, 2], [1248, 1, "\u04E1"], [1249, 2], [1250, 1, "\u04E3"], [1251, 2], [1252, 1, "\u04E5"], [1253, 2], [1254, 1, "\u04E7"], [1255, 2], [1256, 1, "\u04E9"], [1257, 2], [1258, 1, "\u04EB"], [1259, 2], [1260, 1, "\u04ED"], [1261, 2], [1262, 1, "\u04EF"], [1263, 2], [1264, 1, "\u04F1"], [1265, 2], [1266, 1, "\u04F3"], [1267, 2], [1268, 1, "\u04F5"], [1269, 2], [1270, 1, "\u04F7"], [1271, 2], [1272, 1, "\u04F9"], [1273, 2], [1274, 1, "\u04FB"], [1275, 2], [1276, 1, "\u04FD"], [1277, 2], [1278, 1, "\u04FF"], [1279, 2], [1280, 1, "\u0501"], [1281, 2], [1282, 1, "\u0503"], [1283, 2], [1284, 1, "\u0505"], [1285, 2], [1286, 1, "\u0507"], [1287, 2], [1288, 1, "\u0509"], [1289, 2], [1290, 1, "\u050B"], [1291, 2], [1292, 1, "\u050D"], [1293, 2], [1294, 1, "\u050F"], [1295, 2], [1296, 1, "\u0511"], [1297, 2], [1298, 1, "\u0513"], [1299, 2], [1300, 1, "\u0515"], [1301, 2], [1302, 1, "\u0517"], [1303, 2], [1304, 1, "\u0519"], [1305, 2], [1306, 1, "\u051B"], [1307, 2], [1308, 1, "\u051D"], [1309, 2], [1310, 1, "\u051F"], [1311, 2], [1312, 1, "\u0521"], [1313, 2], [1314, 1, "\u0523"], [1315, 2], [1316, 1, "\u0525"], [1317, 2], [1318, 1, "\u0527"], [1319, 2], [1320, 1, "\u0529"], [1321, 2], [1322, 1, "\u052B"], [1323, 2], [1324, 1, "\u052D"], [1325, 2], [1326, 1, "\u052F"], [1327, 2], [1328, 3], [1329, 1, "\u0561"], [1330, 1, "\u0562"], [1331, 1, "\u0563"], [1332, 1, "\u0564"], [1333, 1, "\u0565"], [1334, 1, "\u0566"], [1335, 1, "\u0567"], [1336, 1, "\u0568"], [1337, 1, "\u0569"], [1338, 1, "\u056A"], [1339, 1, "\u056B"], [1340, 1, "\u056C"], [1341, 1, "\u056D"], [1342, 1, "\u056E"], [1343, 1, "\u056F"], [1344, 1, "\u0570"], [1345, 1, "\u0571"], [1346, 1, "\u0572"], [1347, 1, "\u0573"], [1348, 1, "\u0574"], [1349, 1, "\u0575"], [1350, 1, "\u0576"], [1351, 1, "\u0577"], [1352, 1, "\u0578"], [1353, 1, "\u0579"], [1354, 1, "\u057A"], [1355, 1, "\u057B"], [1356, 1, "\u057C"], [1357, 1, "\u057D"], [1358, 1, "\u057E"], [1359, 1, "\u057F"], [1360, 1, "\u0580"], [1361, 1, "\u0581"], [1362, 1, "\u0582"], [1363, 1, "\u0583"], [1364, 1, "\u0584"], [1365, 1, "\u0585"], [1366, 1, "\u0586"], [[1367, 1368], 3], [1369, 2], [[1370, 1375], 2], [1376, 2], [[1377, 1414], 2], [1415, 1, "\u0565\u0582"], [1416, 2], [1417, 2], [1418, 2], [[1419, 1420], 3], [[1421, 1422], 2], [1423, 2], [1424, 3], [[1425, 1441], 2], [1442, 2], [[1443, 1455], 2], [[1456, 1465], 2], [1466, 2], [[1467, 1469], 2], [1470, 2], [1471, 2], [1472, 2], [[1473, 1474], 2], [1475, 2], [1476, 2], [1477, 2], [1478, 2], [1479, 2], [[1480, 1487], 3], [[1488, 1514], 2], [[1515, 1518], 3], [1519, 2], [[1520, 1524], 2], [[1525, 1535], 3], [[1536, 1539], 3], [1540, 3], [1541, 3], [[1542, 1546], 2], [1547, 2], [1548, 2], [[1549, 1551], 2], [[1552, 1557], 2], [[1558, 1562], 2], [1563, 2], [1564, 3], [1565, 2], [1566, 2], [1567, 2], [1568, 2], [[1569, 1594], 2], [[1595, 1599], 2], [1600, 2], [[1601, 1618], 2], [[1619, 1621], 2], [[1622, 1624], 2], [[1625, 1630], 2], [1631, 2], [[1632, 1641], 2], [[1642, 1645], 2], [[1646, 1647], 2], [[1648, 1652], 2], [1653, 1, "\u0627\u0674"], [1654, 1, "\u0648\u0674"], [1655, 1, "\u06C7\u0674"], [1656, 1, "\u064A\u0674"], [[1657, 1719], 2], [[1720, 1721], 2], [[1722, 1726], 2], [1727, 2], [[1728, 1742], 2], [1743, 2], [[1744, 1747], 2], [1748, 2], [[1749, 1756], 2], [1757, 3], [1758, 2], [[1759, 1768], 2], [1769, 2], [[1770, 1773], 2], [[1774, 1775], 2], [[1776, 1785], 2], [[1786, 1790], 2], [1791, 2], [[1792, 1805], 2], [1806, 3], [1807, 3], [[1808, 1836], 2], [[1837, 1839], 2], [[1840, 1866], 2], [[1867, 1868], 3], [[1869, 1871], 2], [[1872, 1901], 2], [[1902, 1919], 2], [[1920, 1968], 2], [1969, 2], [[1970, 1983], 3], [[1984, 2037], 2], [[2038, 2042], 2], [[2043, 2044], 3], [2045, 2], [[2046, 2047], 2], [[2048, 2093], 2], [[2094, 2095], 3], [[2096, 2110], 2], [2111, 3], [[2112, 2139], 2], [[2140, 2141], 3], [2142, 2], [2143, 3], [[2144, 2154], 2], [[2155, 2159], 3], [[2160, 2183], 2], [2184, 2], [[2185, 2190], 2], [2191, 3], [[2192, 2193], 3], [[2194, 2198], 3], [2199, 2], [[2200, 2207], 2], [2208, 2], [2209, 2], [[2210, 2220], 2], [[2221, 2226], 2], [[2227, 2228], 2], [2229, 2], [[2230, 2237], 2], [[2238, 2247], 2], [[2248, 2258], 2], [2259, 2], [[2260, 2273], 2], [2274, 3], [2275, 2], [[2276, 2302], 2], [2303, 2], [2304, 2], [[2305, 2307], 2], [2308, 2], [[2309, 2361], 2], [[2362, 2363], 2], [[2364, 2381], 2], [2382, 2], [2383, 2], [[2384, 2388], 2], [2389, 2], [[2390, 2391], 2], [2392, 1, "\u0915\u093C"], [2393, 1, "\u0916\u093C"], [2394, 1, "\u0917\u093C"], [2395, 1, "\u091C\u093C"], [2396, 1, "\u0921\u093C"], [2397, 1, "\u0922\u093C"], [2398, 1, "\u092B\u093C"], [2399, 1, "\u092F\u093C"], [[2400, 2403], 2], [[2404, 2405], 2], [[2406, 2415], 2], [2416, 2], [[2417, 2418], 2], [[2419, 2423], 2], [2424, 2], [[2425, 2426], 2], [[2427, 2428], 2], [2429, 2], [[2430, 2431], 2], [2432, 2], [[2433, 2435], 2], [2436, 3], [[2437, 2444], 2], [[2445, 2446], 3], [[2447, 2448], 2], [[2449, 2450], 3], [[2451, 2472], 2], [2473, 3], [[2474, 2480], 2], [2481, 3], [2482, 2], [[2483, 2485], 3], [[2486, 2489], 2], [[2490, 2491], 3], [2492, 2], [2493, 2], [[2494, 2500], 2], [[2501, 2502], 3], [[2503, 2504], 2], [[2505, 2506], 3], [[2507, 2509], 2], [2510, 2], [[2511, 2518], 3], [2519, 2], [[2520, 2523], 3], [2524, 1, "\u09A1\u09BC"], [2525, 1, "\u09A2\u09BC"], [2526, 3], [2527, 1, "\u09AF\u09BC"], [[2528, 2531], 2], [[2532, 2533], 3], [[2534, 2545], 2], [[2546, 2554], 2], [2555, 2], [2556, 2], [2557, 2], [2558, 2], [[2559, 2560], 3], [2561, 2], [2562, 2], [2563, 2], [2564, 3], [[2565, 2570], 2], [[2571, 2574], 3], [[2575, 2576], 2], [[2577, 2578], 3], [[2579, 2600], 2], [2601, 3], [[2602, 2608], 2], [2609, 3], [2610, 2], [2611, 1, "\u0A32\u0A3C"], [2612, 3], [2613, 2], [2614, 1, "\u0A38\u0A3C"], [2615, 3], [[2616, 2617], 2], [[2618, 2619], 3], [2620, 2], [2621, 3], [[2622, 2626], 2], [[2627, 2630], 3], [[2631, 2632], 2], [[2633, 2634], 3], [[2635, 2637], 2], [[2638, 2640], 3], [2641, 2], [[2642, 2648], 3], [2649, 1, "\u0A16\u0A3C"], [2650, 1, "\u0A17\u0A3C"], [2651, 1, "\u0A1C\u0A3C"], [2652, 2], [2653, 3], [2654, 1, "\u0A2B\u0A3C"], [[2655, 2661], 3], [[2662, 2676], 2], [2677, 2], [2678, 2], [[2679, 2688], 3], [[2689, 2691], 2], [2692, 3], [[2693, 2699], 2], [2700, 2], [2701, 2], [2702, 3], [[2703, 2705], 2], [2706, 3], [[2707, 2728], 2], [2729, 3], [[2730, 2736], 2], [2737, 3], [[2738, 2739], 2], [2740, 3], [[2741, 2745], 2], [[2746, 2747], 3], [[2748, 2757], 2], [2758, 3], [[2759, 2761], 2], [2762, 3], [[2763, 2765], 2], [[2766, 2767], 3], [2768, 2], [[2769, 2783], 3], [2784, 2], [[2785, 2787], 2], [[2788, 2789], 3], [[2790, 2799], 2], [2800, 2], [2801, 2], [[2802, 2808], 3], [2809, 2], [[2810, 2815], 2], [2816, 3], [[2817, 2819], 2], [2820, 3], [[2821, 2828], 2], [[2829, 2830], 3], [[2831, 2832], 2], [[2833, 2834], 3], [[2835, 2856], 2], [2857, 3], [[2858, 2864], 2], [2865, 3], [[2866, 2867], 2], [2868, 3], [2869, 2], [[2870, 2873], 2], [[2874, 2875], 3], [[2876, 2883], 2], [2884, 2], [[2885, 2886], 3], [[2887, 2888], 2], [[2889, 2890], 3], [[2891, 2893], 2], [[2894, 2900], 3], [2901, 2], [[2902, 2903], 2], [[2904, 2907], 3], [2908, 1, "\u0B21\u0B3C"], [2909, 1, "\u0B22\u0B3C"], [2910, 3], [[2911, 2913], 2], [[2914, 2915], 2], [[2916, 2917], 3], [[2918, 2927], 2], [2928, 2], [2929, 2], [[2930, 2935], 2], [[2936, 2945], 3], [[2946, 2947], 2], [2948, 3], [[2949, 2954], 2], [[2955, 2957], 3], [[2958, 2960], 2], [2961, 3], [[2962, 2965], 2], [[2966, 2968], 3], [[2969, 2970], 2], [2971, 3], [2972, 2], [2973, 3], [[2974, 2975], 2], [[2976, 2978], 3], [[2979, 2980], 2], [[2981, 2983], 3], [[2984, 2986], 2], [[2987, 2989], 3], [[2990, 2997], 2], [2998, 2], [[2999, 3001], 2], [[3002, 3005], 3], [[3006, 3010], 2], [[3011, 3013], 3], [[3014, 3016], 2], [3017, 3], [[3018, 3021], 2], [[3022, 3023], 3], [3024, 2], [[3025, 3030], 3], [3031, 2], [[3032, 3045], 3], [3046, 2], [[3047, 3055], 2], [[3056, 3058], 2], [[3059, 3066], 2], [[3067, 3071], 3], [3072, 2], [[3073, 3075], 2], [3076, 2], [[3077, 3084], 2], [3085, 3], [[3086, 3088], 2], [3089, 3], [[3090, 3112], 2], [3113, 3], [[3114, 3123], 2], [3124, 2], [[3125, 3129], 2], [[3130, 3131], 3], [3132, 2], [3133, 2], [[3134, 3140], 2], [3141, 3], [[3142, 3144], 2], [3145, 3], [[3146, 3149], 2], [[3150, 3156], 3], [[3157, 3158], 2], [3159, 3], [[3160, 3161], 2], [3162, 2], [[3163, 3164], 3], [3165, 2], [[3166, 3167], 3], [[3168, 3169], 2], [[3170, 3171], 2], [[3172, 3173], 3], [[3174, 3183], 2], [[3184, 3190], 3], [3191, 2], [[3192, 3199], 2], [3200, 2], [3201, 2], [[3202, 3203], 2], [3204, 2], [[3205, 3212], 2], [3213, 3], [[3214, 3216], 2], [3217, 3], [[3218, 3240], 2], [3241, 3], [[3242, 3251], 2], [3252, 3], [[3253, 3257], 2], [[3258, 3259], 3], [[3260, 3261], 2], [[3262, 3268], 2], [3269, 3], [[3270, 3272], 2], [3273, 3], [[3274, 3277], 2], [[3278, 3284], 3], [[3285, 3286], 2], [[3287, 3292], 3], [3293, 2], [3294, 2], [3295, 3], [[3296, 3297], 2], [[3298, 3299], 2], [[3300, 3301], 3], [[3302, 3311], 2], [3312, 3], [[3313, 3314], 2], [3315, 2], [[3316, 3327], 3], [3328, 2], [3329, 2], [[3330, 3331], 2], [3332, 2], [[3333, 3340], 2], [3341, 3], [[3342, 3344], 2], [3345, 3], [[3346, 3368], 2], [3369, 2], [[3370, 3385], 2], [3386, 2], [[3387, 3388], 2], [3389, 2], [[3390, 3395], 2], [3396, 2], [3397, 3], [[3398, 3400], 2], [3401, 3], [[3402, 3405], 2], [3406, 2], [3407, 2], [[3408, 3411], 3], [[3412, 3414], 2], [3415, 2], [[3416, 3422], 2], [3423, 2], [[3424, 3425], 2], [[3426, 3427], 2], [[3428, 3429], 3], [[3430, 3439], 2], [[3440, 3445], 2], [[3446, 3448], 2], [3449, 2], [[3450, 3455], 2], [3456, 3], [3457, 2], [[3458, 3459], 2], [3460, 3], [[3461, 3478], 2], [[3479, 3481], 3], [[3482, 3505], 2], [3506, 3], [[3507, 3515], 2], [3516, 3], [3517, 2], [[3518, 3519], 3], [[3520, 3526], 2], [[3527, 3529], 3], [3530, 2], [[3531, 3534], 3], [[3535, 3540], 2], [3541, 3], [3542, 2], [3543, 3], [[3544, 3551], 2], [[3552, 3557], 3], [[3558, 3567], 2], [[3568, 3569], 3], [[3570, 3571], 2], [3572, 2], [[3573, 3584], 3], [[3585, 3634], 2], [3635, 1, "\u0E4D\u0E32"], [[3636, 3642], 2], [[3643, 3646], 3], [3647, 2], [[3648, 3662], 2], [3663, 2], [[3664, 3673], 2], [[3674, 3675], 2], [[3676, 3712], 3], [[3713, 3714], 2], [3715, 3], [3716, 2], [3717, 3], [3718, 2], [[3719, 3720], 2], [3721, 2], [3722, 2], [3723, 3], [3724, 2], [3725, 2], [[3726, 3731], 2], [[3732, 3735], 2], [3736, 2], [[3737, 3743], 2], [3744, 2], [[3745, 3747], 2], [3748, 3], [3749, 2], [3750, 3], [3751, 2], [[3752, 3753], 2], [[3754, 3755], 2], [3756, 2], [[3757, 3762], 2], [3763, 1, "\u0ECD\u0EB2"], [[3764, 3769], 2], [3770, 2], [[3771, 3773], 2], [[3774, 3775], 3], [[3776, 3780], 2], [3781, 3], [3782, 2], [3783, 3], [[3784, 3789], 2], [3790, 2], [3791, 3], [[3792, 3801], 2], [[3802, 3803], 3], [3804, 1, "\u0EAB\u0E99"], [3805, 1, "\u0EAB\u0EA1"], [[3806, 3807], 2], [[3808, 3839], 3], [3840, 2], [[3841, 3850], 2], [3851, 2], [3852, 1, "\u0F0B"], [[3853, 3863], 2], [[3864, 3865], 2], [[3866, 3871], 2], [[3872, 3881], 2], [[3882, 3892], 2], [3893, 2], [3894, 2], [3895, 2], [3896, 2], [3897, 2], [[3898, 3901], 2], [[3902, 3906], 2], [3907, 1, "\u0F42\u0FB7"], [[3908, 3911], 2], [3912, 3], [[3913, 3916], 2], [3917, 1, "\u0F4C\u0FB7"], [[3918, 3921], 2], [3922, 1, "\u0F51\u0FB7"], [[3923, 3926], 2], [3927, 1, "\u0F56\u0FB7"], [[3928, 3931], 2], [3932, 1, "\u0F5B\u0FB7"], [[3933, 3944], 2], [3945, 1, "\u0F40\u0FB5"], [3946, 2], [[3947, 3948], 2], [[3949, 3952], 3], [[3953, 3954], 2], [3955, 1, "\u0F71\u0F72"], [3956, 2], [3957, 1, "\u0F71\u0F74"], [3958, 1, "\u0FB2\u0F80"], [3959, 1, "\u0FB2\u0F71\u0F80"], [3960, 1, "\u0FB3\u0F80"], [3961, 1, "\u0FB3\u0F71\u0F80"], [[3962, 3968], 2], [3969, 1, "\u0F71\u0F80"], [[3970, 3972], 2], [3973, 2], [[3974, 3979], 2], [[3980, 3983], 2], [[3984, 3986], 2], [3987, 1, "\u0F92\u0FB7"], [[3988, 3989], 2], [3990, 2], [3991, 2], [3992, 3], [[3993, 3996], 2], [3997, 1, "\u0F9C\u0FB7"], [[3998, 4001], 2], [4002, 1, "\u0FA1\u0FB7"], [[4003, 4006], 2], [4007, 1, "\u0FA6\u0FB7"], [[4008, 4011], 2], [4012, 1, "\u0FAB\u0FB7"], [4013, 2], [[4014, 4016], 2], [[4017, 4023], 2], [4024, 2], [4025, 1, "\u0F90\u0FB5"], [[4026, 4028], 2], [4029, 3], [[4030, 4037], 2], [4038, 2], [[4039, 4044], 2], [4045, 3], [4046, 2], [4047, 2], [[4048, 4049], 2], [[4050, 4052], 2], [[4053, 4056], 2], [[4057, 4058], 2], [[4059, 4095], 3], [[4096, 4129], 2], [4130, 2], [[4131, 4135], 2], [4136, 2], [[4137, 4138], 2], [4139, 2], [[4140, 4146], 2], [[4147, 4149], 2], [[4150, 4153], 2], [[4154, 4159], 2], [[4160, 4169], 2], [[4170, 4175], 2], [[4176, 4185], 2], [[4186, 4249], 2], [[4250, 4253], 2], [[4254, 4255], 2], [4256, 1, "\u2D00"], [4257, 1, "\u2D01"], [4258, 1, "\u2D02"], [4259, 1, "\u2D03"], [4260, 1, "\u2D04"], [4261, 1, "\u2D05"], [4262, 1, "\u2D06"], [4263, 1, "\u2D07"], [4264, 1, "\u2D08"], [4265, 1, "\u2D09"], [4266, 1, "\u2D0A"], [4267, 1, "\u2D0B"], [4268, 1, "\u2D0C"], [4269, 1, "\u2D0D"], [4270, 1, "\u2D0E"], [4271, 1, "\u2D0F"], [4272, 1, "\u2D10"], [4273, 1, "\u2D11"], [4274, 1, "\u2D12"], [4275, 1, "\u2D13"], [4276, 1, "\u2D14"], [4277, 1, "\u2D15"], [4278, 1, "\u2D16"], [4279, 1, "\u2D17"], [4280, 1, "\u2D18"], [4281, 1, "\u2D19"], [4282, 1, "\u2D1A"], [4283, 1, "\u2D1B"], [4284, 1, "\u2D1C"], [4285, 1, "\u2D1D"], [4286, 1, "\u2D1E"], [4287, 1, "\u2D1F"], [4288, 1, "\u2D20"], [4289, 1, "\u2D21"], [4290, 1, "\u2D22"], [4291, 1, "\u2D23"], [4292, 1, "\u2D24"], [4293, 1, "\u2D25"], [4294, 3], [4295, 1, "\u2D27"], [[4296, 4300], 3], [4301, 1, "\u2D2D"], [[4302, 4303], 3], [[4304, 4342], 2], [[4343, 4344], 2], [[4345, 4346], 2], [4347, 2], [4348, 1, "\u10DC"], [[4349, 4351], 2], [[4352, 4441], 2], [[4442, 4446], 2], [[4447, 4448], 7], [[4449, 4514], 2], [[4515, 4519], 2], [[4520, 4601], 2], [[4602, 4607], 2], [[4608, 4614], 2], [4615, 2], [[4616, 4678], 2], [4679, 2], [4680, 2], [4681, 3], [[4682, 4685], 2], [[4686, 4687], 3], [[4688, 4694], 2], [4695, 3], [4696, 2], [4697, 3], [[4698, 4701], 2], [[4702, 4703], 3], [[4704, 4742], 2], [4743, 2], [4744, 2], [4745, 3], [[4746, 4749], 2], [[4750, 4751], 3], [[4752, 4782], 2], [4783, 2], [4784, 2], [4785, 3], [[4786, 4789], 2], [[4790, 4791], 3], [[4792, 4798], 2], [4799, 3], [4800, 2], [4801, 3], [[4802, 4805], 2], [[4806, 4807], 3], [[4808, 4814], 2], [4815, 2], [[4816, 4822], 2], [4823, 3], [[4824, 4846], 2], [4847, 2], [[4848, 4878], 2], [4879, 2], [4880, 2], [4881, 3], [[4882, 4885], 2], [[4886, 4887], 3], [[4888, 4894], 2], [4895, 2], [[4896, 4934], 2], [4935, 2], [[4936, 4954], 2], [[4955, 4956], 3], [[4957, 4958], 2], [4959, 2], [4960, 2], [[4961, 4988], 2], [[4989, 4991], 3], [[4992, 5007], 2], [[5008, 5017], 2], [[5018, 5023], 3], [[5024, 5108], 2], [5109, 2], [[5110, 5111], 3], [5112, 1, "\u13F0"], [5113, 1, "\u13F1"], [5114, 1, "\u13F2"], [5115, 1, "\u13F3"], [5116, 1, "\u13F4"], [5117, 1, "\u13F5"], [[5118, 5119], 3], [5120, 2], [[5121, 5740], 2], [[5741, 5742], 2], [[5743, 5750], 2], [[5751, 5759], 2], [5760, 3], [[5761, 5786], 2], [[5787, 5788], 2], [[5789, 5791], 3], [[5792, 5866], 2], [[5867, 5872], 2], [[5873, 5880], 2], [[5881, 5887], 3], [[5888, 5900], 2], [5901, 2], [[5902, 5908], 2], [5909, 2], [[5910, 5918], 3], [5919, 2], [[5920, 5940], 2], [[5941, 5942], 2], [[5943, 5951], 3], [[5952, 5971], 2], [[5972, 5983], 3], [[5984, 5996], 2], [5997, 3], [[5998, 6e3], 2], [6001, 3], [[6002, 6003], 2], [[6004, 6015], 3], [[6016, 6067], 2], [[6068, 6069], 7], [[6070, 6099], 2], [[6100, 6102], 2], [6103, 2], [[6104, 6107], 2], [6108, 2], [6109, 2], [[6110, 6111], 3], [[6112, 6121], 2], [[6122, 6127], 3], [[6128, 6137], 2], [[6138, 6143], 3], [[6144, 6154], 2], [[6155, 6158], 7], [6159, 7], [[6160, 6169], 2], [[6170, 6175], 3], [[6176, 6263], 2], [6264, 2], [[6265, 6271], 3], [[6272, 6313], 2], [6314, 2], [[6315, 6319], 3], [[6320, 6389], 2], [[6390, 6399], 3], [[6400, 6428], 2], [[6429, 6430], 2], [6431, 3], [[6432, 6443], 2], [[6444, 6447], 3], [[6448, 6459], 2], [[6460, 6463], 3], [6464, 2], [[6465, 6467], 3], [[6468, 6469], 2], [[6470, 6509], 2], [[6510, 6511], 3], [[6512, 6516], 2], [[6517, 6527], 3], [[6528, 6569], 2], [[6570, 6571], 2], [[6572, 6575], 3], [[6576, 6601], 2], [[6602, 6607], 3], [[6608, 6617], 2], [6618, 2], [[6619, 6621], 3], [[6622, 6623], 2], [[6624, 6655], 2], [[6656, 6683], 2], [[6684, 6685], 3], [[6686, 6687], 2], [[6688, 6750], 2], [6751, 3], [[6752, 6780], 2], [[6781, 6782], 3], [[6783, 6793], 2], [[6794, 6799], 3], [[6800, 6809], 2], [[6810, 6815], 3], [[6816, 6822], 2], [6823, 2], [[6824, 6829], 2], [[6830, 6831], 3], [[6832, 6845], 2], [6846, 2], [[6847, 6848], 2], [[6849, 6862], 2], [[6863, 6911], 3], [[6912, 6987], 2], [6988, 2], [6989, 3], [[6990, 6991], 2], [[6992, 7001], 2], [[7002, 7018], 2], [[7019, 7027], 2], [[7028, 7036], 2], [[7037, 7038], 2], [7039, 2], [[7040, 7082], 2], [[7083, 7085], 2], [[7086, 7097], 2], [[7098, 7103], 2], [[7104, 7155], 2], [[7156, 7163], 3], [[7164, 7167], 2], [[7168, 7223], 2], [[7224, 7226], 3], [[7227, 7231], 2], [[7232, 7241], 2], [[7242, 7244], 3], [[7245, 7293], 2], [[7294, 7295], 2], [7296, 1, "\u0432"], [7297, 1, "\u0434"], [7298, 1, "\u043E"], [7299, 1, "\u0441"], [[7300, 7301], 1, "\u0442"], [7302, 1, "\u044A"], [7303, 1, "\u0463"], [7304, 1, "\uA64B"], [7305, 1, "\u1C8A"], [7306, 2], [[7307, 7311], 3], [7312, 1, "\u10D0"], [7313, 1, "\u10D1"], [7314, 1, "\u10D2"], [7315, 1, "\u10D3"], [7316, 1, "\u10D4"], [7317, 1, "\u10D5"], [7318, 1, "\u10D6"], [7319, 1, "\u10D7"], [7320, 1, "\u10D8"], [7321, 1, "\u10D9"], [7322, 1, "\u10DA"], [7323, 1, "\u10DB"], [7324, 1, "\u10DC"], [7325, 1, "\u10DD"], [7326, 1, "\u10DE"], [7327, 1, "\u10DF"], [7328, 1, "\u10E0"], [7329, 1, "\u10E1"], [7330, 1, "\u10E2"], [7331, 1, "\u10E3"], [7332, 1, "\u10E4"], [7333, 1, "\u10E5"], [7334, 1, "\u10E6"], [7335, 1, "\u10E7"], [7336, 1, "\u10E8"], [7337, 1, "\u10E9"], [7338, 1, "\u10EA"], [7339, 1, "\u10EB"], [7340, 1, "\u10EC"], [7341, 1, "\u10ED"], [7342, 1, "\u10EE"], [7343, 1, "\u10EF"], [7344, 1, "\u10F0"], [7345, 1, "\u10F1"], [7346, 1, "\u10F2"], [7347, 1, "\u10F3"], [7348, 1, "\u10F4"], [7349, 1, "\u10F5"], [7350, 1, "\u10F6"], [7351, 1, "\u10F7"], [7352, 1, "\u10F8"], [7353, 1, "\u10F9"], [7354, 1, "\u10FA"], [[7355, 7356], 3], [7357, 1, "\u10FD"], [7358, 1, "\u10FE"], [7359, 1, "\u10FF"], [[7360, 7367], 2], [[7368, 7375], 3], [[7376, 7378], 2], [7379, 2], [[7380, 7410], 2], [[7411, 7414], 2], [7415, 2], [[7416, 7417], 2], [7418, 2], [[7419, 7423], 3], [[7424, 7467], 2], [7468, 1, "a"], [7469, 1, "\xE6"], [7470, 1, "b"], [7471, 2], [7472, 1, "d"], [7473, 1, "e"], [7474, 1, "\u01DD"], [7475, 1, "g"], [7476, 1, "h"], [7477, 1, "i"], [7478, 1, "j"], [7479, 1, "k"], [7480, 1, "l"], [7481, 1, "m"], [7482, 1, "n"], [7483, 2], [7484, 1, "o"], [7485, 1, "\u0223"], [7486, 1, "p"], [7487, 1, "r"], [7488, 1, "t"], [7489, 1, "u"], [7490, 1, "w"], [7491, 1, "a"], [7492, 1, "\u0250"], [7493, 1, "\u0251"], [7494, 1, "\u1D02"], [7495, 1, "b"], [7496, 1, "d"], [7497, 1, "e"], [7498, 1, "\u0259"], [7499, 1, "\u025B"], [7500, 1, "\u025C"], [7501, 1, "g"], [7502, 2], [7503, 1, "k"], [7504, 1, "m"], [7505, 1, "\u014B"], [7506, 1, "o"], [7507, 1, "\u0254"], [7508, 1, "\u1D16"], [7509, 1, "\u1D17"], [7510, 1, "p"], [7511, 1, "t"], [7512, 1, "u"], [7513, 1, "\u1D1D"], [7514, 1, "\u026F"], [7515, 1, "v"], [7516, 1, "\u1D25"], [7517, 1, "\u03B2"], [7518, 1, "\u03B3"], [7519, 1, "\u03B4"], [7520, 1, "\u03C6"], [7521, 1, "\u03C7"], [7522, 1, "i"], [7523, 1, "r"], [7524, 1, "u"], [7525, 1, "v"], [7526, 1, "\u03B2"], [7527, 1, "\u03B3"], [7528, 1, "\u03C1"], [7529, 1, "\u03C6"], [7530, 1, "\u03C7"], [7531, 2], [[7532, 7543], 2], [7544, 1, "\u043D"], [[7545, 7578], 2], [7579, 1, "\u0252"], [7580, 1, "c"], [7581, 1, "\u0255"], [7582, 1, "\xF0"], [7583, 1, "\u025C"], [7584, 1, "f"], [7585, 1, "\u025F"], [7586, 1, "\u0261"], [7587, 1, "\u0265"], [7588, 1, "\u0268"], [7589, 1, "\u0269"], [7590, 1, "\u026A"], [7591, 1, "\u1D7B"], [7592, 1, "\u029D"], [7593, 1, "\u026D"], [7594, 1, "\u1D85"], [7595, 1, "\u029F"], [7596, 1, "\u0271"], [7597, 1, "\u0270"], [7598, 1, "\u0272"], [7599, 1, "\u0273"], [7600, 1, "\u0274"], [7601, 1, "\u0275"], [7602, 1, "\u0278"], [7603, 1, "\u0282"], [7604, 1, "\u0283"], [7605, 1, "\u01AB"], [7606, 1, "\u0289"], [7607, 1, "\u028A"], [7608, 1, "\u1D1C"], [7609, 1, "\u028B"], [7610, 1, "\u028C"], [7611, 1, "z"], [7612, 1, "\u0290"], [7613, 1, "\u0291"], [7614, 1, "\u0292"], [7615, 1, "\u03B8"], [[7616, 7619], 2], [[7620, 7626], 2], [[7627, 7654], 2], [[7655, 7669], 2], [[7670, 7673], 2], [7674, 2], [7675, 2], [7676, 2], [7677, 2], [[7678, 7679], 2], [7680, 1, "\u1E01"], [7681, 2], [7682, 1, "\u1E03"], [7683, 2], [7684, 1, "\u1E05"], [7685, 2], [7686, 1, "\u1E07"], [7687, 2], [7688, 1, "\u1E09"], [7689, 2], [7690, 1, "\u1E0B"], [7691, 2], [7692, 1, "\u1E0D"], [7693, 2], [7694, 1, "\u1E0F"], [7695, 2], [7696, 1, "\u1E11"], [7697, 2], [7698, 1, "\u1E13"], [7699, 2], [7700, 1, "\u1E15"], [7701, 2], [7702, 1, "\u1E17"], [7703, 2], [7704, 1, "\u1E19"], [7705, 2], [7706, 1, "\u1E1B"], [7707, 2], [7708, 1, "\u1E1D"], [7709, 2], [7710, 1, "\u1E1F"], [7711, 2], [7712, 1, "\u1E21"], [7713, 2], [7714, 1, "\u1E23"], [7715, 2], [7716, 1, "\u1E25"], [7717, 2], [7718, 1, "\u1E27"], [7719, 2], [7720, 1, "\u1E29"], [7721, 2], [7722, 1, "\u1E2B"], [7723, 2], [7724, 1, "\u1E2D"], [7725, 2], [7726, 1, "\u1E2F"], [7727, 2], [7728, 1, "\u1E31"], [7729, 2], [7730, 1, "\u1E33"], [7731, 2], [7732, 1, "\u1E35"], [7733, 2], [7734, 1, "\u1E37"], [7735, 2], [7736, 1, "\u1E39"], [7737, 2], [7738, 1, "\u1E3B"], [7739, 2], [7740, 1, "\u1E3D"], [7741, 2], [7742, 1, "\u1E3F"], [7743, 2], [7744, 1, "\u1E41"], [7745, 2], [7746, 1, "\u1E43"], [7747, 2], [7748, 1, "\u1E45"], [7749, 2], [7750, 1, "\u1E47"], [7751, 2], [7752, 1, "\u1E49"], [7753, 2], [7754, 1, "\u1E4B"], [7755, 2], [7756, 1, "\u1E4D"], [7757, 2], [7758, 1, "\u1E4F"], [7759, 2], [7760, 1, "\u1E51"], [7761, 2], [7762, 1, "\u1E53"], [7763, 2], [7764, 1, "\u1E55"], [7765, 2], [7766, 1, "\u1E57"], [7767, 2], [7768, 1, "\u1E59"], [7769, 2], [7770, 1, "\u1E5B"], [7771, 2], [7772, 1, "\u1E5D"], [7773, 2], [7774, 1, "\u1E5F"], [7775, 2], [7776, 1, "\u1E61"], [7777, 2], [7778, 1, "\u1E63"], [7779, 2], [7780, 1, "\u1E65"], [7781, 2], [7782, 1, "\u1E67"], [7783, 2], [7784, 1, "\u1E69"], [7785, 2], [7786, 1, "\u1E6B"], [7787, 2], [7788, 1, "\u1E6D"], [7789, 2], [7790, 1, "\u1E6F"], [7791, 2], [7792, 1, "\u1E71"], [7793, 2], [7794, 1, "\u1E73"], [7795, 2], [7796, 1, "\u1E75"], [7797, 2], [7798, 1, "\u1E77"], [7799, 2], [7800, 1, "\u1E79"], [7801, 2], [7802, 1, "\u1E7B"], [7803, 2], [7804, 1, "\u1E7D"], [7805, 2], [7806, 1, "\u1E7F"], [7807, 2], [7808, 1, "\u1E81"], [7809, 2], [7810, 1, "\u1E83"], [7811, 2], [7812, 1, "\u1E85"], [7813, 2], [7814, 1, "\u1E87"], [7815, 2], [7816, 1, "\u1E89"], [7817, 2], [7818, 1, "\u1E8B"], [7819, 2], [7820, 1, "\u1E8D"], [7821, 2], [7822, 1, "\u1E8F"], [7823, 2], [7824, 1, "\u1E91"], [7825, 2], [7826, 1, "\u1E93"], [7827, 2], [7828, 1, "\u1E95"], [[7829, 7833], 2], [7834, 1, "a\u02BE"], [7835, 1, "\u1E61"], [[7836, 7837], 2], [7838, 1, "\xDF"], [7839, 2], [7840, 1, "\u1EA1"], [7841, 2], [7842, 1, "\u1EA3"], [7843, 2], [7844, 1, "\u1EA5"], [7845, 2], [7846, 1, "\u1EA7"], [7847, 2], [7848, 1, "\u1EA9"], [7849, 2], [7850, 1, "\u1EAB"], [7851, 2], [7852, 1, "\u1EAD"], [7853, 2], [7854, 1, "\u1EAF"], [7855, 2], [7856, 1, "\u1EB1"], [7857, 2], [7858, 1, "\u1EB3"], [7859, 2], [7860, 1, "\u1EB5"], [7861, 2], [7862, 1, "\u1EB7"], [7863, 2], [7864, 1, "\u1EB9"], [7865, 2], [7866, 1, "\u1EBB"], [7867, 2], [7868, 1, "\u1EBD"], [7869, 2], [7870, 1, "\u1EBF"], [7871, 2], [7872, 1, "\u1EC1"], [7873, 2], [7874, 1, "\u1EC3"], [7875, 2], [7876, 1, "\u1EC5"], [7877, 2], [7878, 1, "\u1EC7"], [7879, 2], [7880, 1, "\u1EC9"], [7881, 2], [7882, 1, "\u1ECB"], [7883, 2], [7884, 1, "\u1ECD"], [7885, 2], [7886, 1, "\u1ECF"], [7887, 2], [7888, 1, "\u1ED1"], [7889, 2], [7890, 1, "\u1ED3"], [7891, 2], [7892, 1, "\u1ED5"], [7893, 2], [7894, 1, "\u1ED7"], [7895, 2], [7896, 1, "\u1ED9"], [7897, 2], [7898, 1, "\u1EDB"], [7899, 2], [7900, 1, "\u1EDD"], [7901, 2], [7902, 1, "\u1EDF"], [7903, 2], [7904, 1, "\u1EE1"], [7905, 2], [7906, 1, "\u1EE3"], [7907, 2], [7908, 1, "\u1EE5"], [7909, 2], [7910, 1, "\u1EE7"], [7911, 2], [7912, 1, "\u1EE9"], [7913, 2], [7914, 1, "\u1EEB"], [7915, 2], [7916, 1, "\u1EED"], [7917, 2], [7918, 1, "\u1EEF"], [7919, 2], [7920, 1, "\u1EF1"], [7921, 2], [7922, 1, "\u1EF3"], [7923, 2], [7924, 1, "\u1EF5"], [7925, 2], [7926, 1, "\u1EF7"], [7927, 2], [7928, 1, "\u1EF9"], [7929, 2], [7930, 1, "\u1EFB"], [7931, 2], [7932, 1, "\u1EFD"], [7933, 2], [7934, 1, "\u1EFF"], [7935, 2], [[7936, 7943], 2], [7944, 1, "\u1F00"], [7945, 1, "\u1F01"], [7946, 1, "\u1F02"], [7947, 1, "\u1F03"], [7948, 1, "\u1F04"], [7949, 1, "\u1F05"], [7950, 1, "\u1F06"], [7951, 1, "\u1F07"], [[7952, 7957], 2], [[7958, 7959], 3], [7960, 1, "\u1F10"], [7961, 1, "\u1F11"], [7962, 1, "\u1F12"], [7963, 1, "\u1F13"], [7964, 1, "\u1F14"], [7965, 1, "\u1F15"], [[7966, 7967], 3], [[7968, 7975], 2], [7976, 1, "\u1F20"], [7977, 1, "\u1F21"], [7978, 1, "\u1F22"], [7979, 1, "\u1F23"], [7980, 1, "\u1F24"], [7981, 1, "\u1F25"], [7982, 1, "\u1F26"], [7983, 1, "\u1F27"], [[7984, 7991], 2], [7992, 1, "\u1F30"], [7993, 1, "\u1F31"], [7994, 1, "\u1F32"], [7995, 1, "\u1F33"], [7996, 1, "\u1F34"], [7997, 1, "\u1F35"], [7998, 1, "\u1F36"], [7999, 1, "\u1F37"], [[8e3, 8005], 2], [[8006, 8007], 3], [8008, 1, "\u1F40"], [8009, 1, "\u1F41"], [8010, 1, "\u1F42"], [8011, 1, "\u1F43"], [8012, 1, "\u1F44"], [8013, 1, "\u1F45"], [[8014, 8015], 3], [[8016, 8023], 2], [8024, 3], [8025, 1, "\u1F51"], [8026, 3], [8027, 1, "\u1F53"], [8028, 3], [8029, 1, "\u1F55"], [8030, 3], [8031, 1, "\u1F57"], [[8032, 8039], 2], [8040, 1, "\u1F60"], [8041, 1, "\u1F61"], [8042, 1, "\u1F62"], [8043, 1, "\u1F63"], [8044, 1, "\u1F64"], [8045, 1, "\u1F65"], [8046, 1, "\u1F66"], [8047, 1, "\u1F67"], [8048, 2], [8049, 1, "\u03AC"], [8050, 2], [8051, 1, "\u03AD"], [8052, 2], [8053, 1, "\u03AE"], [8054, 2], [8055, 1, "\u03AF"], [8056, 2], [8057, 1, "\u03CC"], [8058, 2], [8059, 1, "\u03CD"], [8060, 2], [8061, 1, "\u03CE"], [[8062, 8063], 3], [8064, 1, "\u1F00\u03B9"], [8065, 1, "\u1F01\u03B9"], [8066, 1, "\u1F02\u03B9"], [8067, 1, "\u1F03\u03B9"], [8068, 1, "\u1F04\u03B9"], [8069, 1, "\u1F05\u03B9"], [8070, 1, "\u1F06\u03B9"], [8071, 1, "\u1F07\u03B9"], [8072, 1, "\u1F00\u03B9"], [8073, 1, "\u1F01\u03B9"], [8074, 1, "\u1F02\u03B9"], [8075, 1, "\u1F03\u03B9"], [8076, 1, "\u1F04\u03B9"], [8077, 1, "\u1F05\u03B9"], [8078, 1, "\u1F06\u03B9"], [8079, 1, "\u1F07\u03B9"], [8080, 1, "\u1F20\u03B9"], [8081, 1, "\u1F21\u03B9"], [8082, 1, "\u1F22\u03B9"], [8083, 1, "\u1F23\u03B9"], [8084, 1, "\u1F24\u03B9"], [8085, 1, "\u1F25\u03B9"], [8086, 1, "\u1F26\u03B9"], [8087, 1, "\u1F27\u03B9"], [8088, 1, "\u1F20\u03B9"], [8089, 1, "\u1F21\u03B9"], [8090, 1, "\u1F22\u03B9"], [8091, 1, "\u1F23\u03B9"], [8092, 1, "\u1F24\u03B9"], [8093, 1, "\u1F25\u03B9"], [8094, 1, "\u1F26\u03B9"], [8095, 1, "\u1F27\u03B9"], [8096, 1, "\u1F60\u03B9"], [8097, 1, "\u1F61\u03B9"], [8098, 1, "\u1F62\u03B9"], [8099, 1, "\u1F63\u03B9"], [8100, 1, "\u1F64\u03B9"], [8101, 1, "\u1F65\u03B9"], [8102, 1, "\u1F66\u03B9"], [8103, 1, "\u1F67\u03B9"], [8104, 1, "\u1F60\u03B9"], [8105, 1, "\u1F61\u03B9"], [8106, 1, "\u1F62\u03B9"], [8107, 1, "\u1F63\u03B9"], [8108, 1, "\u1F64\u03B9"], [8109, 1, "\u1F65\u03B9"], [8110, 1, "\u1F66\u03B9"], [8111, 1, "\u1F67\u03B9"], [[8112, 8113], 2], [8114, 1, "\u1F70\u03B9"], [8115, 1, "\u03B1\u03B9"], [8116, 1, "\u03AC\u03B9"], [8117, 3], [8118, 2], [8119, 1, "\u1FB6\u03B9"], [8120, 1, "\u1FB0"], [8121, 1, "\u1FB1"], [8122, 1, "\u1F70"], [8123, 1, "\u03AC"], [8124, 1, "\u03B1\u03B9"], [8125, 1, " \u0313"], [8126, 1, "\u03B9"], [8127, 1, " \u0313"], [8128, 1, " \u0342"], [8129, 1, " \u0308\u0342"], [8130, 1, "\u1F74\u03B9"], [8131, 1, "\u03B7\u03B9"], [8132, 1, "\u03AE\u03B9"], [8133, 3], [8134, 2], [8135, 1, "\u1FC6\u03B9"], [8136, 1, "\u1F72"], [8137, 1, "\u03AD"], [8138, 1, "\u1F74"], [8139, 1, "\u03AE"], [8140, 1, "\u03B7\u03B9"], [8141, 1, " \u0313\u0300"], [8142, 1, " \u0313\u0301"], [8143, 1, " \u0313\u0342"], [[8144, 8146], 2], [8147, 1, "\u0390"], [[8148, 8149], 3], [[8150, 8151], 2], [8152, 1, "\u1FD0"], [8153, 1, "\u1FD1"], [8154, 1, "\u1F76"], [8155, 1, "\u03AF"], [8156, 3], [8157, 1, " \u0314\u0300"], [8158, 1, " \u0314\u0301"], [8159, 1, " \u0314\u0342"], [[8160, 8162], 2], [8163, 1, "\u03B0"], [[8164, 8167], 2], [8168, 1, "\u1FE0"], [8169, 1, "\u1FE1"], [8170, 1, "\u1F7A"], [8171, 1, "\u03CD"], [8172, 1, "\u1FE5"], [8173, 1, " \u0308\u0300"], [8174, 1, " \u0308\u0301"], [8175, 1, "`"], [[8176, 8177], 3], [8178, 1, "\u1F7C\u03B9"], [8179, 1, "\u03C9\u03B9"], [8180, 1, "\u03CE\u03B9"], [8181, 3], [8182, 2], [8183, 1, "\u1FF6\u03B9"], [8184, 1, "\u1F78"], [8185, 1, "\u03CC"], [8186, 1, "\u1F7C"], [8187, 1, "\u03CE"], [8188, 1, "\u03C9\u03B9"], [8189, 1, " \u0301"], [8190, 1, " \u0314"], [8191, 3], [[8192, 8202], 1, " "], [8203, 7], [[8204, 8205], 6, ""], [[8206, 8207], 3], [8208, 2], [8209, 1, "\u2010"], [[8210, 8214], 2], [8215, 1, " \u0333"], [[8216, 8227], 2], [[8228, 8230], 3], [8231, 2], [[8232, 8238], 3], [8239, 1, " "], [[8240, 8242], 2], [8243, 1, "\u2032\u2032"], [8244, 1, "\u2032\u2032\u2032"], [8245, 2], [8246, 1, "\u2035\u2035"], [8247, 1, "\u2035\u2035\u2035"], [[8248, 8251], 2], [8252, 1, "!!"], [8253, 2], [8254, 1, " \u0305"], [[8255, 8262], 2], [8263, 1, "??"], [8264, 1, "?!"], [8265, 1, "!?"], [[8266, 8269], 2], [[8270, 8274], 2], [[8275, 8276], 2], [[8277, 8278], 2], [8279, 1, "\u2032\u2032\u2032\u2032"], [[8280, 8286], 2], [8287, 1, " "], [[8288, 8291], 7], [8292, 7], [8293, 3], [[8294, 8297], 3], [[8298, 8303], 7], [8304, 1, "0"], [8305, 1, "i"], [[8306, 8307], 3], [8308, 1, "4"], [8309, 1, "5"], [8310, 1, "6"], [8311, 1, "7"], [8312, 1, "8"], [8313, 1, "9"], [8314, 1, "+"], [8315, 1, "\u2212"], [8316, 1, "="], [8317, 1, "("], [8318, 1, ")"], [8319, 1, "n"], [8320, 1, "0"], [8321, 1, "1"], [8322, 1, "2"], [8323, 1, "3"], [8324, 1, "4"], [8325, 1, "5"], [8326, 1, "6"], [8327, 1, "7"], [8328, 1, "8"], [8329, 1, "9"], [8330, 1, "+"], [8331, 1, "\u2212"], [8332, 1, "="], [8333, 1, "("], [8334, 1, ")"], [8335, 3], [8336, 1, "a"], [8337, 1, "e"], [8338, 1, "o"], [8339, 1, "x"], [8340, 1, "\u0259"], [8341, 1, "h"], [8342, 1, "k"], [8343, 1, "l"], [8344, 1, "m"], [8345, 1, "n"], [8346, 1, "p"], [8347, 1, "s"], [8348, 1, "t"], [[8349, 8351], 3], [[8352, 8359], 2], [8360, 1, "rs"], [[8361, 8362], 2], [8363, 2], [8364, 2], [[8365, 8367], 2], [[8368, 8369], 2], [[8370, 8373], 2], [[8374, 8376], 2], [8377, 2], [8378, 2], [[8379, 8381], 2], [8382, 2], [8383, 2], [8384, 2], [[8385, 8399], 3], [[8400, 8417], 2], [[8418, 8419], 2], [[8420, 8426], 2], [8427, 2], [[8428, 8431], 2], [8432, 2], [[8433, 8447], 3], [8448, 1, "a/c"], [8449, 1, "a/s"], [8450, 1, "c"], [8451, 1, "\xB0c"], [8452, 2], [8453, 1, "c/o"], [8454, 1, "c/u"], [8455, 1, "\u025B"], [8456, 2], [8457, 1, "\xB0f"], [8458, 1, "g"], [[8459, 8462], 1, "h"], [8463, 1, "\u0127"], [[8464, 8465], 1, "i"], [[8466, 8467], 1, "l"], [8468, 2], [8469, 1, "n"], [8470, 1, "no"], [[8471, 8472], 2], [8473, 1, "p"], [8474, 1, "q"], [[8475, 8477], 1, "r"], [[8478, 8479], 2], [8480, 1, "sm"], [8481, 1, "tel"], [8482, 1, "tm"], [8483, 2], [8484, 1, "z"], [8485, 2], [8486, 1, "\u03C9"], [8487, 2], [8488, 1, "z"], [8489, 2], [8490, 1, "k"], [8491, 1, "\xE5"], [8492, 1, "b"], [8493, 1, "c"], [8494, 2], [[8495, 8496], 1, "e"], [8497, 1, "f"], [8498, 1, "\u214E"], [8499, 1, "m"], [8500, 1, "o"], [8501, 1, "\u05D0"], [8502, 1, "\u05D1"], [8503, 1, "\u05D2"], [8504, 1, "\u05D3"], [8505, 1, "i"], [8506, 2], [8507, 1, "fax"], [8508, 1, "\u03C0"], [[8509, 8510], 1, "\u03B3"], [8511, 1, "\u03C0"], [8512, 1, "\u2211"], [[8513, 8516], 2], [[8517, 8518], 1, "d"], [8519, 1, "e"], [8520, 1, "i"], [8521, 1, "j"], [[8522, 8523], 2], [8524, 2], [8525, 2], [8526, 2], [8527, 2], [8528, 1, "1\u20447"], [8529, 1, "1\u20449"], [8530, 1, "1\u204410"], [8531, 1, "1\u20443"], [8532, 1, "2\u20443"], [8533, 1, "1\u20445"], [8534, 1, "2\u20445"], [8535, 1, "3\u20445"], [8536, 1, "4\u20445"], [8537, 1, "1\u20446"], [8538, 1, "5\u20446"], [8539, 1, "1\u20448"], [8540, 1, "3\u20448"], [8541, 1, "5\u20448"], [8542, 1, "7\u20448"], [8543, 1, "1\u2044"], [8544, 1, "i"], [8545, 1, "ii"], [8546, 1, "iii"], [8547, 1, "iv"], [8548, 1, "v"], [8549, 1, "vi"], [8550, 1, "vii"], [8551, 1, "viii"], [8552, 1, "ix"], [8553, 1, "x"], [8554, 1, "xi"], [8555, 1, "xii"], [8556, 1, "l"], [8557, 1, "c"], [8558, 1, "d"], [8559, 1, "m"], [8560, 1, "i"], [8561, 1, "ii"], [8562, 1, "iii"], [8563, 1, "iv"], [8564, 1, "v"], [8565, 1, "vi"], [8566, 1, "vii"], [8567, 1, "viii"], [8568, 1, "ix"], [8569, 1, "x"], [8570, 1, "xi"], [8571, 1, "xii"], [8572, 1, "l"], [8573, 1, "c"], [8574, 1, "d"], [8575, 1, "m"], [[8576, 8578], 2], [8579, 1, "\u2184"], [8580, 2], [[8581, 8584], 2], [8585, 1, "0\u20443"], [[8586, 8587], 2], [[8588, 8591], 3], [[8592, 8682], 2], [[8683, 8691], 2], [[8692, 8703], 2], [[8704, 8747], 2], [8748, 1, "\u222B\u222B"], [8749, 1, "\u222B\u222B\u222B"], [8750, 2], [8751, 1, "\u222E\u222E"], [8752, 1, "\u222E\u222E\u222E"], [[8753, 8945], 2], [[8946, 8959], 2], [8960, 2], [8961, 2], [[8962, 9e3], 2], [9001, 1, "\u3008"], [9002, 1, "\u3009"], [[9003, 9082], 2], [9083, 2], [9084, 2], [[9085, 9114], 2], [[9115, 9166], 2], [[9167, 9168], 2], [[9169, 9179], 2], [[9180, 9191], 2], [9192, 2], [[9193, 9203], 2], [[9204, 9210], 2], [[9211, 9214], 2], [9215, 2], [[9216, 9252], 2], [[9253, 9254], 2], [[9255, 9257], 2], [[9258, 9279], 3], [[9280, 9290], 2], [[9291, 9311], 3], [9312, 1, "1"], [9313, 1, "2"], [9314, 1, "3"], [9315, 1, "4"], [9316, 1, "5"], [9317, 1, "6"], [9318, 1, "7"], [9319, 1, "8"], [9320, 1, "9"], [9321, 1, "10"], [9322, 1, "11"], [9323, 1, "12"], [9324, 1, "13"], [9325, 1, "14"], [9326, 1, "15"], [9327, 1, "16"], [9328, 1, "17"], [9329, 1, "18"], [9330, 1, "19"], [9331, 1, "20"], [9332, 1, "(1)"], [9333, 1, "(2)"], [9334, 1, "(3)"], [9335, 1, "(4)"], [9336, 1, "(5)"], [9337, 1, "(6)"], [9338, 1, "(7)"], [9339, 1, "(8)"], [9340, 1, "(9)"], [9341, 1, "(10)"], [9342, 1, "(11)"], [9343, 1, "(12)"], [9344, 1, "(13)"], [9345, 1, "(14)"], [9346, 1, "(15)"], [9347, 1, "(16)"], [9348, 1, "(17)"], [9349, 1, "(18)"], [9350, 1, "(19)"], [9351, 1, "(20)"], [[9352, 9371], 3], [9372, 1, "(a)"], [9373, 1, "(b)"], [9374, 1, "(c)"], [9375, 1, "(d)"], [9376, 1, "(e)"], [9377, 1, "(f)"], [9378, 1, "(g)"], [9379, 1, "(h)"], [9380, 1, "(i)"], [9381, 1, "(j)"], [9382, 1, "(k)"], [9383, 1, "(l)"], [9384, 1, "(m)"], [9385, 1, "(n)"], [9386, 1, "(o)"], [9387, 1, "(p)"], [9388, 1, "(q)"], [9389, 1, "(r)"], [9390, 1, "(s)"], [9391, 1, "(t)"], [9392, 1, "(u)"], [9393, 1, "(v)"], [9394, 1, "(w)"], [9395, 1, "(x)"], [9396, 1, "(y)"], [9397, 1, "(z)"], [9398, 1, "a"], [9399, 1, "b"], [9400, 1, "c"], [9401, 1, "d"], [9402, 1, "e"], [9403, 1, "f"], [9404, 1, "g"], [9405, 1, "h"], [9406, 1, "i"], [9407, 1, "j"], [9408, 1, "k"], [9409, 1, "l"], [9410, 1, "m"], [9411, 1, "n"], [9412, 1, "o"], [9413, 1, "p"], [9414, 1, "q"], [9415, 1, "r"], [9416, 1, "s"], [9417, 1, "t"], [9418, 1, "u"], [9419, 1, "v"], [9420, 1, "w"], [9421, 1, "x"], [9422, 1, "y"], [9423, 1, "z"], [9424, 1, "a"], [9425, 1, "b"], [9426, 1, "c"], [9427, 1, "d"], [9428, 1, "e"], [9429, 1, "f"], [9430, 1, "g"], [9431, 1, "h"], [9432, 1, "i"], [9433, 1, "j"], [9434, 1, "k"], [9435, 1, "l"], [9436, 1, "m"], [9437, 1, "n"], [9438, 1, "o"], [9439, 1, "p"], [9440, 1, "q"], [9441, 1, "r"], [9442, 1, "s"], [9443, 1, "t"], [9444, 1, "u"], [9445, 1, "v"], [9446, 1, "w"], [9447, 1, "x"], [9448, 1, "y"], [9449, 1, "z"], [9450, 1, "0"], [[9451, 9470], 2], [9471, 2], [[9472, 9621], 2], [[9622, 9631], 2], [[9632, 9711], 2], [[9712, 9719], 2], [[9720, 9727], 2], [[9728, 9747], 2], [[9748, 9749], 2], [[9750, 9751], 2], [9752, 2], [9753, 2], [[9754, 9839], 2], [[9840, 9841], 2], [[9842, 9853], 2], [[9854, 9855], 2], [[9856, 9865], 2], [[9866, 9873], 2], [[9874, 9884], 2], [9885, 2], [[9886, 9887], 2], [[9888, 9889], 2], [[9890, 9905], 2], [9906, 2], [[9907, 9916], 2], [[9917, 9919], 2], [[9920, 9923], 2], [[9924, 9933], 2], [9934, 2], [[9935, 9953], 2], [9954, 2], [9955, 2], [[9956, 9959], 2], [[9960, 9983], 2], [9984, 2], [[9985, 9988], 2], [9989, 2], [[9990, 9993], 2], [[9994, 9995], 2], [[9996, 10023], 2], [10024, 2], [[10025, 10059], 2], [10060, 2], [10061, 2], [10062, 2], [[10063, 10066], 2], [[10067, 10069], 2], [10070, 2], [10071, 2], [[10072, 10078], 2], [[10079, 10080], 2], [[10081, 10087], 2], [[10088, 10101], 2], [[10102, 10132], 2], [[10133, 10135], 2], [[10136, 10159], 2], [10160, 2], [[10161, 10174], 2], [10175, 2], [[10176, 10182], 2], [[10183, 10186], 2], [10187, 2], [10188, 2], [10189, 2], [[10190, 10191], 2], [[10192, 10219], 2], [[10220, 10223], 2], [[10224, 10239], 2], [[10240, 10495], 2], [[10496, 10763], 2], [10764, 1, "\u222B\u222B\u222B\u222B"], [[10765, 10867], 2], [10868, 1, "::="], [10869, 1, "=="], [10870, 1, "==="], [[10871, 10971], 2], [10972, 1, "\u2ADD\u0338"], [[10973, 11007], 2], [[11008, 11021], 2], [[11022, 11027], 2], [[11028, 11034], 2], [[11035, 11039], 2], [[11040, 11043], 2], [[11044, 11084], 2], [[11085, 11087], 2], [[11088, 11092], 2], [[11093, 11097], 2], [[11098, 11123], 2], [[11124, 11125], 3], [[11126, 11157], 2], [11158, 3], [11159, 2], [[11160, 11193], 2], [[11194, 11196], 2], [[11197, 11208], 2], [11209, 2], [[11210, 11217], 2], [11218, 2], [[11219, 11243], 2], [[11244, 11247], 2], [[11248, 11262], 2], [11263, 2], [11264, 1, "\u2C30"], [11265, 1, "\u2C31"], [11266, 1, "\u2C32"], [11267, 1, "\u2C33"], [11268, 1, "\u2C34"], [11269, 1, "\u2C35"], [11270, 1, "\u2C36"], [11271, 1, "\u2C37"], [11272, 1, "\u2C38"], [11273, 1, "\u2C39"], [11274, 1, "\u2C3A"], [11275, 1, "\u2C3B"], [11276, 1, "\u2C3C"], [11277, 1, "\u2C3D"], [11278, 1, "\u2C3E"], [11279, 1, "\u2C3F"], [11280, 1, "\u2C40"], [11281, 1, "\u2C41"], [11282, 1, "\u2C42"], [11283, 1, "\u2C43"], [11284, 1, "\u2C44"], [11285, 1, "\u2C45"], [11286, 1, "\u2C46"], [11287, 1, "\u2C47"], [11288, 1, "\u2C48"], [11289, 1, "\u2C49"], [11290, 1, "\u2C4A"], [11291, 1, "\u2C4B"], [11292, 1, "\u2C4C"], [11293, 1, "\u2C4D"], [11294, 1, "\u2C4E"], [11295, 1, "\u2C4F"], [11296, 1, "\u2C50"], [11297, 1, "\u2C51"], [11298, 1, "\u2C52"], [11299, 1, "\u2C53"], [11300, 1, "\u2C54"], [11301, 1, "\u2C55"], [11302, 1, "\u2C56"], [11303, 1, "\u2C57"], [11304, 1, "\u2C58"], [11305, 1, "\u2C59"], [11306, 1, "\u2C5A"], [11307, 1, "\u2C5B"], [11308, 1, "\u2C5C"], [11309, 1, "\u2C5D"], [11310, 1, "\u2C5E"], [11311, 1, "\u2C5F"], [[11312, 11358], 2], [11359, 2], [11360, 1, "\u2C61"], [11361, 2], [11362, 1, "\u026B"], [11363, 1, "\u1D7D"], [11364, 1, "\u027D"], [[11365, 11366], 2], [11367, 1, "\u2C68"], [11368, 2], [11369, 1, "\u2C6A"], [11370, 2], [11371, 1, "\u2C6C"], [11372, 2], [11373, 1, "\u0251"], [11374, 1, "\u0271"], [11375, 1, "\u0250"], [11376, 1, "\u0252"], [11377, 2], [11378, 1, "\u2C73"], [11379, 2], [11380, 2], [11381, 1, "\u2C76"], [[11382, 11383], 2], [[11384, 11387], 2], [11388, 1, "j"], [11389, 1, "v"], [11390, 1, "\u023F"], [11391, 1, "\u0240"], [11392, 1, "\u2C81"], [11393, 2], [11394, 1, "\u2C83"], [11395, 2], [11396, 1, "\u2C85"], [11397, 2], [11398, 1, "\u2C87"], [11399, 2], [11400, 1, "\u2C89"], [11401, 2], [11402, 1, "\u2C8B"], [11403, 2], [11404, 1, "\u2C8D"], [11405, 2], [11406, 1, "\u2C8F"], [11407, 2], [11408, 1, "\u2C91"], [11409, 2], [11410, 1, "\u2C93"], [11411, 2], [11412, 1, "\u2C95"], [11413, 2], [11414, 1, "\u2C97"], [11415, 2], [11416, 1, "\u2C99"], [11417, 2], [11418, 1, "\u2C9B"], [11419, 2], [11420, 1, "\u2C9D"], [11421, 2], [11422, 1, "\u2C9F"], [11423, 2], [11424, 1, "\u2CA1"], [11425, 2], [11426, 1, "\u2CA3"], [11427, 2], [11428, 1, "\u2CA5"], [11429, 2], [11430, 1, "\u2CA7"], [11431, 2], [11432, 1, "\u2CA9"], [11433, 2], [11434, 1, "\u2CAB"], [11435, 2], [11436, 1, "\u2CAD"], [11437, 2], [11438, 1, "\u2CAF"], [11439, 2], [11440, 1, "\u2CB1"], [11441, 2], [11442, 1, "\u2CB3"], [11443, 2], [11444, 1, "\u2CB5"], [11445, 2], [11446, 1, "\u2CB7"], [11447, 2], [11448, 1, "\u2CB9"], [11449, 2], [11450, 1, "\u2CBB"], [11451, 2], [11452, 1, "\u2CBD"], [11453, 2], [11454, 1, "\u2CBF"], [11455, 2], [11456, 1, "\u2CC1"], [11457, 2], [11458, 1, "\u2CC3"], [11459, 2], [11460, 1, "\u2CC5"], [11461, 2], [11462, 1, "\u2CC7"], [11463, 2], [11464, 1, "\u2CC9"], [11465, 2], [11466, 1, "\u2CCB"], [11467, 2], [11468, 1, "\u2CCD"], [11469, 2], [11470, 1, "\u2CCF"], [11471, 2], [11472, 1, "\u2CD1"], [11473, 2], [11474, 1, "\u2CD3"], [11475, 2], [11476, 1, "\u2CD5"], [11477, 2], [11478, 1, "\u2CD7"], [11479, 2], [11480, 1, "\u2CD9"], [11481, 2], [11482, 1, "\u2CDB"], [11483, 2], [11484, 1, "\u2CDD"], [11485, 2], [11486, 1, "\u2CDF"], [11487, 2], [11488, 1, "\u2CE1"], [11489, 2], [11490, 1, "\u2CE3"], [[11491, 11492], 2], [[11493, 11498], 2], [11499, 1, "\u2CEC"], [11500, 2], [11501, 1, "\u2CEE"], [[11502, 11505], 2], [11506, 1, "\u2CF3"], [11507, 2], [[11508, 11512], 3], [[11513, 11519], 2], [[11520, 11557], 2], [11558, 3], [11559, 2], [[11560, 11564], 3], [11565, 2], [[11566, 11567], 3], [[11568, 11621], 2], [[11622, 11623], 2], [[11624, 11630], 3], [11631, 1, "\u2D61"], [11632, 2], [[11633, 11646], 3], [11647, 2], [[11648, 11670], 2], [[11671, 11679], 3], [[11680, 11686], 2], [11687, 3], [[11688, 11694], 2], [11695, 3], [[11696, 11702], 2], [11703, 3], [[11704, 11710], 2], [11711, 3], [[11712, 11718], 2], [11719, 3], [[11720, 11726], 2], [11727, 3], [[11728, 11734], 2], [11735, 3], [[11736, 11742], 2], [11743, 3], [[11744, 11775], 2], [[11776, 11799], 2], [[11800, 11803], 2], [[11804, 11805], 2], [[11806, 11822], 2], [11823, 2], [11824, 2], [11825, 2], [[11826, 11835], 2], [[11836, 11842], 2], [[11843, 11844], 2], [[11845, 11849], 2], [[11850, 11854], 2], [11855, 2], [[11856, 11858], 2], [[11859, 11869], 2], [[11870, 11903], 3], [[11904, 11929], 2], [11930, 3], [[11931, 11934], 2], [11935, 1, "\u6BCD"], [[11936, 12018], 2], [12019, 1, "\u9F9F"], [[12020, 12031], 3], [12032, 1, "\u4E00"], [12033, 1, "\u4E28"], [12034, 1, "\u4E36"], [12035, 1, "\u4E3F"], [12036, 1, "\u4E59"], [12037, 1, "\u4E85"], [12038, 1, "\u4E8C"], [12039, 1, "\u4EA0"], [12040, 1, "\u4EBA"], [12041, 1, "\u513F"], [12042, 1, "\u5165"], [12043, 1, "\u516B"], [12044, 1, "\u5182"], [12045, 1, "\u5196"], [12046, 1, "\u51AB"], [12047, 1, "\u51E0"], [12048, 1, "\u51F5"], [12049, 1, "\u5200"], [12050, 1, "\u529B"], [12051, 1, "\u52F9"], [12052, 1, "\u5315"], [12053, 1, "\u531A"], [12054, 1, "\u5338"], [12055, 1, "\u5341"], [12056, 1, "\u535C"], [12057, 1, "\u5369"], [12058, 1, "\u5382"], [12059, 1, "\u53B6"], [12060, 1, "\u53C8"], [12061, 1, "\u53E3"], [12062, 1, "\u56D7"], [12063, 1, "\u571F"], [12064, 1, "\u58EB"], [12065, 1, "\u5902"], [12066, 1, "\u590A"], [12067, 1, "\u5915"], [12068, 1, "\u5927"], [12069, 1, "\u5973"], [12070, 1, "\u5B50"], [12071, 1, "\u5B80"], [12072, 1, "\u5BF8"], [12073, 1, "\u5C0F"], [12074, 1, "\u5C22"], [12075, 1, "\u5C38"], [12076, 1, "\u5C6E"], [12077, 1, "\u5C71"], [12078, 1, "\u5DDB"], [12079, 1, "\u5DE5"], [12080, 1, "\u5DF1"], [12081, 1, "\u5DFE"], [12082, 1, "\u5E72"], [12083, 1, "\u5E7A"], [12084, 1, "\u5E7F"], [12085, 1, "\u5EF4"], [12086, 1, "\u5EFE"], [12087, 1, "\u5F0B"], [12088, 1, "\u5F13"], [12089, 1, "\u5F50"], [12090, 1, "\u5F61"], [12091, 1, "\u5F73"], [12092, 1, "\u5FC3"], [12093, 1, "\u6208"], [12094, 1, "\u6236"], [12095, 1, "\u624B"], [12096, 1, "\u652F"], [12097, 1, "\u6534"], [12098, 1, "\u6587"], [12099, 1, "\u6597"], [12100, 1, "\u65A4"], [12101, 1, "\u65B9"], [12102, 1, "\u65E0"], [12103, 1, "\u65E5"], [12104, 1, "\u66F0"], [12105, 1, "\u6708"], [12106, 1, "\u6728"], [12107, 1, "\u6B20"], [12108, 1, "\u6B62"], [12109, 1, "\u6B79"], [12110, 1, "\u6BB3"], [12111, 1, "\u6BCB"], [12112, 1, "\u6BD4"], [12113, 1, "\u6BDB"], [12114, 1, "\u6C0F"], [12115, 1, "\u6C14"], [12116, 1, "\u6C34"], [12117, 1, "\u706B"], [12118, 1, "\u722A"], [12119, 1, "\u7236"], [12120, 1, "\u723B"], [12121, 1, "\u723F"], [12122, 1, "\u7247"], [12123, 1, "\u7259"], [12124, 1, "\u725B"], [12125, 1, "\u72AC"], [12126, 1, "\u7384"], [12127, 1, "\u7389"], [12128, 1, "\u74DC"], [12129, 1, "\u74E6"], [12130, 1, "\u7518"], [12131, 1, "\u751F"], [12132, 1, "\u7528"], [12133, 1, "\u7530"], [12134, 1, "\u758B"], [12135, 1, "\u7592"], [12136, 1, "\u7676"], [12137, 1, "\u767D"], [12138, 1, "\u76AE"], [12139, 1, "\u76BF"], [12140, 1, "\u76EE"], [12141, 1, "\u77DB"], [12142, 1, "\u77E2"], [12143, 1, "\u77F3"], [12144, 1, "\u793A"], [12145, 1, "\u79B8"], [12146, 1, "\u79BE"], [12147, 1, "\u7A74"], [12148, 1, "\u7ACB"], [12149, 1, "\u7AF9"], [12150, 1, "\u7C73"], [12151, 1, "\u7CF8"], [12152, 1, "\u7F36"], [12153, 1, "\u7F51"], [12154, 1, "\u7F8A"], [12155, 1, "\u7FBD"], [12156, 1, "\u8001"], [12157, 1, "\u800C"], [12158, 1, "\u8012"], [12159, 1, "\u8033"], [12160, 1, "\u807F"], [12161, 1, "\u8089"], [12162, 1, "\u81E3"], [12163, 1, "\u81EA"], [12164, 1, "\u81F3"], [12165, 1, "\u81FC"], [12166, 1, "\u820C"], [12167, 1, "\u821B"], [12168, 1, "\u821F"], [12169, 1, "\u826E"], [12170, 1, "\u8272"], [12171, 1, "\u8278"], [12172, 1, "\u864D"], [12173, 1, "\u866B"], [12174, 1, "\u8840"], [12175, 1, "\u884C"], [12176, 1, "\u8863"], [12177, 1, "\u897E"], [12178, 1, "\u898B"], [12179, 1, "\u89D2"], [12180, 1, "\u8A00"], [12181, 1, "\u8C37"], [12182, 1, "\u8C46"], [12183, 1, "\u8C55"], [12184, 1, "\u8C78"], [12185, 1, "\u8C9D"], [12186, 1, "\u8D64"], [12187, 1, "\u8D70"], [12188, 1, "\u8DB3"], [12189, 1, "\u8EAB"], [12190, 1, "\u8ECA"], [12191, 1, "\u8F9B"], [12192, 1, "\u8FB0"], [12193, 1, "\u8FB5"], [12194, 1, "\u9091"], [12195, 1, "\u9149"], [12196, 1, "\u91C6"], [12197, 1, "\u91CC"], [12198, 1, "\u91D1"], [12199, 1, "\u9577"], [12200, 1, "\u9580"], [12201, 1, "\u961C"], [12202, 1, "\u96B6"], [12203, 1, "\u96B9"], [12204, 1, "\u96E8"], [12205, 1, "\u9751"], [12206, 1, "\u975E"], [12207, 1, "\u9762"], [12208, 1, "\u9769"], [12209, 1, "\u97CB"], [12210, 1, "\u97ED"], [12211, 1, "\u97F3"], [12212, 1, "\u9801"], [12213, 1, "\u98A8"], [12214, 1, "\u98DB"], [12215, 1, "\u98DF"], [12216, 1, "\u9996"], [12217, 1, "\u9999"], [12218, 1, "\u99AC"], [12219, 1, "\u9AA8"], [12220, 1, "\u9AD8"], [12221, 1, "\u9ADF"], [12222, 1, "\u9B25"], [12223, 1, "\u9B2F"], [12224, 1, "\u9B32"], [12225, 1, "\u9B3C"], [12226, 1, "\u9B5A"], [12227, 1, "\u9CE5"], [12228, 1, "\u9E75"], [12229, 1, "\u9E7F"], [12230, 1, "\u9EA5"], [12231, 1, "\u9EBB"], [12232, 1, "\u9EC3"], [12233, 1, "\u9ECD"], [12234, 1, "\u9ED1"], [12235, 1, "\u9EF9"], [12236, 1, "\u9EFD"], [12237, 1, "\u9F0E"], [12238, 1, "\u9F13"], [12239, 1, "\u9F20"], [12240, 1, "\u9F3B"], [12241, 1, "\u9F4A"], [12242, 1, "\u9F52"], [12243, 1, "\u9F8D"], [12244, 1, "\u9F9C"], [12245, 1, "\u9FA0"], [[12246, 12271], 3], [[12272, 12283], 3], [[12284, 12287], 3], [12288, 1, " "], [12289, 2], [12290, 1, "."], [[12291, 12292], 2], [[12293, 12295], 2], [[12296, 12329], 2], [[12330, 12333], 2], [[12334, 12341], 2], [12342, 1, "\u3012"], [12343, 2], [12344, 1, "\u5341"], [12345, 1, "\u5344"], [12346, 1, "\u5345"], [12347, 2], [12348, 2], [12349, 2], [12350, 2], [12351, 2], [12352, 3], [[12353, 12436], 2], [[12437, 12438], 2], [[12439, 12440], 3], [[12441, 12442], 2], [12443, 1, " \u3099"], [12444, 1, " \u309A"], [[12445, 12446], 2], [12447, 1, "\u3088\u308A"], [12448, 2], [[12449, 12542], 2], [12543, 1, "\u30B3\u30C8"], [[12544, 12548], 3], [[12549, 12588], 2], [12589, 2], [12590, 2], [12591, 2], [12592, 3], [12593, 1, "\u1100"], [12594, 1, "\u1101"], [12595, 1, "\u11AA"], [12596, 1, "\u1102"], [12597, 1, "\u11AC"], [12598, 1, "\u11AD"], [12599, 1, "\u1103"], [12600, 1, "\u1104"], [12601, 1, "\u1105"], [12602, 1, "\u11B0"], [12603, 1, "\u11B1"], [12604, 1, "\u11B2"], [12605, 1, "\u11B3"], [12606, 1, "\u11B4"], [12607, 1, "\u11B5"], [12608, 1, "\u111A"], [12609, 1, "\u1106"], [12610, 1, "\u1107"], [12611, 1, "\u1108"], [12612, 1, "\u1121"], [12613, 1, "\u1109"], [12614, 1, "\u110A"], [12615, 1, "\u110B"], [12616, 1, "\u110C"], [12617, 1, "\u110D"], [12618, 1, "\u110E"], [12619, 1, "\u110F"], [12620, 1, "\u1110"], [12621, 1, "\u1111"], [12622, 1, "\u1112"], [12623, 1, "\u1161"], [12624, 1, "\u1162"], [12625, 1, "\u1163"], [12626, 1, "\u1164"], [12627, 1, "\u1165"], [12628, 1, "\u1166"], [12629, 1, "\u1167"], [12630, 1, "\u1168"], [12631, 1, "\u1169"], [12632, 1, "\u116A"], [12633, 1, "\u116B"], [12634, 1, "\u116C"], [12635, 1, "\u116D"], [12636, 1, "\u116E"], [12637, 1, "\u116F"], [12638, 1, "\u1170"], [12639, 1, "\u1171"], [12640, 1, "\u1172"], [12641, 1, "\u1173"], [12642, 1, "\u1174"], [12643, 1, "\u1175"], [12644, 7], [12645, 1, "\u1114"], [12646, 1, "\u1115"], [12647, 1, "\u11C7"], [12648, 1, "\u11C8"], [12649, 1, "\u11CC"], [12650, 1, "\u11CE"], [12651, 1, "\u11D3"], [12652, 1, "\u11D7"], [12653, 1, "\u11D9"], [12654, 1, "\u111C"], [12655, 1, "\u11DD"], [12656, 1, "\u11DF"], [12657, 1, "\u111D"], [12658, 1, "\u111E"], [12659, 1, "\u1120"], [12660, 1, "\u1122"], [12661, 1, "\u1123"], [12662, 1, "\u1127"], [12663, 1, "\u1129"], [12664, 1, "\u112B"], [12665, 1, "\u112C"], [12666, 1, "\u112D"], [12667, 1, "\u112E"], [12668, 1, "\u112F"], [12669, 1, "\u1132"], [12670, 1, "\u1136"], [12671, 1, "\u1140"], [12672, 1, "\u1147"], [12673, 1, "\u114C"], [12674, 1, "\u11F1"], [12675, 1, "\u11F2"], [12676, 1, "\u1157"], [12677, 1, "\u1158"], [12678, 1, "\u1159"], [12679, 1, "\u1184"], [12680, 1, "\u1185"], [12681, 1, "\u1188"], [12682, 1, "\u1191"], [12683, 1, "\u1192"], [12684, 1, "\u1194"], [12685, 1, "\u119E"], [12686, 1, "\u11A1"], [12687, 3], [[12688, 12689], 2], [12690, 1, "\u4E00"], [12691, 1, "\u4E8C"], [12692, 1, "\u4E09"], [12693, 1, "\u56DB"], [12694, 1, "\u4E0A"], [12695, 1, "\u4E2D"], [12696, 1, "\u4E0B"], [12697, 1, "\u7532"], [12698, 1, "\u4E59"], [12699, 1, "\u4E19"], [12700, 1, "\u4E01"], [12701, 1, "\u5929"], [12702, 1, "\u5730"], [12703, 1, "\u4EBA"], [[12704, 12727], 2], [[12728, 12730], 2], [[12731, 12735], 2], [[12736, 12751], 2], [[12752, 12771], 2], [[12772, 12773], 2], [[12774, 12782], 3], [12783, 3], [[12784, 12799], 2], [12800, 1, "(\u1100)"], [12801, 1, "(\u1102)"], [12802, 1, "(\u1103)"], [12803, 1, "(\u1105)"], [12804, 1, "(\u1106)"], [12805, 1, "(\u1107)"], [12806, 1, "(\u1109)"], [12807, 1, "(\u110B)"], [12808, 1, "(\u110C)"], [12809, 1, "(\u110E)"], [12810, 1, "(\u110F)"], [12811, 1, "(\u1110)"], [12812, 1, "(\u1111)"], [12813, 1, "(\u1112)"], [12814, 1, "(\uAC00)"], [12815, 1, "(\uB098)"], [12816, 1, "(\uB2E4)"], [12817, 1, "(\uB77C)"], [12818, 1, "(\uB9C8)"], [12819, 1, "(\uBC14)"], [12820, 1, "(\uC0AC)"], [12821, 1, "(\uC544)"], [12822, 1, "(\uC790)"], [12823, 1, "(\uCC28)"], [12824, 1, "(\uCE74)"], [12825, 1, "(\uD0C0)"], [12826, 1, "(\uD30C)"], [12827, 1, "(\uD558)"], [12828, 1, "(\uC8FC)"], [12829, 1, "(\uC624\uC804)"], [12830, 1, "(\uC624\uD6C4)"], [12831, 3], [12832, 1, "(\u4E00)"], [12833, 1, "(\u4E8C)"], [12834, 1, "(\u4E09)"], [12835, 1, "(\u56DB)"], [12836, 1, "(\u4E94)"], [12837, 1, "(\u516D)"], [12838, 1, "(\u4E03)"], [12839, 1, "(\u516B)"], [12840, 1, "(\u4E5D)"], [12841, 1, "(\u5341)"], [12842, 1, "(\u6708)"], [12843, 1, "(\u706B)"], [12844, 1, "(\u6C34)"], [12845, 1, "(\u6728)"], [12846, 1, "(\u91D1)"], [12847, 1, "(\u571F)"], [12848, 1, "(\u65E5)"], [12849, 1, "(\u682A)"], [12850, 1, "(\u6709)"], [12851, 1, "(\u793E)"], [12852, 1, "(\u540D)"], [12853, 1, "(\u7279)"], [12854, 1, "(\u8CA1)"], [12855, 1, "(\u795D)"], [12856, 1, "(\u52B4)"], [12857, 1, "(\u4EE3)"], [12858, 1, "(\u547C)"], [12859, 1, "(\u5B66)"], [12860, 1, "(\u76E3)"], [12861, 1, "(\u4F01)"], [12862, 1, "(\u8CC7)"], [12863, 1, "(\u5354)"], [12864, 1, "(\u796D)"], [12865, 1, "(\u4F11)"], [12866, 1, "(\u81EA)"], [12867, 1, "(\u81F3)"], [12868, 1, "\u554F"], [12869, 1, "\u5E7C"], [12870, 1, "\u6587"], [12871, 1, "\u7B8F"], [[12872, 12879], 2], [12880, 1, "pte"], [12881, 1, "21"], [12882, 1, "22"], [12883, 1, "23"], [12884, 1, "24"], [12885, 1, "25"], [12886, 1, "26"], [12887, 1, "27"], [12888, 1, "28"], [12889, 1, "29"], [12890, 1, "30"], [12891, 1, "31"], [12892, 1, "32"], [12893, 1, "33"], [12894, 1, "34"], [12895, 1, "35"], [12896, 1, "\u1100"], [12897, 1, "\u1102"], [12898, 1, "\u1103"], [12899, 1, "\u1105"], [12900, 1, "\u1106"], [12901, 1, "\u1107"], [12902, 1, "\u1109"], [12903, 1, "\u110B"], [12904, 1, "\u110C"], [12905, 1, "\u110E"], [12906, 1, "\u110F"], [12907, 1, "\u1110"], [12908, 1, "\u1111"], [12909, 1, "\u1112"], [12910, 1, "\uAC00"], [12911, 1, "\uB098"], [12912, 1, "\uB2E4"], [12913, 1, "\uB77C"], [12914, 1, "\uB9C8"], [12915, 1, "\uBC14"], [12916, 1, "\uC0AC"], [12917, 1, "\uC544"], [12918, 1, "\uC790"], [12919, 1, "\uCC28"], [12920, 1, "\uCE74"], [12921, 1, "\uD0C0"], [12922, 1, "\uD30C"], [12923, 1, "\uD558"], [12924, 1, "\uCC38\uACE0"], [12925, 1, "\uC8FC\uC758"], [12926, 1, "\uC6B0"], [12927, 2], [12928, 1, "\u4E00"], [12929, 1, "\u4E8C"], [12930, 1, "\u4E09"], [12931, 1, "\u56DB"], [12932, 1, "\u4E94"], [12933, 1, "\u516D"], [12934, 1, "\u4E03"], [12935, 1, "\u516B"], [12936, 1, "\u4E5D"], [12937, 1, "\u5341"], [12938, 1, "\u6708"], [12939, 1, "\u706B"], [12940, 1, "\u6C34"], [12941, 1, "\u6728"], [12942, 1, "\u91D1"], [12943, 1, "\u571F"], [12944, 1, "\u65E5"], [12945, 1, "\u682A"], [12946, 1, "\u6709"], [12947, 1, "\u793E"], [12948, 1, "\u540D"], [12949, 1, "\u7279"], [12950, 1, "\u8CA1"], [12951, 1, "\u795D"], [12952, 1, "\u52B4"], [12953, 1, "\u79D8"], [12954, 1, "\u7537"], [12955, 1, "\u5973"], [12956, 1, "\u9069"], [12957, 1, "\u512A"], [12958, 1, "\u5370"], [12959, 1, "\u6CE8"], [12960, 1, "\u9805"], [12961, 1, "\u4F11"], [12962, 1, "\u5199"], [12963, 1, "\u6B63"], [12964, 1, "\u4E0A"], [12965, 1, "\u4E2D"], [12966, 1, "\u4E0B"], [12967, 1, "\u5DE6"], [12968, 1, "\u53F3"], [12969, 1, "\u533B"], [12970, 1, "\u5B97"], [12971, 1, "\u5B66"], [12972, 1, "\u76E3"], [12973, 1, "\u4F01"], [12974, 1, "\u8CC7"], [12975, 1, "\u5354"], [12976, 1, "\u591C"], [12977, 1, "36"], [12978, 1, "37"], [12979, 1, "38"], [12980, 1, "39"], [12981, 1, "40"], [12982, 1, "41"], [12983, 1, "42"], [12984, 1, "43"], [12985, 1, "44"], [12986, 1, "45"], [12987, 1, "46"], [12988, 1, "47"], [12989, 1, "48"], [12990, 1, "49"], [12991, 1, "50"], [12992, 1, "1\u6708"], [12993, 1, "2\u6708"], [12994, 1, "3\u6708"], [12995, 1, "4\u6708"], [12996, 1, "5\u6708"], [12997, 1, "6\u6708"], [12998, 1, "7\u6708"], [12999, 1, "8\u6708"], [13e3, 1, "9\u6708"], [13001, 1, "10\u6708"], [13002, 1, "11\u6708"], [13003, 1, "12\u6708"], [13004, 1, "hg"], [13005, 1, "erg"], [13006, 1, "ev"], [13007, 1, "ltd"], [13008, 1, "\u30A2"], [13009, 1, "\u30A4"], [13010, 1, "\u30A6"], [13011, 1, "\u30A8"], [13012, 1, "\u30AA"], [13013, 1, "\u30AB"], [13014, 1, "\u30AD"], [13015, 1, "\u30AF"], [13016, 1, "\u30B1"], [13017, 1, "\u30B3"], [13018, 1, "\u30B5"], [13019, 1, "\u30B7"], [13020, 1, "\u30B9"], [13021, 1, "\u30BB"], [13022, 1, "\u30BD"], [13023, 1, "\u30BF"], [13024, 1, "\u30C1"], [13025, 1, "\u30C4"], [13026, 1, "\u30C6"], [13027, 1, "\u30C8"], [13028, 1, "\u30CA"], [13029, 1, "\u30CB"], [13030, 1, "\u30CC"], [13031, 1, "\u30CD"], [13032, 1, "\u30CE"], [13033, 1, "\u30CF"], [13034, 1, "\u30D2"], [13035, 1, "\u30D5"], [13036, 1, "\u30D8"], [13037, 1, "\u30DB"], [13038, 1, "\u30DE"], [13039, 1, "\u30DF"], [13040, 1, "\u30E0"], [13041, 1, "\u30E1"], [13042, 1, "\u30E2"], [13043, 1, "\u30E4"], [13044, 1, "\u30E6"], [13045, 1, "\u30E8"], [13046, 1, "\u30E9"], [13047, 1, "\u30EA"], [13048, 1, "\u30EB"], [13049, 1, "\u30EC"], [13050, 1, "\u30ED"], [13051, 1, "\u30EF"], [13052, 1, "\u30F0"], [13053, 1, "\u30F1"], [13054, 1, "\u30F2"], [13055, 1, "\u4EE4\u548C"], [13056, 1, "\u30A2\u30D1\u30FC\u30C8"], [13057, 1, "\u30A2\u30EB\u30D5\u30A1"], [13058, 1, "\u30A2\u30F3\u30DA\u30A2"], [13059, 1, "\u30A2\u30FC\u30EB"], [13060, 1, "\u30A4\u30CB\u30F3\u30B0"], [13061, 1, "\u30A4\u30F3\u30C1"], [13062, 1, "\u30A6\u30A9\u30F3"], [13063, 1, "\u30A8\u30B9\u30AF\u30FC\u30C9"], [13064, 1, "\u30A8\u30FC\u30AB\u30FC"], [13065, 1, "\u30AA\u30F3\u30B9"], [13066, 1, "\u30AA\u30FC\u30E0"], [13067, 1, "\u30AB\u30A4\u30EA"], [13068, 1, "\u30AB\u30E9\u30C3\u30C8"], [13069, 1, "\u30AB\u30ED\u30EA\u30FC"], [13070, 1, "\u30AC\u30ED\u30F3"], [13071, 1, "\u30AC\u30F3\u30DE"], [13072, 1, "\u30AE\u30AC"], [13073, 1, "\u30AE\u30CB\u30FC"], [13074, 1, "\u30AD\u30E5\u30EA\u30FC"], [13075, 1, "\u30AE\u30EB\u30C0\u30FC"], [13076, 1, "\u30AD\u30ED"], [13077, 1, "\u30AD\u30ED\u30B0\u30E9\u30E0"], [13078, 1, "\u30AD\u30ED\u30E1\u30FC\u30C8\u30EB"], [13079, 1, "\u30AD\u30ED\u30EF\u30C3\u30C8"], [13080, 1, "\u30B0\u30E9\u30E0"], [13081, 1, "\u30B0\u30E9\u30E0\u30C8\u30F3"], [13082, 1, "\u30AF\u30EB\u30BC\u30A4\u30ED"], [13083, 1, "\u30AF\u30ED\u30FC\u30CD"], [13084, 1, "\u30B1\u30FC\u30B9"], [13085, 1, "\u30B3\u30EB\u30CA"], [13086, 1, "\u30B3\u30FC\u30DD"], [13087, 1, "\u30B5\u30A4\u30AF\u30EB"], [13088, 1, "\u30B5\u30F3\u30C1\u30FC\u30E0"], [13089, 1, "\u30B7\u30EA\u30F3\u30B0"], [13090, 1, "\u30BB\u30F3\u30C1"], [13091, 1, "\u30BB\u30F3\u30C8"], [13092, 1, "\u30C0\u30FC\u30B9"], [13093, 1, "\u30C7\u30B7"], [13094, 1, "\u30C9\u30EB"], [13095, 1, "\u30C8\u30F3"], [13096, 1, "\u30CA\u30CE"], [13097, 1, "\u30CE\u30C3\u30C8"], [13098, 1, "\u30CF\u30A4\u30C4"], [13099, 1, "\u30D1\u30FC\u30BB\u30F3\u30C8"], [13100, 1, "\u30D1\u30FC\u30C4"], [13101, 1, "\u30D0\u30FC\u30EC\u30EB"], [13102, 1, "\u30D4\u30A2\u30B9\u30C8\u30EB"], [13103, 1, "\u30D4\u30AF\u30EB"], [13104, 1, "\u30D4\u30B3"], [13105, 1, "\u30D3\u30EB"], [13106, 1, "\u30D5\u30A1\u30E9\u30C3\u30C9"], [13107, 1, "\u30D5\u30A3\u30FC\u30C8"], [13108, 1, "\u30D6\u30C3\u30B7\u30A7\u30EB"], [13109, 1, "\u30D5\u30E9\u30F3"], [13110, 1, "\u30D8\u30AF\u30BF\u30FC\u30EB"], [13111, 1, "\u30DA\u30BD"], [13112, 1, "\u30DA\u30CB\u30D2"], [13113, 1, "\u30D8\u30EB\u30C4"], [13114, 1, "\u30DA\u30F3\u30B9"], [13115, 1, "\u30DA\u30FC\u30B8"], [13116, 1, "\u30D9\u30FC\u30BF"], [13117, 1, "\u30DD\u30A4\u30F3\u30C8"], [13118, 1, "\u30DC\u30EB\u30C8"], [13119, 1, "\u30DB\u30F3"], [13120, 1, "\u30DD\u30F3\u30C9"], [13121, 1, "\u30DB\u30FC\u30EB"], [13122, 1, "\u30DB\u30FC\u30F3"], [13123, 1, "\u30DE\u30A4\u30AF\u30ED"], [13124, 1, "\u30DE\u30A4\u30EB"], [13125, 1, "\u30DE\u30C3\u30CF"], [13126, 1, "\u30DE\u30EB\u30AF"], [13127, 1, "\u30DE\u30F3\u30B7\u30E7\u30F3"], [13128, 1, "\u30DF\u30AF\u30ED\u30F3"], [13129, 1, "\u30DF\u30EA"], [13130, 1, "\u30DF\u30EA\u30D0\u30FC\u30EB"], [13131, 1, "\u30E1\u30AC"], [13132, 1, "\u30E1\u30AC\u30C8\u30F3"], [13133, 1, "\u30E1\u30FC\u30C8\u30EB"], [13134, 1, "\u30E4\u30FC\u30C9"], [13135, 1, "\u30E4\u30FC\u30EB"], [13136, 1, "\u30E6\u30A2\u30F3"], [13137, 1, "\u30EA\u30C3\u30C8\u30EB"], [13138, 1, "\u30EA\u30E9"], [13139, 1, "\u30EB\u30D4\u30FC"], [13140, 1, "\u30EB\u30FC\u30D6\u30EB"], [13141, 1, "\u30EC\u30E0"], [13142, 1, "\u30EC\u30F3\u30C8\u30B2\u30F3"], [13143, 1, "\u30EF\u30C3\u30C8"], [13144, 1, "0\u70B9"], [13145, 1, "1\u70B9"], [13146, 1, "2\u70B9"], [13147, 1, "3\u70B9"], [13148, 1, "4\u70B9"], [13149, 1, "5\u70B9"], [13150, 1, "6\u70B9"], [13151, 1, "7\u70B9"], [13152, 1, "8\u70B9"], [13153, 1, "9\u70B9"], [13154, 1, "10\u70B9"], [13155, 1, "11\u70B9"], [13156, 1, "12\u70B9"], [13157, 1, "13\u70B9"], [13158, 1, "14\u70B9"], [13159, 1, "15\u70B9"], [13160, 1, "16\u70B9"], [13161, 1, "17\u70B9"], [13162, 1, "18\u70B9"], [13163, 1, "19\u70B9"], [13164, 1, "20\u70B9"], [13165, 1, "21\u70B9"], [13166, 1, "22\u70B9"], [13167, 1, "23\u70B9"], [13168, 1, "24\u70B9"], [13169, 1, "hpa"], [13170, 1, "da"], [13171, 1, "au"], [13172, 1, "bar"], [13173, 1, "ov"], [13174, 1, "pc"], [13175, 1, "dm"], [13176, 1, "dm2"], [13177, 1, "dm3"], [13178, 1, "iu"], [13179, 1, "\u5E73\u6210"], [13180, 1, "\u662D\u548C"], [13181, 1, "\u5927\u6B63"], [13182, 1, "\u660E\u6CBB"], [13183, 1, "\u682A\u5F0F\u4F1A\u793E"], [13184, 1, "pa"], [13185, 1, "na"], [13186, 1, "\u03BCa"], [13187, 1, "ma"], [13188, 1, "ka"], [13189, 1, "kb"], [13190, 1, "mb"], [13191, 1, "gb"], [13192, 1, "cal"], [13193, 1, "kcal"], [13194, 1, "pf"], [13195, 1, "nf"], [13196, 1, "\u03BCf"], [13197, 1, "\u03BCg"], [13198, 1, "mg"], [13199, 1, "kg"], [13200, 1, "hz"], [13201, 1, "khz"], [13202, 1, "mhz"], [13203, 1, "ghz"], [13204, 1, "thz"], [13205, 1, "\u03BCl"], [13206, 1, "ml"], [13207, 1, "dl"], [13208, 1, "kl"], [13209, 1, "fm"], [13210, 1, "nm"], [13211, 1, "\u03BCm"], [13212, 1, "mm"], [13213, 1, "cm"], [13214, 1, "km"], [13215, 1, "mm2"], [13216, 1, "cm2"], [13217, 1, "m2"], [13218, 1, "km2"], [13219, 1, "mm3"], [13220, 1, "cm3"], [13221, 1, "m3"], [13222, 1, "km3"], [13223, 1, "m\u2215s"], [13224, 1, "m\u2215s2"], [13225, 1, "pa"], [13226, 1, "kpa"], [13227, 1, "mpa"], [13228, 1, "gpa"], [13229, 1, "rad"], [13230, 1, "rad\u2215s"], [13231, 1, "rad\u2215s2"], [13232, 1, "ps"], [13233, 1, "ns"], [13234, 1, "\u03BCs"], [13235, 1, "ms"], [13236, 1, "pv"], [13237, 1, "nv"], [13238, 1, "\u03BCv"], [13239, 1, "mv"], [13240, 1, "kv"], [13241, 1, "mv"], [13242, 1, "pw"], [13243, 1, "nw"], [13244, 1, "\u03BCw"], [13245, 1, "mw"], [13246, 1, "kw"], [13247, 1, "mw"], [13248, 1, "k\u03C9"], [13249, 1, "m\u03C9"], [13250, 3], [13251, 1, "bq"], [13252, 1, "cc"], [13253, 1, "cd"], [13254, 1, "c\u2215kg"], [13255, 3], [13256, 1, "db"], [13257, 1, "gy"], [13258, 1, "ha"], [13259, 1, "hp"], [13260, 1, "in"], [13261, 1, "kk"], [13262, 1, "km"], [13263, 1, "kt"], [13264, 1, "lm"], [13265, 1, "ln"], [13266, 1, "log"], [13267, 1, "lx"], [13268, 1, "mb"], [13269, 1, "mil"], [13270, 1, "mol"], [13271, 1, "ph"], [13272, 3], [13273, 1, "ppm"], [13274, 1, "pr"], [13275, 1, "sr"], [13276, 1, "sv"], [13277, 1, "wb"], [13278, 1, "v\u2215m"], [13279, 1, "a\u2215m"], [13280, 1, "1\u65E5"], [13281, 1, "2\u65E5"], [13282, 1, "3\u65E5"], [13283, 1, "4\u65E5"], [13284, 1, "5\u65E5"], [13285, 1, "6\u65E5"], [13286, 1, "7\u65E5"], [13287, 1, "8\u65E5"], [13288, 1, "9\u65E5"], [13289, 1, "10\u65E5"], [13290, 1, "11\u65E5"], [13291, 1, "12\u65E5"], [13292, 1, "13\u65E5"], [13293, 1, "14\u65E5"], [13294, 1, "15\u65E5"], [13295, 1, "16\u65E5"], [13296, 1, "17\u65E5"], [13297, 1, "18\u65E5"], [13298, 1, "19\u65E5"], [13299, 1, "20\u65E5"], [13300, 1, "21\u65E5"], [13301, 1, "22\u65E5"], [13302, 1, "23\u65E5"], [13303, 1, "24\u65E5"], [13304, 1, "25\u65E5"], [13305, 1, "26\u65E5"], [13306, 1, "27\u65E5"], [13307, 1, "28\u65E5"], [13308, 1, "29\u65E5"], [13309, 1, "30\u65E5"], [13310, 1, "31\u65E5"], [13311, 1, "gal"], [[13312, 19893], 2], [[19894, 19903], 2], [[19904, 19967], 2], [[19968, 40869], 2], [[40870, 40891], 2], [[40892, 40899], 2], [[40900, 40907], 2], [40908, 2], [[40909, 40917], 2], [[40918, 40938], 2], [[40939, 40943], 2], [[40944, 40956], 2], [[40957, 40959], 2], [[40960, 42124], 2], [[42125, 42127], 3], [[42128, 42145], 2], [[42146, 42147], 2], [[42148, 42163], 2], [42164, 2], [[42165, 42176], 2], [42177, 2], [[42178, 42180], 2], [42181, 2], [42182, 2], [[42183, 42191], 3], [[42192, 42237], 2], [[42238, 42239], 2], [[42240, 42508], 2], [[42509, 42511], 2], [[42512, 42539], 2], [[42540, 42559], 3], [42560, 1, "\uA641"], [42561, 2], [42562, 1, "\uA643"], [42563, 2], [42564, 1, "\uA645"], [42565, 2], [42566, 1, "\uA647"], [42567, 2], [42568, 1, "\uA649"], [42569, 2], [42570, 1, "\uA64B"], [42571, 2], [42572, 1, "\uA64D"], [42573, 2], [42574, 1, "\uA64F"], [42575, 2], [42576, 1, "\uA651"], [42577, 2], [42578, 1, "\uA653"], [42579, 2], [42580, 1, "\uA655"], [42581, 2], [42582, 1, "\uA657"], [42583, 2], [42584, 1, "\uA659"], [42585, 2], [42586, 1, "\uA65B"], [42587, 2], [42588, 1, "\uA65D"], [42589, 2], [42590, 1, "\uA65F"], [42591, 2], [42592, 1, "\uA661"], [42593, 2], [42594, 1, "\uA663"], [42595, 2], [42596, 1, "\uA665"], [42597, 2], [42598, 1, "\uA667"], [42599, 2], [42600, 1, "\uA669"], [42601, 2], [42602, 1, "\uA66B"], [42603, 2], [42604, 1, "\uA66D"], [[42605, 42607], 2], [[42608, 42611], 2], [[42612, 42619], 2], [[42620, 42621], 2], [42622, 2], [42623, 2], [42624, 1, "\uA681"], [42625, 2], [42626, 1, "\uA683"], [42627, 2], [42628, 1, "\uA685"], [42629, 2], [42630, 1, "\uA687"], [42631, 2], [42632, 1, "\uA689"], [42633, 2], [42634, 1, "\uA68B"], [42635, 2], [42636, 1, "\uA68D"], [42637, 2], [42638, 1, "\uA68F"], [42639, 2], [42640, 1, "\uA691"], [42641, 2], [42642, 1, "\uA693"], [42643, 2], [42644, 1, "\uA695"], [42645, 2], [42646, 1, "\uA697"], [42647, 2], [42648, 1, "\uA699"], [42649, 2], [42650, 1, "\uA69B"], [42651, 2], [42652, 1, "\u044A"], [42653, 1, "\u044C"], [42654, 2], [42655, 2], [[42656, 42725], 2], [[42726, 42735], 2], [[42736, 42737], 2], [[42738, 42743], 2], [[42744, 42751], 3], [[42752, 42774], 2], [[42775, 42778], 2], [[42779, 42783], 2], [[42784, 42785], 2], [42786, 1, "\uA723"], [42787, 2], [42788, 1, "\uA725"], [42789, 2], [42790, 1, "\uA727"], [42791, 2], [42792, 1, "\uA729"], [42793, 2], [42794, 1, "\uA72B"], [42795, 2], [42796, 1, "\uA72D"], [42797, 2], [42798, 1, "\uA72F"], [[42799, 42801], 2], [42802, 1, "\uA733"], [42803, 2], [42804, 1, "\uA735"], [42805, 2], [42806, 1, "\uA737"], [42807, 2], [42808, 1, "\uA739"], [42809, 2], [42810, 1, "\uA73B"], [42811, 2], [42812, 1, "\uA73D"], [42813, 2], [42814, 1, "\uA73F"], [42815, 2], [42816, 1, "\uA741"], [42817, 2], [42818, 1, "\uA743"], [42819, 2], [42820, 1, "\uA745"], [42821, 2], [42822, 1, "\uA747"], [42823, 2], [42824, 1, "\uA749"], [42825, 2], [42826, 1, "\uA74B"], [42827, 2], [42828, 1, "\uA74D"], [42829, 2], [42830, 1, "\uA74F"], [42831, 2], [42832, 1, "\uA751"], [42833, 2], [42834, 1, "\uA753"], [42835, 2], [42836, 1, "\uA755"], [42837, 2], [42838, 1, "\uA757"], [42839, 2], [42840, 1, "\uA759"], [42841, 2], [42842, 1, "\uA75B"], [42843, 2], [42844, 1, "\uA75D"], [42845, 2], [42846, 1, "\uA75F"], [42847, 2], [42848, 1, "\uA761"], [42849, 2], [42850, 1, "\uA763"], [42851, 2], [42852, 1, "\uA765"], [42853, 2], [42854, 1, "\uA767"], [42855, 2], [42856, 1, "\uA769"], [42857, 2], [42858, 1, "\uA76B"], [42859, 2], [42860, 1, "\uA76D"], [42861, 2], [42862, 1, "\uA76F"], [42863, 2], [42864, 1, "\uA76F"], [[42865, 42872], 2], [42873, 1, "\uA77A"], [42874, 2], [42875, 1, "\uA77C"], [42876, 2], [42877, 1, "\u1D79"], [42878, 1, "\uA77F"], [42879, 2], [42880, 1, "\uA781"], [42881, 2], [42882, 1, "\uA783"], [42883, 2], [42884, 1, "\uA785"], [42885, 2], [42886, 1, "\uA787"], [[42887, 42888], 2], [[42889, 42890], 2], [42891, 1, "\uA78C"], [42892, 2], [42893, 1, "\u0265"], [42894, 2], [42895, 2], [42896, 1, "\uA791"], [42897, 2], [42898, 1, "\uA793"], [42899, 2], [[42900, 42901], 2], [42902, 1, "\uA797"], [42903, 2], [42904, 1, "\uA799"], [42905, 2], [42906, 1, "\uA79B"], [42907, 2], [42908, 1, "\uA79D"], [42909, 2], [42910, 1, "\uA79F"], [42911, 2], [42912, 1, "\uA7A1"], [42913, 2], [42914, 1, "\uA7A3"], [42915, 2], [42916, 1, "\uA7A5"], [42917, 2], [42918, 1, "\uA7A7"], [42919, 2], [42920, 1, "\uA7A9"], [42921, 2], [42922, 1, "\u0266"], [42923, 1, "\u025C"], [42924, 1, "\u0261"], [42925, 1, "\u026C"], [42926, 1, "\u026A"], [42927, 2], [42928, 1, "\u029E"], [42929, 1, "\u0287"], [42930, 1, "\u029D"], [42931, 1, "\uAB53"], [42932, 1, "\uA7B5"], [42933, 2], [42934, 1, "\uA7B7"], [42935, 2], [42936, 1, "\uA7B9"], [42937, 2], [42938, 1, "\uA7BB"], [42939, 2], [42940, 1, "\uA7BD"], [42941, 2], [42942, 1, "\uA7BF"], [42943, 2], [42944, 1, "\uA7C1"], [42945, 2], [42946, 1, "\uA7C3"], [42947, 2], [42948, 1, "\uA794"], [42949, 1, "\u0282"], [42950, 1, "\u1D8E"], [42951, 1, "\uA7C8"], [42952, 2], [42953, 1, "\uA7CA"], [42954, 2], [42955, 1, "\u0264"], [42956, 1, "\uA7CD"], [42957, 2], [[42958, 42959], 3], [42960, 1, "\uA7D1"], [42961, 2], [42962, 3], [42963, 2], [42964, 3], [42965, 2], [42966, 1, "\uA7D7"], [42967, 2], [42968, 1, "\uA7D9"], [42969, 2], [42970, 1, "\uA7DB"], [42971, 2], [42972, 1, "\u019B"], [[42973, 42993], 3], [42994, 1, "c"], [42995, 1, "f"], [42996, 1, "q"], [42997, 1, "\uA7F6"], [42998, 2], [42999, 2], [43e3, 1, "\u0127"], [43001, 1, "\u0153"], [43002, 2], [[43003, 43007], 2], [[43008, 43047], 2], [[43048, 43051], 2], [43052, 2], [[43053, 43055], 3], [[43056, 43065], 2], [[43066, 43071], 3], [[43072, 43123], 2], [[43124, 43127], 2], [[43128, 43135], 3], [[43136, 43204], 2], [43205, 2], [[43206, 43213], 3], [[43214, 43215], 2], [[43216, 43225], 2], [[43226, 43231], 3], [[43232, 43255], 2], [[43256, 43258], 2], [43259, 2], [43260, 2], [43261, 2], [[43262, 43263], 2], [[43264, 43309], 2], [[43310, 43311], 2], [[43312, 43347], 2], [[43348, 43358], 3], [43359, 2], [[43360, 43388], 2], [[43389, 43391], 3], [[43392, 43456], 2], [[43457, 43469], 2], [43470, 3], [[43471, 43481], 2], [[43482, 43485], 3], [[43486, 43487], 2], [[43488, 43518], 2], [43519, 3], [[43520, 43574], 2], [[43575, 43583], 3], [[43584, 43597], 2], [[43598, 43599], 3], [[43600, 43609], 2], [[43610, 43611], 3], [[43612, 43615], 2], [[43616, 43638], 2], [[43639, 43641], 2], [[43642, 43643], 2], [[43644, 43647], 2], [[43648, 43714], 2], [[43715, 43738], 3], [[43739, 43741], 2], [[43742, 43743], 2], [[43744, 43759], 2], [[43760, 43761], 2], [[43762, 43766], 2], [[43767, 43776], 3], [[43777, 43782], 2], [[43783, 43784], 3], [[43785, 43790], 2], [[43791, 43792], 3], [[43793, 43798], 2], [[43799, 43807], 3], [[43808, 43814], 2], [43815, 3], [[43816, 43822], 2], [43823, 3], [[43824, 43866], 2], [43867, 2], [43868, 1, "\uA727"], [43869, 1, "\uAB37"], [43870, 1, "\u026B"], [43871, 1, "\uAB52"], [[43872, 43875], 2], [[43876, 43877], 2], [[43878, 43879], 2], [43880, 2], [43881, 1, "\u028D"], [[43882, 43883], 2], [[43884, 43887], 3], [43888, 1, "\u13A0"], [43889, 1, "\u13A1"], [43890, 1, "\u13A2"], [43891, 1, "\u13A3"], [43892, 1, "\u13A4"], [43893, 1, "\u13A5"], [43894, 1, "\u13A6"], [43895, 1, "\u13A7"], [43896, 1, "\u13A8"], [43897, 1, "\u13A9"], [43898, 1, "\u13AA"], [43899, 1, "\u13AB"], [43900, 1, "\u13AC"], [43901, 1, "\u13AD"], [43902, 1, "\u13AE"], [43903, 1, "\u13AF"], [43904, 1, "\u13B0"], [43905, 1, "\u13B1"], [43906, 1, "\u13B2"], [43907, 1, "\u13B3"], [43908, 1, "\u13B4"], [43909, 1, "\u13B5"], [43910, 1, "\u13B6"], [43911, 1, "\u13B7"], [43912, 1, "\u13B8"], [43913, 1, "\u13B9"], [43914, 1, "\u13BA"], [43915, 1, "\u13BB"], [43916, 1, "\u13BC"], [43917, 1, "\u13BD"], [43918, 1, "\u13BE"], [43919, 1, "\u13BF"], [43920, 1, "\u13C0"], [43921, 1, "\u13C1"], [43922, 1, "\u13C2"], [43923, 1, "\u13C3"], [43924, 1, "\u13C4"], [43925, 1, "\u13C5"], [43926, 1, "\u13C6"], [43927, 1, "\u13C7"], [43928, 1, "\u13C8"], [43929, 1, "\u13C9"], [43930, 1, "\u13CA"], [43931, 1, "\u13CB"], [43932, 1, "\u13CC"], [43933, 1, "\u13CD"], [43934, 1, "\u13CE"], [43935, 1, "\u13CF"], [43936, 1, "\u13D0"], [43937, 1, "\u13D1"], [43938, 1, "\u13D2"], [43939, 1, "\u13D3"], [43940, 1, "\u13D4"], [43941, 1, "\u13D5"], [43942, 1, "\u13D6"], [43943, 1, "\u13D7"], [43944, 1, "\u13D8"], [43945, 1, "\u13D9"], [43946, 1, "\u13DA"], [43947, 1, "\u13DB"], [43948, 1, "\u13DC"], [43949, 1, "\u13DD"], [43950, 1, "\u13DE"], [43951, 1, "\u13DF"], [43952, 1, "\u13E0"], [43953, 1, "\u13E1"], [43954, 1, "\u13E2"], [43955, 1, "\u13E3"], [43956, 1, "\u13E4"], [43957, 1, "\u13E5"], [43958, 1, "\u13E6"], [43959, 1, "\u13E7"], [43960, 1, "\u13E8"], [43961, 1, "\u13E9"], [43962, 1, "\u13EA"], [43963, 1, "\u13EB"], [43964, 1, "\u13EC"], [43965, 1, "\u13ED"], [43966, 1, "\u13EE"], [43967, 1, "\u13EF"], [[43968, 44010], 2], [44011, 2], [[44012, 44013], 2], [[44014, 44015], 3], [[44016, 44025], 2], [[44026, 44031], 3], [[44032, 55203], 2], [[55204, 55215], 3], [[55216, 55238], 2], [[55239, 55242], 3], [[55243, 55291], 2], [[55292, 55295], 3], [[55296, 57343], 3], [[57344, 63743], 3], [63744, 1, "\u8C48"], [63745, 1, "\u66F4"], [63746, 1, "\u8ECA"], [63747, 1, "\u8CC8"], [63748, 1, "\u6ED1"], [63749, 1, "\u4E32"], [63750, 1, "\u53E5"], [[63751, 63752], 1, "\u9F9C"], [63753, 1, "\u5951"], [63754, 1, "\u91D1"], [63755, 1, "\u5587"], [63756, 1, "\u5948"], [63757, 1, "\u61F6"], [63758, 1, "\u7669"], [63759, 1, "\u7F85"], [63760, 1, "\u863F"], [63761, 1, "\u87BA"], [63762, 1, "\u88F8"], [63763, 1, "\u908F"], [63764, 1, "\u6A02"], [63765, 1, "\u6D1B"], [63766, 1, "\u70D9"], [63767, 1, "\u73DE"], [63768, 1, "\u843D"], [63769, 1, "\u916A"], [63770, 1, "\u99F1"], [63771, 1, "\u4E82"], [63772, 1, "\u5375"], [63773, 1, "\u6B04"], [63774, 1, "\u721B"], [63775, 1, "\u862D"], [63776, 1, "\u9E1E"], [63777, 1, "\u5D50"], [63778, 1, "\u6FEB"], [63779, 1, "\u85CD"], [63780, 1, "\u8964"], [63781, 1, "\u62C9"], [63782, 1, "\u81D8"], [63783, 1, "\u881F"], [63784, 1, "\u5ECA"], [63785, 1, "\u6717"], [63786, 1, "\u6D6A"], [63787, 1, "\u72FC"], [63788, 1, "\u90CE"], [63789, 1, "\u4F86"], [63790, 1, "\u51B7"], [63791, 1, "\u52DE"], [63792, 1, "\u64C4"], [63793, 1, "\u6AD3"], [63794, 1, "\u7210"], [63795, 1, "\u76E7"], [63796, 1, "\u8001"], [63797, 1, "\u8606"], [63798, 1, "\u865C"], [63799, 1, "\u8DEF"], [63800, 1, "\u9732"], [63801, 1, "\u9B6F"], [63802, 1, "\u9DFA"], [63803, 1, "\u788C"], [63804, 1, "\u797F"], [63805, 1, "\u7DA0"], [63806, 1, "\u83C9"], [63807, 1, "\u9304"], [63808, 1, "\u9E7F"], [63809, 1, "\u8AD6"], [63810, 1, "\u58DF"], [63811, 1, "\u5F04"], [63812, 1, "\u7C60"], [63813, 1, "\u807E"], [63814, 1, "\u7262"], [63815, 1, "\u78CA"], [63816, 1, "\u8CC2"], [63817, 1, "\u96F7"], [63818, 1, "\u58D8"], [63819, 1, "\u5C62"], [63820, 1, "\u6A13"], [63821, 1, "\u6DDA"], [63822, 1, "\u6F0F"], [63823, 1, "\u7D2F"], [63824, 1, "\u7E37"], [63825, 1, "\u964B"], [63826, 1, "\u52D2"], [63827, 1, "\u808B"], [63828, 1, "\u51DC"], [63829, 1, "\u51CC"], [63830, 1, "\u7A1C"], [63831, 1, "\u7DBE"], [63832, 1, "\u83F1"], [63833, 1, "\u9675"], [63834, 1, "\u8B80"], [63835, 1, "\u62CF"], [63836, 1, "\u6A02"], [63837, 1, "\u8AFE"], [63838, 1, "\u4E39"], [63839, 1, "\u5BE7"], [63840, 1, "\u6012"], [63841, 1, "\u7387"], [63842, 1, "\u7570"], [63843, 1, "\u5317"], [63844, 1, "\u78FB"], [63845, 1, "\u4FBF"], [63846, 1, "\u5FA9"], [63847, 1, "\u4E0D"], [63848, 1, "\u6CCC"], [63849, 1, "\u6578"], [63850, 1, "\u7D22"], [63851, 1, "\u53C3"], [63852, 1, "\u585E"], [63853, 1, "\u7701"], [63854, 1, "\u8449"], [63855, 1, "\u8AAA"], [63856, 1, "\u6BBA"], [63857, 1, "\u8FB0"], [63858, 1, "\u6C88"], [63859, 1, "\u62FE"], [63860, 1, "\u82E5"], [63861, 1, "\u63A0"], [63862, 1, "\u7565"], [63863, 1, "\u4EAE"], [63864, 1, "\u5169"], [63865, 1, "\u51C9"], [63866, 1, "\u6881"], [63867, 1, "\u7CE7"], [63868, 1, "\u826F"], [63869, 1, "\u8AD2"], [63870, 1, "\u91CF"], [63871, 1, "\u52F5"], [63872, 1, "\u5442"], [63873, 1, "\u5973"], [63874, 1, "\u5EEC"], [63875, 1, "\u65C5"], [63876, 1, "\u6FFE"], [63877, 1, "\u792A"], [63878, 1, "\u95AD"], [63879, 1, "\u9A6A"], [63880, 1, "\u9E97"], [63881, 1, "\u9ECE"], [63882, 1, "\u529B"], [63883, 1, "\u66C6"], [63884, 1, "\u6B77"], [63885, 1, "\u8F62"], [63886, 1, "\u5E74"], [63887, 1, "\u6190"], [63888, 1, "\u6200"], [63889, 1, "\u649A"], [63890, 1, "\u6F23"], [63891, 1, "\u7149"], [63892, 1, "\u7489"], [63893, 1, "\u79CA"], [63894, 1, "\u7DF4"], [63895, 1, "\u806F"], [63896, 1, "\u8F26"], [63897, 1, "\u84EE"], [63898, 1, "\u9023"], [63899, 1, "\u934A"], [63900, 1, "\u5217"], [63901, 1, "\u52A3"], [63902, 1, "\u54BD"], [63903, 1, "\u70C8"], [63904, 1, "\u88C2"], [63905, 1, "\u8AAA"], [63906, 1, "\u5EC9"], [63907, 1, "\u5FF5"], [63908, 1, "\u637B"], [63909, 1, "\u6BAE"], [63910, 1, "\u7C3E"], [63911, 1, "\u7375"], [63912, 1, "\u4EE4"], [63913, 1, "\u56F9"], [63914, 1, "\u5BE7"], [63915, 1, "\u5DBA"], [63916, 1, "\u601C"], [63917, 1, "\u73B2"], [63918, 1, "\u7469"], [63919, 1, "\u7F9A"], [63920, 1, "\u8046"], [63921, 1, "\u9234"], [63922, 1, "\u96F6"], [63923, 1, "\u9748"], [63924, 1, "\u9818"], [63925, 1, "\u4F8B"], [63926, 1, "\u79AE"], [63927, 1, "\u91B4"], [63928, 1, "\u96B8"], [63929, 1, "\u60E1"], [63930, 1, "\u4E86"], [63931, 1, "\u50DA"], [63932, 1, "\u5BEE"], [63933, 1, "\u5C3F"], [63934, 1, "\u6599"], [63935, 1, "\u6A02"], [63936, 1, "\u71CE"], [63937, 1, "\u7642"], [63938, 1, "\u84FC"], [63939, 1, "\u907C"], [63940, 1, "\u9F8D"], [63941, 1, "\u6688"], [63942, 1, "\u962E"], [63943, 1, "\u5289"], [63944, 1, "\u677B"], [63945, 1, "\u67F3"], [63946, 1, "\u6D41"], [63947, 1, "\u6E9C"], [63948, 1, "\u7409"], [63949, 1, "\u7559"], [63950, 1, "\u786B"], [63951, 1, "\u7D10"], [63952, 1, "\u985E"], [63953, 1, "\u516D"], [63954, 1, "\u622E"], [63955, 1, "\u9678"], [63956, 1, "\u502B"], [63957, 1, "\u5D19"], [63958, 1, "\u6DEA"], [63959, 1, "\u8F2A"], [63960, 1, "\u5F8B"], [63961, 1, "\u6144"], [63962, 1, "\u6817"], [63963, 1, "\u7387"], [63964, 1, "\u9686"], [63965, 1, "\u5229"], [63966, 1, "\u540F"], [63967, 1, "\u5C65"], [63968, 1, "\u6613"], [63969, 1, "\u674E"], [63970, 1, "\u68A8"], [63971, 1, "\u6CE5"], [63972, 1, "\u7406"], [63973, 1, "\u75E2"], [63974, 1, "\u7F79"], [63975, 1, "\u88CF"], [63976, 1, "\u88E1"], [63977, 1, "\u91CC"], [63978, 1, "\u96E2"], [63979, 1, "\u533F"], [63980, 1, "\u6EBA"], [63981, 1, "\u541D"], [63982, 1, "\u71D0"], [63983, 1, "\u7498"], [63984, 1, "\u85FA"], [63985, 1, "\u96A3"], [63986, 1, "\u9C57"], [63987, 1, "\u9E9F"], [63988, 1, "\u6797"], [63989, 1, "\u6DCB"], [63990, 1, "\u81E8"], [63991, 1, "\u7ACB"], [63992, 1, "\u7B20"], [63993, 1, "\u7C92"], [63994, 1, "\u72C0"], [63995, 1, "\u7099"], [63996, 1, "\u8B58"], [63997, 1, "\u4EC0"], [63998, 1, "\u8336"], [63999, 1, "\u523A"], [64e3, 1, "\u5207"], [64001, 1, "\u5EA6"], [64002, 1, "\u62D3"], [64003, 1, "\u7CD6"], [64004, 1, "\u5B85"], [64005, 1, "\u6D1E"], [64006, 1, "\u66B4"], [64007, 1, "\u8F3B"], [64008, 1, "\u884C"], [64009, 1, "\u964D"], [64010, 1, "\u898B"], [64011, 1, "\u5ED3"], [64012, 1, "\u5140"], [64013, 1, "\u55C0"], [[64014, 64015], 2], [64016, 1, "\u585A"], [64017, 2], [64018, 1, "\u6674"], [[64019, 64020], 2], [64021, 1, "\u51DE"], [64022, 1, "\u732A"], [64023, 1, "\u76CA"], [64024, 1, "\u793C"], [64025, 1, "\u795E"], [64026, 1, "\u7965"], [64027, 1, "\u798F"], [64028, 1, "\u9756"], [64029, 1, "\u7CBE"], [64030, 1, "\u7FBD"], [64031, 2], [64032, 1, "\u8612"], [64033, 2], [64034, 1, "\u8AF8"], [[64035, 64036], 2], [64037, 1, "\u9038"], [64038, 1, "\u90FD"], [[64039, 64041], 2], [64042, 1, "\u98EF"], [64043, 1, "\u98FC"], [64044, 1, "\u9928"], [64045, 1, "\u9DB4"], [64046, 1, "\u90DE"], [64047, 1, "\u96B7"], [64048, 1, "\u4FAE"], [64049, 1, "\u50E7"], [64050, 1, "\u514D"], [64051, 1, "\u52C9"], [64052, 1, "\u52E4"], [64053, 1, "\u5351"], [64054, 1, "\u559D"], [64055, 1, "\u5606"], [64056, 1, "\u5668"], [64057, 1, "\u5840"], [64058, 1, "\u58A8"], [64059, 1, "\u5C64"], [64060, 1, "\u5C6E"], [64061, 1, "\u6094"], [64062, 1, "\u6168"], [64063, 1, "\u618E"], [64064, 1, "\u61F2"], [64065, 1, "\u654F"], [64066, 1, "\u65E2"], [64067, 1, "\u6691"], [64068, 1, "\u6885"], [64069, 1, "\u6D77"], [64070, 1, "\u6E1A"], [64071, 1, "\u6F22"], [64072, 1, "\u716E"], [64073, 1, "\u722B"], [64074, 1, "\u7422"], [64075, 1, "\u7891"], [64076, 1, "\u793E"], [64077, 1, "\u7949"], [64078, 1, "\u7948"], [64079, 1, "\u7950"], [64080, 1, "\u7956"], [64081, 1, "\u795D"], [64082, 1, "\u798D"], [64083, 1, "\u798E"], [64084, 1, "\u7A40"], [64085, 1, "\u7A81"], [64086, 1, "\u7BC0"], [64087, 1, "\u7DF4"], [64088, 1, "\u7E09"], [64089, 1, "\u7E41"], [64090, 1, "\u7F72"], [64091, 1, "\u8005"], [64092, 1, "\u81ED"], [[64093, 64094], 1, "\u8279"], [64095, 1, "\u8457"], [64096, 1, "\u8910"], [64097, 1, "\u8996"], [64098, 1, "\u8B01"], [64099, 1, "\u8B39"], [64100, 1, "\u8CD3"], [64101, 1, "\u8D08"], [64102, 1, "\u8FB6"], [64103, 1, "\u9038"], [64104, 1, "\u96E3"], [64105, 1, "\u97FF"], [64106, 1, "\u983B"], [64107, 1, "\u6075"], [64108, 1, "\u{242EE}"], [64109, 1, "\u8218"], [[64110, 64111], 3], [64112, 1, "\u4E26"], [64113, 1, "\u51B5"], [64114, 1, "\u5168"], [64115, 1, "\u4F80"], [64116, 1, "\u5145"], [64117, 1, "\u5180"], [64118, 1, "\u52C7"], [64119, 1, "\u52FA"], [64120, 1, "\u559D"], [64121, 1, "\u5555"], [64122, 1, "\u5599"], [64123, 1, "\u55E2"], [64124, 1, "\u585A"], [64125, 1, "\u58B3"], [64126, 1, "\u5944"], [64127, 1, "\u5954"], [64128, 1, "\u5A62"], [64129, 1, "\u5B28"], [64130, 1, "\u5ED2"], [64131, 1, "\u5ED9"], [64132, 1, "\u5F69"], [64133, 1, "\u5FAD"], [64134, 1, "\u60D8"], [64135, 1, "\u614E"], [64136, 1, "\u6108"], [64137, 1, "\u618E"], [64138, 1, "\u6160"], [64139, 1, "\u61F2"], [64140, 1, "\u6234"], [64141, 1, "\u63C4"], [64142, 1, "\u641C"], [64143, 1, "\u6452"], [64144, 1, "\u6556"], [64145, 1, "\u6674"], [64146, 1, "\u6717"], [64147, 1, "\u671B"], [64148, 1, "\u6756"], [64149, 1, "\u6B79"], [64150, 1, "\u6BBA"], [64151, 1, "\u6D41"], [64152, 1, "\u6EDB"], [64153, 1, "\u6ECB"], [64154, 1, "\u6F22"], [64155, 1, "\u701E"], [64156, 1, "\u716E"], [64157, 1, "\u77A7"], [64158, 1, "\u7235"], [64159, 1, "\u72AF"], [64160, 1, "\u732A"], [64161, 1, "\u7471"], [64162, 1, "\u7506"], [64163, 1, "\u753B"], [64164, 1, "\u761D"], [64165, 1, "\u761F"], [64166, 1, "\u76CA"], [64167, 1, "\u76DB"], [64168, 1, "\u76F4"], [64169, 1, "\u774A"], [64170, 1, "\u7740"], [64171, 1, "\u78CC"], [64172, 1, "\u7AB1"], [64173, 1, "\u7BC0"], [64174, 1, "\u7C7B"], [64175, 1, "\u7D5B"], [64176, 1, "\u7DF4"], [64177, 1, "\u7F3E"], [64178, 1, "\u8005"], [64179, 1, "\u8352"], [64180, 1, "\u83EF"], [64181, 1, "\u8779"], [64182, 1, "\u8941"], [64183, 1, "\u8986"], [64184, 1, "\u8996"], [64185, 1, "\u8ABF"], [64186, 1, "\u8AF8"], [64187, 1, "\u8ACB"], [64188, 1, "\u8B01"], [64189, 1, "\u8AFE"], [64190, 1, "\u8AED"], [64191, 1, "\u8B39"], [64192, 1, "\u8B8A"], [64193, 1, "\u8D08"], [64194, 1, "\u8F38"], [64195, 1, "\u9072"], [64196, 1, "\u9199"], [64197, 1, "\u9276"], [64198, 1, "\u967C"], [64199, 1, "\u96E3"], [64200, 1, "\u9756"], [64201, 1, "\u97DB"], [64202, 1, "\u97FF"], [64203, 1, "\u980B"], [64204, 1, "\u983B"], [64205, 1, "\u9B12"], [64206, 1, "\u9F9C"], [64207, 1, "\u{2284A}"], [64208, 1, "\u{22844}"], [64209, 1, "\u{233D5}"], [64210, 1, "\u3B9D"], [64211, 1, "\u4018"], [64212, 1, "\u4039"], [64213, 1, "\u{25249}"], [64214, 1, "\u{25CD0}"], [64215, 1, "\u{27ED3}"], [64216, 1, "\u9F43"], [64217, 1, "\u9F8E"], [[64218, 64255], 3], [64256, 1, "ff"], [64257, 1, "fi"], [64258, 1, "fl"], [64259, 1, "ffi"], [64260, 1, "ffl"], [[64261, 64262], 1, "st"], [[64263, 64274], 3], [64275, 1, "\u0574\u0576"], [64276, 1, "\u0574\u0565"], [64277, 1, "\u0574\u056B"], [64278, 1, "\u057E\u0576"], [64279, 1, "\u0574\u056D"], [[64280, 64284], 3], [64285, 1, "\u05D9\u05B4"], [64286, 2], [64287, 1, "\u05F2\u05B7"], [64288, 1, "\u05E2"], [64289, 1, "\u05D0"], [64290, 1, "\u05D3"], [64291, 1, "\u05D4"], [64292, 1, "\u05DB"], [64293, 1, "\u05DC"], [64294, 1, "\u05DD"], [64295, 1, "\u05E8"], [64296, 1, "\u05EA"], [64297, 1, "+"], [64298, 1, "\u05E9\u05C1"], [64299, 1, "\u05E9\u05C2"], [64300, 1, "\u05E9\u05BC\u05C1"], [64301, 1, "\u05E9\u05BC\u05C2"], [64302, 1, "\u05D0\u05B7"], [64303, 1, "\u05D0\u05B8"], [64304, 1, "\u05D0\u05BC"], [64305, 1, "\u05D1\u05BC"], [64306, 1, "\u05D2\u05BC"], [64307, 1, "\u05D3\u05BC"], [64308, 1, "\u05D4\u05BC"], [64309, 1, "\u05D5\u05BC"], [64310, 1, "\u05D6\u05BC"], [64311, 3], [64312, 1, "\u05D8\u05BC"], [64313, 1, "\u05D9\u05BC"], [64314, 1, "\u05DA\u05BC"], [64315, 1, "\u05DB\u05BC"], [64316, 1, "\u05DC\u05BC"], [64317, 3], [64318, 1, "\u05DE\u05BC"], [64319, 3], [64320, 1, "\u05E0\u05BC"], [64321, 1, "\u05E1\u05BC"], [64322, 3], [64323, 1, "\u05E3\u05BC"], [64324, 1, "\u05E4\u05BC"], [64325, 3], [64326, 1, "\u05E6\u05BC"], [64327, 1, "\u05E7\u05BC"], [64328, 1, "\u05E8\u05BC"], [64329, 1, "\u05E9\u05BC"], [64330, 1, "\u05EA\u05BC"], [64331, 1, "\u05D5\u05B9"], [64332, 1, "\u05D1\u05BF"], [64333, 1, "\u05DB\u05BF"], [64334, 1, "\u05E4\u05BF"], [64335, 1, "\u05D0\u05DC"], [[64336, 64337], 1, "\u0671"], [[64338, 64341], 1, "\u067B"], [[64342, 64345], 1, "\u067E"], [[64346, 64349], 1, "\u0680"], [[64350, 64353], 1, "\u067A"], [[64354, 64357], 1, "\u067F"], [[64358, 64361], 1, "\u0679"], [[64362, 64365], 1, "\u06A4"], [[64366, 64369], 1, "\u06A6"], [[64370, 64373], 1, "\u0684"], [[64374, 64377], 1, "\u0683"], [[64378, 64381], 1, "\u0686"], [[64382, 64385], 1, "\u0687"], [[64386, 64387], 1, "\u068D"], [[64388, 64389], 1, "\u068C"], [[64390, 64391], 1, "\u068E"], [[64392, 64393], 1, "\u0688"], [[64394, 64395], 1, "\u0698"], [[64396, 64397], 1, "\u0691"], [[64398, 64401], 1, "\u06A9"], [[64402, 64405], 1, "\u06AF"], [[64406, 64409], 1, "\u06B3"], [[64410, 64413], 1, "\u06B1"], [[64414, 64415], 1, "\u06BA"], [[64416, 64419], 1, "\u06BB"], [[64420, 64421], 1, "\u06C0"], [[64422, 64425], 1, "\u06C1"], [[64426, 64429], 1, "\u06BE"], [[64430, 64431], 1, "\u06D2"], [[64432, 64433], 1, "\u06D3"], [[64434, 64449], 2], [64450, 2], [[64451, 64466], 3], [[64467, 64470], 1, "\u06AD"], [[64471, 64472], 1, "\u06C7"], [[64473, 64474], 1, "\u06C6"], [[64475, 64476], 1, "\u06C8"], [64477, 1, "\u06C7\u0674"], [[64478, 64479], 1, "\u06CB"], [[64480, 64481], 1, "\u06C5"], [[64482, 64483], 1, "\u06C9"], [[64484, 64487], 1, "\u06D0"], [[64488, 64489], 1, "\u0649"], [[64490, 64491], 1, "\u0626\u0627"], [[64492, 64493], 1, "\u0626\u06D5"], [[64494, 64495], 1, "\u0626\u0648"], [[64496, 64497], 1, "\u0626\u06C7"], [[64498, 64499], 1, "\u0626\u06C6"], [[64500, 64501], 1, "\u0626\u06C8"], [[64502, 64504], 1, "\u0626\u06D0"], [[64505, 64507], 1, "\u0626\u0649"], [[64508, 64511], 1, "\u06CC"], [64512, 1, "\u0626\u062C"], [64513, 1, "\u0626\u062D"], [64514, 1, "\u0626\u0645"], [64515, 1, "\u0626\u0649"], [64516, 1, "\u0626\u064A"], [64517, 1, "\u0628\u062C"], [64518, 1, "\u0628\u062D"], [64519, 1, "\u0628\u062E"], [64520, 1, "\u0628\u0645"], [64521, 1, "\u0628\u0649"], [64522, 1, "\u0628\u064A"], [64523, 1, "\u062A\u062C"], [64524, 1, "\u062A\u062D"], [64525, 1, "\u062A\u062E"], [64526, 1, "\u062A\u0645"], [64527, 1, "\u062A\u0649"], [64528, 1, "\u062A\u064A"], [64529, 1, "\u062B\u062C"], [64530, 1, "\u062B\u0645"], [64531, 1, "\u062B\u0649"], [64532, 1, "\u062B\u064A"], [64533, 1, "\u062C\u062D"], [64534, 1, "\u062C\u0645"], [64535, 1, "\u062D\u062C"], [64536, 1, "\u062D\u0645"], [64537, 1, "\u062E\u062C"], [64538, 1, "\u062E\u062D"], [64539, 1, "\u062E\u0645"], [64540, 1, "\u0633\u062C"], [64541, 1, "\u0633\u062D"], [64542, 1, "\u0633\u062E"], [64543, 1, "\u0633\u0645"], [64544, 1, "\u0635\u062D"], [64545, 1, "\u0635\u0645"], [64546, 1, "\u0636\u062C"], [64547, 1, "\u0636\u062D"], [64548, 1, "\u0636\u062E"], [64549, 1, "\u0636\u0645"], [64550, 1, "\u0637\u062D"], [64551, 1, "\u0637\u0645"], [64552, 1, "\u0638\u0645"], [64553, 1, "\u0639\u062C"], [64554, 1, "\u0639\u0645"], [64555, 1, "\u063A\u062C"], [64556, 1, "\u063A\u0645"], [64557, 1, "\u0641\u062C"], [64558, 1, "\u0641\u062D"], [64559, 1, "\u0641\u062E"], [64560, 1, "\u0641\u0645"], [64561, 1, "\u0641\u0649"], [64562, 1, "\u0641\u064A"], [64563, 1, "\u0642\u062D"], [64564, 1, "\u0642\u0645"], [64565, 1, "\u0642\u0649"], [64566, 1, "\u0642\u064A"], [64567, 1, "\u0643\u0627"], [64568, 1, "\u0643\u062C"], [64569, 1, "\u0643\u062D"], [64570, 1, "\u0643\u062E"], [64571, 1, "\u0643\u0644"], [64572, 1, "\u0643\u0645"], [64573, 1, "\u0643\u0649"], [64574, 1, "\u0643\u064A"], [64575, 1, "\u0644\u062C"], [64576, 1, "\u0644\u062D"], [64577, 1, "\u0644\u062E"], [64578, 1, "\u0644\u0645"], [64579, 1, "\u0644\u0649"], [64580, 1, "\u0644\u064A"], [64581, 1, "\u0645\u062C"], [64582, 1, "\u0645\u062D"], [64583, 1, "\u0645\u062E"], [64584, 1, "\u0645\u0645"], [64585, 1, "\u0645\u0649"], [64586, 1, "\u0645\u064A"], [64587, 1, "\u0646\u062C"], [64588, 1, "\u0646\u062D"], [64589, 1, "\u0646\u062E"], [64590, 1, "\u0646\u0645"], [64591, 1, "\u0646\u0649"], [64592, 1, "\u0646\u064A"], [64593, 1, "\u0647\u062C"], [64594, 1, "\u0647\u0645"], [64595, 1, "\u0647\u0649"], [64596, 1, "\u0647\u064A"], [64597, 1, "\u064A\u062C"], [64598, 1, "\u064A\u062D"], [64599, 1, "\u064A\u062E"], [64600, 1, "\u064A\u0645"], [64601, 1, "\u064A\u0649"], [64602, 1, "\u064A\u064A"], [64603, 1, "\u0630\u0670"], [64604, 1, "\u0631\u0670"], [64605, 1, "\u0649\u0670"], [64606, 1, " \u064C\u0651"], [64607, 1, " \u064D\u0651"], [64608, 1, " \u064E\u0651"], [64609, 1, " \u064F\u0651"], [64610, 1, " \u0650\u0651"], [64611, 1, " \u0651\u0670"], [64612, 1, "\u0626\u0631"], [64613, 1, "\u0626\u0632"], [64614, 1, "\u0626\u0645"], [64615, 1, "\u0626\u0646"], [64616, 1, "\u0626\u0649"], [64617, 1, "\u0626\u064A"], [64618, 1, "\u0628\u0631"], [64619, 1, "\u0628\u0632"], [64620, 1, "\u0628\u0645"], [64621, 1, "\u0628\u0646"], [64622, 1, "\u0628\u0649"], [64623, 1, "\u0628\u064A"], [64624, 1, "\u062A\u0631"], [64625, 1, "\u062A\u0632"], [64626, 1, "\u062A\u0645"], [64627, 1, "\u062A\u0646"], [64628, 1, "\u062A\u0649"], [64629, 1, "\u062A\u064A"], [64630, 1, "\u062B\u0631"], [64631, 1, "\u062B\u0632"], [64632, 1, "\u062B\u0645"], [64633, 1, "\u062B\u0646"], [64634, 1, "\u062B\u0649"], [64635, 1, "\u062B\u064A"], [64636, 1, "\u0641\u0649"], [64637, 1, "\u0641\u064A"], [64638, 1, "\u0642\u0649"], [64639, 1, "\u0642\u064A"], [64640, 1, "\u0643\u0627"], [64641, 1, "\u0643\u0644"], [64642, 1, "\u0643\u0645"], [64643, 1, "\u0643\u0649"], [64644, 1, "\u0643\u064A"], [64645, 1, "\u0644\u0645"], [64646, 1, "\u0644\u0649"], [64647, 1, "\u0644\u064A"], [64648, 1, "\u0645\u0627"], [64649, 1, "\u0645\u0645"], [64650, 1, "\u0646\u0631"], [64651, 1, "\u0646\u0632"], [64652, 1, "\u0646\u0645"], [64653, 1, "\u0646\u0646"], [64654, 1, "\u0646\u0649"], [64655, 1, "\u0646\u064A"], [64656, 1, "\u0649\u0670"], [64657, 1, "\u064A\u0631"], [64658, 1, "\u064A\u0632"], [64659, 1, "\u064A\u0645"], [64660, 1, "\u064A\u0646"], [64661, 1, "\u064A\u0649"], [64662, 1, "\u064A\u064A"], [64663, 1, "\u0626\u062C"], [64664, 1, "\u0626\u062D"], [64665, 1, "\u0626\u062E"], [64666, 1, "\u0626\u0645"], [64667, 1, "\u0626\u0647"], [64668, 1, "\u0628\u062C"], [64669, 1, "\u0628\u062D"], [64670, 1, "\u0628\u062E"], [64671, 1, "\u0628\u0645"], [64672, 1, "\u0628\u0647"], [64673, 1, "\u062A\u062C"], [64674, 1, "\u062A\u062D"], [64675, 1, "\u062A\u062E"], [64676, 1, "\u062A\u0645"], [64677, 1, "\u062A\u0647"], [64678, 1, "\u062B\u0645"], [64679, 1, "\u062C\u062D"], [64680, 1, "\u062C\u0645"], [64681, 1, "\u062D\u062C"], [64682, 1, "\u062D\u0645"], [64683, 1, "\u062E\u062C"], [64684, 1, "\u062E\u0645"], [64685, 1, "\u0633\u062C"], [64686, 1, "\u0633\u062D"], [64687, 1, "\u0633\u062E"], [64688, 1, "\u0633\u0645"], [64689, 1, "\u0635\u062D"], [64690, 1, "\u0635\u062E"], [64691, 1, "\u0635\u0645"], [64692, 1, "\u0636\u062C"], [64693, 1, "\u0636\u062D"], [64694, 1, "\u0636\u062E"], [64695, 1, "\u0636\u0645"], [64696, 1, "\u0637\u062D"], [64697, 1, "\u0638\u0645"], [64698, 1, "\u0639\u062C"], [64699, 1, "\u0639\u0645"], [64700, 1, "\u063A\u062C"], [64701, 1, "\u063A\u0645"], [64702, 1, "\u0641\u062C"], [64703, 1, "\u0641\u062D"], [64704, 1, "\u0641\u062E"], [64705, 1, "\u0641\u0645"], [64706, 1, "\u0642\u062D"], [64707, 1, "\u0642\u0645"], [64708, 1, "\u0643\u062C"], [64709, 1, "\u0643\u062D"], [64710, 1, "\u0643\u062E"], [64711, 1, "\u0643\u0644"], [64712, 1, "\u0643\u0645"], [64713, 1, "\u0644\u062C"], [64714, 1, "\u0644\u062D"], [64715, 1, "\u0644\u062E"], [64716, 1, "\u0644\u0645"], [64717, 1, "\u0644\u0647"], [64718, 1, "\u0645\u062C"], [64719, 1, "\u0645\u062D"], [64720, 1, "\u0645\u062E"], [64721, 1, "\u0645\u0645"], [64722, 1, "\u0646\u062C"], [64723, 1, "\u0646\u062D"], [64724, 1, "\u0646\u062E"], [64725, 1, "\u0646\u0645"], [64726, 1, "\u0646\u0647"], [64727, 1, "\u0647\u062C"], [64728, 1, "\u0647\u0645"], [64729, 1, "\u0647\u0670"], [64730, 1, "\u064A\u062C"], [64731, 1, "\u064A\u062D"], [64732, 1, "\u064A\u062E"], [64733, 1, "\u064A\u0645"], [64734, 1, "\u064A\u0647"], [64735, 1, "\u0626\u0645"], [64736, 1, "\u0626\u0647"], [64737, 1, "\u0628\u0645"], [64738, 1, "\u0628\u0647"], [64739, 1, "\u062A\u0645"], [64740, 1, "\u062A\u0647"], [64741, 1, "\u062B\u0645"], [64742, 1, "\u062B\u0647"], [64743, 1, "\u0633\u0645"], [64744, 1, "\u0633\u0647"], [64745, 1, "\u0634\u0645"], [64746, 1, "\u0634\u0647"], [64747, 1, "\u0643\u0644"], [64748, 1, "\u0643\u0645"], [64749, 1, "\u0644\u0645"], [64750, 1, "\u0646\u0645"], [64751, 1, "\u0646\u0647"], [64752, 1, "\u064A\u0645"], [64753, 1, "\u064A\u0647"], [64754, 1, "\u0640\u064E\u0651"], [64755, 1, "\u0640\u064F\u0651"], [64756, 1, "\u0640\u0650\u0651"], [64757, 1, "\u0637\u0649"], [64758, 1, "\u0637\u064A"], [64759, 1, "\u0639\u0649"], [64760, 1, "\u0639\u064A"], [64761, 1, "\u063A\u0649"], [64762, 1, "\u063A\u064A"], [64763, 1, "\u0633\u0649"], [64764, 1, "\u0633\u064A"], [64765, 1, "\u0634\u0649"], [64766, 1, "\u0634\u064A"], [64767, 1, "\u062D\u0649"], [64768, 1, "\u062D\u064A"], [64769, 1, "\u062C\u0649"], [64770, 1, "\u062C\u064A"], [64771, 1, "\u062E\u0649"], [64772, 1, "\u062E\u064A"], [64773, 1, "\u0635\u0649"], [64774, 1, "\u0635\u064A"], [64775, 1, "\u0636\u0649"], [64776, 1, "\u0636\u064A"], [64777, 1, "\u0634\u062C"], [64778, 1, "\u0634\u062D"], [64779, 1, "\u0634\u062E"], [64780, 1, "\u0634\u0645"], [64781, 1, "\u0634\u0631"], [64782, 1, "\u0633\u0631"], [64783, 1, "\u0635\u0631"], [64784, 1, "\u0636\u0631"], [64785, 1, "\u0637\u0649"], [64786, 1, "\u0637\u064A"], [64787, 1, "\u0639\u0649"], [64788, 1, "\u0639\u064A"], [64789, 1, "\u063A\u0649"], [64790, 1, "\u063A\u064A"], [64791, 1, "\u0633\u0649"], [64792, 1, "\u0633\u064A"], [64793, 1, "\u0634\u0649"], [64794, 1, "\u0634\u064A"], [64795, 1, "\u062D\u0649"], [64796, 1, "\u062D\u064A"], [64797, 1, "\u062C\u0649"], [64798, 1, "\u062C\u064A"], [64799, 1, "\u062E\u0649"], [64800, 1, "\u062E\u064A"], [64801, 1, "\u0635\u0649"], [64802, 1, "\u0635\u064A"], [64803, 1, "\u0636\u0649"], [64804, 1, "\u0636\u064A"], [64805, 1, "\u0634\u062C"], [64806, 1, "\u0634\u062D"], [64807, 1, "\u0634\u062E"], [64808, 1, "\u0634\u0645"], [64809, 1, "\u0634\u0631"], [64810, 1, "\u0633\u0631"], [64811, 1, "\u0635\u0631"], [64812, 1, "\u0636\u0631"], [64813, 1, "\u0634\u062C"], [64814, 1, "\u0634\u062D"], [64815, 1, "\u0634\u062E"], [64816, 1, "\u0634\u0645"], [64817, 1, "\u0633\u0647"], [64818, 1, "\u0634\u0647"], [64819, 1, "\u0637\u0645"], [64820, 1, "\u0633\u062C"], [64821, 1, "\u0633\u062D"], [64822, 1, "\u0633\u062E"], [64823, 1, "\u0634\u062C"], [64824, 1, "\u0634\u062D"], [64825, 1, "\u0634\u062E"], [64826, 1, "\u0637\u0645"], [64827, 1, "\u0638\u0645"], [[64828, 64829], 1, "\u0627\u064B"], [[64830, 64831], 2], [[64832, 64847], 2], [64848, 1, "\u062A\u062C\u0645"], [[64849, 64850], 1, "\u062A\u062D\u062C"], [64851, 1, "\u062A\u062D\u0645"], [64852, 1, "\u062A\u062E\u0645"], [64853, 1, "\u062A\u0645\u062C"], [64854, 1, "\u062A\u0645\u062D"], [64855, 1, "\u062A\u0645\u062E"], [[64856, 64857], 1, "\u062C\u0645\u062D"], [64858, 1, "\u062D\u0645\u064A"], [64859, 1, "\u062D\u0645\u0649"], [64860, 1, "\u0633\u062D\u062C"], [64861, 1, "\u0633\u062C\u062D"], [64862, 1, "\u0633\u062C\u0649"], [[64863, 64864], 1, "\u0633\u0645\u062D"], [64865, 1, "\u0633\u0645\u062C"], [[64866, 64867], 1, "\u0633\u0645\u0645"], [[64868, 64869], 1, "\u0635\u062D\u062D"], [64870, 1, "\u0635\u0645\u0645"], [[64871, 64872], 1, "\u0634\u062D\u0645"], [64873, 1, "\u0634\u062C\u064A"], [[64874, 64875], 1, "\u0634\u0645\u062E"], [[64876, 64877], 1, "\u0634\u0645\u0645"], [64878, 1, "\u0636\u062D\u0649"], [[64879, 64880], 1, "\u0636\u062E\u0645"], [[64881, 64882], 1, "\u0637\u0645\u062D"], [64883, 1, "\u0637\u0645\u0645"], [64884, 1, "\u0637\u0645\u064A"], [64885, 1, "\u0639\u062C\u0645"], [[64886, 64887], 1, "\u0639\u0645\u0645"], [64888, 1, "\u0639\u0645\u0649"], [64889, 1, "\u063A\u0645\u0645"], [64890, 1, "\u063A\u0645\u064A"], [64891, 1, "\u063A\u0645\u0649"], [[64892, 64893], 1, "\u0641\u062E\u0645"], [64894, 1, "\u0642\u0645\u062D"], [64895, 1, "\u0642\u0645\u0645"], [64896, 1, "\u0644\u062D\u0645"], [64897, 1, "\u0644\u062D\u064A"], [64898, 1, "\u0644\u062D\u0649"], [[64899, 64900], 1, "\u0644\u062C\u062C"], [[64901, 64902], 1, "\u0644\u062E\u0645"], [[64903, 64904], 1, "\u0644\u0645\u062D"], [64905, 1, "\u0645\u062D\u062C"], [64906, 1, "\u0645\u062D\u0645"], [64907, 1, "\u0645\u062D\u064A"], [64908, 1, "\u0645\u062C\u062D"], [64909, 1, "\u0645\u062C\u0645"], [64910, 1, "\u0645\u062E\u062C"], [64911, 1, "\u0645\u062E\u0645"], [[64912, 64913], 3], [64914, 1, "\u0645\u062C\u062E"], [64915, 1, "\u0647\u0645\u062C"], [64916, 1, "\u0647\u0645\u0645"], [64917, 1, "\u0646\u062D\u0645"], [64918, 1, "\u0646\u062D\u0649"], [[64919, 64920], 1, "\u0646\u062C\u0645"], [64921, 1, "\u0646\u062C\u0649"], [64922, 1, "\u0646\u0645\u064A"], [64923, 1, "\u0646\u0645\u0649"], [[64924, 64925], 1, "\u064A\u0645\u0645"], [64926, 1, "\u0628\u062E\u064A"], [64927, 1, "\u062A\u062C\u064A"], [64928, 1, "\u062A\u062C\u0649"], [64929, 1, "\u062A\u062E\u064A"], [64930, 1, "\u062A\u062E\u0649"], [64931, 1, "\u062A\u0645\u064A"], [64932, 1, "\u062A\u0645\u0649"], [64933, 1, "\u062C\u0645\u064A"], [64934, 1, "\u062C\u062D\u0649"], [64935, 1, "\u062C\u0645\u0649"], [64936, 1, "\u0633\u062E\u0649"], [64937, 1, "\u0635\u062D\u064A"], [64938, 1, "\u0634\u062D\u064A"], [64939, 1, "\u0636\u062D\u064A"], [64940, 1, "\u0644\u062C\u064A"], [64941, 1, "\u0644\u0645\u064A"], [64942, 1, "\u064A\u062D\u064A"], [64943, 1, "\u064A\u062C\u064A"], [64944, 1, "\u064A\u0645\u064A"], [64945, 1, "\u0645\u0645\u064A"], [64946, 1, "\u0642\u0645\u064A"], [64947, 1, "\u0646\u062D\u064A"], [64948, 1, "\u0642\u0645\u062D"], [64949, 1, "\u0644\u062D\u0645"], [64950, 1, "\u0639\u0645\u064A"], [64951, 1, "\u0643\u0645\u064A"], [64952, 1, "\u0646\u062C\u062D"], [64953, 1, "\u0645\u062E\u064A"], [64954, 1, "\u0644\u062C\u0645"], [64955, 1, "\u0643\u0645\u0645"], [64956, 1, "\u0644\u062C\u0645"], [64957, 1, "\u0646\u062C\u062D"], [64958, 1, "\u062C\u062D\u064A"], [64959, 1, "\u062D\u062C\u064A"], [64960, 1, "\u0645\u062C\u064A"], [64961, 1, "\u0641\u0645\u064A"], [64962, 1, "\u0628\u062D\u064A"], [64963, 1, "\u0643\u0645\u0645"], [64964, 1, "\u0639\u062C\u0645"], [64965, 1, "\u0635\u0645\u0645"], [64966, 1, "\u0633\u062E\u064A"], [64967, 1, "\u0646\u062C\u064A"], [[64968, 64974], 3], [64975, 2], [[64976, 65007], 3], [65008, 1, "\u0635\u0644\u06D2"], [65009, 1, "\u0642\u0644\u06D2"], [65010, 1, "\u0627\u0644\u0644\u0647"], [65011, 1, "\u0627\u0643\u0628\u0631"], [65012, 1, "\u0645\u062D\u0645\u062F"], [65013, 1, "\u0635\u0644\u0639\u0645"], [65014, 1, "\u0631\u0633\u0648\u0644"], [65015, 1, "\u0639\u0644\u064A\u0647"], [65016, 1, "\u0648\u0633\u0644\u0645"], [65017, 1, "\u0635\u0644\u0649"], [65018, 1, "\u0635\u0644\u0649 \u0627\u0644\u0644\u0647 \u0639\u0644\u064A\u0647 \u0648\u0633\u0644\u0645"], [65019, 1, "\u062C\u0644 \u062C\u0644\u0627\u0644\u0647"], [65020, 1, "\u0631\u06CC\u0627\u0644"], [65021, 2], [[65022, 65023], 2], [[65024, 65039], 7], [65040, 1, ","], [65041, 1, "\u3001"], [65042, 3], [65043, 1, ":"], [65044, 1, ";"], [65045, 1, "!"], [65046, 1, "?"], [65047, 1, "\u3016"], [65048, 1, "\u3017"], [65049, 3], [[65050, 65055], 3], [[65056, 65059], 2], [[65060, 65062], 2], [[65063, 65069], 2], [[65070, 65071], 2], [65072, 3], [65073, 1, "\u2014"], [65074, 1, "\u2013"], [[65075, 65076], 1, "_"], [65077, 1, "("], [65078, 1, ")"], [65079, 1, "{"], [65080, 1, "}"], [65081, 1, "\u3014"], [65082, 1, "\u3015"], [65083, 1, "\u3010"], [65084, 1, "\u3011"], [65085, 1, "\u300A"], [65086, 1, "\u300B"], [65087, 1, "\u3008"], [65088, 1, "\u3009"], [65089, 1, "\u300C"], [65090, 1, "\u300D"], [65091, 1, "\u300E"], [65092, 1, "\u300F"], [[65093, 65094], 2], [65095, 1, "["], [65096, 1, "]"], [[65097, 65100], 1, " \u0305"], [[65101, 65103], 1, "_"], [65104, 1, ","], [65105, 1, "\u3001"], [65106, 3], [65107, 3], [65108, 1, ";"], [65109, 1, ":"], [65110, 1, "?"], [65111, 1, "!"], [65112, 1, "\u2014"], [65113, 1, "("], [65114, 1, ")"], [65115, 1, "{"], [65116, 1, "}"], [65117, 1, "\u3014"], [65118, 1, "\u3015"], [65119, 1, "#"], [65120, 1, "&"], [65121, 1, "*"], [65122, 1, "+"], [65123, 1, "-"], [65124, 1, "<"], [65125, 1, ">"], [65126, 1, "="], [65127, 3], [65128, 1, "\\"], [65129, 1, "$"], [65130, 1, "%"], [65131, 1, "@"], [[65132, 65135], 3], [65136, 1, " \u064B"], [65137, 1, "\u0640\u064B"], [65138, 1, " \u064C"], [65139, 2], [65140, 1, " \u064D"], [65141, 3], [65142, 1, " \u064E"], [65143, 1, "\u0640\u064E"], [65144, 1, " \u064F"], [65145, 1, "\u0640\u064F"], [65146, 1, " \u0650"], [65147, 1, "\u0640\u0650"], [65148, 1, " \u0651"], [65149, 1, "\u0640\u0651"], [65150, 1, " \u0652"], [65151, 1, "\u0640\u0652"], [65152, 1, "\u0621"], [[65153, 65154], 1, "\u0622"], [[65155, 65156], 1, "\u0623"], [[65157, 65158], 1, "\u0624"], [[65159, 65160], 1, "\u0625"], [[65161, 65164], 1, "\u0626"], [[65165, 65166], 1, "\u0627"], [[65167, 65170], 1, "\u0628"], [[65171, 65172], 1, "\u0629"], [[65173, 65176], 1, "\u062A"], [[65177, 65180], 1, "\u062B"], [[65181, 65184], 1, "\u062C"], [[65185, 65188], 1, "\u062D"], [[65189, 65192], 1, "\u062E"], [[65193, 65194], 1, "\u062F"], [[65195, 65196], 1, "\u0630"], [[65197, 65198], 1, "\u0631"], [[65199, 65200], 1, "\u0632"], [[65201, 65204], 1, "\u0633"], [[65205, 65208], 1, "\u0634"], [[65209, 65212], 1, "\u0635"], [[65213, 65216], 1, "\u0636"], [[65217, 65220], 1, "\u0637"], [[65221, 65224], 1, "\u0638"], [[65225, 65228], 1, "\u0639"], [[65229, 65232], 1, "\u063A"], [[65233, 65236], 1, "\u0641"], [[65237, 65240], 1, "\u0642"], [[65241, 65244], 1, "\u0643"], [[65245, 65248], 1, "\u0644"], [[65249, 65252], 1, "\u0645"], [[65253, 65256], 1, "\u0646"], [[65257, 65260], 1, "\u0647"], [[65261, 65262], 1, "\u0648"], [[65263, 65264], 1, "\u0649"], [[65265, 65268], 1, "\u064A"], [[65269, 65270], 1, "\u0644\u0622"], [[65271, 65272], 1, "\u0644\u0623"], [[65273, 65274], 1, "\u0644\u0625"], [[65275, 65276], 1, "\u0644\u0627"], [[65277, 65278], 3], [65279, 7], [65280, 3], [65281, 1, "!"], [65282, 1, '"'], [65283, 1, "#"], [65284, 1, "$"], [65285, 1, "%"], [65286, 1, "&"], [65287, 1, "'"], [65288, 1, "("], [65289, 1, ")"], [65290, 1, "*"], [65291, 1, "+"], [65292, 1, ","], [65293, 1, "-"], [65294, 1, "."], [65295, 1, "/"], [65296, 1, "0"], [65297, 1, "1"], [65298, 1, "2"], [65299, 1, "3"], [65300, 1, "4"], [65301, 1, "5"], [65302, 1, "6"], [65303, 1, "7"], [65304, 1, "8"], [65305, 1, "9"], [65306, 1, ":"], [65307, 1, ";"], [65308, 1, "<"], [65309, 1, "="], [65310, 1, ">"], [65311, 1, "?"], [65312, 1, "@"], [65313, 1, "a"], [65314, 1, "b"], [65315, 1, "c"], [65316, 1, "d"], [65317, 1, "e"], [65318, 1, "f"], [65319, 1, "g"], [65320, 1, "h"], [65321, 1, "i"], [65322, 1, "j"], [65323, 1, "k"], [65324, 1, "l"], [65325, 1, "m"], [65326, 1, "n"], [65327, 1, "o"], [65328, 1, "p"], [65329, 1, "q"], [65330, 1, "r"], [65331, 1, "s"], [65332, 1, "t"], [65333, 1, "u"], [65334, 1, "v"], [65335, 1, "w"], [65336, 1, "x"], [65337, 1, "y"], [65338, 1, "z"], [65339, 1, "["], [65340, 1, "\\"], [65341, 1, "]"], [65342, 1, "^"], [65343, 1, "_"], [65344, 1, "`"], [65345, 1, "a"], [65346, 1, "b"], [65347, 1, "c"], [65348, 1, "d"], [65349, 1, "e"], [65350, 1, "f"], [65351, 1, "g"], [65352, 1, "h"], [65353, 1, "i"], [65354, 1, "j"], [65355, 1, "k"], [65356, 1, "l"], [65357, 1, "m"], [65358, 1, "n"], [65359, 1, "o"], [65360, 1, "p"], [65361, 1, "q"], [65362, 1, "r"], [65363, 1, "s"], [65364, 1, "t"], [65365, 1, "u"], [65366, 1, "v"], [65367, 1, "w"], [65368, 1, "x"], [65369, 1, "y"], [65370, 1, "z"], [65371, 1, "{"], [65372, 1, "|"], [65373, 1, "}"], [65374, 1, "~"], [65375, 1, "\u2985"], [65376, 1, "\u2986"], [65377, 1, "."], [65378, 1, "\u300C"], [65379, 1, "\u300D"], [65380, 1, "\u3001"], [65381, 1, "\u30FB"], [65382, 1, "\u30F2"], [65383, 1, "\u30A1"], [65384, 1, "\u30A3"], [65385, 1, "\u30A5"], [65386, 1, "\u30A7"], [65387, 1, "\u30A9"], [65388, 1, "\u30E3"], [65389, 1, "\u30E5"], [65390, 1, "\u30E7"], [65391, 1, "\u30C3"], [65392, 1, "\u30FC"], [65393, 1, "\u30A2"], [65394, 1, "\u30A4"], [65395, 1, "\u30A6"], [65396, 1, "\u30A8"], [65397, 1, "\u30AA"], [65398, 1, "\u30AB"], [65399, 1, "\u30AD"], [65400, 1, "\u30AF"], [65401, 1, "\u30B1"], [65402, 1, "\u30B3"], [65403, 1, "\u30B5"], [65404, 1, "\u30B7"], [65405, 1, "\u30B9"], [65406, 1, "\u30BB"], [65407, 1, "\u30BD"], [65408, 1, "\u30BF"], [65409, 1, "\u30C1"], [65410, 1, "\u30C4"], [65411, 1, "\u30C6"], [65412, 1, "\u30C8"], [65413, 1, "\u30CA"], [65414, 1, "\u30CB"], [65415, 1, "\u30CC"], [65416, 1, "\u30CD"], [65417, 1, "\u30CE"], [65418, 1, "\u30CF"], [65419, 1, "\u30D2"], [65420, 1, "\u30D5"], [65421, 1, "\u30D8"], [65422, 1, "\u30DB"], [65423, 1, "\u30DE"], [65424, 1, "\u30DF"], [65425, 1, "\u30E0"], [65426, 1, "\u30E1"], [65427, 1, "\u30E2"], [65428, 1, "\u30E4"], [65429, 1, "\u30E6"], [65430, 1, "\u30E8"], [65431, 1, "\u30E9"], [65432, 1, "\u30EA"], [65433, 1, "\u30EB"], [65434, 1, "\u30EC"], [65435, 1, "\u30ED"], [65436, 1, "\u30EF"], [65437, 1, "\u30F3"], [65438, 1, "\u3099"], [65439, 1, "\u309A"], [65440, 7], [65441, 1, "\u1100"], [65442, 1, "\u1101"], [65443, 1, "\u11AA"], [65444, 1, "\u1102"], [65445, 1, "\u11AC"], [65446, 1, "\u11AD"], [65447, 1, "\u1103"], [65448, 1, "\u1104"], [65449, 1, "\u1105"], [65450, 1, "\u11B0"], [65451, 1, "\u11B1"], [65452, 1, "\u11B2"], [65453, 1, "\u11B3"], [65454, 1, "\u11B4"], [65455, 1, "\u11B5"], [65456, 1, "\u111A"], [65457, 1, "\u1106"], [65458, 1, "\u1107"], [65459, 1, "\u1108"], [65460, 1, "\u1121"], [65461, 1, "\u1109"], [65462, 1, "\u110A"], [65463, 1, "\u110B"], [65464, 1, "\u110C"], [65465, 1, "\u110D"], [65466, 1, "\u110E"], [65467, 1, "\u110F"], [65468, 1, "\u1110"], [65469, 1, "\u1111"], [65470, 1, "\u1112"], [[65471, 65473], 3], [65474, 1, "\u1161"], [65475, 1, "\u1162"], [65476, 1, "\u1163"], [65477, 1, "\u1164"], [65478, 1, "\u1165"], [65479, 1, "\u1166"], [[65480, 65481], 3], [65482, 1, "\u1167"], [65483, 1, "\u1168"], [65484, 1, "\u1169"], [65485, 1, "\u116A"], [65486, 1, "\u116B"], [65487, 1, "\u116C"], [[65488, 65489], 3], [65490, 1, "\u116D"], [65491, 1, "\u116E"], [65492, 1, "\u116F"], [65493, 1, "\u1170"], [65494, 1, "\u1171"], [65495, 1, "\u1172"], [[65496, 65497], 3], [65498, 1, "\u1173"], [65499, 1, "\u1174"], [65500, 1, "\u1175"], [[65501, 65503], 3], [65504, 1, "\xA2"], [65505, 1, "\xA3"], [65506, 1, "\xAC"], [65507, 1, " \u0304"], [65508, 1, "\xA6"], [65509, 1, "\xA5"], [65510, 1, "\u20A9"], [65511, 3], [65512, 1, "\u2502"], [65513, 1, "\u2190"], [65514, 1, "\u2191"], [65515, 1, "\u2192"], [65516, 1, "\u2193"], [65517, 1, "\u25A0"], [65518, 1, "\u25CB"], [[65519, 65528], 3], [[65529, 65531], 3], [65532, 3], [65533, 3], [[65534, 65535], 3], [[65536, 65547], 2], [65548, 3], [[65549, 65574], 2], [65575, 3], [[65576, 65594], 2], [65595, 3], [[65596, 65597], 2], [65598, 3], [[65599, 65613], 2], [[65614, 65615], 3], [[65616, 65629], 2], [[65630, 65663], 3], [[65664, 65786], 2], [[65787, 65791], 3], [[65792, 65794], 2], [[65795, 65798], 3], [[65799, 65843], 2], [[65844, 65846], 3], [[65847, 65855], 2], [[65856, 65930], 2], [[65931, 65932], 2], [[65933, 65934], 2], [65935, 3], [[65936, 65947], 2], [65948, 2], [[65949, 65951], 3], [65952, 2], [[65953, 65999], 3], [[66e3, 66044], 2], [66045, 2], [[66046, 66175], 3], [[66176, 66204], 2], [[66205, 66207], 3], [[66208, 66256], 2], [[66257, 66271], 3], [66272, 2], [[66273, 66299], 2], [[66300, 66303], 3], [[66304, 66334], 2], [66335, 2], [[66336, 66339], 2], [[66340, 66348], 3], [[66349, 66351], 2], [[66352, 66368], 2], [66369, 2], [[66370, 66377], 2], [66378, 2], [[66379, 66383], 3], [[66384, 66426], 2], [[66427, 66431], 3], [[66432, 66461], 2], [66462, 3], [66463, 2], [[66464, 66499], 2], [[66500, 66503], 3], [[66504, 66511], 2], [[66512, 66517], 2], [[66518, 66559], 3], [66560, 1, "\u{10428}"], [66561, 1, "\u{10429}"], [66562, 1, "\u{1042A}"], [66563, 1, "\u{1042B}"], [66564, 1, "\u{1042C}"], [66565, 1, "\u{1042D}"], [66566, 1, "\u{1042E}"], [66567, 1, "\u{1042F}"], [66568, 1, "\u{10430}"], [66569, 1, "\u{10431}"], [66570, 1, "\u{10432}"], [66571, 1, "\u{10433}"], [66572, 1, "\u{10434}"], [66573, 1, "\u{10435}"], [66574, 1, "\u{10436}"], [66575, 1, "\u{10437}"], [66576, 1, "\u{10438}"], [66577, 1, "\u{10439}"], [66578, 1, "\u{1043A}"], [66579, 1, "\u{1043B}"], [66580, 1, "\u{1043C}"], [66581, 1, "\u{1043D}"], [66582, 1, "\u{1043E}"], [66583, 1, "\u{1043F}"], [66584, 1, "\u{10440}"], [66585, 1, "\u{10441}"], [66586, 1, "\u{10442}"], [66587, 1, "\u{10443}"], [66588, 1, "\u{10444}"], [66589, 1, "\u{10445}"], [66590, 1, "\u{10446}"], [66591, 1, "\u{10447}"], [66592, 1, "\u{10448}"], [66593, 1, "\u{10449}"], [66594, 1, "\u{1044A}"], [66595, 1, "\u{1044B}"], [66596, 1, "\u{1044C}"], [66597, 1, "\u{1044D}"], [66598, 1, "\u{1044E}"], [66599, 1, "\u{1044F}"], [[66600, 66637], 2], [[66638, 66717], 2], [[66718, 66719], 3], [[66720, 66729], 2], [[66730, 66735], 3], [66736, 1, "\u{104D8}"], [66737, 1, "\u{104D9}"], [66738, 1, "\u{104DA}"], [66739, 1, "\u{104DB}"], [66740, 1, "\u{104DC}"], [66741, 1, "\u{104DD}"], [66742, 1, "\u{104DE}"], [66743, 1, "\u{104DF}"], [66744, 1, "\u{104E0}"], [66745, 1, "\u{104E1}"], [66746, 1, "\u{104E2}"], [66747, 1, "\u{104E3}"], [66748, 1, "\u{104E4}"], [66749, 1, "\u{104E5}"], [66750, 1, "\u{104E6}"], [66751, 1, "\u{104E7}"], [66752, 1, "\u{104E8}"], [66753, 1, "\u{104E9}"], [66754, 1, "\u{104EA}"], [66755, 1, "\u{104EB}"], [66756, 1, "\u{104EC}"], [66757, 1, "\u{104ED}"], [66758, 1, "\u{104EE}"], [66759, 1, "\u{104EF}"], [66760, 1, "\u{104F0}"], [66761, 1, "\u{104F1}"], [66762, 1, "\u{104F2}"], [66763, 1, "\u{104F3}"], [66764, 1, "\u{104F4}"], [66765, 1, "\u{104F5}"], [66766, 1, "\u{104F6}"], [66767, 1, "\u{104F7}"], [66768, 1, "\u{104F8}"], [66769, 1, "\u{104F9}"], [66770, 1, "\u{104FA}"], [66771, 1, "\u{104FB}"], [[66772, 66775], 3], [[66776, 66811], 2], [[66812, 66815], 3], [[66816, 66855], 2], [[66856, 66863], 3], [[66864, 66915], 2], [[66916, 66926], 3], [66927, 2], [66928, 1, "\u{10597}"], [66929, 1, "\u{10598}"], [66930, 1, "\u{10599}"], [66931, 1, "\u{1059A}"], [66932, 1, "\u{1059B}"], [66933, 1, "\u{1059C}"], [66934, 1, "\u{1059D}"], [66935, 1, "\u{1059E}"], [66936, 1, "\u{1059F}"], [66937, 1, "\u{105A0}"], [66938, 1, "\u{105A1}"], [66939, 3], [66940, 1, "\u{105A3}"], [66941, 1, "\u{105A4}"], [66942, 1, "\u{105A5}"], [66943, 1, "\u{105A6}"], [66944, 1, "\u{105A7}"], [66945, 1, "\u{105A8}"], [66946, 1, "\u{105A9}"], [66947, 1, "\u{105AA}"], [66948, 1, "\u{105AB}"], [66949, 1, "\u{105AC}"], [66950, 1, "\u{105AD}"], [66951, 1, "\u{105AE}"], [66952, 1, "\u{105AF}"], [66953, 1, "\u{105B0}"], [66954, 1, "\u{105B1}"], [66955, 3], [66956, 1, "\u{105B3}"], [66957, 1, "\u{105B4}"], [66958, 1, "\u{105B5}"], [66959, 1, "\u{105B6}"], [66960, 1, "\u{105B7}"], [66961, 1, "\u{105B8}"], [66962, 1, "\u{105B9}"], [66963, 3], [66964, 1, "\u{105BB}"], [66965, 1, "\u{105BC}"], [66966, 3], [[66967, 66977], 2], [66978, 3], [[66979, 66993], 2], [66994, 3], [[66995, 67001], 2], [67002, 3], [[67003, 67004], 2], [[67005, 67007], 3], [[67008, 67059], 2], [[67060, 67071], 3], [[67072, 67382], 2], [[67383, 67391], 3], [[67392, 67413], 2], [[67414, 67423], 3], [[67424, 67431], 2], [[67432, 67455], 3], [67456, 2], [67457, 1, "\u02D0"], [67458, 1, "\u02D1"], [67459, 1, "\xE6"], [67460, 1, "\u0299"], [67461, 1, "\u0253"], [67462, 3], [67463, 1, "\u02A3"], [67464, 1, "\uAB66"], [67465, 1, "\u02A5"], [67466, 1, "\u02A4"], [67467, 1, "\u0256"], [67468, 1, "\u0257"], [67469, 1, "\u1D91"], [67470, 1, "\u0258"], [67471, 1, "\u025E"], [67472, 1, "\u02A9"], [67473, 1, "\u0264"], [67474, 1, "\u0262"], [67475, 1, "\u0260"], [67476, 1, "\u029B"], [67477, 1, "\u0127"], [67478, 1, "\u029C"], [67479, 1, "\u0267"], [67480, 1, "\u0284"], [67481, 1, "\u02AA"], [67482, 1, "\u02AB"], [67483, 1, "\u026C"], [67484, 1, "\u{1DF04}"], [67485, 1, "\uA78E"], [67486, 1, "\u026E"], [67487, 1, "\u{1DF05}"], [67488, 1, "\u028E"], [67489, 1, "\u{1DF06}"], [67490, 1, "\xF8"], [67491, 1, "\u0276"], [67492, 1, "\u0277"], [67493, 1, "q"], [67494, 1, "\u027A"], [67495, 1, "\u{1DF08}"], [67496, 1, "\u027D"], [67497, 1, "\u027E"], [67498, 1, "\u0280"], [67499, 1, "\u02A8"], [67500, 1, "\u02A6"], [67501, 1, "\uAB67"], [67502, 1, "\u02A7"], [67503, 1, "\u0288"], [67504, 1, "\u2C71"], [67505, 3], [67506, 1, "\u028F"], [67507, 1, "\u02A1"], [67508, 1, "\u02A2"], [67509, 1, "\u0298"], [67510, 1, "\u01C0"], [67511, 1, "\u01C1"], [67512, 1, "\u01C2"], [67513, 1, "\u{1DF0A}"], [67514, 1, "\u{1DF1E}"], [[67515, 67583], 3], [[67584, 67589], 2], [[67590, 67591], 3], [67592, 2], [67593, 3], [[67594, 67637], 2], [67638, 3], [[67639, 67640], 2], [[67641, 67643], 3], [67644, 2], [[67645, 67646], 3], [67647, 2], [[67648, 67669], 2], [67670, 3], [[67671, 67679], 2], [[67680, 67702], 2], [[67703, 67711], 2], [[67712, 67742], 2], [[67743, 67750], 3], [[67751, 67759], 2], [[67760, 67807], 3], [[67808, 67826], 2], [67827, 3], [[67828, 67829], 2], [[67830, 67834], 3], [[67835, 67839], 2], [[67840, 67861], 2], [[67862, 67865], 2], [[67866, 67867], 2], [[67868, 67870], 3], [67871, 2], [[67872, 67897], 2], [[67898, 67902], 3], [67903, 2], [[67904, 67967], 3], [[67968, 68023], 2], [[68024, 68027], 3], [[68028, 68029], 2], [[68030, 68031], 2], [[68032, 68047], 2], [[68048, 68049], 3], [[68050, 68095], 2], [[68096, 68099], 2], [68100, 3], [[68101, 68102], 2], [[68103, 68107], 3], [[68108, 68115], 2], [68116, 3], [[68117, 68119], 2], [68120, 3], [[68121, 68147], 2], [[68148, 68149], 2], [[68150, 68151], 3], [[68152, 68154], 2], [[68155, 68158], 3], [68159, 2], [[68160, 68167], 2], [68168, 2], [[68169, 68175], 3], [[68176, 68184], 2], [[68185, 68191], 3], [[68192, 68220], 2], [[68221, 68223], 2], [[68224, 68252], 2], [[68253, 68255], 2], [[68256, 68287], 3], [[68288, 68295], 2], [68296, 2], [[68297, 68326], 2], [[68327, 68330], 3], [[68331, 68342], 2], [[68343, 68351], 3], [[68352, 68405], 2], [[68406, 68408], 3], [[68409, 68415], 2], [[68416, 68437], 2], [[68438, 68439], 3], [[68440, 68447], 2], [[68448, 68466], 2], [[68467, 68471], 3], [[68472, 68479], 2], [[68480, 68497], 2], [[68498, 68504], 3], [[68505, 68508], 2], [[68509, 68520], 3], [[68521, 68527], 2], [[68528, 68607], 3], [[68608, 68680], 2], [[68681, 68735], 3], [68736, 1, "\u{10CC0}"], [68737, 1, "\u{10CC1}"], [68738, 1, "\u{10CC2}"], [68739, 1, "\u{10CC3}"], [68740, 1, "\u{10CC4}"], [68741, 1, "\u{10CC5}"], [68742, 1, "\u{10CC6}"], [68743, 1, "\u{10CC7}"], [68744, 1, "\u{10CC8}"], [68745, 1, "\u{10CC9}"], [68746, 1, "\u{10CCA}"], [68747, 1, "\u{10CCB}"], [68748, 1, "\u{10CCC}"], [68749, 1, "\u{10CCD}"], [68750, 1, "\u{10CCE}"], [68751, 1, "\u{10CCF}"], [68752, 1, "\u{10CD0}"], [68753, 1, "\u{10CD1}"], [68754, 1, "\u{10CD2}"], [68755, 1, "\u{10CD3}"], [68756, 1, "\u{10CD4}"], [68757, 1, "\u{10CD5}"], [68758, 1, "\u{10CD6}"], [68759, 1, "\u{10CD7}"], [68760, 1, "\u{10CD8}"], [68761, 1, "\u{10CD9}"], [68762, 1, "\u{10CDA}"], [68763, 1, "\u{10CDB}"], [68764, 1, "\u{10CDC}"], [68765, 1, "\u{10CDD}"], [68766, 1, "\u{10CDE}"], [68767, 1, "\u{10CDF}"], [68768, 1, "\u{10CE0}"], [68769, 1, "\u{10CE1}"], [68770, 1, "\u{10CE2}"], [68771, 1, "\u{10CE3}"], [68772, 1, "\u{10CE4}"], [68773, 1, "\u{10CE5}"], [68774, 1, "\u{10CE6}"], [68775, 1, "\u{10CE7}"], [68776, 1, "\u{10CE8}"], [68777, 1, "\u{10CE9}"], [68778, 1, "\u{10CEA}"], [68779, 1, "\u{10CEB}"], [68780, 1, "\u{10CEC}"], [68781, 1, "\u{10CED}"], [68782, 1, "\u{10CEE}"], [68783, 1, "\u{10CEF}"], [68784, 1, "\u{10CF0}"], [68785, 1, "\u{10CF1}"], [68786, 1, "\u{10CF2}"], [[68787, 68799], 3], [[68800, 68850], 2], [[68851, 68857], 3], [[68858, 68863], 2], [[68864, 68903], 2], [[68904, 68911], 3], [[68912, 68921], 2], [[68922, 68927], 3], [[68928, 68943], 2], [68944, 1, "\u{10D70}"], [68945, 1, "\u{10D71}"], [68946, 1, "\u{10D72}"], [68947, 1, "\u{10D73}"], [68948, 1, "\u{10D74}"], [68949, 1, "\u{10D75}"], [68950, 1, "\u{10D76}"], [68951, 1, "\u{10D77}"], [68952, 1, "\u{10D78}"], [68953, 1, "\u{10D79}"], [68954, 1, "\u{10D7A}"], [68955, 1, "\u{10D7B}"], [68956, 1, "\u{10D7C}"], [68957, 1, "\u{10D7D}"], [68958, 1, "\u{10D7E}"], [68959, 1, "\u{10D7F}"], [68960, 1, "\u{10D80}"], [68961, 1, "\u{10D81}"], [68962, 1, "\u{10D82}"], [68963, 1, "\u{10D83}"], [68964, 1, "\u{10D84}"], [68965, 1, "\u{10D85}"], [[68966, 68968], 3], [[68969, 68973], 2], [68974, 2], [[68975, 68997], 2], [[68998, 69005], 3], [[69006, 69007], 2], [[69008, 69215], 3], [[69216, 69246], 2], [69247, 3], [[69248, 69289], 2], [69290, 3], [[69291, 69292], 2], [69293, 2], [[69294, 69295], 3], [[69296, 69297], 2], [[69298, 69313], 3], [[69314, 69316], 2], [[69317, 69371], 3], [69372, 2], [[69373, 69375], 2], [[69376, 69404], 2], [[69405, 69414], 2], [69415, 2], [[69416, 69423], 3], [[69424, 69456], 2], [[69457, 69465], 2], [[69466, 69487], 3], [[69488, 69509], 2], [[69510, 69513], 2], [[69514, 69551], 3], [[69552, 69572], 2], [[69573, 69579], 2], [[69580, 69599], 3], [[69600, 69622], 2], [[69623, 69631], 3], [[69632, 69702], 2], [[69703, 69709], 2], [[69710, 69713], 3], [[69714, 69733], 2], [[69734, 69743], 2], [[69744, 69749], 2], [[69750, 69758], 3], [69759, 2], [[69760, 69818], 2], [[69819, 69820], 2], [69821, 3], [[69822, 69825], 2], [69826, 2], [[69827, 69836], 3], [69837, 3], [[69838, 69839], 3], [[69840, 69864], 2], [[69865, 69871], 3], [[69872, 69881], 2], [[69882, 69887], 3], [[69888, 69940], 2], [69941, 3], [[69942, 69951], 2], [[69952, 69955], 2], [[69956, 69958], 2], [69959, 2], [[69960, 69967], 3], [[69968, 70003], 2], [[70004, 70005], 2], [70006, 2], [[70007, 70015], 3], [[70016, 70084], 2], [[70085, 70088], 2], [[70089, 70092], 2], [70093, 2], [[70094, 70095], 2], [[70096, 70105], 2], [70106, 2], [70107, 2], [70108, 2], [[70109, 70111], 2], [70112, 3], [[70113, 70132], 2], [[70133, 70143], 3], [[70144, 70161], 2], [70162, 3], [[70163, 70199], 2], [[70200, 70205], 2], [70206, 2], [[70207, 70209], 2], [[70210, 70271], 3], [[70272, 70278], 2], [70279, 3], [70280, 2], [70281, 3], [[70282, 70285], 2], [70286, 3], [[70287, 70301], 2], [70302, 3], [[70303, 70312], 2], [70313, 2], [[70314, 70319], 3], [[70320, 70378], 2], [[70379, 70383], 3], [[70384, 70393], 2], [[70394, 70399], 3], [70400, 2], [[70401, 70403], 2], [70404, 3], [[70405, 70412], 2], [[70413, 70414], 3], [[70415, 70416], 2], [[70417, 70418], 3], [[70419, 70440], 2], [70441, 3], [[70442, 70448], 2], [70449, 3], [[70450, 70451], 2], [70452, 3], [[70453, 70457], 2], [70458, 3], [70459, 2], [[70460, 70468], 2], [[70469, 70470], 3], [[70471, 70472], 2], [[70473, 70474], 3], [[70475, 70477], 2], [[70478, 70479], 3], [70480, 2], [[70481, 70486], 3], [70487, 2], [[70488, 70492], 3], [[70493, 70499], 2], [[70500, 70501], 3], [[70502, 70508], 2], [[70509, 70511], 3], [[70512, 70516], 2], [[70517, 70527], 3], [[70528, 70537], 2], [70538, 3], [70539, 2], [[70540, 70541], 3], [70542, 2], [70543, 3], [[70544, 70581], 2], [70582, 3], [[70583, 70592], 2], [70593, 3], [70594, 2], [[70595, 70596], 3], [70597, 2], [70598, 3], [[70599, 70602], 2], [70603, 3], [[70604, 70611], 2], [[70612, 70613], 2], [70614, 3], [[70615, 70616], 2], [[70617, 70624], 3], [[70625, 70626], 2], [[70627, 70655], 3], [[70656, 70730], 2], [[70731, 70735], 2], [[70736, 70745], 2], [70746, 2], [70747, 2], [70748, 3], [70749, 2], [70750, 2], [70751, 2], [[70752, 70753], 2], [[70754, 70783], 3], [[70784, 70853], 2], [70854, 2], [70855, 2], [[70856, 70863], 3], [[70864, 70873], 2], [[70874, 71039], 3], [[71040, 71093], 2], [[71094, 71095], 3], [[71096, 71104], 2], [[71105, 71113], 2], [[71114, 71127], 2], [[71128, 71133], 2], [[71134, 71167], 3], [[71168, 71232], 2], [[71233, 71235], 2], [71236, 2], [[71237, 71247], 3], [[71248, 71257], 2], [[71258, 71263], 3], [[71264, 71276], 2], [[71277, 71295], 3], [[71296, 71351], 2], [71352, 2], [71353, 2], [[71354, 71359], 3], [[71360, 71369], 2], [[71370, 71375], 3], [[71376, 71395], 2], [[71396, 71423], 3], [[71424, 71449], 2], [71450, 2], [[71451, 71452], 3], [[71453, 71467], 2], [[71468, 71471], 3], [[71472, 71481], 2], [[71482, 71487], 2], [[71488, 71494], 2], [[71495, 71679], 3], [[71680, 71738], 2], [71739, 2], [[71740, 71839], 3], [71840, 1, "\u{118C0}"], [71841, 1, "\u{118C1}"], [71842, 1, "\u{118C2}"], [71843, 1, "\u{118C3}"], [71844, 1, "\u{118C4}"], [71845, 1, "\u{118C5}"], [71846, 1, "\u{118C6}"], [71847, 1, "\u{118C7}"], [71848, 1, "\u{118C8}"], [71849, 1, "\u{118C9}"], [71850, 1, "\u{118CA}"], [71851, 1, "\u{118CB}"], [71852, 1, "\u{118CC}"], [71853, 1, "\u{118CD}"], [71854, 1, "\u{118CE}"], [71855, 1, "\u{118CF}"], [71856, 1, "\u{118D0}"], [71857, 1, "\u{118D1}"], [71858, 1, "\u{118D2}"], [71859, 1, "\u{118D3}"], [71860, 1, "\u{118D4}"], [71861, 1, "\u{118D5}"], [71862, 1, "\u{118D6}"], [71863, 1, "\u{118D7}"], [71864, 1, "\u{118D8}"], [71865, 1, "\u{118D9}"], [71866, 1, "\u{118DA}"], [71867, 1, "\u{118DB}"], [71868, 1, "\u{118DC}"], [71869, 1, "\u{118DD}"], [71870, 1, "\u{118DE}"], [71871, 1, "\u{118DF}"], [[71872, 71913], 2], [[71914, 71922], 2], [[71923, 71934], 3], [71935, 2], [[71936, 71942], 2], [[71943, 71944], 3], [71945, 2], [[71946, 71947], 3], [[71948, 71955], 2], [71956, 3], [[71957, 71958], 2], [71959, 3], [[71960, 71989], 2], [71990, 3], [[71991, 71992], 2], [[71993, 71994], 3], [[71995, 72003], 2], [[72004, 72006], 2], [[72007, 72015], 3], [[72016, 72025], 2], [[72026, 72095], 3], [[72096, 72103], 2], [[72104, 72105], 3], [[72106, 72151], 2], [[72152, 72153], 3], [[72154, 72161], 2], [72162, 2], [[72163, 72164], 2], [[72165, 72191], 3], [[72192, 72254], 2], [[72255, 72262], 2], [72263, 2], [[72264, 72271], 3], [[72272, 72323], 2], [[72324, 72325], 2], [[72326, 72345], 2], [[72346, 72348], 2], [72349, 2], [[72350, 72354], 2], [[72355, 72367], 3], [[72368, 72383], 2], [[72384, 72440], 2], [[72441, 72447], 3], [[72448, 72457], 2], [[72458, 72639], 3], [[72640, 72672], 2], [72673, 2], [[72674, 72687], 3], [[72688, 72697], 2], [[72698, 72703], 3], [[72704, 72712], 2], [72713, 3], [[72714, 72758], 2], [72759, 3], [[72760, 72768], 2], [[72769, 72773], 2], [[72774, 72783], 3], [[72784, 72793], 2], [[72794, 72812], 2], [[72813, 72815], 3], [[72816, 72817], 2], [[72818, 72847], 2], [[72848, 72849], 3], [[72850, 72871], 2], [72872, 3], [[72873, 72886], 2], [[72887, 72959], 3], [[72960, 72966], 2], [72967, 3], [[72968, 72969], 2], [72970, 3], [[72971, 73014], 2], [[73015, 73017], 3], [73018, 2], [73019, 3], [[73020, 73021], 2], [73022, 3], [[73023, 73031], 2], [[73032, 73039], 3], [[73040, 73049], 2], [[73050, 73055], 3], [[73056, 73061], 2], [73062, 3], [[73063, 73064], 2], [73065, 3], [[73066, 73102], 2], [73103, 3], [[73104, 73105], 2], [73106, 3], [[73107, 73112], 2], [[73113, 73119], 3], [[73120, 73129], 2], [[73130, 73439], 3], [[73440, 73462], 2], [[73463, 73464], 2], [[73465, 73471], 3], [[73472, 73488], 2], [73489, 3], [[73490, 73530], 2], [[73531, 73533], 3], [[73534, 73538], 2], [[73539, 73551], 2], [[73552, 73561], 2], [73562, 2], [[73563, 73647], 3], [73648, 2], [[73649, 73663], 3], [[73664, 73713], 2], [[73714, 73726], 3], [73727, 2], [[73728, 74606], 2], [[74607, 74648], 2], [74649, 2], [[74650, 74751], 3], [[74752, 74850], 2], [[74851, 74862], 2], [74863, 3], [[74864, 74867], 2], [74868, 2], [[74869, 74879], 3], [[74880, 75075], 2], [[75076, 77711], 3], [[77712, 77808], 2], [[77809, 77810], 2], [[77811, 77823], 3], [[77824, 78894], 2], [78895, 2], [[78896, 78904], 3], [[78905, 78911], 3], [[78912, 78933], 2], [[78934, 78943], 3], [[78944, 82938], 2], [[82939, 82943], 3], [[82944, 83526], 2], [[83527, 90367], 3], [[90368, 90425], 2], [[90426, 92159], 3], [[92160, 92728], 2], [[92729, 92735], 3], [[92736, 92766], 2], [92767, 3], [[92768, 92777], 2], [[92778, 92781], 3], [[92782, 92783], 2], [[92784, 92862], 2], [92863, 3], [[92864, 92873], 2], [[92874, 92879], 3], [[92880, 92909], 2], [[92910, 92911], 3], [[92912, 92916], 2], [92917, 2], [[92918, 92927], 3], [[92928, 92982], 2], [[92983, 92991], 2], [[92992, 92995], 2], [[92996, 92997], 2], [[92998, 93007], 3], [[93008, 93017], 2], [93018, 3], [[93019, 93025], 2], [93026, 3], [[93027, 93047], 2], [[93048, 93052], 3], [[93053, 93071], 2], [[93072, 93503], 3], [[93504, 93548], 2], [[93549, 93551], 2], [[93552, 93561], 2], [[93562, 93759], 3], [93760, 1, "\u{16E60}"], [93761, 1, "\u{16E61}"], [93762, 1, "\u{16E62}"], [93763, 1, "\u{16E63}"], [93764, 1, "\u{16E64}"], [93765, 1, "\u{16E65}"], [93766, 1, "\u{16E66}"], [93767, 1, "\u{16E67}"], [93768, 1, "\u{16E68}"], [93769, 1, "\u{16E69}"], [93770, 1, "\u{16E6A}"], [93771, 1, "\u{16E6B}"], [93772, 1, "\u{16E6C}"], [93773, 1, "\u{16E6D}"], [93774, 1, "\u{16E6E}"], [93775, 1, "\u{16E6F}"], [93776, 1, "\u{16E70}"], [93777, 1, "\u{16E71}"], [93778, 1, "\u{16E72}"], [93779, 1, "\u{16E73}"], [93780, 1, "\u{16E74}"], [93781, 1, "\u{16E75}"], [93782, 1, "\u{16E76}"], [93783, 1, "\u{16E77}"], [93784, 1, "\u{16E78}"], [93785, 1, "\u{16E79}"], [93786, 1, "\u{16E7A}"], [93787, 1, "\u{16E7B}"], [93788, 1, "\u{16E7C}"], [93789, 1, "\u{16E7D}"], [93790, 1, "\u{16E7E}"], [93791, 1, "\u{16E7F}"], [[93792, 93823], 2], [[93824, 93850], 2], [[93851, 93951], 3], [[93952, 94020], 2], [[94021, 94026], 2], [[94027, 94030], 3], [94031, 2], [[94032, 94078], 2], [[94079, 94087], 2], [[94088, 94094], 3], [[94095, 94111], 2], [[94112, 94175], 3], [94176, 2], [94177, 2], [94178, 2], [94179, 2], [94180, 2], [[94181, 94191], 3], [[94192, 94193], 2], [[94194, 94207], 3], [[94208, 100332], 2], [[100333, 100337], 2], [[100338, 100343], 2], [[100344, 100351], 3], [[100352, 101106], 2], [[101107, 101589], 2], [[101590, 101630], 3], [101631, 2], [[101632, 101640], 2], [[101641, 110575], 3], [[110576, 110579], 2], [110580, 3], [[110581, 110587], 2], [110588, 3], [[110589, 110590], 2], [110591, 3], [[110592, 110593], 2], [[110594, 110878], 2], [[110879, 110882], 2], [[110883, 110897], 3], [110898, 2], [[110899, 110927], 3], [[110928, 110930], 2], [[110931, 110932], 3], [110933, 2], [[110934, 110947], 3], [[110948, 110951], 2], [[110952, 110959], 3], [[110960, 111355], 2], [[111356, 113663], 3], [[113664, 113770], 2], [[113771, 113775], 3], [[113776, 113788], 2], [[113789, 113791], 3], [[113792, 113800], 2], [[113801, 113807], 3], [[113808, 113817], 2], [[113818, 113819], 3], [113820, 2], [[113821, 113822], 2], [113823, 2], [[113824, 113827], 7], [[113828, 117759], 3], [[117760, 117973], 2], [117974, 1, "a"], [117975, 1, "b"], [117976, 1, "c"], [117977, 1, "d"], [117978, 1, "e"], [117979, 1, "f"], [117980, 1, "g"], [117981, 1, "h"], [117982, 1, "i"], [117983, 1, "j"], [117984, 1, "k"], [117985, 1, "l"], [117986, 1, "m"], [117987, 1, "n"], [117988, 1, "o"], [117989, 1, "p"], [117990, 1, "q"], [117991, 1, "r"], [117992, 1, "s"], [117993, 1, "t"], [117994, 1, "u"], [117995, 1, "v"], [117996, 1, "w"], [117997, 1, "x"], [117998, 1, "y"], [117999, 1, "z"], [118e3, 1, "0"], [118001, 1, "1"], [118002, 1, "2"], [118003, 1, "3"], [118004, 1, "4"], [118005, 1, "5"], [118006, 1, "6"], [118007, 1, "7"], [118008, 1, "8"], [118009, 1, "9"], [[118010, 118015], 3], [[118016, 118451], 2], [[118452, 118527], 3], [[118528, 118573], 2], [[118574, 118575], 3], [[118576, 118598], 2], [[118599, 118607], 3], [[118608, 118723], 2], [[118724, 118783], 3], [[118784, 119029], 2], [[119030, 119039], 3], [[119040, 119078], 2], [[119079, 119080], 3], [119081, 2], [[119082, 119133], 2], [119134, 1, "\u{1D157}\u{1D165}"], [119135, 1, "\u{1D158}\u{1D165}"], [119136, 1, "\u{1D158}\u{1D165}\u{1D16E}"], [119137, 1, "\u{1D158}\u{1D165}\u{1D16F}"], [119138, 1, "\u{1D158}\u{1D165}\u{1D170}"], [119139, 1, "\u{1D158}\u{1D165}\u{1D171}"], [119140, 1, "\u{1D158}\u{1D165}\u{1D172}"], [[119141, 119154], 2], [[119155, 119162], 7], [[119163, 119226], 2], [119227, 1, "\u{1D1B9}\u{1D165}"], [119228, 1, "\u{1D1BA}\u{1D165}"], [119229, 1, "\u{1D1B9}\u{1D165}\u{1D16E}"], [119230, 1, "\u{1D1BA}\u{1D165}\u{1D16E}"], [119231, 1, "\u{1D1B9}\u{1D165}\u{1D16F}"], [119232, 1, "\u{1D1BA}\u{1D165}\u{1D16F}"], [[119233, 119261], 2], [[119262, 119272], 2], [[119273, 119274], 2], [[119275, 119295], 3], [[119296, 119365], 2], [[119366, 119487], 3], [[119488, 119507], 2], [[119508, 119519], 3], [[119520, 119539], 2], [[119540, 119551], 3], [[119552, 119638], 2], [[119639, 119647], 3], [[119648, 119665], 2], [[119666, 119672], 2], [[119673, 119807], 3], [119808, 1, "a"], [119809, 1, "b"], [119810, 1, "c"], [119811, 1, "d"], [119812, 1, "e"], [119813, 1, "f"], [119814, 1, "g"], [119815, 1, "h"], [119816, 1, "i"], [119817, 1, "j"], [119818, 1, "k"], [119819, 1, "l"], [119820, 1, "m"], [119821, 1, "n"], [119822, 1, "o"], [119823, 1, "p"], [119824, 1, "q"], [119825, 1, "r"], [119826, 1, "s"], [119827, 1, "t"], [119828, 1, "u"], [119829, 1, "v"], [119830, 1, "w"], [119831, 1, "x"], [119832, 1, "y"], [119833, 1, "z"], [119834, 1, "a"], [119835, 1, "b"], [119836, 1, "c"], [119837, 1, "d"], [119838, 1, "e"], [119839, 1, "f"], [119840, 1, "g"], [119841, 1, "h"], [119842, 1, "i"], [119843, 1, "j"], [119844, 1, "k"], [119845, 1, "l"], [119846, 1, "m"], [119847, 1, "n"], [119848, 1, "o"], [119849, 1, "p"], [119850, 1, "q"], [119851, 1, "r"], [119852, 1, "s"], [119853, 1, "t"], [119854, 1, "u"], [119855, 1, "v"], [119856, 1, "w"], [119857, 1, "x"], [119858, 1, "y"], [119859, 1, "z"], [119860, 1, "a"], [119861, 1, "b"], [119862, 1, "c"], [119863, 1, "d"], [119864, 1, "e"], [119865, 1, "f"], [119866, 1, "g"], [119867, 1, "h"], [119868, 1, "i"], [119869, 1, "j"], [119870, 1, "k"], [119871, 1, "l"], [119872, 1, "m"], [119873, 1, "n"], [119874, 1, "o"], [119875, 1, "p"], [119876, 1, "q"], [119877, 1, "r"], [119878, 1, "s"], [119879, 1, "t"], [119880, 1, "u"], [119881, 1, "v"], [119882, 1, "w"], [119883, 1, "x"], [119884, 1, "y"], [119885, 1, "z"], [119886, 1, "a"], [119887, 1, "b"], [119888, 1, "c"], [119889, 1, "d"], [119890, 1, "e"], [119891, 1, "f"], [119892, 1, "g"], [119893, 3], [119894, 1, "i"], [119895, 1, "j"], [119896, 1, "k"], [119897, 1, "l"], [119898, 1, "m"], [119899, 1, "n"], [119900, 1, "o"], [119901, 1, "p"], [119902, 1, "q"], [119903, 1, "r"], [119904, 1, "s"], [119905, 1, "t"], [119906, 1, "u"], [119907, 1, "v"], [119908, 1, "w"], [119909, 1, "x"], [119910, 1, "y"], [119911, 1, "z"], [119912, 1, "a"], [119913, 1, "b"], [119914, 1, "c"], [119915, 1, "d"], [119916, 1, "e"], [119917, 1, "f"], [119918, 1, "g"], [119919, 1, "h"], [119920, 1, "i"], [119921, 1, "j"], [119922, 1, "k"], [119923, 1, "l"], [119924, 1, "m"], [119925, 1, "n"], [119926, 1, "o"], [119927, 1, "p"], [119928, 1, "q"], [119929, 1, "r"], [119930, 1, "s"], [119931, 1, "t"], [119932, 1, "u"], [119933, 1, "v"], [119934, 1, "w"], [119935, 1, "x"], [119936, 1, "y"], [119937, 1, "z"], [119938, 1, "a"], [119939, 1, "b"], [119940, 1, "c"], [119941, 1, "d"], [119942, 1, "e"], [119943, 1, "f"], [119944, 1, "g"], [119945, 1, "h"], [119946, 1, "i"], [119947, 1, "j"], [119948, 1, "k"], [119949, 1, "l"], [119950, 1, "m"], [119951, 1, "n"], [119952, 1, "o"], [119953, 1, "p"], [119954, 1, "q"], [119955, 1, "r"], [119956, 1, "s"], [119957, 1, "t"], [119958, 1, "u"], [119959, 1, "v"], [119960, 1, "w"], [119961, 1, "x"], [119962, 1, "y"], [119963, 1, "z"], [119964, 1, "a"], [119965, 3], [119966, 1, "c"], [119967, 1, "d"], [[119968, 119969], 3], [119970, 1, "g"], [[119971, 119972], 3], [119973, 1, "j"], [119974, 1, "k"], [[119975, 119976], 3], [119977, 1, "n"], [119978, 1, "o"], [119979, 1, "p"], [119980, 1, "q"], [119981, 3], [119982, 1, "s"], [119983, 1, "t"], [119984, 1, "u"], [119985, 1, "v"], [119986, 1, "w"], [119987, 1, "x"], [119988, 1, "y"], [119989, 1, "z"], [119990, 1, "a"], [119991, 1, "b"], [119992, 1, "c"], [119993, 1, "d"], [119994, 3], [119995, 1, "f"], [119996, 3], [119997, 1, "h"], [119998, 1, "i"], [119999, 1, "j"], [12e4, 1, "k"], [120001, 1, "l"], [120002, 1, "m"], [120003, 1, "n"], [120004, 3], [120005, 1, "p"], [120006, 1, "q"], [120007, 1, "r"], [120008, 1, "s"], [120009, 1, "t"], [120010, 1, "u"], [120011, 1, "v"], [120012, 1, "w"], [120013, 1, "x"], [120014, 1, "y"], [120015, 1, "z"], [120016, 1, "a"], [120017, 1, "b"], [120018, 1, "c"], [120019, 1, "d"], [120020, 1, "e"], [120021, 1, "f"], [120022, 1, "g"], [120023, 1, "h"], [120024, 1, "i"], [120025, 1, "j"], [120026, 1, "k"], [120027, 1, "l"], [120028, 1, "m"], [120029, 1, "n"], [120030, 1, "o"], [120031, 1, "p"], [120032, 1, "q"], [120033, 1, "r"], [120034, 1, "s"], [120035, 1, "t"], [120036, 1, "u"], [120037, 1, "v"], [120038, 1, "w"], [120039, 1, "x"], [120040, 1, "y"], [120041, 1, "z"], [120042, 1, "a"], [120043, 1, "b"], [120044, 1, "c"], [120045, 1, "d"], [120046, 1, "e"], [120047, 1, "f"], [120048, 1, "g"], [120049, 1, "h"], [120050, 1, "i"], [120051, 1, "j"], [120052, 1, "k"], [120053, 1, "l"], [120054, 1, "m"], [120055, 1, "n"], [120056, 1, "o"], [120057, 1, "p"], [120058, 1, "q"], [120059, 1, "r"], [120060, 1, "s"], [120061, 1, "t"], [120062, 1, "u"], [120063, 1, "v"], [120064, 1, "w"], [120065, 1, "x"], [120066, 1, "y"], [120067, 1, "z"], [120068, 1, "a"], [120069, 1, "b"], [120070, 3], [120071, 1, "d"], [120072, 1, "e"], [120073, 1, "f"], [120074, 1, "g"], [[120075, 120076], 3], [120077, 1, "j"], [120078, 1, "k"], [120079, 1, "l"], [120080, 1, "m"], [120081, 1, "n"], [120082, 1, "o"], [120083, 1, "p"], [120084, 1, "q"], [120085, 3], [120086, 1, "s"], [120087, 1, "t"], [120088, 1, "u"], [120089, 1, "v"], [120090, 1, "w"], [120091, 1, "x"], [120092, 1, "y"], [120093, 3], [120094, 1, "a"], [120095, 1, "b"], [120096, 1, "c"], [120097, 1, "d"], [120098, 1, "e"], [120099, 1, "f"], [120100, 1, "g"], [120101, 1, "h"], [120102, 1, "i"], [120103, 1, "j"], [120104, 1, "k"], [120105, 1, "l"], [120106, 1, "m"], [120107, 1, "n"], [120108, 1, "o"], [120109, 1, "p"], [120110, 1, "q"], [120111, 1, "r"], [120112, 1, "s"], [120113, 1, "t"], [120114, 1, "u"], [120115, 1, "v"], [120116, 1, "w"], [120117, 1, "x"], [120118, 1, "y"], [120119, 1, "z"], [120120, 1, "a"], [120121, 1, "b"], [120122, 3], [120123, 1, "d"], [120124, 1, "e"], [120125, 1, "f"], [120126, 1, "g"], [120127, 3], [120128, 1, "i"], [120129, 1, "j"], [120130, 1, "k"], [120131, 1, "l"], [120132, 1, "m"], [120133, 3], [120134, 1, "o"], [[120135, 120137], 3], [120138, 1, "s"], [120139, 1, "t"], [120140, 1, "u"], [120141, 1, "v"], [120142, 1, "w"], [120143, 1, "x"], [120144, 1, "y"], [120145, 3], [120146, 1, "a"], [120147, 1, "b"], [120148, 1, "c"], [120149, 1, "d"], [120150, 1, "e"], [120151, 1, "f"], [120152, 1, "g"], [120153, 1, "h"], [120154, 1, "i"], [120155, 1, "j"], [120156, 1, "k"], [120157, 1, "l"], [120158, 1, "m"], [120159, 1, "n"], [120160, 1, "o"], [120161, 1, "p"], [120162, 1, "q"], [120163, 1, "r"], [120164, 1, "s"], [120165, 1, "t"], [120166, 1, "u"], [120167, 1, "v"], [120168, 1, "w"], [120169, 1, "x"], [120170, 1, "y"], [120171, 1, "z"], [120172, 1, "a"], [120173, 1, "b"], [120174, 1, "c"], [120175, 1, "d"], [120176, 1, "e"], [120177, 1, "f"], [120178, 1, "g"], [120179, 1, "h"], [120180, 1, "i"], [120181, 1, "j"], [120182, 1, "k"], [120183, 1, "l"], [120184, 1, "m"], [120185, 1, "n"], [120186, 1, "o"], [120187, 1, "p"], [120188, 1, "q"], [120189, 1, "r"], [120190, 1, "s"], [120191, 1, "t"], [120192, 1, "u"], [120193, 1, "v"], [120194, 1, "w"], [120195, 1, "x"], [120196, 1, "y"], [120197, 1, "z"], [120198, 1, "a"], [120199, 1, "b"], [120200, 1, "c"], [120201, 1, "d"], [120202, 1, "e"], [120203, 1, "f"], [120204, 1, "g"], [120205, 1, "h"], [120206, 1, "i"], [120207, 1, "j"], [120208, 1, "k"], [120209, 1, "l"], [120210, 1, "m"], [120211, 1, "n"], [120212, 1, "o"], [120213, 1, "p"], [120214, 1, "q"], [120215, 1, "r"], [120216, 1, "s"], [120217, 1, "t"], [120218, 1, "u"], [120219, 1, "v"], [120220, 1, "w"], [120221, 1, "x"], [120222, 1, "y"], [120223, 1, "z"], [120224, 1, "a"], [120225, 1, "b"], [120226, 1, "c"], [120227, 1, "d"], [120228, 1, "e"], [120229, 1, "f"], [120230, 1, "g"], [120231, 1, "h"], [120232, 1, "i"], [120233, 1, "j"], [120234, 1, "k"], [120235, 1, "l"], [120236, 1, "m"], [120237, 1, "n"], [120238, 1, "o"], [120239, 1, "p"], [120240, 1, "q"], [120241, 1, "r"], [120242, 1, "s"], [120243, 1, "t"], [120244, 1, "u"], [120245, 1, "v"], [120246, 1, "w"], [120247, 1, "x"], [120248, 1, "y"], [120249, 1, "z"], [120250, 1, "a"], [120251, 1, "b"], [120252, 1, "c"], [120253, 1, "d"], [120254, 1, "e"], [120255, 1, "f"], [120256, 1, "g"], [120257, 1, "h"], [120258, 1, "i"], [120259, 1, "j"], [120260, 1, "k"], [120261, 1, "l"], [120262, 1, "m"], [120263, 1, "n"], [120264, 1, "o"], [120265, 1, "p"], [120266, 1, "q"], [120267, 1, "r"], [120268, 1, "s"], [120269, 1, "t"], [120270, 1, "u"], [120271, 1, "v"], [120272, 1, "w"], [120273, 1, "x"], [120274, 1, "y"], [120275, 1, "z"], [120276, 1, "a"], [120277, 1, "b"], [120278, 1, "c"], [120279, 1, "d"], [120280, 1, "e"], [120281, 1, "f"], [120282, 1, "g"], [120283, 1, "h"], [120284, 1, "i"], [120285, 1, "j"], [120286, 1, "k"], [120287, 1, "l"], [120288, 1, "m"], [120289, 1, "n"], [120290, 1, "o"], [120291, 1, "p"], [120292, 1, "q"], [120293, 1, "r"], [120294, 1, "s"], [120295, 1, "t"], [120296, 1, "u"], [120297, 1, "v"], [120298, 1, "w"], [120299, 1, "x"], [120300, 1, "y"], [120301, 1, "z"], [120302, 1, "a"], [120303, 1, "b"], [120304, 1, "c"], [120305, 1, "d"], [120306, 1, "e"], [120307, 1, "f"], [120308, 1, "g"], [120309, 1, "h"], [120310, 1, "i"], [120311, 1, "j"], [120312, 1, "k"], [120313, 1, "l"], [120314, 1, "m"], [120315, 1, "n"], [120316, 1, "o"], [120317, 1, "p"], [120318, 1, "q"], [120319, 1, "r"], [120320, 1, "s"], [120321, 1, "t"], [120322, 1, "u"], [120323, 1, "v"], [120324, 1, "w"], [120325, 1, "x"], [120326, 1, "y"], [120327, 1, "z"], [120328, 1, "a"], [120329, 1, "b"], [120330, 1, "c"], [120331, 1, "d"], [120332, 1, "e"], [120333, 1, "f"], [120334, 1, "g"], [120335, 1, "h"], [120336, 1, "i"], [120337, 1, "j"], [120338, 1, "k"], [120339, 1, "l"], [120340, 1, "m"], [120341, 1, "n"], [120342, 1, "o"], [120343, 1, "p"], [120344, 1, "q"], [120345, 1, "r"], [120346, 1, "s"], [120347, 1, "t"], [120348, 1, "u"], [120349, 1, "v"], [120350, 1, "w"], [120351, 1, "x"], [120352, 1, "y"], [120353, 1, "z"], [120354, 1, "a"], [120355, 1, "b"], [120356, 1, "c"], [120357, 1, "d"], [120358, 1, "e"], [120359, 1, "f"], [120360, 1, "g"], [120361, 1, "h"], [120362, 1, "i"], [120363, 1, "j"], [120364, 1, "k"], [120365, 1, "l"], [120366, 1, "m"], [120367, 1, "n"], [120368, 1, "o"], [120369, 1, "p"], [120370, 1, "q"], [120371, 1, "r"], [120372, 1, "s"], [120373, 1, "t"], [120374, 1, "u"], [120375, 1, "v"], [120376, 1, "w"], [120377, 1, "x"], [120378, 1, "y"], [120379, 1, "z"], [120380, 1, "a"], [120381, 1, "b"], [120382, 1, "c"], [120383, 1, "d"], [120384, 1, "e"], [120385, 1, "f"], [120386, 1, "g"], [120387, 1, "h"], [120388, 1, "i"], [120389, 1, "j"], [120390, 1, "k"], [120391, 1, "l"], [120392, 1, "m"], [120393, 1, "n"], [120394, 1, "o"], [120395, 1, "p"], [120396, 1, "q"], [120397, 1, "r"], [120398, 1, "s"], [120399, 1, "t"], [120400, 1, "u"], [120401, 1, "v"], [120402, 1, "w"], [120403, 1, "x"], [120404, 1, "y"], [120405, 1, "z"], [120406, 1, "a"], [120407, 1, "b"], [120408, 1, "c"], [120409, 1, "d"], [120410, 1, "e"], [120411, 1, "f"], [120412, 1, "g"], [120413, 1, "h"], [120414, 1, "i"], [120415, 1, "j"], [120416, 1, "k"], [120417, 1, "l"], [120418, 1, "m"], [120419, 1, "n"], [120420, 1, "o"], [120421, 1, "p"], [120422, 1, "q"], [120423, 1, "r"], [120424, 1, "s"], [120425, 1, "t"], [120426, 1, "u"], [120427, 1, "v"], [120428, 1, "w"], [120429, 1, "x"], [120430, 1, "y"], [120431, 1, "z"], [120432, 1, "a"], [120433, 1, "b"], [120434, 1, "c"], [120435, 1, "d"], [120436, 1, "e"], [120437, 1, "f"], [120438, 1, "g"], [120439, 1, "h"], [120440, 1, "i"], [120441, 1, "j"], [120442, 1, "k"], [120443, 1, "l"], [120444, 1, "m"], [120445, 1, "n"], [120446, 1, "o"], [120447, 1, "p"], [120448, 1, "q"], [120449, 1, "r"], [120450, 1, "s"], [120451, 1, "t"], [120452, 1, "u"], [120453, 1, "v"], [120454, 1, "w"], [120455, 1, "x"], [120456, 1, "y"], [120457, 1, "z"], [120458, 1, "a"], [120459, 1, "b"], [120460, 1, "c"], [120461, 1, "d"], [120462, 1, "e"], [120463, 1, "f"], [120464, 1, "g"], [120465, 1, "h"], [120466, 1, "i"], [120467, 1, "j"], [120468, 1, "k"], [120469, 1, "l"], [120470, 1, "m"], [120471, 1, "n"], [120472, 1, "o"], [120473, 1, "p"], [120474, 1, "q"], [120475, 1, "r"], [120476, 1, "s"], [120477, 1, "t"], [120478, 1, "u"], [120479, 1, "v"], [120480, 1, "w"], [120481, 1, "x"], [120482, 1, "y"], [120483, 1, "z"], [120484, 1, "\u0131"], [120485, 1, "\u0237"], [[120486, 120487], 3], [120488, 1, "\u03B1"], [120489, 1, "\u03B2"], [120490, 1, "\u03B3"], [120491, 1, "\u03B4"], [120492, 1, "\u03B5"], [120493, 1, "\u03B6"], [120494, 1, "\u03B7"], [120495, 1, "\u03B8"], [120496, 1, "\u03B9"], [120497, 1, "\u03BA"], [120498, 1, "\u03BB"], [120499, 1, "\u03BC"], [120500, 1, "\u03BD"], [120501, 1, "\u03BE"], [120502, 1, "\u03BF"], [120503, 1, "\u03C0"], [120504, 1, "\u03C1"], [120505, 1, "\u03B8"], [120506, 1, "\u03C3"], [120507, 1, "\u03C4"], [120508, 1, "\u03C5"], [120509, 1, "\u03C6"], [120510, 1, "\u03C7"], [120511, 1, "\u03C8"], [120512, 1, "\u03C9"], [120513, 1, "\u2207"], [120514, 1, "\u03B1"], [120515, 1, "\u03B2"], [120516, 1, "\u03B3"], [120517, 1, "\u03B4"], [120518, 1, "\u03B5"], [120519, 1, "\u03B6"], [120520, 1, "\u03B7"], [120521, 1, "\u03B8"], [120522, 1, "\u03B9"], [120523, 1, "\u03BA"], [120524, 1, "\u03BB"], [120525, 1, "\u03BC"], [120526, 1, "\u03BD"], [120527, 1, "\u03BE"], [120528, 1, "\u03BF"], [120529, 1, "\u03C0"], [120530, 1, "\u03C1"], [[120531, 120532], 1, "\u03C3"], [120533, 1, "\u03C4"], [120534, 1, "\u03C5"], [120535, 1, "\u03C6"], [120536, 1, "\u03C7"], [120537, 1, "\u03C8"], [120538, 1, "\u03C9"], [120539, 1, "\u2202"], [120540, 1, "\u03B5"], [120541, 1, "\u03B8"], [120542, 1, "\u03BA"], [120543, 1, "\u03C6"], [120544, 1, "\u03C1"], [120545, 1, "\u03C0"], [120546, 1, "\u03B1"], [120547, 1, "\u03B2"], [120548, 1, "\u03B3"], [120549, 1, "\u03B4"], [120550, 1, "\u03B5"], [120551, 1, "\u03B6"], [120552, 1, "\u03B7"], [120553, 1, "\u03B8"], [120554, 1, "\u03B9"], [120555, 1, "\u03BA"], [120556, 1, "\u03BB"], [120557, 1, "\u03BC"], [120558, 1, "\u03BD"], [120559, 1, "\u03BE"], [120560, 1, "\u03BF"], [120561, 1, "\u03C0"], [120562, 1, "\u03C1"], [120563, 1, "\u03B8"], [120564, 1, "\u03C3"], [120565, 1, "\u03C4"], [120566, 1, "\u03C5"], [120567, 1, "\u03C6"], [120568, 1, "\u03C7"], [120569, 1, "\u03C8"], [120570, 1, "\u03C9"], [120571, 1, "\u2207"], [120572, 1, "\u03B1"], [120573, 1, "\u03B2"], [120574, 1, "\u03B3"], [120575, 1, "\u03B4"], [120576, 1, "\u03B5"], [120577, 1, "\u03B6"], [120578, 1, "\u03B7"], [120579, 1, "\u03B8"], [120580, 1, "\u03B9"], [120581, 1, "\u03BA"], [120582, 1, "\u03BB"], [120583, 1, "\u03BC"], [120584, 1, "\u03BD"], [120585, 1, "\u03BE"], [120586, 1, "\u03BF"], [120587, 1, "\u03C0"], [120588, 1, "\u03C1"], [[120589, 120590], 1, "\u03C3"], [120591, 1, "\u03C4"], [120592, 1, "\u03C5"], [120593, 1, "\u03C6"], [120594, 1, "\u03C7"], [120595, 1, "\u03C8"], [120596, 1, "\u03C9"], [120597, 1, "\u2202"], [120598, 1, "\u03B5"], [120599, 1, "\u03B8"], [120600, 1, "\u03BA"], [120601, 1, "\u03C6"], [120602, 1, "\u03C1"], [120603, 1, "\u03C0"], [120604, 1, "\u03B1"], [120605, 1, "\u03B2"], [120606, 1, "\u03B3"], [120607, 1, "\u03B4"], [120608, 1, "\u03B5"], [120609, 1, "\u03B6"], [120610, 1, "\u03B7"], [120611, 1, "\u03B8"], [120612, 1, "\u03B9"], [120613, 1, "\u03BA"], [120614, 1, "\u03BB"], [120615, 1, "\u03BC"], [120616, 1, "\u03BD"], [120617, 1, "\u03BE"], [120618, 1, "\u03BF"], [120619, 1, "\u03C0"], [120620, 1, "\u03C1"], [120621, 1, "\u03B8"], [120622, 1, "\u03C3"], [120623, 1, "\u03C4"], [120624, 1, "\u03C5"], [120625, 1, "\u03C6"], [120626, 1, "\u03C7"], [120627, 1, "\u03C8"], [120628, 1, "\u03C9"], [120629, 1, "\u2207"], [120630, 1, "\u03B1"], [120631, 1, "\u03B2"], [120632, 1, "\u03B3"], [120633, 1, "\u03B4"], [120634, 1, "\u03B5"], [120635, 1, "\u03B6"], [120636, 1, "\u03B7"], [120637, 1, "\u03B8"], [120638, 1, "\u03B9"], [120639, 1, "\u03BA"], [120640, 1, "\u03BB"], [120641, 1, "\u03BC"], [120642, 1, "\u03BD"], [120643, 1, "\u03BE"], [120644, 1, "\u03BF"], [120645, 1, "\u03C0"], [120646, 1, "\u03C1"], [[120647, 120648], 1, "\u03C3"], [120649, 1, "\u03C4"], [120650, 1, "\u03C5"], [120651, 1, "\u03C6"], [120652, 1, "\u03C7"], [120653, 1, "\u03C8"], [120654, 1, "\u03C9"], [120655, 1, "\u2202"], [120656, 1, "\u03B5"], [120657, 1, "\u03B8"], [120658, 1, "\u03BA"], [120659, 1, "\u03C6"], [120660, 1, "\u03C1"], [120661, 1, "\u03C0"], [120662, 1, "\u03B1"], [120663, 1, "\u03B2"], [120664, 1, "\u03B3"], [120665, 1, "\u03B4"], [120666, 1, "\u03B5"], [120667, 1, "\u03B6"], [120668, 1, "\u03B7"], [120669, 1, "\u03B8"], [120670, 1, "\u03B9"], [120671, 1, "\u03BA"], [120672, 1, "\u03BB"], [120673, 1, "\u03BC"], [120674, 1, "\u03BD"], [120675, 1, "\u03BE"], [120676, 1, "\u03BF"], [120677, 1, "\u03C0"], [120678, 1, "\u03C1"], [120679, 1, "\u03B8"], [120680, 1, "\u03C3"], [120681, 1, "\u03C4"], [120682, 1, "\u03C5"], [120683, 1, "\u03C6"], [120684, 1, "\u03C7"], [120685, 1, "\u03C8"], [120686, 1, "\u03C9"], [120687, 1, "\u2207"], [120688, 1, "\u03B1"], [120689, 1, "\u03B2"], [120690, 1, "\u03B3"], [120691, 1, "\u03B4"], [120692, 1, "\u03B5"], [120693, 1, "\u03B6"], [120694, 1, "\u03B7"], [120695, 1, "\u03B8"], [120696, 1, "\u03B9"], [120697, 1, "\u03BA"], [120698, 1, "\u03BB"], [120699, 1, "\u03BC"], [120700, 1, "\u03BD"], [120701, 1, "\u03BE"], [120702, 1, "\u03BF"], [120703, 1, "\u03C0"], [120704, 1, "\u03C1"], [[120705, 120706], 1, "\u03C3"], [120707, 1, "\u03C4"], [120708, 1, "\u03C5"], [120709, 1, "\u03C6"], [120710, 1, "\u03C7"], [120711, 1, "\u03C8"], [120712, 1, "\u03C9"], [120713, 1, "\u2202"], [120714, 1, "\u03B5"], [120715, 1, "\u03B8"], [120716, 1, "\u03BA"], [120717, 1, "\u03C6"], [120718, 1, "\u03C1"], [120719, 1, "\u03C0"], [120720, 1, "\u03B1"], [120721, 1, "\u03B2"], [120722, 1, "\u03B3"], [120723, 1, "\u03B4"], [120724, 1, "\u03B5"], [120725, 1, "\u03B6"], [120726, 1, "\u03B7"], [120727, 1, "\u03B8"], [120728, 1, "\u03B9"], [120729, 1, "\u03BA"], [120730, 1, "\u03BB"], [120731, 1, "\u03BC"], [120732, 1, "\u03BD"], [120733, 1, "\u03BE"], [120734, 1, "\u03BF"], [120735, 1, "\u03C0"], [120736, 1, "\u03C1"], [120737, 1, "\u03B8"], [120738, 1, "\u03C3"], [120739, 1, "\u03C4"], [120740, 1, "\u03C5"], [120741, 1, "\u03C6"], [120742, 1, "\u03C7"], [120743, 1, "\u03C8"], [120744, 1, "\u03C9"], [120745, 1, "\u2207"], [120746, 1, "\u03B1"], [120747, 1, "\u03B2"], [120748, 1, "\u03B3"], [120749, 1, "\u03B4"], [120750, 1, "\u03B5"], [120751, 1, "\u03B6"], [120752, 1, "\u03B7"], [120753, 1, "\u03B8"], [120754, 1, "\u03B9"], [120755, 1, "\u03BA"], [120756, 1, "\u03BB"], [120757, 1, "\u03BC"], [120758, 1, "\u03BD"], [120759, 1, "\u03BE"], [120760, 1, "\u03BF"], [120761, 1, "\u03C0"], [120762, 1, "\u03C1"], [[120763, 120764], 1, "\u03C3"], [120765, 1, "\u03C4"], [120766, 1, "\u03C5"], [120767, 1, "\u03C6"], [120768, 1, "\u03C7"], [120769, 1, "\u03C8"], [120770, 1, "\u03C9"], [120771, 1, "\u2202"], [120772, 1, "\u03B5"], [120773, 1, "\u03B8"], [120774, 1, "\u03BA"], [120775, 1, "\u03C6"], [120776, 1, "\u03C1"], [120777, 1, "\u03C0"], [[120778, 120779], 1, "\u03DD"], [[120780, 120781], 3], [120782, 1, "0"], [120783, 1, "1"], [120784, 1, "2"], [120785, 1, "3"], [120786, 1, "4"], [120787, 1, "5"], [120788, 1, "6"], [120789, 1, "7"], [120790, 1, "8"], [120791, 1, "9"], [120792, 1, "0"], [120793, 1, "1"], [120794, 1, "2"], [120795, 1, "3"], [120796, 1, "4"], [120797, 1, "5"], [120798, 1, "6"], [120799, 1, "7"], [120800, 1, "8"], [120801, 1, "9"], [120802, 1, "0"], [120803, 1, "1"], [120804, 1, "2"], [120805, 1, "3"], [120806, 1, "4"], [120807, 1, "5"], [120808, 1, "6"], [120809, 1, "7"], [120810, 1, "8"], [120811, 1, "9"], [120812, 1, "0"], [120813, 1, "1"], [120814, 1, "2"], [120815, 1, "3"], [120816, 1, "4"], [120817, 1, "5"], [120818, 1, "6"], [120819, 1, "7"], [120820, 1, "8"], [120821, 1, "9"], [120822, 1, "0"], [120823, 1, "1"], [120824, 1, "2"], [120825, 1, "3"], [120826, 1, "4"], [120827, 1, "5"], [120828, 1, "6"], [120829, 1, "7"], [120830, 1, "8"], [120831, 1, "9"], [[120832, 121343], 2], [[121344, 121398], 2], [[121399, 121402], 2], [[121403, 121452], 2], [[121453, 121460], 2], [121461, 2], [[121462, 121475], 2], [121476, 2], [[121477, 121483], 2], [[121484, 121498], 3], [[121499, 121503], 2], [121504, 3], [[121505, 121519], 2], [[121520, 122623], 3], [[122624, 122654], 2], [[122655, 122660], 3], [[122661, 122666], 2], [[122667, 122879], 3], [[122880, 122886], 2], [122887, 3], [[122888, 122904], 2], [[122905, 122906], 3], [[122907, 122913], 2], [122914, 3], [[122915, 122916], 2], [122917, 3], [[122918, 122922], 2], [[122923, 122927], 3], [122928, 1, "\u0430"], [122929, 1, "\u0431"], [122930, 1, "\u0432"], [122931, 1, "\u0433"], [122932, 1, "\u0434"], [122933, 1, "\u0435"], [122934, 1, "\u0436"], [122935, 1, "\u0437"], [122936, 1, "\u0438"], [122937, 1, "\u043A"], [122938, 1, "\u043B"], [122939, 1, "\u043C"], [122940, 1, "\u043E"], [122941, 1, "\u043F"], [122942, 1, "\u0440"], [122943, 1, "\u0441"], [122944, 1, "\u0442"], [122945, 1, "\u0443"], [122946, 1, "\u0444"], [122947, 1, "\u0445"], [122948, 1, "\u0446"], [122949, 1, "\u0447"], [122950, 1, "\u0448"], [122951, 1, "\u044B"], [122952, 1, "\u044D"], [122953, 1, "\u044E"], [122954, 1, "\uA689"], [122955, 1, "\u04D9"], [122956, 1, "\u0456"], [122957, 1, "\u0458"], [122958, 1, "\u04E9"], [122959, 1, "\u04AF"], [122960, 1, "\u04CF"], [122961, 1, "\u0430"], [122962, 1, "\u0431"], [122963, 1, "\u0432"], [122964, 1, "\u0433"], [122965, 1, "\u0434"], [122966, 1, "\u0435"], [122967, 1, "\u0436"], [122968, 1, "\u0437"], [122969, 1, "\u0438"], [122970, 1, "\u043A"], [122971, 1, "\u043B"], [122972, 1, "\u043E"], [122973, 1, "\u043F"], [122974, 1, "\u0441"], [122975, 1, "\u0443"], [122976, 1, "\u0444"], [122977, 1, "\u0445"], [122978, 1, "\u0446"], [122979, 1, "\u0447"], [122980, 1, "\u0448"], [122981, 1, "\u044A"], [122982, 1, "\u044B"], [122983, 1, "\u0491"], [122984, 1, "\u0456"], [122985, 1, "\u0455"], [122986, 1, "\u045F"], [122987, 1, "\u04AB"], [122988, 1, "\uA651"], [122989, 1, "\u04B1"], [[122990, 123022], 3], [123023, 2], [[123024, 123135], 3], [[123136, 123180], 2], [[123181, 123183], 3], [[123184, 123197], 2], [[123198, 123199], 3], [[123200, 123209], 2], [[123210, 123213], 3], [123214, 2], [123215, 2], [[123216, 123535], 3], [[123536, 123566], 2], [[123567, 123583], 3], [[123584, 123641], 2], [[123642, 123646], 3], [123647, 2], [[123648, 124111], 3], [[124112, 124153], 2], [[124154, 124367], 3], [[124368, 124410], 2], [[124411, 124414], 3], [124415, 2], [[124416, 124895], 3], [[124896, 124902], 2], [124903, 3], [[124904, 124907], 2], [124908, 3], [[124909, 124910], 2], [124911, 3], [[124912, 124926], 2], [124927, 3], [[124928, 125124], 2], [[125125, 125126], 3], [[125127, 125135], 2], [[125136, 125142], 2], [[125143, 125183], 3], [125184, 1, "\u{1E922}"], [125185, 1, "\u{1E923}"], [125186, 1, "\u{1E924}"], [125187, 1, "\u{1E925}"], [125188, 1, "\u{1E926}"], [125189, 1, "\u{1E927}"], [125190, 1, "\u{1E928}"], [125191, 1, "\u{1E929}"], [125192, 1, "\u{1E92A}"], [125193, 1, "\u{1E92B}"], [125194, 1, "\u{1E92C}"], [125195, 1, "\u{1E92D}"], [125196, 1, "\u{1E92E}"], [125197, 1, "\u{1E92F}"], [125198, 1, "\u{1E930}"], [125199, 1, "\u{1E931}"], [125200, 1, "\u{1E932}"], [125201, 1, "\u{1E933}"], [125202, 1, "\u{1E934}"], [125203, 1, "\u{1E935}"], [125204, 1, "\u{1E936}"], [125205, 1, "\u{1E937}"], [125206, 1, "\u{1E938}"], [125207, 1, "\u{1E939}"], [125208, 1, "\u{1E93A}"], [125209, 1, "\u{1E93B}"], [125210, 1, "\u{1E93C}"], [125211, 1, "\u{1E93D}"], [125212, 1, "\u{1E93E}"], [125213, 1, "\u{1E93F}"], [125214, 1, "\u{1E940}"], [125215, 1, "\u{1E941}"], [125216, 1, "\u{1E942}"], [125217, 1, "\u{1E943}"], [[125218, 125258], 2], [125259, 2], [[125260, 125263], 3], [[125264, 125273], 2], [[125274, 125277], 3], [[125278, 125279], 2], [[125280, 126064], 3], [[126065, 126132], 2], [[126133, 126208], 3], [[126209, 126269], 2], [[126270, 126463], 3], [126464, 1, "\u0627"], [126465, 1, "\u0628"], [126466, 1, "\u062C"], [126467, 1, "\u062F"], [126468, 3], [126469, 1, "\u0648"], [126470, 1, "\u0632"], [126471, 1, "\u062D"], [126472, 1, "\u0637"], [126473, 1, "\u064A"], [126474, 1, "\u0643"], [126475, 1, "\u0644"], [126476, 1, "\u0645"], [126477, 1, "\u0646"], [126478, 1, "\u0633"], [126479, 1, "\u0639"], [126480, 1, "\u0641"], [126481, 1, "\u0635"], [126482, 1, "\u0642"], [126483, 1, "\u0631"], [126484, 1, "\u0634"], [126485, 1, "\u062A"], [126486, 1, "\u062B"], [126487, 1, "\u062E"], [126488, 1, "\u0630"], [126489, 1, "\u0636"], [126490, 1, "\u0638"], [126491, 1, "\u063A"], [126492, 1, "\u066E"], [126493, 1, "\u06BA"], [126494, 1, "\u06A1"], [126495, 1, "\u066F"], [126496, 3], [126497, 1, "\u0628"], [126498, 1, "\u062C"], [126499, 3], [126500, 1, "\u0647"], [[126501, 126502], 3], [126503, 1, "\u062D"], [126504, 3], [126505, 1, "\u064A"], [126506, 1, "\u0643"], [126507, 1, "\u0644"], [126508, 1, "\u0645"], [126509, 1, "\u0646"], [126510, 1, "\u0633"], [126511, 1, "\u0639"], [126512, 1, "\u0641"], [126513, 1, "\u0635"], [126514, 1, "\u0642"], [126515, 3], [126516, 1, "\u0634"], [126517, 1, "\u062A"], [126518, 1, "\u062B"], [126519, 1, "\u062E"], [126520, 3], [126521, 1, "\u0636"], [126522, 3], [126523, 1, "\u063A"], [[126524, 126529], 3], [126530, 1, "\u062C"], [[126531, 126534], 3], [126535, 1, "\u062D"], [126536, 3], [126537, 1, "\u064A"], [126538, 3], [126539, 1, "\u0644"], [126540, 3], [126541, 1, "\u0646"], [126542, 1, "\u0633"], [126543, 1, "\u0639"], [126544, 3], [126545, 1, "\u0635"], [126546, 1, "\u0642"], [126547, 3], [126548, 1, "\u0634"], [[126549, 126550], 3], [126551, 1, "\u062E"], [126552, 3], [126553, 1, "\u0636"], [126554, 3], [126555, 1, "\u063A"], [126556, 3], [126557, 1, "\u06BA"], [126558, 3], [126559, 1, "\u066F"], [126560, 3], [126561, 1, "\u0628"], [126562, 1, "\u062C"], [126563, 3], [126564, 1, "\u0647"], [[126565, 126566], 3], [126567, 1, "\u062D"], [126568, 1, "\u0637"], [126569, 1, "\u064A"], [126570, 1, "\u0643"], [126571, 3], [126572, 1, "\u0645"], [126573, 1, "\u0646"], [126574, 1, "\u0633"], [126575, 1, "\u0639"], [126576, 1, "\u0641"], [126577, 1, "\u0635"], [126578, 1, "\u0642"], [126579, 3], [126580, 1, "\u0634"], [126581, 1, "\u062A"], [126582, 1, "\u062B"], [126583, 1, "\u062E"], [126584, 3], [126585, 1, "\u0636"], [126586, 1, "\u0638"], [126587, 1, "\u063A"], [126588, 1, "\u066E"], [126589, 3], [126590, 1, "\u06A1"], [126591, 3], [126592, 1, "\u0627"], [126593, 1, "\u0628"], [126594, 1, "\u062C"], [126595, 1, "\u062F"], [126596, 1, "\u0647"], [126597, 1, "\u0648"], [126598, 1, "\u0632"], [126599, 1, "\u062D"], [126600, 1, "\u0637"], [126601, 1, "\u064A"], [126602, 3], [126603, 1, "\u0644"], [126604, 1, "\u0645"], [126605, 1, "\u0646"], [126606, 1, "\u0633"], [126607, 1, "\u0639"], [126608, 1, "\u0641"], [126609, 1, "\u0635"], [126610, 1, "\u0642"], [126611, 1, "\u0631"], [126612, 1, "\u0634"], [126613, 1, "\u062A"], [126614, 1, "\u062B"], [126615, 1, "\u062E"], [126616, 1, "\u0630"], [126617, 1, "\u0636"], [126618, 1, "\u0638"], [126619, 1, "\u063A"], [[126620, 126624], 3], [126625, 1, "\u0628"], [126626, 1, "\u062C"], [126627, 1, "\u062F"], [126628, 3], [126629, 1, "\u0648"], [126630, 1, "\u0632"], [126631, 1, "\u062D"], [126632, 1, "\u0637"], [126633, 1, "\u064A"], [126634, 3], [126635, 1, "\u0644"], [126636, 1, "\u0645"], [126637, 1, "\u0646"], [126638, 1, "\u0633"], [126639, 1, "\u0639"], [126640, 1, "\u0641"], [126641, 1, "\u0635"], [126642, 1, "\u0642"], [126643, 1, "\u0631"], [126644, 1, "\u0634"], [126645, 1, "\u062A"], [126646, 1, "\u062B"], [126647, 1, "\u062E"], [126648, 1, "\u0630"], [126649, 1, "\u0636"], [126650, 1, "\u0638"], [126651, 1, "\u063A"], [[126652, 126703], 3], [[126704, 126705], 2], [[126706, 126975], 3], [[126976, 127019], 2], [[127020, 127023], 3], [[127024, 127123], 2], [[127124, 127135], 3], [[127136, 127150], 2], [[127151, 127152], 3], [[127153, 127166], 2], [127167, 2], [127168, 3], [[127169, 127183], 2], [127184, 3], [[127185, 127199], 2], [[127200, 127221], 2], [[127222, 127231], 3], [127232, 3], [127233, 1, "0,"], [127234, 1, "1,"], [127235, 1, "2,"], [127236, 1, "3,"], [127237, 1, "4,"], [127238, 1, "5,"], [127239, 1, "6,"], [127240, 1, "7,"], [127241, 1, "8,"], [127242, 1, "9,"], [[127243, 127244], 2], [[127245, 127247], 2], [127248, 1, "(a)"], [127249, 1, "(b)"], [127250, 1, "(c)"], [127251, 1, "(d)"], [127252, 1, "(e)"], [127253, 1, "(f)"], [127254, 1, "(g)"], [127255, 1, "(h)"], [127256, 1, "(i)"], [127257, 1, "(j)"], [127258, 1, "(k)"], [127259, 1, "(l)"], [127260, 1, "(m)"], [127261, 1, "(n)"], [127262, 1, "(o)"], [127263, 1, "(p)"], [127264, 1, "(q)"], [127265, 1, "(r)"], [127266, 1, "(s)"], [127267, 1, "(t)"], [127268, 1, "(u)"], [127269, 1, "(v)"], [127270, 1, "(w)"], [127271, 1, "(x)"], [127272, 1, "(y)"], [127273, 1, "(z)"], [127274, 1, "\u3014s\u3015"], [127275, 1, "c"], [127276, 1, "r"], [127277, 1, "cd"], [127278, 1, "wz"], [127279, 2], [127280, 1, "a"], [127281, 1, "b"], [127282, 1, "c"], [127283, 1, "d"], [127284, 1, "e"], [127285, 1, "f"], [127286, 1, "g"], [127287, 1, "h"], [127288, 1, "i"], [127289, 1, "j"], [127290, 1, "k"], [127291, 1, "l"], [127292, 1, "m"], [127293, 1, "n"], [127294, 1, "o"], [127295, 1, "p"], [127296, 1, "q"], [127297, 1, "r"], [127298, 1, "s"], [127299, 1, "t"], [127300, 1, "u"], [127301, 1, "v"], [127302, 1, "w"], [127303, 1, "x"], [127304, 1, "y"], [127305, 1, "z"], [127306, 1, "hv"], [127307, 1, "mv"], [127308, 1, "sd"], [127309, 1, "ss"], [127310, 1, "ppv"], [127311, 1, "wc"], [[127312, 127318], 2], [127319, 2], [[127320, 127326], 2], [127327, 2], [[127328, 127337], 2], [127338, 1, "mc"], [127339, 1, "md"], [127340, 1, "mr"], [[127341, 127343], 2], [[127344, 127352], 2], [127353, 2], [127354, 2], [[127355, 127356], 2], [[127357, 127358], 2], [127359, 2], [[127360, 127369], 2], [[127370, 127373], 2], [[127374, 127375], 2], [127376, 1, "dj"], [[127377, 127386], 2], [[127387, 127404], 2], [127405, 2], [[127406, 127461], 3], [[127462, 127487], 2], [127488, 1, "\u307B\u304B"], [127489, 1, "\u30B3\u30B3"], [127490, 1, "\u30B5"], [[127491, 127503], 3], [127504, 1, "\u624B"], [127505, 1, "\u5B57"], [127506, 1, "\u53CC"], [127507, 1, "\u30C7"], [127508, 1, "\u4E8C"], [127509, 1, "\u591A"], [127510, 1, "\u89E3"], [127511, 1, "\u5929"], [127512, 1, "\u4EA4"], [127513, 1, "\u6620"], [127514, 1, "\u7121"], [127515, 1, "\u6599"], [127516, 1, "\u524D"], [127517, 1, "\u5F8C"], [127518, 1, "\u518D"], [127519, 1, "\u65B0"], [127520, 1, "\u521D"], [127521, 1, "\u7D42"], [127522, 1, "\u751F"], [127523, 1, "\u8CA9"], [127524, 1, "\u58F0"], [127525, 1, "\u5439"], [127526, 1, "\u6F14"], [127527, 1, "\u6295"], [127528, 1, "\u6355"], [127529, 1, "\u4E00"], [127530, 1, "\u4E09"], [127531, 1, "\u904A"], [127532, 1, "\u5DE6"], [127533, 1, "\u4E2D"], [127534, 1, "\u53F3"], [127535, 1, "\u6307"], [127536, 1, "\u8D70"], [127537, 1, "\u6253"], [127538, 1, "\u7981"], [127539, 1, "\u7A7A"], [127540, 1, "\u5408"], [127541, 1, "\u6E80"], [127542, 1, "\u6709"], [127543, 1, "\u6708"], [127544, 1, "\u7533"], [127545, 1, "\u5272"], [127546, 1, "\u55B6"], [127547, 1, "\u914D"], [[127548, 127551], 3], [127552, 1, "\u3014\u672C\u3015"], [127553, 1, "\u3014\u4E09\u3015"], [127554, 1, "\u3014\u4E8C\u3015"], [127555, 1, "\u3014\u5B89\u3015"], [127556, 1, "\u3014\u70B9\u3015"], [127557, 1, "\u3014\u6253\u3015"], [127558, 1, "\u3014\u76D7\u3015"], [127559, 1, "\u3014\u52DD\u3015"], [127560, 1, "\u3014\u6557\u3015"], [[127561, 127567], 3], [127568, 1, "\u5F97"], [127569, 1, "\u53EF"], [[127570, 127583], 3], [[127584, 127589], 2], [[127590, 127743], 3], [[127744, 127776], 2], [[127777, 127788], 2], [[127789, 127791], 2], [[127792, 127797], 2], [127798, 2], [[127799, 127868], 2], [127869, 2], [[127870, 127871], 2], [[127872, 127891], 2], [[127892, 127903], 2], [[127904, 127940], 2], [127941, 2], [[127942, 127946], 2], [[127947, 127950], 2], [[127951, 127955], 2], [[127956, 127967], 2], [[127968, 127984], 2], [[127985, 127991], 2], [[127992, 127999], 2], [[128e3, 128062], 2], [128063, 2], [128064, 2], [128065, 2], [[128066, 128247], 2], [128248, 2], [[128249, 128252], 2], [[128253, 128254], 2], [128255, 2], [[128256, 128317], 2], [[128318, 128319], 2], [[128320, 128323], 2], [[128324, 128330], 2], [[128331, 128335], 2], [[128336, 128359], 2], [[128360, 128377], 2], [128378, 2], [[128379, 128419], 2], [128420, 2], [[128421, 128506], 2], [[128507, 128511], 2], [128512, 2], [[128513, 128528], 2], [128529, 2], [[128530, 128532], 2], [128533, 2], [128534, 2], [128535, 2], [128536, 2], [128537, 2], [128538, 2], [128539, 2], [[128540, 128542], 2], [128543, 2], [[128544, 128549], 2], [[128550, 128551], 2], [[128552, 128555], 2], [128556, 2], [128557, 2], [[128558, 128559], 2], [[128560, 128563], 2], [128564, 2], [[128565, 128576], 2], [[128577, 128578], 2], [[128579, 128580], 2], [[128581, 128591], 2], [[128592, 128639], 2], [[128640, 128709], 2], [[128710, 128719], 2], [128720, 2], [[128721, 128722], 2], [[128723, 128724], 2], [128725, 2], [[128726, 128727], 2], [[128728, 128731], 3], [128732, 2], [[128733, 128735], 2], [[128736, 128748], 2], [[128749, 128751], 3], [[128752, 128755], 2], [[128756, 128758], 2], [[128759, 128760], 2], [128761, 2], [128762, 2], [[128763, 128764], 2], [[128765, 128767], 3], [[128768, 128883], 2], [[128884, 128886], 2], [[128887, 128890], 3], [[128891, 128895], 2], [[128896, 128980], 2], [[128981, 128984], 2], [128985, 2], [[128986, 128991], 3], [[128992, 129003], 2], [[129004, 129007], 3], [129008, 2], [[129009, 129023], 3], [[129024, 129035], 2], [[129036, 129039], 3], [[129040, 129095], 2], [[129096, 129103], 3], [[129104, 129113], 2], [[129114, 129119], 3], [[129120, 129159], 2], [[129160, 129167], 3], [[129168, 129197], 2], [[129198, 129199], 3], [[129200, 129201], 2], [[129202, 129211], 2], [[129212, 129215], 3], [[129216, 129217], 2], [[129218, 129279], 3], [[129280, 129291], 2], [129292, 2], [[129293, 129295], 2], [[129296, 129304], 2], [[129305, 129310], 2], [129311, 2], [[129312, 129319], 2], [[129320, 129327], 2], [129328, 2], [[129329, 129330], 2], [[129331, 129342], 2], [129343, 2], [[129344, 129355], 2], [129356, 2], [[129357, 129359], 2], [[129360, 129374], 2], [[129375, 129387], 2], [[129388, 129392], 2], [129393, 2], [129394, 2], [[129395, 129398], 2], [[129399, 129400], 2], [129401, 2], [129402, 2], [129403, 2], [[129404, 129407], 2], [[129408, 129412], 2], [[129413, 129425], 2], [[129426, 129431], 2], [[129432, 129442], 2], [[129443, 129444], 2], [[129445, 129450], 2], [[129451, 129453], 2], [[129454, 129455], 2], [[129456, 129465], 2], [[129466, 129471], 2], [129472, 2], [[129473, 129474], 2], [[129475, 129482], 2], [129483, 2], [129484, 2], [[129485, 129487], 2], [[129488, 129510], 2], [[129511, 129535], 2], [[129536, 129619], 2], [[129620, 129631], 3], [[129632, 129645], 2], [[129646, 129647], 3], [[129648, 129651], 2], [129652, 2], [[129653, 129655], 2], [[129656, 129658], 2], [[129659, 129660], 2], [[129661, 129663], 3], [[129664, 129666], 2], [[129667, 129670], 2], [[129671, 129672], 2], [129673, 2], [[129674, 129678], 3], [129679, 2], [[129680, 129685], 2], [[129686, 129704], 2], [[129705, 129708], 2], [[129709, 129711], 2], [[129712, 129718], 2], [[129719, 129722], 2], [[129723, 129725], 2], [129726, 2], [129727, 2], [[129728, 129730], 2], [[129731, 129733], 2], [129734, 2], [[129735, 129741], 3], [[129742, 129743], 2], [[129744, 129750], 2], [[129751, 129753], 2], [[129754, 129755], 2], [129756, 2], [[129757, 129758], 3], [129759, 2], [[129760, 129767], 2], [129768, 2], [129769, 2], [[129770, 129775], 3], [[129776, 129782], 2], [[129783, 129784], 2], [[129785, 129791], 3], [[129792, 129938], 2], [129939, 3], [[129940, 129994], 2], [[129995, 130031], 2], [130032, 1, "0"], [130033, 1, "1"], [130034, 1, "2"], [130035, 1, "3"], [130036, 1, "4"], [130037, 1, "5"], [130038, 1, "6"], [130039, 1, "7"], [130040, 1, "8"], [130041, 1, "9"], [[130042, 131069], 3], [[131070, 131071], 3], [[131072, 173782], 2], [[173783, 173789], 2], [[173790, 173791], 2], [[173792, 173823], 3], [[173824, 177972], 2], [[177973, 177976], 2], [177977, 2], [[177978, 177983], 3], [[177984, 178205], 2], [[178206, 178207], 3], [[178208, 183969], 2], [[183970, 183983], 3], [[183984, 191456], 2], [[191457, 191471], 3], [[191472, 192093], 2], [[192094, 194559], 3], [194560, 1, "\u4E3D"], [194561, 1, "\u4E38"], [194562, 1, "\u4E41"], [194563, 1, "\u{20122}"], [194564, 1, "\u4F60"], [194565, 1, "\u4FAE"], [194566, 1, "\u4FBB"], [194567, 1, "\u5002"], [194568, 1, "\u507A"], [194569, 1, "\u5099"], [194570, 1, "\u50E7"], [194571, 1, "\u50CF"], [194572, 1, "\u349E"], [194573, 1, "\u{2063A}"], [194574, 1, "\u514D"], [194575, 1, "\u5154"], [194576, 1, "\u5164"], [194577, 1, "\u5177"], [194578, 1, "\u{2051C}"], [194579, 1, "\u34B9"], [194580, 1, "\u5167"], [194581, 1, "\u518D"], [194582, 1, "\u{2054B}"], [194583, 1, "\u5197"], [194584, 1, "\u51A4"], [194585, 1, "\u4ECC"], [194586, 1, "\u51AC"], [194587, 1, "\u51B5"], [194588, 1, "\u{291DF}"], [194589, 1, "\u51F5"], [194590, 1, "\u5203"], [194591, 1, "\u34DF"], [194592, 1, "\u523B"], [194593, 1, "\u5246"], [194594, 1, "\u5272"], [194595, 1, "\u5277"], [194596, 1, "\u3515"], [194597, 1, "\u52C7"], [194598, 1, "\u52C9"], [194599, 1, "\u52E4"], [194600, 1, "\u52FA"], [194601, 1, "\u5305"], [194602, 1, "\u5306"], [194603, 1, "\u5317"], [194604, 1, "\u5349"], [194605, 1, "\u5351"], [194606, 1, "\u535A"], [194607, 1, "\u5373"], [194608, 1, "\u537D"], [[194609, 194611], 1, "\u537F"], [194612, 1, "\u{20A2C}"], [194613, 1, "\u7070"], [194614, 1, "\u53CA"], [194615, 1, "\u53DF"], [194616, 1, "\u{20B63}"], [194617, 1, "\u53EB"], [194618, 1, "\u53F1"], [194619, 1, "\u5406"], [194620, 1, "\u549E"], [194621, 1, "\u5438"], [194622, 1, "\u5448"], [194623, 1, "\u5468"], [194624, 1, "\u54A2"], [194625, 1, "\u54F6"], [194626, 1, "\u5510"], [194627, 1, "\u5553"], [194628, 1, "\u5563"], [[194629, 194630], 1, "\u5584"], [194631, 1, "\u5599"], [194632, 1, "\u55AB"], [194633, 1, "\u55B3"], [194634, 1, "\u55C2"], [194635, 1, "\u5716"], [194636, 1, "\u5606"], [194637, 1, "\u5717"], [194638, 1, "\u5651"], [194639, 1, "\u5674"], [194640, 1, "\u5207"], [194641, 1, "\u58EE"], [194642, 1, "\u57CE"], [194643, 1, "\u57F4"], [194644, 1, "\u580D"], [194645, 1, "\u578B"], [194646, 1, "\u5832"], [194647, 1, "\u5831"], [194648, 1, "\u58AC"], [194649, 1, "\u{214E4}"], [194650, 1, "\u58F2"], [194651, 1, "\u58F7"], [194652, 1, "\u5906"], [194653, 1, "\u591A"], [194654, 1, "\u5922"], [194655, 1, "\u5962"], [194656, 1, "\u{216A8}"], [194657, 1, "\u{216EA}"], [194658, 1, "\u59EC"], [194659, 1, "\u5A1B"], [194660, 1, "\u5A27"], [194661, 1, "\u59D8"], [194662, 1, "\u5A66"], [194663, 1, "\u36EE"], [194664, 1, "\u36FC"], [194665, 1, "\u5B08"], [[194666, 194667], 1, "\u5B3E"], [194668, 1, "\u{219C8}"], [194669, 1, "\u5BC3"], [194670, 1, "\u5BD8"], [194671, 1, "\u5BE7"], [194672, 1, "\u5BF3"], [194673, 1, "\u{21B18}"], [194674, 1, "\u5BFF"], [194675, 1, "\u5C06"], [194676, 1, "\u5F53"], [194677, 1, "\u5C22"], [194678, 1, "\u3781"], [194679, 1, "\u5C60"], [194680, 1, "\u5C6E"], [194681, 1, "\u5CC0"], [194682, 1, "\u5C8D"], [194683, 1, "\u{21DE4}"], [194684, 1, "\u5D43"], [194685, 1, "\u{21DE6}"], [194686, 1, "\u5D6E"], [194687, 1, "\u5D6B"], [194688, 1, "\u5D7C"], [194689, 1, "\u5DE1"], [194690, 1, "\u5DE2"], [194691, 1, "\u382F"], [194692, 1, "\u5DFD"], [194693, 1, "\u5E28"], [194694, 1, "\u5E3D"], [194695, 1, "\u5E69"], [194696, 1, "\u3862"], [194697, 1, "\u{22183}"], [194698, 1, "\u387C"], [194699, 1, "\u5EB0"], [194700, 1, "\u5EB3"], [194701, 1, "\u5EB6"], [194702, 1, "\u5ECA"], [194703, 1, "\u{2A392}"], [194704, 1, "\u5EFE"], [[194705, 194706], 1, "\u{22331}"], [194707, 1, "\u8201"], [[194708, 194709], 1, "\u5F22"], [194710, 1, "\u38C7"], [194711, 1, "\u{232B8}"], [194712, 1, "\u{261DA}"], [194713, 1, "\u5F62"], [194714, 1, "\u5F6B"], [194715, 1, "\u38E3"], [194716, 1, "\u5F9A"], [194717, 1, "\u5FCD"], [194718, 1, "\u5FD7"], [194719, 1, "\u5FF9"], [194720, 1, "\u6081"], [194721, 1, "\u393A"], [194722, 1, "\u391C"], [194723, 1, "\u6094"], [194724, 1, "\u{226D4}"], [194725, 1, "\u60C7"], [194726, 1, "\u6148"], [194727, 1, "\u614C"], [194728, 1, "\u614E"], [194729, 1, "\u614C"], [194730, 1, "\u617A"], [194731, 1, "\u618E"], [194732, 1, "\u61B2"], [194733, 1, "\u61A4"], [194734, 1, "\u61AF"], [194735, 1, "\u61DE"], [194736, 1, "\u61F2"], [194737, 1, "\u61F6"], [194738, 1, "\u6210"], [194739, 1, "\u621B"], [194740, 1, "\u625D"], [194741, 1, "\u62B1"], [194742, 1, "\u62D4"], [194743, 1, "\u6350"], [194744, 1, "\u{22B0C}"], [194745, 1, "\u633D"], [194746, 1, "\u62FC"], [194747, 1, "\u6368"], [194748, 1, "\u6383"], [194749, 1, "\u63E4"], [194750, 1, "\u{22BF1}"], [194751, 1, "\u6422"], [194752, 1, "\u63C5"], [194753, 1, "\u63A9"], [194754, 1, "\u3A2E"], [194755, 1, "\u6469"], [194756, 1, "\u647E"], [194757, 1, "\u649D"], [194758, 1, "\u6477"], [194759, 1, "\u3A6C"], [194760, 1, "\u654F"], [194761, 1, "\u656C"], [194762, 1, "\u{2300A}"], [194763, 1, "\u65E3"], [194764, 1, "\u66F8"], [194765, 1, "\u6649"], [194766, 1, "\u3B19"], [194767, 1, "\u6691"], [194768, 1, "\u3B08"], [194769, 1, "\u3AE4"], [194770, 1, "\u5192"], [194771, 1, "\u5195"], [194772, 1, "\u6700"], [194773, 1, "\u669C"], [194774, 1, "\u80AD"], [194775, 1, "\u43D9"], [194776, 1, "\u6717"], [194777, 1, "\u671B"], [194778, 1, "\u6721"], [194779, 1, "\u675E"], [194780, 1, "\u6753"], [194781, 1, "\u{233C3}"], [194782, 1, "\u3B49"], [194783, 1, "\u67FA"], [194784, 1, "\u6785"], [194785, 1, "\u6852"], [194786, 1, "\u6885"], [194787, 1, "\u{2346D}"], [194788, 1, "\u688E"], [194789, 1, "\u681F"], [194790, 1, "\u6914"], [194791, 1, "\u3B9D"], [194792, 1, "\u6942"], [194793, 1, "\u69A3"], [194794, 1, "\u69EA"], [194795, 1, "\u6AA8"], [194796, 1, "\u{236A3}"], [194797, 1, "\u6ADB"], [194798, 1, "\u3C18"], [194799, 1, "\u6B21"], [194800, 1, "\u{238A7}"], [194801, 1, "\u6B54"], [194802, 1, "\u3C4E"], [194803, 1, "\u6B72"], [194804, 1, "\u6B9F"], [194805, 1, "\u6BBA"], [194806, 1, "\u6BBB"], [194807, 1, "\u{23A8D}"], [194808, 1, "\u{21D0B}"], [194809, 1, "\u{23AFA}"], [194810, 1, "\u6C4E"], [194811, 1, "\u{23CBC}"], [194812, 1, "\u6CBF"], [194813, 1, "\u6CCD"], [194814, 1, "\u6C67"], [194815, 1, "\u6D16"], [194816, 1, "\u6D3E"], [194817, 1, "\u6D77"], [194818, 1, "\u6D41"], [194819, 1, "\u6D69"], [194820, 1, "\u6D78"], [194821, 1, "\u6D85"], [194822, 1, "\u{23D1E}"], [194823, 1, "\u6D34"], [194824, 1, "\u6E2F"], [194825, 1, "\u6E6E"], [194826, 1, "\u3D33"], [194827, 1, "\u6ECB"], [194828, 1, "\u6EC7"], [194829, 1, "\u{23ED1}"], [194830, 1, "\u6DF9"], [194831, 1, "\u6F6E"], [194832, 1, "\u{23F5E}"], [194833, 1, "\u{23F8E}"], [194834, 1, "\u6FC6"], [194835, 1, "\u7039"], [194836, 1, "\u701E"], [194837, 1, "\u701B"], [194838, 1, "\u3D96"], [194839, 1, "\u704A"], [194840, 1, "\u707D"], [194841, 1, "\u7077"], [194842, 1, "\u70AD"], [194843, 1, "\u{20525}"], [194844, 1, "\u7145"], [194845, 1, "\u{24263}"], [194846, 1, "\u719C"], [194847, 1, "\u{243AB}"], [194848, 1, "\u7228"], [194849, 1, "\u7235"], [194850, 1, "\u7250"], [194851, 1, "\u{24608}"], [194852, 1, "\u7280"], [194853, 1, "\u7295"], [194854, 1, "\u{24735}"], [194855, 1, "\u{24814}"], [194856, 1, "\u737A"], [194857, 1, "\u738B"], [194858, 1, "\u3EAC"], [194859, 1, "\u73A5"], [[194860, 194861], 1, "\u3EB8"], [194862, 1, "\u7447"], [194863, 1, "\u745C"], [194864, 1, "\u7471"], [194865, 1, "\u7485"], [194866, 1, "\u74CA"], [194867, 1, "\u3F1B"], [194868, 1, "\u7524"], [194869, 1, "\u{24C36}"], [194870, 1, "\u753E"], [194871, 1, "\u{24C92}"], [194872, 1, "\u7570"], [194873, 1, "\u{2219F}"], [194874, 1, "\u7610"], [194875, 1, "\u{24FA1}"], [194876, 1, "\u{24FB8}"], [194877, 1, "\u{25044}"], [194878, 1, "\u3FFC"], [194879, 1, "\u4008"], [194880, 1, "\u76F4"], [194881, 1, "\u{250F3}"], [194882, 1, "\u{250F2}"], [194883, 1, "\u{25119}"], [194884, 1, "\u{25133}"], [194885, 1, "\u771E"], [[194886, 194887], 1, "\u771F"], [194888, 1, "\u774A"], [194889, 1, "\u4039"], [194890, 1, "\u778B"], [194891, 1, "\u4046"], [194892, 1, "\u4096"], [194893, 1, "\u{2541D}"], [194894, 1, "\u784E"], [194895, 1, "\u788C"], [194896, 1, "\u78CC"], [194897, 1, "\u40E3"], [194898, 1, "\u{25626}"], [194899, 1, "\u7956"], [194900, 1, "\u{2569A}"], [194901, 1, "\u{256C5}"], [194902, 1, "\u798F"], [194903, 1, "\u79EB"], [194904, 1, "\u412F"], [194905, 1, "\u7A40"], [194906, 1, "\u7A4A"], [194907, 1, "\u7A4F"], [194908, 1, "\u{2597C}"], [[194909, 194910], 1, "\u{25AA7}"], [194911, 1, "\u7AEE"], [194912, 1, "\u4202"], [194913, 1, "\u{25BAB}"], [194914, 1, "\u7BC6"], [194915, 1, "\u7BC9"], [194916, 1, "\u4227"], [194917, 1, "\u{25C80}"], [194918, 1, "\u7CD2"], [194919, 1, "\u42A0"], [194920, 1, "\u7CE8"], [194921, 1, "\u7CE3"], [194922, 1, "\u7D00"], [194923, 1, "\u{25F86}"], [194924, 1, "\u7D63"], [194925, 1, "\u4301"], [194926, 1, "\u7DC7"], [194927, 1, "\u7E02"], [194928, 1, "\u7E45"], [194929, 1, "\u4334"], [194930, 1, "\u{26228}"], [194931, 1, "\u{26247}"], [194932, 1, "\u4359"], [194933, 1, "\u{262D9}"], [194934, 1, "\u7F7A"], [194935, 1, "\u{2633E}"], [194936, 1, "\u7F95"], [194937, 1, "\u7FFA"], [194938, 1, "\u8005"], [194939, 1, "\u{264DA}"], [194940, 1, "\u{26523}"], [194941, 1, "\u8060"], [194942, 1, "\u{265A8}"], [194943, 1, "\u8070"], [194944, 1, "\u{2335F}"], [194945, 1, "\u43D5"], [194946, 1, "\u80B2"], [194947, 1, "\u8103"], [194948, 1, "\u440B"], [194949, 1, "\u813E"], [194950, 1, "\u5AB5"], [194951, 1, "\u{267A7}"], [194952, 1, "\u{267B5}"], [194953, 1, "\u{23393}"], [194954, 1, "\u{2339C}"], [194955, 1, "\u8201"], [194956, 1, "\u8204"], [194957, 1, "\u8F9E"], [194958, 1, "\u446B"], [194959, 1, "\u8291"], [194960, 1, "\u828B"], [194961, 1, "\u829D"], [194962, 1, "\u52B3"], [194963, 1, "\u82B1"], [194964, 1, "\u82B3"], [194965, 1, "\u82BD"], [194966, 1, "\u82E6"], [194967, 1, "\u{26B3C}"], [194968, 1, "\u82E5"], [194969, 1, "\u831D"], [194970, 1, "\u8363"], [194971, 1, "\u83AD"], [194972, 1, "\u8323"], [194973, 1, "\u83BD"], [194974, 1, "\u83E7"], [194975, 1, "\u8457"], [194976, 1, "\u8353"], [194977, 1, "\u83CA"], [194978, 1, "\u83CC"], [194979, 1, "\u83DC"], [194980, 1, "\u{26C36}"], [194981, 1, "\u{26D6B}"], [194982, 1, "\u{26CD5}"], [194983, 1, "\u452B"], [194984, 1, "\u84F1"], [194985, 1, "\u84F3"], [194986, 1, "\u8516"], [194987, 1, "\u{273CA}"], [194988, 1, "\u8564"], [194989, 1, "\u{26F2C}"], [194990, 1, "\u455D"], [194991, 1, "\u4561"], [194992, 1, "\u{26FB1}"], [194993, 1, "\u{270D2}"], [194994, 1, "\u456B"], [194995, 1, "\u8650"], [194996, 1, "\u865C"], [194997, 1, "\u8667"], [194998, 1, "\u8669"], [194999, 1, "\u86A9"], [195e3, 1, "\u8688"], [195001, 1, "\u870E"], [195002, 1, "\u86E2"], [195003, 1, "\u8779"], [195004, 1, "\u8728"], [195005, 1, "\u876B"], [195006, 1, "\u8786"], [195007, 1, "\u45D7"], [195008, 1, "\u87E1"], [195009, 1, "\u8801"], [195010, 1, "\u45F9"], [195011, 1, "\u8860"], [195012, 1, "\u8863"], [195013, 1, "\u{27667}"], [195014, 1, "\u88D7"], [195015, 1, "\u88DE"], [195016, 1, "\u4635"], [195017, 1, "\u88FA"], [195018, 1, "\u34BB"], [195019, 1, "\u{278AE}"], [195020, 1, "\u{27966}"], [195021, 1, "\u46BE"], [195022, 1, "\u46C7"], [195023, 1, "\u8AA0"], [195024, 1, "\u8AED"], [195025, 1, "\u8B8A"], [195026, 1, "\u8C55"], [195027, 1, "\u{27CA8}"], [195028, 1, "\u8CAB"], [195029, 1, "\u8CC1"], [195030, 1, "\u8D1B"], [195031, 1, "\u8D77"], [195032, 1, "\u{27F2F}"], [195033, 1, "\u{20804}"], [195034, 1, "\u8DCB"], [195035, 1, "\u8DBC"], [195036, 1, "\u8DF0"], [195037, 1, "\u{208DE}"], [195038, 1, "\u8ED4"], [195039, 1, "\u8F38"], [195040, 1, "\u{285D2}"], [195041, 1, "\u{285ED}"], [195042, 1, "\u9094"], [195043, 1, "\u90F1"], [195044, 1, "\u9111"], [195045, 1, "\u{2872E}"], [195046, 1, "\u911B"], [195047, 1, "\u9238"], [195048, 1, "\u92D7"], [195049, 1, "\u92D8"], [195050, 1, "\u927C"], [195051, 1, "\u93F9"], [195052, 1, "\u9415"], [195053, 1, "\u{28BFA}"], [195054, 1, "\u958B"], [195055, 1, "\u4995"], [195056, 1, "\u95B7"], [195057, 1, "\u{28D77}"], [195058, 1, "\u49E6"], [195059, 1, "\u96C3"], [195060, 1, "\u5DB2"], [195061, 1, "\u9723"], [195062, 1, "\u{29145}"], [195063, 1, "\u{2921A}"], [195064, 1, "\u4A6E"], [195065, 1, "\u4A76"], [195066, 1, "\u97E0"], [195067, 1, "\u{2940A}"], [195068, 1, "\u4AB2"], [195069, 1, "\u{29496}"], [[195070, 195071], 1, "\u980B"], [195072, 1, "\u9829"], [195073, 1, "\u{295B6}"], [195074, 1, "\u98E2"], [195075, 1, "\u4B33"], [195076, 1, "\u9929"], [195077, 1, "\u99A7"], [195078, 1, "\u99C2"], [195079, 1, "\u99FE"], [195080, 1, "\u4BCE"], [195081, 1, "\u{29B30}"], [195082, 1, "\u9B12"], [195083, 1, "\u9C40"], [195084, 1, "\u9CFD"], [195085, 1, "\u4CCE"], [195086, 1, "\u4CED"], [195087, 1, "\u9D67"], [195088, 1, "\u{2A0CE}"], [195089, 1, "\u4CF8"], [195090, 1, "\u{2A105}"], [195091, 1, "\u{2A20E}"], [195092, 1, "\u{2A291}"], [195093, 1, "\u9EBB"], [195094, 1, "\u4D56"], [195095, 1, "\u9EF9"], [195096, 1, "\u9EFE"], [195097, 1, "\u9F05"], [195098, 1, "\u9F0F"], [195099, 1, "\u9F16"], [195100, 1, "\u9F3B"], [195101, 1, "\u{2A600}"], [[195102, 196605], 3], [[196606, 196607], 3], [[196608, 201546], 2], [[201547, 201551], 3], [[201552, 205743], 2], [[205744, 262141], 3], [[262142, 262143], 3], [[262144, 327677], 3], [[327678, 327679], 3], [[327680, 393213], 3], [[393214, 393215], 3], [[393216, 458749], 3], [[458750, 458751], 3], [[458752, 524285], 3], [[524286, 524287], 3], [[524288, 589821], 3], [[589822, 589823], 3], [[589824, 655357], 3], [[655358, 655359], 3], [[655360, 720893], 3], [[720894, 720895], 3], [[720896, 786429], 3], [[786430, 786431], 3], [[786432, 851965], 3], [[851966, 851967], 3], [[851968, 917501], 3], [[917502, 917503], 3], [917504, 3], [917505, 3], [[917506, 917535], 3], [[917536, 917631], 3], [[917632, 917759], 3], [[917760, 917999], 7], [[918e3, 983037], 3], [[983038, 983039], 3], [[983040, 1048573], 3], [[1048574, 1048575], 3], [[1048576, 1114109], 3], [[1114110, 1114111], 3]]; } }); // netlify/functions/node_modules/tr46/lib/statusMapping.js var require_statusMapping = __commonJS({ "netlify/functions/node_modules/tr46/lib/statusMapping.js"(exports2, module2) { "use strict"; module2.exports.STATUS_MAPPING = { mapped: 1, valid: 2, disallowed: 3, deviation: 6, ignored: 7 }; } }); // netlify/functions/node_modules/tr46/index.js var require_tr46 = __commonJS({ "netlify/functions/node_modules/tr46/index.js"(exports2, module2) { "use strict"; var punycode = require_punycode(); var regexes = require_regexes(); var mappingTable = require_mappingTable(); var { STATUS_MAPPING } = require_statusMapping(); function containsNonASCII(str) { return /[^\x00-\x7F]/u.test(str); } function findStatus(val) { let start = 0; let end = mappingTable.length - 1; while (start <= end) { const mid = Math.floor((start + end) / 2); const target = mappingTable[mid]; const min = Array.isArray(target[0]) ? target[0][0] : target[0]; const max = Array.isArray(target[0]) ? target[0][1] : target[0]; if (min <= val && max >= val) { return target.slice(1); } else if (min > val) { end = mid - 1; } else { start = mid + 1; } } return null; } function mapChars(domainName, { transitionalProcessing }) { let processed = ""; for (const ch of domainName) { const [status, mapping] = findStatus(ch.codePointAt(0)); switch (status) { case STATUS_MAPPING.disallowed: processed += ch; break; case STATUS_MAPPING.ignored: break; case STATUS_MAPPING.mapped: if (transitionalProcessing && ch === "\u1E9E") { processed += "ss"; } else { processed += mapping; } break; case STATUS_MAPPING.deviation: if (transitionalProcessing) { processed += mapping; } else { processed += ch; } break; case STATUS_MAPPING.valid: processed += ch; break; } } return processed; } function validateLabel(label, { checkHyphens, checkBidi, checkJoiners, transitionalProcessing, useSTD3ASCIIRules, isBidi }) { if (label.length === 0) { return true; } if (label.normalize("NFC") !== label) { return false; } const codePoints = Array.from(label); if (checkHyphens) { if (codePoints[2] === "-" && codePoints[3] === "-" || (label.startsWith("-") || label.endsWith("-"))) { return false; } } if (!checkHyphens) { if (label.startsWith("xn--")) { return false; } } if (label.includes(".")) { return false; } if (regexes.combiningMarks.test(codePoints[0])) { return false; } for (const ch of codePoints) { const codePoint = ch.codePointAt(0); const [status] = findStatus(codePoint); if (transitionalProcessing) { if (status !== STATUS_MAPPING.valid) { return false; } } else if (status !== STATUS_MAPPING.valid && status !== STATUS_MAPPING.deviation) { return false; } if (useSTD3ASCIIRules && codePoint <= 127) { if (!/^(?:[a-z]|[0-9]|-)$/u.test(ch)) { return false; } } } if (checkJoiners) { let last = 0; for (const [i, ch] of codePoints.entries()) { if (ch === "\u200C" || ch === "\u200D") { if (i > 0) { if (regexes.combiningClassVirama.test(codePoints[i - 1])) { continue; } if (ch === "\u200C") { const next = codePoints.indexOf("\u200C", i + 1); const test = next < 0 ? codePoints.slice(last) : codePoints.slice(last, next); if (regexes.validZWNJ.test(test.join(""))) { last = i + 1; continue; } } } return false; } } } if (checkBidi && isBidi) { let rtl; if (regexes.bidiS1LTR.test(codePoints[0])) { rtl = false; } else if (regexes.bidiS1RTL.test(codePoints[0])) { rtl = true; } else { return false; } if (rtl) { if (!regexes.bidiS2.test(label) || !regexes.bidiS3.test(label) || regexes.bidiS4EN.test(label) && regexes.bidiS4AN.test(label)) { return false; } } else if (!regexes.bidiS5.test(label) || !regexes.bidiS6.test(label)) { return false; } } return true; } function isBidiDomain(labels) { const domain = labels.map((label) => { if (label.startsWith("xn--")) { try { return punycode.decode(label.substring(4)); } catch { return ""; } } return label; }).join("."); return regexes.bidiDomain.test(domain); } function processing(domainName, options) { let string = mapChars(domainName, options); string = string.normalize("NFC"); const labels = string.split("."); const isBidi = isBidiDomain(labels); let error = false; for (const [i, origLabel] of labels.entries()) { let label = origLabel; let transitionalProcessingForThisLabel = options.transitionalProcessing; if (label.startsWith("xn--")) { if (containsNonASCII(label)) { error = true; continue; } try { label = punycode.decode(label.substring(4)); } catch { if (!options.ignoreInvalidPunycode) { error = true; continue; } } labels[i] = label; if (label === "" || !containsNonASCII(label)) { error = true; } transitionalProcessingForThisLabel = false; } if (error) { continue; } const validation = validateLabel(label, { ...options, transitionalProcessing: transitionalProcessingForThisLabel, isBidi }); if (!validation) { error = true; } } return { string: labels.join("."), error }; } function toASCII(domainName, { checkHyphens = false, checkBidi = false, checkJoiners = false, useSTD3ASCIIRules = false, verifyDNSLength = false, transitionalProcessing = false, ignoreInvalidPunycode = false } = {}) { const result = processing(domainName, { checkHyphens, checkBidi, checkJoiners, useSTD3ASCIIRules, transitionalProcessing, ignoreInvalidPunycode }); let labels = result.string.split("."); labels = labels.map((l) => { if (containsNonASCII(l)) { try { return `xn--${punycode.encode(l)}`; } catch { result.error = true; } } return l; }); if (verifyDNSLength) { const total = labels.join(".").length; if (total > 253 || total === 0) { result.error = true; } for (let i = 0; i < labels.length; ++i) { if (labels[i].length > 63 || labels[i].length === 0) { result.error = true; break; } } } if (result.error) { return null; } return labels.join("."); } function toUnicode(domainName, { checkHyphens = false, checkBidi = false, checkJoiners = false, useSTD3ASCIIRules = false, transitionalProcessing = false, ignoreInvalidPunycode = false } = {}) { const result = processing(domainName, { checkHyphens, checkBidi, checkJoiners, useSTD3ASCIIRules, transitionalProcessing, ignoreInvalidPunycode }); return { domain: result.string, error: result.error }; } module2.exports = { toASCII, toUnicode }; } }); // netlify/functions/node_modules/whatwg-url/lib/infra.js var require_infra = __commonJS({ "netlify/functions/node_modules/whatwg-url/lib/infra.js"(exports2, module2) { "use strict"; function isASCIIDigit(c) { return c >= 48 && c <= 57; } function isASCIIAlpha(c) { return c >= 65 && c <= 90 || c >= 97 && c <= 122; } function isASCIIAlphanumeric(c) { return isASCIIAlpha(c) || isASCIIDigit(c); } function isASCIIHex(c) { return isASCIIDigit(c) || c >= 65 && c <= 70 || c >= 97 && c <= 102; } module2.exports = { isASCIIDigit, isASCIIAlpha, isASCIIAlphanumeric, isASCIIHex }; } }); // netlify/functions/node_modules/whatwg-url/lib/encoding.js var require_encoding = __commonJS({ "netlify/functions/node_modules/whatwg-url/lib/encoding.js"(exports2, module2) { "use strict"; var utf8Encoder = new TextEncoder(); var utf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true }); function utf8Encode(string) { return utf8Encoder.encode(string); } function utf8DecodeWithoutBOM(bytes) { return utf8Decoder.decode(bytes); } module2.exports = { utf8Encode, utf8DecodeWithoutBOM }; } }); // netlify/functions/node_modules/whatwg-url/lib/percent-encoding.js var require_percent_encoding = __commonJS({ "netlify/functions/node_modules/whatwg-url/lib/percent-encoding.js"(exports2, module2) { "use strict"; var { isASCIIHex } = require_infra(); var { utf8Encode } = require_encoding(); function p(char) { return char.codePointAt(0); } function percentEncode(c) { let hex = c.toString(16).toUpperCase(); if (hex.length === 1) { hex = `0${hex}`; } return `%${hex}`; } function percentDecodeBytes(input) { const output = new Uint8Array(input.byteLength); let outputIndex = 0; for (let i = 0; i < input.byteLength; ++i) { const byte = input[i]; if (byte !== 37) { output[outputIndex++] = byte; } else if (byte === 37 && (!isASCIIHex(input[i + 1]) || !isASCIIHex(input[i + 2]))) { output[outputIndex++] = byte; } else { const bytePoint = parseInt(String.fromCodePoint(input[i + 1], input[i + 2]), 16); output[outputIndex++] = bytePoint; i += 2; } } return output.slice(0, outputIndex); } function percentDecodeString(input) { const bytes = utf8Encode(input); return percentDecodeBytes(bytes); } function isC0ControlPercentEncode(c) { return c <= 31 || c > 126; } var extraFragmentPercentEncodeSet = /* @__PURE__ */ new Set([p(" "), p('"'), p("<"), p(">"), p("`")]); function isFragmentPercentEncode(c) { return isC0ControlPercentEncode(c) || extraFragmentPercentEncodeSet.has(c); } var extraQueryPercentEncodeSet = /* @__PURE__ */ new Set([p(" "), p('"'), p("#"), p("<"), p(">")]); function isQueryPercentEncode(c) { return isC0ControlPercentEncode(c) || extraQueryPercentEncodeSet.has(c); } function isSpecialQueryPercentEncode(c) { return isQueryPercentEncode(c) || c === p("'"); } var extraPathPercentEncodeSet = /* @__PURE__ */ new Set([p("?"), p("`"), p("{"), p("}"), p("^")]); function isPathPercentEncode(c) { return isQueryPercentEncode(c) || extraPathPercentEncodeSet.has(c); } var extraUserinfoPercentEncodeSet = /* @__PURE__ */ new Set([p("/"), p(":"), p(";"), p("="), p("@"), p("["), p("\\"), p("]"), p("|")]); function isUserinfoPercentEncode(c) { return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); } var extraComponentPercentEncodeSet = /* @__PURE__ */ new Set([p("$"), p("%"), p("&"), p("+"), p(",")]); function isComponentPercentEncode(c) { return isUserinfoPercentEncode(c) || extraComponentPercentEncodeSet.has(c); } var extraURLEncodedPercentEncodeSet = /* @__PURE__ */ new Set([p("!"), p("'"), p("("), p(")"), p("~")]); function isURLEncodedPercentEncode(c) { return isComponentPercentEncode(c) || extraURLEncodedPercentEncodeSet.has(c); } function utf8PercentEncodeCodePointInternal(codePoint, percentEncodePredicate) { const bytes = utf8Encode(codePoint); let output = ""; for (const byte of bytes) { if (!percentEncodePredicate(byte)) { output += String.fromCharCode(byte); } else { output += percentEncode(byte); } } return output; } function utf8PercentEncodeCodePoint(codePoint, percentEncodePredicate) { return utf8PercentEncodeCodePointInternal(String.fromCodePoint(codePoint), percentEncodePredicate); } function utf8PercentEncodeString(input, percentEncodePredicate, spaceAsPlus = false) { let output = ""; for (const codePoint of input) { if (spaceAsPlus && codePoint === " ") { output += "+"; } else { output += utf8PercentEncodeCodePointInternal(codePoint, percentEncodePredicate); } } return output; } module2.exports = { isC0ControlPercentEncode, isFragmentPercentEncode, isQueryPercentEncode, isSpecialQueryPercentEncode, isPathPercentEncode, isUserinfoPercentEncode, isURLEncodedPercentEncode, percentDecodeString, percentDecodeBytes, utf8PercentEncodeString, utf8PercentEncodeCodePoint }; } }); // netlify/functions/node_modules/whatwg-url/lib/url-state-machine.js var require_url_state_machine = __commonJS({ "netlify/functions/node_modules/whatwg-url/lib/url-state-machine.js"(exports2, module2) { "use strict"; var tr46 = require_tr46(); var infra = require_infra(); var { utf8DecodeWithoutBOM } = require_encoding(); var { percentDecodeString, utf8PercentEncodeCodePoint, utf8PercentEncodeString, isC0ControlPercentEncode, isFragmentPercentEncode, isQueryPercentEncode, isSpecialQueryPercentEncode, isPathPercentEncode, isUserinfoPercentEncode } = require_percent_encoding(); function p(char) { return char.codePointAt(0); } var specialSchemes = { ftp: 21, file: null, http: 80, https: 443, ws: 80, wss: 443 }; var failure = Symbol("failure"); function countSymbols(str) { return [...str].length; } function at(input, idx) { const c = input[idx]; return isNaN(c) ? void 0 : String.fromCodePoint(c); } function isSingleDot(buffer) { return buffer === "." || buffer.toLowerCase() === "%2e"; } function isDoubleDot(buffer) { buffer = buffer.toLowerCase(); return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; } function isWindowsDriveLetterCodePoints(cp1, cp2) { return infra.isASCIIAlpha(cp1) && (cp2 === p(":") || cp2 === p("|")); } function isWindowsDriveLetterString(string) { return string.length === 2 && infra.isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); } function isNormalizedWindowsDriveLetterString(string) { return string.length === 2 && infra.isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; } function containsForbiddenHostCodePoint(string) { return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u) !== -1; } function containsForbiddenDomainCodePoint(string) { return containsForbiddenHostCodePoint(string) || string.search(/[\u0000-\u001F]|%|\u007F/u) !== -1; } function isSpecialScheme(scheme) { return specialSchemes[scheme] !== void 0; } function isSpecial(url) { return isSpecialScheme(url.scheme); } function isNotSpecial(url) { return !isSpecialScheme(url.scheme); } function defaultPort(scheme) { return specialSchemes[scheme]; } function parseIPv4Number(input) { if (input === "") { return failure; } let R = 10; if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { input = input.substring(2); R = 16; } else if (input.length >= 2 && input.charAt(0) === "0") { input = input.substring(1); R = 8; } if (input === "") { return 0; } let regex = /[^0-7]/u; if (R === 10) { regex = /[^0-9]/u; } if (R === 16) { regex = /[^0-9A-Fa-f]/u; } if (regex.test(input)) { return failure; } return parseInt(input, R); } function parseIPv4(input) { const parts = input.split("."); if (parts[parts.length - 1] === "") { if (parts.length > 1) { parts.pop(); } } if (parts.length > 4) { return failure; } const numbers = []; for (const part of parts) { const n = parseIPv4Number(part); if (n === failure) { return failure; } numbers.push(n); } for (let i = 0; i < numbers.length - 1; ++i) { if (numbers[i] > 255) { return failure; } } if (numbers[numbers.length - 1] >= 256 ** (5 - numbers.length)) { return failure; } let ipv4 = numbers.pop(); let counter = 0; for (const n of numbers) { ipv4 += n * 256 ** (3 - counter); ++counter; } return ipv4; } function serializeIPv4(address) { let output = ""; let n = address; for (let i = 1; i <= 4; ++i) { output = String(n % 256) + output; if (i !== 4) { output = `.${output}`; } n = Math.floor(n / 256); } return output; } function parseIPv6(input) { const address = [0, 0, 0, 0, 0, 0, 0, 0]; let pieceIndex = 0; let compress = null; let pointer = 0; input = Array.from(input, (c) => c.codePointAt(0)); if (input[pointer] === p(":")) { if (input[pointer + 1] !== p(":")) { return failure; } pointer += 2; ++pieceIndex; compress = pieceIndex; } while (pointer < input.length) { if (pieceIndex === 8) { return failure; } if (input[pointer] === p(":")) { if (compress !== null) { return failure; } ++pointer; ++pieceIndex; compress = pieceIndex; continue; } let value = 0; let length = 0; while (length < 4 && infra.isASCIIHex(input[pointer])) { value = value * 16 + parseInt(at(input, pointer), 16); ++pointer; ++length; } if (input[pointer] === p(".")) { if (length === 0) { return failure; } pointer -= length; if (pieceIndex > 6) { return failure; } let numbersSeen = 0; while (input[pointer] !== void 0) { let ipv4Piece = null; if (numbersSeen > 0) { if (input[pointer] === p(".") && numbersSeen < 4) { ++pointer; } else { return failure; } } if (!infra.isASCIIDigit(input[pointer])) { return failure; } while (infra.isASCIIDigit(input[pointer])) { const number = parseInt(at(input, pointer)); if (ipv4Piece === null) { ipv4Piece = number; } else if (ipv4Piece === 0) { return failure; } else { ipv4Piece = ipv4Piece * 10 + number; } if (ipv4Piece > 255) { return failure; } ++pointer; } address[pieceIndex] = address[pieceIndex] * 256 + ipv4Piece; ++numbersSeen; if (numbersSeen === 2 || numbersSeen === 4) { ++pieceIndex; } } if (numbersSeen !== 4) { return failure; } break; } else if (input[pointer] === p(":")) { ++pointer; if (input[pointer] === void 0) { return failure; } } else if (input[pointer] !== void 0) { return failure; } address[pieceIndex] = value; ++pieceIndex; } if (compress !== null) { let swaps = pieceIndex - compress; pieceIndex = 7; while (pieceIndex !== 0 && swaps > 0) { const temp = address[compress + swaps - 1]; address[compress + swaps - 1] = address[pieceIndex]; address[pieceIndex] = temp; --pieceIndex; --swaps; } } else if (compress === null && pieceIndex !== 8) { return failure; } return address; } function serializeIPv6(address) { let output = ""; const compress = findTheIPv6AddressCompressedPieceIndex(address); let ignore0 = false; for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { if (ignore0 && address[pieceIndex] === 0) { continue; } else if (ignore0) { ignore0 = false; } if (compress === pieceIndex) { const separator = pieceIndex === 0 ? "::" : ":"; output += separator; ignore0 = true; continue; } output += address[pieceIndex].toString(16); if (pieceIndex !== 7) { output += ":"; } } return output; } function parseHost(input, isOpaque = false) { if (input[0] === "[") { if (input[input.length - 1] !== "]") { return failure; } return parseIPv6(input.substring(1, input.length - 1)); } if (isOpaque) { return parseOpaqueHost(input); } const domain = utf8DecodeWithoutBOM(percentDecodeString(input)); const asciiDomain = domainToASCII(domain); if (asciiDomain === failure) { return failure; } if (endsInANumber(asciiDomain)) { return parseIPv4(asciiDomain); } return asciiDomain; } function endsInANumber(input) { const parts = input.split("."); if (parts[parts.length - 1] === "") { if (parts.length === 1) { return false; } parts.pop(); } const last = parts[parts.length - 1]; if (parseIPv4Number(last) !== failure) { return true; } if (/^[0-9]+$/u.test(last)) { return true; } return false; } function parseOpaqueHost(input) { if (containsForbiddenHostCodePoint(input)) { return failure; } return utf8PercentEncodeString(input, isC0ControlPercentEncode); } function findTheIPv6AddressCompressedPieceIndex(address) { let longestIndex = null; let longestSize = 1; let foundIndex = null; let foundSize = 0; for (let pieceIndex = 0; pieceIndex < address.length; ++pieceIndex) { if (address[pieceIndex] !== 0) { if (foundSize > longestSize) { longestIndex = foundIndex; longestSize = foundSize; } foundIndex = null; foundSize = 0; } else { if (foundIndex === null) { foundIndex = pieceIndex; } ++foundSize; } } if (foundSize > longestSize) { return foundIndex; } return longestIndex; } function serializeHost(host) { if (typeof host === "number") { return serializeIPv4(host); } if (host instanceof Array) { return `[${serializeIPv6(host)}]`; } return host; } function domainToASCII(domain, beStrict = false) { const result = tr46.toASCII(domain, { checkHyphens: beStrict, checkBidi: true, checkJoiners: true, useSTD3ASCIIRules: beStrict, transitionalProcessing: false, verifyDNSLength: beStrict, ignoreInvalidPunycode: false }); if (result === null) { return failure; } if (!beStrict) { if (result === "") { return failure; } if (containsForbiddenDomainCodePoint(result)) { return failure; } } return result; } function trimControlChars(string) { let start = 0; let end = string.length; for (; start < end; ++start) { if (string.charCodeAt(start) > 32) { break; } } for (; end > start; --end) { if (string.charCodeAt(end - 1) > 32) { break; } } return string.substring(start, end); } function trimTabAndNewline(url) { return url.replace(/\u0009|\u000A|\u000D/ug, ""); } function shortenPath(url) { const { path } = url; if (path.length === 0) { return; } if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { return; } path.pop(); } function includesCredentials(url) { return url.username !== "" || url.password !== ""; } function cannotHaveAUsernamePasswordPort(url) { return url.host === null || url.host === "" || url.scheme === "file"; } function hasAnOpaquePath(url) { return typeof url.path === "string"; } function isNormalizedWindowsDriveLetter(string) { return /^[A-Za-z]:$/u.test(string); } function URLStateMachine(input, base, encodingOverride, url, stateOverride) { this.pointer = 0; this.input = input; this.base = base || null; this.encodingOverride = encodingOverride || "utf-8"; this.stateOverride = stateOverride; this.url = url; this.failure = false; this.parseError = false; if (!this.url) { this.url = { scheme: "", username: "", password: "", host: null, port: null, path: [], query: null, fragment: null }; const res2 = trimControlChars(this.input); if (res2 !== this.input) { this.parseError = true; } this.input = res2; } const res = trimTabAndNewline(this.input); if (res !== this.input) { this.parseError = true; } this.input = res; this.state = stateOverride || "scheme start"; this.buffer = ""; this.atFlag = false; this.arrFlag = false; this.passwordTokenSeenFlag = false; this.input = Array.from(this.input, (c) => c.codePointAt(0)); for (; this.pointer <= this.input.length; ++this.pointer) { const c = this.input[this.pointer]; const cStr = isNaN(c) ? void 0 : String.fromCodePoint(c); const ret = this[`parse ${this.state}`](c, cStr); if (!ret) { break; } else if (ret === failure) { this.failure = true; break; } } } URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { if (infra.isASCIIAlpha(c)) { this.buffer += cStr.toLowerCase(); this.state = "scheme"; } else if (!this.stateOverride) { this.state = "no scheme"; --this.pointer; } else { this.parseError = true; return failure; } return true; }; URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { if (infra.isASCIIAlphanumeric(c) || c === p("+") || c === p("-") || c === p(".")) { this.buffer += cStr.toLowerCase(); } else if (c === p(":")) { if (this.stateOverride) { if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { return false; } if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { return false; } if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { return false; } if (this.url.scheme === "file" && this.url.host === "") { return false; } } this.url.scheme = this.buffer; if (this.stateOverride) { if (this.url.port === defaultPort(this.url.scheme)) { this.url.port = null; } return false; } this.buffer = ""; if (this.url.scheme === "file") { if (this.input[this.pointer + 1] !== p("/") || this.input[this.pointer + 2] !== p("/")) { this.parseError = true; } this.state = "file"; } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { this.state = "special relative or authority"; } else if (isSpecial(this.url)) { this.state = "special authority slashes"; } else if (this.input[this.pointer + 1] === p("/")) { this.state = "path or authority"; ++this.pointer; } else { this.url.path = ""; this.state = "opaque path"; } } else if (!this.stateOverride) { this.buffer = ""; this.state = "no scheme"; this.pointer = -1; } else { this.parseError = true; return failure; } return true; }; URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { if (this.base === null || hasAnOpaquePath(this.base) && c !== p("#")) { return failure; } else if (hasAnOpaquePath(this.base) && c === p("#")) { this.url.scheme = this.base.scheme; this.url.path = this.base.path; this.url.query = this.base.query; this.url.fragment = ""; this.state = "fragment"; } else if (this.base.scheme === "file") { this.state = "file"; --this.pointer; } else { this.state = "relative"; --this.pointer; } return true; }; URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { if (c === p("/") && this.input[this.pointer + 1] === p("/")) { this.state = "special authority ignore slashes"; ++this.pointer; } else { this.parseError = true; this.state = "relative"; --this.pointer; } return true; }; URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { if (c === p("/")) { this.state = "authority"; } else { this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse relative"] = function parseRelative(c) { this.url.scheme = this.base.scheme; if (c === p("/")) { this.state = "relative slash"; } else if (isSpecial(this.url) && c === p("\\")) { this.parseError = true; this.state = "relative slash"; } else { this.url.username = this.base.username; this.url.password = this.base.password; this.url.host = this.base.host; this.url.port = this.base.port; this.url.path = this.base.path.slice(); this.url.query = this.base.query; if (c === p("?")) { this.url.query = ""; this.state = "query"; } else if (c === p("#")) { this.url.fragment = ""; this.state = "fragment"; } else if (!isNaN(c)) { this.url.query = null; this.url.path.pop(); this.state = "path"; --this.pointer; } } return true; }; URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { if (isSpecial(this.url) && (c === p("/") || c === p("\\"))) { if (c === p("\\")) { this.parseError = true; } this.state = "special authority ignore slashes"; } else if (c === p("/")) { this.state = "authority"; } else { this.url.username = this.base.username; this.url.password = this.base.password; this.url.host = this.base.host; this.url.port = this.base.port; this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { if (c === p("/") && this.input[this.pointer + 1] === p("/")) { this.state = "special authority ignore slashes"; ++this.pointer; } else { this.parseError = true; this.state = "special authority ignore slashes"; --this.pointer; } return true; }; URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { if (c !== p("/") && c !== p("\\")) { this.state = "authority"; --this.pointer; } else { this.parseError = true; } return true; }; URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { if (c === p("@")) { this.parseError = true; if (this.atFlag) { this.buffer = `%40${this.buffer}`; } this.atFlag = true; const len = countSymbols(this.buffer); for (let pointer = 0; pointer < len; ++pointer) { const codePoint = this.buffer.codePointAt(pointer); if (codePoint === p(":") && !this.passwordTokenSeenFlag) { this.passwordTokenSeenFlag = true; continue; } const encodedCodePoints = utf8PercentEncodeCodePoint(codePoint, isUserinfoPercentEncode); if (this.passwordTokenSeenFlag) { this.url.password += encodedCodePoints; } else { this.url.username += encodedCodePoints; } } this.buffer = ""; } else if (isNaN(c) || c === p("/") || c === p("?") || c === p("#") || isSpecial(this.url) && c === p("\\")) { if (this.atFlag && this.buffer === "") { this.parseError = true; return failure; } this.pointer -= countSymbols(this.buffer) + 1; this.buffer = ""; this.state = "host"; } else { this.buffer += cStr; } return true; }; URLStateMachine.prototype["parse hostname"] = URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { if (this.stateOverride && this.url.scheme === "file") { --this.pointer; this.state = "file host"; } else if (c === p(":") && !this.arrFlag) { if (this.buffer === "") { this.parseError = true; return failure; } if (this.stateOverride === "hostname") { return false; } const host = parseHost(this.buffer, isNotSpecial(this.url)); if (host === failure) { return failure; } this.url.host = host; this.buffer = ""; this.state = "port"; } else if (isNaN(c) || c === p("/") || c === p("?") || c === p("#") || isSpecial(this.url) && c === p("\\")) { --this.pointer; if (isSpecial(this.url) && this.buffer === "") { this.parseError = true; return failure; } else if (this.stateOverride && this.buffer === "" && (includesCredentials(this.url) || this.url.port !== null)) { this.parseError = true; return false; } const host = parseHost(this.buffer, isNotSpecial(this.url)); if (host === failure) { return failure; } this.url.host = host; this.buffer = ""; this.state = "path start"; if (this.stateOverride) { return false; } } else { if (c === p("[")) { this.arrFlag = true; } else if (c === p("]")) { this.arrFlag = false; } this.buffer += cStr; } return true; }; URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { if (infra.isASCIIDigit(c)) { this.buffer += cStr; } else if (isNaN(c) || c === p("/") || c === p("?") || c === p("#") || isSpecial(this.url) && c === p("\\") || this.stateOverride) { if (this.buffer !== "") { const port = parseInt(this.buffer); if (port > 2 ** 16 - 1) { this.parseError = true; return failure; } this.url.port = port === defaultPort(this.url.scheme) ? null : port; this.buffer = ""; } if (this.stateOverride) { return false; } this.state = "path start"; --this.pointer; } else { this.parseError = true; return failure; } return true; }; var fileOtherwiseCodePoints = /* @__PURE__ */ new Set([p("/"), p("\\"), p("?"), p("#")]); function startsWithWindowsDriveLetter(input, pointer) { const length = input.length - pointer; return length >= 2 && isWindowsDriveLetterCodePoints(input[pointer], input[pointer + 1]) && (length === 2 || fileOtherwiseCodePoints.has(input[pointer + 2])); } URLStateMachine.prototype["parse file"] = function parseFile(c) { this.url.scheme = "file"; this.url.host = ""; if (c === p("/") || c === p("\\")) { if (c === p("\\")) { this.parseError = true; } this.state = "file slash"; } else if (this.base !== null && this.base.scheme === "file") { this.url.host = this.base.host; this.url.path = this.base.path.slice(); this.url.query = this.base.query; if (c === p("?")) { this.url.query = ""; this.state = "query"; } else if (c === p("#")) { this.url.fragment = ""; this.state = "fragment"; } else if (!isNaN(c)) { this.url.query = null; if (!startsWithWindowsDriveLetter(this.input, this.pointer)) { shortenPath(this.url); } else { this.parseError = true; this.url.path = []; } this.state = "path"; --this.pointer; } } else { this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { if (c === p("/") || c === p("\\")) { if (c === p("\\")) { this.parseError = true; } this.state = "file host"; } else { if (this.base !== null && this.base.scheme === "file") { if (!startsWithWindowsDriveLetter(this.input, this.pointer) && isNormalizedWindowsDriveLetterString(this.base.path[0])) { this.url.path.push(this.base.path[0]); } this.url.host = this.base.host; } this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { if (isNaN(c) || c === p("/") || c === p("\\") || c === p("?") || c === p("#")) { --this.pointer; if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { this.parseError = true; this.state = "path"; } else if (this.buffer === "") { this.url.host = ""; if (this.stateOverride) { return false; } this.state = "path start"; } else { let host = parseHost(this.buffer, isNotSpecial(this.url)); if (host === failure) { return failure; } if (host === "localhost") { host = ""; } this.url.host = host; if (this.stateOverride) { return false; } this.buffer = ""; this.state = "path start"; } } else { this.buffer += cStr; } return true; }; URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { if (isSpecial(this.url)) { if (c === p("\\")) { this.parseError = true; } this.state = "path"; if (c !== p("/") && c !== p("\\")) { --this.pointer; } } else if (!this.stateOverride && c === p("?")) { this.url.query = ""; this.state = "query"; } else if (!this.stateOverride && c === p("#")) { this.url.fragment = ""; this.state = "fragment"; } else if (c !== void 0) { this.state = "path"; if (c !== p("/")) { --this.pointer; } } else if (this.stateOverride && this.url.host === null) { this.url.path.push(""); } return true; }; URLStateMachine.prototype["parse path"] = function parsePath(c) { if (isNaN(c) || c === p("/") || isSpecial(this.url) && c === p("\\") || !this.stateOverride && (c === p("?") || c === p("#"))) { if (isSpecial(this.url) && c === p("\\")) { this.parseError = true; } if (isDoubleDot(this.buffer)) { shortenPath(this.url); if (c !== p("/") && !(isSpecial(this.url) && c === p("\\"))) { this.url.path.push(""); } } else if (isSingleDot(this.buffer) && c !== p("/") && !(isSpecial(this.url) && c === p("\\"))) { this.url.path.push(""); } else if (!isSingleDot(this.buffer)) { if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { this.buffer = `${this.buffer[0]}:`; } this.url.path.push(this.buffer); } this.buffer = ""; if (c === p("?")) { this.url.query = ""; this.state = "query"; } if (c === p("#")) { this.url.fragment = ""; this.state = "fragment"; } } else { if (c === p("%") && (!infra.isASCIIHex(this.input[this.pointer + 1]) || !infra.isASCIIHex(this.input[this.pointer + 2]))) { this.parseError = true; } this.buffer += utf8PercentEncodeCodePoint(c, isPathPercentEncode); } return true; }; URLStateMachine.prototype["parse opaque path"] = function parseOpaquePath(c) { if (c === p("?")) { this.url.query = ""; this.state = "query"; } else if (c === p("#")) { this.url.fragment = ""; this.state = "fragment"; } else if (c === p(" ")) { const remaining = this.input[this.pointer + 1]; if (remaining === p("?") || remaining === p("#")) { this.url.path += "%20"; } else { this.url.path += " "; } } else { if (!isNaN(c) && c !== p("%")) { this.parseError = true; } if (c === p("%") && (!infra.isASCIIHex(this.input[this.pointer + 1]) || !infra.isASCIIHex(this.input[this.pointer + 2]))) { this.parseError = true; } if (!isNaN(c)) { this.url.path += utf8PercentEncodeCodePoint(c, isC0ControlPercentEncode); } } return true; }; URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { this.encodingOverride = "utf-8"; } if (!this.stateOverride && c === p("#") || isNaN(c)) { const queryPercentEncodePredicate = isSpecial(this.url) ? isSpecialQueryPercentEncode : isQueryPercentEncode; this.url.query += utf8PercentEncodeString(this.buffer, queryPercentEncodePredicate); this.buffer = ""; if (c === p("#")) { this.url.fragment = ""; this.state = "fragment"; } } else if (!isNaN(c)) { if (c === p("%") && (!infra.isASCIIHex(this.input[this.pointer + 1]) || !infra.isASCIIHex(this.input[this.pointer + 2]))) { this.parseError = true; } this.buffer += cStr; } return true; }; URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { if (!isNaN(c)) { if (c === p("%") && (!infra.isASCIIHex(this.input[this.pointer + 1]) || !infra.isASCIIHex(this.input[this.pointer + 2]))) { this.parseError = true; } this.url.fragment += utf8PercentEncodeCodePoint(c, isFragmentPercentEncode); } return true; }; function serializeURL(url, excludeFragment) { let output = `${url.scheme}:`; if (url.host !== null) { output += "//"; if (url.username !== "" || url.password !== "") { output += url.username; if (url.password !== "") { output += `:${url.password}`; } output += "@"; } output += serializeHost(url.host); if (url.port !== null) { output += `:${url.port}`; } } if (url.host === null && !hasAnOpaquePath(url) && url.path.length > 1 && url.path[0] === "") { output += "/."; } output += serializePath(url); if (url.query !== null) { output += `?${url.query}`; } if (!excludeFragment && url.fragment !== null) { output += `#${url.fragment}`; } return output; } function serializeOrigin(tuple) { let result = `${tuple.scheme}://`; result += serializeHost(tuple.host); if (tuple.port !== null) { result += `:${tuple.port}`; } return result; } function serializePath(url) { if (hasAnOpaquePath(url)) { return url.path; } let output = ""; for (const segment of url.path) { output += `/${segment}`; } return output; } module2.exports.serializeURL = serializeURL; module2.exports.serializePath = serializePath; module2.exports.serializeURLOrigin = function(url) { switch (url.scheme) { case "blob": { const pathURL = module2.exports.parseURL(serializePath(url)); if (pathURL === null) { return "null"; } if (pathURL.scheme !== "http" && pathURL.scheme !== "https") { return "null"; } return module2.exports.serializeURLOrigin(pathURL); } case "ftp": case "http": case "https": case "ws": case "wss": return serializeOrigin({ scheme: url.scheme, host: url.host, port: url.port }); case "file": return "null"; default: return "null"; } }; module2.exports.basicURLParse = function(input, options) { if (options === void 0) { options = {}; } const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); if (usm.failure) { return null; } return usm.url; }; module2.exports.setTheUsername = function(url, username) { url.username = utf8PercentEncodeString(username, isUserinfoPercentEncode); }; module2.exports.setThePassword = function(url, password) { url.password = utf8PercentEncodeString(password, isUserinfoPercentEncode); }; module2.exports.serializeHost = serializeHost; module2.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; module2.exports.hasAnOpaquePath = hasAnOpaquePath; module2.exports.serializeInteger = function(integer) { return String(integer); }; module2.exports.parseURL = function(input, options) { if (options === void 0) { options = {}; } return module2.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); }; } }); // netlify/functions/node_modules/whatwg-url/lib/urlencoded.js var require_urlencoded = __commonJS({ "netlify/functions/node_modules/whatwg-url/lib/urlencoded.js"(exports2, module2) { "use strict"; var { utf8Encode, utf8DecodeWithoutBOM } = require_encoding(); var { percentDecodeBytes, utf8PercentEncodeString, isURLEncodedPercentEncode } = require_percent_encoding(); function p(char) { return char.codePointAt(0); } function parseUrlencoded(input) { const sequences = strictlySplitByteSequence(input, p("&")); const output = []; for (const bytes of sequences) { if (bytes.length === 0) { continue; } let name, value; const indexOfEqual = bytes.indexOf(p("=")); if (indexOfEqual >= 0) { name = bytes.slice(0, indexOfEqual); value = bytes.slice(indexOfEqual + 1); } else { name = bytes; value = new Uint8Array(0); } name = replaceByteInByteSequence(name, 43, 32); value = replaceByteInByteSequence(value, 43, 32); const nameString = utf8DecodeWithoutBOM(percentDecodeBytes(name)); const valueString = utf8DecodeWithoutBOM(percentDecodeBytes(value)); output.push([nameString, valueString]); } return output; } function parseUrlencodedString(input) { return parseUrlencoded(utf8Encode(input)); } function serializeUrlencoded(tuples) { let output = ""; for (const [i, tuple] of tuples.entries()) { const name = utf8PercentEncodeString(tuple[0], isURLEncodedPercentEncode, true); const value = utf8PercentEncodeString(tuple[1], isURLEncodedPercentEncode, true); if (i !== 0) { output += "&"; } output += `${name}=${value}`; } return output; } function strictlySplitByteSequence(buf, cp) { const list = []; let last = 0; let i = buf.indexOf(cp); while (i >= 0) { list.push(buf.slice(last, i)); last = i + 1; i = buf.indexOf(cp, last); } if (last !== buf.length) { list.push(buf.slice(last)); } return list; } function replaceByteInByteSequence(buf, from, to) { let i = buf.indexOf(from); while (i >= 0) { buf[i] = to; i = buf.indexOf(from, i + 1); } return buf; } module2.exports = { parseUrlencodedString, serializeUrlencoded }; } }); // netlify/functions/node_modules/whatwg-url/lib/Function.js var require_Function = __commonJS({ "netlify/functions/node_modules/whatwg-url/lib/Function.js"(exports2) { "use strict"; var conversions = require_lib(); var utils = require_utils2(); exports2.convert = (globalObject, value, { context = "The provided value" } = {}) => { if (typeof value !== "function") { throw new globalObject.TypeError(context + " is not a function"); } function invokeTheCallbackFunction(...args) { const thisArg = utils.tryWrapperForImpl(this); let callResult; for (let i = 0; i < args.length; i++) { args[i] = utils.tryWrapperForImpl(args[i]); } callResult = Reflect.apply(value, thisArg, args); callResult = conversions["any"](callResult, { context, globals: globalObject }); return callResult; } invokeTheCallbackFunction.construct = (...args) => { for (let i = 0; i < args.length; i++) { args[i] = utils.tryWrapperForImpl(args[i]); } let callResult = Reflect.construct(value, args); callResult = conversions["any"](callResult, { context, globals: globalObject }); return callResult; }; invokeTheCallbackFunction[utils.wrapperSymbol] = value; invokeTheCallbackFunction.objectReference = value; return invokeTheCallbackFunction; }; } }); // netlify/functions/node_modules/whatwg-url/lib/URLSearchParams-impl.js var require_URLSearchParams_impl = __commonJS({ "netlify/functions/node_modules/whatwg-url/lib/URLSearchParams-impl.js"(exports2) { "use strict"; var urlencoded = require_urlencoded(); exports2.implementation = class URLSearchParamsImpl { constructor(globalObject, constructorArgs, { doNotStripQMark = false }) { let init = constructorArgs[0]; this._list = []; this._url = null; if (!doNotStripQMark && typeof init === "string" && init[0] === "?") { init = init.slice(1); } if (Array.isArray(init)) { for (const pair of init) { if (pair.length !== 2) { throw new TypeError("Failed to construct 'URLSearchParams': parameter 1 sequence's element does not contain exactly two elements."); } this._list.push([pair[0], pair[1]]); } } else if (typeof init === "object" && Object.getPrototypeOf(init) === null) { for (const name of Object.keys(init)) { const value = init[name]; this._list.push([name, value]); } } else { this._list = urlencoded.parseUrlencodedString(init); } } _updateSteps() { if (this._url !== null) { let serializedQuery = urlencoded.serializeUrlencoded(this._list); if (serializedQuery === "") { serializedQuery = null; } this._url._url.query = serializedQuery; } } get size() { return this._list.length; } append(name, value) { this._list.push([name, value]); this._updateSteps(); } delete(name, value) { let i = 0; while (i < this._list.length) { if (this._list[i][0] === name && (value === void 0 || this._list[i][1] === value)) { this._list.splice(i, 1); } else { i++; } } this._updateSteps(); } get(name) { for (const tuple of this._list) { if (tuple[0] === name) { return tuple[1]; } } return null; } getAll(name) { const output = []; for (const tuple of this._list) { if (tuple[0] === name) { output.push(tuple[1]); } } return output; } has(name, value) { for (const tuple of this._list) { if (tuple[0] === name && (value === void 0 || tuple[1] === value)) { return true; } } return false; } set(name, value) { let found = false; let i = 0; while (i < this._list.length) { if (this._list[i][0] === name) { if (found) { this._list.splice(i, 1); } else { found = true; this._list[i][1] = value; i++; } } else { i++; } } if (!found) { this._list.push([name, value]); } this._updateSteps(); } sort() { this._list.sort((a, b) => { if (a[0] < b[0]) { return -1; } if (a[0] > b[0]) { return 1; } return 0; }); this._updateSteps(); } [Symbol.iterator]() { return this._list[Symbol.iterator](); } toString() { return urlencoded.serializeUrlencoded(this._list); } }; } }); // netlify/functions/node_modules/whatwg-url/lib/URLSearchParams.js var require_URLSearchParams = __commonJS({ "netlify/functions/node_modules/whatwg-url/lib/URLSearchParams.js"(exports2) { "use strict"; var conversions = require_lib(); var utils = require_utils2(); var Function2 = require_Function(); var newObjectInRealm = utils.newObjectInRealm; var implSymbol = utils.implSymbol; var ctorRegistrySymbol = utils.ctorRegistrySymbol; var interfaceName = "URLSearchParams"; exports2.is = (value) => { return utils.isObject(value) && utils.hasOwn(value, implSymbol) && value[implSymbol] instanceof Impl.implementation; }; exports2.isImpl = (value) => { return utils.isObject(value) && value instanceof Impl.implementation; }; exports2.convert = (globalObject, value, { context = "The provided value" } = {}) => { if (exports2.is(value)) { return utils.implForWrapper(value); } throw new globalObject.TypeError(`${context} is not of type 'URLSearchParams'.`); }; exports2.createDefaultIterator = (globalObject, target, kind) => { const ctorRegistry = globalObject[ctorRegistrySymbol]; const iteratorPrototype = ctorRegistry["URLSearchParams Iterator"]; const iterator = Object.create(iteratorPrototype); Object.defineProperty(iterator, utils.iterInternalSymbol, { value: { target, kind, index: 0 }, configurable: true }); return iterator; }; function makeWrapper(globalObject, newTarget) { let proto; if (newTarget !== void 0) { proto = newTarget.prototype; } if (!utils.isObject(proto)) { proto = globalObject[ctorRegistrySymbol]["URLSearchParams"].prototype; } return Object.create(proto); } exports2.create = (globalObject, constructorArgs, privateData) => { const wrapper = makeWrapper(globalObject); return exports2.setup(wrapper, globalObject, constructorArgs, privateData); }; exports2.createImpl = (globalObject, constructorArgs, privateData) => { const wrapper = exports2.create(globalObject, constructorArgs, privateData); return utils.implForWrapper(wrapper); }; exports2._internalSetup = (wrapper, globalObject) => { }; exports2.setup = (wrapper, globalObject, constructorArgs = [], privateData = {}) => { privateData.wrapper = wrapper; exports2._internalSetup(wrapper, globalObject); Object.defineProperty(wrapper, implSymbol, { value: new Impl.implementation(globalObject, constructorArgs, privateData), configurable: true }); wrapper[implSymbol][utils.wrapperSymbol] = wrapper; if (Impl.init) { Impl.init(wrapper[implSymbol]); } return wrapper; }; exports2.new = (globalObject, newTarget) => { const wrapper = makeWrapper(globalObject, newTarget); exports2._internalSetup(wrapper, globalObject); Object.defineProperty(wrapper, implSymbol, { value: Object.create(Impl.implementation.prototype), configurable: true }); wrapper[implSymbol][utils.wrapperSymbol] = wrapper; if (Impl.init) { Impl.init(wrapper[implSymbol]); } return wrapper[implSymbol]; }; var exposed = /* @__PURE__ */ new Set(["Window", "Worker"]); exports2.install = (globalObject, globalNames) => { if (!globalNames.some((globalName) => exposed.has(globalName))) { return; } const ctorRegistry = utils.initCtorRegistry(globalObject); class URLSearchParams { constructor() { const args = []; { let curArg = arguments[0]; if (curArg !== void 0) { if (utils.isObject(curArg)) { if (curArg[Symbol.iterator] !== void 0) { if (!utils.isObject(curArg)) { throw new globalObject.TypeError( "Failed to construct 'URLSearchParams': parameter 1 sequence is not an iterable object." ); } else { const V = []; const tmp = curArg; for (let nextItem of tmp) { if (!utils.isObject(nextItem)) { throw new globalObject.TypeError( "Failed to construct 'URLSearchParams': parameter 1 sequence's element is not an iterable object." ); } else { const V2 = []; const tmp2 = nextItem; for (let nextItem2 of tmp2) { nextItem2 = conversions["USVString"](nextItem2, { context: "Failed to construct 'URLSearchParams': parameter 1 sequence's element's element", globals: globalObject }); V2.push(nextItem2); } nextItem = V2; } V.push(nextItem); } curArg = V; } } else { if (!utils.isObject(curArg)) { throw new globalObject.TypeError( "Failed to construct 'URLSearchParams': parameter 1 record is not an object." ); } else { const result = /* @__PURE__ */ Object.create(null); for (const key of Reflect.ownKeys(curArg)) { const desc = Object.getOwnPropertyDescriptor(curArg, key); if (desc && desc.enumerable) { let typedKey = key; typedKey = conversions["USVString"](typedKey, { context: "Failed to construct 'URLSearchParams': parameter 1 record's key", globals: globalObject }); let typedValue = curArg[key]; typedValue = conversions["USVString"](typedValue, { context: "Failed to construct 'URLSearchParams': parameter 1 record's value", globals: globalObject }); result[typedKey] = typedValue; } } curArg = result; } } } else { curArg = conversions["USVString"](curArg, { context: "Failed to construct 'URLSearchParams': parameter 1", globals: globalObject }); } } else { curArg = ""; } args.push(curArg); } return exports2.setup(Object.create(new.target.prototype), globalObject, args); } append(name, value) { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError( "'append' called on an object that is not a valid instance of URLSearchParams." ); } if (arguments.length < 2) { throw new globalObject.TypeError( `Failed to execute 'append' on 'URLSearchParams': 2 arguments required, but only ${arguments.length} present.` ); } const args = []; { let curArg = arguments[0]; curArg = conversions["USVString"](curArg, { context: "Failed to execute 'append' on 'URLSearchParams': parameter 1", globals: globalObject }); args.push(curArg); } { let curArg = arguments[1]; curArg = conversions["USVString"](curArg, { context: "Failed to execute 'append' on 'URLSearchParams': parameter 2", globals: globalObject }); args.push(curArg); } return utils.tryWrapperForImpl(esValue[implSymbol].append(...args)); } delete(name) { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError( "'delete' called on an object that is not a valid instance of URLSearchParams." ); } if (arguments.length < 1) { throw new globalObject.TypeError( `Failed to execute 'delete' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.` ); } const args = []; { let curArg = arguments[0]; curArg = conversions["USVString"](curArg, { context: "Failed to execute 'delete' on 'URLSearchParams': parameter 1", globals: globalObject }); args.push(curArg); } { let curArg = arguments[1]; if (curArg !== void 0) { curArg = conversions["USVString"](curArg, { context: "Failed to execute 'delete' on 'URLSearchParams': parameter 2", globals: globalObject }); } args.push(curArg); } return utils.tryWrapperForImpl(esValue[implSymbol].delete(...args)); } get(name) { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'get' called on an object that is not a valid instance of URLSearchParams."); } if (arguments.length < 1) { throw new globalObject.TypeError( `Failed to execute 'get' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.` ); } const args = []; { let curArg = arguments[0]; curArg = conversions["USVString"](curArg, { context: "Failed to execute 'get' on 'URLSearchParams': parameter 1", globals: globalObject }); args.push(curArg); } return esValue[implSymbol].get(...args); } getAll(name) { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError( "'getAll' called on an object that is not a valid instance of URLSearchParams." ); } if (arguments.length < 1) { throw new globalObject.TypeError( `Failed to execute 'getAll' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.` ); } const args = []; { let curArg = arguments[0]; curArg = conversions["USVString"](curArg, { context: "Failed to execute 'getAll' on 'URLSearchParams': parameter 1", globals: globalObject }); args.push(curArg); } return utils.tryWrapperForImpl(esValue[implSymbol].getAll(...args)); } has(name) { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'has' called on an object that is not a valid instance of URLSearchParams."); } if (arguments.length < 1) { throw new globalObject.TypeError( `Failed to execute 'has' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.` ); } const args = []; { let curArg = arguments[0]; curArg = conversions["USVString"](curArg, { context: "Failed to execute 'has' on 'URLSearchParams': parameter 1", globals: globalObject }); args.push(curArg); } { let curArg = arguments[1]; if (curArg !== void 0) { curArg = conversions["USVString"](curArg, { context: "Failed to execute 'has' on 'URLSearchParams': parameter 2", globals: globalObject }); } args.push(curArg); } return esValue[implSymbol].has(...args); } set(name, value) { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'set' called on an object that is not a valid instance of URLSearchParams."); } if (arguments.length < 2) { throw new globalObject.TypeError( `Failed to execute 'set' on 'URLSearchParams': 2 arguments required, but only ${arguments.length} present.` ); } const args = []; { let curArg = arguments[0]; curArg = conversions["USVString"](curArg, { context: "Failed to execute 'set' on 'URLSearchParams': parameter 1", globals: globalObject }); args.push(curArg); } { let curArg = arguments[1]; curArg = conversions["USVString"](curArg, { context: "Failed to execute 'set' on 'URLSearchParams': parameter 2", globals: globalObject }); args.push(curArg); } return utils.tryWrapperForImpl(esValue[implSymbol].set(...args)); } sort() { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'sort' called on an object that is not a valid instance of URLSearchParams."); } return utils.tryWrapperForImpl(esValue[implSymbol].sort()); } toString() { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError( "'toString' called on an object that is not a valid instance of URLSearchParams." ); } return esValue[implSymbol].toString(); } keys() { if (!exports2.is(this)) { throw new globalObject.TypeError("'keys' called on an object that is not a valid instance of URLSearchParams."); } return exports2.createDefaultIterator(globalObject, this, "key"); } values() { if (!exports2.is(this)) { throw new globalObject.TypeError( "'values' called on an object that is not a valid instance of URLSearchParams." ); } return exports2.createDefaultIterator(globalObject, this, "value"); } entries() { if (!exports2.is(this)) { throw new globalObject.TypeError( "'entries' called on an object that is not a valid instance of URLSearchParams." ); } return exports2.createDefaultIterator(globalObject, this, "key+value"); } forEach(callback) { if (!exports2.is(this)) { throw new globalObject.TypeError( "'forEach' called on an object that is not a valid instance of URLSearchParams." ); } if (arguments.length < 1) { throw new globalObject.TypeError( "Failed to execute 'forEach' on 'iterable': 1 argument required, but only 0 present." ); } callback = Function2.convert(globalObject, callback, { context: "Failed to execute 'forEach' on 'iterable': The callback provided as parameter 1" }); const thisArg = arguments[1]; let pairs = Array.from(this[implSymbol]); let i = 0; while (i < pairs.length) { const [key, value] = pairs[i].map(utils.tryWrapperForImpl); callback.call(thisArg, value, key, this); pairs = Array.from(this[implSymbol]); i++; } } get size() { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError( "'get size' called on an object that is not a valid instance of URLSearchParams." ); } return esValue[implSymbol]["size"]; } } Object.defineProperties(URLSearchParams.prototype, { append: { enumerable: true }, delete: { enumerable: true }, get: { enumerable: true }, getAll: { enumerable: true }, has: { enumerable: true }, set: { enumerable: true }, sort: { enumerable: true }, toString: { enumerable: true }, keys: { enumerable: true }, values: { enumerable: true }, entries: { enumerable: true }, forEach: { enumerable: true }, size: { enumerable: true }, [Symbol.toStringTag]: { value: "URLSearchParams", configurable: true }, [Symbol.iterator]: { value: URLSearchParams.prototype.entries, configurable: true, writable: true } }); ctorRegistry[interfaceName] = URLSearchParams; ctorRegistry["URLSearchParams Iterator"] = Object.create(ctorRegistry["%IteratorPrototype%"], { [Symbol.toStringTag]: { configurable: true, value: "URLSearchParams Iterator" } }); utils.define(ctorRegistry["URLSearchParams Iterator"], { next() { const internal = this && this[utils.iterInternalSymbol]; if (!internal) { throw new globalObject.TypeError("next() called on a value that is not a URLSearchParams iterator object"); } const { target, kind, index } = internal; const values = Array.from(target[implSymbol]); const len = values.length; if (index >= len) { return newObjectInRealm(globalObject, { value: void 0, done: true }); } const pair = values[index]; internal.index = index + 1; return newObjectInRealm(globalObject, utils.iteratorResult(pair.map(utils.tryWrapperForImpl), kind)); } }); Object.defineProperty(globalObject, interfaceName, { configurable: true, writable: true, value: URLSearchParams }); }; var Impl = require_URLSearchParams_impl(); } }); // netlify/functions/node_modules/whatwg-url/lib/URL-impl.js var require_URL_impl = __commonJS({ "netlify/functions/node_modules/whatwg-url/lib/URL-impl.js"(exports2) { "use strict"; var usm = require_url_state_machine(); var urlencoded = require_urlencoded(); var URLSearchParams = require_URLSearchParams(); exports2.implementation = class URLImpl { // Unlike the spec, we duplicate some code between the constructor and canParse, because we want to give useful error // messages in the constructor that distinguish between the different causes of failure. constructor(globalObject, [url, base]) { let parsedBase = null; if (base !== void 0) { parsedBase = usm.basicURLParse(base); if (parsedBase === null) { throw new TypeError(`Invalid base URL: ${base}`); } } const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); if (parsedURL === null) { throw new TypeError(`Invalid URL: ${url}`); } const query = parsedURL.query !== null ? parsedURL.query : ""; this._url = parsedURL; this._query = URLSearchParams.createImpl(globalObject, [query], { doNotStripQMark: true }); this._query._url = this; } static parse(globalObject, input, base) { try { return new URLImpl(globalObject, [input, base]); } catch { return null; } } static canParse(url, base) { let parsedBase = null; if (base !== void 0) { parsedBase = usm.basicURLParse(base); if (parsedBase === null) { return false; } } const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); if (parsedURL === null) { return false; } return true; } get href() { return usm.serializeURL(this._url); } set href(v) { const parsedURL = usm.basicURLParse(v); if (parsedURL === null) { throw new TypeError(`Invalid URL: ${v}`); } this._url = parsedURL; this._query._list.splice(0); const { query } = parsedURL; if (query !== null) { this._query._list = urlencoded.parseUrlencodedString(query); } } get origin() { return usm.serializeURLOrigin(this._url); } get protocol() { return `${this._url.scheme}:`; } set protocol(v) { usm.basicURLParse(`${v}:`, { url: this._url, stateOverride: "scheme start" }); } get username() { return this._url.username; } set username(v) { if (usm.cannotHaveAUsernamePasswordPort(this._url)) { return; } usm.setTheUsername(this._url, v); } get password() { return this._url.password; } set password(v) { if (usm.cannotHaveAUsernamePasswordPort(this._url)) { return; } usm.setThePassword(this._url, v); } get host() { const url = this._url; if (url.host === null) { return ""; } if (url.port === null) { return usm.serializeHost(url.host); } return `${usm.serializeHost(url.host)}:${usm.serializeInteger(url.port)}`; } set host(v) { if (usm.hasAnOpaquePath(this._url)) { return; } usm.basicURLParse(v, { url: this._url, stateOverride: "host" }); } get hostname() { if (this._url.host === null) { return ""; } return usm.serializeHost(this._url.host); } set hostname(v) { if (usm.hasAnOpaquePath(this._url)) { return; } usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); } get port() { if (this._url.port === null) { return ""; } return usm.serializeInteger(this._url.port); } set port(v) { if (usm.cannotHaveAUsernamePasswordPort(this._url)) { return; } if (v === "") { this._url.port = null; } else { usm.basicURLParse(v, { url: this._url, stateOverride: "port" }); } } get pathname() { return usm.serializePath(this._url); } set pathname(v) { if (usm.hasAnOpaquePath(this._url)) { return; } this._url.path = []; usm.basicURLParse(v, { url: this._url, stateOverride: "path start" }); } get search() { if (this._url.query === null || this._url.query === "") { return ""; } return `?${this._url.query}`; } set search(v) { const url = this._url; if (v === "") { url.query = null; this._query._list = []; return; } const input = v[0] === "?" ? v.substring(1) : v; url.query = ""; usm.basicURLParse(input, { url, stateOverride: "query" }); this._query._list = urlencoded.parseUrlencodedString(input); } get searchParams() { return this._query; } get hash() { if (this._url.fragment === null || this._url.fragment === "") { return ""; } return `#${this._url.fragment}`; } set hash(v) { if (v === "") { this._url.fragment = null; return; } const input = v[0] === "#" ? v.substring(1) : v; this._url.fragment = ""; usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" }); } toJSON() { return this.href; } }; } }); // netlify/functions/node_modules/whatwg-url/lib/URL.js var require_URL = __commonJS({ "netlify/functions/node_modules/whatwg-url/lib/URL.js"(exports2) { "use strict"; var conversions = require_lib(); var utils = require_utils2(); var implSymbol = utils.implSymbol; var ctorRegistrySymbol = utils.ctorRegistrySymbol; var interfaceName = "URL"; exports2.is = (value) => { return utils.isObject(value) && utils.hasOwn(value, implSymbol) && value[implSymbol] instanceof Impl.implementation; }; exports2.isImpl = (value) => { return utils.isObject(value) && value instanceof Impl.implementation; }; exports2.convert = (globalObject, value, { context = "The provided value" } = {}) => { if (exports2.is(value)) { return utils.implForWrapper(value); } throw new globalObject.TypeError(`${context} is not of type 'URL'.`); }; function makeWrapper(globalObject, newTarget) { let proto; if (newTarget !== void 0) { proto = newTarget.prototype; } if (!utils.isObject(proto)) { proto = globalObject[ctorRegistrySymbol]["URL"].prototype; } return Object.create(proto); } exports2.create = (globalObject, constructorArgs, privateData) => { const wrapper = makeWrapper(globalObject); return exports2.setup(wrapper, globalObject, constructorArgs, privateData); }; exports2.createImpl = (globalObject, constructorArgs, privateData) => { const wrapper = exports2.create(globalObject, constructorArgs, privateData); return utils.implForWrapper(wrapper); }; exports2._internalSetup = (wrapper, globalObject) => { }; exports2.setup = (wrapper, globalObject, constructorArgs = [], privateData = {}) => { privateData.wrapper = wrapper; exports2._internalSetup(wrapper, globalObject); Object.defineProperty(wrapper, implSymbol, { value: new Impl.implementation(globalObject, constructorArgs, privateData), configurable: true }); wrapper[implSymbol][utils.wrapperSymbol] = wrapper; if (Impl.init) { Impl.init(wrapper[implSymbol]); } return wrapper; }; exports2.new = (globalObject, newTarget) => { const wrapper = makeWrapper(globalObject, newTarget); exports2._internalSetup(wrapper, globalObject); Object.defineProperty(wrapper, implSymbol, { value: Object.create(Impl.implementation.prototype), configurable: true }); wrapper[implSymbol][utils.wrapperSymbol] = wrapper; if (Impl.init) { Impl.init(wrapper[implSymbol]); } return wrapper[implSymbol]; }; var exposed = /* @__PURE__ */ new Set(["Window", "Worker"]); exports2.install = (globalObject, globalNames) => { if (!globalNames.some((globalName) => exposed.has(globalName))) { return; } const ctorRegistry = utils.initCtorRegistry(globalObject); class URL2 { constructor(url) { if (arguments.length < 1) { throw new globalObject.TypeError( `Failed to construct 'URL': 1 argument required, but only ${arguments.length} present.` ); } const args = []; { let curArg = arguments[0]; curArg = conversions["USVString"](curArg, { context: "Failed to construct 'URL': parameter 1", globals: globalObject }); args.push(curArg); } { let curArg = arguments[1]; if (curArg !== void 0) { curArg = conversions["USVString"](curArg, { context: "Failed to construct 'URL': parameter 2", globals: globalObject }); } args.push(curArg); } return exports2.setup(Object.create(new.target.prototype), globalObject, args); } toJSON() { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'toJSON' called on an object that is not a valid instance of URL."); } return esValue[implSymbol].toJSON(); } get href() { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'get href' called on an object that is not a valid instance of URL."); } return esValue[implSymbol]["href"]; } set href(V) { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'set href' called on an object that is not a valid instance of URL."); } V = conversions["USVString"](V, { context: "Failed to set the 'href' property on 'URL': The provided value", globals: globalObject }); esValue[implSymbol]["href"] = V; } toString() { const esValue = this; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'toString' called on an object that is not a valid instance of URL."); } return esValue[implSymbol]["href"]; } get origin() { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'get origin' called on an object that is not a valid instance of URL."); } return esValue[implSymbol]["origin"]; } get protocol() { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'get protocol' called on an object that is not a valid instance of URL."); } return esValue[implSymbol]["protocol"]; } set protocol(V) { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'set protocol' called on an object that is not a valid instance of URL."); } V = conversions["USVString"](V, { context: "Failed to set the 'protocol' property on 'URL': The provided value", globals: globalObject }); esValue[implSymbol]["protocol"] = V; } get username() { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'get username' called on an object that is not a valid instance of URL."); } return esValue[implSymbol]["username"]; } set username(V) { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'set username' called on an object that is not a valid instance of URL."); } V = conversions["USVString"](V, { context: "Failed to set the 'username' property on 'URL': The provided value", globals: globalObject }); esValue[implSymbol]["username"] = V; } get password() { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'get password' called on an object that is not a valid instance of URL."); } return esValue[implSymbol]["password"]; } set password(V) { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'set password' called on an object that is not a valid instance of URL."); } V = conversions["USVString"](V, { context: "Failed to set the 'password' property on 'URL': The provided value", globals: globalObject }); esValue[implSymbol]["password"] = V; } get host() { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'get host' called on an object that is not a valid instance of URL."); } return esValue[implSymbol]["host"]; } set host(V) { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'set host' called on an object that is not a valid instance of URL."); } V = conversions["USVString"](V, { context: "Failed to set the 'host' property on 'URL': The provided value", globals: globalObject }); esValue[implSymbol]["host"] = V; } get hostname() { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'get hostname' called on an object that is not a valid instance of URL."); } return esValue[implSymbol]["hostname"]; } set hostname(V) { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'set hostname' called on an object that is not a valid instance of URL."); } V = conversions["USVString"](V, { context: "Failed to set the 'hostname' property on 'URL': The provided value", globals: globalObject }); esValue[implSymbol]["hostname"] = V; } get port() { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'get port' called on an object that is not a valid instance of URL."); } return esValue[implSymbol]["port"]; } set port(V) { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'set port' called on an object that is not a valid instance of URL."); } V = conversions["USVString"](V, { context: "Failed to set the 'port' property on 'URL': The provided value", globals: globalObject }); esValue[implSymbol]["port"] = V; } get pathname() { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'get pathname' called on an object that is not a valid instance of URL."); } return esValue[implSymbol]["pathname"]; } set pathname(V) { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'set pathname' called on an object that is not a valid instance of URL."); } V = conversions["USVString"](V, { context: "Failed to set the 'pathname' property on 'URL': The provided value", globals: globalObject }); esValue[implSymbol]["pathname"] = V; } get search() { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'get search' called on an object that is not a valid instance of URL."); } return esValue[implSymbol]["search"]; } set search(V) { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'set search' called on an object that is not a valid instance of URL."); } V = conversions["USVString"](V, { context: "Failed to set the 'search' property on 'URL': The provided value", globals: globalObject }); esValue[implSymbol]["search"] = V; } get searchParams() { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'get searchParams' called on an object that is not a valid instance of URL."); } return utils.getSameObject(this, "searchParams", () => { return utils.tryWrapperForImpl(esValue[implSymbol]["searchParams"]); }); } get hash() { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'get hash' called on an object that is not a valid instance of URL."); } return esValue[implSymbol]["hash"]; } set hash(V) { const esValue = this !== null && this !== void 0 ? this : globalObject; if (!exports2.is(esValue)) { throw new globalObject.TypeError("'set hash' called on an object that is not a valid instance of URL."); } V = conversions["USVString"](V, { context: "Failed to set the 'hash' property on 'URL': The provided value", globals: globalObject }); esValue[implSymbol]["hash"] = V; } static parse(url) { if (arguments.length < 1) { throw new globalObject.TypeError( `Failed to execute 'parse' on 'URL': 1 argument required, but only ${arguments.length} present.` ); } const args = []; { let curArg = arguments[0]; curArg = conversions["USVString"](curArg, { context: "Failed to execute 'parse' on 'URL': parameter 1", globals: globalObject }); args.push(curArg); } { let curArg = arguments[1]; if (curArg !== void 0) { curArg = conversions["USVString"](curArg, { context: "Failed to execute 'parse' on 'URL': parameter 2", globals: globalObject }); } args.push(curArg); } return utils.tryWrapperForImpl(Impl.implementation.parse(globalObject, ...args)); } static canParse(url) { if (arguments.length < 1) { throw new globalObject.TypeError( `Failed to execute 'canParse' on 'URL': 1 argument required, but only ${arguments.length} present.` ); } const args = []; { let curArg = arguments[0]; curArg = conversions["USVString"](curArg, { context: "Failed to execute 'canParse' on 'URL': parameter 1", globals: globalObject }); args.push(curArg); } { let curArg = arguments[1]; if (curArg !== void 0) { curArg = conversions["USVString"](curArg, { context: "Failed to execute 'canParse' on 'URL': parameter 2", globals: globalObject }); } args.push(curArg); } return Impl.implementation.canParse(...args); } } Object.defineProperties(URL2.prototype, { toJSON: { enumerable: true }, href: { enumerable: true }, toString: { enumerable: true }, origin: { enumerable: true }, protocol: { enumerable: true }, username: { enumerable: true }, password: { enumerable: true }, host: { enumerable: true }, hostname: { enumerable: true }, port: { enumerable: true }, pathname: { enumerable: true }, search: { enumerable: true }, searchParams: { enumerable: true }, hash: { enumerable: true }, [Symbol.toStringTag]: { value: "URL", configurable: true } }); Object.defineProperties(URL2, { parse: { enumerable: true }, canParse: { enumerable: true } }); ctorRegistry[interfaceName] = URL2; Object.defineProperty(globalObject, interfaceName, { configurable: true, writable: true, value: URL2 }); if (globalNames.includes("Window")) { Object.defineProperty(globalObject, "webkitURL", { configurable: true, writable: true, value: URL2 }); } }; var Impl = require_URL_impl(); } }); // netlify/functions/node_modules/whatwg-url/webidl2js-wrapper.js var require_webidl2js_wrapper = __commonJS({ "netlify/functions/node_modules/whatwg-url/webidl2js-wrapper.js"(exports2) { "use strict"; var URL2 = require_URL(); var URLSearchParams = require_URLSearchParams(); exports2.URL = URL2; exports2.URLSearchParams = URLSearchParams; } }); // netlify/functions/node_modules/whatwg-url/index.js var require_whatwg_url = __commonJS({ "netlify/functions/node_modules/whatwg-url/index.js"(exports2) { "use strict"; var { URL: URL2, URLSearchParams } = require_webidl2js_wrapper(); var urlStateMachine = require_url_state_machine(); var percentEncoding = require_percent_encoding(); var sharedGlobalObject = { Array, Object, Promise, String, TypeError }; URL2.install(sharedGlobalObject, ["Window"]); URLSearchParams.install(sharedGlobalObject, ["Window"]); exports2.URL = sharedGlobalObject.URL; exports2.URLSearchParams = sharedGlobalObject.URLSearchParams; exports2.parseURL = urlStateMachine.parseURL; exports2.basicURLParse = urlStateMachine.basicURLParse; exports2.serializeURL = urlStateMachine.serializeURL; exports2.serializePath = urlStateMachine.serializePath; exports2.serializeHost = urlStateMachine.serializeHost; exports2.serializeInteger = urlStateMachine.serializeInteger; exports2.serializeURLOrigin = urlStateMachine.serializeURLOrigin; exports2.setTheUsername = urlStateMachine.setTheUsername; exports2.setThePassword = urlStateMachine.setThePassword; exports2.cannotHaveAUsernamePasswordPort = urlStateMachine.cannotHaveAUsernamePasswordPort; exports2.hasAnOpaquePath = urlStateMachine.hasAnOpaquePath; exports2.percentDecodeString = percentEncoding.percentDecodeString; exports2.percentDecodeBytes = percentEncoding.percentDecodeBytes; } }); // netlify/functions/node_modules/mongodb-connection-string-url/lib/redact.js var require_redact = __commonJS({ "netlify/functions/node_modules/mongodb-connection-string-url/lib/redact.js"(exports2) { "use strict"; var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = exports2 && exports2.__importStar || function(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) { for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); } __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.redactConnectionString = exports2.redactValidConnectionString = void 0; var index_1 = __importStar(require_lib2()); function redactValidConnectionString(inputUrl, options) { var _a, _b; const url = inputUrl.clone(); const replacementString = (_a = options === null || options === void 0 ? void 0 : options.replacementString) !== null && _a !== void 0 ? _a : "_credentials_"; const redactUsernames = (_b = options === null || options === void 0 ? void 0 : options.redactUsernames) !== null && _b !== void 0 ? _b : true; if ((url.username || url.password) && redactUsernames) { url.username = replacementString; url.password = ""; } else if (url.password) { url.password = replacementString; } if (url.searchParams.has("authMechanismProperties")) { const props = new index_1.CommaAndColonSeparatedRecord(url.searchParams.get("authMechanismProperties")); if (props.get("AWS_SESSION_TOKEN")) { props.set("AWS_SESSION_TOKEN", replacementString); url.searchParams.set("authMechanismProperties", props.toString()); } } if (url.searchParams.has("tlsCertificateKeyFilePassword")) { url.searchParams.set("tlsCertificateKeyFilePassword", replacementString); } if (url.searchParams.has("proxyUsername") && redactUsernames) { url.searchParams.set("proxyUsername", replacementString); } if (url.searchParams.has("proxyPassword")) { url.searchParams.set("proxyPassword", replacementString); } return url; } exports2.redactValidConnectionString = redactValidConnectionString; function redactConnectionString(uri, options) { var _a, _b; const replacementString = (_a = options === null || options === void 0 ? void 0 : options.replacementString) !== null && _a !== void 0 ? _a : ""; const redactUsernames = (_b = options === null || options === void 0 ? void 0 : options.redactUsernames) !== null && _b !== void 0 ? _b : true; let parsed; try { parsed = new index_1.default(uri); } catch (_c) { } if (parsed) { options = { ...options, replacementString: "___credentials___" }; return parsed.redact(options).toString().replace(/___credentials___/g, replacementString); } const R = replacementString; const replacements = [ (uri2) => uri2.replace(redactUsernames ? /(\/\/)(.*)(@)/g : /(\/\/[^@]*:)(.*)(@)/g, `$1${R}$3`), (uri2) => uri2.replace(/(AWS_SESSION_TOKEN(:|%3A))([^,&]+)/gi, `$1${R}`), (uri2) => uri2.replace(/(tlsCertificateKeyFilePassword=)([^&]+)/gi, `$1${R}`), (uri2) => redactUsernames ? uri2.replace(/(proxyUsername=)([^&]+)/gi, `$1${R}`) : uri2, (uri2) => uri2.replace(/(proxyPassword=)([^&]+)/gi, `$1${R}`) ]; for (const replacer of replacements) { uri = replacer(uri); } return uri; } exports2.redactConnectionString = redactConnectionString; } }); // netlify/functions/node_modules/mongodb-connection-string-url/lib/index.js var require_lib2 = __commonJS({ "netlify/functions/node_modules/mongodb-connection-string-url/lib/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.CommaAndColonSeparatedRecord = exports2.ConnectionString = exports2.redactConnectionString = void 0; var whatwg_url_1 = require_whatwg_url(); var redact_1 = require_redact(); Object.defineProperty(exports2, "redactConnectionString", { enumerable: true, get: function() { return redact_1.redactConnectionString; } }); var DUMMY_HOSTNAME = "__this_is_a_placeholder__"; function connectionStringHasValidScheme(connectionString) { return connectionString.startsWith("mongodb://") || connectionString.startsWith("mongodb+srv://"); } var HOSTS_REGEX = /^(?[^/]+):\/\/(?:(?[^:@]*)(?::(?[^@]*))?@)?(?(?!:)[^/?@]*)(?.*)/; var CaseInsensitiveMap = class extends Map { delete(name) { return super.delete(this._normalizeKey(name)); } get(name) { return super.get(this._normalizeKey(name)); } has(name) { return super.has(this._normalizeKey(name)); } set(name, value) { return super.set(this._normalizeKey(name), value); } _normalizeKey(name) { name = `${name}`; for (const key of this.keys()) { if (key.toLowerCase() === name.toLowerCase()) { name = key; break; } } return name; } }; function caseInsenstiveURLSearchParams(Ctor) { return class CaseInsenstiveURLSearchParams extends Ctor { append(name, value) { return super.append(this._normalizeKey(name), value); } delete(name) { return super.delete(this._normalizeKey(name)); } get(name) { return super.get(this._normalizeKey(name)); } getAll(name) { return super.getAll(this._normalizeKey(name)); } has(name) { return super.has(this._normalizeKey(name)); } set(name, value) { return super.set(this._normalizeKey(name), value); } keys() { return super.keys(); } values() { return super.values(); } entries() { return super.entries(); } [Symbol.iterator]() { return super[Symbol.iterator](); } _normalizeKey(name) { return CaseInsensitiveMap.prototype._normalizeKey.call(this, name); } }; } var URLWithoutHost = class extends whatwg_url_1.URL { }; var MongoParseError = class extends Error { get name() { return "MongoParseError"; } }; var ConnectionString = class _ConnectionString extends URLWithoutHost { constructor(uri, options = {}) { var _a; const { looseValidation } = options; if (!looseValidation && !connectionStringHasValidScheme(uri)) { throw new MongoParseError('Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"'); } const match = uri.match(HOSTS_REGEX); if (!match) { throw new MongoParseError(`Invalid connection string "${uri}"`); } const { protocol, username, password, hosts, rest } = (_a = match.groups) !== null && _a !== void 0 ? _a : {}; if (!looseValidation) { if (!protocol || !hosts) { throw new MongoParseError(`Protocol and host list are required in "${uri}"`); } try { decodeURIComponent(username !== null && username !== void 0 ? username : ""); decodeURIComponent(password !== null && password !== void 0 ? password : ""); } catch (err) { throw new MongoParseError(err.message); } const illegalCharacters = /[:/?#[\]@]/gi; if (username === null || username === void 0 ? void 0 : username.match(illegalCharacters)) { throw new MongoParseError(`Username contains unescaped characters ${username}`); } if (!username || !password) { const uriWithoutProtocol = uri.replace(`${protocol}://`, ""); if (uriWithoutProtocol.startsWith("@") || uriWithoutProtocol.startsWith(":")) { throw new MongoParseError("URI contained empty userinfo section"); } } if (password === null || password === void 0 ? void 0 : password.match(illegalCharacters)) { throw new MongoParseError("Password contains unescaped characters"); } } let authString = ""; if (typeof username === "string") authString += username; if (typeof password === "string") authString += `:${password}`; if (authString) authString += "@"; try { super(`${protocol.toLowerCase()}://${authString}${DUMMY_HOSTNAME}${rest}`); } catch (err) { if (looseValidation) { new _ConnectionString(uri, { ...options, looseValidation: false }); } if (typeof err.message === "string") { err.message = err.message.replace(DUMMY_HOSTNAME, hosts); } throw err; } this._hosts = hosts.split(","); if (!looseValidation) { if (this.isSRV && this.hosts.length !== 1) { throw new MongoParseError("mongodb+srv URI cannot have multiple service names"); } if (this.isSRV && this.hosts.some((host) => host.includes(":"))) { throw new MongoParseError("mongodb+srv URI cannot have port number"); } } if (!this.pathname) { this.pathname = "/"; } Object.setPrototypeOf(this.searchParams, caseInsenstiveURLSearchParams(this.searchParams.constructor).prototype); } get host() { return DUMMY_HOSTNAME; } set host(_ignored) { throw new Error("No single host for connection string"); } get hostname() { return DUMMY_HOSTNAME; } set hostname(_ignored) { throw new Error("No single host for connection string"); } get port() { return ""; } set port(_ignored) { throw new Error("No single host for connection string"); } get href() { return this.toString(); } set href(_ignored) { throw new Error("Cannot set href for connection strings"); } get isSRV() { return this.protocol.includes("srv"); } get hosts() { return this._hosts; } set hosts(list) { this._hosts = list; } toString() { return super.toString().replace(DUMMY_HOSTNAME, this.hosts.join(",")); } clone() { return new _ConnectionString(this.toString(), { looseValidation: true }); } redact(options) { return (0, redact_1.redactValidConnectionString)(this, options); } typedSearchParams() { const sametype = false; return this.searchParams; } [Symbol.for("nodejs.util.inspect.custom")]() { const { href, origin, protocol, username, password, hosts, pathname, search, searchParams, hash } = this; return { href, origin, protocol, username, password, hosts, pathname, search, searchParams, hash }; } }; exports2.ConnectionString = ConnectionString; var CommaAndColonSeparatedRecord = class extends CaseInsensitiveMap { constructor(from) { super(); for (const entry of (from !== null && from !== void 0 ? from : "").split(",")) { if (!entry) continue; const colonIndex = entry.indexOf(":"); if (colonIndex === -1) { this.set(entry, ""); } else { this.set(entry.slice(0, colonIndex), entry.slice(colonIndex + 1)); } } } toString() { return [...this].map((entry) => entry.join(":")).join(","); } }; exports2.CommaAndColonSeparatedRecord = CommaAndColonSeparatedRecord; exports2.default = ConnectionString; } }); // netlify/functions/node_modules/mongodb/lib/cmap/commands.js var require_commands = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/commands.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.OpCompressedRequest = exports2.OpMsgResponse = exports2.OpMsgRequest = exports2.DocumentSequence = exports2.OpReply = exports2.OpQueryRequest = void 0; var BSON = require_bson2(); var error_1 = require_error(); var compression_1 = require_compression(); var constants_1 = require_constants2(); var _requestId = 0; var OPTS_TAILABLE_CURSOR = 2; var OPTS_SECONDARY = 4; var OPTS_OPLOG_REPLAY = 8; var OPTS_NO_CURSOR_TIMEOUT = 16; var OPTS_AWAIT_DATA = 32; var OPTS_EXHAUST = 64; var OPTS_PARTIAL = 128; var CURSOR_NOT_FOUND = 1; var QUERY_FAILURE = 2; var SHARD_CONFIG_STALE = 4; var AWAIT_CAPABLE = 8; var encodeUTF8Into = BSON.BSON.onDemand.ByteUtils.encodeUTF8Into; var OpQueryRequest = class _OpQueryRequest { constructor(databaseName, query, options) { this.moreToCome = false; const ns = `${databaseName}.$cmd`; if (typeof databaseName !== "string") { throw new error_1.MongoRuntimeError("Database name must be a string for a query"); } if (query == null) throw new error_1.MongoRuntimeError("A query document must be specified for query"); if (ns.indexOf("\0") !== -1) { throw new error_1.MongoRuntimeError("Namespace cannot contain a null character"); } this.databaseName = databaseName; this.query = query; this.ns = ns; this.numberToSkip = options.numberToSkip || 0; this.numberToReturn = options.numberToReturn || 0; this.returnFieldSelector = options.returnFieldSelector || void 0; this.requestId = options.requestId ?? _OpQueryRequest.getRequestId(); this.pre32Limit = options.pre32Limit; this.serializeFunctions = typeof options.serializeFunctions === "boolean" ? options.serializeFunctions : false; this.ignoreUndefined = typeof options.ignoreUndefined === "boolean" ? options.ignoreUndefined : false; this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; this.checkKeys = typeof options.checkKeys === "boolean" ? options.checkKeys : false; this.batchSize = this.numberToReturn; this.tailable = false; this.secondaryOk = typeof options.secondaryOk === "boolean" ? options.secondaryOk : false; this.oplogReplay = false; this.noCursorTimeout = false; this.awaitData = false; this.exhaust = false; this.partial = false; } /** Assign next request Id. */ incRequestId() { this.requestId = _requestId++; } /** Peek next request Id. */ nextRequestId() { return _requestId + 1; } /** Increment then return next request Id. */ static getRequestId() { return ++_requestId; } // Uses a single allocated buffer for the process, avoiding multiple memory allocations toBin() { const buffers = []; let projection = null; let flags = 0; if (this.tailable) { flags |= OPTS_TAILABLE_CURSOR; } if (this.secondaryOk) { flags |= OPTS_SECONDARY; } if (this.oplogReplay) { flags |= OPTS_OPLOG_REPLAY; } if (this.noCursorTimeout) { flags |= OPTS_NO_CURSOR_TIMEOUT; } if (this.awaitData) { flags |= OPTS_AWAIT_DATA; } if (this.exhaust) { flags |= OPTS_EXHAUST; } if (this.partial) { flags |= OPTS_PARTIAL; } if (this.batchSize !== this.numberToReturn) this.numberToReturn = this.batchSize; const header = Buffer.alloc( 4 * 4 + // Header 4 + // Flags Buffer.byteLength(this.ns) + 1 + // namespace 4 + // numberToSkip 4 // numberToReturn ); buffers.push(header); const query = BSON.serialize(this.query, { checkKeys: this.checkKeys, serializeFunctions: this.serializeFunctions, ignoreUndefined: this.ignoreUndefined }); buffers.push(query); if (this.returnFieldSelector && Object.keys(this.returnFieldSelector).length > 0) { projection = BSON.serialize(this.returnFieldSelector, { checkKeys: this.checkKeys, serializeFunctions: this.serializeFunctions, ignoreUndefined: this.ignoreUndefined }); buffers.push(projection); } const totalLength = header.length + query.length + (projection ? projection.length : 0); let index = 4; header[3] = totalLength >> 24 & 255; header[2] = totalLength >> 16 & 255; header[1] = totalLength >> 8 & 255; header[0] = totalLength & 255; header[index + 3] = this.requestId >> 24 & 255; header[index + 2] = this.requestId >> 16 & 255; header[index + 1] = this.requestId >> 8 & 255; header[index] = this.requestId & 255; index = index + 4; header[index + 3] = 0 >> 24 & 255; header[index + 2] = 0 >> 16 & 255; header[index + 1] = 0 >> 8 & 255; header[index] = 0 & 255; index = index + 4; header[index + 3] = constants_1.OP_QUERY >> 24 & 255; header[index + 2] = constants_1.OP_QUERY >> 16 & 255; header[index + 1] = constants_1.OP_QUERY >> 8 & 255; header[index] = constants_1.OP_QUERY & 255; index = index + 4; header[index + 3] = flags >> 24 & 255; header[index + 2] = flags >> 16 & 255; header[index + 1] = flags >> 8 & 255; header[index] = flags & 255; index = index + 4; index = index + header.write(this.ns, index, "utf8") + 1; header[index - 1] = 0; header[index + 3] = this.numberToSkip >> 24 & 255; header[index + 2] = this.numberToSkip >> 16 & 255; header[index + 1] = this.numberToSkip >> 8 & 255; header[index] = this.numberToSkip & 255; index = index + 4; header[index + 3] = this.numberToReturn >> 24 & 255; header[index + 2] = this.numberToReturn >> 16 & 255; header[index + 1] = this.numberToReturn >> 8 & 255; header[index] = this.numberToReturn & 255; index = index + 4; return buffers; } }; exports2.OpQueryRequest = OpQueryRequest; var OpReply = class { constructor(message, msgHeader, msgBody, opts) { this.index = 0; this.sections = []; this.moreToCome = false; this.parsed = false; this.raw = message; this.data = msgBody; this.opts = opts ?? { useBigInt64: false, promoteLongs: true, promoteValues: true, promoteBuffers: false, bsonRegExp: false }; this.length = msgHeader.length; this.requestId = msgHeader.requestId; this.responseTo = msgHeader.responseTo; this.opCode = msgHeader.opCode; this.fromCompressed = msgHeader.fromCompressed; this.useBigInt64 = typeof this.opts.useBigInt64 === "boolean" ? this.opts.useBigInt64 : false; this.promoteLongs = typeof this.opts.promoteLongs === "boolean" ? this.opts.promoteLongs : true; this.promoteValues = typeof this.opts.promoteValues === "boolean" ? this.opts.promoteValues : true; this.promoteBuffers = typeof this.opts.promoteBuffers === "boolean" ? this.opts.promoteBuffers : false; this.bsonRegExp = typeof this.opts.bsonRegExp === "boolean" ? this.opts.bsonRegExp : false; } isParsed() { return this.parsed; } parse() { if (this.parsed) return this.sections[0]; this.index = 20; this.responseFlags = this.data.readInt32LE(0); this.cursorId = new BSON.Long(this.data.readInt32LE(4), this.data.readInt32LE(8)); this.startingFrom = this.data.readInt32LE(12); this.numberReturned = this.data.readInt32LE(16); if (this.numberReturned < 0 || this.numberReturned > 2 ** 32 - 1) { throw new RangeError(`OP_REPLY numberReturned is an invalid array length ${this.numberReturned}`); } this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0; this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0; this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0; this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0; for (let i = 0; i < this.numberReturned; i++) { const bsonSize = this.data[this.index] | this.data[this.index + 1] << 8 | this.data[this.index + 2] << 16 | this.data[this.index + 3] << 24; const section = this.data.subarray(this.index, this.index + bsonSize); this.sections.push(section); this.index = this.index + bsonSize; } this.parsed = true; return this.sections[0]; } }; exports2.OpReply = OpReply; var OPTS_CHECKSUM_PRESENT = 1; var OPTS_MORE_TO_COME = 2; var OPTS_EXHAUST_ALLOWED = 1 << 16; var DocumentSequence = class { /** * Create a new document sequence for the provided field. * @param field - The field it will replace. */ constructor(field, documents) { this.field = field; this.documents = []; this.chunks = []; this.serializedDocumentsLength = 0; const buffer = Buffer.allocUnsafe(1 + 4 + this.field.length + 1); buffer[0] = 1; encodeUTF8Into(buffer, `${this.field}\0`, 5); this.chunks.push(buffer); this.header = buffer; if (documents) { for (const doc of documents) { this.push(doc, BSON.serialize(doc)); } } } /** * Push a document to the document sequence. Will serialize the document * as well and return the current serialized length of all documents. * @param document - The document to add. * @param buffer - The serialized document in raw BSON. * @returns The new total document sequence length. */ push(document2, buffer) { this.serializedDocumentsLength += buffer.length; this.documents.push(document2); this.chunks.push(buffer); this.header?.writeInt32LE(4 + this.field.length + 1 + this.serializedDocumentsLength, 1); return this.serializedDocumentsLength + this.header.length; } /** * Get the fully serialized bytes for the document sequence section. * @returns The section bytes. */ toBin() { return Buffer.concat(this.chunks); } }; exports2.DocumentSequence = DocumentSequence; var OpMsgRequest = class _OpMsgRequest { constructor(databaseName, command, options) { if (command == null) throw new error_1.MongoInvalidArgumentError("Query document must be specified for query"); this.databaseName = databaseName; this.command = command; this.command.$db = databaseName; this.options = options ?? {}; this.requestId = options.requestId ? options.requestId : _OpMsgRequest.getRequestId(); this.serializeFunctions = typeof options.serializeFunctions === "boolean" ? options.serializeFunctions : false; this.ignoreUndefined = typeof options.ignoreUndefined === "boolean" ? options.ignoreUndefined : false; this.checkKeys = typeof options.checkKeys === "boolean" ? options.checkKeys : false; this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; this.checksumPresent = false; this.moreToCome = options.moreToCome ?? command.writeConcern?.w === 0; this.exhaustAllowed = typeof options.exhaustAllowed === "boolean" ? options.exhaustAllowed : false; } toBin() { const buffers = []; let flags = 0; if (this.checksumPresent) { flags |= OPTS_CHECKSUM_PRESENT; } if (this.moreToCome) { flags |= OPTS_MORE_TO_COME; } if (this.exhaustAllowed) { flags |= OPTS_EXHAUST_ALLOWED; } const header = Buffer.alloc( 4 * 4 + // Header 4 // Flags ); buffers.push(header); let totalLength = header.length; const command = this.command; totalLength += this.makeSections(buffers, command); header.writeInt32LE(totalLength, 0); header.writeInt32LE(this.requestId, 4); header.writeInt32LE(0, 8); header.writeInt32LE(constants_1.OP_MSG, 12); header.writeUInt32LE(flags, 16); return buffers; } /** * Add the sections to the OP_MSG request's buffers and returns the length. */ makeSections(buffers, document2) { const sequencesBuffer = this.extractDocumentSequences(document2); const payloadTypeBuffer = Buffer.allocUnsafe(1); payloadTypeBuffer[0] = 0; const documentBuffer = this.serializeBson(document2); buffers.push(payloadTypeBuffer); buffers.push(documentBuffer); buffers.push(sequencesBuffer); return payloadTypeBuffer.length + documentBuffer.length + sequencesBuffer.length; } /** * Extracts the document sequences from the command document and returns * a buffer to be added as multiple sections after the initial type 0 * section in the message. */ extractDocumentSequences(document2) { const chunks = []; for (const [key, value] of Object.entries(document2)) { if (value instanceof DocumentSequence) { chunks.push(value.toBin()); delete document2[key]; } } if (chunks.length > 0) { return Buffer.concat(chunks); } return Buffer.alloc(0); } serializeBson(document2) { return BSON.serialize(document2, { checkKeys: this.checkKeys, serializeFunctions: this.serializeFunctions, ignoreUndefined: this.ignoreUndefined }); } static getRequestId() { _requestId = _requestId + 1 & 2147483647; return _requestId; } }; exports2.OpMsgRequest = OpMsgRequest; var OpMsgResponse = class { constructor(message, msgHeader, msgBody, opts) { this.index = 0; this.sections = []; this.parsed = false; this.raw = message; this.data = msgBody; this.opts = opts ?? { useBigInt64: false, promoteLongs: true, promoteValues: true, promoteBuffers: false, bsonRegExp: false }; this.length = msgHeader.length; this.requestId = msgHeader.requestId; this.responseTo = msgHeader.responseTo; this.opCode = msgHeader.opCode; this.fromCompressed = msgHeader.fromCompressed; this.responseFlags = msgBody.readInt32LE(0); this.checksumPresent = (this.responseFlags & OPTS_CHECKSUM_PRESENT) !== 0; this.moreToCome = (this.responseFlags & OPTS_MORE_TO_COME) !== 0; this.exhaustAllowed = (this.responseFlags & OPTS_EXHAUST_ALLOWED) !== 0; this.useBigInt64 = typeof this.opts.useBigInt64 === "boolean" ? this.opts.useBigInt64 : false; this.promoteLongs = typeof this.opts.promoteLongs === "boolean" ? this.opts.promoteLongs : true; this.promoteValues = typeof this.opts.promoteValues === "boolean" ? this.opts.promoteValues : true; this.promoteBuffers = typeof this.opts.promoteBuffers === "boolean" ? this.opts.promoteBuffers : false; this.bsonRegExp = typeof this.opts.bsonRegExp === "boolean" ? this.opts.bsonRegExp : false; } isParsed() { return this.parsed; } parse() { if (this.parsed) return this.sections[0]; this.index = 4; while (this.index < this.data.length) { const payloadType = this.data.readUInt8(this.index++); if (payloadType === 0) { const bsonSize = this.data.readUInt32LE(this.index); const bin = this.data.subarray(this.index, this.index + bsonSize); this.sections.push(bin); this.index += bsonSize; } else if (payloadType === 1) { throw new error_1.MongoRuntimeError("OP_MSG Payload Type 1 detected unsupported protocol"); } } this.parsed = true; return this.sections[0]; } }; exports2.OpMsgResponse = OpMsgResponse; var MESSAGE_HEADER_SIZE = 16; var COMPRESSION_DETAILS_SIZE = 9; var OpCompressedRequest = class { constructor(command, options) { this.command = command; this.options = { zlibCompressionLevel: options.zlibCompressionLevel, agreedCompressor: options.agreedCompressor }; } // Return whether a command contains an uncompressible command term // Will return true if command contains no uncompressible command terms static canCompress(command) { const commandDoc = command instanceof OpMsgRequest ? command.command : command.query; const commandName = Object.keys(commandDoc)[0]; return !compression_1.uncompressibleCommands.has(commandName); } async toBin() { const concatenatedOriginalCommandBuffer = Buffer.concat(this.command.toBin()); const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE); const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12); const compressedMessage = await (0, compression_1.compress)(this.options, messageToBeCompressed); const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE); msgHeader.writeInt32LE(MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length, 0); msgHeader.writeInt32LE(this.command.requestId, 4); msgHeader.writeInt32LE(0, 8); msgHeader.writeInt32LE(constants_1.OP_COMPRESSED, 12); const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE); compressionDetails.writeInt32LE(originalCommandOpCode, 0); compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); compressionDetails.writeUInt8(compression_1.Compressor[this.options.agreedCompressor], 8); return [msgHeader, compressionDetails, compressedMessage]; } }; exports2.OpCompressedRequest = OpCompressedRequest; } }); // netlify/functions/node_modules/mongodb/lib/cmap/wire_protocol/compression.js var require_compression = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/wire_protocol/compression.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.uncompressibleCommands = exports2.Compressor = void 0; exports2.compress = compress; exports2.decompress = decompress; exports2.compressCommand = compressCommand; exports2.decompressResponse = decompressResponse; var util_1 = require("util"); var zlib = require("zlib"); var constants_1 = require_constants(); var deps_1 = require_deps(); var error_1 = require_error(); var commands_1 = require_commands(); var constants_2 = require_constants2(); exports2.Compressor = Object.freeze({ none: 0, snappy: 1, zlib: 2, zstd: 3 }); exports2.uncompressibleCommands = /* @__PURE__ */ new Set([ constants_1.LEGACY_HELLO_COMMAND, "saslStart", "saslContinue", "getnonce", "authenticate", "createUser", "updateUser", "copydbSaslStart", "copydbgetnonce", "copydb" ]); var ZSTD_COMPRESSION_LEVEL = 3; var zlibInflate = (0, util_1.promisify)(zlib.inflate.bind(zlib)); var zlibDeflate = (0, util_1.promisify)(zlib.deflate.bind(zlib)); var zstd; var Snappy = null; function loadSnappy() { if (Snappy == null) { const snappyImport = (0, deps_1.getSnappy)(); if ("kModuleError" in snappyImport) { throw snappyImport.kModuleError; } Snappy = snappyImport; } return Snappy; } async function compress(options, dataToBeCompressed) { const zlibOptions = {}; switch (options.agreedCompressor) { case "snappy": { Snappy ??= loadSnappy(); return await Snappy.compress(dataToBeCompressed); } case "zstd": { loadZstd(); if ("kModuleError" in zstd) { throw zstd["kModuleError"]; } return await zstd.compress(dataToBeCompressed, ZSTD_COMPRESSION_LEVEL); } case "zlib": { if (options.zlibCompressionLevel) { zlibOptions.level = options.zlibCompressionLevel; } return await zlibDeflate(dataToBeCompressed, zlibOptions); } default: { throw new error_1.MongoInvalidArgumentError(`Unknown compressor ${options.agreedCompressor} failed to compress`); } } } async function decompress(compressorID, compressedData) { if (compressorID !== exports2.Compressor.snappy && compressorID !== exports2.Compressor.zstd && compressorID !== exports2.Compressor.zlib && compressorID !== exports2.Compressor.none) { throw new error_1.MongoDecompressionError(`Server sent message compressed using an unsupported compressor. (Received compressor ID ${compressorID})`); } switch (compressorID) { case exports2.Compressor.snappy: { Snappy ??= loadSnappy(); return await Snappy.uncompress(compressedData, { asBuffer: true }); } case exports2.Compressor.zstd: { loadZstd(); if ("kModuleError" in zstd) { throw zstd["kModuleError"]; } return await zstd.decompress(compressedData); } case exports2.Compressor.zlib: { return await zlibInflate(compressedData); } default: { return compressedData; } } } function loadZstd() { if (!zstd) { zstd = (0, deps_1.getZstdLibrary)(); } } var MESSAGE_HEADER_SIZE = 16; async function compressCommand(command, description) { const finalCommand = description.agreedCompressor === "none" || !commands_1.OpCompressedRequest.canCompress(command) ? command : new commands_1.OpCompressedRequest(command, { agreedCompressor: description.agreedCompressor ?? "none", zlibCompressionLevel: description.zlibCompressionLevel ?? 0 }); const data = await finalCommand.toBin(); return Buffer.concat(data); } async function decompressResponse(message) { const messageHeader = { length: message.readInt32LE(0), requestId: message.readInt32LE(4), responseTo: message.readInt32LE(8), opCode: message.readInt32LE(12) }; if (messageHeader.opCode !== constants_2.OP_COMPRESSED) { const ResponseType2 = messageHeader.opCode === constants_2.OP_MSG ? commands_1.OpMsgResponse : commands_1.OpReply; const messageBody2 = message.subarray(MESSAGE_HEADER_SIZE); return new ResponseType2(message, messageHeader, messageBody2); } const header = { ...messageHeader, fromCompressed: true, opCode: message.readInt32LE(MESSAGE_HEADER_SIZE), length: message.readInt32LE(MESSAGE_HEADER_SIZE + 4) }; const compressorID = message[MESSAGE_HEADER_SIZE + 8]; const compressedBuffer = message.slice(MESSAGE_HEADER_SIZE + 9); const ResponseType = header.opCode === constants_2.OP_MSG ? commands_1.OpMsgResponse : commands_1.OpReply; const messageBody = await decompress(compressorID, compressedBuffer); if (messageBody.length !== header.length) { throw new error_1.MongoDecompressionError("Message body and message header must be the same length"); } return new ResponseType(message, header, messageBody); } } }); // netlify/functions/node_modules/mongodb/lib/client-side-encryption/crypto_callbacks.js var require_crypto_callbacks = __commonJS({ "netlify/functions/node_modules/mongodb/lib/client-side-encryption/crypto_callbacks.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.hmacSha256Hook = exports2.hmacSha512Hook = exports2.aes256CtrDecryptHook = exports2.aes256CtrEncryptHook = exports2.aes256CbcDecryptHook = exports2.aes256CbcEncryptHook = void 0; exports2.makeAES256Hook = makeAES256Hook; exports2.randomHook = randomHook; exports2.sha256Hook = sha256Hook; exports2.makeHmacHook = makeHmacHook; exports2.signRsaSha256Hook = signRsaSha256Hook; var crypto = require("crypto"); function makeAES256Hook(method, mode) { return function(key, iv, input, output) { let result; try { const cipher = crypto[method](mode, key, iv); cipher.setAutoPadding(false); result = cipher.update(input); const final = cipher.final(); if (final.length > 0) { result = Buffer.concat([result, final]); } } catch (e) { return e; } result.copy(output); return result.length; }; } function randomHook(buffer, count) { try { crypto.randomFillSync(buffer, 0, count); } catch (e) { return e; } return count; } function sha256Hook(input, output) { let result; try { result = crypto.createHash("sha256").update(input).digest(); } catch (e) { return e; } result.copy(output); return result.length; } function makeHmacHook(algorithm) { return (key, input, output) => { let result; try { result = crypto.createHmac(algorithm, key).update(input).digest(); } catch (e) { return e; } result.copy(output); return result.length; }; } function signRsaSha256Hook(key, input, output) { let result; try { const signer = crypto.createSign("sha256WithRSAEncryption"); const privateKey = Buffer.from(`-----BEGIN PRIVATE KEY----- ${key.toString("base64")} -----END PRIVATE KEY----- `); result = signer.update(input).end().sign(privateKey); } catch (e) { return e; } result.copy(output); return result.length; } exports2.aes256CbcEncryptHook = makeAES256Hook("createCipheriv", "aes-256-cbc"); exports2.aes256CbcDecryptHook = makeAES256Hook("createDecipheriv", "aes-256-cbc"); exports2.aes256CtrEncryptHook = makeAES256Hook("createCipheriv", "aes-256-ctr"); exports2.aes256CtrDecryptHook = makeAES256Hook("createDecipheriv", "aes-256-ctr"); exports2.hmacSha512Hook = makeHmacHook("sha512"); exports2.hmacSha256Hook = makeHmacHook("sha256"); } }); // netlify/functions/node_modules/mongodb/lib/client-side-encryption/errors.js var require_errors = __commonJS({ "netlify/functions/node_modules/mongodb/lib/client-side-encryption/errors.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.MongoCryptKMSRequestNetworkTimeoutError = exports2.MongoCryptAzureKMSRequestError = exports2.MongoCryptCreateEncryptedCollectionError = exports2.MongoCryptCreateDataKeyError = exports2.MongoCryptInvalidArgumentError = exports2.MongoCryptError = void 0; var error_1 = require_error(); var MongoCryptError = class extends error_1.MongoError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message, options = {}) { super(message, options); } get name() { return "MongoCryptError"; } }; exports2.MongoCryptError = MongoCryptError; var MongoCryptInvalidArgumentError = class extends MongoCryptError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message) { super(message); } get name() { return "MongoCryptInvalidArgumentError"; } }; exports2.MongoCryptInvalidArgumentError = MongoCryptInvalidArgumentError; var MongoCryptCreateDataKeyError = class extends MongoCryptError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(encryptedFields, { cause }) { super(`Unable to complete creating data keys: ${cause.message}`, { cause }); this.encryptedFields = encryptedFields; } get name() { return "MongoCryptCreateDataKeyError"; } }; exports2.MongoCryptCreateDataKeyError = MongoCryptCreateDataKeyError; var MongoCryptCreateEncryptedCollectionError = class extends MongoCryptError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(encryptedFields, { cause }) { super(`Unable to create collection: ${cause.message}`, { cause }); this.encryptedFields = encryptedFields; } get name() { return "MongoCryptCreateEncryptedCollectionError"; } }; exports2.MongoCryptCreateEncryptedCollectionError = MongoCryptCreateEncryptedCollectionError; var MongoCryptAzureKMSRequestError = class extends MongoCryptError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message, body) { super(message); this.body = body; } get name() { return "MongoCryptAzureKMSRequestError"; } }; exports2.MongoCryptAzureKMSRequestError = MongoCryptAzureKMSRequestError; var MongoCryptKMSRequestNetworkTimeoutError = class extends MongoCryptError { get name() { return "MongoCryptKMSRequestNetworkTimeoutError"; } }; exports2.MongoCryptKMSRequestNetworkTimeoutError = MongoCryptKMSRequestNetworkTimeoutError; } }); // netlify/functions/node_modules/mongodb/lib/cmap/auth/aws_temporary_credentials.js var require_aws_temporary_credentials = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/auth/aws_temporary_credentials.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.LegacyAWSTemporaryCredentialProvider = exports2.AWSSDKCredentialProvider = exports2.AWSTemporaryCredentialProvider = void 0; var deps_1 = require_deps(); var error_1 = require_error(); var utils_1 = require_utils(); var AWS_RELATIVE_URI = "http://169.254.170.2"; var AWS_EC2_URI = "http://169.254.169.254"; var AWS_EC2_PATH = "/latest/meta-data/iam/security-credentials"; var AWSTemporaryCredentialProvider = class _AWSTemporaryCredentialProvider { static get awsSDK() { _AWSTemporaryCredentialProvider._awsSDK ??= (0, deps_1.getAwsCredentialProvider)(); return _AWSTemporaryCredentialProvider._awsSDK; } static get isAWSSDKInstalled() { return !("kModuleError" in _AWSTemporaryCredentialProvider.awsSDK); } }; exports2.AWSTemporaryCredentialProvider = AWSTemporaryCredentialProvider; var AWSSDKCredentialProvider = class extends AWSTemporaryCredentialProvider { /** * Create the SDK credentials provider. * @param credentialsProvider - The credentials provider. */ constructor(credentialsProvider) { super(); if (credentialsProvider) { this._provider = credentialsProvider; } } /** * The AWS SDK caches credentials automatically and handles refresh when the credentials have expired. * To ensure this occurs, we need to cache the `provider` returned by the AWS sdk and re-use it when fetching credentials. */ get provider() { if ("kModuleError" in AWSTemporaryCredentialProvider.awsSDK) { throw AWSTemporaryCredentialProvider.awsSDK.kModuleError; } if (this._provider) { return this._provider; } let { AWS_STS_REGIONAL_ENDPOINTS = "", AWS_REGION = "" } = process.env; AWS_STS_REGIONAL_ENDPOINTS = AWS_STS_REGIONAL_ENDPOINTS.toLowerCase(); AWS_REGION = AWS_REGION.toLowerCase(); const awsRegionSettingsExist = AWS_REGION.length !== 0 && AWS_STS_REGIONAL_ENDPOINTS.length !== 0; const LEGACY_REGIONS = /* @__PURE__ */ new Set([ "ap-northeast-1", "ap-south-1", "ap-southeast-1", "ap-southeast-2", "aws-global", "ca-central-1", "eu-central-1", "eu-north-1", "eu-west-1", "eu-west-2", "eu-west-3", "sa-east-1", "us-east-1", "us-east-2", "us-west-1", "us-west-2" ]); const useRegionalSts = AWS_STS_REGIONAL_ENDPOINTS === "regional" || AWS_STS_REGIONAL_ENDPOINTS === "legacy" && !LEGACY_REGIONS.has(AWS_REGION); this._provider = awsRegionSettingsExist && useRegionalSts ? AWSTemporaryCredentialProvider.awsSDK.fromNodeProviderChain({ clientConfig: { region: AWS_REGION } }) : AWSTemporaryCredentialProvider.awsSDK.fromNodeProviderChain(); return this._provider; } async getCredentials() { try { const creds = await this.provider(); return { AccessKeyId: creds.accessKeyId, SecretAccessKey: creds.secretAccessKey, Token: creds.sessionToken, Expiration: creds.expiration }; } catch (error) { throw new error_1.MongoAWSError(error.message, { cause: error }); } } }; exports2.AWSSDKCredentialProvider = AWSSDKCredentialProvider; var LegacyAWSTemporaryCredentialProvider = class extends AWSTemporaryCredentialProvider { async getCredentials() { if (process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI) { return await (0, utils_1.request)(`${AWS_RELATIVE_URI}${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`); } const token = await (0, utils_1.request)(`${AWS_EC2_URI}/latest/api/token`, { method: "PUT", json: false, headers: { "X-aws-ec2-metadata-token-ttl-seconds": 30 } }); const roleName = await (0, utils_1.request)(`${AWS_EC2_URI}/${AWS_EC2_PATH}`, { json: false, headers: { "X-aws-ec2-metadata-token": token } }); const creds = await (0, utils_1.request)(`${AWS_EC2_URI}/${AWS_EC2_PATH}/${roleName}`, { headers: { "X-aws-ec2-metadata-token": token } }); return creds; } }; exports2.LegacyAWSTemporaryCredentialProvider = LegacyAWSTemporaryCredentialProvider; } }); // netlify/functions/node_modules/mongodb/lib/client-side-encryption/providers/aws.js var require_aws = __commonJS({ "netlify/functions/node_modules/mongodb/lib/client-side-encryption/providers/aws.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.loadAWSCredentials = loadAWSCredentials; var aws_temporary_credentials_1 = require_aws_temporary_credentials(); async function loadAWSCredentials(kmsProviders, provider) { const credentialProvider = new aws_temporary_credentials_1.AWSSDKCredentialProvider(provider); const { SecretAccessKey = "", AccessKeyId = "", Token } = await credentialProvider.getCredentials(); const aws = { secretAccessKey: SecretAccessKey, accessKeyId: AccessKeyId }; Token != null && (aws.sessionToken = Token); return { ...kmsProviders, aws }; } } }); // netlify/functions/node_modules/mongodb/lib/client-side-encryption/providers/azure.js var require_azure = __commonJS({ "netlify/functions/node_modules/mongodb/lib/client-side-encryption/providers/azure.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.tokenCache = exports2.AzureCredentialCache = exports2.AZURE_BASE_URL = void 0; exports2.addAzureParams = addAzureParams; exports2.prepareRequest = prepareRequest; exports2.fetchAzureKMSToken = fetchAzureKMSToken; exports2.loadAzureCredentials = loadAzureCredentials; var error_1 = require_error(); var utils_1 = require_utils(); var errors_1 = require_errors(); var MINIMUM_TOKEN_REFRESH_IN_MILLISECONDS = 6e3; exports2.AZURE_BASE_URL = "http://169.254.169.254/metadata/identity/oauth2/token?"; var AzureCredentialCache = class { constructor() { this.cachedToken = null; } async getToken() { if (this.cachedToken == null || this.needsRefresh(this.cachedToken)) { this.cachedToken = await this._getToken(); } return { accessToken: this.cachedToken.accessToken }; } needsRefresh(token) { const timeUntilExpirationMS = token.expiresOnTimestamp - Date.now(); return timeUntilExpirationMS <= MINIMUM_TOKEN_REFRESH_IN_MILLISECONDS; } /** * exposed for testing */ resetCache() { this.cachedToken = null; } /** * exposed for testing */ _getToken() { return fetchAzureKMSToken(); } }; exports2.AzureCredentialCache = AzureCredentialCache; exports2.tokenCache = new AzureCredentialCache(); async function parseResponse(response) { const { status, body: rawBody } = response; const body = (() => { try { return JSON.parse(rawBody); } catch { throw new errors_1.MongoCryptAzureKMSRequestError("Malformed JSON body in GET request."); } })(); if (status !== 200) { throw new errors_1.MongoCryptAzureKMSRequestError("Unable to complete request.", body); } if (!body.access_token) { throw new errors_1.MongoCryptAzureKMSRequestError("Malformed response body - missing field `access_token`."); } if (!body.expires_in) { throw new errors_1.MongoCryptAzureKMSRequestError("Malformed response body - missing field `expires_in`."); } const expiresInMS = Number(body.expires_in) * 1e3; if (Number.isNaN(expiresInMS)) { throw new errors_1.MongoCryptAzureKMSRequestError("Malformed response body - unable to parse int from `expires_in` field."); } return { accessToken: body.access_token, expiresOnTimestamp: Date.now() + expiresInMS }; } function addAzureParams(url, resource, username) { url.searchParams.append("api-version", "2018-02-01"); url.searchParams.append("resource", resource); if (username) { url.searchParams.append("client_id", username); } return url; } function prepareRequest(options) { const url = new URL(options.url?.toString() ?? exports2.AZURE_BASE_URL); addAzureParams(url, "https://vault.azure.net"); const headers = { ...options.headers, "Content-Type": "application/json", Metadata: true }; return { headers, url }; } async function fetchAzureKMSToken(options = {}) { const { headers, url } = prepareRequest(options); try { const response = await (0, utils_1.get)(url, { headers }); return await parseResponse(response); } catch (error) { if (error instanceof error_1.MongoNetworkTimeoutError) { throw new errors_1.MongoCryptAzureKMSRequestError(`[Azure KMS] ${error.message}`); } throw error; } } async function loadAzureCredentials(kmsProviders) { const azure = await exports2.tokenCache.getToken(); return { ...kmsProviders, azure }; } } }); // netlify/functions/node_modules/mongodb/lib/client-side-encryption/providers/gcp.js var require_gcp = __commonJS({ "netlify/functions/node_modules/mongodb/lib/client-side-encryption/providers/gcp.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.loadGCPCredentials = loadGCPCredentials; var deps_1 = require_deps(); async function loadGCPCredentials(kmsProviders) { const gcpMetadata = (0, deps_1.getGcpMetadata)(); if ("kModuleError" in gcpMetadata) { return kmsProviders; } const { access_token: accessToken } = await gcpMetadata.instance({ property: "service-accounts/default/token" }); return { ...kmsProviders, gcp: { accessToken } }; } } }); // netlify/functions/node_modules/mongodb/lib/client-side-encryption/providers/index.js var require_providers2 = __commonJS({ "netlify/functions/node_modules/mongodb/lib/client-side-encryption/providers/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.isEmptyCredentials = isEmptyCredentials; exports2.refreshKMSCredentials = refreshKMSCredentials; var aws_1 = require_aws(); var azure_1 = require_azure(); var gcp_1 = require_gcp(); function isEmptyCredentials(providerName, kmsProviders) { const provider = kmsProviders[providerName]; if (provider == null) { return false; } return typeof provider === "object" && Object.keys(provider).length === 0; } async function refreshKMSCredentials(kmsProviders, credentialProviders) { let finalKMSProviders = kmsProviders; if (isEmptyCredentials("aws", kmsProviders)) { finalKMSProviders = await (0, aws_1.loadAWSCredentials)(finalKMSProviders, credentialProviders?.aws); } if (isEmptyCredentials("gcp", kmsProviders)) { finalKMSProviders = await (0, gcp_1.loadGCPCredentials)(finalKMSProviders); } if (isEmptyCredentials("azure", kmsProviders)) { finalKMSProviders = await (0, azure_1.loadAzureCredentials)(finalKMSProviders); } return finalKMSProviders; } } }); // netlify/functions/node_modules/mongodb/lib/client-side-encryption/state_machine.js var require_state_machine = __commonJS({ "netlify/functions/node_modules/mongodb/lib/client-side-encryption/state_machine.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.StateMachine = void 0; var fs = require("fs/promises"); var net = require("net"); var tls = require("tls"); var bson_1 = require_bson2(); var abstract_cursor_1 = require_abstract_cursor(); var deps_1 = require_deps(); var error_1 = require_error(); var timeout_1 = require_timeout(); var utils_1 = require_utils(); var client_encryption_1 = require_client_encryption(); var errors_1 = require_errors(); var socks = null; function loadSocks() { if (socks == null) { const socksImport = (0, deps_1.getSocks)(); if ("kModuleError" in socksImport) { throw socksImport.kModuleError; } socks = socksImport; } return socks; } var MONGOCRYPT_CTX_ERROR = 0; var MONGOCRYPT_CTX_NEED_MONGO_COLLINFO = 1; var MONGOCRYPT_CTX_NEED_MONGO_MARKINGS = 2; var MONGOCRYPT_CTX_NEED_MONGO_KEYS = 3; var MONGOCRYPT_CTX_NEED_KMS_CREDENTIALS = 7; var MONGOCRYPT_CTX_NEED_KMS = 4; var MONGOCRYPT_CTX_READY = 5; var MONGOCRYPT_CTX_DONE = 6; var HTTPS_PORT = 443; var stateToString = /* @__PURE__ */ new Map([ [MONGOCRYPT_CTX_ERROR, "MONGOCRYPT_CTX_ERROR"], [MONGOCRYPT_CTX_NEED_MONGO_COLLINFO, "MONGOCRYPT_CTX_NEED_MONGO_COLLINFO"], [MONGOCRYPT_CTX_NEED_MONGO_MARKINGS, "MONGOCRYPT_CTX_NEED_MONGO_MARKINGS"], [MONGOCRYPT_CTX_NEED_MONGO_KEYS, "MONGOCRYPT_CTX_NEED_MONGO_KEYS"], [MONGOCRYPT_CTX_NEED_KMS_CREDENTIALS, "MONGOCRYPT_CTX_NEED_KMS_CREDENTIALS"], [MONGOCRYPT_CTX_NEED_KMS, "MONGOCRYPT_CTX_NEED_KMS"], [MONGOCRYPT_CTX_READY, "MONGOCRYPT_CTX_READY"], [MONGOCRYPT_CTX_DONE, "MONGOCRYPT_CTX_DONE"] ]); var INSECURE_TLS_OPTIONS = [ "tlsInsecure", "tlsAllowInvalidCertificates", "tlsAllowInvalidHostnames" ]; function debug(msg) { if (process.env.MONGODB_CRYPT_DEBUG) { console.error(msg); } } var EMPTY_V; var StateMachine = class { constructor(options, bsonOptions = (0, bson_1.pluckBSONSerializeOptions)(options)) { this.options = options; this.bsonOptions = bsonOptions; } /** * Executes the state machine according to the specification */ async execute(executor, context, options) { const keyVaultNamespace = executor._keyVaultNamespace; const keyVaultClient = executor._keyVaultClient; const metaDataClient = executor._metaDataClient; const mongocryptdClient = executor._mongocryptdClient; const mongocryptdManager = executor._mongocryptdManager; let result = null; const getStatus = () => context.status; const getState = () => context.state; while (getState() !== MONGOCRYPT_CTX_DONE && getState() !== MONGOCRYPT_CTX_ERROR) { options.signal?.throwIfAborted(); debug(`[context#${context.id}] ${stateToString.get(getState()) || getState()}`); switch (getState()) { case MONGOCRYPT_CTX_NEED_MONGO_COLLINFO: { const filter = (0, bson_1.deserialize)(context.nextMongoOperation()); if (!metaDataClient) { throw new errors_1.MongoCryptError("unreachable state machine state: entered MONGOCRYPT_CTX_NEED_MONGO_COLLINFO but metadata client is undefined"); } const collInfoCursor = this.fetchCollectionInfo(metaDataClient, context.ns, filter, options); for await (const collInfo of collInfoCursor) { context.addMongoOperationResponse((0, bson_1.serialize)(collInfo)); if (getState() === MONGOCRYPT_CTX_ERROR) break; } if (getState() === MONGOCRYPT_CTX_ERROR) break; context.finishMongoOperation(); break; } case MONGOCRYPT_CTX_NEED_MONGO_MARKINGS: { const command = context.nextMongoOperation(); if (getState() === MONGOCRYPT_CTX_ERROR) break; if (!mongocryptdClient) { throw new errors_1.MongoCryptError("unreachable state machine state: entered MONGOCRYPT_CTX_NEED_MONGO_MARKINGS but mongocryptdClient is undefined"); } const markedCommand = mongocryptdManager ? await mongocryptdManager.withRespawn(this.markCommand.bind(this, mongocryptdClient, context.ns, command, options)) : await this.markCommand(mongocryptdClient, context.ns, command, options); context.addMongoOperationResponse(markedCommand); context.finishMongoOperation(); break; } case MONGOCRYPT_CTX_NEED_MONGO_KEYS: { const filter = context.nextMongoOperation(); const keys = await this.fetchKeys(keyVaultClient, keyVaultNamespace, filter, options); if (keys.length === 0) { result = EMPTY_V ??= (0, bson_1.serialize)({ v: [] }); } for (const key of keys) { context.addMongoOperationResponse((0, bson_1.serialize)(key)); } context.finishMongoOperation(); break; } case MONGOCRYPT_CTX_NEED_KMS_CREDENTIALS: { const kmsProviders = await executor.askForKMSCredentials(); context.provideKMSProviders((0, bson_1.serialize)(kmsProviders)); break; } case MONGOCRYPT_CTX_NEED_KMS: { await Promise.all(this.requests(context, options)); context.finishKMSRequests(); break; } case MONGOCRYPT_CTX_READY: { const finalizedContext = context.finalize(); if (getState() === MONGOCRYPT_CTX_ERROR) { const message = getStatus().message || "Finalization error"; throw new errors_1.MongoCryptError(message); } result = finalizedContext; break; } default: throw new errors_1.MongoCryptError(`Unknown state: ${getState()}`); } } if (getState() === MONGOCRYPT_CTX_ERROR || result == null) { const message = getStatus().message; if (!message) { debug(`unidentifiable error in MongoCrypt - received an error status from \`libmongocrypt\` but received no error message.`); } throw new errors_1.MongoCryptError(message ?? "unidentifiable error in MongoCrypt - received an error status from `libmongocrypt` but received no error message."); } return result; } /** * Handles the request to the KMS service. Exposed for testing purposes. Do not directly invoke. * @param kmsContext - A C++ KMS context returned from the bindings * @returns A promise that resolves when the KMS reply has be fully parsed */ async kmsRequest(request, options) { const parsedUrl = request.endpoint.split(":"); const port = parsedUrl[1] != null ? Number.parseInt(parsedUrl[1], 10) : HTTPS_PORT; const socketOptions = { host: parsedUrl[0], servername: parsedUrl[0], port, ...(0, client_encryption_1.autoSelectSocketOptions)(this.options.socketOptions || {}) }; const message = request.message; const buffer = new utils_1.BufferPool(); let netSocket; let socket; function destroySockets() { for (const sock of [socket, netSocket]) { if (sock) { sock.destroy(); } } } function onerror(cause) { return new errors_1.MongoCryptError("KMS request failed", { cause }); } function onclose() { return new errors_1.MongoCryptError("KMS request closed"); } const tlsOptions = this.options.tlsOptions; if (tlsOptions) { const kmsProvider = request.kmsProvider; const providerTlsOptions = tlsOptions[kmsProvider]; if (providerTlsOptions) { const error = this.validateTlsOptions(kmsProvider, providerTlsOptions); if (error) { throw error; } try { await this.setTlsOptions(providerTlsOptions, socketOptions); } catch (err) { throw onerror(err); } } } let abortListener; try { if (this.options.proxyOptions && this.options.proxyOptions.proxyHost) { netSocket = new net.Socket(); const { promise: willConnect, reject: rejectOnNetSocketError, resolve: resolveOnNetSocketConnect } = (0, utils_1.promiseWithResolvers)(); netSocket.once("error", (err) => rejectOnNetSocketError(onerror(err))).once("close", () => rejectOnNetSocketError(onclose())).once("connect", () => resolveOnNetSocketConnect()); const netSocketOptions = { ...socketOptions, host: this.options.proxyOptions.proxyHost, port: this.options.proxyOptions.proxyPort || 1080 }; netSocket.connect(netSocketOptions); await willConnect; try { socks ??= loadSocks(); socketOptions.socket = (await socks.SocksClient.createConnection({ existing_socket: netSocket, command: "connect", destination: { host: socketOptions.host, port: socketOptions.port }, proxy: { // host and port are ignored because we pass existing_socket host: "iLoveJavaScript", port: 0, type: 5, userId: this.options.proxyOptions.proxyUsername, password: this.options.proxyOptions.proxyPassword } })).socket; } catch (err) { throw onerror(err); } } socket = tls.connect(socketOptions, () => { socket.write(message); }); const { promise: willResolveKmsRequest, reject: rejectOnTlsSocketError, resolve } = (0, utils_1.promiseWithResolvers)(); abortListener = (0, utils_1.addAbortListener)(options?.signal, function() { destroySockets(); rejectOnTlsSocketError(this.reason); }); socket.once("error", (err) => rejectOnTlsSocketError(onerror(err))).once("close", () => rejectOnTlsSocketError(onclose())).on("data", (data) => { buffer.append(data); while (request.bytesNeeded > 0 && buffer.length) { const bytesNeeded = Math.min(request.bytesNeeded, buffer.length); request.addResponse(buffer.read(bytesNeeded)); } if (request.bytesNeeded <= 0) { resolve(); } }); await (options?.timeoutContext?.csotEnabled() ? Promise.all([ willResolveKmsRequest, timeout_1.Timeout.expires(options.timeoutContext?.remainingTimeMS) ]) : willResolveKmsRequest); } catch (error) { if (error instanceof timeout_1.TimeoutError) throw new error_1.MongoOperationTimeoutError("KMS request timed out"); throw error; } finally { destroySockets(); abortListener?.[utils_1.kDispose](); } } *requests(context, options) { for (let request = context.nextKMSRequest(); request != null; request = context.nextKMSRequest()) { yield this.kmsRequest(request, options); } } /** * Validates the provided TLS options are secure. * * @param kmsProvider - The KMS provider name. * @param tlsOptions - The client TLS options for the provider. * * @returns An error if any option is invalid. */ validateTlsOptions(kmsProvider, tlsOptions) { const tlsOptionNames = Object.keys(tlsOptions); for (const option of INSECURE_TLS_OPTIONS) { if (tlsOptionNames.includes(option)) { return new errors_1.MongoCryptError(`Insecure TLS options prohibited for ${kmsProvider}: ${option}`); } } } /** * Sets only the valid secure TLS options. * * @param tlsOptions - The client TLS options for the provider. * @param options - The existing connection options. */ async setTlsOptions(tlsOptions, options) { if (tlsOptions.tlsCertificateKeyFile) { const cert = await fs.readFile(tlsOptions.tlsCertificateKeyFile); options.cert = options.key = cert; } if (tlsOptions.tlsCAFile) { options.ca = await fs.readFile(tlsOptions.tlsCAFile); } if (tlsOptions.tlsCertificateKeyFilePassword) { options.passphrase = tlsOptions.tlsCertificateKeyFilePassword; } } /** * Fetches collection info for a provided namespace, when libmongocrypt * enters the `MONGOCRYPT_CTX_NEED_MONGO_COLLINFO` state. The result is * used to inform libmongocrypt of the schema associated with this * namespace. Exposed for testing purposes. Do not directly invoke. * * @param client - A MongoClient connected to the topology * @param ns - The namespace to list collections from * @param filter - A filter for the listCollections command * @param callback - Invoked with the info of the requested collection, or with an error */ fetchCollectionInfo(client, ns, filter, options) { const { db } = utils_1.MongoDBCollectionNamespace.fromString(ns); const cursor = client.db(db).listCollections(filter, { promoteLongs: false, promoteValues: false, timeoutContext: options?.timeoutContext && new abstract_cursor_1.CursorTimeoutContext(options?.timeoutContext, Symbol()), signal: options?.signal, nameOnly: false }); return cursor; } /** * Calls to the mongocryptd to provide markings for a command. * Exposed for testing purposes. Do not directly invoke. * @param client - A MongoClient connected to a mongocryptd * @param ns - The namespace (database.collection) the command is being executed on * @param command - The command to execute. * @param callback - Invoked with the serialized and marked bson command, or with an error */ async markCommand(client, ns, command, options) { const { db } = utils_1.MongoDBCollectionNamespace.fromString(ns); const bsonOptions = { promoteLongs: false, promoteValues: false }; const rawCommand = (0, bson_1.deserialize)(command, bsonOptions); const commandOptions = { timeoutMS: void 0, signal: void 0 }; if (options?.timeoutContext?.csotEnabled()) { commandOptions.timeoutMS = options.timeoutContext.remainingTimeMS; } if (options?.signal) { commandOptions.signal = options.signal; } const response = await client.db(db).command(rawCommand, { ...bsonOptions, ...commandOptions }); return (0, bson_1.serialize)(response, this.bsonOptions); } /** * Requests keys from the keyVault collection on the topology. * Exposed for testing purposes. Do not directly invoke. * @param client - A MongoClient connected to the topology * @param keyVaultNamespace - The namespace (database.collection) of the keyVault Collection * @param filter - The filter for the find query against the keyVault Collection * @param callback - Invoked with the found keys, or with an error */ fetchKeys(client, keyVaultNamespace, filter, options) { const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(keyVaultNamespace); const commandOptions = { timeoutContext: void 0, signal: void 0 }; if (options?.timeoutContext != null) { commandOptions.timeoutContext = new abstract_cursor_1.CursorTimeoutContext(options.timeoutContext, Symbol()); } if (options?.signal != null) { commandOptions.signal = options.signal; } return client.db(dbName).collection(collectionName, { readConcern: { level: "majority" } }).find((0, bson_1.deserialize)(filter), commandOptions).toArray(); } }; exports2.StateMachine = StateMachine; } }); // netlify/functions/node_modules/mongodb/lib/client-side-encryption/client_encryption.js var require_client_encryption = __commonJS({ "netlify/functions/node_modules/mongodb/lib/client-side-encryption/client_encryption.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ClientEncryption = void 0; exports2.autoSelectSocketOptions = autoSelectSocketOptions; var bson_1 = require_bson2(); var deps_1 = require_deps(); var timeout_1 = require_timeout(); var utils_1 = require_utils(); var cryptoCallbacks = require_crypto_callbacks(); var errors_1 = require_errors(); var index_1 = require_providers2(); var state_machine_1 = require_state_machine(); var ClientEncryption = class _ClientEncryption { /** @internal */ static getMongoCrypt() { const encryption = (0, deps_1.getMongoDBClientEncryption)(); if ("kModuleError" in encryption) { throw encryption.kModuleError; } return encryption.MongoCrypt; } /** * Create a new encryption instance * * @example * ```ts * new ClientEncryption(mongoClient, { * keyVaultNamespace: 'client.encryption', * kmsProviders: { * local: { * key: masterKey // The master key used for encryption/decryption. A 96-byte long Buffer * } * } * }); * ``` * * @example * ```ts * new ClientEncryption(mongoClient, { * keyVaultNamespace: 'client.encryption', * kmsProviders: { * aws: { * accessKeyId: AWS_ACCESS_KEY, * secretAccessKey: AWS_SECRET_KEY * } * } * }); * ``` */ constructor(client, options) { this._client = client; this._proxyOptions = options.proxyOptions ?? {}; this._tlsOptions = options.tlsOptions ?? {}; this._kmsProviders = options.kmsProviders || {}; const { timeoutMS } = (0, utils_1.resolveTimeoutOptions)(client, options); this._timeoutMS = timeoutMS; this._credentialProviders = options.credentialProviders; if (options.credentialProviders?.aws && !(0, index_1.isEmptyCredentials)("aws", this._kmsProviders)) { throw new errors_1.MongoCryptInvalidArgumentError("Can only provide a custom AWS credential provider when the state machine is configured for automatic AWS credential fetching"); } if (options.keyVaultNamespace == null) { throw new errors_1.MongoCryptInvalidArgumentError("Missing required option `keyVaultNamespace`"); } const mongoCryptOptions = { ...options, cryptoCallbacks, kmsProviders: !Buffer.isBuffer(this._kmsProviders) ? (0, bson_1.serialize)(this._kmsProviders) : this._kmsProviders }; this._keyVaultNamespace = options.keyVaultNamespace; this._keyVaultClient = options.keyVaultClient || client; const MongoCrypt = _ClientEncryption.getMongoCrypt(); this._mongoCrypt = new MongoCrypt(mongoCryptOptions); } /** * Creates a data key used for explicit encryption and inserts it into the key vault namespace * * @example * ```ts * // Using async/await to create a local key * const dataKeyId = await clientEncryption.createDataKey('local'); * ``` * * @example * ```ts * // Using async/await to create an aws key * const dataKeyId = await clientEncryption.createDataKey('aws', { * masterKey: { * region: 'us-east-1', * key: 'xxxxxxxxxxxxxx' // CMK ARN here * } * }); * ``` * * @example * ```ts * // Using async/await to create an aws key with a keyAltName * const dataKeyId = await clientEncryption.createDataKey('aws', { * masterKey: { * region: 'us-east-1', * key: 'xxxxxxxxxxxxxx' // CMK ARN here * }, * keyAltNames: [ 'mySpecialKey' ] * }); * ``` */ async createDataKey(provider, options = {}) { if (options.keyAltNames && !Array.isArray(options.keyAltNames)) { throw new errors_1.MongoCryptInvalidArgumentError(`Option "keyAltNames" must be an array of strings, but was of type ${typeof options.keyAltNames}.`); } let keyAltNames = void 0; if (options.keyAltNames && options.keyAltNames.length > 0) { keyAltNames = options.keyAltNames.map((keyAltName, i) => { if (typeof keyAltName !== "string") { throw new errors_1.MongoCryptInvalidArgumentError(`Option "keyAltNames" must be an array of strings, but item at index ${i} was of type ${typeof keyAltName}`); } return (0, bson_1.serialize)({ keyAltName }); }); } let keyMaterial = void 0; if (options.keyMaterial) { keyMaterial = (0, bson_1.serialize)({ keyMaterial: options.keyMaterial }); } const dataKeyBson = (0, bson_1.serialize)({ provider, ...options.masterKey }); const context = this._mongoCrypt.makeDataKeyContext(dataKeyBson, { keyAltNames, keyMaterial }); const stateMachine = new state_machine_1.StateMachine({ proxyOptions: this._proxyOptions, tlsOptions: this._tlsOptions, socketOptions: autoSelectSocketOptions(this._client.s.options) }); const timeoutContext = options?.timeoutContext ?? timeout_1.TimeoutContext.create((0, utils_1.resolveTimeoutOptions)(this._client, { timeoutMS: this._timeoutMS })); const dataKey = (0, bson_1.deserialize)(await stateMachine.execute(this, context, { timeoutContext })); const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace); const { insertedId } = await this._keyVaultClient.db(dbName).collection(collectionName).insertOne(dataKey, { writeConcern: { w: "majority" }, timeoutMS: timeoutContext?.csotEnabled() ? timeoutContext?.getRemainingTimeMSOrThrow() : void 0 }); return insertedId; } /** * Searches the keyvault for any data keys matching the provided filter. If there are matches, rewrapManyDataKey then attempts to re-wrap the data keys using the provided options. * * If no matches are found, then no bulk write is performed. * * @example * ```ts * // rewrapping all data data keys (using a filter that matches all documents) * const filter = {}; * * const result = await clientEncryption.rewrapManyDataKey(filter); * if (result.bulkWriteResult != null) { * // keys were re-wrapped, results will be available in the bulkWrite object. * } * ``` * * @example * ```ts * // attempting to rewrap all data keys with no matches * const filter = { _id: new Binary() } // assume _id matches no documents in the database * const result = await clientEncryption.rewrapManyDataKey(filter); * * if (result.bulkWriteResult == null) { * // no keys matched, `bulkWriteResult` does not exist on the result object * } * ``` */ async rewrapManyDataKey(filter, options) { let keyEncryptionKeyBson = void 0; if (options) { const keyEncryptionKey = Object.assign({ provider: options.provider }, options.masterKey); keyEncryptionKeyBson = (0, bson_1.serialize)(keyEncryptionKey); } const filterBson = (0, bson_1.serialize)(filter); const context = this._mongoCrypt.makeRewrapManyDataKeyContext(filterBson, keyEncryptionKeyBson); const stateMachine = new state_machine_1.StateMachine({ proxyOptions: this._proxyOptions, tlsOptions: this._tlsOptions, socketOptions: autoSelectSocketOptions(this._client.s.options) }); const timeoutContext = timeout_1.TimeoutContext.create((0, utils_1.resolveTimeoutOptions)(this._client, { timeoutMS: this._timeoutMS })); const { v: dataKeys } = (0, bson_1.deserialize)(await stateMachine.execute(this, context, { timeoutContext })); if (dataKeys.length === 0) { return {}; } const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace); const replacements = dataKeys.map((key) => ({ updateOne: { filter: { _id: key._id }, update: { $set: { masterKey: key.masterKey, keyMaterial: key.keyMaterial }, $currentDate: { updateDate: true } } } })); const result = await this._keyVaultClient.db(dbName).collection(collectionName).bulkWrite(replacements, { writeConcern: { w: "majority" }, timeoutMS: timeoutContext.csotEnabled() ? timeoutContext?.remainingTimeMS : void 0 }); return { bulkWriteResult: result }; } /** * Deletes the key with the provided id from the keyvault, if it exists. * * @example * ```ts * // delete a key by _id * const id = new Binary(); // id is a bson binary subtype 4 object * const { deletedCount } = await clientEncryption.deleteKey(id); * * if (deletedCount != null && deletedCount > 0) { * // successful deletion * } * ``` * */ async deleteKey(_id) { const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace); return await this._keyVaultClient.db(dbName).collection(collectionName).deleteOne({ _id }, { writeConcern: { w: "majority" }, timeoutMS: this._timeoutMS }); } /** * Finds all the keys currently stored in the keyvault. * * This method will not throw. * * @returns a FindCursor over all keys in the keyvault. * @example * ```ts * // fetching all keys * const keys = await clientEncryption.getKeys().toArray(); * ``` */ getKeys() { const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace); return this._keyVaultClient.db(dbName).collection(collectionName).find({}, { readConcern: { level: "majority" }, timeoutMS: this._timeoutMS }); } /** * Finds a key in the keyvault with the specified _id. * * Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents * match the id. The promise rejects with an error if an error is thrown. * @example * ```ts * // getting a key by id * const id = new Binary(); // id is a bson binary subtype 4 object * const key = await clientEncryption.getKey(id); * if (!key) { * // key is null if there was no matching key * } * ``` */ async getKey(_id) { const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace); return await this._keyVaultClient.db(dbName).collection(collectionName).findOne({ _id }, { readConcern: { level: "majority" }, timeoutMS: this._timeoutMS }); } /** * Finds a key in the keyvault which has the specified keyAltName. * * @param keyAltName - a keyAltName to search for a key * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents * match the keyAltName. The promise rejects with an error if an error is thrown. * @example * ```ts * // get a key by alt name * const keyAltName = 'keyAltName'; * const key = await clientEncryption.getKeyByAltName(keyAltName); * if (!key) { * // key is null if there is no matching key * } * ``` */ async getKeyByAltName(keyAltName) { const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace); return await this._keyVaultClient.db(dbName).collection(collectionName).findOne({ keyAltNames: keyAltName }, { readConcern: { level: "majority" }, timeoutMS: this._timeoutMS }); } /** * Adds a keyAltName to a key identified by the provided _id. * * This method resolves to/returns the *old* key value (prior to adding the new altKeyName). * * @param _id - The id of the document to update. * @param keyAltName - a keyAltName to search for a key * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents * match the id. The promise rejects with an error if an error is thrown. * @example * ```ts * // adding an keyAltName to a data key * const id = new Binary(); // id is a bson binary subtype 4 object * const keyAltName = 'keyAltName'; * const oldKey = await clientEncryption.addKeyAltName(id, keyAltName); * if (!oldKey) { * // null is returned if there is no matching document with an id matching the supplied id * } * ``` */ async addKeyAltName(_id, keyAltName) { const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace); const value = await this._keyVaultClient.db(dbName).collection(collectionName).findOneAndUpdate({ _id }, { $addToSet: { keyAltNames: keyAltName } }, { writeConcern: { w: "majority" }, returnDocument: "before", timeoutMS: this._timeoutMS }); return value; } /** * Adds a keyAltName to a key identified by the provided _id. * * This method resolves to/returns the *old* key value (prior to removing the new altKeyName). * * If the removed keyAltName is the last keyAltName for that key, the `altKeyNames` property is unset from the document. * * @param _id - The id of the document to update. * @param keyAltName - a keyAltName to search for a key * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents * match the id. The promise rejects with an error if an error is thrown. * @example * ```ts * // removing a key alt name from a data key * const id = new Binary(); // id is a bson binary subtype 4 object * const keyAltName = 'keyAltName'; * const oldKey = await clientEncryption.removeKeyAltName(id, keyAltName); * * if (!oldKey) { * // null is returned if there is no matching document with an id matching the supplied id * } * ``` */ async removeKeyAltName(_id, keyAltName) { const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace); const pipeline = [ { $set: { keyAltNames: { $cond: [ { $eq: ["$keyAltNames", [keyAltName]] }, "$$REMOVE", { $filter: { input: "$keyAltNames", cond: { $ne: ["$$this", keyAltName] } } } ] } } } ]; const value = await this._keyVaultClient.db(dbName).collection(collectionName).findOneAndUpdate({ _id }, pipeline, { writeConcern: { w: "majority" }, returnDocument: "before", timeoutMS: this._timeoutMS }); return value; } /** * A convenience method for creating an encrypted collection. * This method will create data keys for any encryptedFields that do not have a `keyId` defined * and then create a new collection with the full set of encryptedFields. * * @param db - A Node.js driver Db object with which to create the collection * @param name - The name of the collection to be created * @param options - Options for createDataKey and for createCollection * @returns created collection and generated encryptedFields * @throws MongoCryptCreateDataKeyError - If part way through the process a createDataKey invocation fails, an error will be rejected that has the partial `encryptedFields` that were created. * @throws MongoCryptCreateEncryptedCollectionError - If creating the collection fails, an error will be rejected that has the entire `encryptedFields` that were created. */ async createEncryptedCollection(db, name, options) { const { provider, masterKey, createCollectionOptions: { encryptedFields: { ...encryptedFields }, ...createCollectionOptions } } = options; const timeoutContext = this._timeoutMS != null ? timeout_1.TimeoutContext.create((0, utils_1.resolveTimeoutOptions)(this._client, { timeoutMS: this._timeoutMS })) : void 0; if (Array.isArray(encryptedFields.fields)) { const createDataKeyPromises = encryptedFields.fields.map(async (field) => field == null || typeof field !== "object" || field.keyId != null ? field : { ...field, keyId: await this.createDataKey(provider, { masterKey, // clone the timeoutContext // in order to avoid sharing the same timeout for server selection and connection checkout across different concurrent operations timeoutContext: timeoutContext?.csotEnabled() ? timeoutContext?.clone() : void 0 }) }); const createDataKeyResolutions = await Promise.allSettled(createDataKeyPromises); encryptedFields.fields = createDataKeyResolutions.map((resolution, index) => resolution.status === "fulfilled" ? resolution.value : encryptedFields.fields[index]); const rejection = createDataKeyResolutions.find((result) => result.status === "rejected"); if (rejection != null) { throw new errors_1.MongoCryptCreateDataKeyError(encryptedFields, { cause: rejection.reason }); } } try { const collection = await db.createCollection(name, { ...createCollectionOptions, encryptedFields, timeoutMS: timeoutContext?.csotEnabled() ? timeoutContext?.getRemainingTimeMSOrThrow() : void 0 }); return { collection, encryptedFields }; } catch (cause) { throw new errors_1.MongoCryptCreateEncryptedCollectionError(encryptedFields, { cause }); } } /** * Explicitly encrypt a provided value. Note that either `options.keyId` or `options.keyAltName` must * be specified. Specifying both `options.keyId` and `options.keyAltName` is considered an error. * * @param value - The value that you wish to serialize. Must be of a type that can be serialized into BSON * @param options - * @returns a Promise that either resolves with the encrypted value, or rejects with an error. * * @example * ```ts * // Encryption with async/await api * async function encryptMyData(value) { * const keyId = await clientEncryption.createDataKey('local'); * return clientEncryption.encrypt(value, { keyId, algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' }); * } * ``` * * @example * ```ts * // Encryption using a keyAltName * async function encryptMyData(value) { * await clientEncryption.createDataKey('local', { keyAltNames: 'mySpecialKey' }); * return clientEncryption.encrypt(value, { keyAltName: 'mySpecialKey', algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' }); * } * ``` */ async encrypt(value, options) { return await this._encrypt(value, false, options); } /** * Encrypts a Match Expression or Aggregate Expression to query a range index. * * Only supported when queryType is "range" and algorithm is "Range". * * @param expression - a BSON document of one of the following forms: * 1. A Match Expression of this form: * `{$and: [{: {$gt: }}, {: {$lt: }}]}` * 2. An Aggregate Expression of this form: * `{$and: [{$gt: [, ]}, {$lt: [, ]}]}` * * `$gt` may also be `$gte`. `$lt` may also be `$lte`. * * @param options - * @returns Returns a Promise that either resolves with the encrypted value or rejects with an error. */ async encryptExpression(expression, options) { return await this._encrypt(expression, true, options); } /** * Explicitly decrypt a provided encrypted value * * @param value - An encrypted value * @returns a Promise that either resolves with the decrypted value, or rejects with an error * * @example * ```ts * // Decrypting value with async/await API * async function decryptMyValue(value) { * return clientEncryption.decrypt(value); * } * ``` */ async decrypt(value) { const valueBuffer = (0, bson_1.serialize)({ v: value }); const context = this._mongoCrypt.makeExplicitDecryptionContext(valueBuffer); const stateMachine = new state_machine_1.StateMachine({ proxyOptions: this._proxyOptions, tlsOptions: this._tlsOptions, socketOptions: autoSelectSocketOptions(this._client.s.options) }); const timeoutContext = this._timeoutMS != null ? timeout_1.TimeoutContext.create((0, utils_1.resolveTimeoutOptions)(this._client, { timeoutMS: this._timeoutMS })) : void 0; const { v } = (0, bson_1.deserialize)(await stateMachine.execute(this, context, { timeoutContext })); return v; } /** * @internal * Ask the user for KMS credentials. * * This returns anything that looks like the kmsProviders original input * option. It can be empty, and any provider specified here will override * the original ones. */ async askForKMSCredentials() { return await (0, index_1.refreshKMSCredentials)(this._kmsProviders, this._credentialProviders); } static get libmongocryptVersion() { return _ClientEncryption.getMongoCrypt().libmongocryptVersion; } /** * @internal * A helper that perform explicit encryption of values and expressions. * Explicitly encrypt a provided value. Note that either `options.keyId` or `options.keyAltName` must * be specified. Specifying both `options.keyId` and `options.keyAltName` is considered an error. * * @param value - The value that you wish to encrypt. Must be of a type that can be serialized into BSON * @param expressionMode - a boolean that indicates whether or not to encrypt the value as an expression * @param options - options to pass to encrypt * @returns the raw result of the call to stateMachine.execute(). When expressionMode is set to true, the return * value will be a bson document. When false, the value will be a BSON Binary. * */ async _encrypt(value, expressionMode, options) { const { algorithm, keyId, keyAltName, contentionFactor, queryType, rangeOptions } = options; const contextOptions = { expressionMode, algorithm }; if (keyId) { contextOptions.keyId = keyId.buffer; } if (keyAltName) { if (keyId) { throw new errors_1.MongoCryptInvalidArgumentError(`"options" cannot contain both "keyId" and "keyAltName"`); } if (typeof keyAltName !== "string") { throw new errors_1.MongoCryptInvalidArgumentError(`"options.keyAltName" must be of type string, but was of type ${typeof keyAltName}`); } contextOptions.keyAltName = (0, bson_1.serialize)({ keyAltName }); } if (typeof contentionFactor === "number" || typeof contentionFactor === "bigint") { contextOptions.contentionFactor = contentionFactor; } if (typeof queryType === "string") { contextOptions.queryType = queryType; } if (typeof rangeOptions === "object") { contextOptions.rangeOptions = (0, bson_1.serialize)(rangeOptions); } const valueBuffer = (0, bson_1.serialize)({ v: value }); const stateMachine = new state_machine_1.StateMachine({ proxyOptions: this._proxyOptions, tlsOptions: this._tlsOptions, socketOptions: autoSelectSocketOptions(this._client.s.options) }); const context = this._mongoCrypt.makeExplicitEncryptionContext(valueBuffer, contextOptions); const timeoutContext = this._timeoutMS != null ? timeout_1.TimeoutContext.create((0, utils_1.resolveTimeoutOptions)(this._client, { timeoutMS: this._timeoutMS })) : void 0; const { v } = (0, bson_1.deserialize)(await stateMachine.execute(this, context, { timeoutContext })); return v; } }; exports2.ClientEncryption = ClientEncryption; function autoSelectSocketOptions(baseOptions) { const options = { autoSelectFamily: true }; if ("autoSelectFamily" in baseOptions) { options.autoSelectFamily = baseOptions.autoSelectFamily; } if ("autoSelectFamilyAttemptTimeout" in baseOptions) { options.autoSelectFamilyAttemptTimeout = baseOptions.autoSelectFamilyAttemptTimeout; } return options; } } }); // netlify/functions/node_modules/mongodb/lib/client-side-encryption/mongocryptd_manager.js var require_mongocryptd_manager = __commonJS({ "netlify/functions/node_modules/mongodb/lib/client-side-encryption/mongocryptd_manager.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.MongocryptdManager = void 0; var error_1 = require_error(); var MongocryptdManager = class _MongocryptdManager { constructor(extraOptions = {}) { this.spawnPath = ""; this.spawnArgs = []; this.uri = typeof extraOptions.mongocryptdURI === "string" && extraOptions.mongocryptdURI.length > 0 ? extraOptions.mongocryptdURI : _MongocryptdManager.DEFAULT_MONGOCRYPTD_URI; this.bypassSpawn = !!extraOptions.mongocryptdBypassSpawn; if (Object.hasOwn(extraOptions, "mongocryptdSpawnPath") && extraOptions.mongocryptdSpawnPath) { this.spawnPath = extraOptions.mongocryptdSpawnPath; } if (Object.hasOwn(extraOptions, "mongocryptdSpawnArgs") && Array.isArray(extraOptions.mongocryptdSpawnArgs)) { this.spawnArgs = this.spawnArgs.concat(extraOptions.mongocryptdSpawnArgs); } if (this.spawnArgs.filter((arg) => typeof arg === "string").every((arg) => arg.indexOf("--idleShutdownTimeoutSecs") < 0)) { this.spawnArgs.push("--idleShutdownTimeoutSecs", "60"); } } /** * Will check to see if a mongocryptd is up. If it is not up, it will attempt * to spawn a mongocryptd in a detached process, and then wait for it to be up. */ async spawn() { const cmdName = this.spawnPath || "mongocryptd"; const { spawn } = require("child_process"); this._child = spawn(cmdName, this.spawnArgs, { stdio: "ignore", detached: true }); this._child.on("error", () => { }); this._child.unref(); } /** * @returns the result of `fn` or rejects with an error. */ async withRespawn(fn) { try { const result2 = await fn(); return result2; } catch (err) { const shouldSpawn = err instanceof error_1.MongoNetworkTimeoutError && !this.bypassSpawn; if (!shouldSpawn) { throw err; } } await this.spawn(); const result = await fn(); return result; } }; exports2.MongocryptdManager = MongocryptdManager; MongocryptdManager.DEFAULT_MONGOCRYPTD_URI = "mongodb://localhost:27020"; } }); // netlify/functions/node_modules/mongodb/lib/client-side-encryption/auto_encrypter.js var require_auto_encrypter = __commonJS({ "netlify/functions/node_modules/mongodb/lib/client-side-encryption/auto_encrypter.js"(exports2) { "use strict"; var _a; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.AutoEncrypter = exports2.AutoEncryptionLoggerLevel = void 0; var net = require("net"); var bson_1 = require_bson2(); var constants_1 = require_constants(); var deps_1 = require_deps(); var error_1 = require_error(); var mongo_client_1 = require_mongo_client(); var utils_1 = require_utils(); var client_encryption_1 = require_client_encryption(); var cryptoCallbacks = require_crypto_callbacks(); var errors_1 = require_errors(); var mongocryptd_manager_1 = require_mongocryptd_manager(); var providers_1 = require_providers2(); var state_machine_1 = require_state_machine(); exports2.AutoEncryptionLoggerLevel = Object.freeze({ FatalError: 0, Error: 1, Warning: 2, Info: 3, Trace: 4 }); var AutoEncrypter = class _AutoEncrypter { /** @internal */ static getMongoCrypt() { const encryption = (0, deps_1.getMongoDBClientEncryption)(); if ("kModuleError" in encryption) { throw encryption.kModuleError; } return encryption.MongoCrypt; } /** * Create an AutoEncrypter * * **Note**: Do not instantiate this class directly. Rather, supply the relevant options to a MongoClient * * **Note**: Supplying `options.schemaMap` provides more security than relying on JSON Schemas obtained from the server. * It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending unencrypted data that should be encrypted. * Schemas supplied in the schemaMap only apply to configuring automatic encryption for Client-Side Field Level Encryption. * Other validation rules in the JSON schema will not be enforced by the driver and will result in an error. * * @example Create an AutoEncrypter that makes use of mongocryptd * ```ts * // Enabling autoEncryption via a MongoClient using mongocryptd * const { MongoClient } = require('mongodb'); * const client = new MongoClient(URL, { * autoEncryption: { * kmsProviders: { * aws: { * accessKeyId: AWS_ACCESS_KEY, * secretAccessKey: AWS_SECRET_KEY * } * } * } * }); * ``` * * await client.connect(); * // From here on, the client will be encrypting / decrypting automatically * @example Create an AutoEncrypter that makes use of libmongocrypt's CSFLE shared library * ```ts * // Enabling autoEncryption via a MongoClient using CSFLE shared library * const { MongoClient } = require('mongodb'); * const client = new MongoClient(URL, { * autoEncryption: { * kmsProviders: { * aws: {} * }, * extraOptions: { * cryptSharedLibPath: '/path/to/local/crypt/shared/lib', * cryptSharedLibRequired: true * } * } * }); * ``` * * await client.connect(); * // From here on, the client will be encrypting / decrypting automatically */ constructor(client, options) { this[_a] = false; this._client = client; this._bypassEncryption = options.bypassAutoEncryption === true; this._keyVaultNamespace = options.keyVaultNamespace || "admin.datakeys"; this._keyVaultClient = options.keyVaultClient || client; this._metaDataClient = options.metadataClient || client; this._proxyOptions = options.proxyOptions || {}; this._tlsOptions = options.tlsOptions || {}; this._kmsProviders = options.kmsProviders || {}; this._credentialProviders = options.credentialProviders; if (options.credentialProviders?.aws && !(0, providers_1.isEmptyCredentials)("aws", this._kmsProviders)) { throw new errors_1.MongoCryptInvalidArgumentError("Can only provide a custom AWS credential provider when the state machine is configured for automatic AWS credential fetching"); } const mongoCryptOptions = { enableMultipleCollinfo: true, cryptoCallbacks }; if (options.schemaMap) { mongoCryptOptions.schemaMap = Buffer.isBuffer(options.schemaMap) ? options.schemaMap : (0, bson_1.serialize)(options.schemaMap); } if (options.encryptedFieldsMap) { mongoCryptOptions.encryptedFieldsMap = Buffer.isBuffer(options.encryptedFieldsMap) ? options.encryptedFieldsMap : (0, bson_1.serialize)(options.encryptedFieldsMap); } mongoCryptOptions.kmsProviders = !Buffer.isBuffer(this._kmsProviders) ? (0, bson_1.serialize)(this._kmsProviders) : this._kmsProviders; if (options.options?.logger) { mongoCryptOptions.logger = options.options.logger; } if (options.extraOptions && options.extraOptions.cryptSharedLibPath) { mongoCryptOptions.cryptSharedLibPath = options.extraOptions.cryptSharedLibPath; } if (options.bypassQueryAnalysis) { mongoCryptOptions.bypassQueryAnalysis = options.bypassQueryAnalysis; } if (options.keyExpirationMS != null) { mongoCryptOptions.keyExpirationMS = options.keyExpirationMS; } this._bypassMongocryptdAndCryptShared = this._bypassEncryption || !!options.bypassQueryAnalysis; if (options.extraOptions && options.extraOptions.cryptSharedLibSearchPaths) { mongoCryptOptions.cryptSharedLibSearchPaths = options.extraOptions.cryptSharedLibSearchPaths; } else if (!this._bypassMongocryptdAndCryptShared) { mongoCryptOptions.cryptSharedLibSearchPaths = ["$SYSTEM"]; } const MongoCrypt = _AutoEncrypter.getMongoCrypt(); this._mongocrypt = new MongoCrypt(mongoCryptOptions); this._contextCounter = 0; if (options.extraOptions && options.extraOptions.cryptSharedLibRequired && !this.cryptSharedLibVersionInfo) { throw new errors_1.MongoCryptInvalidArgumentError("`cryptSharedLibRequired` set but no crypt_shared library loaded"); } if (!this._bypassMongocryptdAndCryptShared && !this.cryptSharedLibVersionInfo) { this._mongocryptdManager = new mongocryptd_manager_1.MongocryptdManager(options.extraOptions); const clientOptions = { serverSelectionTimeoutMS: 1e4 }; if ((options.extraOptions == null || typeof options.extraOptions.mongocryptdURI !== "string") && !net.getDefaultAutoSelectFamily) { clientOptions.family = 4; } if (net.getDefaultAutoSelectFamily) { Object.assign(clientOptions, (0, client_encryption_1.autoSelectSocketOptions)(this._client.s?.options ?? {})); } this._mongocryptdClient = new mongo_client_1.MongoClient(this._mongocryptdManager.uri, clientOptions); } } /** * Initializes the auto encrypter by spawning a mongocryptd and connecting to it. * * This function is a no-op when bypassSpawn is set or the crypt shared library is used. */ async init() { if (this._bypassMongocryptdAndCryptShared || this.cryptSharedLibVersionInfo) { return; } if (!this._mongocryptdManager) { throw new error_1.MongoRuntimeError("Reached impossible state: mongocryptdManager is undefined when neither bypassSpawn nor the shared lib are specified."); } if (!this._mongocryptdClient) { throw new error_1.MongoRuntimeError("Reached impossible state: mongocryptdClient is undefined when neither bypassSpawn nor the shared lib are specified."); } if (!this._mongocryptdManager.bypassSpawn) { await this._mongocryptdManager.spawn(); } try { const client = await this._mongocryptdClient.connect(); return client; } catch (error) { throw new error_1.MongoRuntimeError("Unable to connect to `mongocryptd`, please make sure it is running or in your PATH for auto-spawn", { cause: error }); } } /** * Cleans up the `_mongocryptdClient`, if present. */ async close() { await this._mongocryptdClient?.close(); } /** * Encrypt a command for a given namespace. */ async encrypt(ns, cmd, options = {}) { options.signal?.throwIfAborted(); if (this._bypassEncryption) { return cmd; } const commandBuffer = Buffer.isBuffer(cmd) ? cmd : (0, bson_1.serialize)(cmd, options); const context = this._mongocrypt.makeEncryptionContext(utils_1.MongoDBCollectionNamespace.fromString(ns).db, commandBuffer); context.id = this._contextCounter++; context.ns = ns; context.document = cmd; const stateMachine = new state_machine_1.StateMachine({ promoteValues: false, promoteLongs: false, proxyOptions: this._proxyOptions, tlsOptions: this._tlsOptions, socketOptions: (0, client_encryption_1.autoSelectSocketOptions)(this._client.s.options) }); return (0, bson_1.deserialize)(await stateMachine.execute(this, context, options), { promoteValues: false, promoteLongs: false }); } /** * Decrypt a command response */ async decrypt(response, options = {}) { options.signal?.throwIfAborted(); const context = this._mongocrypt.makeDecryptionContext(response); context.id = this._contextCounter++; const stateMachine = new state_machine_1.StateMachine({ ...options, proxyOptions: this._proxyOptions, tlsOptions: this._tlsOptions, socketOptions: (0, client_encryption_1.autoSelectSocketOptions)(this._client.s.options) }); return await stateMachine.execute(this, context, options); } /** * Ask the user for KMS credentials. * * This returns anything that looks like the kmsProviders original input * option. It can be empty, and any provider specified here will override * the original ones. */ async askForKMSCredentials() { return await (0, providers_1.refreshKMSCredentials)(this._kmsProviders, this._credentialProviders); } /** * Return the current libmongocrypt's CSFLE shared library version * as `{ version: bigint, versionStr: string }`, or `null` if no CSFLE * shared library was loaded. */ get cryptSharedLibVersionInfo() { return this._mongocrypt.cryptSharedLibVersionInfo; } static get libmongocryptVersion() { return _AutoEncrypter.getMongoCrypt().libmongocryptVersion; } }; exports2.AutoEncrypter = AutoEncrypter; _a = constants_1.kDecorateResult; } }); // netlify/functions/node_modules/mongodb/lib/encrypter.js var require_encrypter = __commonJS({ "netlify/functions/node_modules/mongodb/lib/encrypter.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.Encrypter = void 0; var auto_encrypter_1 = require_auto_encrypter(); var constants_1 = require_constants(); var deps_1 = require_deps(); var error_1 = require_error(); var mongo_client_1 = require_mongo_client(); var Encrypter = class { constructor(client, uri, options) { if (typeof options.autoEncryption !== "object") { throw new error_1.MongoInvalidArgumentError('Option "autoEncryption" must be specified'); } this.internalClient = null; this.bypassAutoEncryption = !!options.autoEncryption.bypassAutoEncryption; this.needsConnecting = false; if (options.maxPoolSize === 0 && options.autoEncryption.keyVaultClient == null) { options.autoEncryption.keyVaultClient = client; } else if (options.autoEncryption.keyVaultClient == null) { options.autoEncryption.keyVaultClient = this.getInternalClient(client, uri, options); } if (this.bypassAutoEncryption) { options.autoEncryption.metadataClient = void 0; } else if (options.maxPoolSize === 0) { options.autoEncryption.metadataClient = client; } else { options.autoEncryption.metadataClient = this.getInternalClient(client, uri, options); } if (options.proxyHost) { options.autoEncryption.proxyOptions = { proxyHost: options.proxyHost, proxyPort: options.proxyPort, proxyUsername: options.proxyUsername, proxyPassword: options.proxyPassword }; } this.autoEncrypter = new auto_encrypter_1.AutoEncrypter(client, options.autoEncryption); } getInternalClient(client, uri, options) { let internalClient = this.internalClient; if (internalClient == null) { const clonedOptions = {}; for (const key of [ ...Object.getOwnPropertyNames(options), ...Object.getOwnPropertySymbols(options) ]) { if (["autoEncryption", "minPoolSize", "servers", "caseTranslate", "dbName"].includes(key)) continue; Reflect.set(clonedOptions, key, Reflect.get(options, key)); } clonedOptions.minPoolSize = 0; internalClient = new mongo_client_1.MongoClient(uri, clonedOptions); this.internalClient = internalClient; for (const eventName of constants_1.MONGO_CLIENT_EVENTS) { for (const listener of client.listeners(eventName)) { internalClient.on(eventName, listener); } } client.on("newListener", (eventName, listener) => { internalClient?.on(eventName, listener); }); this.needsConnecting = true; } return internalClient; } async connectInternalClient() { const internalClient = this.internalClient; if (this.needsConnecting && internalClient != null) { this.needsConnecting = false; await internalClient.connect(); } } async close(client) { let error; try { await this.autoEncrypter.close(); } catch (autoEncrypterError) { error = autoEncrypterError; } const internalClient = this.internalClient; if (internalClient != null && client !== internalClient) { return await internalClient.close(); } if (error != null) { throw error; } } static checkForMongoCrypt() { const mongodbClientEncryption = (0, deps_1.getMongoDBClientEncryption)(); if ("kModuleError" in mongodbClientEncryption) { throw new error_1.MongoMissingDependencyError("Auto-encryption requested, but the module is not installed. Please add `mongodb-client-encryption` as a dependency of your project", { cause: mongodbClientEncryption["kModuleError"], dependencyName: "mongodb-client-encryption" }); } } }; exports2.Encrypter = Encrypter; } }); // netlify/functions/node_modules/mongodb/lib/cmap/metrics.js var require_metrics = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/metrics.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ConnectionPoolMetrics = void 0; var ConnectionPoolMetrics = class _ConnectionPoolMetrics { constructor() { this.txnConnections = 0; this.cursorConnections = 0; this.otherConnections = 0; } /** * Mark a connection as pinned for a specific operation. */ markPinned(pinType) { if (pinType === _ConnectionPoolMetrics.TXN) { this.txnConnections += 1; } else if (pinType === _ConnectionPoolMetrics.CURSOR) { this.cursorConnections += 1; } else { this.otherConnections += 1; } } /** * Unmark a connection as pinned for an operation. */ markUnpinned(pinType) { if (pinType === _ConnectionPoolMetrics.TXN) { this.txnConnections -= 1; } else if (pinType === _ConnectionPoolMetrics.CURSOR) { this.cursorConnections -= 1; } else { this.otherConnections -= 1; } } /** * Return information about the cmap metrics as a string. */ info(maxPoolSize) { return `Timed out while checking out a connection from connection pool: maxPoolSize: ${maxPoolSize}, connections in use by cursors: ${this.cursorConnections}, connections in use by transactions: ${this.txnConnections}, connections in use by other operations: ${this.otherConnections}`; } /** * Reset the metrics to the initial values. */ reset() { this.txnConnections = 0; this.cursorConnections = 0; this.otherConnections = 0; } }; exports2.ConnectionPoolMetrics = ConnectionPoolMetrics; ConnectionPoolMetrics.TXN = "txn"; ConnectionPoolMetrics.CURSOR = "cursor"; ConnectionPoolMetrics.OTHER = "other"; } }); // netlify/functions/node_modules/mongodb/lib/sdam/server_description.js var require_server_description = __commonJS({ "netlify/functions/node_modules/mongodb/lib/sdam/server_description.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ServerDescription = void 0; exports2.parseServerType = parseServerType; exports2.compareTopologyVersion = compareTopologyVersion; var bson_1 = require_bson2(); var error_1 = require_error(); var utils_1 = require_utils(); var common_1 = require_common(); var WRITABLE_SERVER_TYPES = /* @__PURE__ */ new Set([ common_1.ServerType.RSPrimary, common_1.ServerType.Standalone, common_1.ServerType.Mongos, common_1.ServerType.LoadBalancer ]); var DATA_BEARING_SERVER_TYPES = /* @__PURE__ */ new Set([ common_1.ServerType.RSPrimary, common_1.ServerType.RSSecondary, common_1.ServerType.Mongos, common_1.ServerType.Standalone, common_1.ServerType.LoadBalancer ]); var ServerDescription = class { /** * Create a ServerDescription * @internal * * @param address - The address of the server * @param hello - An optional hello response for this server */ constructor(address, hello, options = {}) { if (address == null || address === "") { throw new error_1.MongoRuntimeError("ServerDescription must be provided with a non-empty address"); } this.address = typeof address === "string" ? utils_1.HostAddress.fromString(address).toString() : address.toString(); this.type = parseServerType(hello, options); this.hosts = hello?.hosts?.map((host) => host.toLowerCase()) ?? []; this.passives = hello?.passives?.map((host) => host.toLowerCase()) ?? []; this.arbiters = hello?.arbiters?.map((host) => host.toLowerCase()) ?? []; this.tags = hello?.tags ?? {}; this.minWireVersion = hello?.minWireVersion ?? 0; this.maxWireVersion = hello?.maxWireVersion ?? 0; this.roundTripTime = options?.roundTripTime ?? -1; this.minRoundTripTime = options?.minRoundTripTime ?? 0; this.lastUpdateTime = (0, utils_1.now)(); this.lastWriteDate = hello?.lastWrite?.lastWriteDate ?? 0; this.error = options.error ?? null; this.error?.stack; this.topologyVersion = this.error?.topologyVersion ?? hello?.topologyVersion ?? null; this.setName = hello?.setName ?? null; this.setVersion = hello?.setVersion ?? null; this.electionId = hello?.electionId ?? null; this.logicalSessionTimeoutMinutes = hello?.logicalSessionTimeoutMinutes ?? null; this.maxMessageSizeBytes = hello?.maxMessageSizeBytes ?? null; this.maxWriteBatchSize = hello?.maxWriteBatchSize ?? null; this.maxBsonObjectSize = hello?.maxBsonObjectSize ?? null; this.primary = hello?.primary ?? null; this.me = hello?.me?.toLowerCase() ?? null; this.$clusterTime = hello?.$clusterTime ?? null; this.iscryptd = Boolean(hello?.iscryptd); } get hostAddress() { return utils_1.HostAddress.fromString(this.address); } get allHosts() { return this.hosts.concat(this.arbiters).concat(this.passives); } /** Is this server available for reads*/ get isReadable() { return this.type === common_1.ServerType.RSSecondary || this.isWritable; } /** Is this server data bearing */ get isDataBearing() { return DATA_BEARING_SERVER_TYPES.has(this.type); } /** Is this server available for writes */ get isWritable() { return WRITABLE_SERVER_TYPES.has(this.type); } get host() { const chopLength = `:${this.port}`.length; return this.address.slice(0, -chopLength); } get port() { const port = this.address.split(":").pop(); return port ? Number.parseInt(port, 10) : 27017; } /** * Determines if another `ServerDescription` is equal to this one per the rules defined in the SDAM specification. * @see https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.md */ equals(other) { const topologyVersionsEqual = this.topologyVersion === other?.topologyVersion || compareTopologyVersion(this.topologyVersion, other?.topologyVersion) === 0; const electionIdsEqual = this.electionId != null && other?.electionId != null ? (0, utils_1.compareObjectId)(this.electionId, other.electionId) === 0 : this.electionId === other?.electionId; return other != null && other.iscryptd === this.iscryptd && (0, utils_1.errorStrictEqual)(this.error, other.error) && this.type === other.type && this.minWireVersion === other.minWireVersion && (0, utils_1.arrayStrictEqual)(this.hosts, other.hosts) && tagsStrictEqual(this.tags, other.tags) && this.setName === other.setName && this.setVersion === other.setVersion && electionIdsEqual && this.primary === other.primary && this.logicalSessionTimeoutMinutes === other.logicalSessionTimeoutMinutes && topologyVersionsEqual; } }; exports2.ServerDescription = ServerDescription; function parseServerType(hello, options) { if (options?.loadBalanced) { return common_1.ServerType.LoadBalancer; } if (!hello || !hello.ok) { return common_1.ServerType.Unknown; } if (hello.isreplicaset) { return common_1.ServerType.RSGhost; } if (hello.msg && hello.msg === "isdbgrid") { return common_1.ServerType.Mongos; } if (hello.setName) { if (hello.hidden) { return common_1.ServerType.RSOther; } else if (hello.isWritablePrimary) { return common_1.ServerType.RSPrimary; } else if (hello.secondary) { return common_1.ServerType.RSSecondary; } else if (hello.arbiterOnly) { return common_1.ServerType.RSArbiter; } else { return common_1.ServerType.RSOther; } } return common_1.ServerType.Standalone; } function tagsStrictEqual(tags, tags2) { const tagsKeys = Object.keys(tags); const tags2Keys = Object.keys(tags2); return tagsKeys.length === tags2Keys.length && tagsKeys.every((key) => tags2[key] === tags[key]); } function compareTopologyVersion(currentTv, newTv) { if (currentTv == null || newTv == null) { return -1; } if (!currentTv.processId.equals(newTv.processId)) { return -1; } const currentCounter = typeof currentTv.counter === "bigint" ? bson_1.Long.fromBigInt(currentTv.counter) : bson_1.Long.isLong(currentTv.counter) ? currentTv.counter : bson_1.Long.fromNumber(currentTv.counter); const newCounter = typeof newTv.counter === "bigint" ? bson_1.Long.fromBigInt(newTv.counter) : bson_1.Long.isLong(newTv.counter) ? newTv.counter : bson_1.Long.fromNumber(newTv.counter); return currentCounter.compare(newCounter); } } }); // netlify/functions/node_modules/mongodb/lib/sdam/topology_description.js var require_topology_description = __commonJS({ "netlify/functions/node_modules/mongodb/lib/sdam/topology_description.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.TopologyDescription = void 0; var bson_1 = require_bson2(); var WIRE_CONSTANTS = require_constants2(); var error_1 = require_error(); var utils_1 = require_utils(); var common_1 = require_common(); var server_description_1 = require_server_description(); var MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION; var MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION; var MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION; var MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION; var MONGOS_OR_UNKNOWN = /* @__PURE__ */ new Set([common_1.ServerType.Mongos, common_1.ServerType.Unknown]); var MONGOS_OR_STANDALONE = /* @__PURE__ */ new Set([common_1.ServerType.Mongos, common_1.ServerType.Standalone]); var NON_PRIMARY_RS_MEMBERS = /* @__PURE__ */ new Set([ common_1.ServerType.RSSecondary, common_1.ServerType.RSArbiter, common_1.ServerType.RSOther ]); var TopologyDescription = class _TopologyDescription { /** * Create a TopologyDescription */ constructor(topologyType, serverDescriptions = null, setName = null, maxSetVersion = null, maxElectionId = null, commonWireVersion = null, options = null) { options = options ?? {}; this.type = topologyType ?? common_1.TopologyType.Unknown; this.servers = serverDescriptions ?? /* @__PURE__ */ new Map(); this.stale = false; this.compatible = true; this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 0; this.localThresholdMS = options.localThresholdMS ?? 15; this.setName = setName ?? null; this.maxElectionId = maxElectionId ?? null; this.maxSetVersion = maxSetVersion ?? null; this.commonWireVersion = commonWireVersion ?? 0; for (const serverDescription of this.servers.values()) { if (serverDescription.type === common_1.ServerType.Unknown || serverDescription.type === common_1.ServerType.LoadBalancer) { continue; } if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) { this.compatible = false; this.compatibilityError = `Server at ${serverDescription.address} requires wire version ${serverDescription.minWireVersion}, but this version of the driver only supports up to ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; } if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) { this.compatible = false; this.compatibilityError = `Server at ${serverDescription.address} reports wire version ${serverDescription.maxWireVersion}, but this version of the driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION}).`; break; } } this.logicalSessionTimeoutMinutes = null; for (const [, server] of this.servers) { if (server.isReadable) { if (server.logicalSessionTimeoutMinutes == null) { this.logicalSessionTimeoutMinutes = null; break; } if (this.logicalSessionTimeoutMinutes == null) { this.logicalSessionTimeoutMinutes = server.logicalSessionTimeoutMinutes; continue; } this.logicalSessionTimeoutMinutes = Math.min(this.logicalSessionTimeoutMinutes, server.logicalSessionTimeoutMinutes); } } } /** * Returns a new TopologyDescription based on the SrvPollingEvent * @internal */ updateFromSrvPollingEvent(ev, srvMaxHosts = 0) { const incomingHostnames = ev.hostnames(); const currentHostnames = new Set(this.servers.keys()); const hostnamesToAdd = new Set(incomingHostnames); const hostnamesToRemove = /* @__PURE__ */ new Set(); for (const hostname of currentHostnames) { hostnamesToAdd.delete(hostname); if (!incomingHostnames.has(hostname)) { hostnamesToRemove.add(hostname); } } if (hostnamesToAdd.size === 0 && hostnamesToRemove.size === 0) { return this; } const serverDescriptions = new Map(this.servers); for (const removedHost of hostnamesToRemove) { serverDescriptions.delete(removedHost); } if (hostnamesToAdd.size > 0) { if (srvMaxHosts === 0) { for (const hostToAdd of hostnamesToAdd) { serverDescriptions.set(hostToAdd, new server_description_1.ServerDescription(hostToAdd)); } } else if (serverDescriptions.size < srvMaxHosts) { const selectedHosts = (0, utils_1.shuffle)(hostnamesToAdd, srvMaxHosts - serverDescriptions.size); for (const selectedHostToAdd of selectedHosts) { serverDescriptions.set(selectedHostToAdd, new server_description_1.ServerDescription(selectedHostToAdd)); } } } return new _TopologyDescription(this.type, serverDescriptions, this.setName, this.maxSetVersion, this.maxElectionId, this.commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS }); } /** * Returns a copy of this description updated with a given ServerDescription * @internal */ update(serverDescription) { const address = serverDescription.address; let { type: topologyType, setName, maxSetVersion, maxElectionId, commonWireVersion } = this; const serverType = serverDescription.type; const serverDescriptions = new Map(this.servers); if (serverDescription.maxWireVersion !== 0) { if (commonWireVersion == null) { commonWireVersion = serverDescription.maxWireVersion; } else { commonWireVersion = Math.min(commonWireVersion, serverDescription.maxWireVersion); } } if (typeof serverDescription.setName === "string" && typeof setName === "string" && serverDescription.setName !== setName) { if (topologyType === common_1.TopologyType.Single) { serverDescription = new server_description_1.ServerDescription(address); } else { serverDescriptions.delete(address); } } serverDescriptions.set(address, serverDescription); if (topologyType === common_1.TopologyType.Single) { return new _TopologyDescription(common_1.TopologyType.Single, serverDescriptions, setName, maxSetVersion, maxElectionId, commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS }); } if (topologyType === common_1.TopologyType.Unknown) { if (serverType === common_1.ServerType.Standalone && this.servers.size !== 1) { serverDescriptions.delete(address); } else { topologyType = topologyTypeForServerType(serverType); } } if (topologyType === common_1.TopologyType.Sharded) { if (!MONGOS_OR_UNKNOWN.has(serverType)) { serverDescriptions.delete(address); } } if (topologyType === common_1.TopologyType.ReplicaSetNoPrimary) { if (MONGOS_OR_STANDALONE.has(serverType)) { serverDescriptions.delete(address); } if (serverType === common_1.ServerType.RSPrimary) { const result = updateRsFromPrimary(serverDescriptions, serverDescription, setName, maxSetVersion, maxElectionId); topologyType = result[0]; setName = result[1]; maxSetVersion = result[2]; maxElectionId = result[3]; } else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) { const result = updateRsNoPrimaryFromMember(serverDescriptions, serverDescription, setName); topologyType = result[0]; setName = result[1]; } } if (topologyType === common_1.TopologyType.ReplicaSetWithPrimary) { if (MONGOS_OR_STANDALONE.has(serverType)) { serverDescriptions.delete(address); topologyType = checkHasPrimary(serverDescriptions); } else if (serverType === common_1.ServerType.RSPrimary) { const result = updateRsFromPrimary(serverDescriptions, serverDescription, setName, maxSetVersion, maxElectionId); topologyType = result[0]; setName = result[1]; maxSetVersion = result[2]; maxElectionId = result[3]; } else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) { topologyType = updateRsWithPrimaryFromMember(serverDescriptions, serverDescription, setName); } else { topologyType = checkHasPrimary(serverDescriptions); } } return new _TopologyDescription(topologyType, serverDescriptions, setName, maxSetVersion, maxElectionId, commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS }); } get error() { const descriptionsWithError = Array.from(this.servers.values()).filter((sd) => sd.error); if (descriptionsWithError.length > 0) { return descriptionsWithError[0].error; } return null; } /** * Determines if the topology description has any known servers */ get hasKnownServers() { return Array.from(this.servers.values()).some((sd) => sd.type !== common_1.ServerType.Unknown); } /** * Determines if this topology description has a data-bearing server available. */ get hasDataBearingServers() { return Array.from(this.servers.values()).some((sd) => sd.isDataBearing); } /** * Determines if the topology has a definition for the provided address * @internal */ hasServer(address) { return this.servers.has(address); } /** * Returns a JSON-serializable representation of the TopologyDescription. This is primarily * intended for use with JSON.stringify(). * * This method will not throw. */ toJSON() { return bson_1.EJSON.serialize(this); } }; exports2.TopologyDescription = TopologyDescription; function topologyTypeForServerType(serverType) { switch (serverType) { case common_1.ServerType.Standalone: return common_1.TopologyType.Single; case common_1.ServerType.Mongos: return common_1.TopologyType.Sharded; case common_1.ServerType.RSPrimary: return common_1.TopologyType.ReplicaSetWithPrimary; case common_1.ServerType.RSOther: case common_1.ServerType.RSSecondary: return common_1.TopologyType.ReplicaSetNoPrimary; default: return common_1.TopologyType.Unknown; } } function updateRsFromPrimary(serverDescriptions, serverDescription, setName = null, maxSetVersion = null, maxElectionId = null) { const setVersionElectionIdMismatch = (serverDescription2, maxSetVersion2, maxElectionId2) => { return `primary marked stale due to electionId/setVersion mismatch: server setVersion: ${serverDescription2.setVersion}, server electionId: ${serverDescription2.electionId}, topology setVersion: ${maxSetVersion2}, topology electionId: ${maxElectionId2}`; }; setName = setName || serverDescription.setName; if (setName !== serverDescription.setName) { serverDescriptions.delete(serverDescription.address); return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; } if (serverDescription.maxWireVersion >= 17) { const electionIdComparison = (0, utils_1.compareObjectId)(maxElectionId, serverDescription.electionId); const maxElectionIdIsEqual = electionIdComparison === 0; const maxElectionIdIsLess = electionIdComparison === -1; const maxSetVersionIsLessOrEqual = (maxSetVersion ?? -1) <= (serverDescription.setVersion ?? -1); if (maxElectionIdIsLess || maxElectionIdIsEqual && maxSetVersionIsLessOrEqual) { maxElectionId = serverDescription.electionId; maxSetVersion = serverDescription.setVersion; } else { serverDescriptions.set(serverDescription.address, new server_description_1.ServerDescription(serverDescription.address, void 0, { error: new error_1.MongoStalePrimaryError(setVersionElectionIdMismatch(serverDescription, maxSetVersion, maxElectionId)) })); return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; } } else { const electionId = serverDescription.electionId ? serverDescription.electionId : null; if (serverDescription.setVersion && electionId) { if (maxSetVersion && maxElectionId) { if (maxSetVersion > serverDescription.setVersion || (0, utils_1.compareObjectId)(maxElectionId, electionId) > 0) { serverDescriptions.set(serverDescription.address, new server_description_1.ServerDescription(serverDescription.address, void 0, { error: new error_1.MongoStalePrimaryError(setVersionElectionIdMismatch(serverDescription, maxSetVersion, maxElectionId)) })); return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; } } maxElectionId = serverDescription.electionId; } if (serverDescription.setVersion != null && (maxSetVersion == null || serverDescription.setVersion > maxSetVersion)) { maxSetVersion = serverDescription.setVersion; } } for (const [address, server] of serverDescriptions) { if (server.type === common_1.ServerType.RSPrimary && server.address !== serverDescription.address) { serverDescriptions.set(address, new server_description_1.ServerDescription(server.address, void 0, { error: new error_1.MongoStalePrimaryError("primary marked stale due to discovery of newer primary") })); break; } } serverDescription.allHosts.forEach((address) => { if (!serverDescriptions.has(address)) { serverDescriptions.set(address, new server_description_1.ServerDescription(address)); } }); const currentAddresses = Array.from(serverDescriptions.keys()); const responseAddresses = serverDescription.allHosts; currentAddresses.filter((addr) => responseAddresses.indexOf(addr) === -1).forEach((address) => { serverDescriptions.delete(address); }); return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; } function updateRsWithPrimaryFromMember(serverDescriptions, serverDescription, setName = null) { if (setName == null) { throw new error_1.MongoRuntimeError('Argument "setName" is required if connected to a replica set'); } if (setName !== serverDescription.setName || serverDescription.me && serverDescription.address !== serverDescription.me) { serverDescriptions.delete(serverDescription.address); } return checkHasPrimary(serverDescriptions); } function updateRsNoPrimaryFromMember(serverDescriptions, serverDescription, setName = null) { const topologyType = common_1.TopologyType.ReplicaSetNoPrimary; setName = setName ?? serverDescription.setName; if (setName !== serverDescription.setName) { serverDescriptions.delete(serverDescription.address); return [topologyType, setName]; } serverDescription.allHosts.forEach((address) => { if (!serverDescriptions.has(address)) { serverDescriptions.set(address, new server_description_1.ServerDescription(address)); } }); if (serverDescription.me && serverDescription.address !== serverDescription.me) { serverDescriptions.delete(serverDescription.address); } return [topologyType, setName]; } function checkHasPrimary(serverDescriptions) { for (const serverDescription of serverDescriptions.values()) { if (serverDescription.type === common_1.ServerType.RSPrimary) { return common_1.TopologyType.ReplicaSetWithPrimary; } } return common_1.TopologyType.ReplicaSetNoPrimary; } } }); // netlify/functions/node_modules/mongodb/lib/cmap/wire_protocol/shared.js var require_shared = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/wire_protocol/shared.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getReadPreference = getReadPreference; exports2.isSharded = isSharded; var error_1 = require_error(); var read_preference_1 = require_read_preference(); var common_1 = require_common(); var topology_description_1 = require_topology_description(); function getReadPreference(options) { let readPreference = options?.readPreference ?? read_preference_1.ReadPreference.primary; if (typeof readPreference === "string") { readPreference = read_preference_1.ReadPreference.fromString(readPreference); } if (!(readPreference instanceof read_preference_1.ReadPreference)) { throw new error_1.MongoInvalidArgumentError('Option "readPreference" must be a ReadPreference instance'); } return readPreference; } function isSharded(topologyOrServer) { if (topologyOrServer == null) { return false; } if (topologyOrServer.description && topologyOrServer.description.type === common_1.ServerType.Mongos) { return true; } if (topologyOrServer.description && topologyOrServer.description instanceof topology_description_1.TopologyDescription) { const servers = Array.from(topologyOrServer.description.servers.values()); return servers.some((server) => server.type === common_1.ServerType.Mongos); } return false; } } }); // netlify/functions/node_modules/mongodb/lib/transactions.js var require_transactions = __commonJS({ "netlify/functions/node_modules/mongodb/lib/transactions.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.Transaction = exports2.TxnState = void 0; exports2.isTransactionCommand = isTransactionCommand; var error_1 = require_error(); var read_concern_1 = require_read_concern(); var read_preference_1 = require_read_preference(); var write_concern_1 = require_write_concern(); exports2.TxnState = Object.freeze({ NO_TRANSACTION: "NO_TRANSACTION", STARTING_TRANSACTION: "STARTING_TRANSACTION", TRANSACTION_IN_PROGRESS: "TRANSACTION_IN_PROGRESS", TRANSACTION_COMMITTED: "TRANSACTION_COMMITTED", TRANSACTION_COMMITTED_EMPTY: "TRANSACTION_COMMITTED_EMPTY", TRANSACTION_ABORTED: "TRANSACTION_ABORTED" }); var stateMachine = { [exports2.TxnState.NO_TRANSACTION]: [exports2.TxnState.NO_TRANSACTION, exports2.TxnState.STARTING_TRANSACTION], [exports2.TxnState.STARTING_TRANSACTION]: [ exports2.TxnState.TRANSACTION_IN_PROGRESS, exports2.TxnState.TRANSACTION_COMMITTED, exports2.TxnState.TRANSACTION_COMMITTED_EMPTY, exports2.TxnState.TRANSACTION_ABORTED ], [exports2.TxnState.TRANSACTION_IN_PROGRESS]: [ exports2.TxnState.TRANSACTION_IN_PROGRESS, exports2.TxnState.TRANSACTION_COMMITTED, exports2.TxnState.TRANSACTION_ABORTED ], [exports2.TxnState.TRANSACTION_COMMITTED]: [ exports2.TxnState.TRANSACTION_COMMITTED, exports2.TxnState.TRANSACTION_COMMITTED_EMPTY, exports2.TxnState.STARTING_TRANSACTION, exports2.TxnState.NO_TRANSACTION ], [exports2.TxnState.TRANSACTION_ABORTED]: [exports2.TxnState.STARTING_TRANSACTION, exports2.TxnState.NO_TRANSACTION], [exports2.TxnState.TRANSACTION_COMMITTED_EMPTY]: [ exports2.TxnState.TRANSACTION_COMMITTED_EMPTY, exports2.TxnState.NO_TRANSACTION ] }; var ACTIVE_STATES = /* @__PURE__ */ new Set([ exports2.TxnState.STARTING_TRANSACTION, exports2.TxnState.TRANSACTION_IN_PROGRESS ]); var COMMITTED_STATES = /* @__PURE__ */ new Set([ exports2.TxnState.TRANSACTION_COMMITTED, exports2.TxnState.TRANSACTION_COMMITTED_EMPTY, exports2.TxnState.TRANSACTION_ABORTED ]); var Transaction = class { /** Create a transaction @internal */ constructor(options) { options = options ?? {}; this.state = exports2.TxnState.NO_TRANSACTION; this.options = {}; const writeConcern = write_concern_1.WriteConcern.fromOptions(options); if (writeConcern) { if (writeConcern.w === 0) { throw new error_1.MongoTransactionError("Transactions do not support unacknowledged write concern"); } this.options.writeConcern = writeConcern; } if (options.readConcern) { this.options.readConcern = read_concern_1.ReadConcern.fromOptions(options); } if (options.readPreference) { this.options.readPreference = read_preference_1.ReadPreference.fromOptions(options); } if (options.maxCommitTimeMS) { this.options.maxTimeMS = options.maxCommitTimeMS; } this._pinnedServer = void 0; this._recoveryToken = void 0; } /** @internal */ get server() { return this._pinnedServer; } /** @deprecated - Will be made internal in a future major release. */ get recoveryToken() { return this._recoveryToken; } /** @deprecated - Will be made internal in a future major release. */ get isPinned() { return !!this.server; } /** * @deprecated - Will be made internal in a future major release. * @returns Whether the transaction has started */ get isStarting() { return this.state === exports2.TxnState.STARTING_TRANSACTION; } /** * @deprecated - Will be made internal in a future major release. * @returns Whether this session is presently in a transaction */ get isActive() { return ACTIVE_STATES.has(this.state); } /** @deprecated - Will be made internal in a future major release. */ get isCommitted() { return COMMITTED_STATES.has(this.state); } /** * Transition the transaction in the state machine * @internal * @param nextState - The new state to transition to */ transition(nextState) { const nextStates = stateMachine[this.state]; if (nextStates && nextStates.includes(nextState)) { this.state = nextState; if (this.state === exports2.TxnState.NO_TRANSACTION || this.state === exports2.TxnState.STARTING_TRANSACTION || this.state === exports2.TxnState.TRANSACTION_ABORTED) { this.unpinServer(); } return; } throw new error_1.MongoRuntimeError(`Attempted illegal state transition from [${this.state}] to [${nextState}]`); } /** @internal */ pinServer(server) { if (this.isActive) { this._pinnedServer = server; } } /** @internal */ unpinServer() { this._pinnedServer = void 0; } }; exports2.Transaction = Transaction; function isTransactionCommand(command) { return !!(command.commitTransaction || command.abortTransaction); } } }); // netlify/functions/node_modules/mongodb/lib/sessions.js var require_sessions = __commonJS({ "netlify/functions/node_modules/mongodb/lib/sessions.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ServerSessionPool = exports2.ServerSession = exports2.ClientSession = void 0; exports2.maybeClearPinnedConnection = maybeClearPinnedConnection; exports2.applySession = applySession; exports2.updateSessionFromResponse = updateSessionFromResponse; var bson_1 = require_bson2(); var metrics_1 = require_metrics(); var shared_1 = require_shared(); var constants_1 = require_constants(); var error_1 = require_error(); var mongo_types_1 = require_mongo_types(); var execute_operation_1 = require_execute_operation(); var run_command_1 = require_run_command(); var read_concern_1 = require_read_concern(); var read_preference_1 = require_read_preference(); var resource_management_1 = require_resource_management(); var common_1 = require_common(); var timeout_1 = require_timeout(); var transactions_1 = require_transactions(); var utils_1 = require_utils(); var write_concern_1 = require_write_concern(); var minWireVersionForShardedTransactions = 8; var ClientSession = class _ClientSession extends mongo_types_1.TypedEventEmitter { /** * Create a client session. * @internal * @param client - The current client * @param sessionPool - The server session pool (Internal Class) * @param options - Optional settings * @param clientOptions - Optional settings provided when creating a MongoClient */ constructor(client, sessionPool, options, clientOptions) { super(); this.timeoutContext = null; this.on("error", utils_1.noop); if (client == null) { throw new error_1.MongoRuntimeError("ClientSession requires a MongoClient"); } if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) { throw new error_1.MongoRuntimeError("ClientSession requires a ServerSessionPool"); } options = options ?? {}; this.snapshotEnabled = options.snapshot === true; if (options.causalConsistency === true && this.snapshotEnabled) { throw new error_1.MongoInvalidArgumentError('Properties "causalConsistency" and "snapshot" are mutually exclusive'); } this.client = client; this.sessionPool = sessionPool; this.hasEnded = false; this.clientOptions = clientOptions; this.timeoutMS = options.defaultTimeoutMS ?? client.s.options?.timeoutMS; this.explicit = !!options.explicit; this._serverSession = this.explicit ? this.sessionPool.acquire() : null; this.txnNumberIncrement = 0; const defaultCausalConsistencyValue = this.explicit && options.snapshot !== true; this.supports = { // if we can enable causal consistency, do so by default causalConsistency: options.causalConsistency ?? defaultCausalConsistencyValue }; this.clusterTime = options.initialClusterTime; this.operationTime = void 0; this.owner = options.owner; this.defaultTransactionOptions = { ...options.defaultTransactionOptions }; this.transaction = new transactions_1.Transaction(); } /** The server id associated with this session */ get id() { return this.serverSession?.id; } get serverSession() { let serverSession = this._serverSession; if (serverSession == null) { if (this.explicit) { throw new error_1.MongoRuntimeError("Unexpected null serverSession for an explicit session"); } if (this.hasEnded) { throw new error_1.MongoRuntimeError("Unexpected null serverSession for an ended implicit session"); } serverSession = this.sessionPool.acquire(); this._serverSession = serverSession; } return serverSession; } get loadBalanced() { return this.client.topology?.description.type === common_1.TopologyType.LoadBalanced; } /** @internal */ pin(conn) { if (this.pinnedConnection) { throw TypeError("Cannot pin multiple connections to the same session"); } this.pinnedConnection = conn; conn.emit(constants_1.PINNED, this.inTransaction() ? metrics_1.ConnectionPoolMetrics.TXN : metrics_1.ConnectionPoolMetrics.CURSOR); } /** @internal */ unpin(options) { if (this.loadBalanced) { return maybeClearPinnedConnection(this, options); } this.transaction.unpinServer(); } get isPinned() { return this.loadBalanced ? !!this.pinnedConnection : this.transaction.isPinned; } /** * Frees any client-side resources held by the current session. If a session is in a transaction, * the transaction is aborted. * * Does not end the session on the server. * * @param options - Optional settings. Currently reserved for future use */ async endSession(options) { try { if (this.inTransaction()) { await this.abortTransaction({ ...options, throwTimeout: true }); } } catch (error) { if (error.name === "MongoOperationTimeoutError") throw error; (0, utils_1.squashError)(error); } finally { if (!this.hasEnded) { const serverSession = this.serverSession; if (serverSession != null) { this.sessionPool.release(serverSession); this._serverSession = new ServerSession(serverSession); } this.hasEnded = true; this.emit("ended", this); } maybeClearPinnedConnection(this, { force: true, ...options }); } } /** @internal */ async asyncDispose() { await this.endSession({ force: true }); } /** * Advances the operationTime for a ClientSession. * * @param operationTime - the `BSON.Timestamp` of the operation type it is desired to advance to */ advanceOperationTime(operationTime) { if (this.operationTime == null) { this.operationTime = operationTime; return; } if (operationTime.greaterThan(this.operationTime)) { this.operationTime = operationTime; } } /** * Advances the clusterTime for a ClientSession to the provided clusterTime of another ClientSession * * @param clusterTime - the $clusterTime returned by the server from another session in the form of a document containing the `BSON.Timestamp` clusterTime and signature */ advanceClusterTime(clusterTime) { if (!clusterTime || typeof clusterTime !== "object") { throw new error_1.MongoInvalidArgumentError("input cluster time must be an object"); } if (!clusterTime.clusterTime || clusterTime.clusterTime._bsontype !== "Timestamp") { throw new error_1.MongoInvalidArgumentError('input cluster time "clusterTime" property must be a valid BSON Timestamp'); } if (!clusterTime.signature || clusterTime.signature.hash?._bsontype !== "Binary" || typeof clusterTime.signature.keyId !== "bigint" && typeof clusterTime.signature.keyId !== "number" && clusterTime.signature.keyId?._bsontype !== "Long") { throw new error_1.MongoInvalidArgumentError('input cluster time must have a valid "signature" property with BSON Binary hash and BSON Long keyId'); } (0, common_1._advanceClusterTime)(this, clusterTime); } /** * Used to determine if this session equals another * * @param session - The session to compare to */ equals(session) { if (!(session instanceof _ClientSession)) { return false; } if (this.id == null || session.id == null) { return false; } return utils_1.ByteUtils.equals(this.id.id.buffer, session.id.id.buffer); } /** * Increment the transaction number on the internal ServerSession * * @privateRemarks * This helper increments a value stored on the client session that will be * added to the serverSession's txnNumber upon applying it to a command. * This is because the serverSession is lazily acquired after a connection is obtained */ incrementTransactionNumber() { this.txnNumberIncrement += 1; } /** @returns whether this session is currently in a transaction or not */ inTransaction() { return this.transaction.isActive; } /** * Starts a new transaction with the given options. * * @remarks * **IMPORTANT**: Running operations in parallel is not supported during a transaction. The use of `Promise.all`, * `Promise.allSettled`, `Promise.race`, etc to parallelize operations inside a transaction is * undefined behaviour. * * @param options - Options for the transaction */ startTransaction(options) { if (this.snapshotEnabled) { throw new error_1.MongoCompatibilityError("Transactions are not supported in snapshot sessions"); } if (this.inTransaction()) { throw new error_1.MongoTransactionError("Transaction already in progress"); } if (this.isPinned && this.transaction.isCommitted) { this.unpin(); } const topologyMaxWireVersion = (0, utils_1.maxWireVersion)(this.client.topology); if ((0, shared_1.isSharded)(this.client.topology) && topologyMaxWireVersion != null && topologyMaxWireVersion < minWireVersionForShardedTransactions) { throw new error_1.MongoCompatibilityError("Transactions are not supported on sharded clusters in MongoDB < 4.2."); } this.commitAttempted = false; this.incrementTransactionNumber(); this.transaction = new transactions_1.Transaction({ readConcern: options?.readConcern ?? this.defaultTransactionOptions.readConcern ?? this.clientOptions?.readConcern, writeConcern: options?.writeConcern ?? this.defaultTransactionOptions.writeConcern ?? this.clientOptions?.writeConcern, readPreference: options?.readPreference ?? this.defaultTransactionOptions.readPreference ?? this.clientOptions?.readPreference, maxCommitTimeMS: options?.maxCommitTimeMS ?? this.defaultTransactionOptions.maxCommitTimeMS }); this.transaction.transition(transactions_1.TxnState.STARTING_TRANSACTION); } /** * Commits the currently active transaction in this session. * * @param options - Optional options, can be used to override `defaultTimeoutMS`. */ async commitTransaction(options) { if (this.transaction.state === transactions_1.TxnState.NO_TRANSACTION) { throw new error_1.MongoTransactionError("No transaction started"); } if (this.transaction.state === transactions_1.TxnState.STARTING_TRANSACTION || this.transaction.state === transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY) { this.transaction.transition(transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY); return; } if (this.transaction.state === transactions_1.TxnState.TRANSACTION_ABORTED) { throw new error_1.MongoTransactionError("Cannot call commitTransaction after calling abortTransaction"); } const command = { commitTransaction: 1 }; const timeoutMS = typeof options?.timeoutMS === "number" ? options.timeoutMS : typeof this.timeoutMS === "number" ? this.timeoutMS : null; const wc = this.transaction.options.writeConcern ?? this.clientOptions?.writeConcern; if (wc != null) { if (timeoutMS == null && this.timeoutContext == null) { write_concern_1.WriteConcern.apply(command, { wtimeoutMS: 1e4, w: "majority", ...wc }); } else { const wcKeys = Object.keys(wc); if (wcKeys.length > 2 || !wcKeys.includes("wtimeoutMS") && !wcKeys.includes("wTimeoutMS")) write_concern_1.WriteConcern.apply(command, { ...wc, wtimeoutMS: void 0 }); } } if (this.transaction.state === transactions_1.TxnState.TRANSACTION_COMMITTED || this.commitAttempted) { if (timeoutMS == null && this.timeoutContext == null) { write_concern_1.WriteConcern.apply(command, { wtimeoutMS: 1e4, ...wc, w: "majority" }); } else { write_concern_1.WriteConcern.apply(command, { w: "majority", ...wc, wtimeoutMS: void 0 }); } } if (typeof this.transaction.options.maxTimeMS === "number") { command.maxTimeMS = this.transaction.options.maxTimeMS; } if (this.transaction.recoveryToken) { command.recoveryToken = this.transaction.recoveryToken; } const operation = new run_command_1.RunAdminCommandOperation(command, { session: this, readPreference: read_preference_1.ReadPreference.primary, bypassPinningCheck: true }); const timeoutContext = this.timeoutContext ?? (typeof timeoutMS === "number" ? timeout_1.TimeoutContext.create({ serverSelectionTimeoutMS: this.clientOptions.serverSelectionTimeoutMS, socketTimeoutMS: this.clientOptions.socketTimeoutMS, timeoutMS }) : null); try { await (0, execute_operation_1.executeOperation)(this.client, operation, timeoutContext); this.commitAttempted = void 0; return; } catch (firstCommitError) { this.commitAttempted = true; if (firstCommitError instanceof error_1.MongoError && (0, error_1.isRetryableWriteError)(firstCommitError)) { write_concern_1.WriteConcern.apply(command, { wtimeoutMS: 1e4, ...wc, w: "majority" }); this.unpin({ force: true }); try { await (0, execute_operation_1.executeOperation)(this.client, new run_command_1.RunAdminCommandOperation(command, { session: this, readPreference: read_preference_1.ReadPreference.primary, bypassPinningCheck: true }), timeoutContext); return; } catch (retryCommitError) { if (shouldAddUnknownTransactionCommitResultLabel(retryCommitError)) { retryCommitError.addErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult); } if (shouldUnpinAfterCommitError(retryCommitError)) { this.unpin({ error: retryCommitError }); } throw retryCommitError; } } if (shouldAddUnknownTransactionCommitResultLabel(firstCommitError)) { firstCommitError.addErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult); } if (shouldUnpinAfterCommitError(firstCommitError)) { this.unpin({ error: firstCommitError }); } throw firstCommitError; } finally { this.transaction.transition(transactions_1.TxnState.TRANSACTION_COMMITTED); } } async abortTransaction(options) { if (this.transaction.state === transactions_1.TxnState.NO_TRANSACTION) { throw new error_1.MongoTransactionError("No transaction started"); } if (this.transaction.state === transactions_1.TxnState.STARTING_TRANSACTION) { this.transaction.transition(transactions_1.TxnState.TRANSACTION_ABORTED); return; } if (this.transaction.state === transactions_1.TxnState.TRANSACTION_ABORTED) { throw new error_1.MongoTransactionError("Cannot call abortTransaction twice"); } if (this.transaction.state === transactions_1.TxnState.TRANSACTION_COMMITTED || this.transaction.state === transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY) { throw new error_1.MongoTransactionError("Cannot call abortTransaction after calling commitTransaction"); } const command = { abortTransaction: 1 }; const timeoutMS = typeof options?.timeoutMS === "number" ? options.timeoutMS : this.timeoutContext?.csotEnabled() ? this.timeoutContext.timeoutMS : typeof this.timeoutMS === "number" ? this.timeoutMS : null; const timeoutContext = timeoutMS != null ? timeout_1.TimeoutContext.create({ timeoutMS, serverSelectionTimeoutMS: this.clientOptions.serverSelectionTimeoutMS, socketTimeoutMS: this.clientOptions.socketTimeoutMS }) : null; const wc = this.transaction.options.writeConcern ?? this.clientOptions?.writeConcern; if (wc != null && timeoutMS == null) { write_concern_1.WriteConcern.apply(command, { wtimeoutMS: 1e4, w: "majority", ...wc }); } if (this.transaction.recoveryToken) { command.recoveryToken = this.transaction.recoveryToken; } const operation = new run_command_1.RunAdminCommandOperation(command, { session: this, readPreference: read_preference_1.ReadPreference.primary, bypassPinningCheck: true }); try { await (0, execute_operation_1.executeOperation)(this.client, operation, timeoutContext); this.unpin(); return; } catch (firstAbortError) { this.unpin(); if (firstAbortError.name === "MongoRuntimeError") throw firstAbortError; if (options?.throwTimeout && firstAbortError.name === "MongoOperationTimeoutError") { throw firstAbortError; } if (firstAbortError instanceof error_1.MongoError && (0, error_1.isRetryableWriteError)(firstAbortError)) { try { await (0, execute_operation_1.executeOperation)(this.client, operation, timeoutContext); return; } catch (secondAbortError) { if (secondAbortError.name === "MongoRuntimeError") throw secondAbortError; if (options?.throwTimeout && secondAbortError.name === "MongoOperationTimeoutError") { throw secondAbortError; } } } } finally { this.transaction.transition(transactions_1.TxnState.TRANSACTION_ABORTED); if (this.loadBalanced) { maybeClearPinnedConnection(this, { force: false }); } } } /** * This is here to ensure that ClientSession is never serialized to BSON. */ toBSON() { throw new error_1.MongoRuntimeError("ClientSession cannot be serialized to BSON."); } /** * Starts a transaction and runs a provided function, ensuring the commitTransaction is always attempted when all operations run in the function have completed. * * **IMPORTANT:** This method requires the function passed in to return a Promise. That promise must be made by `await`-ing all operations in such a way that rejections are propagated to the returned promise. * * **IMPORTANT:** Running operations in parallel is not supported during a transaction. The use of `Promise.all`, * `Promise.allSettled`, `Promise.race`, etc to parallelize operations inside a transaction is * undefined behaviour. * * **IMPORTANT:** When running an operation inside a `withTransaction` callback, if it is not * provided the explicit session in its options, it will not be part of the transaction and it will not respect timeoutMS. * * * @remarks * - If all operations successfully complete and the `commitTransaction` operation is successful, then the provided function will return the result of the provided function. * - If the transaction is unable to complete or an error is thrown from within the provided function, then the provided function will throw an error. * - If the transaction is manually aborted within the provided function it will not throw. * - If the driver needs to attempt to retry the operations, the provided function may be called multiple times. * * Checkout a descriptive example here: * @see https://www.mongodb.com/blog/post/quick-start-nodejs--mongodb--how-to-implement-transactions * * If a command inside withTransaction fails: * - It may cause the transaction on the server to be aborted. * - This situation is normally handled transparently by the driver. * - However, if the application catches such an error and does not rethrow it, the driver will not be able to determine whether the transaction was aborted or not. * - The driver will then retry the transaction indefinitely. * * To avoid this situation, the application must not silently handle errors within the provided function. * If the application needs to handle errors within, it must await all operations such that if an operation is rejected it becomes the rejection of the callback function passed into withTransaction. * * @param fn - callback to run within a transaction * @param options - optional settings for the transaction * @returns A raw command response or undefined */ async withTransaction(fn, options) { const MAX_TIMEOUT = 12e4; const timeoutMS = options?.timeoutMS ?? this.timeoutMS ?? null; this.timeoutContext = timeoutMS != null ? timeout_1.TimeoutContext.create({ timeoutMS, serverSelectionTimeoutMS: this.clientOptions.serverSelectionTimeoutMS, socketTimeoutMS: this.clientOptions.socketTimeoutMS }) : null; const startTime = this.timeoutContext?.csotEnabled() ? this.timeoutContext.start : (0, utils_1.now)(); let committed = false; let result; try { while (!committed) { this.startTransaction(options); try { const promise = fn(this); if (!(0, utils_1.isPromiseLike)(promise)) { throw new error_1.MongoInvalidArgumentError("Function provided to `withTransaction` must return a Promise"); } result = await promise; if (this.transaction.state === transactions_1.TxnState.NO_TRANSACTION || this.transaction.state === transactions_1.TxnState.TRANSACTION_COMMITTED || this.transaction.state === transactions_1.TxnState.TRANSACTION_ABORTED) { return result; } } catch (fnError) { if (!(fnError instanceof error_1.MongoError) || fnError instanceof error_1.MongoInvalidArgumentError) { await this.abortTransaction(); throw fnError; } if (this.transaction.state === transactions_1.TxnState.STARTING_TRANSACTION || this.transaction.state === transactions_1.TxnState.TRANSACTION_IN_PROGRESS) { await this.abortTransaction(); } if (fnError.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError) && (this.timeoutContext != null || (0, utils_1.now)() - startTime < MAX_TIMEOUT)) { continue; } throw fnError; } while (!committed) { try { await this.commitTransaction(); committed = true; } catch (commitError) { if (!isMaxTimeMSExpiredError(commitError) && commitError.hasErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult) && (this.timeoutContext != null || (0, utils_1.now)() - startTime < MAX_TIMEOUT)) { continue; } if (commitError.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError) && (this.timeoutContext != null || (0, utils_1.now)() - startTime < MAX_TIMEOUT)) { break; } throw commitError; } } } return result; } finally { this.timeoutContext = null; } } }; exports2.ClientSession = ClientSession; (0, resource_management_1.configureResourceManagement)(ClientSession.prototype); var NON_DETERMINISTIC_WRITE_CONCERN_ERRORS = /* @__PURE__ */ new Set([ "CannotSatisfyWriteConcern", "UnknownReplWriteConcern", "UnsatisfiableWriteConcern" ]); function shouldUnpinAfterCommitError(commitError) { if (commitError instanceof error_1.MongoError) { if ((0, error_1.isRetryableWriteError)(commitError) || commitError instanceof error_1.MongoWriteConcernError || isMaxTimeMSExpiredError(commitError)) { if (isUnknownTransactionCommitResult(commitError)) { return true; } } else if (commitError.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) { return true; } } return false; } function shouldAddUnknownTransactionCommitResultLabel(commitError) { let ok = (0, error_1.isRetryableWriteError)(commitError); ok ||= commitError instanceof error_1.MongoWriteConcernError; ok ||= isMaxTimeMSExpiredError(commitError); ok &&= isUnknownTransactionCommitResult(commitError); return ok; } function isUnknownTransactionCommitResult(err) { const isNonDeterministicWriteConcernError = err instanceof error_1.MongoServerError && err.codeName && NON_DETERMINISTIC_WRITE_CONCERN_ERRORS.has(err.codeName); return isMaxTimeMSExpiredError(err) || !isNonDeterministicWriteConcernError && err.code !== error_1.MONGODB_ERROR_CODES.UnsatisfiableWriteConcern && err.code !== error_1.MONGODB_ERROR_CODES.UnknownReplWriteConcern; } function maybeClearPinnedConnection(session, options) { const conn = session.pinnedConnection; const error = options?.error; if (session.inTransaction() && error && error instanceof error_1.MongoError && error.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) { return; } const topology = session.client.topology; if (conn && topology != null) { const servers = Array.from(topology.s.servers.values()); const loadBalancer = servers[0]; if (options?.error == null || options?.force) { loadBalancer.pool.checkIn(conn); session.pinnedConnection = void 0; conn.emit(constants_1.UNPINNED, session.transaction.state !== transactions_1.TxnState.NO_TRANSACTION ? metrics_1.ConnectionPoolMetrics.TXN : metrics_1.ConnectionPoolMetrics.CURSOR); if (options?.forceClear) { loadBalancer.pool.clear({ serviceId: conn.serviceId }); } } } } function isMaxTimeMSExpiredError(err) { if (err == null || !(err instanceof error_1.MongoServerError)) { return false; } return err.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired || err.writeConcernError?.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired; } var ServerSession = class { /** @internal */ constructor(cloned) { if (cloned != null) { const idBytes = Buffer.allocUnsafe(16); idBytes.set(cloned.id.id.buffer); this.id = { id: new bson_1.Binary(idBytes, cloned.id.id.sub_type) }; this.lastUse = cloned.lastUse; this.txnNumber = cloned.txnNumber; this.isDirty = cloned.isDirty; return; } this.id = { id: new bson_1.Binary((0, utils_1.uuidV4)(), bson_1.Binary.SUBTYPE_UUID) }; this.lastUse = (0, utils_1.now)(); this.txnNumber = 0; this.isDirty = false; } /** * Determines if the server session has timed out. * * @param sessionTimeoutMinutes - The server's "logicalSessionTimeoutMinutes" */ hasTimedOut(sessionTimeoutMinutes) { const idleTimeMinutes = Math.round((0, utils_1.calculateDurationInMs)(this.lastUse) % 864e5 % 36e5 / 6e4); return idleTimeMinutes > sessionTimeoutMinutes - 1; } }; exports2.ServerSession = ServerSession; var ServerSessionPool = class { constructor(client) { if (client == null) { throw new error_1.MongoRuntimeError("ServerSessionPool requires a MongoClient"); } this.client = client; this.sessions = new utils_1.List(); } /** * Acquire a Server Session from the pool. * Iterates through each session in the pool, removing any stale sessions * along the way. The first non-stale session found is removed from the * pool and returned. If no non-stale session is found, a new ServerSession is created. */ acquire() { const sessionTimeoutMinutes = this.client.topology?.logicalSessionTimeoutMinutes ?? 10; let session = null; while (this.sessions.length > 0) { const potentialSession = this.sessions.shift(); if (potentialSession != null && (!!this.client.topology?.loadBalanced || !potentialSession.hasTimedOut(sessionTimeoutMinutes))) { session = potentialSession; break; } } if (session == null) { session = new ServerSession(); } return session; } /** * Release a session to the session pool * Adds the session back to the session pool if the session has not timed out yet. * This method also removes any stale sessions from the pool. * * @param session - The session to release to the pool */ release(session) { const sessionTimeoutMinutes = this.client.topology?.logicalSessionTimeoutMinutes ?? 10; if (this.client.topology?.loadBalanced && !sessionTimeoutMinutes) { this.sessions.unshift(session); } if (!sessionTimeoutMinutes) { return; } this.sessions.prune((session2) => session2.hasTimedOut(sessionTimeoutMinutes)); if (!session.hasTimedOut(sessionTimeoutMinutes)) { if (session.isDirty) { return; } this.sessions.unshift(session); } } }; exports2.ServerSessionPool = ServerSessionPool; function applySession(session, command, options) { if (session.hasEnded) { return new error_1.MongoExpiredSessionError(); } const serverSession = session.serverSession; if (serverSession == null) { return new error_1.MongoRuntimeError("Unable to acquire server session"); } if (options.writeConcern?.w === 0) { if (session && session.explicit) { return new error_1.MongoAPIError("Cannot have explicit session with unacknowledged writes"); } return; } serverSession.lastUse = (0, utils_1.now)(); command.lsid = serverSession.id; const inTxnOrTxnCommand = session.inTransaction() || (0, transactions_1.isTransactionCommand)(command); const isRetryableWrite = !!options.willRetryWrite; if (isRetryableWrite || inTxnOrTxnCommand) { serverSession.txnNumber += session.txnNumberIncrement; session.txnNumberIncrement = 0; command.txnNumber = bson_1.Long.fromNumber(serverSession.txnNumber); } if (!inTxnOrTxnCommand) { if (session.transaction.state !== transactions_1.TxnState.NO_TRANSACTION) { session.transaction.transition(transactions_1.TxnState.NO_TRANSACTION); } if (session.supports.causalConsistency && session.operationTime && (0, utils_1.commandSupportsReadConcern)(command)) { command.readConcern = command.readConcern || {}; Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); } else if (session.snapshotEnabled) { command.readConcern = command.readConcern || { level: read_concern_1.ReadConcernLevel.snapshot }; if (session.snapshotTime != null) { Object.assign(command.readConcern, { atClusterTime: session.snapshotTime }); } } return; } command.autocommit = false; if (session.transaction.state === transactions_1.TxnState.STARTING_TRANSACTION) { session.transaction.transition(transactions_1.TxnState.TRANSACTION_IN_PROGRESS); command.startTransaction = true; const readConcern = session.transaction.options.readConcern || session?.clientOptions?.readConcern; if (readConcern) { command.readConcern = readConcern; } if (session.supports.causalConsistency && session.operationTime) { command.readConcern = command.readConcern || {}; Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); } } return; } function updateSessionFromResponse(session, document2) { if (document2.$clusterTime) { (0, common_1._advanceClusterTime)(session, document2.$clusterTime); } if (document2.operationTime && session && session.supports.causalConsistency) { session.advanceOperationTime(document2.operationTime); } if (document2.recoveryToken && session && session.inTransaction()) { session.transaction._recoveryToken = document2.recoveryToken; } if (session?.snapshotEnabled && session.snapshotTime == null) { const atClusterTime = document2.atClusterTime; if (atClusterTime) { session.snapshotTime = atClusterTime; } } } } }); // netlify/functions/node_modules/mongodb/lib/cmap/command_monitoring_events.js var require_command_monitoring_events = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/command_monitoring_events.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.SENSITIVE_COMMANDS = exports2.CommandFailedEvent = exports2.CommandSucceededEvent = exports2.CommandStartedEvent = void 0; var constants_1 = require_constants(); var utils_1 = require_utils(); var commands_1 = require_commands(); var CommandStartedEvent = class { /** * Create a started event * * @internal * @param pool - the pool that originated the command * @param command - the command */ constructor(connection, command, serverConnectionId) { this.name = constants_1.COMMAND_STARTED; const cmd = extractCommand(command); const commandName = extractCommandName(cmd); const { address, connectionId, serviceId } = extractConnectionDetails(connection); if (exports2.SENSITIVE_COMMANDS.has(commandName)) { this.commandObj = {}; this.commandObj[commandName] = true; } this.address = address; this.connectionId = connectionId; this.serviceId = serviceId; this.requestId = command.requestId; this.databaseName = command.databaseName; this.commandName = commandName; this.command = maybeRedact(commandName, cmd, cmd); this.serverConnectionId = serverConnectionId; } /* @internal */ get hasServiceId() { return !!this.serviceId; } }; exports2.CommandStartedEvent = CommandStartedEvent; var CommandSucceededEvent = class { /** * Create a succeeded event * * @internal * @param pool - the pool that originated the command * @param command - the command * @param reply - the reply for this command from the server * @param started - a high resolution tuple timestamp of when the command was first sent, to calculate duration */ constructor(connection, command, reply, started, serverConnectionId) { this.name = constants_1.COMMAND_SUCCEEDED; const cmd = extractCommand(command); const commandName = extractCommandName(cmd); const { address, connectionId, serviceId } = extractConnectionDetails(connection); this.address = address; this.connectionId = connectionId; this.serviceId = serviceId; this.requestId = command.requestId; this.commandName = commandName; this.duration = (0, utils_1.calculateDurationInMs)(started); this.reply = maybeRedact(commandName, cmd, extractReply(reply)); this.serverConnectionId = serverConnectionId; this.databaseName = command.databaseName; } /* @internal */ get hasServiceId() { return !!this.serviceId; } }; exports2.CommandSucceededEvent = CommandSucceededEvent; var CommandFailedEvent = class { /** * Create a failure event * * @internal * @param pool - the pool that originated the command * @param command - the command * @param error - the generated error or a server error response * @param started - a high resolution tuple timestamp of when the command was first sent, to calculate duration */ constructor(connection, command, error, started, serverConnectionId) { this.name = constants_1.COMMAND_FAILED; const cmd = extractCommand(command); const commandName = extractCommandName(cmd); const { address, connectionId, serviceId } = extractConnectionDetails(connection); this.address = address; this.connectionId = connectionId; this.serviceId = serviceId; this.requestId = command.requestId; this.commandName = commandName; this.duration = (0, utils_1.calculateDurationInMs)(started); this.failure = maybeRedact(commandName, cmd, error); this.serverConnectionId = serverConnectionId; this.databaseName = command.databaseName; } /* @internal */ get hasServiceId() { return !!this.serviceId; } }; exports2.CommandFailedEvent = CommandFailedEvent; exports2.SENSITIVE_COMMANDS = /* @__PURE__ */ new Set([ "authenticate", "saslStart", "saslContinue", "getnonce", "createUser", "updateUser", "copydbgetnonce", "copydbsaslstart", "copydb" ]); var HELLO_COMMANDS = /* @__PURE__ */ new Set(["hello", constants_1.LEGACY_HELLO_COMMAND, constants_1.LEGACY_HELLO_COMMAND_CAMEL_CASE]); var extractCommandName = (commandDoc) => Object.keys(commandDoc)[0]; var collectionName = (command) => command.ns.split(".")[1]; var maybeRedact = (commandName, commandDoc, result) => exports2.SENSITIVE_COMMANDS.has(commandName) || HELLO_COMMANDS.has(commandName) && commandDoc.speculativeAuthenticate ? {} : result; var LEGACY_FIND_QUERY_MAP = { $query: "filter", $orderby: "sort", $hint: "hint", $comment: "comment", $maxScan: "maxScan", $max: "max", $min: "min", $returnKey: "returnKey", $showDiskLoc: "showRecordId", $maxTimeMS: "maxTimeMS", $snapshot: "snapshot" }; var LEGACY_FIND_OPTIONS_MAP = { numberToSkip: "skip", numberToReturn: "batchSize", returnFieldSelector: "projection" }; function extractCommand(command) { if (command instanceof commands_1.OpMsgRequest) { const cmd = { ...command.command }; if (cmd.ops instanceof commands_1.DocumentSequence) { cmd.ops = cmd.ops.documents; } if (cmd.nsInfo instanceof commands_1.DocumentSequence) { cmd.nsInfo = cmd.nsInfo.documents; } return cmd; } if (command.query?.$query) { let result; if (command.ns === "admin.$cmd") { result = Object.assign({}, command.query.$query); } else { result = { find: collectionName(command) }; Object.keys(LEGACY_FIND_QUERY_MAP).forEach((key) => { if (command.query[key] != null) { result[LEGACY_FIND_QUERY_MAP[key]] = { ...command.query[key] }; } }); } Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach((key) => { const legacyKey = key; if (command[legacyKey] != null) { result[LEGACY_FIND_OPTIONS_MAP[legacyKey]] = command[legacyKey]; } }); return result; } let clonedQuery = {}; const clonedCommand = { ...command }; if (command.query) { clonedQuery = { ...command.query }; clonedCommand.query = clonedQuery; } return command.query ? clonedQuery : clonedCommand; } function extractReply(reply) { if (!reply) { return reply; } return reply.result ? reply.result : reply; } function extractConnectionDetails(connection) { let connectionId; if ("id" in connection) { connectionId = connection.id; } return { address: connection.address, serviceId: connection.serviceId, connectionId }; } } }); // netlify/functions/node_modules/mongodb/lib/cmap/stream_description.js var require_stream_description = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/stream_description.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.StreamDescription = void 0; var bson_1 = require_bson2(); var common_1 = require_common(); var server_description_1 = require_server_description(); var RESPONSE_FIELDS = [ "minWireVersion", "maxWireVersion", "maxBsonObjectSize", "maxMessageSizeBytes", "maxWriteBatchSize", "logicalSessionTimeoutMinutes" ]; var StreamDescription = class { constructor(address, options) { this.hello = null; this.address = address; this.type = common_1.ServerType.Unknown; this.minWireVersion = void 0; this.maxWireVersion = void 0; this.maxBsonObjectSize = 16777216; this.maxMessageSizeBytes = 48e6; this.maxWriteBatchSize = 1e5; this.logicalSessionTimeoutMinutes = options?.logicalSessionTimeoutMinutes; this.loadBalanced = !!options?.loadBalanced; this.compressors = options && options.compressors && Array.isArray(options.compressors) ? options.compressors : []; this.serverConnectionId = null; } receiveResponse(response) { if (response == null) { return; } this.hello = response; this.type = (0, server_description_1.parseServerType)(response); if ("connectionId" in response) { this.serverConnectionId = this.parseServerConnectionID(response.connectionId); } else { this.serverConnectionId = null; } for (const field of RESPONSE_FIELDS) { if (response[field] != null) { this[field] = response[field]; } if ("__nodejs_mock_server__" in response) { this.__nodejs_mock_server__ = response["__nodejs_mock_server__"]; } } if (response.compression) { this.compressor = this.compressors.filter((c) => response.compression?.includes(c))[0]; } } /* @internal */ parseServerConnectionID(serverConnectionId) { return bson_1.Long.isLong(serverConnectionId) ? serverConnectionId.toBigInt() : ( // @ts-expect-error: Doubles are coercible to number BigInt(serverConnectionId) ); } }; exports2.StreamDescription = StreamDescription; } }); // netlify/functions/node_modules/mongodb/lib/cmap/wire_protocol/on_data.js var require_on_data = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/wire_protocol/on_data.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.onData = onData; var utils_1 = require_utils(); function onData(emitter, { timeoutContext, signal }) { signal?.throwIfAborted(); const unconsumedEvents = new utils_1.List(); const unconsumedPromises = new utils_1.List(); let error = null; let finished = false; const iterator = { next() { const value = unconsumedEvents.shift(); if (value != null) { return Promise.resolve({ value, done: false }); } if (error != null) { const p = Promise.reject(error); error = null; return p; } if (finished) return closeHandler(); const { promise, resolve, reject } = (0, utils_1.promiseWithResolvers)(); unconsumedPromises.push({ resolve, reject }); return promise; }, return() { return closeHandler(); }, throw(err) { errorHandler(err); return Promise.resolve({ value: void 0, done: true }); }, [Symbol.asyncIterator]() { return this; }, // Note this should currently not be used, but is required by the AsyncGenerator interface. async [Symbol.asyncDispose]() { await closeHandler(); } }; emitter.on("data", eventHandler); emitter.on("error", errorHandler); const abortListener = (0, utils_1.addAbortListener)(signal, function() { errorHandler(this.reason); }); const timeoutForSocketRead = timeoutContext?.timeoutForSocketRead; timeoutForSocketRead?.throwIfExpired(); timeoutForSocketRead?.then(void 0, errorHandler); return iterator; function eventHandler(value) { const promise = unconsumedPromises.shift(); if (promise != null) promise.resolve({ value, done: false }); else unconsumedEvents.push(value); } function errorHandler(err) { const promise = unconsumedPromises.shift(); if (promise != null) promise.reject(err); else error = err; void closeHandler(); } function closeHandler() { emitter.off("data", eventHandler); emitter.off("error", errorHandler); abortListener?.[utils_1.kDispose](); finished = true; timeoutForSocketRead?.clear(); const doneResult = { value: void 0, done: finished }; for (const promise of unconsumedPromises) { promise.resolve(doneResult); } return Promise.resolve(doneResult); } } } }); // netlify/functions/node_modules/mongodb/lib/cmap/connection.js var require_connection = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/connection.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.CryptoConnection = exports2.SizedMessageTransform = exports2.Connection = void 0; exports2.hasSessionSupport = hasSessionSupport; var stream_1 = require("stream"); var timers_1 = require("timers"); var bson_1 = require_bson2(); var constants_1 = require_constants(); var error_1 = require_error(); var mongo_logger_1 = require_mongo_logger(); var mongo_types_1 = require_mongo_types(); var read_preference_1 = require_read_preference(); var common_1 = require_common(); var sessions_1 = require_sessions(); var timeout_1 = require_timeout(); var utils_1 = require_utils(); var command_monitoring_events_1 = require_command_monitoring_events(); var commands_1 = require_commands(); var stream_description_1 = require_stream_description(); var compression_1 = require_compression(); var on_data_1 = require_on_data(); var responses_1 = require_responses(); var shared_1 = require_shared(); function hasSessionSupport(conn) { const description = conn.description; return description.logicalSessionTimeoutMinutes != null; } function streamIdentifier(stream, options) { if (options.proxyHost) { return options.hostAddress.toString(); } const { remoteAddress, remotePort } = stream; if (typeof remoteAddress === "string" && typeof remotePort === "number") { return utils_1.HostAddress.fromHostPort(remoteAddress, remotePort).toString(); } return (0, utils_1.uuidV4)().toString("hex"); } var Connection = class _Connection extends mongo_types_1.TypedEventEmitter { constructor(stream, options) { super(); this.lastHelloMS = -1; this.helloOk = false; this.delayedTimeoutId = null; this.closed = false; this.clusterTime = null; this.error = null; this.dataEvents = null; this.on("error", utils_1.noop); this.socket = stream; this.id = options.id; this.address = streamIdentifier(stream, options); this.socketTimeoutMS = options.socketTimeoutMS ?? 0; this.monitorCommands = options.monitorCommands; this.serverApi = options.serverApi; this.mongoLogger = options.mongoLogger; this.established = false; this.description = new stream_description_1.StreamDescription(this.address, options); this.generation = options.generation; this.lastUseTime = (0, utils_1.now)(); this.messageStream = this.socket.on("error", this.onSocketError.bind(this)).pipe(new SizedMessageTransform({ connection: this })).on("error", this.onTransformError.bind(this)); this.socket.on("close", this.onClose.bind(this)); this.socket.on("timeout", this.onTimeout.bind(this)); this.messageStream.pause(); } get hello() { return this.description.hello; } // the `connect` method stores the result of the handshake hello on the connection set hello(response) { this.description.receiveResponse(response); Object.freeze(this.description); } get serviceId() { return this.hello?.serviceId; } get loadBalanced() { return this.description.loadBalanced; } get idleTime() { return (0, utils_1.calculateDurationInMs)(this.lastUseTime); } get hasSessionSupport() { return this.description.logicalSessionTimeoutMinutes != null; } get supportsOpMsg() { return this.description != null && (0, utils_1.maxWireVersion)(this) >= 6 && !this.description.__nodejs_mock_server__; } get shouldEmitAndLogCommand() { return (this.monitorCommands || this.established && !this.authContext?.reauthenticating && this.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.COMMAND, mongo_logger_1.SeverityLevel.DEBUG)) ?? false; } markAvailable() { this.lastUseTime = (0, utils_1.now)(); } onSocketError(cause) { this.onError(new error_1.MongoNetworkError(cause.message, { cause })); } onTransformError(error) { this.onError(error); } onError(error) { this.cleanup(error); } onClose() { const message = `connection ${this.id} to ${this.address} closed`; this.cleanup(new error_1.MongoNetworkError(message)); } onTimeout() { this.delayedTimeoutId = (0, timers_1.setTimeout)(() => { const message = `connection ${this.id} to ${this.address} timed out`; const beforeHandshake = this.hello == null; this.cleanup(new error_1.MongoNetworkTimeoutError(message, { beforeHandshake })); }, 1).unref(); } destroy() { if (this.closed) { return; } this.removeAllListeners(_Connection.PINNED); this.removeAllListeners(_Connection.UNPINNED); const message = `connection ${this.id} to ${this.address} closed`; this.cleanup(new error_1.MongoNetworkError(message)); } /** * A method that cleans up the connection. When `force` is true, this method * forcibly destroys the socket. * * If an error is provided, any in-flight operations will be closed with the error. * * This method does nothing if the connection is already closed. */ cleanup(error) { if (this.closed) { return; } this.socket.destroy(); this.error = error; this.dataEvents?.throw(error).then(void 0, utils_1.squashError); this.closed = true; this.emit(_Connection.CLOSE); } prepareCommand(db, command, options) { let cmd = { ...command }; const readPreference = (0, shared_1.getReadPreference)(options); const session = options?.session; let clusterTime = this.clusterTime; if (this.serverApi) { const { version, strict, deprecationErrors } = this.serverApi; cmd.apiVersion = version; if (strict != null) cmd.apiStrict = strict; if (deprecationErrors != null) cmd.apiDeprecationErrors = deprecationErrors; } if (this.hasSessionSupport && session) { if (session.clusterTime && clusterTime && session.clusterTime.clusterTime.greaterThan(clusterTime.clusterTime)) { clusterTime = session.clusterTime; } const sessionError = (0, sessions_1.applySession)(session, cmd, options); if (sessionError) throw sessionError; } else if (session?.explicit) { throw new error_1.MongoCompatibilityError("Current topology does not support sessions"); } if (clusterTime) { cmd.$clusterTime = clusterTime; } if (this.description.type !== common_1.ServerType.Standalone) { if (!(0, shared_1.isSharded)(this) && !this.description.loadBalanced && this.supportsOpMsg && options.directConnection === true && readPreference?.mode === "primary") { cmd.$readPreference = read_preference_1.ReadPreference.primaryPreferred.toJSON(); } else if ((0, shared_1.isSharded)(this) && !this.supportsOpMsg && readPreference?.mode !== "primary") { cmd = { $query: cmd, $readPreference: readPreference.toJSON() }; } else if (readPreference?.mode !== "primary") { cmd.$readPreference = readPreference.toJSON(); } } const commandOptions = { numberToSkip: 0, numberToReturn: -1, checkKeys: false, // This value is not overridable secondaryOk: readPreference.secondaryOk(), ...options }; options.timeoutContext?.addMaxTimeMSToCommand(cmd, options); const message = this.supportsOpMsg ? new commands_1.OpMsgRequest(db, cmd, commandOptions) : new commands_1.OpQueryRequest(db, cmd, commandOptions); return message; } async *sendWire(message, options, responseType) { this.throwIfAborted(); const timeout = options.socketTimeoutMS ?? options?.timeoutContext?.getSocketTimeoutMS() ?? this.socketTimeoutMS; this.socket.setTimeout(timeout); try { await this.writeCommand(message, { agreedCompressor: this.description.compressor ?? "none", zlibCompressionLevel: this.description.zlibCompressionLevel, timeoutContext: options.timeoutContext, signal: options.signal }); if (options.noResponse || message.moreToCome) { yield responses_1.MongoDBResponse.empty; return; } this.throwIfAborted(); if (options.timeoutContext?.csotEnabled() && options.timeoutContext.minRoundTripTime != null && options.timeoutContext.remainingTimeMS < options.timeoutContext.minRoundTripTime) { throw new error_1.MongoOperationTimeoutError("Server roundtrip time is greater than the time remaining"); } for await (const response of this.readMany(options)) { this.socket.setTimeout(0); const bson = response.parse(); const document2 = (responseType ?? responses_1.MongoDBResponse).make(bson); yield document2; this.throwIfAborted(); this.socket.setTimeout(timeout); } } finally { this.socket.setTimeout(0); } } async *sendCommand(ns, command, options, responseType) { options?.signal?.throwIfAborted(); const message = this.prepareCommand(ns.db, command, options); let started = 0; if (this.shouldEmitAndLogCommand) { started = (0, utils_1.now)(); this.emitAndLogCommand(this.monitorCommands, _Connection.COMMAND_STARTED, message.databaseName, this.established, new command_monitoring_events_1.CommandStartedEvent(this, message, this.description.serverConnectionId)); } const bsonOptions = options.documentsReturnedIn == null || !options.raw ? options : { ...options, raw: false, fieldsAsRaw: { [options.documentsReturnedIn]: true } }; let document2 = void 0; let object = void 0; try { this.throwIfAborted(); for await (document2 of this.sendWire(message, options, responseType)) { object = void 0; if (options.session != null) { (0, sessions_1.updateSessionFromResponse)(options.session, document2); } if (document2.$clusterTime) { this.clusterTime = document2.$clusterTime; this.emit(_Connection.CLUSTER_TIME_RECEIVED, document2.$clusterTime); } if (document2.ok === 0) { if (options.timeoutContext?.csotEnabled() && document2.isMaxTimeExpiredError) { throw new error_1.MongoOperationTimeoutError("Server reported a timeout error", { cause: new error_1.MongoServerError(object ??= document2.toObject(bsonOptions)) }); } throw new error_1.MongoServerError(object ??= document2.toObject(bsonOptions)); } if (this.shouldEmitAndLogCommand) { this.emitAndLogCommand(this.monitorCommands, _Connection.COMMAND_SUCCEEDED, message.databaseName, this.established, new command_monitoring_events_1.CommandSucceededEvent(this, message, options.noResponse ? void 0 : message.moreToCome ? { ok: 1 } : object ??= document2.toObject(bsonOptions), started, this.description.serverConnectionId)); } if (responseType == null) { yield object ??= document2.toObject(bsonOptions); } else { yield document2; } this.throwIfAborted(); } } catch (error) { if (this.shouldEmitAndLogCommand) { this.emitAndLogCommand(this.monitorCommands, _Connection.COMMAND_FAILED, message.databaseName, this.established, new command_monitoring_events_1.CommandFailedEvent(this, message, error, started, this.description.serverConnectionId)); } throw error; } } async command(ns, command, options = {}, responseType) { this.throwIfAborted(); options.signal?.throwIfAborted(); for await (const document2 of this.sendCommand(ns, command, options, responseType)) { if (options.timeoutContext?.csotEnabled()) { if (responses_1.MongoDBResponse.is(document2)) { if (document2.isMaxTimeExpiredError) { throw new error_1.MongoOperationTimeoutError("Server reported a timeout error", { cause: new error_1.MongoServerError(document2.toObject()) }); } } else { if (Array.isArray(document2?.writeErrors) && document2.writeErrors.some((error) => error?.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired) || document2?.writeConcernError?.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired) { throw new error_1.MongoOperationTimeoutError("Server reported a timeout error", { cause: new error_1.MongoServerError(document2) }); } } } return document2; } throw new error_1.MongoUnexpectedServerResponseError("Unable to get response from server"); } exhaustCommand(ns, command, options, replyListener) { const exhaustLoop = async () => { this.throwIfAborted(); for await (const reply of this.sendCommand(ns, command, options)) { replyListener(void 0, reply); this.throwIfAborted(); } throw new error_1.MongoUnexpectedServerResponseError("Server ended moreToCome unexpectedly"); }; exhaustLoop().then(void 0, replyListener); } throwIfAborted() { if (this.error) throw this.error; } /** * @internal * * Writes an OP_MSG or OP_QUERY request to the socket, optionally compressing the command. This method * waits until the socket's buffer has emptied (the Nodejs socket `drain` event has fired). */ async writeCommand(command, options) { const finalCommand = options.agreedCompressor === "none" || !commands_1.OpCompressedRequest.canCompress(command) ? command : new commands_1.OpCompressedRequest(command, { agreedCompressor: options.agreedCompressor ?? "none", zlibCompressionLevel: options.zlibCompressionLevel ?? 0 }); const buffer = Buffer.concat(await finalCommand.toBin()); if (options.timeoutContext?.csotEnabled()) { if (options.timeoutContext.minRoundTripTime != null && options.timeoutContext.remainingTimeMS < options.timeoutContext.minRoundTripTime) { throw new error_1.MongoOperationTimeoutError("Server roundtrip time is greater than the time remaining"); } } if (this.socket.write(buffer)) return; const drainEvent = (0, utils_1.once)(this.socket, "drain", options); const timeout = options?.timeoutContext?.timeoutForSocketWrite; const drained = timeout ? Promise.race([drainEvent, timeout]) : drainEvent; try { return await drained; } catch (writeError) { if (timeout_1.TimeoutError.is(writeError)) { const timeoutError = new error_1.MongoOperationTimeoutError("Timed out at socket write"); this.onError(timeoutError); throw timeoutError; } else if (writeError === options.signal?.reason) { this.onError(writeError); } throw writeError; } finally { timeout?.clear(); } } /** * @internal * * Returns an async generator that yields full wire protocol messages from the underlying socket. This function * yields messages until `moreToCome` is false or not present in a response, or the caller cancels the request * by calling `return` on the generator. * * Note that `for-await` loops call `return` automatically when the loop is exited. */ async *readMany(options) { try { this.dataEvents = (0, on_data_1.onData)(this.messageStream, options); this.messageStream.resume(); for await (const message of this.dataEvents) { const response = await (0, compression_1.decompressResponse)(message); yield response; if (!response.moreToCome) { return; } } } catch (readError) { if (timeout_1.TimeoutError.is(readError)) { const timeoutError = new error_1.MongoOperationTimeoutError(`Timed out during socket read (${readError.duration}ms)`); this.dataEvents = null; this.onError(timeoutError); throw timeoutError; } else if (readError === options.signal?.reason) { this.onError(readError); } throw readError; } finally { this.dataEvents = null; this.messageStream.pause(); } } }; exports2.Connection = Connection; Connection.COMMAND_STARTED = constants_1.COMMAND_STARTED; Connection.COMMAND_SUCCEEDED = constants_1.COMMAND_SUCCEEDED; Connection.COMMAND_FAILED = constants_1.COMMAND_FAILED; Connection.CLUSTER_TIME_RECEIVED = constants_1.CLUSTER_TIME_RECEIVED; Connection.CLOSE = constants_1.CLOSE; Connection.PINNED = constants_1.PINNED; Connection.UNPINNED = constants_1.UNPINNED; var SizedMessageTransform = class extends stream_1.Transform { constructor({ connection }) { super({ writableObjectMode: false, readableObjectMode: true }); this.bufferPool = new utils_1.BufferPool(); this.connection = connection; } _transform(chunk, encoding, callback) { if (this.connection.delayedTimeoutId != null) { (0, timers_1.clearTimeout)(this.connection.delayedTimeoutId); this.connection.delayedTimeoutId = null; } this.bufferPool.append(chunk); while (this.bufferPool.length) { const sizeOfMessage = this.bufferPool.getInt32(); if (sizeOfMessage == null) { break; } if (sizeOfMessage < 0) { return callback(new error_1.MongoParseError(`Message size cannot be negative: ${sizeOfMessage}`)); } if (sizeOfMessage > this.bufferPool.length) { break; } const message = this.bufferPool.read(sizeOfMessage); if (!this.push(message)) { return callback(new error_1.MongoRuntimeError(`SizedMessageTransform does not support backpressure`)); } } callback(); } }; exports2.SizedMessageTransform = SizedMessageTransform; var CryptoConnection = class extends Connection { constructor(stream, options) { super(stream, options); this.autoEncrypter = options.autoEncrypter; } async command(ns, cmd, options, responseType) { const { autoEncrypter } = this; if (!autoEncrypter) { throw new error_1.MongoMissingDependencyError("No AutoEncrypter available for encryption", { dependencyName: "n/a" }); } const serverWireVersion = (0, utils_1.maxWireVersion)(this); if (serverWireVersion === 0) { return await super.command(ns, cmd, options, responseType); } if (serverWireVersion < 8) { throw new error_1.MongoCompatibilityError("Auto-encryption requires a minimum MongoDB version of 4.2"); } const sort = cmd.find || cmd.findAndModify ? cmd.sort : null; const indexKeys = cmd.createIndexes ? cmd.indexes.map((index) => index.key) : null; const encrypted = await autoEncrypter.encrypt(ns.toString(), cmd, options); if (sort != null && (cmd.find || cmd.findAndModify)) { encrypted.sort = sort; } if (indexKeys != null && cmd.createIndexes) { for (const [offset, index] of indexKeys.entries()) { encrypted.indexes[offset].key = index; } } const encryptedResponse = await super.command( ns, encrypted, options, // Eventually we want to require `responseType` which means we would satisfy `T` as the return type. // In the meantime, we want encryptedResponse to always be _at least_ a MongoDBResponse if not a more specific subclass // So that we can ensure we have access to the on-demand APIs for decorate response responseType ?? responses_1.MongoDBResponse ); const result = await autoEncrypter.decrypt(encryptedResponse.toBytes(), options); const decryptedResponse = responseType?.make(result) ?? (0, bson_1.deserialize)(result, options); if (autoEncrypter[constants_1.kDecorateResult]) { if (responseType == null) { (0, utils_1.decorateDecryptionResult)(decryptedResponse, encryptedResponse.toObject(), true); } else if (decryptedResponse instanceof responses_1.CursorResponse) { decryptedResponse.encryptedResponse = encryptedResponse; } } return decryptedResponse; } }; exports2.CryptoConnection = CryptoConnection; } }); // netlify/functions/node_modules/mongodb/lib/cmap/connect.js var require_connect = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/connect.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.LEGAL_TCP_SOCKET_OPTIONS = exports2.LEGAL_TLS_SOCKET_OPTIONS = void 0; exports2.connect = connect; exports2.makeConnection = makeConnection; exports2.performInitialHandshake = performInitialHandshake; exports2.prepareHandshakeDocument = prepareHandshakeDocument; exports2.makeSocket = makeSocket; var net = require("net"); var tls = require("tls"); var constants_1 = require_constants(); var deps_1 = require_deps(); var error_1 = require_error(); var utils_1 = require_utils(); var auth_provider_1 = require_auth_provider(); var providers_1 = require_providers(); var connection_1 = require_connection(); var constants_2 = require_constants2(); async function connect(options) { let connection = null; try { const socket = await makeSocket(options); connection = makeConnection(options, socket); await performInitialHandshake(connection, options); return connection; } catch (error) { connection?.destroy(); throw error; } } function makeConnection(options, socket) { let ConnectionType = options.connectionType ?? connection_1.Connection; if (options.autoEncrypter) { ConnectionType = connection_1.CryptoConnection; } return new ConnectionType(socket, options); } function checkSupportedServer(hello, options) { const maxWireVersion = Number(hello.maxWireVersion); const minWireVersion = Number(hello.minWireVersion); const serverVersionHighEnough = !Number.isNaN(maxWireVersion) && maxWireVersion >= constants_2.MIN_SUPPORTED_WIRE_VERSION; const serverVersionLowEnough = !Number.isNaN(minWireVersion) && minWireVersion <= constants_2.MAX_SUPPORTED_WIRE_VERSION; if (serverVersionHighEnough) { if (serverVersionLowEnough) { return null; } const message2 = `Server at ${options.hostAddress} reports minimum wire version ${JSON.stringify(hello.minWireVersion)}, but this version of the Node.js Driver requires at most ${constants_2.MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${constants_2.MAX_SUPPORTED_SERVER_VERSION})`; return new error_1.MongoCompatibilityError(message2); } const message = `Server at ${options.hostAddress} reports maximum wire version ${JSON.stringify(hello.maxWireVersion) ?? 0}, but this version of the Node.js Driver requires at least ${constants_2.MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${constants_2.MIN_SUPPORTED_SERVER_VERSION})`; return new error_1.MongoCompatibilityError(message); } async function performInitialHandshake(conn, options) { const credentials = options.credentials; if (credentials) { if (!(credentials.mechanism === providers_1.AuthMechanism.MONGODB_DEFAULT) && !options.authProviders.getOrCreateProvider(credentials.mechanism, credentials.mechanismProperties)) { throw new error_1.MongoInvalidArgumentError(`AuthMechanism '${credentials.mechanism}' not supported`); } } const authContext = new auth_provider_1.AuthContext(conn, credentials, options); conn.authContext = authContext; const handshakeDoc = await prepareHandshakeDocument(authContext); const handshakeOptions = { ...options, raw: false }; if (typeof options.connectTimeoutMS === "number") { handshakeOptions.socketTimeoutMS = options.connectTimeoutMS; } const start = (/* @__PURE__ */ new Date()).getTime(); const response = await executeHandshake(handshakeDoc, handshakeOptions); if (!("isWritablePrimary" in response)) { response.isWritablePrimary = response[constants_1.LEGACY_HELLO_COMMAND]; } if (response.helloOk) { conn.helloOk = true; } const supportedServerErr = checkSupportedServer(response, options); if (supportedServerErr) { throw supportedServerErr; } if (options.loadBalanced) { if (!response.serviceId) { throw new error_1.MongoCompatibilityError("Driver attempted to initialize in load balancing mode, but the server does not support this mode."); } } conn.hello = response; conn.lastHelloMS = (/* @__PURE__ */ new Date()).getTime() - start; if (!response.arbiterOnly && credentials) { authContext.response = response; const resolvedCredentials = credentials.resolveAuthMechanism(response); const provider = options.authProviders.getOrCreateProvider(resolvedCredentials.mechanism, resolvedCredentials.mechanismProperties); if (!provider) { throw new error_1.MongoInvalidArgumentError(`No AuthProvider for ${resolvedCredentials.mechanism} defined.`); } try { await provider.auth(authContext); } catch (error) { if (error instanceof error_1.MongoError) { error.addErrorLabel(error_1.MongoErrorLabel.HandshakeError); if ((0, error_1.needsRetryableWriteLabel)(error, response.maxWireVersion, conn.description.type)) { error.addErrorLabel(error_1.MongoErrorLabel.RetryableWriteError); } } throw error; } } conn.established = true; async function executeHandshake(handshakeDoc2, handshakeOptions2) { try { const handshakeResponse = await conn.command((0, utils_1.ns)("admin.$cmd"), handshakeDoc2, handshakeOptions2); return handshakeResponse; } catch (error) { if (error instanceof error_1.MongoError) { error.addErrorLabel(error_1.MongoErrorLabel.HandshakeError); } throw error; } } } async function prepareHandshakeDocument(authContext) { const options = authContext.options; const compressors = options.compressors ? options.compressors : []; const { serverApi } = authContext.connection; const clientMetadata = await options.extendedMetadata; const handshakeDoc = { [serverApi?.version || options.loadBalanced === true ? "hello" : constants_1.LEGACY_HELLO_COMMAND]: 1, helloOk: true, client: clientMetadata, compression: compressors }; if (options.loadBalanced === true) { handshakeDoc.loadBalanced = true; } const credentials = authContext.credentials; if (credentials) { if (credentials.mechanism === providers_1.AuthMechanism.MONGODB_DEFAULT && credentials.username) { handshakeDoc.saslSupportedMechs = `${credentials.source}.${credentials.username}`; const provider2 = authContext.options.authProviders.getOrCreateProvider(providers_1.AuthMechanism.MONGODB_SCRAM_SHA256, credentials.mechanismProperties); if (!provider2) { throw new error_1.MongoInvalidArgumentError(`No AuthProvider for ${providers_1.AuthMechanism.MONGODB_SCRAM_SHA256} defined.`); } return await provider2.prepare(handshakeDoc, authContext); } const provider = authContext.options.authProviders.getOrCreateProvider(credentials.mechanism, credentials.mechanismProperties); if (!provider) { throw new error_1.MongoInvalidArgumentError(`No AuthProvider for ${credentials.mechanism} defined.`); } return await provider.prepare(handshakeDoc, authContext); } return handshakeDoc; } exports2.LEGAL_TLS_SOCKET_OPTIONS = [ "allowPartialTrustChain", "ALPNProtocols", "ca", "cert", "checkServerIdentity", "ciphers", "crl", "ecdhCurve", "key", "minDHSize", "passphrase", "pfx", "rejectUnauthorized", "secureContext", "secureProtocol", "servername", "session" ]; exports2.LEGAL_TCP_SOCKET_OPTIONS = [ "autoSelectFamily", "autoSelectFamilyAttemptTimeout", "keepAliveInitialDelay", "family", "hints", "localAddress", "localPort", "lookup" ]; function parseConnectOptions(options) { const hostAddress = options.hostAddress; if (!hostAddress) throw new error_1.MongoInvalidArgumentError('Option "hostAddress" is required'); const result = {}; for (const name of exports2.LEGAL_TCP_SOCKET_OPTIONS) { if (options[name] != null) { result[name] = options[name]; } } result.keepAliveInitialDelay ??= 12e4; result.keepAlive = true; result.noDelay = options.noDelay ?? true; if (typeof hostAddress.socketPath === "string") { result.path = hostAddress.socketPath; return result; } else if (typeof hostAddress.host === "string") { result.host = hostAddress.host; result.port = hostAddress.port; return result; } else { throw new error_1.MongoRuntimeError(`Unexpected HostAddress ${JSON.stringify(hostAddress)}`); } } function parseSslOptions(options) { const result = parseConnectOptions(options); for (const name of exports2.LEGAL_TLS_SOCKET_OPTIONS) { if (options[name] != null) { result[name] = options[name]; } } if (options.existingSocket) { result.socket = options.existingSocket; } if (result.servername == null && result.host && !net.isIP(result.host)) { result.servername = result.host; } return result; } async function makeSocket(options) { const useTLS = options.tls ?? false; const connectTimeoutMS = options.connectTimeoutMS ?? 3e4; const existingSocket = options.existingSocket; let socket; if (options.proxyHost != null) { return await makeSocks5Connection({ ...options, connectTimeoutMS // Should always be present for Socks5 }); } if (useTLS) { const tlsSocket = tls.connect(parseSslOptions(options)); if (typeof tlsSocket.disableRenegotiation === "function") { tlsSocket.disableRenegotiation(); } socket = tlsSocket; } else if (existingSocket) { socket = existingSocket; } else { socket = net.createConnection(parseConnectOptions(options)); } socket.setTimeout(connectTimeoutMS); let cancellationHandler = null; const { promise: connectedSocket, resolve, reject } = (0, utils_1.promiseWithResolvers)(); if (existingSocket) { resolve(socket); } else { const start = performance.now(); const connectEvent = useTLS ? "secureConnect" : "connect"; socket.once(connectEvent, () => resolve(socket)).once("error", (cause) => reject(new error_1.MongoNetworkError(error_1.MongoError.buildErrorMessage(cause), { cause }))).once("timeout", () => { reject(new error_1.MongoNetworkTimeoutError(`Socket '${connectEvent}' timed out after ${performance.now() - start | 0}ms (connectTimeoutMS: ${connectTimeoutMS})`)); }).once("close", () => reject(new error_1.MongoNetworkError(`Socket closed after ${performance.now() - start | 0} during connection establishment`))); if (options.cancellationToken != null) { cancellationHandler = () => reject(new error_1.MongoNetworkError(`Socket connection establishment was cancelled after ${performance.now() - start | 0}`)); options.cancellationToken.once("cancel", cancellationHandler); } } try { socket = await connectedSocket; return socket; } catch (error) { socket.destroy(); throw error; } finally { socket.setTimeout(0); if (cancellationHandler != null) { options.cancellationToken?.removeListener("cancel", cancellationHandler); } } } var socks = null; function loadSocks() { if (socks == null) { const socksImport = (0, deps_1.getSocks)(); if ("kModuleError" in socksImport) { throw socksImport.kModuleError; } socks = socksImport; } return socks; } async function makeSocks5Connection(options) { const hostAddress = utils_1.HostAddress.fromHostPort( options.proxyHost ?? "", // proxyHost is guaranteed to set here options.proxyPort ?? 1080 ); const rawSocket = await makeSocket({ ...options, hostAddress, tls: false, proxyHost: void 0 }); const destination = parseConnectOptions(options); if (typeof destination.host !== "string" || typeof destination.port !== "number") { throw new error_1.MongoInvalidArgumentError("Can only make Socks5 connections to TCP hosts"); } socks ??= loadSocks(); let existingSocket; try { const connection = await socks.SocksClient.createConnection({ existing_socket: rawSocket, timeout: options.connectTimeoutMS, command: "connect", destination: { host: destination.host, port: destination.port }, proxy: { // host and port are ignored because we pass existing_socket host: "iLoveJavaScript", port: 0, type: 5, userId: options.proxyUsername || void 0, password: options.proxyPassword || void 0 } }); existingSocket = connection.socket; } catch (cause) { throw new error_1.MongoNetworkError(error_1.MongoError.buildErrorMessage(cause), { cause }); } return await makeSocket({ ...options, existingSocket, proxyHost: void 0 }); } } }); // netlify/functions/node_modules/mongodb/lib/sdam/events.js var require_events = __commonJS({ "netlify/functions/node_modules/mongodb/lib/sdam/events.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ServerHeartbeatFailedEvent = exports2.ServerHeartbeatSucceededEvent = exports2.ServerHeartbeatStartedEvent = exports2.TopologyClosedEvent = exports2.TopologyOpeningEvent = exports2.TopologyDescriptionChangedEvent = exports2.ServerClosedEvent = exports2.ServerOpeningEvent = exports2.ServerDescriptionChangedEvent = void 0; var constants_1 = require_constants(); var ServerDescriptionChangedEvent = class { /** @internal */ constructor(topologyId, address, previousDescription, newDescription) { this.name = constants_1.SERVER_DESCRIPTION_CHANGED; this.topologyId = topologyId; this.address = address; this.previousDescription = previousDescription; this.newDescription = newDescription; } }; exports2.ServerDescriptionChangedEvent = ServerDescriptionChangedEvent; var ServerOpeningEvent = class { /** @internal */ constructor(topologyId, address) { this.name = constants_1.SERVER_OPENING; this.topologyId = topologyId; this.address = address; } }; exports2.ServerOpeningEvent = ServerOpeningEvent; var ServerClosedEvent = class { /** @internal */ constructor(topologyId, address) { this.name = constants_1.SERVER_CLOSED; this.topologyId = topologyId; this.address = address; } }; exports2.ServerClosedEvent = ServerClosedEvent; var TopologyDescriptionChangedEvent = class { /** @internal */ constructor(topologyId, previousDescription, newDescription) { this.name = constants_1.TOPOLOGY_DESCRIPTION_CHANGED; this.topologyId = topologyId; this.previousDescription = previousDescription; this.newDescription = newDescription; } }; exports2.TopologyDescriptionChangedEvent = TopologyDescriptionChangedEvent; var TopologyOpeningEvent = class { /** @internal */ constructor(topologyId) { this.name = constants_1.TOPOLOGY_OPENING; this.topologyId = topologyId; } }; exports2.TopologyOpeningEvent = TopologyOpeningEvent; var TopologyClosedEvent = class { /** @internal */ constructor(topologyId) { this.name = constants_1.TOPOLOGY_CLOSED; this.topologyId = topologyId; } }; exports2.TopologyClosedEvent = TopologyClosedEvent; var ServerHeartbeatStartedEvent = class { /** @internal */ constructor(connectionId, awaited) { this.name = constants_1.SERVER_HEARTBEAT_STARTED; this.connectionId = connectionId; this.awaited = awaited; } }; exports2.ServerHeartbeatStartedEvent = ServerHeartbeatStartedEvent; var ServerHeartbeatSucceededEvent = class { /** @internal */ constructor(connectionId, duration, reply, awaited) { this.name = constants_1.SERVER_HEARTBEAT_SUCCEEDED; this.connectionId = connectionId; this.duration = duration; this.reply = reply ?? {}; this.awaited = awaited; } }; exports2.ServerHeartbeatSucceededEvent = ServerHeartbeatSucceededEvent; var ServerHeartbeatFailedEvent = class { /** @internal */ constructor(connectionId, duration, failure, awaited) { this.name = constants_1.SERVER_HEARTBEAT_FAILED; this.connectionId = connectionId; this.duration = duration; this.failure = failure; this.awaited = awaited; } }; exports2.ServerHeartbeatFailedEvent = ServerHeartbeatFailedEvent; } }); // netlify/functions/node_modules/mongodb/lib/cmap/connection_pool_events.js var require_connection_pool_events = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/connection_pool_events.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ConnectionPoolClearedEvent = exports2.ConnectionCheckedInEvent = exports2.ConnectionCheckedOutEvent = exports2.ConnectionCheckOutFailedEvent = exports2.ConnectionCheckOutStartedEvent = exports2.ConnectionClosedEvent = exports2.ConnectionReadyEvent = exports2.ConnectionCreatedEvent = exports2.ConnectionPoolClosedEvent = exports2.ConnectionPoolReadyEvent = exports2.ConnectionPoolCreatedEvent = exports2.ConnectionPoolMonitoringEvent = void 0; var constants_1 = require_constants(); var utils_1 = require_utils(); var ConnectionPoolMonitoringEvent = class { /** @internal */ constructor(pool) { this.time = /* @__PURE__ */ new Date(); this.address = pool.address; } }; exports2.ConnectionPoolMonitoringEvent = ConnectionPoolMonitoringEvent; var ConnectionPoolCreatedEvent = class extends ConnectionPoolMonitoringEvent { /** @internal */ constructor(pool) { super(pool); this.name = constants_1.CONNECTION_POOL_CREATED; const { maxConnecting, maxPoolSize, minPoolSize, maxIdleTimeMS, waitQueueTimeoutMS } = pool.options; this.options = { maxConnecting, maxPoolSize, minPoolSize, maxIdleTimeMS, waitQueueTimeoutMS }; } }; exports2.ConnectionPoolCreatedEvent = ConnectionPoolCreatedEvent; var ConnectionPoolReadyEvent = class extends ConnectionPoolMonitoringEvent { /** @internal */ constructor(pool) { super(pool); this.name = constants_1.CONNECTION_POOL_READY; } }; exports2.ConnectionPoolReadyEvent = ConnectionPoolReadyEvent; var ConnectionPoolClosedEvent = class extends ConnectionPoolMonitoringEvent { /** @internal */ constructor(pool) { super(pool); this.name = constants_1.CONNECTION_POOL_CLOSED; } }; exports2.ConnectionPoolClosedEvent = ConnectionPoolClosedEvent; var ConnectionCreatedEvent = class extends ConnectionPoolMonitoringEvent { /** @internal */ constructor(pool, connection) { super(pool); this.name = constants_1.CONNECTION_CREATED; this.connectionId = connection.id; } }; exports2.ConnectionCreatedEvent = ConnectionCreatedEvent; var ConnectionReadyEvent = class extends ConnectionPoolMonitoringEvent { /** @internal */ constructor(pool, connection, connectionCreatedEventTime) { super(pool); this.name = constants_1.CONNECTION_READY; this.durationMS = (0, utils_1.now)() - connectionCreatedEventTime; this.connectionId = connection.id; } }; exports2.ConnectionReadyEvent = ConnectionReadyEvent; var ConnectionClosedEvent = class extends ConnectionPoolMonitoringEvent { /** @internal */ constructor(pool, connection, reason, error) { super(pool); this.name = constants_1.CONNECTION_CLOSED; this.connectionId = connection.id; this.reason = reason; this.serviceId = connection.serviceId; this.error = error ?? null; } }; exports2.ConnectionClosedEvent = ConnectionClosedEvent; var ConnectionCheckOutStartedEvent = class extends ConnectionPoolMonitoringEvent { /** @internal */ constructor(pool) { super(pool); this.name = constants_1.CONNECTION_CHECK_OUT_STARTED; } }; exports2.ConnectionCheckOutStartedEvent = ConnectionCheckOutStartedEvent; var ConnectionCheckOutFailedEvent = class extends ConnectionPoolMonitoringEvent { /** @internal */ constructor(pool, reason, checkoutTime, error) { super(pool); this.name = constants_1.CONNECTION_CHECK_OUT_FAILED; this.durationMS = (0, utils_1.now)() - checkoutTime; this.reason = reason; this.error = error; } }; exports2.ConnectionCheckOutFailedEvent = ConnectionCheckOutFailedEvent; var ConnectionCheckedOutEvent = class extends ConnectionPoolMonitoringEvent { /** @internal */ constructor(pool, connection, checkoutTime) { super(pool); this.name = constants_1.CONNECTION_CHECKED_OUT; this.durationMS = (0, utils_1.now)() - checkoutTime; this.connectionId = connection.id; } }; exports2.ConnectionCheckedOutEvent = ConnectionCheckedOutEvent; var ConnectionCheckedInEvent = class extends ConnectionPoolMonitoringEvent { /** @internal */ constructor(pool, connection) { super(pool); this.name = constants_1.CONNECTION_CHECKED_IN; this.connectionId = connection.id; } }; exports2.ConnectionCheckedInEvent = ConnectionCheckedInEvent; var ConnectionPoolClearedEvent = class extends ConnectionPoolMonitoringEvent { /** @internal */ constructor(pool, options = {}) { super(pool); this.name = constants_1.CONNECTION_POOL_CLEARED; this.serviceId = options.serviceId; this.interruptInUseConnections = options.interruptInUseConnections; } }; exports2.ConnectionPoolClearedEvent = ConnectionPoolClearedEvent; } }); // netlify/functions/node_modules/mongodb/lib/cmap/errors.js var require_errors2 = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/errors.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.WaitQueueTimeoutError = exports2.PoolClearedOnNetworkError = exports2.PoolClearedError = exports2.PoolClosedError = void 0; var error_1 = require_error(); var PoolClosedError = class extends error_1.MongoDriverError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(pool) { super("Attempted to check out a connection from closed connection pool"); this.address = pool.address; } get name() { return "MongoPoolClosedError"; } }; exports2.PoolClosedError = PoolClosedError; var PoolClearedError = class extends error_1.MongoNetworkError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(pool, message) { const errorMessage = message ? message : `Connection pool for ${pool.address} was cleared because another operation failed with: "${pool.serverError?.message}"`; super(errorMessage, pool.serverError ? { cause: pool.serverError } : void 0); this.address = pool.address; this.addErrorLabel(error_1.MongoErrorLabel.PoolRequstedRetry); } get name() { return "MongoPoolClearedError"; } }; exports2.PoolClearedError = PoolClearedError; var PoolClearedOnNetworkError = class extends PoolClearedError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(pool) { super(pool, `Connection to ${pool.address} interrupted due to server monitor timeout`); } get name() { return "PoolClearedOnNetworkError"; } }; exports2.PoolClearedOnNetworkError = PoolClearedOnNetworkError; var WaitQueueTimeoutError = class extends error_1.MongoDriverError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(message, address) { super(message); this.address = address; } get name() { return "MongoWaitQueueTimeoutError"; } }; exports2.WaitQueueTimeoutError = WaitQueueTimeoutError; } }); // netlify/functions/node_modules/mongodb/lib/cmap/connection_pool.js var require_connection_pool = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/connection_pool.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ConnectionPool = exports2.PoolState = void 0; var timers_1 = require("timers"); var constants_1 = require_constants(); var error_1 = require_error(); var mongo_types_1 = require_mongo_types(); var timeout_1 = require_timeout(); var utils_1 = require_utils(); var connect_1 = require_connect(); var connection_1 = require_connection(); var connection_pool_events_1 = require_connection_pool_events(); var errors_1 = require_errors2(); var metrics_1 = require_metrics(); exports2.PoolState = Object.freeze({ paused: "paused", ready: "ready", closed: "closed" }); var ConnectionPool = class _ConnectionPool extends mongo_types_1.TypedEventEmitter { constructor(server, options) { super(); this.on("error", utils_1.noop); this.options = Object.freeze({ connectionType: connection_1.Connection, ...options, maxPoolSize: options.maxPoolSize ?? 100, minPoolSize: options.minPoolSize ?? 0, maxConnecting: options.maxConnecting ?? 2, maxIdleTimeMS: options.maxIdleTimeMS ?? 0, waitQueueTimeoutMS: options.waitQueueTimeoutMS ?? 0, minPoolSizeCheckFrequencyMS: options.minPoolSizeCheckFrequencyMS ?? 100, autoEncrypter: options.autoEncrypter }); if (this.options.minPoolSize > this.options.maxPoolSize) { throw new error_1.MongoInvalidArgumentError("Connection pool minimum size must not be greater than maximum pool size"); } this.poolState = exports2.PoolState.paused; this.server = server; this.connections = new utils_1.List(); this.pending = 0; this.checkedOut = /* @__PURE__ */ new Set(); this.minPoolSizeTimer = void 0; this.generation = 0; this.serviceGenerations = /* @__PURE__ */ new Map(); this.connectionCounter = (0, utils_1.makeCounter)(1); this.cancellationToken = new mongo_types_1.CancellationToken(); this.cancellationToken.setMaxListeners(Infinity); this.waitQueue = new utils_1.List(); this.metrics = new metrics_1.ConnectionPoolMetrics(); this.processingWaitQueue = false; this.mongoLogger = this.server.topology.client?.mongoLogger; this.component = "connection"; process.nextTick(() => { this.emitAndLog(_ConnectionPool.CONNECTION_POOL_CREATED, new connection_pool_events_1.ConnectionPoolCreatedEvent(this)); }); } /** The address of the endpoint the pool is connected to */ get address() { return this.options.hostAddress.toString(); } /** * Check if the pool has been closed * * TODO(NODE-3263): We can remove this property once shell no longer needs it */ get closed() { return this.poolState === exports2.PoolState.closed; } /** An integer expressing how many total connections (available + pending + in use) the pool currently has */ get totalConnectionCount() { return this.availableConnectionCount + this.pendingConnectionCount + this.currentCheckedOutCount; } /** An integer expressing how many connections are currently available in the pool. */ get availableConnectionCount() { return this.connections.length; } get pendingConnectionCount() { return this.pending; } get currentCheckedOutCount() { return this.checkedOut.size; } get waitQueueSize() { return this.waitQueue.length; } get loadBalanced() { return this.options.loadBalanced; } get serverError() { return this.server.description.error; } /** * This is exposed ONLY for use in mongosh, to enable * killing all connections if a user quits the shell with * operations in progress. * * This property may be removed as a part of NODE-3263. */ get checkedOutConnections() { return this.checkedOut; } /** * Get the metrics information for the pool when a wait queue timeout occurs. */ waitQueueErrorMetrics() { return this.metrics.info(this.options.maxPoolSize); } /** * Set the pool state to "ready" */ ready() { if (this.poolState !== exports2.PoolState.paused) { return; } this.poolState = exports2.PoolState.ready; this.emitAndLog(_ConnectionPool.CONNECTION_POOL_READY, new connection_pool_events_1.ConnectionPoolReadyEvent(this)); (0, timers_1.clearTimeout)(this.minPoolSizeTimer); this.ensureMinPoolSize(); } /** * Check a connection out of this pool. The connection will continue to be tracked, but no reference to it * will be held by the pool. This means that if a connection is checked out it MUST be checked back in or * explicitly destroyed by the new owner. */ async checkOut(options) { const checkoutTime = (0, utils_1.now)(); this.emitAndLog(_ConnectionPool.CONNECTION_CHECK_OUT_STARTED, new connection_pool_events_1.ConnectionCheckOutStartedEvent(this)); const { promise, resolve, reject } = (0, utils_1.promiseWithResolvers)(); const timeout = options.timeoutContext.connectionCheckoutTimeout; const waitQueueMember = { resolve, reject, cancelled: false, checkoutTime }; const abortListener = (0, utils_1.addAbortListener)(options.signal, function() { waitQueueMember.cancelled = true; reject(this.reason); }); this.waitQueue.push(waitQueueMember); process.nextTick(() => this.processWaitQueue()); try { timeout?.throwIfExpired(); return await (timeout ? Promise.race([promise, timeout]) : promise); } catch (error) { if (timeout_1.TimeoutError.is(error)) { timeout?.clear(); waitQueueMember.cancelled = true; this.emitAndLog(_ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, "timeout", waitQueueMember.checkoutTime)); const timeoutError = new errors_1.WaitQueueTimeoutError(this.loadBalanced ? this.waitQueueErrorMetrics() : "Timed out while checking out a connection from connection pool", this.address); if (options.timeoutContext.csotEnabled()) { throw new error_1.MongoOperationTimeoutError("Timed out during connection checkout", { cause: timeoutError }); } throw timeoutError; } throw error; } finally { abortListener?.[utils_1.kDispose](); timeout?.clear(); } } /** * Check a connection into the pool. * * @param connection - The connection to check in */ checkIn(connection) { if (!this.checkedOut.has(connection)) { return; } const poolClosed = this.closed; const stale = this.connectionIsStale(connection); const willDestroy = !!(poolClosed || stale || connection.closed); if (!willDestroy) { connection.markAvailable(); this.connections.unshift(connection); } this.checkedOut.delete(connection); this.emitAndLog(_ConnectionPool.CONNECTION_CHECKED_IN, new connection_pool_events_1.ConnectionCheckedInEvent(this, connection)); if (willDestroy) { const reason = connection.closed ? "error" : poolClosed ? "poolClosed" : "stale"; this.destroyConnection(connection, reason); } process.nextTick(() => this.processWaitQueue()); } /** * Clear the pool * * Pool reset is handled by incrementing the pool's generation count. Any existing connection of a * previous generation will eventually be pruned during subsequent checkouts. */ clear(options = {}) { if (this.closed) { return; } if (this.loadBalanced) { const { serviceId } = options; if (!serviceId) { throw new error_1.MongoRuntimeError("ConnectionPool.clear() called in load balanced mode with no serviceId."); } const sid = serviceId.toHexString(); const generation = this.serviceGenerations.get(sid); if (generation == null) { throw new error_1.MongoRuntimeError("Service generations are required in load balancer mode."); } else { this.serviceGenerations.set(sid, generation + 1); } this.emitAndLog(_ConnectionPool.CONNECTION_POOL_CLEARED, new connection_pool_events_1.ConnectionPoolClearedEvent(this, { serviceId })); return; } const interruptInUseConnections = options.interruptInUseConnections ?? false; const oldGeneration = this.generation; this.generation += 1; const alreadyPaused = this.poolState === exports2.PoolState.paused; this.poolState = exports2.PoolState.paused; this.clearMinPoolSizeTimer(); if (!alreadyPaused) { this.emitAndLog(_ConnectionPool.CONNECTION_POOL_CLEARED, new connection_pool_events_1.ConnectionPoolClearedEvent(this, { interruptInUseConnections })); } if (interruptInUseConnections) { process.nextTick(() => this.interruptInUseConnections(oldGeneration)); } this.processWaitQueue(); } /** * Closes all stale in-use connections in the pool with a resumable PoolClearedOnNetworkError. * * Only connections where `connection.generation <= minGeneration` are killed. */ interruptInUseConnections(minGeneration) { for (const connection of this.checkedOut) { if (connection.generation <= minGeneration) { connection.onError(new errors_1.PoolClearedOnNetworkError(this)); } } } /** For MongoClient.close() procedures */ closeCheckedOutConnections() { for (const conn of this.checkedOut) { conn.onError(new error_1.MongoClientClosedError()); } } /** Close the pool */ close() { if (this.closed) { return; } this.cancellationToken.emit("cancel"); if (typeof this.connectionCounter.return === "function") { this.connectionCounter.return(void 0); } this.poolState = exports2.PoolState.closed; this.clearMinPoolSizeTimer(); this.processWaitQueue(); for (const conn of this.connections) { this.emitAndLog(_ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(this, conn, "poolClosed")); conn.destroy(); } this.connections.clear(); this.emitAndLog(_ConnectionPool.CONNECTION_POOL_CLOSED, new connection_pool_events_1.ConnectionPoolClosedEvent(this)); } /** * @internal * Reauthenticate a connection */ async reauthenticate(connection) { const authContext = connection.authContext; if (!authContext) { throw new error_1.MongoRuntimeError("No auth context found on connection."); } const credentials = authContext.credentials; if (!credentials) { throw new error_1.MongoMissingCredentialsError("Connection is missing credentials when asked to reauthenticate"); } const resolvedCredentials = credentials.resolveAuthMechanism(connection.hello); const provider = this.server.topology.client.s.authProviders.getOrCreateProvider(resolvedCredentials.mechanism, resolvedCredentials.mechanismProperties); if (!provider) { throw new error_1.MongoMissingCredentialsError(`Reauthenticate failed due to no auth provider for ${credentials.mechanism}`); } await provider.reauth(authContext); return; } /** Clear the min pool size timer */ clearMinPoolSizeTimer() { const minPoolSizeTimer = this.minPoolSizeTimer; if (minPoolSizeTimer) { (0, timers_1.clearTimeout)(minPoolSizeTimer); } } destroyConnection(connection, reason) { this.emitAndLog(_ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(this, connection, reason)); connection.destroy(); } connectionIsStale(connection) { const serviceId = connection.serviceId; if (this.loadBalanced && serviceId) { const sid = serviceId.toHexString(); const generation = this.serviceGenerations.get(sid); return connection.generation !== generation; } return connection.generation !== this.generation; } connectionIsIdle(connection) { return !!(this.options.maxIdleTimeMS && connection.idleTime > this.options.maxIdleTimeMS); } /** * Destroys a connection if the connection is perished. * * @returns `true` if the connection was destroyed, `false` otherwise. */ destroyConnectionIfPerished(connection) { const isStale = this.connectionIsStale(connection); const isIdle = this.connectionIsIdle(connection); if (!isStale && !isIdle && !connection.closed) { return false; } const reason = connection.closed ? "error" : isStale ? "stale" : "idle"; this.destroyConnection(connection, reason); return true; } createConnection(callback) { const connectOptions = { ...this.options, id: this.connectionCounter.next().value, generation: this.generation, cancellationToken: this.cancellationToken, mongoLogger: this.mongoLogger, authProviders: this.server.topology.client.s.authProviders, extendedMetadata: this.server.topology.client.options.extendedMetadata }; this.pending++; const connectionCreatedTime = (0, utils_1.now)(); this.emitAndLog(_ConnectionPool.CONNECTION_CREATED, new connection_pool_events_1.ConnectionCreatedEvent(this, { id: connectOptions.id })); (0, connect_1.connect)(connectOptions).then((connection) => { if (this.poolState !== exports2.PoolState.ready) { this.pending--; connection.destroy(); callback(this.closed ? new errors_1.PoolClosedError(this) : new errors_1.PoolClearedError(this)); return; } for (const event of [...constants_1.APM_EVENTS, connection_1.Connection.CLUSTER_TIME_RECEIVED]) { connection.on(event, (e) => this.emit(event, e)); } if (this.loadBalanced) { connection.on(connection_1.Connection.PINNED, (pinType) => this.metrics.markPinned(pinType)); connection.on(connection_1.Connection.UNPINNED, (pinType) => this.metrics.markUnpinned(pinType)); const serviceId = connection.serviceId; if (serviceId) { let generation; const sid = serviceId.toHexString(); if (generation = this.serviceGenerations.get(sid)) { connection.generation = generation; } else { this.serviceGenerations.set(sid, 0); connection.generation = 0; } } } connection.markAvailable(); this.emitAndLog(_ConnectionPool.CONNECTION_READY, new connection_pool_events_1.ConnectionReadyEvent(this, connection, connectionCreatedTime)); this.pending--; callback(void 0, connection); }, (error) => { this.pending--; this.server.handleError(error); this.emitAndLog(_ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent( this, { id: connectOptions.id, serviceId: void 0 }, "error", // TODO(NODE-5192): Remove this cast error )); if (error instanceof error_1.MongoNetworkError || error instanceof error_1.MongoServerError) { error.connectionGeneration = connectOptions.generation; } callback(error ?? new error_1.MongoRuntimeError("Connection creation failed without error")); }); } ensureMinPoolSize() { const minPoolSize = this.options.minPoolSize; if (this.poolState !== exports2.PoolState.ready) { return; } this.connections.prune((connection) => this.destroyConnectionIfPerished(connection)); if (this.totalConnectionCount < minPoolSize && this.pendingConnectionCount < this.options.maxConnecting) { this.createConnection((err, connection) => { if (!err && connection) { this.connections.push(connection); process.nextTick(() => this.processWaitQueue()); } if (this.poolState === exports2.PoolState.ready) { (0, timers_1.clearTimeout)(this.minPoolSizeTimer); this.minPoolSizeTimer = (0, timers_1.setTimeout)(() => this.ensureMinPoolSize(), this.options.minPoolSizeCheckFrequencyMS); } }); } else { (0, timers_1.clearTimeout)(this.minPoolSizeTimer); this.minPoolSizeTimer = (0, timers_1.setTimeout)(() => this.ensureMinPoolSize(), this.options.minPoolSizeCheckFrequencyMS); } } processWaitQueue() { if (this.processingWaitQueue) { return; } this.processingWaitQueue = true; while (this.waitQueueSize) { const waitQueueMember = this.waitQueue.first(); if (!waitQueueMember) { this.waitQueue.shift(); continue; } if (waitQueueMember.cancelled) { this.waitQueue.shift(); continue; } if (this.poolState !== exports2.PoolState.ready) { const reason = this.closed ? "poolClosed" : "connectionError"; const error = this.closed ? new errors_1.PoolClosedError(this) : new errors_1.PoolClearedError(this); this.emitAndLog(_ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, reason, waitQueueMember.checkoutTime, error)); this.waitQueue.shift(); waitQueueMember.reject(error); continue; } if (!this.availableConnectionCount) { break; } const connection = this.connections.shift(); if (!connection) { break; } if (!this.destroyConnectionIfPerished(connection)) { this.checkedOut.add(connection); this.emitAndLog(_ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(this, connection, waitQueueMember.checkoutTime)); this.waitQueue.shift(); waitQueueMember.resolve(connection); } } const { maxPoolSize, maxConnecting } = this.options; while (this.waitQueueSize > 0 && this.pendingConnectionCount < maxConnecting && (maxPoolSize === 0 || this.totalConnectionCount < maxPoolSize)) { const waitQueueMember = this.waitQueue.shift(); if (!waitQueueMember || waitQueueMember.cancelled) { continue; } this.createConnection((err, connection) => { if (waitQueueMember.cancelled) { if (!err && connection) { this.connections.push(connection); } } else { if (err) { this.emitAndLog( _ConnectionPool.CONNECTION_CHECK_OUT_FAILED, // TODO(NODE-5192): Remove this cast new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, "connectionError", waitQueueMember.checkoutTime, err) ); waitQueueMember.reject(err); } else if (connection) { this.checkedOut.add(connection); this.emitAndLog(_ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(this, connection, waitQueueMember.checkoutTime)); waitQueueMember.resolve(connection); } } process.nextTick(() => this.processWaitQueue()); }); } this.processingWaitQueue = false; } }; exports2.ConnectionPool = ConnectionPool; ConnectionPool.CONNECTION_POOL_CREATED = constants_1.CONNECTION_POOL_CREATED; ConnectionPool.CONNECTION_POOL_CLOSED = constants_1.CONNECTION_POOL_CLOSED; ConnectionPool.CONNECTION_POOL_CLEARED = constants_1.CONNECTION_POOL_CLEARED; ConnectionPool.CONNECTION_POOL_READY = constants_1.CONNECTION_POOL_READY; ConnectionPool.CONNECTION_CREATED = constants_1.CONNECTION_CREATED; ConnectionPool.CONNECTION_READY = constants_1.CONNECTION_READY; ConnectionPool.CONNECTION_CLOSED = constants_1.CONNECTION_CLOSED; ConnectionPool.CONNECTION_CHECK_OUT_STARTED = constants_1.CONNECTION_CHECK_OUT_STARTED; ConnectionPool.CONNECTION_CHECK_OUT_FAILED = constants_1.CONNECTION_CHECK_OUT_FAILED; ConnectionPool.CONNECTION_CHECKED_OUT = constants_1.CONNECTION_CHECKED_OUT; ConnectionPool.CONNECTION_CHECKED_IN = constants_1.CONNECTION_CHECKED_IN; } }); // netlify/functions/node_modules/mongodb/lib/sdam/server.js var require_server = __commonJS({ "netlify/functions/node_modules/mongodb/lib/sdam/server.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.Server = void 0; var connection_1 = require_connection(); var connection_pool_1 = require_connection_pool(); var errors_1 = require_errors2(); var constants_1 = require_constants(); var error_1 = require_error(); var mongo_types_1 = require_mongo_types(); var transactions_1 = require_transactions(); var utils_1 = require_utils(); var write_concern_1 = require_write_concern(); var common_1 = require_common(); var monitor_1 = require_monitor(); var server_description_1 = require_server_description(); var stateTransition = (0, utils_1.makeStateMachine)({ [common_1.STATE_CLOSED]: [common_1.STATE_CLOSED, common_1.STATE_CONNECTING], [common_1.STATE_CONNECTING]: [common_1.STATE_CONNECTING, common_1.STATE_CLOSING, common_1.STATE_CONNECTED, common_1.STATE_CLOSED], [common_1.STATE_CONNECTED]: [common_1.STATE_CONNECTED, common_1.STATE_CLOSING, common_1.STATE_CLOSED], [common_1.STATE_CLOSING]: [common_1.STATE_CLOSING, common_1.STATE_CLOSED] }); var Server = class _Server extends mongo_types_1.TypedEventEmitter { /** * Create a server */ constructor(topology, description, options) { super(); this.on("error", utils_1.noop); this.serverApi = options.serverApi; const poolOptions = { hostAddress: description.hostAddress, ...options }; this.topology = topology; this.pool = new connection_pool_1.ConnectionPool(this, poolOptions); this.s = { description, options, state: common_1.STATE_CLOSED, operationCount: 0 }; for (const event of [...constants_1.CMAP_EVENTS, ...constants_1.APM_EVENTS]) { this.pool.on(event, (e) => this.emit(event, e)); } this.pool.on(connection_1.Connection.CLUSTER_TIME_RECEIVED, (clusterTime) => { this.clusterTime = clusterTime; }); if (this.loadBalanced) { this.monitor = null; return; } this.monitor = new monitor_1.Monitor(this, this.s.options); for (const event of constants_1.HEARTBEAT_EVENTS) { this.monitor.on(event, (e) => this.emit(event, e)); } this.monitor.on("resetServer", (error) => markServerUnknown(this, error)); this.monitor.on(_Server.SERVER_HEARTBEAT_SUCCEEDED, (event) => { this.emit(_Server.DESCRIPTION_RECEIVED, new server_description_1.ServerDescription(this.description.hostAddress, event.reply, { roundTripTime: this.monitor?.roundTripTime, minRoundTripTime: this.monitor?.minRoundTripTime })); if (this.s.state === common_1.STATE_CONNECTING) { stateTransition(this, common_1.STATE_CONNECTED); this.emit(_Server.CONNECT, this); } }); } get clusterTime() { return this.topology.clusterTime; } set clusterTime(clusterTime) { this.topology.clusterTime = clusterTime; } get description() { return this.s.description; } get name() { return this.s.description.address; } get autoEncrypter() { if (this.s.options && this.s.options.autoEncrypter) { return this.s.options.autoEncrypter; } return; } get loadBalanced() { return this.topology.description.type === common_1.TopologyType.LoadBalanced; } /** * Initiate server connect */ connect() { if (this.s.state !== common_1.STATE_CLOSED) { return; } stateTransition(this, common_1.STATE_CONNECTING); if (!this.loadBalanced) { this.monitor?.connect(); } else { stateTransition(this, common_1.STATE_CONNECTED); this.emit(_Server.CONNECT, this); } } closeCheckedOutConnections() { return this.pool.closeCheckedOutConnections(); } /** Destroy the server connection */ close() { if (this.s.state === common_1.STATE_CLOSED) { return; } stateTransition(this, common_1.STATE_CLOSING); if (!this.loadBalanced) { this.monitor?.close(); } this.pool.close(); stateTransition(this, common_1.STATE_CLOSED); this.emit("closed"); } /** * Immediately schedule monitoring of this server. If there already an attempt being made * this will be a no-op. */ requestCheck() { if (!this.loadBalanced) { this.monitor?.requestCheck(); } } async command(ns, cmd, { ...options }, responseType) { if (ns.db == null || typeof ns === "string") { throw new error_1.MongoInvalidArgumentError("Namespace must not be a string"); } if (this.s.state === common_1.STATE_CLOSING || this.s.state === common_1.STATE_CLOSED) { throw new error_1.MongoServerClosedError(); } options.directConnection = this.topology.s.options.directConnection; if (options.omitReadPreference) { delete options.readPreference; } if (this.description.iscryptd) { options.omitMaxTimeMS = true; } const session = options.session; let conn = session?.pinnedConnection; this.incrementOperationCount(); if (conn == null) { try { conn = await this.pool.checkOut(options); if (this.loadBalanced && isPinnableCommand(cmd, session)) { session?.pin(conn); } } catch (checkoutError) { this.decrementOperationCount(); if (!(checkoutError instanceof errors_1.PoolClearedError)) this.handleError(checkoutError); throw checkoutError; } } let reauthPromise = null; try { try { const res = await conn.command(ns, cmd, options, responseType); (0, write_concern_1.throwIfWriteConcernError)(res); return res; } catch (commandError) { throw this.decorateCommandError(conn, cmd, options, commandError); } } catch (operationError) { if (operationError instanceof error_1.MongoError && operationError.code === error_1.MONGODB_ERROR_CODES.Reauthenticate) { reauthPromise = this.pool.reauthenticate(conn); reauthPromise.then(void 0, (error) => { reauthPromise = null; (0, utils_1.squashError)(error); }); await (0, utils_1.abortable)(reauthPromise, options); reauthPromise = null; try { const res = await conn.command(ns, cmd, options, responseType); (0, write_concern_1.throwIfWriteConcernError)(res); return res; } catch (commandError) { throw this.decorateCommandError(conn, cmd, options, commandError); } } else { throw operationError; } } finally { this.decrementOperationCount(); if (session?.pinnedConnection !== conn) { if (reauthPromise != null) { const checkBackIn = () => { this.pool.checkIn(conn); }; void reauthPromise.then(checkBackIn, checkBackIn); } else { this.pool.checkIn(conn); } } } } /** * Handle SDAM error * @internal */ handleError(error, connection) { if (!(error instanceof error_1.MongoError)) { return; } const isStaleError = error.connectionGeneration && error.connectionGeneration < this.pool.generation; if (isStaleError) { return; } const isNetworkNonTimeoutError = error instanceof error_1.MongoNetworkError && !(error instanceof error_1.MongoNetworkTimeoutError); const isNetworkTimeoutBeforeHandshakeError = error instanceof error_1.MongoNetworkError && error.beforeHandshake; const isAuthHandshakeError = error.hasErrorLabel(error_1.MongoErrorLabel.HandshakeError); if (isNetworkNonTimeoutError || isNetworkTimeoutBeforeHandshakeError || isAuthHandshakeError) { if (!this.loadBalanced) { error.addErrorLabel(error_1.MongoErrorLabel.ResetPool); markServerUnknown(this, error); } else if (connection) { this.pool.clear({ serviceId: connection.serviceId }); } } else { if ((0, error_1.isSDAMUnrecoverableError)(error)) { if (shouldHandleStateChangeError(this, error)) { const shouldClearPool = (0, utils_1.maxWireVersion)(this) <= 7 || (0, error_1.isNodeShuttingDownError)(error); if (this.loadBalanced && connection && shouldClearPool) { this.pool.clear({ serviceId: connection.serviceId }); } if (!this.loadBalanced) { if (shouldClearPool) { error.addErrorLabel(error_1.MongoErrorLabel.ResetPool); } markServerUnknown(this, error); process.nextTick(() => this.requestCheck()); } } } } } /** * Ensure that error is properly decorated and internal state is updated before throwing * @internal */ decorateCommandError(connection, cmd, options, error) { if (typeof error !== "object" || error == null || !("name" in error)) { throw new error_1.MongoRuntimeError("An unexpected error type: " + typeof error); } if (error.name === "AbortError" && "cause" in error && error.cause instanceof error_1.MongoError) { error = error.cause; } if (!(error instanceof error_1.MongoError)) { return error; } if (connectionIsStale(this.pool, connection)) { return error; } const session = options?.session; if (error instanceof error_1.MongoNetworkError) { if (session && !session.hasEnded && session.serverSession) { session.serverSession.isDirty = true; } if (inActiveTransaction(session, cmd) && !error.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) { error.addErrorLabel(error_1.MongoErrorLabel.TransientTransactionError); } if ((isRetryableWritesEnabled(this.topology) || (0, transactions_1.isTransactionCommand)(cmd)) && (0, utils_1.supportsRetryableWrites)(this) && !inActiveTransaction(session, cmd)) { error.addErrorLabel(error_1.MongoErrorLabel.RetryableWriteError); } } else { if ((isRetryableWritesEnabled(this.topology) || (0, transactions_1.isTransactionCommand)(cmd)) && (0, error_1.needsRetryableWriteLabel)(error, (0, utils_1.maxWireVersion)(this), this.description.type) && !inActiveTransaction(session, cmd)) { error.addErrorLabel(error_1.MongoErrorLabel.RetryableWriteError); } } if (session && session.isPinned && error.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) { session.unpin({ force: true }); } this.handleError(error, connection); return error; } /** * Decrement the operation count, returning the new count. */ decrementOperationCount() { return this.s.operationCount -= 1; } /** * Increment the operation count, returning the new count. */ incrementOperationCount() { return this.s.operationCount += 1; } }; exports2.Server = Server; Server.SERVER_HEARTBEAT_STARTED = constants_1.SERVER_HEARTBEAT_STARTED; Server.SERVER_HEARTBEAT_SUCCEEDED = constants_1.SERVER_HEARTBEAT_SUCCEEDED; Server.SERVER_HEARTBEAT_FAILED = constants_1.SERVER_HEARTBEAT_FAILED; Server.CONNECT = constants_1.CONNECT; Server.DESCRIPTION_RECEIVED = constants_1.DESCRIPTION_RECEIVED; Server.CLOSED = constants_1.CLOSED; Server.ENDED = constants_1.ENDED; function markServerUnknown(server, error) { if (server.loadBalanced) { return; } if (error instanceof error_1.MongoNetworkError && !(error instanceof error_1.MongoNetworkTimeoutError)) { server.monitor?.reset(); } server.emit(Server.DESCRIPTION_RECEIVED, new server_description_1.ServerDescription(server.description.hostAddress, void 0, { error })); } function isPinnableCommand(cmd, session) { if (session) { return session.inTransaction() || session.transaction.isCommitted && "commitTransaction" in cmd || "aggregate" in cmd || "find" in cmd || "getMore" in cmd || "listCollections" in cmd || "listIndexes" in cmd || "bulkWrite" in cmd; } return false; } function connectionIsStale(pool, connection) { if (connection.serviceId) { return connection.generation !== pool.serviceGenerations.get(connection.serviceId.toHexString()); } return connection.generation !== pool.generation; } function shouldHandleStateChangeError(server, err) { const etv = err.topologyVersion; const stv = server.description.topologyVersion; return (0, server_description_1.compareTopologyVersion)(stv, etv) < 0; } function inActiveTransaction(session, cmd) { return session && session.inTransaction() && !(0, transactions_1.isTransactionCommand)(cmd); } function isRetryableWritesEnabled(topology) { return topology.s.options.retryWrites !== false; } } }); // netlify/functions/node_modules/mongodb/lib/sdam/monitor.js var require_monitor = __commonJS({ "netlify/functions/node_modules/mongodb/lib/sdam/monitor.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.RTTSampler = exports2.MonitorInterval = exports2.RTTPinger = exports2.Monitor = exports2.ServerMonitoringMode = void 0; var timers_1 = require("timers"); var bson_1 = require_bson2(); var connect_1 = require_connect(); var client_metadata_1 = require_client_metadata(); var constants_1 = require_constants(); var error_1 = require_error(); var mongo_logger_1 = require_mongo_logger(); var mongo_types_1 = require_mongo_types(); var utils_1 = require_utils(); var common_1 = require_common(); var events_1 = require_events(); var server_1 = require_server(); var STATE_IDLE = "idle"; var STATE_MONITORING = "monitoring"; var stateTransition = (0, utils_1.makeStateMachine)({ [common_1.STATE_CLOSING]: [common_1.STATE_CLOSING, STATE_IDLE, common_1.STATE_CLOSED], [common_1.STATE_CLOSED]: [common_1.STATE_CLOSED, STATE_MONITORING], [STATE_IDLE]: [STATE_IDLE, STATE_MONITORING, common_1.STATE_CLOSING], [STATE_MONITORING]: [STATE_MONITORING, STATE_IDLE, common_1.STATE_CLOSING] }); var INVALID_REQUEST_CHECK_STATES = /* @__PURE__ */ new Set([common_1.STATE_CLOSING, common_1.STATE_CLOSED, STATE_MONITORING]); function isInCloseState(monitor) { return monitor.s.state === common_1.STATE_CLOSED || monitor.s.state === common_1.STATE_CLOSING; } exports2.ServerMonitoringMode = Object.freeze({ auto: "auto", poll: "poll", stream: "stream" }); var Monitor = class extends mongo_types_1.TypedEventEmitter { constructor(server, options) { super(); this.component = mongo_logger_1.MongoLoggableComponent.TOPOLOGY; this.on("error", utils_1.noop); this.server = server; this.connection = null; this.cancellationToken = new mongo_types_1.CancellationToken(); this.cancellationToken.setMaxListeners(Infinity); this.monitorId = void 0; this.s = { state: common_1.STATE_CLOSED }; this.address = server.description.address; this.options = Object.freeze({ connectTimeoutMS: options.connectTimeoutMS ?? 1e4, heartbeatFrequencyMS: options.heartbeatFrequencyMS ?? 1e4, minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS ?? 500, serverMonitoringMode: options.serverMonitoringMode }); this.isRunningInFaasEnv = (0, client_metadata_1.getFAASEnv)() != null; this.mongoLogger = this.server.topology.client?.mongoLogger; this.rttSampler = new RTTSampler(10); const cancellationToken = this.cancellationToken; const connectOptions = { id: "", generation: server.pool.generation, cancellationToken, hostAddress: server.description.hostAddress, ...options, // force BSON serialization options raw: false, useBigInt64: false, promoteLongs: true, promoteValues: true, promoteBuffers: true }; delete connectOptions.credentials; if (connectOptions.autoEncrypter) { delete connectOptions.autoEncrypter; } this.connectOptions = Object.freeze(connectOptions); } connect() { if (this.s.state !== common_1.STATE_CLOSED) { return; } const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; this.monitorId = new MonitorInterval(monitorServer(this), { heartbeatFrequencyMS, minHeartbeatFrequencyMS, immediate: true }); } requestCheck() { if (INVALID_REQUEST_CHECK_STATES.has(this.s.state)) { return; } this.monitorId?.wake(); } reset() { const topologyVersion = this.server.description.topologyVersion; if (isInCloseState(this) || topologyVersion == null) { return; } stateTransition(this, common_1.STATE_CLOSING); resetMonitorState(this); stateTransition(this, STATE_IDLE); const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; this.monitorId = new MonitorInterval(monitorServer(this), { heartbeatFrequencyMS, minHeartbeatFrequencyMS }); } close() { if (isInCloseState(this)) { return; } stateTransition(this, common_1.STATE_CLOSING); resetMonitorState(this); this.emit("close"); stateTransition(this, common_1.STATE_CLOSED); } get roundTripTime() { return this.rttSampler.average(); } get minRoundTripTime() { return this.rttSampler.min(); } get latestRtt() { return this.rttSampler.last; } addRttSample(rtt) { this.rttSampler.addSample(rtt); } clearRttSamples() { this.rttSampler.clear(); } }; exports2.Monitor = Monitor; function resetMonitorState(monitor) { monitor.monitorId?.stop(); monitor.monitorId = void 0; monitor.rttPinger?.close(); monitor.rttPinger = void 0; monitor.cancellationToken.emit("cancel"); monitor.connection?.destroy(); monitor.connection = null; monitor.clearRttSamples(); } function useStreamingProtocol(monitor, topologyVersion) { if (topologyVersion == null) return false; const serverMonitoringMode = monitor.options.serverMonitoringMode; if (serverMonitoringMode === exports2.ServerMonitoringMode.poll) return false; if (serverMonitoringMode === exports2.ServerMonitoringMode.stream) return true; if (monitor.isRunningInFaasEnv) return false; return true; } function checkServer(monitor, callback) { let start; let awaited; const topologyVersion = monitor.server.description.topologyVersion; const isAwaitable = useStreamingProtocol(monitor, topologyVersion); monitor.emitAndLogHeartbeat(server_1.Server.SERVER_HEARTBEAT_STARTED, monitor.server.topology.s.id, void 0, new events_1.ServerHeartbeatStartedEvent(monitor.address, isAwaitable)); function onHeartbeatFailed(err) { monitor.connection?.destroy(); monitor.connection = null; monitor.emitAndLogHeartbeat(server_1.Server.SERVER_HEARTBEAT_FAILED, monitor.server.topology.s.id, void 0, new events_1.ServerHeartbeatFailedEvent(monitor.address, (0, utils_1.calculateDurationInMs)(start), err, awaited)); const error = !(err instanceof error_1.MongoError) ? new error_1.MongoError(error_1.MongoError.buildErrorMessage(err), { cause: err }) : err; error.addErrorLabel(error_1.MongoErrorLabel.ResetPool); if (error instanceof error_1.MongoNetworkTimeoutError) { error.addErrorLabel(error_1.MongoErrorLabel.InterruptInUseConnections); } monitor.emit("resetServer", error); callback(err); } function onHeartbeatSucceeded(hello) { if (!("isWritablePrimary" in hello)) { hello.isWritablePrimary = hello[constants_1.LEGACY_HELLO_COMMAND]; } const duration = isAwaitable && monitor.rttPinger ? monitor.rttPinger.latestRtt ?? (0, utils_1.calculateDurationInMs)(start) : (0, utils_1.calculateDurationInMs)(start); monitor.addRttSample(duration); monitor.emitAndLogHeartbeat(server_1.Server.SERVER_HEARTBEAT_SUCCEEDED, monitor.server.topology.s.id, hello.connectionId, new events_1.ServerHeartbeatSucceededEvent(monitor.address, duration, hello, isAwaitable)); if (isAwaitable) { monitor.emitAndLogHeartbeat(server_1.Server.SERVER_HEARTBEAT_STARTED, monitor.server.topology.s.id, void 0, new events_1.ServerHeartbeatStartedEvent(monitor.address, true)); start = (0, utils_1.now)(); } else { monitor.rttPinger?.close(); monitor.rttPinger = void 0; callback(void 0, hello); } } const { connection } = monitor; if (connection && !connection.closed) { const { serverApi, helloOk } = connection; const connectTimeoutMS = monitor.options.connectTimeoutMS; const maxAwaitTimeMS = monitor.options.heartbeatFrequencyMS; const cmd = { [serverApi?.version || helloOk ? "hello" : constants_1.LEGACY_HELLO_COMMAND]: 1, ...isAwaitable && topologyVersion ? { maxAwaitTimeMS, topologyVersion: makeTopologyVersion(topologyVersion) } : {} }; const options = isAwaitable ? { socketTimeoutMS: connectTimeoutMS ? connectTimeoutMS + maxAwaitTimeMS : 0, exhaustAllowed: true } : { socketTimeoutMS: connectTimeoutMS }; if (isAwaitable && monitor.rttPinger == null) { monitor.rttPinger = new RTTPinger(monitor); } start = (0, utils_1.now)(); if (isAwaitable) { awaited = true; return connection.exhaustCommand((0, utils_1.ns)("admin.$cmd"), cmd, options, (error, hello) => { if (error) return onHeartbeatFailed(error); return onHeartbeatSucceeded(hello); }); } awaited = false; connection.command((0, utils_1.ns)("admin.$cmd"), cmd, options).then(onHeartbeatSucceeded, onHeartbeatFailed); return; } (async () => { const socket = await (0, connect_1.makeSocket)(monitor.connectOptions); const connection2 = (0, connect_1.makeConnection)(monitor.connectOptions, socket); start = (0, utils_1.now)(); try { await (0, connect_1.performInitialHandshake)(connection2, monitor.connectOptions); return connection2; } catch (error) { connection2.destroy(); throw error; } })().then((connection2) => { if (isInCloseState(monitor)) { connection2.destroy(); return; } const duration = (0, utils_1.calculateDurationInMs)(start); monitor.addRttSample(duration); monitor.connection = connection2; monitor.emitAndLogHeartbeat(server_1.Server.SERVER_HEARTBEAT_SUCCEEDED, monitor.server.topology.s.id, connection2.hello?.connectionId, new events_1.ServerHeartbeatSucceededEvent(monitor.address, duration, connection2.hello, useStreamingProtocol(monitor, connection2.hello?.topologyVersion))); callback(void 0, connection2.hello); }, (error) => { monitor.connection = null; awaited = false; onHeartbeatFailed(error); }); } function monitorServer(monitor) { return (callback) => { if (monitor.s.state === STATE_MONITORING) { process.nextTick(callback); return; } stateTransition(monitor, STATE_MONITORING); function done() { if (!isInCloseState(monitor)) { stateTransition(monitor, STATE_IDLE); } callback(); } checkServer(monitor, (err, hello) => { if (err) { if (monitor.server.description.type === common_1.ServerType.Unknown) { return done(); } } if (useStreamingProtocol(monitor, hello?.topologyVersion)) { (0, timers_1.setTimeout)(() => { if (!isInCloseState(monitor)) { monitor.monitorId?.wake(); } }, 0); } done(); }); }; } function makeTopologyVersion(tv) { return { processId: tv.processId, // tests mock counter as just number, but in a real situation counter should always be a Long // TODO(NODE-2674): Preserve int64 sent from MongoDB counter: bson_1.Long.isLong(tv.counter) ? tv.counter : bson_1.Long.fromNumber(tv.counter) }; } var RTTPinger = class { constructor(monitor) { this.connection = void 0; this.cancellationToken = monitor.cancellationToken; this.closed = false; this.monitor = monitor; this.latestRtt = monitor.latestRtt ?? void 0; const heartbeatFrequencyMS = monitor.options.heartbeatFrequencyMS; this.monitorId = (0, timers_1.setTimeout)(() => this.measureRoundTripTime(), heartbeatFrequencyMS); } get roundTripTime() { return this.monitor.roundTripTime; } get minRoundTripTime() { return this.monitor.minRoundTripTime; } close() { this.closed = true; (0, timers_1.clearTimeout)(this.monitorId); this.connection?.destroy(); this.connection = void 0; } measureAndReschedule(start, conn) { if (this.closed) { conn?.destroy(); return; } if (this.connection == null) { this.connection = conn; } this.latestRtt = (0, utils_1.calculateDurationInMs)(start); this.monitorId = (0, timers_1.setTimeout)(() => this.measureRoundTripTime(), this.monitor.options.heartbeatFrequencyMS); } measureRoundTripTime() { const start = (0, utils_1.now)(); if (this.closed) { return; } const connection = this.connection; if (connection == null) { (0, connect_1.connect)(this.monitor.connectOptions).then((connection2) => { this.measureAndReschedule(start, connection2); }, () => { this.connection = void 0; }); return; } const commandName = connection.serverApi?.version || connection.helloOk ? "hello" : constants_1.LEGACY_HELLO_COMMAND; connection.command((0, utils_1.ns)("admin.$cmd"), { [commandName]: 1 }, void 0).then(() => this.measureAndReschedule(start), () => { this.connection?.destroy(); this.connection = void 0; return; }); } }; exports2.RTTPinger = RTTPinger; var MonitorInterval = class { constructor(fn, options = {}) { this.isExpeditedCallToFnScheduled = false; this.stopped = false; this.isExecutionInProgress = false; this.hasExecutedOnce = false; this._executeAndReschedule = () => { if (this.stopped) return; if (this.timerId) { (0, timers_1.clearTimeout)(this.timerId); } this.isExpeditedCallToFnScheduled = false; this.isExecutionInProgress = true; this.fn(() => { this.lastExecutionEnded = (0, utils_1.now)(); this.isExecutionInProgress = false; this._reschedule(this.heartbeatFrequencyMS); }); }; this.fn = fn; this.lastExecutionEnded = -Infinity; this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 1e3; this.minHeartbeatFrequencyMS = options.minHeartbeatFrequencyMS ?? 500; if (options.immediate) { this._executeAndReschedule(); } else { this._reschedule(void 0); } } wake() { const currentTime = (0, utils_1.now)(); const timeSinceLastCall = currentTime - this.lastExecutionEnded; if (timeSinceLastCall < 0) { return this._executeAndReschedule(); } if (this.isExecutionInProgress) { return; } if (this.isExpeditedCallToFnScheduled) { return; } if (timeSinceLastCall < this.minHeartbeatFrequencyMS) { this.isExpeditedCallToFnScheduled = true; this._reschedule(this.minHeartbeatFrequencyMS - timeSinceLastCall); return; } this._executeAndReschedule(); } stop() { this.stopped = true; if (this.timerId) { (0, timers_1.clearTimeout)(this.timerId); this.timerId = void 0; } this.lastExecutionEnded = -Infinity; this.isExpeditedCallToFnScheduled = false; } toString() { return JSON.stringify(this); } toJSON() { const currentTime = (0, utils_1.now)(); const timeSinceLastCall = currentTime - this.lastExecutionEnded; return { timerId: this.timerId != null ? "set" : "cleared", lastCallTime: this.lastExecutionEnded, isExpeditedCheckScheduled: this.isExpeditedCallToFnScheduled, stopped: this.stopped, heartbeatFrequencyMS: this.heartbeatFrequencyMS, minHeartbeatFrequencyMS: this.minHeartbeatFrequencyMS, currentTime, timeSinceLastCall }; } _reschedule(ms) { if (this.stopped) return; if (this.timerId) { (0, timers_1.clearTimeout)(this.timerId); } this.timerId = (0, timers_1.setTimeout)(this._executeAndReschedule, ms || this.heartbeatFrequencyMS); } }; exports2.MonitorInterval = MonitorInterval; var RTTSampler = class { constructor(windowSize = 10) { this.rttSamples = new Float64Array(windowSize); this.length = 0; this.writeIndex = 0; } /** * Adds an rtt sample to the end of the circular buffer * When `windowSize` samples have been collected, `addSample` overwrites the least recently added * sample */ addSample(sample) { this.rttSamples[this.writeIndex++] = sample; if (this.length < this.rttSamples.length) { this.length++; } this.writeIndex %= this.rttSamples.length; } /** * When \< 2 samples have been collected, returns 0 * Otherwise computes the minimum value samples contained in the buffer */ min() { if (this.length < 2) return 0; let min = this.rttSamples[0]; for (let i = 1; i < this.length; i++) { if (this.rttSamples[i] < min) min = this.rttSamples[i]; } return min; } /** * Returns mean of samples contained in the buffer */ average() { if (this.length === 0) return 0; let sum = 0; for (let i = 0; i < this.length; i++) { sum += this.rttSamples[i]; } return sum / this.length; } /** * Returns most recently inserted element in the buffer * Returns null if the buffer is empty * */ get last() { if (this.length === 0) return null; return this.rttSamples[this.writeIndex === 0 ? this.length - 1 : this.writeIndex - 1]; } /** * Clear the buffer * NOTE: this does not overwrite the data held in the internal array, just the pointers into * this array */ clear() { this.length = 0; this.writeIndex = 0; } }; exports2.RTTSampler = RTTSampler; } }); // netlify/functions/node_modules/mongodb/lib/connection_string.js var require_connection_string = __commonJS({ "netlify/functions/node_modules/mongodb/lib/connection_string.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.DEFAULT_OPTIONS = exports2.OPTIONS = void 0; exports2.resolveSRVRecord = resolveSRVRecord; exports2.parseOptions = parseOptions; var dns = require("dns"); var mongodb_connection_string_url_1 = require_lib2(); var url_1 = require("url"); var mongo_credentials_1 = require_mongo_credentials(); var providers_1 = require_providers(); var client_metadata_1 = require_client_metadata(); var compression_1 = require_compression(); var encrypter_1 = require_encrypter(); var error_1 = require_error(); var mongo_client_1 = require_mongo_client(); var mongo_logger_1 = require_mongo_logger(); var read_concern_1 = require_read_concern(); var read_preference_1 = require_read_preference(); var monitor_1 = require_monitor(); var utils_1 = require_utils(); var write_concern_1 = require_write_concern(); var VALID_TXT_RECORDS = ["authSource", "replicaSet", "loadBalanced"]; var LB_SINGLE_HOST_ERROR = "loadBalanced option only supported with a single host in the URI"; var LB_REPLICA_SET_ERROR = "loadBalanced option not supported with a replicaSet option"; var LB_DIRECT_CONNECTION_ERROR = "loadBalanced option not supported when directConnection is provided"; function retryDNSTimeoutFor(api) { return async function dnsReqRetryTimeout(lookupAddress) { try { return await dns.promises[api](lookupAddress); } catch (firstDNSError) { if (firstDNSError.code === dns.TIMEOUT) { return await dns.promises[api](lookupAddress); } else { throw firstDNSError; } } }; } var resolveSrv = retryDNSTimeoutFor("resolveSrv"); var resolveTxt = retryDNSTimeoutFor("resolveTxt"); async function resolveSRVRecord(options) { if (typeof options.srvHost !== "string") { throw new error_1.MongoAPIError('Option "srvHost" must not be empty'); } const lookupAddress = options.srvHost; const txtResolutionPromise = resolveTxt(lookupAddress); txtResolutionPromise.then(void 0, utils_1.squashError); const hostname = `_${options.srvServiceName}._tcp.${lookupAddress}`; const addresses = await resolveSrv(hostname); if (addresses.length === 0) { throw new error_1.MongoAPIError("No addresses found at host"); } for (const { name } of addresses) { (0, utils_1.checkParentDomainMatch)(name, lookupAddress); } const hostAddresses = addresses.map((r) => utils_1.HostAddress.fromString(`${r.name}:${r.port ?? 27017}`)); validateLoadBalancedOptions(hostAddresses, options, true); let record; try { record = await txtResolutionPromise; } catch (error) { if (error.code !== "ENODATA" && error.code !== "ENOTFOUND") { throw error; } return hostAddresses; } if (record.length > 1) { throw new error_1.MongoParseError("Multiple text records not allowed"); } const txtRecordOptions = new url_1.URLSearchParams(record[0].join("")); const txtRecordOptionKeys = [...txtRecordOptions.keys()]; if (txtRecordOptionKeys.some((key) => !VALID_TXT_RECORDS.includes(key))) { throw new error_1.MongoParseError(`Text record may only set any of: ${VALID_TXT_RECORDS.join(", ")}`); } if (VALID_TXT_RECORDS.some((option) => txtRecordOptions.get(option) === "")) { throw new error_1.MongoParseError("Cannot have empty URI params in DNS TXT Record"); } const source = txtRecordOptions.get("authSource") ?? void 0; const replicaSet = txtRecordOptions.get("replicaSet") ?? void 0; const loadBalanced = txtRecordOptions.get("loadBalanced") ?? void 0; if (!options.userSpecifiedAuthSource && source && options.credentials && !providers_1.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(options.credentials.mechanism)) { options.credentials = mongo_credentials_1.MongoCredentials.merge(options.credentials, { source }); } if (!options.userSpecifiedReplicaSet && replicaSet) { options.replicaSet = replicaSet; } if (loadBalanced === "true") { options.loadBalanced = true; } if (options.replicaSet && options.srvMaxHosts > 0) { throw new error_1.MongoParseError("Cannot combine replicaSet option with srvMaxHosts"); } validateLoadBalancedOptions(hostAddresses, options, true); return hostAddresses; } function checkTLSOptions(allOptions) { if (!allOptions) return; const check = (a, b) => { if (allOptions.has(a) && allOptions.has(b)) { throw new error_1.MongoAPIError(`The '${a}' option cannot be used with the '${b}' option`); } }; check("tlsInsecure", "tlsAllowInvalidCertificates"); check("tlsInsecure", "tlsAllowInvalidHostnames"); } function getBoolean(name, value) { if (typeof value === "boolean") return value; switch (value) { case "true": return true; case "false": return false; default: throw new error_1.MongoParseError(`${name} must be either "true" or "false"`); } } function getIntFromOptions(name, value) { const parsedInt = (0, utils_1.parseInteger)(value); if (parsedInt != null) { return parsedInt; } throw new error_1.MongoParseError(`Expected ${name} to be stringified int value, got: ${value}`); } function getUIntFromOptions(name, value) { const parsedValue = getIntFromOptions(name, value); if (parsedValue < 0) { throw new error_1.MongoParseError(`${name} can only be a positive int value, got: ${value}`); } return parsedValue; } function* entriesFromString(value) { if (value === "") { return; } const keyValuePairs = value.split(","); for (const keyValue of keyValuePairs) { const [key, value2] = keyValue.split(/:(.*)/); if (value2 == null) { throw new error_1.MongoParseError("Cannot have undefined values in key value pairs"); } yield [key, value2]; } } var CaseInsensitiveMap = class extends Map { constructor(entries = []) { super(entries.map(([k, v]) => [k.toLowerCase(), v])); } has(k) { return super.has(k.toLowerCase()); } get(k) { return super.get(k.toLowerCase()); } set(k, v) { return super.set(k.toLowerCase(), v); } delete(k) { return super.delete(k.toLowerCase()); } }; function parseOptions(uri, mongoClient = void 0, options = {}) { if (mongoClient != null && !(mongoClient instanceof mongo_client_1.MongoClient)) { options = mongoClient; mongoClient = void 0; } if (options.useBigInt64 && typeof options.promoteLongs === "boolean" && !options.promoteLongs) { throw new error_1.MongoAPIError("Must request either bigint or Long for int64 deserialization"); } if (options.useBigInt64 && typeof options.promoteValues === "boolean" && !options.promoteValues) { throw new error_1.MongoAPIError("Must request either bigint or Long for int64 deserialization"); } const url = new mongodb_connection_string_url_1.default(uri); const { hosts, isSRV } = url; const mongoOptions = /* @__PURE__ */ Object.create(null); mongoOptions.hosts = isSRV ? [] : hosts.map(utils_1.HostAddress.fromString); const urlOptions = new CaseInsensitiveMap(); if (url.pathname !== "/" && url.pathname !== "") { const dbName = decodeURIComponent(url.pathname[0] === "/" ? url.pathname.slice(1) : url.pathname); if (dbName) { urlOptions.set("dbName", [dbName]); } } if (url.username !== "") { const auth = { username: decodeURIComponent(url.username) }; if (typeof url.password === "string") { auth.password = decodeURIComponent(url.password); } urlOptions.set("auth", [auth]); } for (const key of url.searchParams.keys()) { const values = url.searchParams.getAll(key); const isReadPreferenceTags = /readPreferenceTags/i.test(key); if (!isReadPreferenceTags && values.length > 1) { throw new error_1.MongoInvalidArgumentError(`URI option "${key}" cannot appear more than once in the connection string`); } if (!isReadPreferenceTags && values.includes("")) { throw new error_1.MongoAPIError(`URI option "${key}" cannot be specified with no value`); } if (!urlOptions.has(key)) { urlOptions.set(key, values); } } const objectOptions = new CaseInsensitiveMap(Object.entries(options).filter(([, v]) => v != null)); if (urlOptions.has("serverApi")) { throw new error_1.MongoParseError("URI cannot contain `serverApi`, it can only be passed to the client"); } const uriMechanismProperties = urlOptions.get("authMechanismProperties"); if (uriMechanismProperties) { for (const property of uriMechanismProperties) { if (/(^|,)ALLOWED_HOSTS:/.test(property)) { throw new error_1.MongoParseError("Auth mechanism property ALLOWED_HOSTS is not allowed in the connection string."); } } } if (objectOptions.has("loadBalanced")) { throw new error_1.MongoParseError("loadBalanced is only a valid option in the URI"); } const allProvidedOptions = new CaseInsensitiveMap(); const allProvidedKeys = /* @__PURE__ */ new Set([...urlOptions.keys(), ...objectOptions.keys()]); for (const key of allProvidedKeys) { const values = []; const objectOptionValue = objectOptions.get(key); if (objectOptionValue != null) { values.push(objectOptionValue); } const urlValues = urlOptions.get(key) ?? []; values.push(...urlValues); allProvidedOptions.set(key, values); } if (allProvidedOptions.has("tls") || allProvidedOptions.has("ssl")) { const tlsAndSslOpts = (allProvidedOptions.get("tls") || []).concat(allProvidedOptions.get("ssl") || []).map(getBoolean.bind(null, "tls/ssl")); if (new Set(tlsAndSslOpts).size !== 1) { throw new error_1.MongoParseError("All values of tls/ssl must be the same."); } } checkTLSOptions(allProvidedOptions); const unsupportedOptions = (0, utils_1.setDifference)(allProvidedKeys, Array.from(Object.keys(exports2.OPTIONS)).map((s) => s.toLowerCase())); if (unsupportedOptions.size !== 0) { const optionWord = unsupportedOptions.size > 1 ? "options" : "option"; const isOrAre = unsupportedOptions.size > 1 ? "are" : "is"; throw new error_1.MongoParseError(`${optionWord} ${Array.from(unsupportedOptions).join(", ")} ${isOrAre} not supported`); } for (const [key, descriptor] of Object.entries(exports2.OPTIONS)) { const values = allProvidedOptions.get(key); if (!values || values.length === 0) { if (exports2.DEFAULT_OPTIONS.has(key)) { setOption(mongoOptions, key, descriptor, [exports2.DEFAULT_OPTIONS.get(key)]); } } else { const { deprecated } = descriptor; if (deprecated) { const deprecatedMsg = typeof deprecated === "string" ? `: ${deprecated}` : ""; (0, utils_1.emitWarning)(`${key} is a deprecated option${deprecatedMsg}`); } setOption(mongoOptions, key, descriptor, values); } } if (mongoOptions.credentials) { const isGssapi = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_GSSAPI; const isX509 = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_X509; const isAws = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_AWS; const isOidc = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_OIDC; if ((isGssapi || isX509) && allProvidedOptions.has("authSource") && mongoOptions.credentials.source !== "$external") { throw new error_1.MongoParseError(`authMechanism ${mongoOptions.credentials.mechanism} requires an authSource of '$external'`); } if (!(isGssapi || isX509 || isAws || isOidc) && mongoOptions.dbName && !allProvidedOptions.has("authSource")) { mongoOptions.credentials = mongo_credentials_1.MongoCredentials.merge(mongoOptions.credentials, { source: mongoOptions.dbName }); } if (isAws && mongoOptions.credentials.username && !mongoOptions.credentials.password) { throw new error_1.MongoMissingCredentialsError(`When using ${mongoOptions.credentials.mechanism} password must be set when a username is specified`); } mongoOptions.credentials.validate(); if (mongoOptions.credentials.password === "" && mongoOptions.credentials.username === "" && mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_DEFAULT && Object.keys(mongoOptions.credentials.mechanismProperties).length === 0) { delete mongoOptions.credentials; } } if (!mongoOptions.dbName) { mongoOptions.dbName = "test"; } validateLoadBalancedOptions(hosts, mongoOptions, isSRV); if (mongoClient && mongoOptions.autoEncryption) { encrypter_1.Encrypter.checkForMongoCrypt(); mongoOptions.encrypter = new encrypter_1.Encrypter(mongoClient, uri, options); mongoOptions.autoEncrypter = mongoOptions.encrypter.autoEncrypter; } mongoOptions.userSpecifiedAuthSource = objectOptions.has("authSource") || urlOptions.has("authSource"); mongoOptions.userSpecifiedReplicaSet = objectOptions.has("replicaSet") || urlOptions.has("replicaSet"); if (isSRV) { mongoOptions.srvHost = hosts[0]; if (mongoOptions.directConnection) { throw new error_1.MongoAPIError("SRV URI does not support directConnection"); } if (mongoOptions.srvMaxHosts > 0 && typeof mongoOptions.replicaSet === "string") { throw new error_1.MongoParseError("Cannot use srvMaxHosts option with replicaSet"); } const noUserSpecifiedTLS = !objectOptions.has("tls") && !urlOptions.has("tls"); const noUserSpecifiedSSL = !objectOptions.has("ssl") && !urlOptions.has("ssl"); if (noUserSpecifiedTLS && noUserSpecifiedSSL) { mongoOptions.tls = true; } } else { const userSpecifiedSrvOptions = urlOptions.has("srvMaxHosts") || objectOptions.has("srvMaxHosts") || urlOptions.has("srvServiceName") || objectOptions.has("srvServiceName"); if (userSpecifiedSrvOptions) { throw new error_1.MongoParseError("Cannot use srvMaxHosts or srvServiceName with a non-srv connection string"); } } if (mongoOptions.directConnection && mongoOptions.hosts.length !== 1) { throw new error_1.MongoParseError("directConnection option requires exactly one host"); } if (!mongoOptions.proxyHost && (mongoOptions.proxyPort || mongoOptions.proxyUsername || mongoOptions.proxyPassword)) { throw new error_1.MongoParseError("Must specify proxyHost if other proxy options are passed"); } if (mongoOptions.proxyUsername && !mongoOptions.proxyPassword || !mongoOptions.proxyUsername && mongoOptions.proxyPassword) { throw new error_1.MongoParseError("Can only specify both of proxy username/password or neither"); } const proxyOptions = ["proxyHost", "proxyPort", "proxyUsername", "proxyPassword"].map((key) => urlOptions.get(key) ?? []); if (proxyOptions.some((options2) => options2.length > 1)) { throw new error_1.MongoParseError("Proxy options cannot be specified multiple times in the connection string"); } mongoOptions.mongoLoggerOptions = mongo_logger_1.MongoLogger.resolveOptions({ MONGODB_LOG_COMMAND: process.env.MONGODB_LOG_COMMAND, MONGODB_LOG_TOPOLOGY: process.env.MONGODB_LOG_TOPOLOGY, MONGODB_LOG_SERVER_SELECTION: process.env.MONGODB_LOG_SERVER_SELECTION, MONGODB_LOG_CONNECTION: process.env.MONGODB_LOG_CONNECTION, MONGODB_LOG_CLIENT: process.env.MONGODB_LOG_CLIENT, MONGODB_LOG_ALL: process.env.MONGODB_LOG_ALL, MONGODB_LOG_MAX_DOCUMENT_LENGTH: process.env.MONGODB_LOG_MAX_DOCUMENT_LENGTH, MONGODB_LOG_PATH: process.env.MONGODB_LOG_PATH }, { mongodbLogPath: mongoOptions.mongodbLogPath, mongodbLogComponentSeverities: mongoOptions.mongodbLogComponentSeverities, mongodbLogMaxDocumentLength: mongoOptions.mongodbLogMaxDocumentLength }); mongoOptions.additionalDriverInfo = []; mongoOptions.metadata = (0, client_metadata_1.makeClientMetadata)(mongoOptions); mongoOptions.extendedMetadata = (0, client_metadata_1.addContainerMetadata)(mongoOptions.metadata).then(void 0, utils_1.squashError); return mongoOptions; } function validateLoadBalancedOptions(hosts, mongoOptions, isSrv) { if (mongoOptions.loadBalanced) { if (hosts.length > 1) { throw new error_1.MongoParseError(LB_SINGLE_HOST_ERROR); } if (mongoOptions.replicaSet) { throw new error_1.MongoParseError(LB_REPLICA_SET_ERROR); } if (mongoOptions.directConnection) { throw new error_1.MongoParseError(LB_DIRECT_CONNECTION_ERROR); } if (isSrv && mongoOptions.srvMaxHosts > 0) { throw new error_1.MongoParseError("Cannot limit srv hosts with loadBalanced enabled"); } } return; } function setOption(mongoOptions, key, descriptor, values) { const { target, type, transform } = descriptor; const name = target ?? key; switch (type) { case "boolean": mongoOptions[name] = getBoolean(name, values[0]); break; case "int": mongoOptions[name] = getIntFromOptions(name, values[0]); break; case "uint": mongoOptions[name] = getUIntFromOptions(name, values[0]); break; case "string": if (values[0] == null) { break; } mongoOptions[name] = String(values[0]); break; case "record": if (!(0, utils_1.isRecord)(values[0])) { throw new error_1.MongoParseError(`${name} must be an object`); } mongoOptions[name] = values[0]; break; case "any": mongoOptions[name] = values[0]; break; default: { if (!transform) { throw new error_1.MongoParseError("Descriptors missing a type must define a transform"); } const transformValue = transform({ name, options: mongoOptions, values }); mongoOptions[name] = transformValue; break; } } } exports2.OPTIONS = { appName: { type: "string" }, auth: { target: "credentials", transform({ name, options, values: [value] }) { if (!(0, utils_1.isRecord)(value, ["username", "password"])) { throw new error_1.MongoParseError(`${name} must be an object with 'username' and 'password' properties`); } return mongo_credentials_1.MongoCredentials.merge(options.credentials, { username: value.username, password: value.password }); } }, authMechanism: { target: "credentials", transform({ options, values: [value] }) { const mechanisms = Object.values(providers_1.AuthMechanism); const [mechanism] = mechanisms.filter((m) => m.match(RegExp(String.raw`\b${value}\b`, "i"))); if (!mechanism) { throw new error_1.MongoParseError(`authMechanism one of ${mechanisms}, got ${value}`); } let source = options.credentials?.source; if (mechanism === providers_1.AuthMechanism.MONGODB_PLAIN || providers_1.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(mechanism)) { source = "$external"; } let password = options.credentials?.password; if (mechanism === providers_1.AuthMechanism.MONGODB_X509 && password === "") { password = void 0; } return mongo_credentials_1.MongoCredentials.merge(options.credentials, { mechanism, source, password }); } }, // Note that if the authMechanismProperties contain a TOKEN_RESOURCE that has a // comma in it, it MUST be supplied as a MongoClient option instead of in the // connection string. authMechanismProperties: { target: "credentials", transform({ options, values }) { let mechanismProperties = /* @__PURE__ */ Object.create(null); for (const optionValue of values) { if (typeof optionValue === "string") { for (const [key, value] of entriesFromString(optionValue)) { try { mechanismProperties[key] = getBoolean(key, value); } catch { mechanismProperties[key] = value; } } } else { if (!(0, utils_1.isRecord)(optionValue)) { throw new error_1.MongoParseError("AuthMechanismProperties must be an object"); } mechanismProperties = { ...optionValue }; } } return mongo_credentials_1.MongoCredentials.merge(options.credentials, { mechanismProperties }); } }, authSource: { target: "credentials", transform({ options, values: [value] }) { const source = String(value); return mongo_credentials_1.MongoCredentials.merge(options.credentials, { source }); } }, autoEncryption: { type: "record" }, autoSelectFamily: { type: "boolean", default: true }, autoSelectFamilyAttemptTimeout: { type: "uint" }, bsonRegExp: { type: "boolean" }, serverApi: { target: "serverApi", transform({ values: [version] }) { const serverApiToValidate = typeof version === "string" ? { version } : version; const versionToValidate = serverApiToValidate && serverApiToValidate.version; if (!versionToValidate) { throw new error_1.MongoParseError(`Invalid \`serverApi\` property; must specify a version from the following enum: ["${Object.values(mongo_client_1.ServerApiVersion).join('", "')}"]`); } if (!Object.values(mongo_client_1.ServerApiVersion).some((v) => v === versionToValidate)) { throw new error_1.MongoParseError(`Invalid server API version=${versionToValidate}; must be in the following enum: ["${Object.values(mongo_client_1.ServerApiVersion).join('", "')}"]`); } return serverApiToValidate; } }, checkKeys: { type: "boolean" }, compressors: { default: "none", target: "compressors", transform({ values }) { const compressionList = /* @__PURE__ */ new Set(); for (const compVal of values) { const compValArray = typeof compVal === "string" ? compVal.split(",") : compVal; if (!Array.isArray(compValArray)) { throw new error_1.MongoInvalidArgumentError("compressors must be an array or a comma-delimited list of strings"); } for (const c of compValArray) { if (Object.keys(compression_1.Compressor).includes(String(c))) { compressionList.add(String(c)); } else { throw new error_1.MongoInvalidArgumentError(`${c} is not a valid compression mechanism. Must be one of: ${Object.keys(compression_1.Compressor)}.`); } } } return [...compressionList]; } }, connectTimeoutMS: { default: 3e4, type: "uint" }, dbName: { type: "string" }, directConnection: { default: false, type: "boolean" }, driverInfo: { default: {}, type: "record" }, enableUtf8Validation: { type: "boolean", default: true }, family: { transform({ name, values: [value] }) { const transformValue = getIntFromOptions(name, value); if (transformValue === 4 || transformValue === 6) { return transformValue; } throw new error_1.MongoParseError(`Option 'family' must be 4 or 6 got ${transformValue}.`); } }, fieldsAsRaw: { type: "record" }, forceServerObjectId: { default: false, type: "boolean" }, fsync: { deprecated: "Please use journal instead", target: "writeConcern", transform({ name, options, values: [value] }) { const wc = write_concern_1.WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, fsync: getBoolean(name, value) } }); if (!wc) throw new error_1.MongoParseError(`Unable to make a writeConcern from fsync=${value}`); return wc; } }, heartbeatFrequencyMS: { default: 1e4, type: "uint" }, ignoreUndefined: { type: "boolean" }, j: { deprecated: "Please use journal instead", target: "writeConcern", transform({ name, options, values: [value] }) { const wc = write_concern_1.WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, journal: getBoolean(name, value) } }); if (!wc) throw new error_1.MongoParseError(`Unable to make a writeConcern from journal=${value}`); return wc; } }, journal: { target: "writeConcern", transform({ name, options, values: [value] }) { const wc = write_concern_1.WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, journal: getBoolean(name, value) } }); if (!wc) throw new error_1.MongoParseError(`Unable to make a writeConcern from journal=${value}`); return wc; } }, loadBalanced: { default: false, type: "boolean" }, localThresholdMS: { default: 15, type: "uint" }, maxConnecting: { default: 2, transform({ name, values: [value] }) { const maxConnecting = getUIntFromOptions(name, value); if (maxConnecting === 0) { throw new error_1.MongoInvalidArgumentError("maxConnecting must be > 0 if specified"); } return maxConnecting; } }, maxIdleTimeMS: { default: 0, type: "uint" }, maxPoolSize: { default: 100, type: "uint" }, maxStalenessSeconds: { target: "readPreference", transform({ name, options, values: [value] }) { const maxStalenessSeconds = getUIntFromOptions(name, value); if (options.readPreference) { return read_preference_1.ReadPreference.fromOptions({ readPreference: { ...options.readPreference, maxStalenessSeconds } }); } else { return new read_preference_1.ReadPreference("secondary", void 0, { maxStalenessSeconds }); } } }, minInternalBufferSize: { type: "uint" }, minPoolSize: { default: 0, type: "uint" }, minHeartbeatFrequencyMS: { default: 500, type: "uint" }, monitorCommands: { default: false, type: "boolean" }, name: { target: "driverInfo", transform({ values: [value], options }) { return { ...options.driverInfo, name: String(value) }; } }, noDelay: { default: true, type: "boolean" }, pkFactory: { default: utils_1.DEFAULT_PK_FACTORY, transform({ values: [value] }) { if ((0, utils_1.isRecord)(value, ["createPk"]) && typeof value.createPk === "function") { return value; } throw new error_1.MongoParseError(`Option pkFactory must be an object with a createPk function, got ${value}`); } }, promoteBuffers: { type: "boolean" }, promoteLongs: { type: "boolean" }, promoteValues: { type: "boolean" }, useBigInt64: { type: "boolean" }, proxyHost: { type: "string" }, proxyPassword: { type: "string" }, proxyPort: { type: "uint" }, proxyUsername: { type: "string" }, raw: { default: false, type: "boolean" }, readConcern: { transform({ values: [value], options }) { if (value instanceof read_concern_1.ReadConcern || (0, utils_1.isRecord)(value, ["level"])) { return read_concern_1.ReadConcern.fromOptions({ ...options.readConcern, ...value }); } throw new error_1.MongoParseError(`ReadConcern must be an object, got ${JSON.stringify(value)}`); } }, readConcernLevel: { target: "readConcern", transform({ values: [level], options }) { return read_concern_1.ReadConcern.fromOptions({ ...options.readConcern, level }); } }, readPreference: { default: read_preference_1.ReadPreference.primary, transform({ values: [value], options }) { if (value instanceof read_preference_1.ReadPreference) { return read_preference_1.ReadPreference.fromOptions({ readPreference: { ...options.readPreference, ...value }, ...value }); } if ((0, utils_1.isRecord)(value, ["mode"])) { const rp = read_preference_1.ReadPreference.fromOptions({ readPreference: { ...options.readPreference, ...value }, ...value }); if (rp) return rp; else throw new error_1.MongoParseError(`Cannot make read preference from ${JSON.stringify(value)}`); } if (typeof value === "string") { const rpOpts = { hedge: options.readPreference?.hedge, maxStalenessSeconds: options.readPreference?.maxStalenessSeconds }; return new read_preference_1.ReadPreference(value, options.readPreference?.tags, rpOpts); } throw new error_1.MongoParseError(`Unknown ReadPreference value: ${value}`); } }, readPreferenceTags: { target: "readPreference", transform({ values, options }) { const tags = Array.isArray(values[0]) ? values[0] : values; const readPreferenceTags = []; for (const tag of tags) { const readPreferenceTag = /* @__PURE__ */ Object.create(null); if (typeof tag === "string") { for (const [k, v] of entriesFromString(tag)) { readPreferenceTag[k] = v; } } if ((0, utils_1.isRecord)(tag)) { for (const [k, v] of Object.entries(tag)) { readPreferenceTag[k] = v; } } readPreferenceTags.push(readPreferenceTag); } return read_preference_1.ReadPreference.fromOptions({ readPreference: options.readPreference, readPreferenceTags }); } }, replicaSet: { type: "string" }, retryReads: { default: true, type: "boolean" }, retryWrites: { default: true, type: "boolean" }, serializeFunctions: { type: "boolean" }, serverMonitoringMode: { default: "auto", transform({ values: [value] }) { if (!Object.values(monitor_1.ServerMonitoringMode).includes(value)) { throw new error_1.MongoParseError("serverMonitoringMode must be one of `auto`, `poll`, or `stream`"); } return value; } }, serverSelectionTimeoutMS: { default: 3e4, type: "uint" }, servername: { type: "string" }, socketTimeoutMS: { // TODO(NODE-6491): deprecated: 'Please use timeoutMS instead', default: 0, type: "uint" }, srvMaxHosts: { type: "uint", default: 0 }, srvServiceName: { type: "string", default: "mongodb" }, ssl: { target: "tls", type: "boolean" }, timeoutMS: { type: "uint" }, tls: { type: "boolean" }, tlsAllowInvalidCertificates: { target: "rejectUnauthorized", transform({ name, values: [value] }) { return !getBoolean(name, value); } }, tlsAllowInvalidHostnames: { target: "checkServerIdentity", transform({ name, values: [value] }) { return getBoolean(name, value) ? () => void 0 : void 0; } }, tlsCAFile: { type: "string" }, tlsCRLFile: { type: "string" }, tlsCertificateKeyFile: { type: "string" }, tlsCertificateKeyFilePassword: { target: "passphrase", type: "any" }, tlsInsecure: { transform({ name, options, values: [value] }) { const tlsInsecure = getBoolean(name, value); if (tlsInsecure) { options.checkServerIdentity = () => void 0; options.rejectUnauthorized = false; } else { options.checkServerIdentity = options.tlsAllowInvalidHostnames ? () => void 0 : void 0; options.rejectUnauthorized = options.tlsAllowInvalidCertificates ? false : true; } return tlsInsecure; } }, w: { target: "writeConcern", transform({ values: [value], options }) { return write_concern_1.WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, w: value } }); } }, waitQueueTimeoutMS: { // TODO(NODE-6491): deprecated: 'Please use timeoutMS instead', default: 0, type: "uint" }, writeConcern: { target: "writeConcern", transform({ values: [value], options }) { if ((0, utils_1.isRecord)(value) || value instanceof write_concern_1.WriteConcern) { return write_concern_1.WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, ...value } }); } else if (value === "majority" || typeof value === "number") { return write_concern_1.WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, w: value } }); } throw new error_1.MongoParseError(`Invalid WriteConcern cannot parse: ${JSON.stringify(value)}`); } }, wtimeout: { deprecated: "Please use wtimeoutMS instead", target: "writeConcern", transform({ values: [value], options }) { const wc = write_concern_1.WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, wtimeout: getUIntFromOptions("wtimeout", value) } }); if (wc) return wc; throw new error_1.MongoParseError(`Cannot make WriteConcern from wtimeout`); } }, wtimeoutMS: { target: "writeConcern", transform({ values: [value], options }) { const wc = write_concern_1.WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, wtimeoutMS: getUIntFromOptions("wtimeoutMS", value) } }); if (wc) return wc; throw new error_1.MongoParseError(`Cannot make WriteConcern from wtimeout`); } }, zlibCompressionLevel: { default: 0, type: "int" }, mongodbLogPath: { transform({ values: [value] }) { if (!(typeof value === "string" && ["stderr", "stdout"].includes(value) || value && typeof value === "object" && "write" in value && typeof value.write === "function")) { throw new error_1.MongoAPIError(`Option 'mongodbLogPath' must be of type 'stderr' | 'stdout' | MongoDBLogWritable`); } return value; } }, mongodbLogComponentSeverities: { transform({ values: [value] }) { if (typeof value !== "object" || !value) { throw new error_1.MongoAPIError(`Option 'mongodbLogComponentSeverities' must be a non-null object`); } for (const [k, v] of Object.entries(value)) { if (typeof v !== "string" || typeof k !== "string") { throw new error_1.MongoAPIError(`User input for option 'mongodbLogComponentSeverities' object cannot include a non-string key or value`); } if (!Object.values(mongo_logger_1.MongoLoggableComponent).some((val) => val === k) && k !== "default") { throw new error_1.MongoAPIError(`User input for option 'mongodbLogComponentSeverities' contains invalid key: ${k}`); } if (!Object.values(mongo_logger_1.SeverityLevel).some((val) => val === v)) { throw new error_1.MongoAPIError(`Option 'mongodbLogComponentSeverities' does not support ${v} as a value for ${k}`); } } return value; } }, mongodbLogMaxDocumentLength: { type: "uint" }, // Custom types for modifying core behavior connectionType: { type: "any" }, srvPoller: { type: "any" }, // Accepted Node.js Options allowPartialTrustChain: { type: "any" }, minDHSize: { type: "any" }, pskCallback: { type: "any" }, secureContext: { type: "any" }, enableTrace: { type: "any" }, requestCert: { type: "any" }, rejectUnauthorized: { type: "any" }, checkServerIdentity: { type: "any" }, keepAliveInitialDelay: { type: "any" }, ALPNProtocols: { type: "any" }, SNICallback: { type: "any" }, session: { type: "any" }, requestOCSP: { type: "any" }, localAddress: { type: "any" }, localPort: { type: "any" }, hints: { type: "any" }, lookup: { type: "any" }, ca: { type: "any" }, cert: { type: "any" }, ciphers: { type: "any" }, crl: { type: "any" }, ecdhCurve: { type: "any" }, key: { type: "any" }, passphrase: { type: "any" }, pfx: { type: "any" }, secureProtocol: { type: "any" }, index: { type: "any" }, // Legacy options from v3 era useNewUrlParser: { type: "boolean", deprecated: "useNewUrlParser has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version" }, useUnifiedTopology: { type: "boolean", deprecated: "useUnifiedTopology has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version" }, __skipPingOnConnect: { type: "boolean" } }; exports2.DEFAULT_OPTIONS = new CaseInsensitiveMap(Object.entries(exports2.OPTIONS).filter(([, descriptor]) => descriptor.default != null).map(([k, d]) => [k, d.default])); } }); // netlify/functions/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js var require_mongodb_aws = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.MongoDBAWS = void 0; var BSON = require_bson2(); var deps_1 = require_deps(); var error_1 = require_error(); var utils_1 = require_utils(); var auth_provider_1 = require_auth_provider(); var aws_temporary_credentials_1 = require_aws_temporary_credentials(); var mongo_credentials_1 = require_mongo_credentials(); var providers_1 = require_providers(); var ASCII_N = 110; var bsonOptions = { useBigInt64: false, promoteLongs: true, promoteValues: true, promoteBuffers: false, bsonRegExp: false }; var MongoDBAWS = class extends auth_provider_1.AuthProvider { constructor(credentialProvider) { super(); this.credentialProvider = credentialProvider; this.credentialFetcher = aws_temporary_credentials_1.AWSTemporaryCredentialProvider.isAWSSDKInstalled ? new aws_temporary_credentials_1.AWSSDKCredentialProvider(credentialProvider) : new aws_temporary_credentials_1.LegacyAWSTemporaryCredentialProvider(); } async auth(authContext) { const { connection } = authContext; if (!authContext.credentials) { throw new error_1.MongoMissingCredentialsError("AuthContext must provide credentials."); } if ("kModuleError" in deps_1.aws4) { throw deps_1.aws4["kModuleError"]; } const { sign } = deps_1.aws4; if ((0, utils_1.maxWireVersion)(connection) < 9) { throw new error_1.MongoCompatibilityError("MONGODB-AWS authentication requires MongoDB version 4.4 or later"); } if (!authContext.credentials.username) { authContext.credentials = await makeTempCredentials(authContext.credentials, this.credentialFetcher); } const { credentials } = authContext; const accessKeyId = credentials.username; const secretAccessKey = credentials.password; const sessionToken = credentials.mechanismProperties.AWS_SESSION_TOKEN; const awsCredentials = accessKeyId && secretAccessKey && sessionToken ? { accessKeyId, secretAccessKey, sessionToken } : accessKeyId && secretAccessKey ? { accessKeyId, secretAccessKey } : void 0; const db = credentials.source; const nonce = await (0, utils_1.randomBytes)(32); const saslStart = { saslStart: 1, mechanism: "MONGODB-AWS", payload: BSON.serialize({ r: nonce, p: ASCII_N }, bsonOptions) }; const saslStartResponse = await connection.command((0, utils_1.ns)(`${db}.$cmd`), saslStart, void 0); const serverResponse = BSON.deserialize(saslStartResponse.payload.buffer, bsonOptions); const host = serverResponse.h; const serverNonce = serverResponse.s.buffer; if (serverNonce.length !== 64) { throw new error_1.MongoRuntimeError(`Invalid server nonce length ${serverNonce.length}, expected 64`); } if (!utils_1.ByteUtils.equals(serverNonce.subarray(0, nonce.byteLength), nonce)) { throw new error_1.MongoRuntimeError("Server nonce does not begin with client nonce"); } if (host.length < 1 || host.length > 255 || host.indexOf("..") !== -1) { throw new error_1.MongoRuntimeError(`Server returned an invalid host: "${host}"`); } const body = "Action=GetCallerIdentity&Version=2011-06-15"; const options = sign({ method: "POST", host, region: deriveRegion(serverResponse.h), service: "sts", headers: { "Content-Type": "application/x-www-form-urlencoded", "Content-Length": body.length, "X-MongoDB-Server-Nonce": utils_1.ByteUtils.toBase64(serverNonce), "X-MongoDB-GS2-CB-Flag": "n" }, path: "/", body }, awsCredentials); const payload = { a: options.headers.Authorization, d: options.headers["X-Amz-Date"] }; if (sessionToken) { payload.t = sessionToken; } const saslContinue = { saslContinue: 1, conversationId: saslStartResponse.conversationId, payload: BSON.serialize(payload, bsonOptions) }; await connection.command((0, utils_1.ns)(`${db}.$cmd`), saslContinue, void 0); } }; exports2.MongoDBAWS = MongoDBAWS; async function makeTempCredentials(credentials, awsCredentialFetcher) { function makeMongoCredentialsFromAWSTemp(creds) { if (!creds.AccessKeyId || !creds.SecretAccessKey) { throw new error_1.MongoMissingCredentialsError("Could not obtain temporary MONGODB-AWS credentials"); } return new mongo_credentials_1.MongoCredentials({ username: creds.AccessKeyId, password: creds.SecretAccessKey, source: credentials.source, mechanism: providers_1.AuthMechanism.MONGODB_AWS, mechanismProperties: { AWS_SESSION_TOKEN: creds.Token } }); } const temporaryCredentials = await awsCredentialFetcher.getCredentials(); return makeMongoCredentialsFromAWSTemp(temporaryCredentials); } function deriveRegion(host) { const parts = host.split("."); if (parts.length === 1 || parts[1] === "amazonaws") { return "us-east-1"; } return parts[1]; } } }); // netlify/functions/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/command_builders.js var require_command_builders = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/command_builders.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.finishCommandDocument = finishCommandDocument; exports2.startCommandDocument = startCommandDocument; var bson_1 = require_bson2(); var providers_1 = require_providers(); function finishCommandDocument(token, conversationId) { if (conversationId != null) { return { saslContinue: 1, conversationId, payload: new bson_1.Binary(bson_1.BSON.serialize({ jwt: token })) }; } return { saslStart: 1, mechanism: providers_1.AuthMechanism.MONGODB_OIDC, payload: new bson_1.Binary(bson_1.BSON.serialize({ jwt: token })) }; } function startCommandDocument(credentials) { const payload = {}; if (credentials.username) { payload.n = credentials.username; } return { saslStart: 1, autoAuthorize: 1, mechanism: providers_1.AuthMechanism.MONGODB_OIDC, payload: new bson_1.Binary(bson_1.BSON.serialize(payload)) }; } } }); // netlify/functions/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_workflow.js var require_callback_workflow = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_workflow.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.CallbackWorkflow = exports2.AUTOMATED_TIMEOUT_MS = exports2.HUMAN_TIMEOUT_MS = void 0; var promises_1 = require("timers/promises"); var error_1 = require_error(); var utils_1 = require_utils(); var command_builders_1 = require_command_builders(); exports2.HUMAN_TIMEOUT_MS = 3e5; exports2.AUTOMATED_TIMEOUT_MS = 6e4; var RESULT_PROPERTIES = ["accessToken", "expiresInSeconds", "refreshToken"]; var CALLBACK_RESULT_ERROR = "User provided OIDC callbacks must return a valid object with an accessToken."; var THROTTLE_MS = 100; var CallbackWorkflow = class { /** * Instantiate the callback workflow. */ constructor(cache, callback) { this.cache = cache; this.callback = this.withLock(callback); this.lastExecutionTime = Date.now() - THROTTLE_MS; } /** * Get the document to add for speculative authentication. This also needs * to add a db field from the credentials source. */ async speculativeAuth(connection, credentials) { if (this.cache.hasAccessToken) { const accessToken = this.cache.getAccessToken(); connection.accessToken = accessToken; const document2 = (0, command_builders_1.finishCommandDocument)(accessToken); document2.db = credentials.source; return { speculativeAuthenticate: document2 }; } return {}; } /** * Reauthenticate the callback workflow. For this we invalidated the access token * in the cache and run the authentication steps again. No initial handshake needs * to be sent. */ async reauthenticate(connection, credentials) { if (this.cache.hasAccessToken) { if (connection.accessToken === this.cache.getAccessToken()) { this.cache.removeAccessToken(); delete connection.accessToken; } else { connection.accessToken = this.cache.getAccessToken(); } } await this.execute(connection, credentials); } /** * Starts the callback authentication process. If there is a speculative * authentication document from the initial handshake, then we will use that * value to get the issuer, otherwise we will send the saslStart command. */ async startAuthentication(connection, credentials, response) { let result; if (response?.speculativeAuthenticate) { result = response.speculativeAuthenticate; } else { result = await connection.command((0, utils_1.ns)(credentials.source), (0, command_builders_1.startCommandDocument)(credentials), void 0); } return result; } /** * Finishes the callback authentication process. */ async finishAuthentication(connection, credentials, token, conversationId) { await connection.command((0, utils_1.ns)(credentials.source), (0, command_builders_1.finishCommandDocument)(token, conversationId), void 0); } /** * Executes the callback and validates the output. */ async executeAndValidateCallback(params) { const result = await this.callback(params); if (isCallbackResultInvalid(result)) { throw new error_1.MongoMissingCredentialsError(CALLBACK_RESULT_ERROR); } return result; } /** * Ensure the callback is only executed one at a time and throttles the calls * to every 100ms. */ withLock(callback) { let lock = Promise.resolve(); return async (params) => { await lock; lock = lock.catch(() => null).then(async () => { const difference = Date.now() - this.lastExecutionTime; if (difference <= THROTTLE_MS) { await (0, promises_1.setTimeout)(THROTTLE_MS - difference, { signal: params.timeoutContext }); } this.lastExecutionTime = Date.now(); return await callback(params); }); return await lock; }; } }; exports2.CallbackWorkflow = CallbackWorkflow; function isCallbackResultInvalid(tokenResult) { if (tokenResult == null || typeof tokenResult !== "object") return true; if (!("accessToken" in tokenResult)) return true; return !Object.getOwnPropertyNames(tokenResult).every((prop) => RESULT_PROPERTIES.includes(prop)); } } }); // netlify/functions/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/automated_callback_workflow.js var require_automated_callback_workflow = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/automated_callback_workflow.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.AutomatedCallbackWorkflow = void 0; var error_1 = require_error(); var timeout_1 = require_timeout(); var mongodb_oidc_1 = require_mongodb_oidc(); var callback_workflow_1 = require_callback_workflow(); var AutomatedCallbackWorkflow = class extends callback_workflow_1.CallbackWorkflow { /** * Instantiate the human callback workflow. */ constructor(cache, callback) { super(cache, callback); } /** * Execute the OIDC callback workflow. */ async execute(connection, credentials) { if (this.cache.hasAccessToken) { const token = this.cache.getAccessToken(); if (!connection.accessToken) { connection.accessToken = token; } try { return await this.finishAuthentication(connection, credentials, token); } catch (error) { if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.AuthenticationFailed) { this.cache.removeAccessToken(); return await this.execute(connection, credentials); } else { throw error; } } } const response = await this.fetchAccessToken(credentials); this.cache.put(response); connection.accessToken = response.accessToken; await this.finishAuthentication(connection, credentials, response.accessToken); } /** * Fetches the access token using the callback. */ async fetchAccessToken(credentials) { const controller = new AbortController(); const params = { timeoutContext: controller.signal, version: mongodb_oidc_1.OIDC_VERSION }; if (credentials.username) { params.username = credentials.username; } if (credentials.mechanismProperties.TOKEN_RESOURCE) { params.tokenAudience = credentials.mechanismProperties.TOKEN_RESOURCE; } const timeout = timeout_1.Timeout.expires(callback_workflow_1.AUTOMATED_TIMEOUT_MS); try { return await Promise.race([this.executeAndValidateCallback(params), timeout]); } catch (error) { if (timeout_1.TimeoutError.is(error)) { controller.abort(); throw new error_1.MongoOIDCError(`OIDC callback timed out after ${callback_workflow_1.AUTOMATED_TIMEOUT_MS}ms.`); } throw error; } finally { timeout.clear(); } } }; exports2.AutomatedCallbackWorkflow = AutomatedCallbackWorkflow; } }); // netlify/functions/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/azure_machine_workflow.js var require_azure_machine_workflow = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/azure_machine_workflow.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.callback = void 0; var azure_1 = require_azure(); var error_1 = require_error(); var utils_1 = require_utils(); var AZURE_HEADERS = Object.freeze({ Metadata: "true", Accept: "application/json" }); var ENDPOINT_RESULT_ERROR = "Azure endpoint did not return a value with only access_token and expires_in properties"; var TOKEN_RESOURCE_MISSING_ERROR = "TOKEN_RESOURCE must be set in the auth mechanism properties when ENVIRONMENT is azure."; var callback = async (params) => { const tokenAudience = params.tokenAudience; const username = params.username; if (!tokenAudience) { throw new error_1.MongoAzureError(TOKEN_RESOURCE_MISSING_ERROR); } const response = await getAzureTokenData(tokenAudience, username); if (!isEndpointResultValid(response)) { throw new error_1.MongoAzureError(ENDPOINT_RESULT_ERROR); } return response; }; exports2.callback = callback; async function getAzureTokenData(tokenAudience, username) { const url = new URL(azure_1.AZURE_BASE_URL); (0, azure_1.addAzureParams)(url, tokenAudience, username); const response = await (0, utils_1.get)(url, { headers: AZURE_HEADERS }); if (response.status !== 200) { throw new error_1.MongoAzureError(`Status code ${response.status} returned from the Azure endpoint. Response body: ${response.body}`); } const result = JSON.parse(response.body); return { accessToken: result.access_token, expiresInSeconds: Number(result.expires_in) }; } function isEndpointResultValid(token) { if (token == null || typeof token !== "object") return false; return "accessToken" in token && typeof token.accessToken === "string" && "expiresInSeconds" in token && typeof token.expiresInSeconds === "number"; } } }); // netlify/functions/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/gcp_machine_workflow.js var require_gcp_machine_workflow = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/gcp_machine_workflow.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.callback = void 0; var error_1 = require_error(); var utils_1 = require_utils(); var GCP_BASE_URL = "http://metadata/computeMetadata/v1/instance/service-accounts/default/identity"; var GCP_HEADERS = Object.freeze({ "Metadata-Flavor": "Google" }); var TOKEN_RESOURCE_MISSING_ERROR = "TOKEN_RESOURCE must be set in the auth mechanism properties when ENVIRONMENT is gcp."; var callback = async (params) => { const tokenAudience = params.tokenAudience; if (!tokenAudience) { throw new error_1.MongoGCPError(TOKEN_RESOURCE_MISSING_ERROR); } return await getGcpTokenData(tokenAudience); }; exports2.callback = callback; async function getGcpTokenData(tokenAudience) { const url = new URL(GCP_BASE_URL); url.searchParams.append("audience", tokenAudience); const response = await (0, utils_1.get)(url, { headers: GCP_HEADERS }); if (response.status !== 200) { throw new error_1.MongoGCPError(`Status code ${response.status} returned from the GCP endpoint. Response body: ${response.body}`); } return { accessToken: response.body }; } } }); // netlify/functions/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/k8s_machine_workflow.js var require_k8s_machine_workflow = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/k8s_machine_workflow.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.callback = void 0; var promises_1 = require("fs/promises"); var FALLBACK_FILENAME = "/var/run/secrets/kubernetes.io/serviceaccount/token"; var AZURE_FILENAME = "AZURE_FEDERATED_TOKEN_FILE"; var AWS_FILENAME = "AWS_WEB_IDENTITY_TOKEN_FILE"; var callback = async () => { let filename; if (process.env[AZURE_FILENAME]) { filename = process.env[AZURE_FILENAME]; } else if (process.env[AWS_FILENAME]) { filename = process.env[AWS_FILENAME]; } else { filename = FALLBACK_FILENAME; } const token = await (0, promises_1.readFile)(filename, "utf8"); return { accessToken: token }; }; exports2.callback = callback; } }); // netlify/functions/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/token_cache.js var require_token_cache = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/token_cache.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.TokenCache = void 0; var error_1 = require_error(); var MongoOIDCError = class extends error_1.MongoDriverError { }; var TokenCache = class { get hasAccessToken() { return !!this.accessToken; } get hasRefreshToken() { return !!this.refreshToken; } get hasIdpInfo() { return !!this.idpInfo; } getAccessToken() { if (!this.accessToken) { throw new MongoOIDCError("Attempted to get an access token when none exists."); } return this.accessToken; } getRefreshToken() { if (!this.refreshToken) { throw new MongoOIDCError("Attempted to get a refresh token when none exists."); } return this.refreshToken; } getIdpInfo() { if (!this.idpInfo) { throw new MongoOIDCError("Attempted to get IDP information when none exists."); } return this.idpInfo; } put(response, idpInfo) { this.accessToken = response.accessToken; this.refreshToken = response.refreshToken; this.expiresInSeconds = response.expiresInSeconds; if (idpInfo) { this.idpInfo = idpInfo; } } removeAccessToken() { this.accessToken = void 0; } removeRefreshToken() { this.refreshToken = void 0; } }; exports2.TokenCache = TokenCache; } }); // netlify/functions/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/token_machine_workflow.js var require_token_machine_workflow = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/token_machine_workflow.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.callback = void 0; var fs = require("fs"); var error_1 = require_error(); var TOKEN_MISSING_ERROR = "OIDC_TOKEN_FILE must be set in the environment."; var callback = async () => { const tokenFile = process.env.OIDC_TOKEN_FILE; if (!tokenFile) { throw new error_1.MongoAWSError(TOKEN_MISSING_ERROR); } const token = await fs.promises.readFile(tokenFile, "utf8"); return { accessToken: token }; }; exports2.callback = callback; } }); // netlify/functions/node_modules/mongodb/lib/cmap/auth/mongodb_oidc.js var require_mongodb_oidc = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/auth/mongodb_oidc.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.MongoDBOIDC = exports2.OIDC_WORKFLOWS = exports2.OIDC_VERSION = void 0; var error_1 = require_error(); var auth_provider_1 = require_auth_provider(); var automated_callback_workflow_1 = require_automated_callback_workflow(); var azure_machine_workflow_1 = require_azure_machine_workflow(); var gcp_machine_workflow_1 = require_gcp_machine_workflow(); var k8s_machine_workflow_1 = require_k8s_machine_workflow(); var token_cache_1 = require_token_cache(); var token_machine_workflow_1 = require_token_machine_workflow(); var MISSING_CREDENTIALS_ERROR = "AuthContext must provide credentials."; exports2.OIDC_VERSION = 1; exports2.OIDC_WORKFLOWS = /* @__PURE__ */ new Map(); exports2.OIDC_WORKFLOWS.set("test", () => new automated_callback_workflow_1.AutomatedCallbackWorkflow(new token_cache_1.TokenCache(), token_machine_workflow_1.callback)); exports2.OIDC_WORKFLOWS.set("azure", () => new automated_callback_workflow_1.AutomatedCallbackWorkflow(new token_cache_1.TokenCache(), azure_machine_workflow_1.callback)); exports2.OIDC_WORKFLOWS.set("gcp", () => new automated_callback_workflow_1.AutomatedCallbackWorkflow(new token_cache_1.TokenCache(), gcp_machine_workflow_1.callback)); exports2.OIDC_WORKFLOWS.set("k8s", () => new automated_callback_workflow_1.AutomatedCallbackWorkflow(new token_cache_1.TokenCache(), k8s_machine_workflow_1.callback)); var MongoDBOIDC = class extends auth_provider_1.AuthProvider { /** * Instantiate the auth provider. */ constructor(workflow) { super(); if (!workflow) { throw new error_1.MongoInvalidArgumentError("No workflow provided to the OIDC auth provider."); } this.workflow = workflow; } /** * Authenticate using OIDC */ async auth(authContext) { const { connection, reauthenticating, response } = authContext; if (response?.speculativeAuthenticate?.done && !reauthenticating) { return; } const credentials = getCredentials(authContext); if (reauthenticating) { await this.workflow.reauthenticate(connection, credentials); } else { await this.workflow.execute(connection, credentials, response); } } /** * Add the speculative auth for the initial handshake. */ async prepare(handshakeDoc, authContext) { const { connection } = authContext; const credentials = getCredentials(authContext); const result = await this.workflow.speculativeAuth(connection, credentials); return { ...handshakeDoc, ...result }; } }; exports2.MongoDBOIDC = MongoDBOIDC; function getCredentials(authContext) { const { credentials } = authContext; if (!credentials) { throw new error_1.MongoMissingCredentialsError(MISSING_CREDENTIALS_ERROR); } return credentials; } } }); // netlify/functions/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/human_callback_workflow.js var require_human_callback_workflow = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/human_callback_workflow.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.HumanCallbackWorkflow = void 0; var bson_1 = require_bson2(); var error_1 = require_error(); var timeout_1 = require_timeout(); var mongodb_oidc_1 = require_mongodb_oidc(); var callback_workflow_1 = require_callback_workflow(); var HumanCallbackWorkflow = class extends callback_workflow_1.CallbackWorkflow { /** * Instantiate the human callback workflow. */ constructor(cache, callback) { super(cache, callback); } /** * Execute the OIDC human callback workflow. */ async execute(connection, credentials) { if (this.cache.hasAccessToken) { const token = this.cache.getAccessToken(); connection.accessToken = token; try { return await this.finishAuthentication(connection, credentials, token); } catch (error) { if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.AuthenticationFailed) { this.cache.removeAccessToken(); delete connection.accessToken; return await this.execute(connection, credentials); } else { throw error; } } } if (this.cache.hasRefreshToken) { const refreshToken = this.cache.getRefreshToken(); const result = await this.fetchAccessToken(this.cache.getIdpInfo(), credentials, refreshToken); this.cache.put(result); connection.accessToken = result.accessToken; try { return await this.finishAuthentication(connection, credentials, result.accessToken); } catch (error) { if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.AuthenticationFailed) { this.cache.removeRefreshToken(); delete connection.accessToken; return await this.execute(connection, credentials); } else { throw error; } } } const startResponse = await this.startAuthentication(connection, credentials); const conversationId = startResponse.conversationId; const idpInfo = bson_1.BSON.deserialize(startResponse.payload.buffer); const callbackResponse = await this.fetchAccessToken(idpInfo, credentials); this.cache.put(callbackResponse, idpInfo); connection.accessToken = callbackResponse.accessToken; return await this.finishAuthentication(connection, credentials, callbackResponse.accessToken, conversationId); } /** * Fetches an access token using the callback. */ async fetchAccessToken(idpInfo, credentials, refreshToken) { const controller = new AbortController(); const params = { timeoutContext: controller.signal, version: mongodb_oidc_1.OIDC_VERSION, idpInfo }; if (credentials.username) { params.username = credentials.username; } if (refreshToken) { params.refreshToken = refreshToken; } const timeout = timeout_1.Timeout.expires(callback_workflow_1.HUMAN_TIMEOUT_MS); try { return await Promise.race([this.executeAndValidateCallback(params), timeout]); } catch (error) { if (timeout_1.TimeoutError.is(error)) { controller.abort(); throw new error_1.MongoOIDCError(`OIDC callback timed out after ${callback_workflow_1.HUMAN_TIMEOUT_MS}ms.`); } throw error; } finally { timeout.clear(); } } }; exports2.HumanCallbackWorkflow = HumanCallbackWorkflow; } }); // netlify/functions/node_modules/mongodb/lib/cmap/auth/plain.js var require_plain = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/auth/plain.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.Plain = void 0; var bson_1 = require_bson2(); var error_1 = require_error(); var utils_1 = require_utils(); var auth_provider_1 = require_auth_provider(); var Plain = class extends auth_provider_1.AuthProvider { async auth(authContext) { const { connection, credentials } = authContext; if (!credentials) { throw new error_1.MongoMissingCredentialsError("AuthContext must provide credentials."); } const { username, password } = credentials; const payload = new bson_1.Binary(Buffer.from(`\0${username}\0${password}`)); const command = { saslStart: 1, mechanism: "PLAIN", payload, autoAuthorize: 1 }; await connection.command((0, utils_1.ns)("$external.$cmd"), command, void 0); } }; exports2.Plain = Plain; } }); // netlify/functions/node_modules/@mongodb-js/saslprep/dist/index.js var require_dist = __commonJS({ "netlify/functions/node_modules/@mongodb-js/saslprep/dist/index.js"(exports2, module2) { "use strict"; var getCodePoint = (character) => character.codePointAt(0); var first = (x) => x[0]; var last = (x) => x[x.length - 1]; function toCodePoints(input) { const codepoints = []; const size = input.length; for (let i = 0; i < size; i += 1) { const before = input.charCodeAt(i); if (before >= 55296 && before <= 56319 && size > i + 1) { const next = input.charCodeAt(i + 1); if (next >= 56320 && next <= 57343) { codepoints.push((before - 55296) * 1024 + next - 56320 + 65536); i += 1; continue; } } codepoints.push(before); } return codepoints; } function saslprep({ unassigned_code_points, commonly_mapped_to_nothing, non_ASCII_space_characters, prohibited_characters, bidirectional_r_al, bidirectional_l }, input, opts = {}) { const mapping2space = non_ASCII_space_characters; const mapping2nothing = commonly_mapped_to_nothing; if (typeof input !== "string") { throw new TypeError("Expected string."); } if (input.length === 0) { return ""; } const mapped_input = toCodePoints(input).map((character) => mapping2space.get(character) ? 32 : character).filter((character) => !mapping2nothing.get(character)); const normalized_input = String.fromCodePoint.apply(null, mapped_input).normalize("NFKC"); const normalized_map = toCodePoints(normalized_input); const hasProhibited = normalized_map.some((character) => prohibited_characters.get(character)); if (hasProhibited) { throw new Error("Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3"); } if (opts.allowUnassigned !== true) { const hasUnassigned = normalized_map.some((character) => unassigned_code_points.get(character)); if (hasUnassigned) { throw new Error("Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5"); } } const hasBidiRAL = normalized_map.some((character) => bidirectional_r_al.get(character)); const hasBidiL = normalized_map.some((character) => bidirectional_l.get(character)); if (hasBidiRAL && hasBidiL) { throw new Error("String must not contain RandALCat and LCat at the same time, see https://tools.ietf.org/html/rfc3454#section-6"); } const isFirstBidiRAL = bidirectional_r_al.get(getCodePoint(first(normalized_input))); const isLastBidiRAL = bidirectional_r_al.get(getCodePoint(last(normalized_input))); if (hasBidiRAL && !(isFirstBidiRAL && isLastBidiRAL)) { throw new Error("Bidirectional RandALCat character must be the first and the last character of the string, see https://tools.ietf.org/html/rfc3454#section-6"); } return normalized_input; } saslprep.saslprep = saslprep; saslprep.default = saslprep; module2.exports = saslprep; } }); // netlify/functions/node_modules/memory-pager/index.js var require_memory_pager = __commonJS({ "netlify/functions/node_modules/memory-pager/index.js"(exports2, module2) { module2.exports = Pager; function Pager(pageSize, opts) { if (!(this instanceof Pager)) return new Pager(pageSize, opts); this.length = 0; this.updates = []; this.path = new Uint16Array(4); this.pages = new Array(32768); this.maxPages = this.pages.length; this.level = 0; this.pageSize = pageSize || 1024; this.deduplicate = opts ? opts.deduplicate : null; this.zeros = this.deduplicate ? alloc(this.deduplicate.length) : null; } Pager.prototype.updated = function(page) { while (this.deduplicate && page.buffer[page.deduplicate] === this.deduplicate[page.deduplicate]) { page.deduplicate++; if (page.deduplicate === this.deduplicate.length) { page.deduplicate = 0; if (page.buffer.equals && page.buffer.equals(this.deduplicate)) page.buffer = this.deduplicate; break; } } if (page.updated || !this.updates) return; page.updated = true; this.updates.push(page); }; Pager.prototype.lastUpdate = function() { if (!this.updates || !this.updates.length) return null; var page = this.updates.pop(); page.updated = false; return page; }; Pager.prototype._array = function(i, noAllocate) { if (i >= this.maxPages) { if (noAllocate) return; grow(this, i); } factor(i, this.path); var arr = this.pages; for (var j = this.level; j > 0; j--) { var p = this.path[j]; var next = arr[p]; if (!next) { if (noAllocate) return; next = arr[p] = new Array(32768); } arr = next; } return arr; }; Pager.prototype.get = function(i, noAllocate) { var arr = this._array(i, noAllocate); var first = this.path[0]; var page = arr && arr[first]; if (!page && !noAllocate) { page = arr[first] = new Page(i, alloc(this.pageSize)); if (i >= this.length) this.length = i + 1; } if (page && page.buffer === this.deduplicate && this.deduplicate && !noAllocate) { page.buffer = copy(page.buffer); page.deduplicate = 0; } return page; }; Pager.prototype.set = function(i, buf) { var arr = this._array(i, false); var first = this.path[0]; if (i >= this.length) this.length = i + 1; if (!buf || this.zeros && buf.equals && buf.equals(this.zeros)) { arr[first] = void 0; return; } if (this.deduplicate && buf.equals && buf.equals(this.deduplicate)) { buf = this.deduplicate; } var page = arr[first]; var b = truncate(buf, this.pageSize); if (page) page.buffer = b; else arr[first] = new Page(i, b); }; Pager.prototype.toBuffer = function() { var list = new Array(this.length); var empty = alloc(this.pageSize); var ptr = 0; while (ptr < list.length) { var arr = this._array(ptr, true); for (var i = 0; i < 32768 && ptr < list.length; i++) { list[ptr++] = arr && arr[i] ? arr[i].buffer : empty; } } return Buffer.concat(list); }; function grow(pager, index) { while (pager.maxPages < index) { var old = pager.pages; pager.pages = new Array(32768); pager.pages[0] = old; pager.level++; pager.maxPages *= 32768; } } function truncate(buf, len) { if (buf.length === len) return buf; if (buf.length > len) return buf.slice(0, len); var cpy = alloc(len); buf.copy(cpy); return cpy; } function alloc(size) { if (Buffer.alloc) return Buffer.alloc(size); var buf = new Buffer(size); buf.fill(0); return buf; } function copy(buf) { var cpy = Buffer.allocUnsafe ? Buffer.allocUnsafe(buf.length) : new Buffer(buf.length); buf.copy(cpy); return cpy; } function Page(i, buf) { this.offset = i * buf.length; this.buffer = buf; this.updated = false; this.deduplicate = 0; } function factor(n, out) { n = (n - (out[0] = n & 32767)) / 32768; n = (n - (out[1] = n & 32767)) / 32768; out[3] = (n - (out[2] = n & 32767)) / 32768 & 32767; } } }); // netlify/functions/node_modules/sparse-bitfield/index.js var require_sparse_bitfield = __commonJS({ "netlify/functions/node_modules/sparse-bitfield/index.js"(exports2, module2) { var pager = require_memory_pager(); module2.exports = Bitfield; function Bitfield(opts) { if (!(this instanceof Bitfield)) return new Bitfield(opts); if (!opts) opts = {}; if (Buffer.isBuffer(opts)) opts = { buffer: opts }; this.pageOffset = opts.pageOffset || 0; this.pageSize = opts.pageSize || 1024; this.pages = opts.pages || pager(this.pageSize); this.byteLength = this.pages.length * this.pageSize; this.length = 8 * this.byteLength; if (!powerOfTwo(this.pageSize)) throw new Error("The page size should be a power of two"); this._trackUpdates = !!opts.trackUpdates; this._pageMask = this.pageSize - 1; if (opts.buffer) { for (var i = 0; i < opts.buffer.length; i += this.pageSize) { this.pages.set(i / this.pageSize, opts.buffer.slice(i, i + this.pageSize)); } this.byteLength = opts.buffer.length; this.length = 8 * this.byteLength; } } Bitfield.prototype.get = function(i) { var o = i & 7; var j = (i - o) / 8; return !!(this.getByte(j) & 128 >> o); }; Bitfield.prototype.getByte = function(i) { var o = i & this._pageMask; var j = (i - o) / this.pageSize; var page = this.pages.get(j, true); return page ? page.buffer[o + this.pageOffset] : 0; }; Bitfield.prototype.set = function(i, v) { var o = i & 7; var j = (i - o) / 8; var b = this.getByte(j); return this.setByte(j, v ? b | 128 >> o : b & (255 ^ 128 >> o)); }; Bitfield.prototype.toBuffer = function() { var all = alloc(this.pages.length * this.pageSize); for (var i = 0; i < this.pages.length; i++) { var next = this.pages.get(i, true); var allOffset = i * this.pageSize; if (next) next.buffer.copy(all, allOffset, this.pageOffset, this.pageOffset + this.pageSize); } return all; }; Bitfield.prototype.setByte = function(i, b) { var o = i & this._pageMask; var j = (i - o) / this.pageSize; var page = this.pages.get(j, false); o += this.pageOffset; if (page.buffer[o] === b) return false; page.buffer[o] = b; if (i >= this.byteLength) { this.byteLength = i + 1; this.length = this.byteLength * 8; } if (this._trackUpdates) this.pages.updated(page); return true; }; function alloc(n) { if (Buffer.alloc) return Buffer.alloc(n); var b = new Buffer(n); b.fill(0); return b; } function powerOfTwo(x) { return !(x & x - 1); } } }); // netlify/functions/node_modules/@mongodb-js/saslprep/dist/memory-code-points.js var require_memory_code_points = __commonJS({ "netlify/functions/node_modules/@mongodb-js/saslprep/dist/memory-code-points.js"(exports2) { "use strict"; var __importDefault = exports2 && exports2.__importDefault || function(mod) { return mod && mod.__esModule ? mod : { "default": mod }; }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.createMemoryCodePoints = createMemoryCodePoints; var sparse_bitfield_1 = __importDefault(require_sparse_bitfield()); function createMemoryCodePoints(data) { let offset = 0; function read() { const size = data.readUInt32BE(offset); offset += 4; const codepoints = data.slice(offset, offset + size); offset += size; return (0, sparse_bitfield_1.default)({ buffer: codepoints }); } const unassigned_code_points = read(); const commonly_mapped_to_nothing = read(); const non_ASCII_space_characters = read(); const prohibited_characters = read(); const bidirectional_r_al = read(); const bidirectional_l = read(); return { unassigned_code_points, commonly_mapped_to_nothing, non_ASCII_space_characters, prohibited_characters, bidirectional_r_al, bidirectional_l }; } } }); // netlify/functions/node_modules/@mongodb-js/saslprep/dist/code-points-data.js var require_code_points_data = __commonJS({ "netlify/functions/node_modules/@mongodb-js/saslprep/dist/code-points-data.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var zlib_1 = require("zlib"); exports2.default = (0, zlib_1.gunzipSync)(Buffer.from("H4sIAAAAAAACA+3dTYgcaRkA4LemO9Mhxm0FITnE9Cwr4jHgwgZ22B6YywqCJ0HQg5CL4sGTuOjCtGSF4CkHEW856MlTQHD3EJnWkU0Owh5VxE3LHlYQdNxd2U6mU59UV/d09fw4M2EySSXPAzNdP1/9fX/99bzVNZEN4jisRDulVFnQmLxm1aXF9Id/2/xMxNJ4XZlg576yuYlGt9gupV6xoFf8jhu9YvulVrFlp5XSx+lfvYhORGPXvqIRWSxERKtIm8bKFd10WNfKDS5Fo9jJWrq2+M2IlW+8uHgl/+BsROfPF4v5L7148Ur68Sha6dqZpYiVVy8tvLCWXo80Sf/lS89dGX2wHGvpzoXVn75/YWH5wmqe8uika82ViJXTy83Ve2k5Urozm38wm4/ls6t5uT6yfsTSJ7J3T0VKt8c5ExEXI8aFkH729c3eT+7EC6ca8cVULZUiYacX0R5PNWNxlh9L1y90q5kyzrpyy+9WcvOV6URntqw7La9sNVstXyczWVaWYbaaTYqzOHpr7pyiNT3/YzKuT63Z/FqKZlFTiuXtFM2vVOtIq7jiyKJbWZaOWD0euz0yoV2Z7kY0xq2x0YhfzVpmM5px9nTEH7JZ0ot5u39p0ma75Z472/s/H+2yr2inYyuq7fMvJivH2rM72N/Z3lyL31F2b1ya1P0zn816k2KP6JU9UzseucdQH5YqVeH/lFajSN2udg+TLJ9rksNxlvV2lki19rXKI43TPLejFu4ov7k3nMbhyhfY3Xb37f8BAGCf0eMTOH5szf154KmnNgKcnLb+Fzi2AfXktbN7fJelwTAiO/W5uQ2KINXRYu+znqo/WTAdLadURHmy3qciazd3bra4T3w16/f7t7Ms9U5gfJu10955sx1r3vmhBAAAAAAAgId20J1iZbDowNvIjuH427Gr5l/eiC+8OplZON8sVjx/qr9y+Pj+YRItT+NqAM+kkZs3AAAAAID6yfx1FwCAI97/dCh1/ub6SA0AAAAAAAAAgNoT/wcAAAAAAACA+hP/BwAAAAAAAID6E/8HAAAAAAAAgPoT/wcAAAAAAACA+hP/BwAAAAAAAID6E/8HAAAAAAAAgPoT/wcAAAAAAACA+hP/BwAAAAAAAID6E/8HAAAAAAAAgPoT/wcAAAAAAACA+hutp5SiQpYAAAAAAAAAQO2MIpZiT804flnAE2fhwjOeAZXr76kOAAAAAAAA8FjNf4N/l0NE3U/vuVQskLpSd4/Yh2xu9xTu0tFeeNYsLI2f/VMdNxTzj6Je9E/+6pp6Nn3awW3A54goe4Bss6v+PGsjQGMAAAAAAOBp5XEgwH6e7J7rwEQHRb/XvAMAAAAAAAA8yzoDeQDwVGjIAgAAAAAAAACoPfF/AAAAAAAAAKg/8X8AAAAAAAAAqD/xfwAAAAAAAACoP/F/AAAAAAAAAKg/8X8AAAAAAAAAqD/xfwAAAAAAAACoP/F/AAAAAAAAAKg/8X8AAAAAAAAAqD/xfwAAAAAAAACoP/F/AAAAAAAAAKg/8X8AAAAAAAAAqL/GSkSkClkCAAAAAAAAALXTSAAAAAAAAABA3Y1kAQAAAAAAAADUX8RSXZ9dsHC9+M8Fg2Ex/em1lAZpEBGttcrVjZqLEa+k0XpKw9mG4zWx4ukPUMhkAQAAAAAAABzBqbSe3//rXOS9HxGdo4TqR2XkutCdBu+LaPZw/lBbO7cbHnh2C7N7AIo4evEznllqLqWUp/LnYOtpM2bnOH66wI1+9GO4sOuISwv/TOlumu56FDv3NZhc4mR9v7zYIrafr40j/Cccvj9Xns3t3mu99E7qxUv3bqS0/ouNH/08++RGemfQ+nsx/5uNXsQPGulynPvv3ZTW37zd+1ovrqaYpP/122X6Xpx779Z3zr/3YOPKW1lkaRDf31pPaf3j/msRsVGkL+d/f+/m4sJsPm1cfSsr16e8m9Ldj/KsnyIuR3nXw83Is3EhxLd/2V773ks3m/cj/THKUummdP9qKhIOImuOU0Xjwb3y+oqt735rpTetVbF9n8R4x9crRfO77TKqVOZpDclv5bfK18lMnk+q0K18UpxF/RrGXE0Zxtqx3tWSj+vxbL4XaasfKb0dRbtLW73JsfPGg177H+OmGKlfvS1msllt7JEJm9XOJqXR+Fkfo1H66uy5H1v3Xx5+uJmGLw9jro2u7Loj4PnuR6+f+e3d261+eazNhzrL7X83MohoHpS4PddV8ki1it61//pw1g7z6p1U/26Nm2llST57B5rUvuG0XqSU/rPd7jYrqWcbd+beJQ77BgPMDwn37/8BAGCf0eMTOH4cPlufv9VGgJOzqf8Fjm1APXkd7B7f5dF57GPMaWy/MTvjvNvtXj6h8W2+GXvnzXaseeeHEgAAAAAAAB7aQXeKlcGiadBoEOeLb2dtpGOL2MyOtf391a3P/zD96c3JzIP3t4oV797vrh8+vn+YRL5bBuj/AQAAAABqJvfHXQAAHkX82zfXAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACeAgkAAAAAAAAAqLuRLAAAAAAAAACA2hv9D1iu/VAYaAYA", "base64")); } }); // netlify/functions/node_modules/@mongodb-js/saslprep/dist/node.js var require_node = __commonJS({ "netlify/functions/node_modules/@mongodb-js/saslprep/dist/node.js"(exports2, module2) { "use strict"; var __importDefault = exports2 && exports2.__importDefault || function(mod) { return mod && mod.__esModule ? mod : { "default": mod }; }; var index_1 = __importDefault(require_dist()); var memory_code_points_1 = require_memory_code_points(); var code_points_data_1 = __importDefault(require_code_points_data()); var codePoints = (0, memory_code_points_1.createMemoryCodePoints)(code_points_data_1.default); function saslprep(input, opts) { return (0, index_1.default)(codePoints, input, opts); } saslprep.saslprep = saslprep; saslprep.default = saslprep; module2.exports = saslprep; } }); // netlify/functions/node_modules/mongodb/lib/cmap/auth/scram.js var require_scram = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/auth/scram.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ScramSHA256 = exports2.ScramSHA1 = void 0; var saslprep_1 = require_node(); var crypto = require("crypto"); var bson_1 = require_bson2(); var error_1 = require_error(); var utils_1 = require_utils(); var auth_provider_1 = require_auth_provider(); var providers_1 = require_providers(); var ScramSHA = class extends auth_provider_1.AuthProvider { constructor(cryptoMethod) { super(); this.cryptoMethod = cryptoMethod || "sha1"; } async prepare(handshakeDoc, authContext) { const cryptoMethod = this.cryptoMethod; const credentials = authContext.credentials; if (!credentials) { throw new error_1.MongoMissingCredentialsError("AuthContext must provide credentials."); } const nonce = await (0, utils_1.randomBytes)(24); authContext.nonce = nonce; const request = { ...handshakeDoc, speculativeAuthenticate: { ...makeFirstMessage(cryptoMethod, credentials, nonce), db: credentials.source } }; return request; } async auth(authContext) { const { reauthenticating, response } = authContext; if (response?.speculativeAuthenticate && !reauthenticating) { return await continueScramConversation(this.cryptoMethod, response.speculativeAuthenticate, authContext); } return await executeScram(this.cryptoMethod, authContext); } }; function cleanUsername(username) { return username.replace("=", "=3D").replace(",", "=2C"); } function clientFirstMessageBare(username, nonce) { return Buffer.concat([ Buffer.from("n=", "utf8"), Buffer.from(username, "utf8"), Buffer.from(",r=", "utf8"), Buffer.from(nonce.toString("base64"), "utf8") ]); } function makeFirstMessage(cryptoMethod, credentials, nonce) { const username = cleanUsername(credentials.username); const mechanism = cryptoMethod === "sha1" ? providers_1.AuthMechanism.MONGODB_SCRAM_SHA1 : providers_1.AuthMechanism.MONGODB_SCRAM_SHA256; return { saslStart: 1, mechanism, payload: new bson_1.Binary(Buffer.concat([Buffer.from("n,,", "utf8"), clientFirstMessageBare(username, nonce)])), autoAuthorize: 1, options: { skipEmptyExchange: true } }; } async function executeScram(cryptoMethod, authContext) { const { connection, credentials } = authContext; if (!credentials) { throw new error_1.MongoMissingCredentialsError("AuthContext must provide credentials."); } if (!authContext.nonce) { throw new error_1.MongoInvalidArgumentError("AuthContext must contain a valid nonce property"); } const nonce = authContext.nonce; const db = credentials.source; const saslStartCmd = makeFirstMessage(cryptoMethod, credentials, nonce); const response = await connection.command((0, utils_1.ns)(`${db}.$cmd`), saslStartCmd, void 0); await continueScramConversation(cryptoMethod, response, authContext); } async function continueScramConversation(cryptoMethod, response, authContext) { const connection = authContext.connection; const credentials = authContext.credentials; if (!credentials) { throw new error_1.MongoMissingCredentialsError("AuthContext must provide credentials."); } if (!authContext.nonce) { throw new error_1.MongoInvalidArgumentError("Unable to continue SCRAM without valid nonce"); } const nonce = authContext.nonce; const db = credentials.source; const username = cleanUsername(credentials.username); const password = credentials.password; const processedPassword = cryptoMethod === "sha256" ? (0, saslprep_1.saslprep)(password) : passwordDigest(username, password); const payload = Buffer.isBuffer(response.payload) ? new bson_1.Binary(response.payload) : response.payload; const dict = parsePayload(payload); const iterations = parseInt(dict.i, 10); if (iterations && iterations < 4096) { throw new error_1.MongoRuntimeError(`Server returned an invalid iteration count ${iterations}`); } const salt = dict.s; const rnonce = dict.r; if (rnonce.startsWith("nonce")) { throw new error_1.MongoRuntimeError(`Server returned an invalid nonce: ${rnonce}`); } const withoutProof = `c=biws,r=${rnonce}`; const saltedPassword = HI(processedPassword, Buffer.from(salt, "base64"), iterations, cryptoMethod); const clientKey = HMAC(cryptoMethod, saltedPassword, "Client Key"); const serverKey = HMAC(cryptoMethod, saltedPassword, "Server Key"); const storedKey = H(cryptoMethod, clientKey); const authMessage = [ clientFirstMessageBare(username, nonce), payload.toString("utf8"), withoutProof ].join(","); const clientSignature = HMAC(cryptoMethod, storedKey, authMessage); const clientProof = `p=${xor(clientKey, clientSignature)}`; const clientFinal = [withoutProof, clientProof].join(","); const serverSignature = HMAC(cryptoMethod, serverKey, authMessage); const saslContinueCmd = { saslContinue: 1, conversationId: response.conversationId, payload: new bson_1.Binary(Buffer.from(clientFinal)) }; const r = await connection.command((0, utils_1.ns)(`${db}.$cmd`), saslContinueCmd, void 0); const parsedResponse = parsePayload(r.payload); if (!compareDigest(Buffer.from(parsedResponse.v, "base64"), serverSignature)) { throw new error_1.MongoRuntimeError("Server returned an invalid signature"); } if (r.done !== false) { return; } const retrySaslContinueCmd = { saslContinue: 1, conversationId: r.conversationId, payload: Buffer.alloc(0) }; await connection.command((0, utils_1.ns)(`${db}.$cmd`), retrySaslContinueCmd, void 0); } function parsePayload(payload) { const payloadStr = payload.toString("utf8"); const dict = {}; const parts = payloadStr.split(","); for (let i = 0; i < parts.length; i++) { const valueParts = (parts[i].match(/^([^=]*)=(.*)$/) ?? []).slice(1); dict[valueParts[0]] = valueParts[1]; } return dict; } function passwordDigest(username, password) { if (typeof username !== "string") { throw new error_1.MongoInvalidArgumentError("Username must be a string"); } if (typeof password !== "string") { throw new error_1.MongoInvalidArgumentError("Password must be a string"); } if (password.length === 0) { throw new error_1.MongoInvalidArgumentError("Password cannot be empty"); } let md5; try { md5 = crypto.createHash("md5"); } catch (err) { if (crypto.getFips()) { throw new Error("Auth mechanism SCRAM-SHA-1 is not supported in FIPS mode"); } throw err; } md5.update(`${username}:mongo:${password}`, "utf8"); return md5.digest("hex"); } function xor(a, b) { if (!Buffer.isBuffer(a)) { a = Buffer.from(a); } if (!Buffer.isBuffer(b)) { b = Buffer.from(b); } const length = Math.max(a.length, b.length); const res = []; for (let i = 0; i < length; i += 1) { res.push(a[i] ^ b[i]); } return Buffer.from(res).toString("base64"); } function H(method, text) { return crypto.createHash(method).update(text).digest(); } function HMAC(method, key, text) { return crypto.createHmac(method, key).update(text).digest(); } var _hiCache = {}; var _hiCacheCount = 0; function _hiCachePurge() { _hiCache = {}; _hiCacheCount = 0; } var hiLengthMap = { sha256: 32, sha1: 20 }; function HI(data, salt, iterations, cryptoMethod) { const key = [data, salt.toString("base64"), iterations].join("_"); if (_hiCache[key] != null) { return _hiCache[key]; } const saltedData = crypto.pbkdf2Sync(data, salt, iterations, hiLengthMap[cryptoMethod], cryptoMethod); if (_hiCacheCount >= 200) { _hiCachePurge(); } _hiCache[key] = saltedData; _hiCacheCount += 1; return saltedData; } function compareDigest(lhs, rhs) { if (lhs.length !== rhs.length) { return false; } if (typeof crypto.timingSafeEqual === "function") { return crypto.timingSafeEqual(lhs, rhs); } let result = 0; for (let i = 0; i < lhs.length; i++) { result |= lhs[i] ^ rhs[i]; } return result === 0; } var ScramSHA1 = class extends ScramSHA { constructor() { super("sha1"); } }; exports2.ScramSHA1 = ScramSHA1; var ScramSHA256 = class extends ScramSHA { constructor() { super("sha256"); } }; exports2.ScramSHA256 = ScramSHA256; } }); // netlify/functions/node_modules/mongodb/lib/cmap/auth/x509.js var require_x509 = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cmap/auth/x509.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.X509 = void 0; var error_1 = require_error(); var utils_1 = require_utils(); var auth_provider_1 = require_auth_provider(); var X509 = class extends auth_provider_1.AuthProvider { async prepare(handshakeDoc, authContext) { const { credentials } = authContext; if (!credentials) { throw new error_1.MongoMissingCredentialsError("AuthContext must provide credentials."); } return { ...handshakeDoc, speculativeAuthenticate: x509AuthenticateCommand(credentials) }; } async auth(authContext) { const connection = authContext.connection; const credentials = authContext.credentials; if (!credentials) { throw new error_1.MongoMissingCredentialsError("AuthContext must provide credentials."); } const response = authContext.response; if (response?.speculativeAuthenticate) { return; } await connection.command((0, utils_1.ns)("$external.$cmd"), x509AuthenticateCommand(credentials), void 0); } }; exports2.X509 = X509; function x509AuthenticateCommand(credentials) { const command = { authenticate: 1, mechanism: "MONGODB-X509" }; if (credentials.username) { command.user = credentials.username; } return command; } } }); // netlify/functions/node_modules/mongodb/lib/mongo_client_auth_providers.js var require_mongo_client_auth_providers = __commonJS({ "netlify/functions/node_modules/mongodb/lib/mongo_client_auth_providers.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.MongoClientAuthProviders = void 0; var gssapi_1 = require_gssapi(); var mongodb_aws_1 = require_mongodb_aws(); var mongodb_oidc_1 = require_mongodb_oidc(); var automated_callback_workflow_1 = require_automated_callback_workflow(); var human_callback_workflow_1 = require_human_callback_workflow(); var token_cache_1 = require_token_cache(); var plain_1 = require_plain(); var providers_1 = require_providers(); var scram_1 = require_scram(); var x509_1 = require_x509(); var error_1 = require_error(); var AUTH_PROVIDERS = /* @__PURE__ */ new Map([ [ providers_1.AuthMechanism.MONGODB_AWS, ({ AWS_CREDENTIAL_PROVIDER }) => new mongodb_aws_1.MongoDBAWS(AWS_CREDENTIAL_PROVIDER) ], [ providers_1.AuthMechanism.MONGODB_CR, () => { throw new error_1.MongoInvalidArgumentError("MONGODB-CR is no longer a supported auth mechanism in MongoDB 4.0+"); } ], [providers_1.AuthMechanism.MONGODB_GSSAPI, () => new gssapi_1.GSSAPI()], [providers_1.AuthMechanism.MONGODB_OIDC, (properties) => new mongodb_oidc_1.MongoDBOIDC(getWorkflow(properties))], [providers_1.AuthMechanism.MONGODB_PLAIN, () => new plain_1.Plain()], [providers_1.AuthMechanism.MONGODB_SCRAM_SHA1, () => new scram_1.ScramSHA1()], [providers_1.AuthMechanism.MONGODB_SCRAM_SHA256, () => new scram_1.ScramSHA256()], [providers_1.AuthMechanism.MONGODB_X509, () => new x509_1.X509()] ]); var MongoClientAuthProviders = class { constructor() { this.existingProviders = /* @__PURE__ */ new Map(); } /** * Get or create an authentication provider based on the provided mechanism. * We don't want to create all providers at once, as some providers may not be used. * @param name - The name of the provider to get or create. * @param credentials - The credentials. * @returns The provider. * @throws MongoInvalidArgumentError if the mechanism is not supported. * @internal */ getOrCreateProvider(name, authMechanismProperties) { const authProvider = this.existingProviders.get(name); if (authProvider) { return authProvider; } const providerFunction = AUTH_PROVIDERS.get(name); if (!providerFunction) { throw new error_1.MongoInvalidArgumentError(`authMechanism ${name} not supported`); } const provider = providerFunction(authMechanismProperties); this.existingProviders.set(name, provider); return provider; } }; exports2.MongoClientAuthProviders = MongoClientAuthProviders; function getWorkflow(authMechanismProperties) { if (authMechanismProperties.OIDC_HUMAN_CALLBACK) { return new human_callback_workflow_1.HumanCallbackWorkflow(new token_cache_1.TokenCache(), authMechanismProperties.OIDC_HUMAN_CALLBACK); } else if (authMechanismProperties.OIDC_CALLBACK) { return new automated_callback_workflow_1.AutomatedCallbackWorkflow(new token_cache_1.TokenCache(), authMechanismProperties.OIDC_CALLBACK); } else { const environment = authMechanismProperties.ENVIRONMENT; const workflow = mongodb_oidc_1.OIDC_WORKFLOWS.get(environment)?.(); if (!workflow) { throw new error_1.MongoInvalidArgumentError(`Could not load workflow for environment ${authMechanismProperties.ENVIRONMENT}`); } return workflow; } } } }); // netlify/functions/node_modules/mongodb/lib/gridfs/download.js var require_download = __commonJS({ "netlify/functions/node_modules/mongodb/lib/gridfs/download.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.GridFSBucketReadStream = void 0; var stream_1 = require("stream"); var abstract_cursor_1 = require_abstract_cursor(); var error_1 = require_error(); var timeout_1 = require_timeout(); var GridFSBucketReadStream = class extends stream_1.Readable { /** * @param chunks - Handle for chunks collection * @param files - Handle for files collection * @param readPreference - The read preference to use * @param filter - The filter to use to find the file document * @internal */ constructor(chunks, files, readPreference, filter, options) { super({ emitClose: true }); this.s = { bytesToTrim: 0, bytesToSkip: 0, bytesRead: 0, chunks, expected: 0, files, filter, init: false, expectedEnd: 0, options: { start: 0, end: 0, ...options }, readPreference, timeoutContext: options?.timeoutMS != null ? new timeout_1.CSOTTimeoutContext({ timeoutMS: options.timeoutMS, serverSelectionTimeoutMS: 0 }) : void 0 }; } /** * Reads from the cursor and pushes to the stream. * Private Impl, do not call directly * @internal */ _read() { if (this.destroyed) return; waitForFile(this, () => doRead(this)); } /** * Sets the 0-based offset in bytes to start streaming from. Throws * an error if this stream has entered flowing mode * (e.g. if you've already called `on('data')`) * * @param start - 0-based offset in bytes to start streaming from */ start(start = 0) { throwIfInitialized(this); this.s.options.start = start; return this; } /** * Sets the 0-based offset in bytes to start streaming from. Throws * an error if this stream has entered flowing mode * (e.g. if you've already called `on('data')`) * * @param end - Offset in bytes to stop reading at */ end(end = 0) { throwIfInitialized(this); this.s.options.end = end; return this; } /** * Marks this stream as aborted (will never push another `data` event) * and kills the underlying cursor. Will emit the 'end' event, and then * the 'close' event once the cursor is successfully killed. */ async abort() { this.push(null); this.destroy(); const remainingTimeMS = this.s.timeoutContext?.getRemainingTimeMSOrThrow(); await this.s.cursor?.close({ timeoutMS: remainingTimeMS }); } }; exports2.GridFSBucketReadStream = GridFSBucketReadStream; GridFSBucketReadStream.FILE = "file"; function throwIfInitialized(stream) { if (stream.s.init) { throw new error_1.MongoGridFSStreamError("Options cannot be changed after the stream is initialized"); } } function doRead(stream) { if (stream.destroyed) return; if (!stream.s.cursor) return; if (!stream.s.file) return; const handleReadResult = (doc) => { if (stream.destroyed) return; if (!doc) { stream.push(null); stream.s.cursor?.close().then(void 0, (error) => stream.destroy(error)); return; } if (!stream.s.file) return; const bytesRemaining = stream.s.file.length - stream.s.bytesRead; const expectedN = stream.s.expected++; const expectedLength = Math.min(stream.s.file.chunkSize, bytesRemaining); if (doc.n > expectedN) { return stream.destroy(new error_1.MongoGridFSChunkError(`ChunkIsMissing: Got unexpected n: ${doc.n}, expected: ${expectedN}`)); } if (doc.n < expectedN) { return stream.destroy(new error_1.MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${doc.n}, expected: ${expectedN}`)); } let buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer; if (buf.byteLength !== expectedLength) { if (bytesRemaining <= 0) { return stream.destroy(new error_1.MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${doc.n}, expected file length ${stream.s.file.length} bytes but already read ${stream.s.bytesRead} bytes`)); } return stream.destroy(new error_1.MongoGridFSChunkError(`ChunkIsWrongSize: Got unexpected length: ${buf.byteLength}, expected: ${expectedLength}`)); } stream.s.bytesRead += buf.byteLength; if (buf.byteLength === 0) { return stream.push(null); } let sliceStart = null; let sliceEnd = null; if (stream.s.bytesToSkip != null) { sliceStart = stream.s.bytesToSkip; stream.s.bytesToSkip = 0; } const atEndOfStream = expectedN === stream.s.expectedEnd - 1; const bytesLeftToRead = stream.s.options.end - stream.s.bytesToSkip; if (atEndOfStream && stream.s.bytesToTrim != null) { sliceEnd = stream.s.file.chunkSize - stream.s.bytesToTrim; } else if (stream.s.options.end && bytesLeftToRead < doc.data.byteLength) { sliceEnd = bytesLeftToRead; } if (sliceStart != null || sliceEnd != null) { buf = buf.slice(sliceStart || 0, sliceEnd || buf.byteLength); } stream.push(buf); return; }; stream.s.cursor.next().then(handleReadResult, (error) => { if (stream.destroyed) return; stream.destroy(error); }); } function init(stream) { const findOneOptions = {}; if (stream.s.readPreference) { findOneOptions.readPreference = stream.s.readPreference; } if (stream.s.options && stream.s.options.sort) { findOneOptions.sort = stream.s.options.sort; } if (stream.s.options && stream.s.options.skip) { findOneOptions.skip = stream.s.options.skip; } const handleReadResult = (doc) => { if (stream.destroyed) return; if (!doc) { const identifier = stream.s.filter._id ? stream.s.filter._id.toString() : stream.s.filter.filename; const errmsg = `FileNotFound: file ${identifier} was not found`; const err = new error_1.MongoRuntimeError(errmsg); err.code = "ENOENT"; return stream.destroy(err); } if (doc.length <= 0) { stream.push(null); return; } if (stream.destroyed) { stream.destroy(); return; } try { stream.s.bytesToSkip = handleStartOption(stream, doc, stream.s.options); } catch (error) { return stream.destroy(error); } const filter = { files_id: doc._id }; if (stream.s.options && stream.s.options.start != null) { const skip = Math.floor(stream.s.options.start / doc.chunkSize); if (skip > 0) { filter["n"] = { $gte: skip }; } } let remainingTimeMS2; try { remainingTimeMS2 = stream.s.timeoutContext?.getRemainingTimeMSOrThrow(`Download timed out after ${stream.s.timeoutContext?.timeoutMS}ms`); } catch (error) { return stream.destroy(error); } stream.s.cursor = stream.s.chunks.find(filter, { timeoutMode: stream.s.options.timeoutMS != null ? abstract_cursor_1.CursorTimeoutMode.LIFETIME : void 0, timeoutMS: remainingTimeMS2 }).sort({ n: 1 }); if (stream.s.readPreference) { stream.s.cursor.withReadPreference(stream.s.readPreference); } stream.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); stream.s.file = doc; try { stream.s.bytesToTrim = handleEndOption(stream, doc, stream.s.cursor, stream.s.options); } catch (error) { return stream.destroy(error); } stream.emit(GridFSBucketReadStream.FILE, doc); return; }; let remainingTimeMS; try { remainingTimeMS = stream.s.timeoutContext?.getRemainingTimeMSOrThrow(`Download timed out after ${stream.s.timeoutContext?.timeoutMS}ms`); } catch (error) { if (!stream.destroyed) stream.destroy(error); return; } findOneOptions.timeoutMS = remainingTimeMS; stream.s.files.findOne(stream.s.filter, findOneOptions).then(handleReadResult, (error) => { if (stream.destroyed) return; stream.destroy(error); }); } function waitForFile(stream, callback) { if (stream.s.file) { return callback(); } if (!stream.s.init) { init(stream); stream.s.init = true; } stream.once("file", () => { callback(); }); } function handleStartOption(stream, doc, options) { if (options && options.start != null) { if (options.start > doc.length) { throw new error_1.MongoInvalidArgumentError(`Stream start (${options.start}) must not be more than the length of the file (${doc.length})`); } if (options.start < 0) { throw new error_1.MongoInvalidArgumentError(`Stream start (${options.start}) must not be negative`); } if (options.end != null && options.end < options.start) { throw new error_1.MongoInvalidArgumentError(`Stream start (${options.start}) must not be greater than stream end (${options.end})`); } stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize; stream.s.expected = Math.floor(options.start / doc.chunkSize); return options.start - stream.s.bytesRead; } throw new error_1.MongoInvalidArgumentError("Start option must be defined"); } function handleEndOption(stream, doc, cursor, options) { if (options && options.end != null) { if (options.end > doc.length) { throw new error_1.MongoInvalidArgumentError(`Stream end (${options.end}) must not be more than the length of the file (${doc.length})`); } if (options.start == null || options.start < 0) { throw new error_1.MongoInvalidArgumentError(`Stream end (${options.end}) must not be negative`); } const start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0; cursor.limit(Math.ceil(options.end / doc.chunkSize) - start); stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize); return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end; } throw new error_1.MongoInvalidArgumentError("End option must be defined"); } } }); // netlify/functions/node_modules/mongodb/lib/gridfs/upload.js var require_upload = __commonJS({ "netlify/functions/node_modules/mongodb/lib/gridfs/upload.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.GridFSBucketWriteStream = void 0; var stream_1 = require("stream"); var bson_1 = require_bson2(); var abstract_cursor_1 = require_abstract_cursor(); var error_1 = require_error(); var timeout_1 = require_timeout(); var utils_1 = require_utils(); var write_concern_1 = require_write_concern(); var GridFSBucketWriteStream = class extends stream_1.Writable { /** * @param bucket - Handle for this stream's corresponding bucket * @param filename - The value of the 'filename' key in the files doc * @param options - Optional settings. * @internal */ constructor(bucket, filename, options) { super(); this.gridFSFile = null; options = options ?? {}; this.bucket = bucket; this.chunks = bucket.s._chunksCollection; this.filename = filename; this.files = bucket.s._filesCollection; this.options = options; this.writeConcern = write_concern_1.WriteConcern.fromOptions(options) || bucket.s.options.writeConcern; this.done = false; this.id = options.id ? options.id : new bson_1.ObjectId(); this.chunkSizeBytes = options.chunkSizeBytes || this.bucket.s.options.chunkSizeBytes; this.bufToStore = Buffer.alloc(this.chunkSizeBytes); this.length = 0; this.n = 0; this.pos = 0; this.state = { streamEnd: false, outstandingRequests: 0, errored: false, aborted: false }; if (options.timeoutMS != null) this.timeoutContext = new timeout_1.CSOTTimeoutContext({ timeoutMS: options.timeoutMS, serverSelectionTimeoutMS: (0, utils_1.resolveTimeoutOptions)(this.bucket.s.db.client, {}).serverSelectionTimeoutMS }); } /** * @internal * * The stream is considered constructed when the indexes are done being created */ _construct(callback) { if (!this.bucket.s.calledOpenUploadStream) { this.bucket.s.calledOpenUploadStream = true; checkIndexes(this).then(() => { this.bucket.s.checkedIndexes = true; this.bucket.emit("index"); callback(); }, (error) => { if (error instanceof error_1.MongoOperationTimeoutError) { return handleError(this, error, callback); } (0, utils_1.squashError)(error); callback(); }); } else { return process.nextTick(callback); } } /** * @internal * Write a buffer to the stream. * * @param chunk - Buffer to write * @param encoding - Optional encoding for the buffer * @param callback - Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. */ _write(chunk, encoding, callback) { doWrite(this, chunk, encoding, callback); } /** @internal */ _final(callback) { if (this.state.streamEnd) { return process.nextTick(callback); } this.state.streamEnd = true; writeRemnant(this, callback); } /** * Places this write stream into an aborted state (all future writes fail) * and deletes all chunks that have already been written. */ async abort() { if (this.state.streamEnd) { throw new error_1.MongoAPIError("Cannot abort a stream that has already completed"); } if (this.state.aborted) { throw new error_1.MongoAPIError("Cannot call abort() on a stream twice"); } this.state.aborted = true; const remainingTimeMS = this.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${this.timeoutContext?.timeoutMS}ms`); await this.chunks.deleteMany({ files_id: this.id }, { timeoutMS: remainingTimeMS }); } }; exports2.GridFSBucketWriteStream = GridFSBucketWriteStream; function handleError(stream, error, callback) { if (stream.state.errored) { process.nextTick(callback); return; } stream.state.errored = true; process.nextTick(callback, error); } function createChunkDoc(filesId, n, data) { return { _id: new bson_1.ObjectId(), files_id: filesId, n, data }; } async function checkChunksIndex(stream) { const index = { files_id: 1, n: 1 }; let remainingTimeMS; remainingTimeMS = stream.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`); let indexes; try { indexes = await stream.chunks.listIndexes({ timeoutMode: remainingTimeMS != null ? abstract_cursor_1.CursorTimeoutMode.LIFETIME : void 0, timeoutMS: remainingTimeMS }).toArray(); } catch (error) { if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { indexes = []; } else { throw error; } } const hasChunksIndex = !!indexes.find((index2) => { const keys = Object.keys(index2.key); if (keys.length === 2 && index2.key.files_id === 1 && index2.key.n === 1) { return true; } return false; }); if (!hasChunksIndex) { remainingTimeMS = stream.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`); await stream.chunks.createIndex(index, { ...stream.writeConcern, background: true, unique: true, timeoutMS: remainingTimeMS }); } } function checkDone(stream, callback) { if (stream.done) { return process.nextTick(callback); } if (stream.state.streamEnd && stream.state.outstandingRequests === 0 && !stream.state.errored) { stream.done = true; const gridFSFile = createFilesDoc(stream.id, stream.length, stream.chunkSizeBytes, stream.filename, stream.options.contentType, stream.options.aliases, stream.options.metadata); if (isAborted(stream, callback)) { return; } const remainingTimeMS = stream.timeoutContext?.remainingTimeMS; if (remainingTimeMS != null && remainingTimeMS <= 0) { return handleError(stream, new error_1.MongoOperationTimeoutError(`Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`), callback); } stream.files.insertOne(gridFSFile, { writeConcern: stream.writeConcern, timeoutMS: remainingTimeMS }).then(() => { stream.gridFSFile = gridFSFile; callback(); }, (error) => { return handleError(stream, error, callback); }); return; } process.nextTick(callback); } async function checkIndexes(stream) { let remainingTimeMS = stream.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`); const doc = await stream.files.findOne({}, { projection: { _id: 1 }, timeoutMS: remainingTimeMS }); if (doc != null) { return; } const index = { filename: 1, uploadDate: 1 }; let indexes; remainingTimeMS = stream.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`); const listIndexesOptions = { timeoutMode: remainingTimeMS != null ? abstract_cursor_1.CursorTimeoutMode.LIFETIME : void 0, timeoutMS: remainingTimeMS }; try { indexes = await stream.files.listIndexes(listIndexesOptions).toArray(); } catch (error) { if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { indexes = []; } else { throw error; } } const hasFileIndex = !!indexes.find((index2) => { const keys = Object.keys(index2.key); if (keys.length === 2 && index2.key.filename === 1 && index2.key.uploadDate === 1) { return true; } return false; }); if (!hasFileIndex) { remainingTimeMS = stream.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`); await stream.files.createIndex(index, { background: false, timeoutMS: remainingTimeMS }); } await checkChunksIndex(stream); } function createFilesDoc(_id, length, chunkSize, filename, contentType, aliases, metadata) { const ret = { _id, length, chunkSize, uploadDate: /* @__PURE__ */ new Date(), filename }; if (contentType) { ret.contentType = contentType; } if (aliases) { ret.aliases = aliases; } if (metadata) { ret.metadata = metadata; } return ret; } function doWrite(stream, chunk, encoding, callback) { if (isAborted(stream, callback)) { return; } const inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding); stream.length += inputBuf.length; if (stream.pos + inputBuf.length < stream.chunkSizeBytes) { inputBuf.copy(stream.bufToStore, stream.pos); stream.pos += inputBuf.length; process.nextTick(callback); return; } let inputBufRemaining = inputBuf.length; let spaceRemaining = stream.chunkSizeBytes - stream.pos; let numToCopy = Math.min(spaceRemaining, inputBuf.length); let outstandingRequests = 0; while (inputBufRemaining > 0) { const inputBufPos = inputBuf.length - inputBufRemaining; inputBuf.copy(stream.bufToStore, stream.pos, inputBufPos, inputBufPos + numToCopy); stream.pos += numToCopy; spaceRemaining -= numToCopy; let doc; if (spaceRemaining === 0) { doc = createChunkDoc(stream.id, stream.n, Buffer.from(stream.bufToStore)); const remainingTimeMS = stream.timeoutContext?.remainingTimeMS; if (remainingTimeMS != null && remainingTimeMS <= 0) { return handleError(stream, new error_1.MongoOperationTimeoutError(`Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`), callback); } ++stream.state.outstandingRequests; ++outstandingRequests; if (isAborted(stream, callback)) { return; } stream.chunks.insertOne(doc, { writeConcern: stream.writeConcern, timeoutMS: remainingTimeMS }).then(() => { --stream.state.outstandingRequests; --outstandingRequests; if (!outstandingRequests) { checkDone(stream, callback); } }, (error) => { return handleError(stream, error, callback); }); spaceRemaining = stream.chunkSizeBytes; stream.pos = 0; ++stream.n; } inputBufRemaining -= numToCopy; numToCopy = Math.min(spaceRemaining, inputBufRemaining); } } function writeRemnant(stream, callback) { if (stream.pos === 0) { return checkDone(stream, callback); } const remnant = Buffer.alloc(stream.pos); stream.bufToStore.copy(remnant, 0, 0, stream.pos); const doc = createChunkDoc(stream.id, stream.n, remnant); if (isAborted(stream, callback)) { return; } const remainingTimeMS = stream.timeoutContext?.remainingTimeMS; if (remainingTimeMS != null && remainingTimeMS <= 0) { return handleError(stream, new error_1.MongoOperationTimeoutError(`Upload timed out after ${stream.timeoutContext?.timeoutMS}ms`), callback); } ++stream.state.outstandingRequests; stream.chunks.insertOne(doc, { writeConcern: stream.writeConcern, timeoutMS: remainingTimeMS }).then(() => { --stream.state.outstandingRequests; checkDone(stream, callback); }, (error) => { return handleError(stream, error, callback); }); } function isAborted(stream, callback) { if (stream.state.aborted) { process.nextTick(callback, new error_1.MongoAPIError("Stream has been aborted")); return true; } return false; } } }); // netlify/functions/node_modules/mongodb/lib/gridfs/index.js var require_gridfs = __commonJS({ "netlify/functions/node_modules/mongodb/lib/gridfs/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.GridFSBucket = void 0; var error_1 = require_error(); var mongo_types_1 = require_mongo_types(); var timeout_1 = require_timeout(); var utils_1 = require_utils(); var write_concern_1 = require_write_concern(); var download_1 = require_download(); var upload_1 = require_upload(); var DEFAULT_GRIDFS_BUCKET_OPTIONS = { bucketName: "fs", chunkSizeBytes: 255 * 1024 }; var GridFSBucket = class extends mongo_types_1.TypedEventEmitter { constructor(db, options) { super(); this.on("error", utils_1.noop); this.setMaxListeners(0); const privateOptions = (0, utils_1.resolveOptions)(db, { ...DEFAULT_GRIDFS_BUCKET_OPTIONS, ...options, writeConcern: write_concern_1.WriteConcern.fromOptions(options) }); this.s = { db, options: privateOptions, _chunksCollection: db.collection(privateOptions.bucketName + ".chunks"), _filesCollection: db.collection(privateOptions.bucketName + ".files"), checkedIndexes: false, calledOpenUploadStream: false }; } /** * Returns a writable stream (GridFSBucketWriteStream) for writing * buffers to GridFS. The stream's 'id' property contains the resulting * file's id. * * @param filename - The value of the 'filename' key in the files doc * @param options - Optional settings. */ openUploadStream(filename, options) { return new upload_1.GridFSBucketWriteStream(this, filename, { timeoutMS: this.s.options.timeoutMS, ...options }); } /** * Returns a writable stream (GridFSBucketWriteStream) for writing * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting * file's id. */ openUploadStreamWithId(id, filename, options) { return new upload_1.GridFSBucketWriteStream(this, filename, { timeoutMS: this.s.options.timeoutMS, ...options, id }); } /** Returns a readable stream (GridFSBucketReadStream) for streaming file data from GridFS. */ openDownloadStream(id, options) { return new download_1.GridFSBucketReadStream(this.s._chunksCollection, this.s._filesCollection, this.s.options.readPreference, { _id: id }, { timeoutMS: this.s.options.timeoutMS, ...options }); } /** * Deletes a file with the given id * * @param id - The id of the file doc */ async delete(id, options) { const { timeoutMS } = (0, utils_1.resolveOptions)(this.s.db, options); let timeoutContext = void 0; if (timeoutMS) { timeoutContext = new timeout_1.CSOTTimeoutContext({ timeoutMS, serverSelectionTimeoutMS: this.s.db.client.s.options.serverSelectionTimeoutMS }); } const { deletedCount } = await this.s._filesCollection.deleteOne({ _id: id }, { timeoutMS: timeoutContext?.remainingTimeMS }); const remainingTimeMS = timeoutContext?.remainingTimeMS; if (remainingTimeMS != null && remainingTimeMS <= 0) throw new error_1.MongoOperationTimeoutError(`Timed out after ${timeoutMS}ms`); await this.s._chunksCollection.deleteMany({ files_id: id }, { timeoutMS: remainingTimeMS }); if (deletedCount === 0) { throw new error_1.MongoRuntimeError(`File not found for id ${id}`); } } /** Convenience wrapper around find on the files collection */ find(filter = {}, options = {}) { return this.s._filesCollection.find(filter, options); } /** * Returns a readable stream (GridFSBucketReadStream) for streaming the * file with the given name from GridFS. If there are multiple files with * the same name, this will stream the most recent file with the given name * (as determined by the `uploadDate` field). You can set the `revision` * option to change this behavior. */ openDownloadStreamByName(filename, options) { let sort = { uploadDate: -1 }; let skip = void 0; if (options && options.revision != null) { if (options.revision >= 0) { sort = { uploadDate: 1 }; skip = options.revision; } else { skip = -options.revision - 1; } } return new download_1.GridFSBucketReadStream(this.s._chunksCollection, this.s._filesCollection, this.s.options.readPreference, { filename }, { timeoutMS: this.s.options.timeoutMS, ...options, sort, skip }); } /** * Renames the file with the given _id to the given string * * @param id - the id of the file to rename * @param filename - new name for the file */ async rename(id, filename, options) { const filter = { _id: id }; const update = { $set: { filename } }; const { matchedCount } = await this.s._filesCollection.updateOne(filter, update, options); if (matchedCount === 0) { throw new error_1.MongoRuntimeError(`File with id ${id} not found`); } } /** Removes this bucket's files collection, followed by its chunks collection. */ async drop(options) { const { timeoutMS } = (0, utils_1.resolveOptions)(this.s.db, options); let timeoutContext = void 0; if (timeoutMS) { timeoutContext = new timeout_1.CSOTTimeoutContext({ timeoutMS, serverSelectionTimeoutMS: this.s.db.client.s.options.serverSelectionTimeoutMS }); } if (timeoutContext) { await this.s._filesCollection.drop({ timeoutMS: timeoutContext.remainingTimeMS }); const remainingTimeMS = timeoutContext.getRemainingTimeMSOrThrow(`Timed out after ${timeoutMS}ms`); await this.s._chunksCollection.drop({ timeoutMS: remainingTimeMS }); } else { await this.s._filesCollection.drop(); await this.s._chunksCollection.drop(); } } }; exports2.GridFSBucket = GridFSBucket; GridFSBucket.INDEX = "index"; } }); // netlify/functions/node_modules/mongodb/lib/sdam/server_selection_events.js var require_server_selection_events = __commonJS({ "netlify/functions/node_modules/mongodb/lib/sdam/server_selection_events.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.WaitingForSuitableServerEvent = exports2.ServerSelectionSucceededEvent = exports2.ServerSelectionFailedEvent = exports2.ServerSelectionStartedEvent = exports2.ServerSelectionEvent = void 0; var utils_1 = require_utils(); var constants_1 = require_constants(); var ServerSelectionEvent = class { /** @internal */ constructor(selector, topologyDescription, operation) { this.selector = selector; this.operation = operation; this.topologyDescription = topologyDescription; } }; exports2.ServerSelectionEvent = ServerSelectionEvent; var ServerSelectionStartedEvent = class extends ServerSelectionEvent { /** @internal */ constructor(selector, topologyDescription, operation) { super(selector, topologyDescription, operation); this.name = constants_1.SERVER_SELECTION_STARTED; this.message = "Server selection started"; } }; exports2.ServerSelectionStartedEvent = ServerSelectionStartedEvent; var ServerSelectionFailedEvent = class extends ServerSelectionEvent { /** @internal */ constructor(selector, topologyDescription, error, operation) { super(selector, topologyDescription, operation); this.name = constants_1.SERVER_SELECTION_FAILED; this.message = "Server selection failed"; this.failure = error; } }; exports2.ServerSelectionFailedEvent = ServerSelectionFailedEvent; var ServerSelectionSucceededEvent = class extends ServerSelectionEvent { /** @internal */ constructor(selector, topologyDescription, address, operation) { super(selector, topologyDescription, operation); this.name = constants_1.SERVER_SELECTION_SUCCEEDED; this.message = "Server selection succeeded"; const { host, port } = utils_1.HostAddress.fromString(address).toHostPort(); this.serverHost = host; this.serverPort = port; } }; exports2.ServerSelectionSucceededEvent = ServerSelectionSucceededEvent; var WaitingForSuitableServerEvent = class extends ServerSelectionEvent { /** @internal */ constructor(selector, topologyDescription, remainingTimeMS, operation) { super(selector, topologyDescription, operation); this.name = constants_1.WAITING_FOR_SUITABLE_SERVER; this.message = "Waiting for suitable server to become available"; this.remainingTimeMS = remainingTimeMS; } }; exports2.WaitingForSuitableServerEvent = WaitingForSuitableServerEvent; } }); // netlify/functions/node_modules/mongodb/lib/sdam/srv_polling.js var require_srv_polling = __commonJS({ "netlify/functions/node_modules/mongodb/lib/sdam/srv_polling.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.SrvPoller = exports2.SrvPollingEvent = void 0; var dns = require("dns"); var timers_1 = require("timers"); var error_1 = require_error(); var mongo_types_1 = require_mongo_types(); var utils_1 = require_utils(); var SrvPollingEvent = class { constructor(srvRecords) { this.srvRecords = srvRecords; } hostnames() { return new Set(this.srvRecords.map((r) => utils_1.HostAddress.fromSrvRecord(r).toString())); } }; exports2.SrvPollingEvent = SrvPollingEvent; var SrvPoller = class _SrvPoller extends mongo_types_1.TypedEventEmitter { constructor(options) { super(); this.on("error", utils_1.noop); if (!options || !options.srvHost) { throw new error_1.MongoRuntimeError("Options for SrvPoller must exist and include srvHost"); } this.srvHost = options.srvHost; this.srvMaxHosts = options.srvMaxHosts ?? 0; this.srvServiceName = options.srvServiceName ?? "mongodb"; this.rescanSrvIntervalMS = 6e4; this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 1e4; this.haMode = false; this.generation = 0; this._timeout = void 0; } get srvAddress() { return `_${this.srvServiceName}._tcp.${this.srvHost}`; } get intervalMS() { return this.haMode ? this.heartbeatFrequencyMS : this.rescanSrvIntervalMS; } start() { if (!this._timeout) { this.schedule(); } } stop() { if (this._timeout) { (0, timers_1.clearTimeout)(this._timeout); this.generation += 1; this._timeout = void 0; } } // TODO(NODE-4994): implement new logging logic for SrvPoller failures schedule() { if (this._timeout) { (0, timers_1.clearTimeout)(this._timeout); } this._timeout = (0, timers_1.setTimeout)(() => { this._poll().then(void 0, utils_1.squashError); }, this.intervalMS); } success(srvRecords) { this.haMode = false; this.schedule(); this.emit(_SrvPoller.SRV_RECORD_DISCOVERY, new SrvPollingEvent(srvRecords)); } failure() { this.haMode = true; this.schedule(); } async _poll() { const generation = this.generation; let srvRecords; try { srvRecords = await dns.promises.resolveSrv(this.srvAddress); } catch { this.failure(); return; } if (generation !== this.generation) { return; } const finalAddresses = []; for (const record of srvRecords) { try { (0, utils_1.checkParentDomainMatch)(record.name, this.srvHost); finalAddresses.push(record); } catch (error) { (0, utils_1.squashError)(error); } } if (!finalAddresses.length) { this.failure(); return; } this.success(finalAddresses); } }; exports2.SrvPoller = SrvPoller; SrvPoller.SRV_RECORD_DISCOVERY = "srvRecordDiscovery"; } }); // netlify/functions/node_modules/mongodb/lib/index.js var require_lib3 = __commonJS({ "netlify/functions/node_modules/mongodb/lib/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.MongoServerClosedError = exports2.MongoRuntimeError = exports2.MongoParseError = exports2.MongoOperationTimeoutError = exports2.MongoOIDCError = exports2.MongoNotConnectedError = exports2.MongoNetworkTimeoutError = exports2.MongoNetworkError = exports2.MongoMissingDependencyError = exports2.MongoMissingCredentialsError = exports2.MongoKerberosError = exports2.MongoInvalidArgumentError = exports2.MongoGridFSStreamError = exports2.MongoGridFSChunkError = exports2.MongoGCPError = exports2.MongoExpiredSessionError = exports2.MongoError = exports2.MongoDriverError = exports2.MongoDecompressionError = exports2.MongoCursorInUseError = exports2.MongoCursorExhaustedError = exports2.MongoCompatibilityError = exports2.MongoClientClosedError = exports2.MongoClientBulkWriteExecutionError = exports2.MongoClientBulkWriteError = exports2.MongoClientBulkWriteCursorError = exports2.MongoChangeStreamError = exports2.MongoBatchReExecutionError = exports2.MongoAzureError = exports2.MongoAWSError = exports2.MongoAPIError = exports2.ChangeStreamCursor = exports2.ClientEncryption = exports2.MongoBulkWriteError = exports2.UUID = exports2.Timestamp = exports2.ObjectId = exports2.MinKey = exports2.MaxKey = exports2.Long = exports2.Int32 = exports2.Double = exports2.Decimal128 = exports2.DBRef = exports2.Code = exports2.BSONType = exports2.BSONSymbol = exports2.BSONRegExp = exports2.Binary = exports2.BSON = void 0; exports2.CommandFailedEvent = exports2.WriteConcern = exports2.ReadPreference = exports2.ReadConcern = exports2.TopologyType = exports2.ServerType = exports2.ReadPreferenceMode = exports2.ReadConcernLevel = exports2.ProfilingLevel = exports2.ReturnDocument = exports2.SeverityLevel = exports2.MongoLoggableComponent = exports2.ServerApiVersion = exports2.ExplainVerbosity = exports2.MongoErrorLabel = exports2.CursorTimeoutMode = exports2.CURSOR_FLAGS = exports2.Compressor = exports2.AuthMechanism = exports2.GSSAPICanonicalizationValue = exports2.AutoEncryptionLoggerLevel = exports2.BatchType = exports2.UnorderedBulkOperation = exports2.OrderedBulkOperation = exports2.MongoClient = exports2.ListIndexesCursor = exports2.ListCollectionsCursor = exports2.GridFSBucketWriteStream = exports2.GridFSBucketReadStream = exports2.GridFSBucket = exports2.FindCursor = exports2.ExplainableCursor = exports2.Db = exports2.Collection = exports2.ClientSession = exports2.ChangeStream = exports2.CancellationToken = exports2.AggregationCursor = exports2.Admin = exports2.AbstractCursor = exports2.configureExplicitResourceManagement = exports2.MongoWriteConcernError = exports2.MongoUnexpectedServerResponseError = exports2.MongoTransactionError = exports2.MongoTopologyClosedError = exports2.MongoTailableCursorError = exports2.MongoSystemError = exports2.MongoStalePrimaryError = exports2.MongoServerSelectionError = exports2.MongoServerError = void 0; exports2.MongoClientAuthProviders = exports2.MongoCryptKMSRequestNetworkTimeoutError = exports2.MongoCryptInvalidArgumentError = exports2.MongoCryptError = exports2.MongoCryptCreateEncryptedCollectionError = exports2.MongoCryptCreateDataKeyError = exports2.MongoCryptAzureKMSRequestError = exports2.SrvPollingEvent = exports2.WaitingForSuitableServerEvent = exports2.ServerSelectionSucceededEvent = exports2.ServerSelectionStartedEvent = exports2.ServerSelectionFailedEvent = exports2.ServerSelectionEvent = exports2.TopologyOpeningEvent = exports2.TopologyDescriptionChangedEvent = exports2.TopologyClosedEvent = exports2.ServerOpeningEvent = exports2.ServerHeartbeatSucceededEvent = exports2.ServerHeartbeatStartedEvent = exports2.ServerHeartbeatFailedEvent = exports2.ServerDescriptionChangedEvent = exports2.ServerClosedEvent = exports2.ConnectionReadyEvent = exports2.ConnectionPoolReadyEvent = exports2.ConnectionPoolMonitoringEvent = exports2.ConnectionPoolCreatedEvent = exports2.ConnectionPoolClosedEvent = exports2.ConnectionPoolClearedEvent = exports2.ConnectionCreatedEvent = exports2.ConnectionClosedEvent = exports2.ConnectionCheckOutStartedEvent = exports2.ConnectionCheckOutFailedEvent = exports2.ConnectionCheckedOutEvent = exports2.ConnectionCheckedInEvent = exports2.CommandSucceededEvent = exports2.CommandStartedEvent = void 0; var admin_1 = require_admin(); Object.defineProperty(exports2, "Admin", { enumerable: true, get: function() { return admin_1.Admin; } }); var ordered_1 = require_ordered(); Object.defineProperty(exports2, "OrderedBulkOperation", { enumerable: true, get: function() { return ordered_1.OrderedBulkOperation; } }); var unordered_1 = require_unordered(); Object.defineProperty(exports2, "UnorderedBulkOperation", { enumerable: true, get: function() { return unordered_1.UnorderedBulkOperation; } }); var change_stream_1 = require_change_stream(); Object.defineProperty(exports2, "ChangeStream", { enumerable: true, get: function() { return change_stream_1.ChangeStream; } }); var collection_1 = require_collection(); Object.defineProperty(exports2, "Collection", { enumerable: true, get: function() { return collection_1.Collection; } }); var abstract_cursor_1 = require_abstract_cursor(); Object.defineProperty(exports2, "AbstractCursor", { enumerable: true, get: function() { return abstract_cursor_1.AbstractCursor; } }); var aggregation_cursor_1 = require_aggregation_cursor(); Object.defineProperty(exports2, "AggregationCursor", { enumerable: true, get: function() { return aggregation_cursor_1.AggregationCursor; } }); var find_cursor_1 = require_find_cursor(); Object.defineProperty(exports2, "FindCursor", { enumerable: true, get: function() { return find_cursor_1.FindCursor; } }); var list_collections_cursor_1 = require_list_collections_cursor(); Object.defineProperty(exports2, "ListCollectionsCursor", { enumerable: true, get: function() { return list_collections_cursor_1.ListCollectionsCursor; } }); var list_indexes_cursor_1 = require_list_indexes_cursor(); Object.defineProperty(exports2, "ListIndexesCursor", { enumerable: true, get: function() { return list_indexes_cursor_1.ListIndexesCursor; } }); var db_1 = require_db(); Object.defineProperty(exports2, "Db", { enumerable: true, get: function() { return db_1.Db; } }); var explain_1 = require_explain(); Object.defineProperty(exports2, "ExplainableCursor", { enumerable: true, get: function() { return explain_1.ExplainableCursor; } }); var gridfs_1 = require_gridfs(); Object.defineProperty(exports2, "GridFSBucket", { enumerable: true, get: function() { return gridfs_1.GridFSBucket; } }); var download_1 = require_download(); Object.defineProperty(exports2, "GridFSBucketReadStream", { enumerable: true, get: function() { return download_1.GridFSBucketReadStream; } }); var upload_1 = require_upload(); Object.defineProperty(exports2, "GridFSBucketWriteStream", { enumerable: true, get: function() { return upload_1.GridFSBucketWriteStream; } }); var mongo_client_1 = require_mongo_client(); Object.defineProperty(exports2, "MongoClient", { enumerable: true, get: function() { return mongo_client_1.MongoClient; } }); var mongo_types_1 = require_mongo_types(); Object.defineProperty(exports2, "CancellationToken", { enumerable: true, get: function() { return mongo_types_1.CancellationToken; } }); var sessions_1 = require_sessions(); Object.defineProperty(exports2, "ClientSession", { enumerable: true, get: function() { return sessions_1.ClientSession; } }); var bson_1 = require_bson2(); Object.defineProperty(exports2, "BSON", { enumerable: true, get: function() { return bson_1.BSON; } }); var bson_2 = require_bson2(); Object.defineProperty(exports2, "Binary", { enumerable: true, get: function() { return bson_2.Binary; } }); Object.defineProperty(exports2, "BSONRegExp", { enumerable: true, get: function() { return bson_2.BSONRegExp; } }); Object.defineProperty(exports2, "BSONSymbol", { enumerable: true, get: function() { return bson_2.BSONSymbol; } }); Object.defineProperty(exports2, "BSONType", { enumerable: true, get: function() { return bson_2.BSONType; } }); Object.defineProperty(exports2, "Code", { enumerable: true, get: function() { return bson_2.Code; } }); Object.defineProperty(exports2, "DBRef", { enumerable: true, get: function() { return bson_2.DBRef; } }); Object.defineProperty(exports2, "Decimal128", { enumerable: true, get: function() { return bson_2.Decimal128; } }); Object.defineProperty(exports2, "Double", { enumerable: true, get: function() { return bson_2.Double; } }); Object.defineProperty(exports2, "Int32", { enumerable: true, get: function() { return bson_2.Int32; } }); Object.defineProperty(exports2, "Long", { enumerable: true, get: function() { return bson_2.Long; } }); Object.defineProperty(exports2, "MaxKey", { enumerable: true, get: function() { return bson_2.MaxKey; } }); Object.defineProperty(exports2, "MinKey", { enumerable: true, get: function() { return bson_2.MinKey; } }); Object.defineProperty(exports2, "ObjectId", { enumerable: true, get: function() { return bson_2.ObjectId; } }); Object.defineProperty(exports2, "Timestamp", { enumerable: true, get: function() { return bson_2.Timestamp; } }); Object.defineProperty(exports2, "UUID", { enumerable: true, get: function() { return bson_2.UUID; } }); var common_1 = require_common2(); Object.defineProperty(exports2, "MongoBulkWriteError", { enumerable: true, get: function() { return common_1.MongoBulkWriteError; } }); var client_encryption_1 = require_client_encryption(); Object.defineProperty(exports2, "ClientEncryption", { enumerable: true, get: function() { return client_encryption_1.ClientEncryption; } }); var change_stream_cursor_1 = require_change_stream_cursor(); Object.defineProperty(exports2, "ChangeStreamCursor", { enumerable: true, get: function() { return change_stream_cursor_1.ChangeStreamCursor; } }); var error_1 = require_error(); Object.defineProperty(exports2, "MongoAPIError", { enumerable: true, get: function() { return error_1.MongoAPIError; } }); Object.defineProperty(exports2, "MongoAWSError", { enumerable: true, get: function() { return error_1.MongoAWSError; } }); Object.defineProperty(exports2, "MongoAzureError", { enumerable: true, get: function() { return error_1.MongoAzureError; } }); Object.defineProperty(exports2, "MongoBatchReExecutionError", { enumerable: true, get: function() { return error_1.MongoBatchReExecutionError; } }); Object.defineProperty(exports2, "MongoChangeStreamError", { enumerable: true, get: function() { return error_1.MongoChangeStreamError; } }); Object.defineProperty(exports2, "MongoClientBulkWriteCursorError", { enumerable: true, get: function() { return error_1.MongoClientBulkWriteCursorError; } }); Object.defineProperty(exports2, "MongoClientBulkWriteError", { enumerable: true, get: function() { return error_1.MongoClientBulkWriteError; } }); Object.defineProperty(exports2, "MongoClientBulkWriteExecutionError", { enumerable: true, get: function() { return error_1.MongoClientBulkWriteExecutionError; } }); Object.defineProperty(exports2, "MongoClientClosedError", { enumerable: true, get: function() { return error_1.MongoClientClosedError; } }); Object.defineProperty(exports2, "MongoCompatibilityError", { enumerable: true, get: function() { return error_1.MongoCompatibilityError; } }); Object.defineProperty(exports2, "MongoCursorExhaustedError", { enumerable: true, get: function() { return error_1.MongoCursorExhaustedError; } }); Object.defineProperty(exports2, "MongoCursorInUseError", { enumerable: true, get: function() { return error_1.MongoCursorInUseError; } }); Object.defineProperty(exports2, "MongoDecompressionError", { enumerable: true, get: function() { return error_1.MongoDecompressionError; } }); Object.defineProperty(exports2, "MongoDriverError", { enumerable: true, get: function() { return error_1.MongoDriverError; } }); Object.defineProperty(exports2, "MongoError", { enumerable: true, get: function() { return error_1.MongoError; } }); Object.defineProperty(exports2, "MongoExpiredSessionError", { enumerable: true, get: function() { return error_1.MongoExpiredSessionError; } }); Object.defineProperty(exports2, "MongoGCPError", { enumerable: true, get: function() { return error_1.MongoGCPError; } }); Object.defineProperty(exports2, "MongoGridFSChunkError", { enumerable: true, get: function() { return error_1.MongoGridFSChunkError; } }); Object.defineProperty(exports2, "MongoGridFSStreamError", { enumerable: true, get: function() { return error_1.MongoGridFSStreamError; } }); Object.defineProperty(exports2, "MongoInvalidArgumentError", { enumerable: true, get: function() { return error_1.MongoInvalidArgumentError; } }); Object.defineProperty(exports2, "MongoKerberosError", { enumerable: true, get: function() { return error_1.MongoKerberosError; } }); Object.defineProperty(exports2, "MongoMissingCredentialsError", { enumerable: true, get: function() { return error_1.MongoMissingCredentialsError; } }); Object.defineProperty(exports2, "MongoMissingDependencyError", { enumerable: true, get: function() { return error_1.MongoMissingDependencyError; } }); Object.defineProperty(exports2, "MongoNetworkError", { enumerable: true, get: function() { return error_1.MongoNetworkError; } }); Object.defineProperty(exports2, "MongoNetworkTimeoutError", { enumerable: true, get: function() { return error_1.MongoNetworkTimeoutError; } }); Object.defineProperty(exports2, "MongoNotConnectedError", { enumerable: true, get: function() { return error_1.MongoNotConnectedError; } }); Object.defineProperty(exports2, "MongoOIDCError", { enumerable: true, get: function() { return error_1.MongoOIDCError; } }); Object.defineProperty(exports2, "MongoOperationTimeoutError", { enumerable: true, get: function() { return error_1.MongoOperationTimeoutError; } }); Object.defineProperty(exports2, "MongoParseError", { enumerable: true, get: function() { return error_1.MongoParseError; } }); Object.defineProperty(exports2, "MongoRuntimeError", { enumerable: true, get: function() { return error_1.MongoRuntimeError; } }); Object.defineProperty(exports2, "MongoServerClosedError", { enumerable: true, get: function() { return error_1.MongoServerClosedError; } }); Object.defineProperty(exports2, "MongoServerError", { enumerable: true, get: function() { return error_1.MongoServerError; } }); Object.defineProperty(exports2, "MongoServerSelectionError", { enumerable: true, get: function() { return error_1.MongoServerSelectionError; } }); Object.defineProperty(exports2, "MongoStalePrimaryError", { enumerable: true, get: function() { return error_1.MongoStalePrimaryError; } }); Object.defineProperty(exports2, "MongoSystemError", { enumerable: true, get: function() { return error_1.MongoSystemError; } }); Object.defineProperty(exports2, "MongoTailableCursorError", { enumerable: true, get: function() { return error_1.MongoTailableCursorError; } }); Object.defineProperty(exports2, "MongoTopologyClosedError", { enumerable: true, get: function() { return error_1.MongoTopologyClosedError; } }); Object.defineProperty(exports2, "MongoTransactionError", { enumerable: true, get: function() { return error_1.MongoTransactionError; } }); Object.defineProperty(exports2, "MongoUnexpectedServerResponseError", { enumerable: true, get: function() { return error_1.MongoUnexpectedServerResponseError; } }); Object.defineProperty(exports2, "MongoWriteConcernError", { enumerable: true, get: function() { return error_1.MongoWriteConcernError; } }); var resource_management_1 = require_resource_management(); Object.defineProperty(exports2, "configureExplicitResourceManagement", { enumerable: true, get: function() { return resource_management_1.configureExplicitResourceManagement; } }); var common_2 = require_common2(); Object.defineProperty(exports2, "BatchType", { enumerable: true, get: function() { return common_2.BatchType; } }); var auto_encrypter_1 = require_auto_encrypter(); Object.defineProperty(exports2, "AutoEncryptionLoggerLevel", { enumerable: true, get: function() { return auto_encrypter_1.AutoEncryptionLoggerLevel; } }); var gssapi_1 = require_gssapi(); Object.defineProperty(exports2, "GSSAPICanonicalizationValue", { enumerable: true, get: function() { return gssapi_1.GSSAPICanonicalizationValue; } }); var providers_1 = require_providers(); Object.defineProperty(exports2, "AuthMechanism", { enumerable: true, get: function() { return providers_1.AuthMechanism; } }); var compression_1 = require_compression(); Object.defineProperty(exports2, "Compressor", { enumerable: true, get: function() { return compression_1.Compressor; } }); var abstract_cursor_2 = require_abstract_cursor(); Object.defineProperty(exports2, "CURSOR_FLAGS", { enumerable: true, get: function() { return abstract_cursor_2.CURSOR_FLAGS; } }); Object.defineProperty(exports2, "CursorTimeoutMode", { enumerable: true, get: function() { return abstract_cursor_2.CursorTimeoutMode; } }); var error_2 = require_error(); Object.defineProperty(exports2, "MongoErrorLabel", { enumerable: true, get: function() { return error_2.MongoErrorLabel; } }); var explain_2 = require_explain(); Object.defineProperty(exports2, "ExplainVerbosity", { enumerable: true, get: function() { return explain_2.ExplainVerbosity; } }); var mongo_client_2 = require_mongo_client(); Object.defineProperty(exports2, "ServerApiVersion", { enumerable: true, get: function() { return mongo_client_2.ServerApiVersion; } }); var mongo_logger_1 = require_mongo_logger(); Object.defineProperty(exports2, "MongoLoggableComponent", { enumerable: true, get: function() { return mongo_logger_1.MongoLoggableComponent; } }); Object.defineProperty(exports2, "SeverityLevel", { enumerable: true, get: function() { return mongo_logger_1.SeverityLevel; } }); var find_and_modify_1 = require_find_and_modify(); Object.defineProperty(exports2, "ReturnDocument", { enumerable: true, get: function() { return find_and_modify_1.ReturnDocument; } }); var set_profiling_level_1 = require_set_profiling_level(); Object.defineProperty(exports2, "ProfilingLevel", { enumerable: true, get: function() { return set_profiling_level_1.ProfilingLevel; } }); var read_concern_1 = require_read_concern(); Object.defineProperty(exports2, "ReadConcernLevel", { enumerable: true, get: function() { return read_concern_1.ReadConcernLevel; } }); var read_preference_1 = require_read_preference(); Object.defineProperty(exports2, "ReadPreferenceMode", { enumerable: true, get: function() { return read_preference_1.ReadPreferenceMode; } }); var common_3 = require_common(); Object.defineProperty(exports2, "ServerType", { enumerable: true, get: function() { return common_3.ServerType; } }); Object.defineProperty(exports2, "TopologyType", { enumerable: true, get: function() { return common_3.TopologyType; } }); var read_concern_2 = require_read_concern(); Object.defineProperty(exports2, "ReadConcern", { enumerable: true, get: function() { return read_concern_2.ReadConcern; } }); var read_preference_2 = require_read_preference(); Object.defineProperty(exports2, "ReadPreference", { enumerable: true, get: function() { return read_preference_2.ReadPreference; } }); var write_concern_1 = require_write_concern(); Object.defineProperty(exports2, "WriteConcern", { enumerable: true, get: function() { return write_concern_1.WriteConcern; } }); var command_monitoring_events_1 = require_command_monitoring_events(); Object.defineProperty(exports2, "CommandFailedEvent", { enumerable: true, get: function() { return command_monitoring_events_1.CommandFailedEvent; } }); Object.defineProperty(exports2, "CommandStartedEvent", { enumerable: true, get: function() { return command_monitoring_events_1.CommandStartedEvent; } }); Object.defineProperty(exports2, "CommandSucceededEvent", { enumerable: true, get: function() { return command_monitoring_events_1.CommandSucceededEvent; } }); var connection_pool_events_1 = require_connection_pool_events(); Object.defineProperty(exports2, "ConnectionCheckedInEvent", { enumerable: true, get: function() { return connection_pool_events_1.ConnectionCheckedInEvent; } }); Object.defineProperty(exports2, "ConnectionCheckedOutEvent", { enumerable: true, get: function() { return connection_pool_events_1.ConnectionCheckedOutEvent; } }); Object.defineProperty(exports2, "ConnectionCheckOutFailedEvent", { enumerable: true, get: function() { return connection_pool_events_1.ConnectionCheckOutFailedEvent; } }); Object.defineProperty(exports2, "ConnectionCheckOutStartedEvent", { enumerable: true, get: function() { return connection_pool_events_1.ConnectionCheckOutStartedEvent; } }); Object.defineProperty(exports2, "ConnectionClosedEvent", { enumerable: true, get: function() { return connection_pool_events_1.ConnectionClosedEvent; } }); Object.defineProperty(exports2, "ConnectionCreatedEvent", { enumerable: true, get: function() { return connection_pool_events_1.ConnectionCreatedEvent; } }); Object.defineProperty(exports2, "ConnectionPoolClearedEvent", { enumerable: true, get: function() { return connection_pool_events_1.ConnectionPoolClearedEvent; } }); Object.defineProperty(exports2, "ConnectionPoolClosedEvent", { enumerable: true, get: function() { return connection_pool_events_1.ConnectionPoolClosedEvent; } }); Object.defineProperty(exports2, "ConnectionPoolCreatedEvent", { enumerable: true, get: function() { return connection_pool_events_1.ConnectionPoolCreatedEvent; } }); Object.defineProperty(exports2, "ConnectionPoolMonitoringEvent", { enumerable: true, get: function() { return connection_pool_events_1.ConnectionPoolMonitoringEvent; } }); Object.defineProperty(exports2, "ConnectionPoolReadyEvent", { enumerable: true, get: function() { return connection_pool_events_1.ConnectionPoolReadyEvent; } }); Object.defineProperty(exports2, "ConnectionReadyEvent", { enumerable: true, get: function() { return connection_pool_events_1.ConnectionReadyEvent; } }); var events_1 = require_events(); Object.defineProperty(exports2, "ServerClosedEvent", { enumerable: true, get: function() { return events_1.ServerClosedEvent; } }); Object.defineProperty(exports2, "ServerDescriptionChangedEvent", { enumerable: true, get: function() { return events_1.ServerDescriptionChangedEvent; } }); Object.defineProperty(exports2, "ServerHeartbeatFailedEvent", { enumerable: true, get: function() { return events_1.ServerHeartbeatFailedEvent; } }); Object.defineProperty(exports2, "ServerHeartbeatStartedEvent", { enumerable: true, get: function() { return events_1.ServerHeartbeatStartedEvent; } }); Object.defineProperty(exports2, "ServerHeartbeatSucceededEvent", { enumerable: true, get: function() { return events_1.ServerHeartbeatSucceededEvent; } }); Object.defineProperty(exports2, "ServerOpeningEvent", { enumerable: true, get: function() { return events_1.ServerOpeningEvent; } }); Object.defineProperty(exports2, "TopologyClosedEvent", { enumerable: true, get: function() { return events_1.TopologyClosedEvent; } }); Object.defineProperty(exports2, "TopologyDescriptionChangedEvent", { enumerable: true, get: function() { return events_1.TopologyDescriptionChangedEvent; } }); Object.defineProperty(exports2, "TopologyOpeningEvent", { enumerable: true, get: function() { return events_1.TopologyOpeningEvent; } }); var server_selection_events_1 = require_server_selection_events(); Object.defineProperty(exports2, "ServerSelectionEvent", { enumerable: true, get: function() { return server_selection_events_1.ServerSelectionEvent; } }); Object.defineProperty(exports2, "ServerSelectionFailedEvent", { enumerable: true, get: function() { return server_selection_events_1.ServerSelectionFailedEvent; } }); Object.defineProperty(exports2, "ServerSelectionStartedEvent", { enumerable: true, get: function() { return server_selection_events_1.ServerSelectionStartedEvent; } }); Object.defineProperty(exports2, "ServerSelectionSucceededEvent", { enumerable: true, get: function() { return server_selection_events_1.ServerSelectionSucceededEvent; } }); Object.defineProperty(exports2, "WaitingForSuitableServerEvent", { enumerable: true, get: function() { return server_selection_events_1.WaitingForSuitableServerEvent; } }); var srv_polling_1 = require_srv_polling(); Object.defineProperty(exports2, "SrvPollingEvent", { enumerable: true, get: function() { return srv_polling_1.SrvPollingEvent; } }); var errors_1 = require_errors(); Object.defineProperty(exports2, "MongoCryptAzureKMSRequestError", { enumerable: true, get: function() { return errors_1.MongoCryptAzureKMSRequestError; } }); Object.defineProperty(exports2, "MongoCryptCreateDataKeyError", { enumerable: true, get: function() { return errors_1.MongoCryptCreateDataKeyError; } }); Object.defineProperty(exports2, "MongoCryptCreateEncryptedCollectionError", { enumerable: true, get: function() { return errors_1.MongoCryptCreateEncryptedCollectionError; } }); Object.defineProperty(exports2, "MongoCryptError", { enumerable: true, get: function() { return errors_1.MongoCryptError; } }); Object.defineProperty(exports2, "MongoCryptInvalidArgumentError", { enumerable: true, get: function() { return errors_1.MongoCryptInvalidArgumentError; } }); Object.defineProperty(exports2, "MongoCryptKMSRequestNetworkTimeoutError", { enumerable: true, get: function() { return errors_1.MongoCryptKMSRequestNetworkTimeoutError; } }); var mongo_client_auth_providers_1 = require_mongo_client_auth_providers(); Object.defineProperty(exports2, "MongoClientAuthProviders", { enumerable: true, get: function() { return mongo_client_auth_providers_1.MongoClientAuthProviders; } }); } }); // netlify/functions/node_modules/mongodb/lib/beta.js var require_beta = __commonJS({ "netlify/functions/node_modules/mongodb/lib/beta.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); __exportStar(require_lib3(), exports2); function __exportStar(mod) { for (const key of Object.keys(mod)) { Object.defineProperty(exports2, key, { enumerable: true, get: function() { return mod[key]; } }); } } } }); // netlify/functions/node_modules/mongodb/lib/operations/client_bulk_write/client_bulk_write.js var require_client_bulk_write = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/client_bulk_write/client_bulk_write.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ClientBulkWriteOperation = void 0; var beta_1 = require_beta(); var responses_1 = require_responses(); var utils_1 = require_utils(); var command_1 = require_command(); var operation_1 = require_operation(); var ClientBulkWriteOperation = class extends command_1.CommandOperation { get commandName() { return "bulkWrite"; } constructor(commandBuilder, options) { super(void 0, options); this.commandBuilder = commandBuilder; this.options = options; this.ns = new utils_1.MongoDBNamespace("admin", "$cmd"); } resetBatch() { return this.commandBuilder.resetBatch(); } get canRetryWrite() { return this.commandBuilder.isBatchRetryable; } /** * Execute the command. Superclass will handle write concern, etc. * @param server - The server. * @param session - The session. * @returns The response. */ async execute(server, session, timeoutContext) { let command; if (server.description.type === beta_1.ServerType.LoadBalancer) { if (session) { let connection; if (!session.pinnedConnection) { connection = await server.pool.checkOut({ timeoutContext }); session.pin(connection); } else { connection = session.pinnedConnection; } command = this.commandBuilder.buildBatch(connection.hello?.maxMessageSizeBytes, connection.hello?.maxWriteBatchSize, connection.hello?.maxBsonObjectSize); } else { throw new beta_1.MongoClientBulkWriteExecutionError("Session provided to the client bulk write operation must be present."); } } else { if (!server.description.maxWriteBatchSize || !server.description.maxMessageSizeBytes || !server.description.maxBsonObjectSize) { throw new beta_1.MongoClientBulkWriteExecutionError("In order to execute a client bulk write, both maxWriteBatchSize, maxMessageSizeBytes and maxBsonObjectSize must be provided by the servers hello response."); } command = this.commandBuilder.buildBatch(server.description.maxMessageSizeBytes, server.description.maxWriteBatchSize, server.description.maxBsonObjectSize); } if (!this.canRetryWrite) { this.options.willRetryWrite = false; } return await super.executeCommand(server, session, command, timeoutContext, responses_1.ClientBulkWriteCursorResponse); } }; exports2.ClientBulkWriteOperation = ClientBulkWriteOperation; (0, operation_1.defineAspects)(ClientBulkWriteOperation, [ operation_1.Aspect.WRITE_OPERATION, operation_1.Aspect.SKIP_COLLATION, operation_1.Aspect.CURSOR_CREATING, operation_1.Aspect.RETRYABLE, operation_1.Aspect.COMMAND_BATCHING ]); } }); // netlify/functions/node_modules/mongodb/lib/cursor/client_bulk_write_cursor.js var require_client_bulk_write_cursor = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cursor/client_bulk_write_cursor.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ClientBulkWriteCursor = void 0; var client_bulk_write_1 = require_client_bulk_write(); var execute_operation_1 = require_execute_operation(); var utils_1 = require_utils(); var abstract_cursor_1 = require_abstract_cursor(); var ClientBulkWriteCursor = class _ClientBulkWriteCursor extends abstract_cursor_1.AbstractCursor { /** @internal */ constructor(client, commandBuilder, options = {}) { super(client, new utils_1.MongoDBNamespace("admin", "$cmd"), options); this.commandBuilder = commandBuilder; this.clientBulkWriteOptions = options; } /** * We need a way to get the top level cursor response fields for * generating the bulk write result, so we expose this here. */ get response() { if (this.cursorResponse) return this.cursorResponse; return null; } get operations() { return this.commandBuilder.lastOperations; } clone() { const clonedOptions = (0, utils_1.mergeOptions)({}, this.clientBulkWriteOptions); delete clonedOptions.session; return new _ClientBulkWriteCursor(this.client, this.commandBuilder, { ...clonedOptions }); } /** @internal */ async _initialize(session) { const clientBulkWriteOperation = new client_bulk_write_1.ClientBulkWriteOperation(this.commandBuilder, { ...this.clientBulkWriteOptions, ...this.cursorOptions, session }); const response = await (0, execute_operation_1.executeOperation)(this.client, clientBulkWriteOperation, this.timeoutContext); this.cursorResponse = response; return { server: clientBulkWriteOperation.server, session, response }; } }; exports2.ClientBulkWriteCursor = ClientBulkWriteCursor; } }); // netlify/functions/node_modules/mongodb/lib/operations/client_bulk_write/command_builder.js var require_command_builder = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/client_bulk_write/command_builder.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.buildReplaceOneOperation = exports2.buildUpdateManyOperation = exports2.buildUpdateOneOperation = exports2.buildDeleteManyOperation = exports2.buildDeleteOneOperation = exports2.buildInsertOneOperation = exports2.ClientBulkWriteCommandBuilder = void 0; exports2.buildOperation = buildOperation; var bson_1 = require_bson2(); var commands_1 = require_commands(); var error_1 = require_error(); var sort_1 = require_sort(); var utils_1 = require_utils(); var MESSAGE_OVERHEAD_BYTES = 1e3; var ClientBulkWriteCommandBuilder = class { /** * Create the command builder. * @param models - The client write models. */ constructor(models, options, pkFactory) { this.models = models; this.options = options; this.pkFactory = pkFactory ?? utils_1.DEFAULT_PK_FACTORY; this.currentModelIndex = 0; this.previousModelIndex = 0; this.lastOperations = []; this.isBatchRetryable = true; } /** * Gets the errorsOnly value for the command, which is the inverse of the * user provided verboseResults option. Defaults to true. */ get errorsOnly() { if ("verboseResults" in this.options) { return !this.options.verboseResults; } return true; } /** * Determines if there is another batch to process. * @returns True if not all batches have been built. */ hasNextBatch() { return this.currentModelIndex < this.models.length; } /** * When we need to retry a command we need to set the current * model index back to its previous value. */ resetBatch() { this.currentModelIndex = this.previousModelIndex; return true; } /** * Build a single batch of a client bulk write command. * @param maxMessageSizeBytes - The max message size in bytes. * @param maxWriteBatchSize - The max write batch size. * @returns The client bulk write command. */ buildBatch(maxMessageSizeBytes, maxWriteBatchSize, maxBsonObjectSize) { this.isBatchRetryable = true; let commandLength = 0; let currentNamespaceIndex = 0; const command = this.baseCommand(); const namespaces = /* @__PURE__ */ new Map(); this.previousModelIndex = this.currentModelIndex; while (this.currentModelIndex < this.models.length) { const model = this.models[this.currentModelIndex]; const ns = model.namespace; const nsIndex = namespaces.get(ns); if (model.name === "deleteMany" || model.name === "updateMany") { this.isBatchRetryable = false; } if (nsIndex != null) { const operation = buildOperation(model, nsIndex, this.pkFactory, this.options); let operationBuffer; try { operationBuffer = bson_1.BSON.serialize(operation); } catch (cause) { throw new error_1.MongoInvalidArgumentError(`Could not serialize operation to BSON`, { cause }); } validateBufferSize("ops", operationBuffer, maxBsonObjectSize); if (commandLength + operationBuffer.length < maxMessageSizeBytes && command.ops.documents.length < maxWriteBatchSize) { commandLength = MESSAGE_OVERHEAD_BYTES + command.ops.push(operation, operationBuffer); this.currentModelIndex++; } else { break; } } else { namespaces.set(ns, currentNamespaceIndex); const nsInfo = { ns }; const operation = buildOperation(model, currentNamespaceIndex, this.pkFactory, this.options); let nsInfoBuffer; let operationBuffer; try { nsInfoBuffer = bson_1.BSON.serialize(nsInfo); operationBuffer = bson_1.BSON.serialize(operation); } catch (cause) { throw new error_1.MongoInvalidArgumentError(`Could not serialize ns info to BSON`, { cause }); } validateBufferSize("nsInfo", nsInfoBuffer, maxBsonObjectSize); validateBufferSize("ops", operationBuffer, maxBsonObjectSize); if (commandLength + nsInfoBuffer.length + operationBuffer.length < maxMessageSizeBytes && command.ops.documents.length < maxWriteBatchSize) { commandLength = MESSAGE_OVERHEAD_BYTES + command.nsInfo.push(nsInfo, nsInfoBuffer) + command.ops.push(operation, operationBuffer); currentNamespaceIndex++; this.currentModelIndex++; } else { break; } } } this.lastOperations = command.ops.documents; return command; } baseCommand() { const command = { bulkWrite: 1, errorsOnly: this.errorsOnly, ordered: this.options.ordered ?? true, ops: new commands_1.DocumentSequence("ops"), nsInfo: new commands_1.DocumentSequence("nsInfo") }; if (this.options.bypassDocumentValidation != null) { command.bypassDocumentValidation = this.options.bypassDocumentValidation; } if (this.options.let) { command.let = this.options.let; } if (this.options.comment !== void 0) { command.comment = this.options.comment; } return command; } }; exports2.ClientBulkWriteCommandBuilder = ClientBulkWriteCommandBuilder; function validateBufferSize(name, buffer, maxBsonObjectSize) { if (buffer.length > maxBsonObjectSize) { throw new error_1.MongoInvalidArgumentError(`Client bulk write operation ${name} of length ${buffer.length} exceeds the max bson object size of ${maxBsonObjectSize}`); } } var buildInsertOneOperation = (model, index, pkFactory) => { const document2 = { insert: index, document: model.document }; document2.document._id = model.document._id ?? pkFactory.createPk(); return document2; }; exports2.buildInsertOneOperation = buildInsertOneOperation; var buildDeleteOneOperation = (model, index) => { return createDeleteOperation(model, index, false); }; exports2.buildDeleteOneOperation = buildDeleteOneOperation; var buildDeleteManyOperation = (model, index) => { return createDeleteOperation(model, index, true); }; exports2.buildDeleteManyOperation = buildDeleteManyOperation; function createDeleteOperation(model, index, multi) { const document2 = { delete: index, multi, filter: model.filter }; if (model.hint) { document2.hint = model.hint; } if (model.collation) { document2.collation = model.collation; } return document2; } var buildUpdateOneOperation = (model, index, options) => { return createUpdateOperation(model, index, false, options); }; exports2.buildUpdateOneOperation = buildUpdateOneOperation; var buildUpdateManyOperation = (model, index, options) => { return createUpdateOperation(model, index, true, options); }; exports2.buildUpdateManyOperation = buildUpdateManyOperation; function validateUpdate(update, options) { if (!(0, utils_1.hasAtomicOperators)(update, options)) { throw new error_1.MongoAPIError("Client bulk write update models must only contain atomic modifiers (start with $) and must not be empty."); } } function createUpdateOperation(model, index, multi, options) { validateUpdate(model.update, options); const document2 = { update: index, multi, filter: model.filter, updateMods: model.update }; if (model.hint) { document2.hint = model.hint; } if (model.upsert) { document2.upsert = model.upsert; } if (model.arrayFilters) { document2.arrayFilters = model.arrayFilters; } if (model.collation) { document2.collation = model.collation; } if (!multi && "sort" in model && model.sort != null) { document2.sort = (0, sort_1.formatSort)(model.sort); } return document2; } var buildReplaceOneOperation = (model, index) => { if ((0, utils_1.hasAtomicOperators)(model.replacement)) { throw new error_1.MongoAPIError("Client bulk write replace models must not contain atomic modifiers (start with $) and must not be empty."); } const document2 = { update: index, multi: false, filter: model.filter, updateMods: model.replacement }; if (model.hint) { document2.hint = model.hint; } if (model.upsert) { document2.upsert = model.upsert; } if (model.collation) { document2.collation = model.collation; } if (model.sort != null) { document2.sort = (0, sort_1.formatSort)(model.sort); } return document2; }; exports2.buildReplaceOneOperation = buildReplaceOneOperation; function buildOperation(model, index, pkFactory, options) { switch (model.name) { case "insertOne": return (0, exports2.buildInsertOneOperation)(model, index, pkFactory); case "deleteOne": return (0, exports2.buildDeleteOneOperation)(model, index); case "deleteMany": return (0, exports2.buildDeleteManyOperation)(model, index); case "updateOne": return (0, exports2.buildUpdateOneOperation)(model, index, options); case "updateMany": return (0, exports2.buildUpdateManyOperation)(model, index, options); case "replaceOne": return (0, exports2.buildReplaceOneOperation)(model, index); } } } }); // netlify/functions/node_modules/mongodb/lib/operations/client_bulk_write/results_merger.js var require_results_merger = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/client_bulk_write/results_merger.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ClientBulkWriteResultsMerger = void 0; var __1 = require_lib3(); var error_1 = require_error(); var UNACKNOWLEDGED = { acknowledged: false, insertedCount: 0, upsertedCount: 0, matchedCount: 0, modifiedCount: 0, deletedCount: 0, insertResults: void 0, updateResults: void 0, deleteResults: void 0 }; var ClientBulkWriteResultsMerger = class { /** * @returns The standard unacknowledged bulk write result. */ static unacknowledged() { return UNACKNOWLEDGED; } /** * Instantiate the merger. * @param options - The options. */ constructor(options) { this.options = options; this.currentBatchOffset = 0; this.writeConcernErrors = []; this.writeErrors = /* @__PURE__ */ new Map(); this.result = { acknowledged: true, insertedCount: 0, upsertedCount: 0, matchedCount: 0, modifiedCount: 0, deletedCount: 0, insertResults: void 0, updateResults: void 0, deleteResults: void 0 }; if (options.verboseResults) { this.result.insertResults = /* @__PURE__ */ new Map(); this.result.updateResults = /* @__PURE__ */ new Map(); this.result.deleteResults = /* @__PURE__ */ new Map(); } } /** * Get the bulk write result object. */ get bulkWriteResult() { return { acknowledged: this.result.acknowledged, insertedCount: this.result.insertedCount, upsertedCount: this.result.upsertedCount, matchedCount: this.result.matchedCount, modifiedCount: this.result.modifiedCount, deletedCount: this.result.deletedCount, insertResults: this.result.insertResults, updateResults: this.result.updateResults, deleteResults: this.result.deleteResults }; } /** * Merge the results in the cursor to the existing result. * @param currentBatchOffset - The offset index to the original models. * @param response - The cursor response. * @param documents - The documents in the cursor. * @returns The current result. */ async merge(cursor) { let writeConcernErrorResult; try { for await (const document2 of cursor) { if (document2.ok === 1) { if (this.options.verboseResults) { this.processDocument(cursor, document2); } } else { if (this.options.ordered) { const error = new error_1.MongoClientBulkWriteError({ message: "Mongo client ordered bulk write encountered a write error." }); error.writeErrors.set(document2.idx + this.currentBatchOffset, { code: document2.code, message: document2.errmsg }); error.partialResult = this.result; throw error; } else { this.writeErrors.set(document2.idx + this.currentBatchOffset, { code: document2.code, message: document2.errmsg }); } } } } catch (error) { if (error instanceof __1.MongoWriteConcernError) { const result = error.result; writeConcernErrorResult = { insertedCount: result.nInserted, upsertedCount: result.nUpserted, matchedCount: result.nMatched, modifiedCount: result.nModified, deletedCount: result.nDeleted, writeConcernError: result.writeConcernError }; if (this.options.verboseResults && result.cursor.firstBatch) { for (const document2 of result.cursor.firstBatch) { if (document2.ok === 1) { this.processDocument(cursor, document2); } } } } else { throw error; } } finally { if (cursor.response) { const response = cursor.response; this.incrementCounts(response); } this.currentBatchOffset += cursor.operations.length; } if (writeConcernErrorResult) { const writeConcernError = writeConcernErrorResult.writeConcernError; this.incrementCounts(writeConcernErrorResult); this.writeConcernErrors.push({ code: writeConcernError.code, message: writeConcernError.errmsg }); } return this.result; } /** * Process an individual document in the results. * @param cursor - The cursor. * @param document - The document to process. */ processDocument(cursor, document2) { const operation = cursor.operations[document2.idx]; if ("insert" in operation) { this.result.insertResults?.set(document2.idx + this.currentBatchOffset, { insertedId: operation.document._id }); } if ("update" in operation) { const result = { matchedCount: document2.n, modifiedCount: document2.nModified ?? 0, // Check if the bulk did actually upsert. didUpsert: document2.upserted != null }; if (document2.upserted) { result.upsertedId = document2.upserted._id; } this.result.updateResults?.set(document2.idx + this.currentBatchOffset, result); } if ("delete" in operation) { this.result.deleteResults?.set(document2.idx + this.currentBatchOffset, { deletedCount: document2.n }); } } /** * Increment the result counts. * @param document - The document with the results. */ incrementCounts(document2) { this.result.insertedCount += document2.insertedCount; this.result.upsertedCount += document2.upsertedCount; this.result.matchedCount += document2.matchedCount; this.result.modifiedCount += document2.modifiedCount; this.result.deletedCount += document2.deletedCount; } }; exports2.ClientBulkWriteResultsMerger = ClientBulkWriteResultsMerger; } }); // netlify/functions/node_modules/mongodb/lib/operations/client_bulk_write/executor.js var require_executor = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/client_bulk_write/executor.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ClientBulkWriteExecutor = void 0; var abstract_cursor_1 = require_abstract_cursor(); var client_bulk_write_cursor_1 = require_client_bulk_write_cursor(); var error_1 = require_error(); var timeout_1 = require_timeout(); var utils_1 = require_utils(); var write_concern_1 = require_write_concern(); var execute_operation_1 = require_execute_operation(); var client_bulk_write_1 = require_client_bulk_write(); var command_builder_1 = require_command_builder(); var results_merger_1 = require_results_merger(); var ClientBulkWriteExecutor = class { /** * Instantiate the executor. * @param client - The mongo client. * @param operations - The user supplied bulk write models. * @param options - The bulk write options. */ constructor(client, operations, options) { if (operations.length === 0) { throw new error_1.MongoClientBulkWriteExecutionError("No client bulk write models were provided."); } this.client = client; this.operations = operations; this.options = { ordered: true, bypassDocumentValidation: false, verboseResults: false, ...options }; if (!this.options.writeConcern) { this.options.writeConcern = write_concern_1.WriteConcern.fromOptions(this.client.s.options); } if (this.options.writeConcern?.w === 0) { if (this.options.verboseResults) { throw new error_1.MongoInvalidArgumentError("Cannot request unacknowledged write concern and verbose results"); } if (this.options.ordered) { throw new error_1.MongoInvalidArgumentError("Cannot request unacknowledged write concern and ordered writes"); } } } /** * Execute the client bulk write. Will split commands into batches and exhaust the cursors * for each, then merge the results into one. * @returns The result. */ async execute() { const pkFactory = this.client.s.options.pkFactory; const commandBuilder = new command_builder_1.ClientBulkWriteCommandBuilder(this.operations, this.options, pkFactory); const resolvedOptions = (0, utils_1.resolveTimeoutOptions)(this.client, this.options); const context = timeout_1.TimeoutContext.create(resolvedOptions); if (this.options.writeConcern?.w === 0) { while (commandBuilder.hasNextBatch()) { const operation = new client_bulk_write_1.ClientBulkWriteOperation(commandBuilder, this.options); await (0, execute_operation_1.executeOperation)(this.client, operation, context); } return results_merger_1.ClientBulkWriteResultsMerger.unacknowledged(); } else { const resultsMerger = new results_merger_1.ClientBulkWriteResultsMerger(this.options); while (commandBuilder.hasNextBatch()) { const cursorContext = new abstract_cursor_1.CursorTimeoutContext(context, Symbol()); const options = { ...this.options, timeoutContext: cursorContext, ...resolvedOptions.timeoutMS != null && { timeoutMode: abstract_cursor_1.CursorTimeoutMode.LIFETIME } }; const cursor = new client_bulk_write_cursor_1.ClientBulkWriteCursor(this.client, commandBuilder, options); try { await resultsMerger.merge(cursor); } catch (error) { if (error instanceof error_1.MongoServerError && !(error instanceof error_1.MongoClientBulkWriteError)) { const bulkWriteError = new error_1.MongoClientBulkWriteError({ message: "Mongo client bulk write encountered an error during execution" }); bulkWriteError.cause = error; bulkWriteError.partialResult = resultsMerger.bulkWriteResult; throw bulkWriteError; } else { throw error; } } } if (resultsMerger.writeConcernErrors.length > 0 || resultsMerger.writeErrors.size > 0) { const error = new error_1.MongoClientBulkWriteError({ message: "Mongo client bulk write encountered errors during execution." }); error.writeConcernErrors = resultsMerger.writeConcernErrors; error.writeErrors = resultsMerger.writeErrors; error.partialResult = resultsMerger.bulkWriteResult; throw error; } return resultsMerger.bulkWriteResult; } } }; exports2.ClientBulkWriteExecutor = ClientBulkWriteExecutor; } }); // netlify/functions/node_modules/mongodb/lib/sdam/topology.js var require_topology = __commonJS({ "netlify/functions/node_modules/mongodb/lib/sdam/topology.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ServerCapabilities = exports2.Topology = void 0; var connection_string_1 = require_connection_string(); var constants_1 = require_constants(); var error_1 = require_error(); var mongo_logger_1 = require_mongo_logger(); var mongo_types_1 = require_mongo_types(); var read_preference_1 = require_read_preference(); var timeout_1 = require_timeout(); var utils_1 = require_utils(); var common_1 = require_common(); var events_1 = require_events(); var server_1 = require_server(); var server_description_1 = require_server_description(); var server_selection_1 = require_server_selection(); var server_selection_events_1 = require_server_selection_events(); var srv_polling_1 = require_srv_polling(); var topology_description_1 = require_topology_description(); var globalTopologyCounter = 0; var stateTransition = (0, utils_1.makeStateMachine)({ [common_1.STATE_CLOSED]: [common_1.STATE_CLOSED, common_1.STATE_CONNECTING], [common_1.STATE_CONNECTING]: [common_1.STATE_CONNECTING, common_1.STATE_CLOSING, common_1.STATE_CONNECTED, common_1.STATE_CLOSED], [common_1.STATE_CONNECTED]: [common_1.STATE_CONNECTED, common_1.STATE_CLOSING, common_1.STATE_CLOSED], [common_1.STATE_CLOSING]: [common_1.STATE_CLOSING, common_1.STATE_CLOSED] }); var Topology = class _Topology extends mongo_types_1.TypedEventEmitter { /** * @param seedlist - a list of HostAddress instances to connect to */ constructor(client, seeds, options) { super(); this.on("error", utils_1.noop); this.client = client; options = options ?? { hosts: [utils_1.HostAddress.fromString("localhost:27017")], ...Object.fromEntries(connection_string_1.DEFAULT_OPTIONS.entries()) }; if (typeof seeds === "string") { seeds = [utils_1.HostAddress.fromString(seeds)]; } else if (!Array.isArray(seeds)) { seeds = [seeds]; } const seedlist = []; for (const seed of seeds) { if (typeof seed === "string") { seedlist.push(utils_1.HostAddress.fromString(seed)); } else if (seed instanceof utils_1.HostAddress) { seedlist.push(seed); } else { throw new error_1.MongoRuntimeError(`Topology cannot be constructed from ${JSON.stringify(seed)}`); } } const topologyType = topologyTypeFromOptions(options); const topologyId = globalTopologyCounter++; const selectedHosts = options.srvMaxHosts == null || options.srvMaxHosts === 0 || options.srvMaxHosts >= seedlist.length ? seedlist : (0, utils_1.shuffle)(seedlist, options.srvMaxHosts); const serverDescriptions = /* @__PURE__ */ new Map(); for (const hostAddress of selectedHosts) { serverDescriptions.set(hostAddress.toString(), new server_description_1.ServerDescription(hostAddress)); } this.waitQueue = new utils_1.List(); this.s = { // the id of this topology id: topologyId, // passed in options options, // initial seedlist of servers to connect to seedlist, // initial state state: common_1.STATE_CLOSED, // the topology description description: new topology_description_1.TopologyDescription(topologyType, serverDescriptions, options.replicaSet, void 0, void 0, void 0, options), serverSelectionTimeoutMS: options.serverSelectionTimeoutMS, heartbeatFrequencyMS: options.heartbeatFrequencyMS, minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS, // a map of server instances to normalized addresses servers: /* @__PURE__ */ new Map(), credentials: options?.credentials, clusterTime: void 0, detectShardedTopology: (ev) => this.detectShardedTopology(ev), detectSrvRecords: (ev) => this.detectSrvRecords(ev) }; this.mongoLogger = client.mongoLogger; this.component = "topology"; if (options.srvHost && !options.loadBalanced) { this.s.srvPoller = options.srvPoller ?? new srv_polling_1.SrvPoller({ heartbeatFrequencyMS: this.s.heartbeatFrequencyMS, srvHost: options.srvHost, srvMaxHosts: options.srvMaxHosts, srvServiceName: options.srvServiceName }); this.on(_Topology.TOPOLOGY_DESCRIPTION_CHANGED, this.s.detectShardedTopology); } this.connectionLock = void 0; } detectShardedTopology(event) { const previousType = event.previousDescription.type; const newType = event.newDescription.type; const transitionToSharded = previousType !== common_1.TopologyType.Sharded && newType === common_1.TopologyType.Sharded; const srvListeners = this.s.srvPoller?.listeners(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY); const listeningToSrvPolling = !!srvListeners?.includes(this.s.detectSrvRecords); if (transitionToSharded && !listeningToSrvPolling) { this.s.srvPoller?.on(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY, this.s.detectSrvRecords); this.s.srvPoller?.start(); } } detectSrvRecords(ev) { const previousTopologyDescription = this.s.description; this.s.description = this.s.description.updateFromSrvPollingEvent(ev, this.s.options.srvMaxHosts); if (this.s.description === previousTopologyDescription) { return; } updateServers(this); this.emitAndLog(_Topology.TOPOLOGY_DESCRIPTION_CHANGED, new events_1.TopologyDescriptionChangedEvent(this.s.id, previousTopologyDescription, this.s.description)); } /** * @returns A `TopologyDescription` for this topology */ get description() { return this.s.description; } get loadBalanced() { return this.s.options.loadBalanced; } get serverApi() { return this.s.options.serverApi; } get capabilities() { return new ServerCapabilities(this.lastHello()); } /** Initiate server connect */ async connect(options) { this.connectionLock ??= this._connect(options); try { await this.connectionLock; return this; } finally { this.connectionLock = void 0; } } async _connect(options) { options = options ?? {}; if (this.s.state === common_1.STATE_CONNECTED) { return this; } stateTransition(this, common_1.STATE_CONNECTING); this.emitAndLog(_Topology.TOPOLOGY_OPENING, new events_1.TopologyOpeningEvent(this.s.id)); this.emitAndLog(_Topology.TOPOLOGY_DESCRIPTION_CHANGED, new events_1.TopologyDescriptionChangedEvent( this.s.id, new topology_description_1.TopologyDescription(common_1.TopologyType.Unknown), // initial is always Unknown this.s.description )); const serverDescriptions = Array.from(this.s.description.servers.values()); this.s.servers = new Map(serverDescriptions.map((serverDescription) => [ serverDescription.address, createAndConnectServer(this, serverDescription) ])); if (this.s.options.loadBalanced) { for (const description of serverDescriptions) { const newDescription = new server_description_1.ServerDescription(description.hostAddress, void 0, { loadBalanced: this.s.options.loadBalanced }); this.serverUpdateHandler(newDescription); } } const serverSelectionTimeoutMS = this.client.s.options.serverSelectionTimeoutMS; const readPreference = options.readPreference ?? read_preference_1.ReadPreference.primary; const timeoutContext = timeout_1.TimeoutContext.create({ // TODO(NODE-6448): auto-connect ignores timeoutMS; potential future feature timeoutMS: void 0, serverSelectionTimeoutMS, waitQueueTimeoutMS: this.client.s.options.waitQueueTimeoutMS }); const selectServerOptions = { operationName: "ping", ...options, timeoutContext }; try { const server = await this.selectServer((0, server_selection_1.readPreferenceServerSelector)(readPreference), selectServerOptions); const skipPingOnConnect = this.s.options.__skipPingOnConnect === true; if (!skipPingOnConnect && this.s.credentials) { await server.command((0, utils_1.ns)("admin.$cmd"), { ping: 1 }, { timeoutContext }); stateTransition(this, common_1.STATE_CONNECTED); this.emit(_Topology.OPEN, this); this.emit(_Topology.CONNECT, this); return this; } stateTransition(this, common_1.STATE_CONNECTED); this.emit(_Topology.OPEN, this); this.emit(_Topology.CONNECT, this); return this; } catch (error) { this.close(); throw error; } } closeCheckedOutConnections() { for (const server of this.s.servers.values()) { return server.closeCheckedOutConnections(); } } /** Close this topology */ close() { if (this.s.state === common_1.STATE_CLOSED || this.s.state === common_1.STATE_CLOSING) { return; } for (const server of this.s.servers.values()) { closeServer(server, this); } this.s.servers.clear(); stateTransition(this, common_1.STATE_CLOSING); drainWaitQueue(this.waitQueue, new error_1.MongoTopologyClosedError()); if (this.s.srvPoller) { this.s.srvPoller.stop(); this.s.srvPoller.removeListener(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY, this.s.detectSrvRecords); } this.removeListener(_Topology.TOPOLOGY_DESCRIPTION_CHANGED, this.s.detectShardedTopology); stateTransition(this, common_1.STATE_CLOSED); this.emitAndLog(_Topology.TOPOLOGY_CLOSED, new events_1.TopologyClosedEvent(this.s.id)); } /** * Selects a server according to the selection predicate provided * * @param selector - An optional selector to select servers by, defaults to a random selection within a latency window * @param options - Optional settings related to server selection * @param callback - The callback used to indicate success or failure * @returns An instance of a `Server` meeting the criteria of the predicate provided */ async selectServer(selector, options) { let serverSelector; if (typeof selector !== "function") { if (typeof selector === "string") { serverSelector = (0, server_selection_1.readPreferenceServerSelector)(read_preference_1.ReadPreference.fromString(selector)); } else { let readPreference; if (selector instanceof read_preference_1.ReadPreference) { readPreference = selector; } else { read_preference_1.ReadPreference.translate(options); readPreference = options.readPreference || read_preference_1.ReadPreference.primary; } serverSelector = (0, server_selection_1.readPreferenceServerSelector)(readPreference); } } else { serverSelector = selector; } options = { serverSelectionTimeoutMS: this.s.serverSelectionTimeoutMS, ...options }; if (this.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) { this.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionStartedEvent(selector, this.description, options.operationName)); } let timeout; if (options.timeoutContext) timeout = options.timeoutContext.serverSelectionTimeout; else { timeout = timeout_1.Timeout.expires(options.serverSelectionTimeoutMS ?? 0); } const isSharded = this.description.type === common_1.TopologyType.Sharded; const session = options.session; const transaction = session && session.transaction; if (isSharded && transaction && transaction.server) { if (this.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) { this.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionSucceededEvent(selector, this.description, transaction.server.pool.address, options.operationName)); } if (options.timeoutContext?.clearServerSelectionTimeout) timeout?.clear(); return transaction.server; } const { promise: serverPromise, resolve, reject } = (0, utils_1.promiseWithResolvers)(); const waitQueueMember = { serverSelector, topologyDescription: this.description, mongoLogger: this.client.mongoLogger, transaction, resolve, reject, cancelled: false, startTime: (0, utils_1.now)(), operationName: options.operationName, waitingLogged: false, previousServer: options.previousServer }; const abortListener = (0, utils_1.addAbortListener)(options.signal, function() { waitQueueMember.cancelled = true; reject(this.reason); }); this.waitQueue.push(waitQueueMember); processWaitQueue(this); try { timeout?.throwIfExpired(); const server = await (timeout ? Promise.race([serverPromise, timeout]) : serverPromise); if (options.timeoutContext?.csotEnabled() && server.description.minRoundTripTime !== 0) { options.timeoutContext.minRoundTripTime = server.description.minRoundTripTime; } return server; } catch (error) { if (timeout_1.TimeoutError.is(error)) { waitQueueMember.cancelled = true; const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${timeout?.duration} ms`, this.description); if (this.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) { this.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionFailedEvent(selector, this.description, timeoutError, options.operationName)); } if (options.timeoutContext?.csotEnabled()) { throw new error_1.MongoOperationTimeoutError("Timed out during server selection", { cause: timeoutError }); } throw timeoutError; } throw error; } finally { abortListener?.[utils_1.kDispose](); if (options.timeoutContext?.clearServerSelectionTimeout) timeout?.clear(); } } /** * Update the internal TopologyDescription with a ServerDescription * * @param serverDescription - The server to update in the internal list of server descriptions */ serverUpdateHandler(serverDescription) { if (!this.s.description.hasServer(serverDescription.address)) { return; } if (isStaleServerDescription(this.s.description, serverDescription)) { return; } const previousTopologyDescription = this.s.description; const previousServerDescription = this.s.description.servers.get(serverDescription.address); if (!previousServerDescription) { return; } const clusterTime = serverDescription.$clusterTime; if (clusterTime) { (0, common_1._advanceClusterTime)(this, clusterTime); } const equalDescriptions = previousServerDescription && previousServerDescription.equals(serverDescription); this.s.description = this.s.description.update(serverDescription); if (this.s.description.compatibilityError) { this.emit(_Topology.ERROR, new error_1.MongoCompatibilityError(this.s.description.compatibilityError)); return; } if (!equalDescriptions) { const newDescription = this.s.description.servers.get(serverDescription.address); if (newDescription) { this.emit(_Topology.SERVER_DESCRIPTION_CHANGED, new events_1.ServerDescriptionChangedEvent(this.s.id, serverDescription.address, previousServerDescription, newDescription)); } } updateServers(this, serverDescription); if (this.waitQueue.length > 0) { processWaitQueue(this); } if (!equalDescriptions) { this.emitAndLog(_Topology.TOPOLOGY_DESCRIPTION_CHANGED, new events_1.TopologyDescriptionChangedEvent(this.s.id, previousTopologyDescription, this.s.description)); } } auth(credentials, callback) { if (typeof credentials === "function") callback = credentials, credentials = void 0; if (typeof callback === "function") callback(void 0, true); } get clientMetadata() { return this.s.options.metadata; } isConnected() { return this.s.state === common_1.STATE_CONNECTED; } isDestroyed() { return this.s.state === common_1.STATE_CLOSED; } // NOTE: There are many places in code where we explicitly check the last hello // to do feature support detection. This should be done any other way, but for // now we will just return the first hello seen, which should suffice. lastHello() { const serverDescriptions = Array.from(this.description.servers.values()); if (serverDescriptions.length === 0) return {}; const sd = serverDescriptions.filter((sd2) => sd2.type !== common_1.ServerType.Unknown)[0]; const result = sd || { maxWireVersion: this.description.commonWireVersion }; return result; } get commonWireVersion() { return this.description.commonWireVersion; } get logicalSessionTimeoutMinutes() { return this.description.logicalSessionTimeoutMinutes; } get clusterTime() { return this.s.clusterTime; } set clusterTime(clusterTime) { this.s.clusterTime = clusterTime; } }; exports2.Topology = Topology; Topology.SERVER_OPENING = constants_1.SERVER_OPENING; Topology.SERVER_CLOSED = constants_1.SERVER_CLOSED; Topology.SERVER_DESCRIPTION_CHANGED = constants_1.SERVER_DESCRIPTION_CHANGED; Topology.TOPOLOGY_OPENING = constants_1.TOPOLOGY_OPENING; Topology.TOPOLOGY_CLOSED = constants_1.TOPOLOGY_CLOSED; Topology.TOPOLOGY_DESCRIPTION_CHANGED = constants_1.TOPOLOGY_DESCRIPTION_CHANGED; Topology.ERROR = constants_1.ERROR; Topology.OPEN = constants_1.OPEN; Topology.CONNECT = constants_1.CONNECT; Topology.CLOSE = constants_1.CLOSE; Topology.TIMEOUT = constants_1.TIMEOUT; function closeServer(server, topology) { for (const event of constants_1.LOCAL_SERVER_EVENTS) { server.removeAllListeners(event); } server.close(); topology.emitAndLog(Topology.SERVER_CLOSED, new events_1.ServerClosedEvent(topology.s.id, server.description.address)); for (const event of constants_1.SERVER_RELAY_EVENTS) { server.removeAllListeners(event); } } function topologyTypeFromOptions(options) { if (options?.directConnection) { return common_1.TopologyType.Single; } if (options?.replicaSet) { return common_1.TopologyType.ReplicaSetNoPrimary; } if (options?.loadBalanced) { return common_1.TopologyType.LoadBalanced; } return common_1.TopologyType.Unknown; } function createAndConnectServer(topology, serverDescription) { topology.emitAndLog(Topology.SERVER_OPENING, new events_1.ServerOpeningEvent(topology.s.id, serverDescription.address)); const server = new server_1.Server(topology, serverDescription, topology.s.options); for (const event of constants_1.SERVER_RELAY_EVENTS) { server.on(event, (e) => topology.emit(event, e)); } server.on(server_1.Server.DESCRIPTION_RECEIVED, (description) => topology.serverUpdateHandler(description)); server.connect(); return server; } function updateServers(topology, incomingServerDescription) { if (incomingServerDescription && topology.s.servers.has(incomingServerDescription.address)) { const server = topology.s.servers.get(incomingServerDescription.address); if (server) { server.s.description = incomingServerDescription; if (incomingServerDescription.error instanceof error_1.MongoError && incomingServerDescription.error.hasErrorLabel(error_1.MongoErrorLabel.ResetPool)) { const interruptInUseConnections = incomingServerDescription.error.hasErrorLabel(error_1.MongoErrorLabel.InterruptInUseConnections); server.pool.clear({ interruptInUseConnections }); } else if (incomingServerDescription.error == null) { const newTopologyType = topology.s.description.type; const shouldMarkPoolReady = incomingServerDescription.isDataBearing || incomingServerDescription.type !== common_1.ServerType.Unknown && newTopologyType === common_1.TopologyType.Single; if (shouldMarkPoolReady) { server.pool.ready(); } } } } for (const serverDescription of topology.description.servers.values()) { if (!topology.s.servers.has(serverDescription.address)) { const server = createAndConnectServer(topology, serverDescription); topology.s.servers.set(serverDescription.address, server); } } for (const entry of topology.s.servers) { const serverAddress = entry[0]; if (topology.description.hasServer(serverAddress)) { continue; } if (!topology.s.servers.has(serverAddress)) { continue; } const server = topology.s.servers.get(serverAddress); topology.s.servers.delete(serverAddress); if (server) { closeServer(server, topology); } } } function drainWaitQueue(queue, drainError) { while (queue.length) { const waitQueueMember = queue.shift(); if (!waitQueueMember) { continue; } if (!waitQueueMember.cancelled) { if (waitQueueMember.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) { waitQueueMember.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionFailedEvent(waitQueueMember.serverSelector, waitQueueMember.topologyDescription, drainError, waitQueueMember.operationName)); } waitQueueMember.reject(drainError); } } } function processWaitQueue(topology) { if (topology.s.state === common_1.STATE_CLOSED) { drainWaitQueue(topology.waitQueue, new error_1.MongoTopologyClosedError()); return; } const isSharded = topology.description.type === common_1.TopologyType.Sharded; const serverDescriptions = Array.from(topology.description.servers.values()); const membersToProcess = topology.waitQueue.length; for (let i = 0; i < membersToProcess; ++i) { const waitQueueMember = topology.waitQueue.shift(); if (!waitQueueMember) { continue; } if (waitQueueMember.cancelled) { continue; } let selectedDescriptions; try { const serverSelector = waitQueueMember.serverSelector; const previousServer = waitQueueMember.previousServer; selectedDescriptions = serverSelector ? serverSelector(topology.description, serverDescriptions, previousServer ? [previousServer] : []) : serverDescriptions; } catch (selectorError) { if (topology.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) { topology.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionFailedEvent(waitQueueMember.serverSelector, topology.description, selectorError, waitQueueMember.operationName)); } waitQueueMember.reject(selectorError); continue; } let selectedServer; if (selectedDescriptions.length === 0) { if (!waitQueueMember.waitingLogged) { if (topology.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.INFORMATIONAL)) { topology.client.mongoLogger?.info(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.WaitingForSuitableServerEvent(waitQueueMember.serverSelector, topology.description, topology.s.serverSelectionTimeoutMS !== 0 ? topology.s.serverSelectionTimeoutMS - ((0, utils_1.now)() - waitQueueMember.startTime) : -1, waitQueueMember.operationName)); } waitQueueMember.waitingLogged = true; } topology.waitQueue.push(waitQueueMember); continue; } else if (selectedDescriptions.length === 1) { selectedServer = topology.s.servers.get(selectedDescriptions[0].address); } else { const descriptions = (0, utils_1.shuffle)(selectedDescriptions, 2); const server1 = topology.s.servers.get(descriptions[0].address); const server2 = topology.s.servers.get(descriptions[1].address); selectedServer = server1 && server2 && server1.s.operationCount < server2.s.operationCount ? server1 : server2; } if (!selectedServer) { const serverSelectionError = new error_1.MongoServerSelectionError("server selection returned a server description but the server was not found in the topology", topology.description); if (topology.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) { topology.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionFailedEvent(waitQueueMember.serverSelector, topology.description, serverSelectionError, waitQueueMember.operationName)); } waitQueueMember.reject(serverSelectionError); return; } const transaction = waitQueueMember.transaction; if (isSharded && transaction && transaction.isActive && selectedServer) { transaction.pinServer(selectedServer); } if (topology.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) { topology.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionSucceededEvent(waitQueueMember.serverSelector, waitQueueMember.topologyDescription, selectedServer.pool.address, waitQueueMember.operationName)); } waitQueueMember.resolve(selectedServer); } if (topology.waitQueue.length > 0) { for (const [, server] of topology.s.servers) { process.nextTick(function scheduleServerCheck() { return server.requestCheck(); }); } } } function isStaleServerDescription(topologyDescription, incomingServerDescription) { const currentServerDescription = topologyDescription.servers.get(incomingServerDescription.address); const currentTopologyVersion = currentServerDescription?.topologyVersion; return (0, server_description_1.compareTopologyVersion)(currentTopologyVersion, incomingServerDescription.topologyVersion) > 0; } var ServerCapabilities = class { constructor(hello) { this.minWireVersion = hello.minWireVersion || 0; this.maxWireVersion = hello.maxWireVersion || 0; } get hasAggregationCursor() { return this.maxWireVersion >= 1; } get hasWriteCommands() { return this.maxWireVersion >= 2; } get hasTextSearch() { return this.minWireVersion >= 0; } get hasAuthCommands() { return this.maxWireVersion >= 1; } get hasListCollectionsCommand() { return this.maxWireVersion >= 3; } get hasListIndexesCommand() { return this.maxWireVersion >= 3; } get supportsSnapshotReads() { return this.maxWireVersion >= 13; } get commandsTakeWriteConcern() { return this.maxWireVersion >= 5; } get commandsTakeCollation() { return this.maxWireVersion >= 5; } }; exports2.ServerCapabilities = ServerCapabilities; } }); // netlify/functions/node_modules/mongodb/lib/mongo_client.js var require_mongo_client = __commonJS({ "netlify/functions/node_modules/mongodb/lib/mongo_client.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.MongoClient = exports2.ServerApiVersion = void 0; var fs_1 = require("fs"); var bson_1 = require_bson2(); var change_stream_1 = require_change_stream(); var mongo_credentials_1 = require_mongo_credentials(); var providers_1 = require_providers(); var client_metadata_1 = require_client_metadata(); var connection_string_1 = require_connection_string(); var constants_1 = require_constants(); var db_1 = require_db(); var error_1 = require_error(); var mongo_client_auth_providers_1 = require_mongo_client_auth_providers(); var mongo_logger_1 = require_mongo_logger(); var mongo_types_1 = require_mongo_types(); var executor_1 = require_executor(); var execute_operation_1 = require_execute_operation(); var run_command_1 = require_run_command(); var read_preference_1 = require_read_preference(); var resource_management_1 = require_resource_management(); var server_selection_1 = require_server_selection(); var topology_1 = require_topology(); var sessions_1 = require_sessions(); var utils_1 = require_utils(); exports2.ServerApiVersion = Object.freeze({ v1: "1" }); var MongoClient = class extends mongo_types_1.TypedEventEmitter { constructor(url, options) { super(); this.on("error", utils_1.noop); this.options = (0, connection_string_1.parseOptions)(url, this, options); const shouldSetLogger = Object.values(this.options.mongoLoggerOptions.componentSeverities).some((value) => value !== mongo_logger_1.SeverityLevel.OFF); this.mongoLogger = shouldSetLogger ? new mongo_logger_1.MongoLogger(this.options.mongoLoggerOptions) : void 0; const client = this; this.s = { url, bsonOptions: (0, bson_1.resolveBSONOptions)(this.options), namespace: (0, utils_1.ns)("admin"), hasBeenClosed: false, sessionPool: new sessions_1.ServerSessionPool(this), activeSessions: /* @__PURE__ */ new Set(), activeCursors: /* @__PURE__ */ new Set(), authProviders: new mongo_client_auth_providers_1.MongoClientAuthProviders(), get options() { return client.options; }, get readConcern() { return client.options.readConcern; }, get writeConcern() { return client.options.writeConcern; }, get readPreference() { return client.options.readPreference; }, get isMongoClient() { return true; } }; this.checkForNonGenuineHosts(); } /** @internal */ async asyncDispose() { await this.close(); } /** * Append metadata to the client metadata after instantiation. * @param driverInfo - Information about the application or library. */ appendMetadata(driverInfo) { this.options.additionalDriverInfo.push(driverInfo); this.options.metadata = (0, client_metadata_1.makeClientMetadata)(this.options); this.options.extendedMetadata = (0, client_metadata_1.addContainerMetadata)(this.options.metadata).then(void 0, utils_1.squashError).then((result) => result ?? {}); } /** @internal */ checkForNonGenuineHosts() { const documentDBHostnames = this.options.hosts.filter((hostAddress) => (0, utils_1.isHostMatch)(utils_1.DOCUMENT_DB_CHECK, hostAddress.host)); const srvHostIsDocumentDB = (0, utils_1.isHostMatch)(utils_1.DOCUMENT_DB_CHECK, this.options.srvHost); const cosmosDBHostnames = this.options.hosts.filter((hostAddress) => (0, utils_1.isHostMatch)(utils_1.COSMOS_DB_CHECK, hostAddress.host)); const srvHostIsCosmosDB = (0, utils_1.isHostMatch)(utils_1.COSMOS_DB_CHECK, this.options.srvHost); if (documentDBHostnames.length !== 0 || srvHostIsDocumentDB) { this.mongoLogger?.info("client", utils_1.DOCUMENT_DB_MSG); } else if (cosmosDBHostnames.length !== 0 || srvHostIsCosmosDB) { this.mongoLogger?.info("client", utils_1.COSMOS_DB_MSG); } } get serverApi() { return this.options.serverApi && Object.freeze({ ...this.options.serverApi }); } /** * Intended for APM use only * @internal */ get monitorCommands() { return this.options.monitorCommands; } set monitorCommands(value) { this.options.monitorCommands = value; } /** @internal */ get autoEncrypter() { return this.options.autoEncrypter; } get readConcern() { return this.s.readConcern; } get writeConcern() { return this.s.writeConcern; } get readPreference() { return this.s.readPreference; } get bsonOptions() { return this.s.bsonOptions; } get timeoutMS() { return this.s.options.timeoutMS; } /** * Executes a client bulk write operation, available on server 8.0+. * @param models - The client bulk write models. * @param options - The client bulk write options. * @returns A ClientBulkWriteResult for acknowledged writes and ok: 1 for unacknowledged writes. */ async bulkWrite(models, options) { if (this.autoEncrypter) { throw new error_1.MongoInvalidArgumentError("MongoClient bulkWrite does not currently support automatic encryption."); } return await new executor_1.ClientBulkWriteExecutor(this, models, (0, utils_1.resolveOptions)(this, options)).execute(); } /** * Connect to MongoDB using a url * * @remarks * Calling `connect` is optional since the first operation you perform will call `connect` if it's needed. * `timeoutMS` will bound the time any operation can take before throwing a timeout error. * However, when the operation being run is automatically connecting your `MongoClient` the `timeoutMS` will not apply to the time taken to connect the MongoClient. * This means the time to setup the `MongoClient` does not count against `timeoutMS`. * If you are using `timeoutMS` we recommend connecting your client explicitly in advance of any operation to avoid this inconsistent execution time. * * @remarks * The driver will look up corresponding SRV and TXT records if the connection string starts with `mongodb+srv://`. * If those look ups throw a DNS Timeout error, the driver will retry the look up once. * * @see docs.mongodb.org/manual/reference/connection-string/ */ async connect() { if (this.connectionLock) { return await this.connectionLock; } try { this.connectionLock = this._connect(); await this.connectionLock; } finally { this.connectionLock = void 0; } return this; } /** * Create a topology to open the connection, must be locked to avoid topology leaks in concurrency scenario. * Locking is enforced by the connect method. * * @internal */ async _connect() { if (this.topology && this.topology.isConnected()) { return this; } const options = this.options; if (options.tls) { if (typeof options.tlsCAFile === "string") { options.ca ??= await fs_1.promises.readFile(options.tlsCAFile); } if (typeof options.tlsCRLFile === "string") { options.crl ??= await fs_1.promises.readFile(options.tlsCRLFile); } if (typeof options.tlsCertificateKeyFile === "string") { if (!options.key || !options.cert) { const contents = await fs_1.promises.readFile(options.tlsCertificateKeyFile); options.key ??= contents; options.cert ??= contents; } } } if (typeof options.srvHost === "string") { const hosts = await (0, connection_string_1.resolveSRVRecord)(options); for (const [index, host] of hosts.entries()) { options.hosts[index] = host; } } if (options.credentials?.mechanism === providers_1.AuthMechanism.MONGODB_OIDC) { const allowedHosts = options.credentials?.mechanismProperties?.ALLOWED_HOSTS || mongo_credentials_1.DEFAULT_ALLOWED_HOSTS; const isServiceAuth = !!options.credentials?.mechanismProperties?.ENVIRONMENT; if (!isServiceAuth) { for (const host of options.hosts) { if (!(0, utils_1.hostMatchesWildcards)(host.toHostPort().host, allowedHosts)) { throw new error_1.MongoInvalidArgumentError(`Host '${host}' is not valid for OIDC authentication with ALLOWED_HOSTS of '${allowedHosts.join(",")}'`); } } } } this.topology = new topology_1.Topology(this, options.hosts, options); this.topology.once(topology_1.Topology.OPEN, () => this.emit("open", this)); for (const event of constants_1.MONGO_CLIENT_EVENTS) { this.topology.on(event, (...args) => this.emit(event, ...args)); } const topologyConnect = async () => { try { await this.topology?.connect(options); } catch (error) { this.topology?.close(); throw error; } }; if (this.autoEncrypter) { await this.autoEncrypter?.init(); await topologyConnect(); await options.encrypter.connectInternalClient(); } else { await topologyConnect(); } return this; } /** * Cleans up resources managed by the MongoClient. * * The close method clears and closes all resources whose lifetimes are managed by the MongoClient. * Please refer to the `MongoClient` class documentation for a high level overview of the client's key features and responsibilities. * * **However,** the close method does not handle the cleanup of resources explicitly created by the user. * Any user-created driver resource with its own `close()` method should be explicitly closed by the user before calling MongoClient.close(). * This method is written as a "best effort" attempt to leave behind the least amount of resources server-side when possible. * * The following list defines ideal preconditions and consequent pitfalls if they are not met. * The MongoClient, ClientSession, Cursors and ChangeStreams all support [explicit resource management](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html). * By using explicit resource management to manage the lifetime of driver resources instead of manually managing their lifetimes, the pitfalls outlined below can be avoided. * * The close method performs the following in the order listed: * - Client-side: * - **Close in-use connections**: Any connections that are currently waiting on a response from the server will be closed. * This is performed _first_ to avoid reaching the next step (server-side clean up) and having no available connections to check out. * - _Ideal_: All operations have been awaited or cancelled, and the outcomes, regardless of success or failure, have been processed before closing the client servicing the operation. * - _Pitfall_: When `client.close()` is called and all connections are in use, after closing them, the client must create new connections for cleanup operations, which comes at the cost of new TLS/TCP handshakes and authentication steps. * - Server-side: * - **Close active cursors**: All cursors that haven't been completed will have a `killCursor` operation sent to the server they were initialized on, freeing the server-side resource. * - _Ideal_: Cursors are explicitly closed or completed before `client.close()` is called. * - _Pitfall_: `killCursors` may have to build a new connection if the in-use closure ended all pooled connections. * - **End active sessions**: In-use sessions created with `client.startSession()` or `client.withSession()` or implicitly by the driver will have their `.endSession()` method called. * Contrary to the name of the method, `endSession()` returns the session to the client's pool of sessions rather than end them on the server. * - _Ideal_: Transaction outcomes are awaited and their corresponding explicit sessions are ended before `client.close()` is called. * - _Pitfall_: **This step aborts in-progress transactions**. It is advisable to observe the outcome of a transaction before closing your client. * - **End all pooled sessions**: The `endSessions` command with all session IDs the client has pooled is sent to the server to inform the cluster it can clean them up. * - _Ideal_: No user intervention is expected. * - _Pitfall_: None. * * The remaining shutdown is of the MongoClient resources that are intended to be entirely internal but is documented here as their existence relates to the JS event loop. * * - Client-side (again): * - **Stop all server monitoring**: Connections kept live for detecting cluster changes and roundtrip time measurements are shutdown. * - **Close all pooled connections**: Each server node in the cluster has a corresponding connection pool and all connections in the pool are closed. Any operations waiting to check out a connection will have an error thrown instead of a connection returned. * - **Clear out server selection queue**: Any operations that are in the process of waiting for a server to be selected will have an error thrown instead of a server returned. * - **Close encryption-related resources**: An internal MongoClient created for communicating with `mongocryptd` or other encryption purposes is closed. (Using this same method of course!) * * After the close method completes there should be no MongoClient related resources [ref-ed in Node.js' event loop](https://docs.libuv.org/en/v1.x/handle.html#reference-counting). * This should allow Node.js to exit gracefully if MongoClient resources were the only active handles in the event loop. * * @param _force - currently an unused flag that has no effect. Defaults to `false`. */ async close(_force = false) { if (this.closeLock) { return await this.closeLock; } try { this.closeLock = this._close(); await this.closeLock; } finally { this.closeLock = void 0; } } /* @internal */ async _close() { Object.defineProperty(this.s, "hasBeenClosed", { value: true, enumerable: true, configurable: false, writable: false }); this.topology?.closeCheckedOutConnections(); const activeCursorCloses = Array.from(this.s.activeCursors, (cursor) => cursor.close()); this.s.activeCursors.clear(); await Promise.all(activeCursorCloses); const activeSessionEnds = Array.from(this.s.activeSessions, (session) => session.endSession()); this.s.activeSessions.clear(); await Promise.all(activeSessionEnds); if (this.topology == null) { return; } const selector = (0, server_selection_1.readPreferenceServerSelector)(read_preference_1.ReadPreference.primaryPreferred); const topologyDescription = this.topology.description; const serverDescriptions = Array.from(topologyDescription.servers.values()); const servers = selector(topologyDescription, serverDescriptions); if (servers.length !== 0) { const endSessions = Array.from(this.s.sessionPool.sessions, ({ id }) => id); if (endSessions.length !== 0) { try { await (0, execute_operation_1.executeOperation)(this, new run_command_1.RunAdminCommandOperation({ endSessions }, { readPreference: read_preference_1.ReadPreference.primaryPreferred, noResponse: true })); } catch (error) { (0, utils_1.squashError)(error); } } } const topology = this.topology; this.topology = void 0; topology.close(); const { encrypter } = this.options; if (encrypter) { await encrypter.close(this); } } /** * Create a new Db instance sharing the current socket connections. * * @param dbName - The name of the database we want to use. If not provided, use database name from connection string. * @param options - Optional settings for Db construction */ db(dbName, options) { options = options ?? {}; if (!dbName) { dbName = this.s.options.dbName; } const finalOptions = Object.assign({}, this.options, options); const db = new db_1.Db(this, dbName, finalOptions); return db; } /** * Connect to MongoDB using a url * * @remarks * Calling `connect` is optional since the first operation you perform will call `connect` if it's needed. * `timeoutMS` will bound the time any operation can take before throwing a timeout error. * However, when the operation being run is automatically connecting your `MongoClient` the `timeoutMS` will not apply to the time taken to connect the MongoClient. * This means the time to setup the `MongoClient` does not count against `timeoutMS`. * If you are using `timeoutMS` we recommend connecting your client explicitly in advance of any operation to avoid this inconsistent execution time. * * @remarks * The programmatically provided options take precedence over the URI options. * * @remarks * The driver will look up corresponding SRV and TXT records if the connection string starts with `mongodb+srv://`. * If those look ups throw a DNS Timeout error, the driver will retry the look up once. * * @see https://www.mongodb.com/docs/manual/reference/connection-string/ */ static async connect(url, options) { const client = new this(url, options); return await client.connect(); } /** * Creates a new ClientSession. When using the returned session in an operation * a corresponding ServerSession will be created. * * @remarks * A ClientSession instance may only be passed to operations being performed on the same * MongoClient it was started from. */ startSession(options) { const session = new sessions_1.ClientSession(this, this.s.sessionPool, { explicit: true, ...options }, this.options); this.s.activeSessions.add(session); session.once("ended", () => { this.s.activeSessions.delete(session); }); return session; } async withSession(optionsOrExecutor, executor) { const options = { // Always define an owner owner: Symbol(), // If it's an object inherit the options ...typeof optionsOrExecutor === "object" ? optionsOrExecutor : {} }; const withSessionCallback = typeof optionsOrExecutor === "function" ? optionsOrExecutor : executor; if (withSessionCallback == null) { throw new error_1.MongoInvalidArgumentError("Missing required callback parameter"); } const session = this.startSession(options); try { return await withSessionCallback(session); } finally { try { await session.endSession(); } catch (error) { (0, utils_1.squashError)(error); } } } /** * Create a new Change Stream, watching for new changes (insertions, updates, * replacements, deletions, and invalidations) in this cluster. Will ignore all * changes to system collections, as well as the local, admin, and config databases. * * @remarks * watch() accepts two generic arguments for distinct use cases: * - The first is to provide the schema that may be defined for all the data within the current cluster * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument * * @remarks * When `timeoutMS` is configured for a change stream, it will have different behaviour depending * on whether the change stream is in iterator mode or emitter mode. In both cases, a change * stream will time out if it does not receive a change event within `timeoutMS` of the last change * event. * * Note that if a change stream is consistently timing out when watching a collection, database or * client that is being changed, then this may be due to the server timing out before it can finish * processing the existing oplog. To address this, restart the change stream with a higher * `timeoutMS`. * * If the change stream times out the initial aggregate operation to establish the change stream on * the server, then the client will close the change stream. If the getMore calls to the server * time out, then the change stream will be left open, but will throw a MongoOperationTimeoutError * when in iterator mode and emit an error event that returns a MongoOperationTimeoutError in * emitter mode. * * To determine whether or not the change stream is still open following a timeout, check the * {@link ChangeStream.closed} getter. * * @example * In iterator mode, if a next() call throws a timeout error, it will attempt to resume the change stream. * The next call can just be retried after this succeeds. * ```ts * const changeStream = collection.watch([], { timeoutMS: 100 }); * try { * await changeStream.next(); * } catch (e) { * if (e instanceof MongoOperationTimeoutError && !changeStream.closed) { * await changeStream.next(); * } * throw e; * } * ``` * * @example * In emitter mode, if the change stream goes `timeoutMS` without emitting a change event, it will * emit an error event that returns a MongoOperationTimeoutError, but will not close the change * stream unless the resume attempt fails. There is no need to re-establish change listeners as * this will automatically continue emitting change events once the resume attempt completes. * * ```ts * const changeStream = collection.watch([], { timeoutMS: 100 }); * changeStream.on('change', console.log); * changeStream.on('error', e => { * if (e instanceof MongoOperationTimeoutError && !changeStream.closed) { * // do nothing * } else { * changeStream.close(); * } * }); * ``` * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. * @param options - Optional settings for the command * @typeParam TSchema - Type of the data being detected by the change stream * @typeParam TChange - Type of the whole change stream document emitted */ watch(pipeline = [], options = {}) { if (!Array.isArray(pipeline)) { options = pipeline; pipeline = []; } return new change_stream_1.ChangeStream(this, pipeline, (0, utils_1.resolveOptions)(this, options)); } }; exports2.MongoClient = MongoClient; (0, resource_management_1.configureResourceManagement)(MongoClient.prototype); } }); // netlify/functions/node_modules/mongodb/lib/resource_management.js var require_resource_management = __commonJS({ "netlify/functions/node_modules/mongodb/lib/resource_management.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.configureResourceManagement = configureResourceManagement; exports2.configureExplicitResourceManagement = configureExplicitResourceManagement; function configureResourceManagement(target) { Symbol.asyncDispose && Object.defineProperty(target, Symbol.asyncDispose, { value: async function asyncDispose() { await this.asyncDispose(); }, enumerable: false, configurable: true, writable: true }); } function configureExplicitResourceManagement() { const { MongoClient } = require_mongo_client(); const { ClientSession } = require_sessions(); const { AbstractCursor } = require_abstract_cursor(); const { ChangeStream } = require_change_stream(); configureResourceManagement(MongoClient.prototype); configureResourceManagement(ClientSession.prototype); configureResourceManagement(AbstractCursor.prototype); configureResourceManagement(ChangeStream.prototype); } } }); // netlify/functions/node_modules/mongodb/lib/cursor/abstract_cursor.js var require_abstract_cursor = __commonJS({ "netlify/functions/node_modules/mongodb/lib/cursor/abstract_cursor.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.CursorTimeoutContext = exports2.AbstractCursor = exports2.CursorTimeoutMode = exports2.CURSOR_FLAGS = void 0; var stream_1 = require("stream"); var bson_1 = require_bson2(); var error_1 = require_error(); var mongo_types_1 = require_mongo_types(); var execute_operation_1 = require_execute_operation(); var get_more_1 = require_get_more(); var kill_cursors_1 = require_kill_cursors(); var read_concern_1 = require_read_concern(); var read_preference_1 = require_read_preference(); var resource_management_1 = require_resource_management(); var sessions_1 = require_sessions(); var timeout_1 = require_timeout(); var utils_1 = require_utils(); exports2.CURSOR_FLAGS = [ "tailable", "oplogReplay", "noCursorTimeout", "awaitData", "exhaust", "partial" ]; function removeActiveCursor() { this.client.s.activeCursors.delete(this); } exports2.CursorTimeoutMode = Object.freeze({ ITERATION: "iteration", LIFETIME: "cursorLifetime" }); var AbstractCursor = class extends mongo_types_1.TypedEventEmitter { /** @internal */ constructor(client, namespace, options = {}) { super(); this.documents = null; this.hasEmittedClose = false; this.on("error", utils_1.noop); if (!client.s.isMongoClient) { throw new error_1.MongoRuntimeError("Cursor must be constructed with MongoClient"); } this.cursorClient = client; this.cursorNamespace = namespace; this.cursorId = null; this.initialized = false; this.isClosed = false; this.isKilled = false; this.cursorOptions = { readPreference: options.readPreference && options.readPreference instanceof read_preference_1.ReadPreference ? options.readPreference : read_preference_1.ReadPreference.primary, ...(0, bson_1.pluckBSONSerializeOptions)(options), timeoutMS: options?.timeoutContext?.csotEnabled() ? options.timeoutContext.timeoutMS : options.timeoutMS, tailable: options.tailable, awaitData: options.awaitData }; if (this.cursorOptions.timeoutMS != null) { if (options.timeoutMode == null) { if (options.tailable) { if (options.awaitData) { if (options.maxAwaitTimeMS != null && options.maxAwaitTimeMS >= this.cursorOptions.timeoutMS) throw new error_1.MongoInvalidArgumentError("Cannot specify maxAwaitTimeMS >= timeoutMS for a tailable awaitData cursor"); } this.cursorOptions.timeoutMode = exports2.CursorTimeoutMode.ITERATION; } else { this.cursorOptions.timeoutMode = exports2.CursorTimeoutMode.LIFETIME; } } else { if (options.tailable && options.timeoutMode === exports2.CursorTimeoutMode.LIFETIME) { throw new error_1.MongoInvalidArgumentError("Cannot set tailable cursor's timeoutMode to LIFETIME"); } this.cursorOptions.timeoutMode = options.timeoutMode; } } else { if (options.timeoutMode != null) throw new error_1.MongoInvalidArgumentError("Cannot set timeoutMode without setting timeoutMS"); } this.cursorOptions.omitMaxTimeMS = this.cursorOptions.timeoutMS != null && (this.cursorOptions.timeoutMode === exports2.CursorTimeoutMode.ITERATION && !this.cursorOptions.tailable || this.cursorOptions.tailable && !this.cursorOptions.awaitData); const readConcern = read_concern_1.ReadConcern.fromOptions(options); if (readConcern) { this.cursorOptions.readConcern = readConcern; } if (typeof options.batchSize === "number") { this.cursorOptions.batchSize = options.batchSize; } if (options.comment !== void 0) { this.cursorOptions.comment = options.comment; } if (typeof options.maxTimeMS === "number") { this.cursorOptions.maxTimeMS = options.maxTimeMS; } if (typeof options.maxAwaitTimeMS === "number") { this.cursorOptions.maxAwaitTimeMS = options.maxAwaitTimeMS; } this.cursorSession = options.session ?? null; this.deserializationOptions = { ...this.cursorOptions, validation: { utf8: options?.enableUtf8Validation === false ? false : true } }; this.timeoutContext = options.timeoutContext; this.signal = options.signal; this.abortListener = (0, utils_1.addAbortListener)(this.signal, () => void this.close().then(void 0, utils_1.squashError)); this.trackCursor(); } /** * The cursor has no id until it receives a response from the initial cursor creating command. * * It is non-zero for as long as the database has an open cursor. * * The initiating command may receive a zero id if the entire result is in the `firstBatch`. */ get id() { return this.cursorId ?? void 0; } /** @internal */ get isDead() { return (this.cursorId?.isZero() ?? false) || this.isClosed || this.isKilled; } /** @internal */ get client() { return this.cursorClient; } /** @internal */ get server() { return this.selectedServer; } get namespace() { return this.cursorNamespace; } get readPreference() { return this.cursorOptions.readPreference; } get readConcern() { return this.cursorOptions.readConcern; } /** @internal */ get session() { return this.cursorSession; } set session(clientSession) { this.cursorSession = clientSession; } /** * The cursor is closed and all remaining locally buffered documents have been iterated. */ get closed() { return this.isClosed && (this.documents?.length ?? 0) === 0; } /** * A `killCursors` command was attempted on this cursor. * This is performed if the cursor id is non zero. */ get killed() { return this.isKilled; } get loadBalanced() { return !!this.cursorClient.topology?.loadBalanced; } /** @internal */ async asyncDispose() { await this.close(); } /** Adds cursor to client's tracking so it will be closed by MongoClient.close() */ trackCursor() { this.cursorClient.s.activeCursors.add(this); if (!this.listeners("close").includes(removeActiveCursor)) { this.once("close", removeActiveCursor); } } /** Returns current buffered documents length */ bufferedCount() { return this.documents?.length ?? 0; } /** Returns current buffered documents */ readBufferedDocuments(number) { const bufferedDocs = []; const documentsToRead = Math.min(number ?? this.documents?.length ?? 0, this.documents?.length ?? 0); for (let count = 0; count < documentsToRead; count++) { const document2 = this.documents?.shift(this.deserializationOptions); if (document2 != null) { bufferedDocs.push(document2); } } return bufferedDocs; } async *[Symbol.asyncIterator]() { this.signal?.throwIfAborted(); if (this.closed) { return; } try { while (true) { if (this.isKilled) { return; } if (this.closed) { return; } if (this.cursorId != null && this.isDead && (this.documents?.length ?? 0) === 0) { return; } const document2 = await this.next(); if (document2 === null) { return; } yield document2; this.signal?.throwIfAborted(); } } finally { if (!this.isClosed) { try { await this.close(); } catch (error) { (0, utils_1.squashError)(error); } } } } stream(options) { const readable = new ReadableCursorStream(this); const abortListener = (0, utils_1.addAbortListener)(this.signal, function() { readable.destroy(this.reason); }); readable.once("end", () => { abortListener?.[utils_1.kDispose](); }); if (options?.transform) { const transform = options.transform; const transformedStream = readable.pipe(new stream_1.Transform({ objectMode: true, highWaterMark: 1, transform(chunk, _, callback) { try { const transformed = transform(chunk); callback(void 0, transformed); } catch (err) { callback(err); } } })); readable.on("error", (err) => transformedStream.emit("error", err)); return transformedStream; } return readable; } async hasNext() { this.signal?.throwIfAborted(); if (this.cursorId === bson_1.Long.ZERO) { return false; } if (this.cursorOptions.timeoutMode === exports2.CursorTimeoutMode.ITERATION && this.cursorId != null) { this.timeoutContext?.refresh(); } try { do { if ((this.documents?.length ?? 0) !== 0) { return true; } await this.fetchBatch(); } while (!this.isDead || (this.documents?.length ?? 0) !== 0); } finally { if (this.cursorOptions.timeoutMode === exports2.CursorTimeoutMode.ITERATION) { this.timeoutContext?.clear(); } } return false; } /** Get the next available document from the cursor, returns null if no more documents are available. */ async next() { this.signal?.throwIfAborted(); if (this.cursorId === bson_1.Long.ZERO) { throw new error_1.MongoCursorExhaustedError(); } if (this.cursorOptions.timeoutMode === exports2.CursorTimeoutMode.ITERATION && this.cursorId != null) { this.timeoutContext?.refresh(); } try { do { const doc = this.documents?.shift(this.deserializationOptions); if (doc != null) { if (this.transform != null) return await this.transformDocument(doc); return doc; } await this.fetchBatch(); } while (!this.isDead || (this.documents?.length ?? 0) !== 0); } finally { if (this.cursorOptions.timeoutMode === exports2.CursorTimeoutMode.ITERATION) { this.timeoutContext?.clear(); } } return null; } /** * Try to get the next available document from the cursor or `null` if an empty batch is returned */ async tryNext() { this.signal?.throwIfAborted(); if (this.cursorId === bson_1.Long.ZERO) { throw new error_1.MongoCursorExhaustedError(); } if (this.cursorOptions.timeoutMode === exports2.CursorTimeoutMode.ITERATION && this.cursorId != null) { this.timeoutContext?.refresh(); } try { let doc = this.documents?.shift(this.deserializationOptions); if (doc != null) { if (this.transform != null) return await this.transformDocument(doc); return doc; } await this.fetchBatch(); doc = this.documents?.shift(this.deserializationOptions); if (doc != null) { if (this.transform != null) return await this.transformDocument(doc); return doc; } } finally { if (this.cursorOptions.timeoutMode === exports2.CursorTimeoutMode.ITERATION) { this.timeoutContext?.clear(); } } return null; } /** * Iterates over all the documents for this cursor using the iterator, callback pattern. * * If the iterator returns `false`, iteration will stop. * * @param iterator - The iteration callback. * @deprecated - Will be removed in a future release. Use for await...of instead. */ async forEach(iterator) { this.signal?.throwIfAborted(); if (typeof iterator !== "function") { throw new error_1.MongoInvalidArgumentError('Argument "iterator" must be a function'); } for await (const document2 of this) { const result = iterator(document2); if (result === false) { break; } } } /** * Frees any client-side resources used by the cursor. */ async close(options) { await this.cleanup(options?.timeoutMS); } /** * Returns an array of documents. The caller is responsible for making sure that there * is enough memory to store the results. Note that the array only contains partial * results when this cursor had been previously accessed. In that case, * cursor.rewind() can be used to reset the cursor. */ async toArray() { this.signal?.throwIfAborted(); const array = []; for await (const document2 of this) { array.push(document2); const docs = this.readBufferedDocuments(); if (this.transform != null) { for (const doc of docs) { array.push(await this.transformDocument(doc)); } } else { array.push(...docs); } } return array; } /** * Add a cursor flag to the cursor * * @param flag - The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -. * @param value - The flag boolean value. */ addCursorFlag(flag, value) { this.throwIfInitialized(); if (!exports2.CURSOR_FLAGS.includes(flag)) { throw new error_1.MongoInvalidArgumentError(`Flag ${flag} is not one of ${exports2.CURSOR_FLAGS}`); } if (typeof value !== "boolean") { throw new error_1.MongoInvalidArgumentError(`Flag ${flag} must be a boolean value`); } this.cursorOptions[flag] = value; return this; } /** * Map all documents using the provided function * If there is a transform set on the cursor, that will be called first and the result passed to * this function's transform. * * @remarks * * **Note** Cursors use `null` internally to indicate that there are no more documents in the cursor. Providing a mapping * function that maps values to `null` will result in the cursor closing itself before it has finished iterating * all documents. This will **not** result in a memory leak, just surprising behavior. For example: * * ```typescript * const cursor = collection.find({}); * cursor.map(() => null); * * const documents = await cursor.toArray(); * // documents is always [], regardless of how many documents are in the collection. * ``` * * Other falsey values are allowed: * * ```typescript * const cursor = collection.find({}); * cursor.map(() => ''); * * const documents = await cursor.toArray(); * // documents is now an array of empty strings * ``` * * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, * it **does not** return a new instance of a cursor. This means when calling map, * you should always assign the result to a new variable in order to get a correctly typed cursor variable. * Take note of the following example: * * @example * ```typescript * const cursor: FindCursor = coll.find(); * const mappedCursor: FindCursor = cursor.map(doc => Object.keys(doc).length); * const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[] * ``` * @param transform - The mapping transformation method. */ map(transform) { this.throwIfInitialized(); const oldTransform = this.transform; if (oldTransform) { this.transform = (doc) => { return transform(oldTransform(doc)); }; } else { this.transform = transform; } return this; } /** * Set the ReadPreference for the cursor. * * @param readPreference - The new read preference for the cursor. */ withReadPreference(readPreference) { this.throwIfInitialized(); if (readPreference instanceof read_preference_1.ReadPreference) { this.cursorOptions.readPreference = readPreference; } else if (typeof readPreference === "string") { this.cursorOptions.readPreference = read_preference_1.ReadPreference.fromString(readPreference); } else { throw new error_1.MongoInvalidArgumentError(`Invalid read preference: ${readPreference}`); } return this; } /** * Set the ReadPreference for the cursor. * * @param readPreference - The new read preference for the cursor. */ withReadConcern(readConcern) { this.throwIfInitialized(); const resolvedReadConcern = read_concern_1.ReadConcern.fromOptions({ readConcern }); if (resolvedReadConcern) { this.cursorOptions.readConcern = resolvedReadConcern; } return this; } /** * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) * * @param value - Number of milliseconds to wait before aborting the query. */ maxTimeMS(value) { this.throwIfInitialized(); if (typeof value !== "number") { throw new error_1.MongoInvalidArgumentError("Argument for maxTimeMS must be a number"); } this.cursorOptions.maxTimeMS = value; return this; } /** * Set the batch size for the cursor. * * @param value - The number of documents to return per batch. See {@link https://www.mongodb.com/docs/manual/reference/command/find/|find command documentation}. */ batchSize(value) { this.throwIfInitialized(); if (this.cursorOptions.tailable) { throw new error_1.MongoTailableCursorError("Tailable cursor does not support batchSize"); } if (typeof value !== "number") { throw new error_1.MongoInvalidArgumentError('Operation "batchSize" requires an integer'); } this.cursorOptions.batchSize = value; return this; } /** * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even * if the resultant data has already been retrieved by this cursor. */ rewind() { if (this.timeoutContext && this.timeoutContext.owner !== this) { throw new error_1.MongoAPIError(`Cannot rewind cursor that does not own its timeout context.`); } if (!this.initialized) { return; } this.cursorId = null; this.documents?.clear(); this.timeoutContext?.clear(); this.timeoutContext = void 0; this.isClosed = false; this.isKilled = false; this.initialized = false; this.hasEmittedClose = false; this.trackCursor(); if (this.cursorSession?.explicit === false) { if (!this.cursorSession.hasEnded) { this.cursorSession.endSession().then(void 0, utils_1.squashError); } this.cursorSession = null; } } /** @internal */ async getMore(batchSize) { if (this.cursorId == null) { throw new error_1.MongoRuntimeError("Unexpected null cursor id. A cursor creating command should have set this"); } if (this.selectedServer == null) { throw new error_1.MongoRuntimeError("Unexpected null selectedServer. A cursor creating command should have set this"); } if (this.cursorSession == null) { throw new error_1.MongoRuntimeError("Unexpected null session. A cursor creating command should have set this"); } const getMoreOptions = { ...this.cursorOptions, session: this.cursorSession, batchSize }; const getMoreOperation = new get_more_1.GetMoreOperation(this.cursorNamespace, this.cursorId, this.selectedServer, getMoreOptions); return await (0, execute_operation_1.executeOperation)(this.cursorClient, getMoreOperation, this.timeoutContext); } /** * @internal * * This function is exposed for the unified test runner's createChangeStream * operation. We cannot refactor to use the abstract _initialize method without * a significant refactor. */ async cursorInit() { if (this.cursorOptions.timeoutMS != null) { this.timeoutContext ??= new CursorTimeoutContext(timeout_1.TimeoutContext.create({ serverSelectionTimeoutMS: this.client.s.options.serverSelectionTimeoutMS, timeoutMS: this.cursorOptions.timeoutMS }), this); } try { this.cursorSession ??= this.cursorClient.startSession({ owner: this, explicit: false }); const state = await this._initialize(this.cursorSession); this.cursorOptions.omitMaxTimeMS = this.cursorOptions.timeoutMS != null; const response = state.response; this.selectedServer = state.server; this.cursorId = response.id; this.cursorNamespace = response.ns ?? this.namespace; this.documents = response; this.initialized = true; } catch (error) { this.initialized = true; await this.cleanup(void 0, error); throw error; } if (this.isDead) { await this.cleanup(); } return; } /** @internal Attempt to obtain more documents */ async fetchBatch() { if (this.isClosed) { return; } if (this.isDead) { await this.cleanup(); return; } if (this.cursorId == null) { await this.cursorInit(); if ((this.documents?.length ?? 0) !== 0 || this.isDead) return; } const batchSize = this.cursorOptions.batchSize || 1e3; try { const response = await this.getMore(batchSize); this.cursorId = response.id; this.documents = response; } catch (error) { try { await this.cleanup(void 0, error); } catch (cleanupError) { (0, utils_1.squashError)(cleanupError); } throw error; } if (this.isDead) { await this.cleanup(); } } /** @internal */ async cleanup(timeoutMS, error) { this.abortListener?.[utils_1.kDispose](); this.isClosed = true; const timeoutContextForKillCursors = () => { if (timeoutMS != null) { this.timeoutContext?.clear(); return new CursorTimeoutContext(timeout_1.TimeoutContext.create({ serverSelectionTimeoutMS: this.client.s.options.serverSelectionTimeoutMS, timeoutMS }), this); } else { return this.timeoutContext?.refreshed(); } }; const withEmitClose = async (fn) => { try { await fn(); } finally { this.emitClose(); } }; const close = async () => { const session = this.cursorSession; if (!session) return; try { if (!this.isKilled && this.cursorId && !this.cursorId.isZero() && this.cursorNamespace && this.selectedServer && !session.hasEnded) { this.isKilled = true; const cursorId = this.cursorId; this.cursorId = bson_1.Long.ZERO; await (0, execute_operation_1.executeOperation)(this.cursorClient, new kill_cursors_1.KillCursorsOperation(cursorId, this.cursorNamespace, this.selectedServer, { session }), timeoutContextForKillCursors()); } } catch (error2) { (0, utils_1.squashError)(error2); } finally { if (session.owner === this) { await session.endSession({ error }); } if (!session.inTransaction()) { (0, sessions_1.maybeClearPinnedConnection)(session, { error }); } } }; await withEmitClose(close); } /** @internal */ emitClose() { try { if (!this.hasEmittedClose && ((this.documents?.length ?? 0) === 0 || this.isClosed)) { this.emit("close"); } } finally { this.hasEmittedClose = true; } } /** @internal */ async transformDocument(document2) { if (this.transform == null) return document2; try { const transformedDocument = this.transform(document2); if (transformedDocument === null) { const TRANSFORM_TO_NULL_ERROR = "Cursor returned a `null` document, but the cursor is not exhausted. Mapping documents to `null` is not supported in the cursor transform."; throw new error_1.MongoAPIError(TRANSFORM_TO_NULL_ERROR); } return transformedDocument; } catch (transformError) { try { await this.close(); } catch (closeError) { (0, utils_1.squashError)(closeError); } throw transformError; } } /** @internal */ throwIfInitialized() { if (this.initialized) throw new error_1.MongoCursorInUseError(); } }; exports2.AbstractCursor = AbstractCursor; AbstractCursor.CLOSE = "close"; var ReadableCursorStream = class extends stream_1.Readable { constructor(cursor) { super({ objectMode: true, autoDestroy: false, highWaterMark: 1 }); this._readInProgress = false; this._cursor = cursor; } // eslint-disable-next-line @typescript-eslint/no-unused-vars _read(size) { if (!this._readInProgress) { this._readInProgress = true; this._readNext(); } } _destroy(error, callback) { this._cursor.close().then(() => callback(error), (closeError) => callback(closeError)); } _readNext() { if (this._cursor.id === bson_1.Long.ZERO) { this.push(null); return; } this._cursor.next().then( // result from next() (result) => { if (result == null) { this.push(null); } else if (this.destroyed) { this._cursor.close().then(void 0, utils_1.squashError); } else { if (this.push(result)) { return this._readNext(); } this._readInProgress = false; } }, // error from next() (err) => { if (err.message.match(/server is closed/)) { this._cursor.close().then(void 0, utils_1.squashError); return this.push(null); } if (err.message.match(/operation was interrupted/)) { return this.push(null); } return this.destroy(err); } ).catch((error) => { this._readInProgress = false; this.destroy(error); }); } }; (0, resource_management_1.configureResourceManagement)(AbstractCursor.prototype); var CursorTimeoutContext = class _CursorTimeoutContext extends timeout_1.TimeoutContext { constructor(timeoutContext, owner) { super(); this.timeoutContext = timeoutContext; this.owner = owner; } get serverSelectionTimeout() { return this.timeoutContext.serverSelectionTimeout; } get connectionCheckoutTimeout() { return this.timeoutContext.connectionCheckoutTimeout; } get clearServerSelectionTimeout() { return this.timeoutContext.clearServerSelectionTimeout; } get timeoutForSocketWrite() { return this.timeoutContext.timeoutForSocketWrite; } get timeoutForSocketRead() { return this.timeoutContext.timeoutForSocketRead; } csotEnabled() { return this.timeoutContext.csotEnabled(); } refresh() { if (typeof this.owner !== "symbol") return this.timeoutContext.refresh(); } clear() { if (typeof this.owner !== "symbol") return this.timeoutContext.clear(); } get maxTimeMS() { return this.timeoutContext.maxTimeMS; } get timeoutMS() { return this.timeoutContext.csotEnabled() ? this.timeoutContext.timeoutMS : null; } refreshed() { return new _CursorTimeoutContext(this.timeoutContext.refreshed(), this.owner); } addMaxTimeMSToCommand(command, options) { this.timeoutContext.addMaxTimeMSToCommand(command, options); } getSocketTimeoutMS() { return this.timeoutContext.getSocketTimeoutMS(); } }; exports2.CursorTimeoutContext = CursorTimeoutContext; } }); // netlify/functions/node_modules/mongodb/lib/explain.js var require_explain = __commonJS({ "netlify/functions/node_modules/mongodb/lib/explain.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ExplainableCursor = exports2.Explain = exports2.ExplainVerbosity = void 0; exports2.validateExplainTimeoutOptions = validateExplainTimeoutOptions; exports2.decorateWithExplain = decorateWithExplain; var abstract_cursor_1 = require_abstract_cursor(); var error_1 = require_error(); exports2.ExplainVerbosity = Object.freeze({ queryPlanner: "queryPlanner", queryPlannerExtended: "queryPlannerExtended", executionStats: "executionStats", allPlansExecution: "allPlansExecution" }); var Explain = class _Explain { constructor(verbosity, maxTimeMS) { if (typeof verbosity === "boolean") { this.verbosity = verbosity ? exports2.ExplainVerbosity.allPlansExecution : exports2.ExplainVerbosity.queryPlanner; } else { this.verbosity = verbosity; } this.maxTimeMS = maxTimeMS; } static fromOptions({ explain } = {}) { if (explain == null) return; if (typeof explain === "boolean" || typeof explain === "string") { return new _Explain(explain); } const { verbosity, maxTimeMS } = explain; return new _Explain(verbosity, maxTimeMS); } }; exports2.Explain = Explain; function validateExplainTimeoutOptions(options, explain) { const { maxTimeMS, timeoutMS } = options; if (timeoutMS != null && (maxTimeMS != null || explain?.maxTimeMS != null)) { throw new error_1.MongoAPIError("Cannot use maxTimeMS with timeoutMS for explain commands."); } } function decorateWithExplain(command, explain) { const { verbosity, maxTimeMS } = explain; const baseCommand = { explain: command, verbosity }; if (typeof maxTimeMS === "number") { baseCommand.maxTimeMS = maxTimeMS; } return baseCommand; } var ExplainableCursor = class extends abstract_cursor_1.AbstractCursor { resolveExplainTimeoutOptions(verbosity, options) { let explain; let timeout; if (verbosity == null && options == null) { explain = void 0; timeout = void 0; } else if (verbosity != null && options == null) { explain = typeof verbosity !== "object" ? verbosity : "verbosity" in verbosity ? verbosity : void 0; timeout = typeof verbosity === "object" && "timeoutMS" in verbosity ? verbosity : void 0; } else { explain = verbosity; timeout = options; } return { timeout, explain }; } }; exports2.ExplainableCursor = ExplainableCursor; } }); // netlify/functions/node_modules/mongodb/lib/operations/command.js var require_command = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/command.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.CommandOperation = void 0; var error_1 = require_error(); var explain_1 = require_explain(); var read_concern_1 = require_read_concern(); var server_selection_1 = require_server_selection(); var utils_1 = require_utils(); var write_concern_1 = require_write_concern(); var operation_1 = require_operation(); var CommandOperation = class extends operation_1.AbstractOperation { constructor(parent, options) { super(options); this.options = options ?? {}; const dbNameOverride = options?.dbName || options?.authdb; if (dbNameOverride) { this.ns = new utils_1.MongoDBNamespace(dbNameOverride, "$cmd"); } else { this.ns = parent ? parent.s.namespace.withCollection("$cmd") : new utils_1.MongoDBNamespace("admin", "$cmd"); } this.readConcern = read_concern_1.ReadConcern.fromOptions(options); this.writeConcern = write_concern_1.WriteConcern.fromOptions(options); if (this.hasAspect(operation_1.Aspect.EXPLAINABLE)) { this.explain = explain_1.Explain.fromOptions(options); if (this.explain) (0, explain_1.validateExplainTimeoutOptions)(this.options, this.explain); } else if (options?.explain != null) { throw new error_1.MongoInvalidArgumentError(`Option "explain" is not supported on this command`); } } get canRetryWrite() { if (this.hasAspect(operation_1.Aspect.EXPLAINABLE)) { return this.explain == null; } return super.canRetryWrite; } async executeCommand(server, session, cmd, timeoutContext, responseType) { this.server = server; const options = { ...this.options, ...this.bsonOptions, timeoutContext, readPreference: this.readPreference, session }; const serverWireVersion = (0, utils_1.maxWireVersion)(server); const inTransaction = this.session && this.session.inTransaction(); if (this.readConcern && (0, utils_1.commandSupportsReadConcern)(cmd) && !inTransaction) { Object.assign(cmd, { readConcern: this.readConcern }); } if (this.trySecondaryWrite && serverWireVersion < server_selection_1.MIN_SECONDARY_WRITE_WIRE_VERSION) { options.omitReadPreference = true; } if (this.writeConcern && this.hasAspect(operation_1.Aspect.WRITE_OPERATION) && !inTransaction) { write_concern_1.WriteConcern.apply(cmd, this.writeConcern); } if (options.collation && typeof options.collation === "object" && !this.hasAspect(operation_1.Aspect.SKIP_COLLATION)) { Object.assign(cmd, { collation: options.collation }); } if (typeof options.maxTimeMS === "number") { cmd.maxTimeMS = options.maxTimeMS; } if (this.hasAspect(operation_1.Aspect.EXPLAINABLE) && this.explain) { cmd = (0, explain_1.decorateWithExplain)(cmd, this.explain); } return await server.command(this.ns, cmd, options, responseType); } }; exports2.CommandOperation = CommandOperation; } }); // netlify/functions/node_modules/mongodb/lib/operations/delete.js var require_delete = __commonJS({ "netlify/functions/node_modules/mongodb/lib/operations/delete.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.DeleteManyOperation = exports2.DeleteOneOperation = exports2.DeleteOperation = void 0; exports2.makeDeleteStatement = makeDeleteStatement; var error_1 = require_error(); var command_1 = require_command(); var operation_1 = require_operation(); var DeleteOperation = class extends command_1.CommandOperation { constructor(ns, statements, options) { super(void 0, options); this.options = options; this.ns = ns; this.statements = statements; } get commandName() { return "delete"; } get canRetryWrite() { if (super.canRetryWrite === false) { return false; } return this.statements.every((op) => op.limit != null ? op.limit > 0 : true); } async execute(server, session, timeoutContext) { const options = this.options ?? {}; const ordered = typeof options.ordered === "boolean" ? options.ordered : true; const command = { delete: this.ns.collection, deletes: this.statements, ordered }; if (options.let) { command.let = options.let; } if (options.comment !== void 0) { command.comment = options.comment; } const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; if (unacknowledgedWrite) { if (this.statements.find((o) => o.hint)) { throw new error_1.MongoCompatibilityError(`hint is not supported with unacknowledged writes`); } } const res = await super.executeCommand(server, session, command, timeoutContext); return res; } }; exports2.DeleteOperation = DeleteOperation; var DeleteOneOperation = class extends DeleteOperation { constructor(collection, filter, options) { super(collection.s.namespace, [makeDeleteStatement(filter, { ...options, limit: 1 })], options); } async execute(server, session, timeoutContext) { const res = await super.execute(server, session, timeoutContext); if (this.explain) return res; if (res.code) throw new error_1.MongoServerError(res); if (res.writeErrors) throw new error_1.MongoServerError(res.writeErrors[0]); return { acknowledged: this.writeConcern?.w !== 0, deletedCount: res.n }; } }; exports2.DeleteOneOperation = DeleteOneOperation; var DeleteManyOperation = class extends DeleteOperation { constructor(collection, filter, options) { super(collection.s.namespace, [makeDeleteStatement(filter, options)], options); } async execute(server, session, timeoutContext) { const res = await super.execute(server, session, timeoutContext); if (this.explain) return res; if (res.code) throw new error_1.MongoServerError(res); if (res.writeErrors) throw new error_1.MongoServerError(res.writeErrors[0]); return { acknowledged: this.writeConcern?.w !== 0, deletedCount: res.n }; } }; exports2.DeleteManyOperation = DeleteManyOperation; function makeDeleteStatement(filter, options) { const op = { q: filter, limit: typeof options.limit === "number" ? options.limit : 0 }; if (options.collation) { op.collation = options.collation; } if (options.hint) { op.hint = options.hint; } return op; } (0, operation_1.defineAspects)(DeleteOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION]); (0, operation_1.defineAspects)(DeleteOneOperation, [ operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION, operation_1.Aspect.EXPLAINABLE, operation_1.Aspect.SKIP_COLLATION ]); (0, operation_1.defineAspects)(DeleteManyOperation, [ operation_1.Aspect.WRITE_OPERATION, operation_1.Aspect.EXPLAINABLE, operation_1.Aspect.SKIP_COLLATION ]); } }); // netlify/functions/node_modules/mongodb/lib/bulk/common.js var require_common2 = __commonJS({ "netlify/functions/node_modules/mongodb/lib/bulk/common.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.BulkOperationBase = exports2.BulkWriteShimOperation = exports2.FindOperators = exports2.MongoBulkWriteError = exports2.WriteError = exports2.WriteConcernError = exports2.BulkWriteResult = exports2.Batch = exports2.BatchType = void 0; exports2.mergeBatchResults = mergeBatchResults; var bson_1 = require_bson2(); var error_1 = require_error(); var delete_1 = require_delete(); var execute_operation_1 = require_execute_operation(); var insert_1 = require_insert(); var operation_1 = require_operation(); var update_1 = require_update2(); var utils_1 = require_utils(); var write_concern_1 = require_write_concern(); exports2.BatchType = Object.freeze({ INSERT: 1, UPDATE: 2, DELETE: 3 }); var Batch = class { constructor(batchType, originalZeroIndex) { this.originalZeroIndex = originalZeroIndex; this.currentIndex = 0; this.originalIndexes = []; this.batchType = batchType; this.operations = []; this.size = 0; this.sizeBytes = 0; } }; exports2.Batch = Batch; var BulkWriteResult = class _BulkWriteResult { static generateIdMap(ids) { const idMap = {}; for (const doc of ids) { idMap[doc.index] = doc._id; } return idMap; } /** * Create a new BulkWriteResult instance * @internal */ constructor(bulkResult, isOrdered) { this.result = bulkResult; this.insertedCount = this.result.nInserted ?? 0; this.matchedCount = this.result.nMatched ?? 0; this.modifiedCount = this.result.nModified ?? 0; this.deletedCount = this.result.nRemoved ?? 0; this.upsertedCount = this.result.upserted.length ?? 0; this.upsertedIds = _BulkWriteResult.generateIdMap(this.result.upserted); this.insertedIds = _BulkWriteResult.generateIdMap(this.getSuccessfullyInsertedIds(bulkResult, isOrdered)); Object.defineProperty(this, "result", { value: this.result, enumerable: false }); } /** Evaluates to true if the bulk operation correctly executes */ get ok() { return this.result.ok; } /** * Returns document_ids that were actually inserted * @internal */ getSuccessfullyInsertedIds(bulkResult, isOrdered) { if (bulkResult.writeErrors.length === 0) return bulkResult.insertedIds; if (isOrdered) { return bulkResult.insertedIds.slice(0, bulkResult.writeErrors[0].index); } return bulkResult.insertedIds.filter(({ index }) => !bulkResult.writeErrors.some((writeError) => index === writeError.index)); } /** Returns the upserted id at the given index */ getUpsertedIdAt(index) { return this.result.upserted[index]; } /** Returns raw internal result */ getRawResponse() { return this.result; } /** Returns true if the bulk operation contains a write error */ hasWriteErrors() { return this.result.writeErrors.length > 0; } /** Returns the number of write errors from the bulk operation */ getWriteErrorCount() { return this.result.writeErrors.length; } /** Returns a specific write error object */ getWriteErrorAt(index) { return index < this.result.writeErrors.length ? this.result.writeErrors[index] : void 0; } /** Retrieve all write errors */ getWriteErrors() { return this.result.writeErrors; } /** Retrieve the write concern error if one exists */ getWriteConcernError() { if (this.result.writeConcernErrors.length === 0) { return; } else if (this.result.writeConcernErrors.length === 1) { return this.result.writeConcernErrors[0]; } else { let errmsg = ""; for (let i = 0; i < this.result.writeConcernErrors.length; i++) { const err = this.result.writeConcernErrors[i]; errmsg = errmsg + err.errmsg; if (i === 0) errmsg = errmsg + " and "; } return new WriteConcernError({ errmsg, code: error_1.MONGODB_ERROR_CODES.WriteConcernTimeout }); } } toString() { return `BulkWriteResult(${bson_1.EJSON.stringify(this.result)})`; } isOk() { return this.result.ok === 1; } }; exports2.BulkWriteResult = BulkWriteResult; var WriteConcernError = class { constructor(error) { this.serverError = error; } /** Write concern error code. */ get code() { return this.serverError.code; } /** Write concern error message. */ get errmsg() { return this.serverError.errmsg; } /** Write concern error info. */ get errInfo() { return this.serverError.errInfo; } toJSON() { return this.serverError; } toString() { return `WriteConcernError(${this.errmsg})`; } }; exports2.WriteConcernError = WriteConcernError; var WriteError = class { constructor(err) { this.err = err; } /** WriteError code. */ get code() { return this.err.code; } /** WriteError original bulk operation index. */ get index() { return this.err.index; } /** WriteError message. */ get errmsg() { return this.err.errmsg; } /** WriteError details. */ get errInfo() { return this.err.errInfo; } /** Returns the underlying operation that caused the error */ getOperation() { return this.err.op; } toJSON() { return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op }; } toString() { return `WriteError(${JSON.stringify(this.toJSON())})`; } }; exports2.WriteError = WriteError; function mergeBatchResults(batch, bulkResult, err, result) { if (err) { result = err; } else if (result && result.result) { result = result.result; } if (result == null) { return; } if (result.ok === 0 && bulkResult.ok === 1) { bulkResult.ok = 0; const writeError = { index: 0, code: result.code || 0, errmsg: result.message, errInfo: result.errInfo, op: batch.operations[0] }; bulkResult.writeErrors.push(new WriteError(writeError)); return; } else if (result.ok === 0 && bulkResult.ok === 0) { return; } if (isInsertBatch(batch) && result.n) { bulkResult.nInserted = bulkResult.nInserted + result.n; } if (isDeleteBatch(batch) && result.n) { bulkResult.nRemoved = bulkResult.nRemoved + result.n; } let nUpserted = 0; if (Array.isArray(result.upserted)) { nUpserted = result.upserted.length; for (let i = 0; i < result.upserted.length; i++) { bulkResult.upserted.push({ index: result.upserted[i].index + batch.originalZeroIndex, _id: result.upserted[i]._id }); } } else if (result.upserted) { nUpserted = 1; bulkResult.upserted.push({ index: batch.originalZeroIndex, _id: result.upserted }); } if (isUpdateBatch(batch) && result.n) { const nModified = result.nModified; bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); if (typeof nModified === "number") { bulkResult.nModified = bulkResult.nModified + nModified; } else { bulkResult.nModified = 0; } } if (Array.isArray(result.writeErrors)) { for (let i = 0; i < result.writeErrors.length; i++) { const writeError = { index: batch.originalIndexes[result.writeErrors[i].index], code: result.writeErrors[i].code, errmsg: result.writeErrors[i].errmsg, errInfo: result.writeErrors[i].errInfo, op: batch.operations[result.writeErrors[i].index] }; bulkResult.writeErrors.push(new WriteError(writeError)); } } if (result.writeConcernError) { bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); } } async function executeCommands(bulkOperation, options) { if (bulkOperation.s.batches.length === 0) { return new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered); } for (const batch of bulkOperation.s.batches) { const finalOptions = (0, utils_1.resolveOptions)(bulkOperation, { ...options, ordered: bulkOperation.isOrdered }); if (finalOptions.bypassDocumentValidation !== true) { delete finalOptions.bypassDocumentValidation; } if (bulkOperation.s.bypassDocumentValidation === true) { finalOptions.bypassDocumentValidation = true; } if (bulkOperation.s.checkKeys === false) { finalOptions.checkKeys = false; } if (finalOptions.retryWrites) { if (isUpdateBatch(batch)) { finalOptions.retryWrites = finalOptions.retryWrites && !batch.operations.some((op) => op.multi); } if (isDeleteBatch(batch)) { finalOptions.retryWrites = finalOptions.retryWrites && !batch.operations.some((op) => op.limit === 0); } } const operation = isInsertBatch(batch) ? new insert_1.InsertOperation(bulkOperation.s.namespace, batch.operations, finalOptions) : isUpdateBatch(batch) ? new update_1.UpdateOperation(bulkOperation.s.namespace, batch.operations, finalOptions) : isDeleteBatch(batch) ? new delete_1.DeleteOperation(bulkOperation.s.namespace, batch.operations, finalOptions) : null; if (operation == null) throw new error_1.MongoRuntimeError(`Unknown batchType: ${batch.batchType}`); let thrownError = null; let result; try { result = await (0, execute_operation_1.executeOperation)(bulkOperation.s.collection.client, operation, finalOptions.timeoutContext); } catch (error) { thrownError = error; } if (thrownError != null) { if (thrownError instanceof error_1.MongoWriteConcernError) { mergeBatchResults(batch, bulkOperation.s.bulkResult, thrownError, result); const writeResult3 = new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered); throw new MongoBulkWriteError({ message: thrownError.result.writeConcernError.errmsg, code: thrownError.result.writeConcernError.code }, writeResult3); } else { throw new MongoBulkWriteError(thrownError, new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered)); } } mergeBatchResults(batch, bulkOperation.s.bulkResult, thrownError, result); const writeResult2 = new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered); bulkOperation.handleWriteError(writeResult2); } bulkOperation.s.batches.length = 0; const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered); bulkOperation.handleWriteError(writeResult); return writeResult; } var MongoBulkWriteError = class extends error_1.MongoServerError { /** * **Do not use this constructor!** * * Meant for internal use only. * * @remarks * This class is only meant to be constructed within the driver. This constructor is * not subject to semantic versioning compatibility guarantees and may change at any time. * * @public **/ constructor(error, result) { super(error); this.writeErrors = []; if (error instanceof WriteConcernError) this.err = error; else if (!(error instanceof Error)) { this.message = error.message; this.code = error.code; this.writeErrors = error.writeErrors ?? []; } this.result = result; Object.assign(this, error); } get name() { return "MongoBulkWriteError"; } /** Number of documents inserted. */ get insertedCount() { return this.result.insertedCount; } /** Number of documents matched for update. */ get matchedCount() { return this.result.matchedCount; } /** Number of documents modified. */ get modifiedCount() { return this.result.modifiedCount; } /** Number of documents deleted. */ get deletedCount() { return this.result.deletedCount; } /** Number of documents upserted. */ get upsertedCount() { return this.result.upsertedCount; } /** Inserted document generated Id's, hash key is the index of the originating operation */ get insertedIds() { return this.result.insertedIds; } /** Upserted document generated Id's, hash key is the index of the originating operation */ get upsertedIds() { return this.result.upsertedIds; } }; exports2.MongoBulkWriteError = MongoBulkWriteError; var FindOperators = class { /** * Creates a new FindOperators object. * @internal */ constructor(bulkOperation) { this.bulkOperation = bulkOperation; } /** Add a multiple update operation to the bulk operation */ update(updateDocument) { const currentOp = buildCurrentOp(this.bulkOperation); return this.bulkOperation.addToOperationsList(exports2.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, updateDocument, { ...currentOp, multi: true })); } /** Add a single update operation to the bulk operation */ updateOne(updateDocument) { if (!(0, utils_1.hasAtomicOperators)(updateDocument, this.bulkOperation.bsonOptions)) { throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators"); } const currentOp = buildCurrentOp(this.bulkOperation); return this.bulkOperation.addToOperationsList(exports2.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, updateDocument, { ...currentOp, multi: false })); } /** Add a replace one operation to the bulk operation */ replaceOne(replacement) { if ((0, utils_1.hasAtomicOperators)(replacement)) { throw new error_1.MongoInvalidArgumentError("Replacement document must not use atomic operators"); } const currentOp = buildCurrentOp(this.bulkOperation); return this.bulkOperation.addToOperationsList(exports2.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, replacement, { ...currentOp, multi: false })); } /** Add a delete one operation to the bulk operation */ deleteOne() { const currentOp = buildCurrentOp(this.bulkOperation); return this.bulkOperation.addToOperationsList(exports2.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(currentOp.selector, { ...currentOp, limit: 1 })); } /** Add a delete many operation to the bulk operation */ delete() { const currentOp = buildCurrentOp(this.bulkOperation); return this.bulkOperation.addToOperationsList(exports2.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(currentOp.selector, { ...currentOp, limit: 0 })); } /** Upsert modifier for update bulk operation, noting that this operation is an upsert. */ upsert() { if (!this.bulkOperation.s.currentOp) { this.bulkOperation.s.currentOp = {}; } this.bulkOperation.s.currentOp.upsert = true; return this; } /** Specifies the collation for the query condition. */ collation(collation) { if (!this.bulkOperation.s.currentOp) { this.bulkOperation.s.currentOp = {}; } this.bulkOperation.s.currentOp.collation = collation; return this; } /** Specifies arrayFilters for UpdateOne or UpdateMany bulk operations. */ arrayFilters(arrayFilters) { if (!this.bulkOperation.s.currentOp) { this.bulkOperation.s.currentOp = {}; } this.bulkOperation.s.currentOp.arrayFilters = arrayFilters; return this; } /** Specifies hint for the bulk operation. */ hint(hint) { if (!this.bulkOperation.s.currentOp) { this.bulkOperation.s.currentOp = {}; } this.bulkOperation.s.currentOp.hint = hint; return this; } }; exports2.FindOperators = FindOperators; var BulkWriteShimOperation = class extends operation_1.AbstractOperation { constructor(bulkOperation, options) { super(options); this.bulkOperation = bulkOperation; } get commandName() { return "bulkWrite"; } async execute(_server, session, timeoutContext) { if (this.options.session == null) { this.options.session = session; } return await executeCommands(this.bulkOperation, { ...this.options, timeoutContext }); } }; exports2.BulkWriteShimOperation = BulkWriteShimOperation; var BulkOperationBase = class { /** * Create a new OrderedBulkOperation or UnorderedBulkOperation instance * @internal */ constructor(collection, options, isOrdered) { this.collection = collection; this.isOrdered = isOrdered; const topology = (0, utils_1.getTopology)(collection); options = options == null ? {} : options; const namespace = collection.s.namespace; const executed = false; const currentOp = void 0; const hello = topology.lastHello(); const usingAutoEncryption = !!(topology.s.options && topology.s.options.autoEncrypter); const maxBsonObjectSize = hello && hello.maxBsonObjectSize ? hello.maxBsonObjectSize : 1024 * 1024 * 16; const maxBatchSizeBytes = usingAutoEncryption ? 1024 * 1024 * 2 : maxBsonObjectSize; const maxWriteBatchSize = hello && hello.maxWriteBatchSize ? hello.maxWriteBatchSize : 1e3; const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2; let finalOptions = Object.assign({}, options); finalOptions = (0, utils_1.applyRetryableWrites)(finalOptions, collection.s.db); const bulkResult = { ok: 1, writeErrors: [], writeConcernErrors: [], insertedIds: [], nInserted: 0, nUpserted: 0, nMatched: 0, nModified: 0, nRemoved: 0, upserted: [] }; this.s = { // Final result bulkResult, // Current batch state currentBatch: void 0, currentIndex: 0, // ordered specific currentBatchSize: 0, currentBatchSizeBytes: 0, // unordered specific currentInsertBatch: void 0, currentUpdateBatch: void 0, currentRemoveBatch: void 0, batches: [], // Write concern writeConcern: write_concern_1.WriteConcern.fromOptions(options), // Max batch size options maxBsonObjectSize, maxBatchSizeBytes, maxWriteBatchSize, maxKeySize, // Namespace namespace, // Topology topology, // Options options: finalOptions, // BSON options bsonOptions: (0, bson_1.resolveBSONOptions)(options), // Current operation currentOp, // Executed executed, // Collection collection, // Fundamental error err: void 0, // check keys checkKeys: typeof options.checkKeys === "boolean" ? options.checkKeys : false }; if (options.bypassDocumentValidation === true) { this.s.bypassDocumentValidation = true; } } /** * Add a single insert document to the bulk operation * * @example * ```ts * const bulkOp = collection.initializeOrderedBulkOp(); * * // Adds three inserts to the bulkOp. * bulkOp * .insert({ a: 1 }) * .insert({ b: 2 }) * .insert({ c: 3 }); * await bulkOp.execute(); * ``` */ insert(document2) { (0, utils_1.maybeAddIdToDocuments)(this.collection, document2, { forceServerObjectId: this.shouldForceServerObjectId() }); return this.addToOperationsList(exports2.BatchType.INSERT, document2); } /** * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne. * Returns a builder object used to complete the definition of the operation. * * @example * ```ts * const bulkOp = collection.initializeOrderedBulkOp(); * * // Add an updateOne to the bulkOp * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } }); * * // Add an updateMany to the bulkOp * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } }); * * // Add an upsert * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } }); * * // Add a deletion * bulkOp.find({ g: 7 }).deleteOne(); * * // Add a multi deletion * bulkOp.find({ h: 8 }).delete(); * * // Add a replaceOne * bulkOp.find({ i: 9 }).replaceOne({writeConcern: { j: 10 }}); * * // Update using a pipeline (requires Mongodb 4.2 or higher) * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([ * { $set: { total: { $sum: [ '$y', '$z' ] } } } * ]); * * // All of the ops will now be executed * await bulkOp.execute(); * ``` */ find(selector) { if (!selector) { throw new error_1.MongoInvalidArgumentError("Bulk find operation must specify a selector"); } this.s.currentOp = { selector }; return new FindOperators(this); } /** Specifies a raw operation to perform in the bulk write. */ raw(op) { if (op == null || typeof op !== "object") { throw new error_1.MongoInvalidArgumentError("Operation must be an object with an operation key"); } if ("insertOne" in op) { const forceServerObjectId = this.shouldForceServerObjectId(); const document2 = op.insertOne && op.insertOne.document == null ? ( // TODO(NODE-6003): remove support for omitting the `documents` subdocument in bulk inserts op.insertOne ) : op.insertOne.document; (0, utils_1.maybeAddIdToDocuments)(this.collection, document2, { forceServerObjectId }); return this.addToOperationsList(exports2.BatchType.INSERT, document2); } if ("replaceOne" in op || "updateOne" in op || "updateMany" in op) { if ("replaceOne" in op) { if ("q" in op.replaceOne) { throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed"); } const updateStatement = (0, update_1.makeUpdateStatement)(op.replaceOne.filter, op.replaceOne.replacement, { ...op.replaceOne, multi: false }); if ((0, utils_1.hasAtomicOperators)(updateStatement.u)) { throw new error_1.MongoInvalidArgumentError("Replacement document must not use atomic operators"); } return this.addToOperationsList(exports2.BatchType.UPDATE, updateStatement); } if ("updateOne" in op) { if ("q" in op.updateOne) { throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed"); } const updateStatement = (0, update_1.makeUpdateStatement)(op.updateOne.filter, op.updateOne.update, { ...op.updateOne, multi: false }); if (!(0, utils_1.hasAtomicOperators)(updateStatement.u, this.bsonOptions)) { throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators"); } return this.addToOperationsList(exports2.BatchType.UPDATE, updateStatement); } if ("updateMany" in op) { if ("q" in op.updateMany) { throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed"); } const updateStatement = (0, update_1.makeUpdateStatement)(op.updateMany.filter, op.updateMany.update, { ...op.updateMany, multi: true }); if (!(0, utils_1.hasAtomicOperators)(updateStatement.u, this.bsonOptions)) { throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators"); } return this.addToOperationsList(exports2.BatchType.UPDATE, updateStatement); } } if ("deleteOne" in op) { if ("q" in op.deleteOne) { throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed"); } return this.addToOperationsList(exports2.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(op.deleteOne.filter, { ...op.deleteOne, limit: 1 })); } if ("deleteMany" in op) { if ("q" in op.deleteMany) { throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed"); } return this.addToOperationsList(exports2.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(op.deleteMany.filter, { ...op.deleteMany, limit: 0 })); } throw new error_1.MongoInvalidArgumentError("bulkWrite only supports insertOne, updateOne, updateMany, deleteOne, deleteMany"); } get length() { return this.s.currentIndex; } get bsonOptions() { return this.s.bsonOptions; } get writeConcern() { return this.s.writeConcern; } get batches() { const batches = [...this.s.batches]; if (this.isOrdered) { if (this.s.currentBatch) batches.push(this.s.currentBatch); } else { if (this.s.currentInsertBatch) batches.push(this.s.currentInsertBatch); if (this.s.currentUpdateBatch) batches.push(this.s.currentUpdateBatch); if (this.s.currentRemoveBatch) batches.push(this.s.currentRemoveBatch); } return batches; } async execute(options = {}) { if (this.s.executed) { throw new error_1.MongoBatchReExecutionError(); } const writeConcern = write_concern_1.WriteConcern.fromOptions(options); if (writeConcern) { this.s.writeConcern = writeConcern; } if (this.isOrdered) { if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch); } else { if (this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); if (this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); if (this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); } if (this.s.batches.length === 0) { throw new error_1.MongoInvalidArgumentError("Invalid BulkOperation, Batch cannot be empty"); } this.s.executed = true; const finalOptions = { ...this.s.options, ...options }; const operation = new BulkWriteShimOperation(this, finalOptions); return await (0, execute_operation_1.executeOperation)(this.s.collection.client, operation, finalOptions.timeoutContext); } /** * Handles the write error before executing commands * @internal */ handleWriteError(writeResult) { if (this.s.bulkResult.writeErrors.length > 0) { const msg = this.s.bulkResult.writeErrors[0].errmsg ? this.s.bulkResult.writeErrors[0].errmsg : "write operation failed"; throw new MongoBulkWriteError({ message: msg, code: this.s.bulkResult.writeErrors[0].code, writeErrors: this.s.bulkResult.writeErrors }, writeResult); } const writeConcernError = writeResult.getWriteConcernError(); if (writeConcernError) { throw new MongoBulkWriteError(writeConcernError, writeResult); } } shouldForceServerObjectId() { return this.s.options.forceServerObjectId === true || this.s.collection.s.db.options?.forceServerObjectId === true; } }; exports2.BulkOperationBase = BulkOperationBase; function isInsertBatch(batch) { return batch.batchType === exports2.BatchType.INSERT; } function isUpdateBatch(batch) { return batch.batchType === exports2.BatchType.UPDATE; } function isDeleteBatch(batch) { return batch.batchType === exports2.BatchType.DELETE; } function buildCurrentOp(bulkOp) { let { currentOp } = bulkOp.s; bulkOp.s.currentOp = void 0; if (!currentOp) currentOp = {}; return currentOp; } } }); // netlify/functions/node_modules/mongoose/lib/drivers/node-mongodb-native/bulkWriteResult.js var require_bulkWriteResult = __commonJS({ "netlify/functions/node_modules/mongoose/lib/drivers/node-mongodb-native/bulkWriteResult.js"(exports2, module2) { "use strict"; var BulkWriteResult = require_common2().BulkWriteResult; module2.exports = BulkWriteResult; } }); // netlify/functions/node_modules/mongoose/lib/connectionState.js var require_connectionState = __commonJS({ "netlify/functions/node_modules/mongoose/lib/connectionState.js"(exports2, module2) { "use strict"; var STATES = module2.exports = exports2 = /* @__PURE__ */ Object.create(null); var disconnected = "disconnected"; var connected = "connected"; var connecting = "connecting"; var disconnecting = "disconnecting"; var uninitialized = "uninitialized"; STATES[0] = disconnected; STATES[1] = connected; STATES[2] = connecting; STATES[3] = disconnecting; STATES[99] = uninitialized; STATES[disconnected] = 0; STATES[connected] = 1; STATES[connecting] = 2; STATES[disconnecting] = 3; STATES[uninitialized] = 99; } }); // netlify/functions/node_modules/mongoose/lib/helpers/immediate.js var require_immediate = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/immediate.js"(exports2, module2) { "use strict"; var nextTick = typeof process !== "undefined" && typeof process.nextTick === "function" ? process.nextTick.bind(process) : (cb) => setTimeout(cb, 0); module2.exports = function immediate(cb) { return nextTick(cb); }; } }); // netlify/functions/node_modules/mongoose/lib/collection.js var require_collection2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/collection.js"(exports2, module2) { "use strict"; var EventEmitter = require("events").EventEmitter; var STATES = require_connectionState(); var immediate = require_immediate(); function Collection(name, conn, opts) { if (opts === void 0) { opts = {}; } this.opts = opts; this.name = name; this.collectionName = name; this.conn = conn; this.queue = []; this.buffer = !conn?._hasOpened; this.emitter = new EventEmitter(); if (STATES.connected === this.conn.readyState) { this.onOpen(); } } Collection.prototype.name; Collection.prototype.collectionName; Collection.prototype.conn; Collection.prototype.onOpen = function() { this.buffer = false; immediate(() => this.doQueue()); }; Collection.prototype.onClose = function() { }; Collection.prototype.addQueue = function(name, args) { this.queue.push([name, args]); return this; }; Collection.prototype.removeQueue = function(name, args) { const index = this.queue.findIndex((v) => v[0] === name && v[1] === args); if (index === -1) { return false; } this.queue.splice(index, 1); return true; }; Collection.prototype.doQueue = function() { for (const method of this.queue) { if (typeof method[0] === "function") { method[0].apply(this, method[1]); } else { this[method[0]].apply(this, method[1]); } } this.queue = []; const _this = this; immediate(function() { _this.emitter.emit("queue"); }); return this; }; Collection.prototype.ensureIndex = function() { throw new Error("Collection#ensureIndex unimplemented by driver"); }; Collection.prototype.createIndex = function() { throw new Error("Collection#createIndex unimplemented by driver"); }; Collection.prototype.findAndModify = function() { throw new Error("Collection#findAndModify unimplemented by driver"); }; Collection.prototype.findOneAndUpdate = function() { throw new Error("Collection#findOneAndUpdate unimplemented by driver"); }; Collection.prototype.findOneAndDelete = function() { throw new Error("Collection#findOneAndDelete unimplemented by driver"); }; Collection.prototype.findOneAndReplace = function() { throw new Error("Collection#findOneAndReplace unimplemented by driver"); }; Collection.prototype.findOne = function() { throw new Error("Collection#findOne unimplemented by driver"); }; Collection.prototype.find = function() { throw new Error("Collection#find unimplemented by driver"); }; Collection.prototype.insert = function() { throw new Error("Collection#insert unimplemented by driver"); }; Collection.prototype.insertOne = function() { throw new Error("Collection#insertOne unimplemented by driver"); }; Collection.prototype.insertMany = function() { throw new Error("Collection#insertMany unimplemented by driver"); }; Collection.prototype.save = function() { throw new Error("Collection#save unimplemented by driver"); }; Collection.prototype.updateOne = function() { throw new Error("Collection#updateOne unimplemented by driver"); }; Collection.prototype.updateMany = function() { throw new Error("Collection#updateMany unimplemented by driver"); }; Collection.prototype.deleteOne = function() { throw new Error("Collection#deleteOne unimplemented by driver"); }; Collection.prototype.deleteMany = function() { throw new Error("Collection#deleteMany unimplemented by driver"); }; Collection.prototype.getIndexes = function() { throw new Error("Collection#getIndexes unimplemented by driver"); }; Collection.prototype.watch = function() { throw new Error("Collection#watch unimplemented by driver"); }; Collection.prototype._shouldBufferCommands = function _shouldBufferCommands() { const opts = this.opts; if (opts.bufferCommands != null) { return opts.bufferCommands; } if (opts && opts.schemaUserProvidedOptions != null && opts.schemaUserProvidedOptions.bufferCommands != null) { return opts.schemaUserProvidedOptions.bufferCommands; } return this.conn._shouldBufferCommands(); }; Collection.prototype._getBufferTimeoutMS = function _getBufferTimeoutMS() { const conn = this.conn; const opts = this.opts; if (opts.bufferTimeoutMS != null) { return opts.bufferTimeoutMS; } if (opts && opts.schemaUserProvidedOptions != null && opts.schemaUserProvidedOptions.bufferTimeoutMS != null) { return opts.schemaUserProvidedOptions.bufferTimeoutMS; } return conn._getBufferTimeoutMS(); }; module2.exports = Collection; } }); // netlify/functions/node_modules/mongoose/lib/error/mongooseError.js var require_mongooseError = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/mongooseError.js"(exports2, module2) { "use strict"; var MongooseError = class extends Error { }; Object.defineProperty(MongooseError.prototype, "name", { value: "MongooseError" }); module2.exports = MongooseError; } }); // netlify/functions/node_modules/mongoose/lib/helpers/symbols.js var require_symbols = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/symbols.js"(exports2) { "use strict"; exports2.arrayAtomicsBackupSymbol = Symbol("mongoose#Array#atomicsBackup"); exports2.arrayAtomicsSymbol = Symbol("mongoose#Array#_atomics"); exports2.arrayParentSymbol = Symbol("mongoose#Array#_parent"); exports2.arrayPathSymbol = Symbol("mongoose#Array#_path"); exports2.arraySchemaSymbol = Symbol("mongoose#Array#_schema"); exports2.documentArrayParent = Symbol("mongoose#documentArrayParent"); exports2.documentIsSelected = Symbol("mongoose#Document#isSelected"); exports2.documentIsModified = Symbol("mongoose#Document#isModified"); exports2.documentModifiedPaths = Symbol("mongoose#Document#modifiedPaths"); exports2.documentSchemaSymbol = Symbol("mongoose#Document#schema"); exports2.getSymbol = Symbol("mongoose#Document#get"); exports2.modelSymbol = Symbol("mongoose#Model"); exports2.objectIdSymbol = Symbol("mongoose#ObjectId"); exports2.populateModelSymbol = Symbol("mongoose#PopulateOptions#Model"); exports2.schemaTypeSymbol = Symbol("mongoose#schemaType"); exports2.sessionNewDocuments = Symbol("mongoose#ClientSession#newDocuments"); exports2.scopeSymbol = Symbol("mongoose#Document#scope"); exports2.validatorErrorSymbol = Symbol("mongoose#validatorError"); } }); // netlify/functions/node_modules/mongoose/lib/types/objectid.js var require_objectid = __commonJS({ "netlify/functions/node_modules/mongoose/lib/types/objectid.js"(exports2, module2) { "use strict"; var ObjectId2 = require_bson().ObjectId; var objectIdSymbol = require_symbols().objectIdSymbol; Object.defineProperty(ObjectId2.prototype, "_id", { enumerable: false, configurable: true, get: function() { return this; } }); if (!ObjectId2.prototype.hasOwnProperty("valueOf")) { ObjectId2.prototype.valueOf = function objectIdValueOf() { return this.toString(); }; } ObjectId2.prototype[objectIdSymbol] = true; module2.exports = ObjectId2; } }); // netlify/functions/node_modules/mongoose/lib/helpers/getConstructorName.js var require_getConstructorName = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/getConstructorName.js"(exports2, module2) { "use strict"; module2.exports = function getConstructorName(val) { if (val == null) { return void 0; } if (typeof val.constructor !== "function") { return void 0; } return val.constructor.name; }; } }); // netlify/functions/node_modules/mongoose/lib/options.js var require_options = __commonJS({ "netlify/functions/node_modules/mongoose/lib/options.js"(exports2) { "use strict"; exports2.internalToObjectOptions = { transform: false, virtuals: false, getters: false, _skipDepopulateTopLevel: true, depopulate: true, flattenDecimals: false, useProjection: false, versionKey: true, flattenObjectIds: false }; } }); // netlify/functions/node_modules/mongoose/lib/types/decimal128.js var require_decimal128 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/types/decimal128.js"(exports2, module2) { "use strict"; module2.exports = require_bson().Decimal128; } }); // netlify/functions/node_modules/mongoose/lib/helpers/specialProperties.js var require_specialProperties = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/specialProperties.js"(exports2, module2) { "use strict"; module2.exports = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]); } }); // netlify/functions/node_modules/mongoose/lib/types/array/isMongooseArray.js var require_isMongooseArray = __commonJS({ "netlify/functions/node_modules/mongoose/lib/types/array/isMongooseArray.js"(exports2) { "use strict"; exports2.isMongooseArray = function(mongooseArray) { return Array.isArray(mongooseArray) && mongooseArray.isMongooseArray; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/isMongooseObject.js var require_isMongooseObject = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/isMongooseObject.js"(exports2, module2) { "use strict"; var isMongooseArray = require_isMongooseArray().isMongooseArray; module2.exports = function(v) { return v != null && (isMongooseArray(v) || // Array or Document Array v.$__ != null || // Document v.isMongooseBuffer || // Buffer v.$isMongooseMap); }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/getFunctionName.js var require_getFunctionName = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/getFunctionName.js"(exports2, module2) { "use strict"; var functionNameRE = /^function\s*([^\s(]+)/; module2.exports = function(fn) { return fn.name || (fn.toString().trim().match(functionNameRE) || [])[1]; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/isBsonType.js var require_isBsonType = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/isBsonType.js"(exports2, module2) { "use strict"; function isBsonType(obj, typename) { return obj != null && obj._bsontype === typename; } module2.exports = isBsonType; } }); // netlify/functions/node_modules/mongoose/lib/helpers/isObject.js var require_isObject = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/isObject.js"(exports2, module2) { "use strict"; module2.exports = function(arg) { return Buffer.isBuffer(arg) || Object.prototype.toString.call(arg) === "[object Object]"; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/isPOJO.js var require_isPOJO = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/isPOJO.js"(exports2, module2) { "use strict"; module2.exports = function isPOJO(arg) { if (arg == null || typeof arg !== "object") { return false; } const proto = Object.getPrototypeOf(arg); return !proto || proto.constructor.name === "Object"; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/query/trusted.js var require_trusted = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/query/trusted.js"(exports2) { "use strict"; var trustedSymbol = Symbol("mongoose#trustedSymbol"); exports2.trustedSymbol = trustedSymbol; exports2.trusted = function trusted(obj) { if (obj == null || typeof obj !== "object") { return obj; } obj[trustedSymbol] = true; return obj; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/clone.js var require_clone = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/clone.js"(exports2, module2) { "use strict"; var Decimal = require_decimal128(); var ObjectId2 = require_objectid(); var specialProperties = require_specialProperties(); var isMongooseObject = require_isMongooseObject(); var getFunctionName = require_getFunctionName(); var isBsonType = require_isBsonType(); var isMongooseArray = require_isMongooseArray().isMongooseArray; var isObject = require_isObject(); var isPOJO = require_isPOJO(); var symbols = require_symbols(); var trustedSymbol = require_trusted().trustedSymbol; var BSON = require_bson(); function clone(obj, options, isArrayChild) { if (obj == null) { return obj; } if (isBsonType(obj, "Double")) { return new BSON.Double(obj.value); } if (typeof obj === "number" || typeof obj === "string" || typeof obj === "boolean" || typeof obj === "bigint") { return obj; } if (Array.isArray(obj)) { return cloneArray(obj, options); } if (isMongooseObject(obj)) { if (options) { if (options.retainDocuments && obj.$__ != null) { const clonedDoc = obj.$clone(); if (obj.__index != null) { clonedDoc.__index = obj.__index; } if (obj.__parentArray != null) { clonedDoc.__parentArray = obj.__parentArray; } clonedDoc.$__parent = obj.$__parent; return clonedDoc; } } if (isPOJO(obj) && obj.$__ != null && obj._doc != null) { return obj._doc; } let ret; if (options && options.json && typeof obj.toJSON === "function") { ret = obj.toJSON(options); } else { ret = obj.toObject(options); } return ret; } const objConstructor = obj.constructor; if (objConstructor) { switch (getFunctionName(objConstructor)) { case "Object": return cloneObject(obj, options, isArrayChild); case "Date": return new objConstructor(+obj); case "RegExp": return cloneRegExp(obj); default: break; } } if (isBsonType(obj, "ObjectId")) { if (options && options.flattenObjectIds) { return obj.toJSON(); } return new ObjectId2(obj.id); } if (isBsonType(obj, "Decimal128")) { if (options && options.flattenDecimals) { return obj.toJSON(); } return Decimal.fromString(obj.toString()); } if (!objConstructor && isObject(obj)) { return cloneObject(obj, options, isArrayChild); } if (typeof obj === "object" && obj[symbols.schemaTypeSymbol]) { return obj.clone(); } if (options && options.bson && typeof obj.toBSON === "function") { return obj; } if (typeof obj.valueOf === "function") { return obj.valueOf(); } return cloneObject(obj, options, isArrayChild); } module2.exports = clone; function cloneObject(obj, options, isArrayChild) { const minimize = options && options.minimize; const omitUndefined = options && options.omitUndefined; const seen = options && options._seen; const ret = {}; let hasKeys; if (seen && seen.has(obj)) { return seen.get(obj); } else if (seen) { seen.set(obj, ret); } if (trustedSymbol in obj && options?.copyTrustedSymbol !== false) { ret[trustedSymbol] = obj[trustedSymbol]; } const keys = Object.keys(obj); const len = keys.length; for (let i = 0; i < len; ++i) { const key = keys[i]; if (specialProperties.has(key)) { continue; } const val = clone(obj[key], options, false); if ((minimize === false || omitUndefined) && typeof val === "undefined") { delete ret[key]; } else if (minimize !== true || typeof val !== "undefined") { hasKeys || (hasKeys = true); ret[key] = val; } } return minimize && !isArrayChild ? hasKeys && ret : ret; } function cloneArray(arr, options) { let i = 0; const len = arr.length; let ret = null; if (options?.retainDocuments) { if (arr.isMongooseDocumentArray) { ret = new (arr.$schemaType()).schema.base.Types.DocumentArray([], arr.$path(), arr.$parent(), arr.$schemaType()); } else if (arr.isMongooseArray) { ret = new (arr.$parent()).schema.base.Types.Array([], arr.$path(), arr.$parent(), arr.$schemaType()); } else { ret = new Array(len); } } else { ret = new Array(len); } arr = isMongooseArray(arr) ? arr.__array : arr; for (i = 0; i < len; ++i) { ret[i] = clone(arr[i], options, true); } return ret; } function cloneRegExp(regexp) { const ret = new RegExp(regexp.source, regexp.flags); if (ret.lastIndex !== regexp.lastIndex) { ret.lastIndex = regexp.lastIndex; } return ret; } } }); // netlify/functions/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js var require_collection3 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js"(exports2, module2) { "use strict"; var MongooseCollection = require_collection2(); var MongooseError = require_mongooseError(); var Collection = require_lib3().Collection; var ObjectId2 = require_objectid(); var getConstructorName = require_getConstructorName(); var internalToObjectOptions = require_options().internalToObjectOptions; var stream = require("stream"); var util = require("util"); var formatToObjectOptions = Object.freeze({ ...internalToObjectOptions, copyTrustedSymbol: false }); function NativeCollection(name, conn, options) { this.collection = null; this.Promise = options.Promise || Promise; this.modelName = options.modelName; delete options.modelName; this._closed = false; MongooseCollection.apply(this, arguments); } Object.setPrototypeOf(NativeCollection.prototype, MongooseCollection.prototype); NativeCollection.prototype.onOpen = function() { this.collection = this.conn.db.collection(this.name); MongooseCollection.prototype.onOpen.call(this); return this.collection; }; NativeCollection.prototype.onClose = function(force) { MongooseCollection.prototype.onClose.call(this, force); }; NativeCollection.prototype._getCollection = function _getCollection() { if (this.collection) { return this.collection; } if (this.conn.db != null) { this.collection = this.conn.db.collection(this.name); return this.collection; } return null; }; var syncCollectionMethods = { watch: true, find: true, aggregate: true }; function iter(i) { NativeCollection.prototype[i] = function() { const collection = this._getCollection(); const args = Array.from(arguments); const _this = this; const globalDebug = _this && _this.conn && _this.conn.base && _this.conn.base.options && _this.conn.base.options.debug; const connectionDebug = _this && _this.conn && _this.conn.options && _this.conn.options.debug; const debug = connectionDebug == null ? globalDebug : connectionDebug; const lastArg = arguments[arguments.length - 1]; const opId = new ObjectId2(); if (this.conn.$wasForceClosed) { const error = new MongooseError("Connection was force closed"); if (args.length > 0 && typeof args[args.length - 1] === "function") { args[args.length - 1](error); return; } else { throw error; } } let _args = args; let callback = null; if (this._shouldBufferCommands() && this.buffer) { this.conn.emit("buffer", { _id: opId, modelName: _this.modelName, collectionName: _this.name, method: i, args }); let callback2; let _args2 = args; let promise = null; let timeout = null; if (syncCollectionMethods[i] && typeof lastArg === "function") { this.addQueue(i, _args2); callback2 = lastArg; } else if (syncCollectionMethods[i]) { promise = new this.Promise((resolve, reject) => { callback2 = function collectionOperationCallback(err, res) { if (timeout != null) { clearTimeout(timeout); } if (err != null) { return reject(err); } resolve(res); }; _args2 = args.concat([callback2]); this.addQueue(i, _args2); }); } else if (typeof lastArg === "function") { callback2 = function collectionOperationCallback() { if (timeout != null) { clearTimeout(timeout); } return lastArg.apply(this, arguments); }; _args2 = args.slice(0, args.length - 1).concat([callback2]); } else { promise = new Promise((resolve, reject) => { callback2 = function collectionOperationCallback(err, res) { if (timeout != null) { clearTimeout(timeout); } if (err != null) { return reject(err); } resolve(res); }; _args2 = args.concat([callback2]); this.addQueue(i, _args2); }); } const bufferTimeoutMS = this._getBufferTimeoutMS(); timeout = setTimeout(() => { const removed = this.removeQueue(i, _args2); if (removed) { const message = "Operation `" + this.name + "." + i + "()` buffering timed out after " + bufferTimeoutMS + "ms"; const err = new MongooseError(message); this.conn.emit("buffer-end", { _id: opId, modelName: _this.modelName, collectionName: _this.name, method: i, error: err }); callback2(err); } }, bufferTimeoutMS); if (!syncCollectionMethods[i] && typeof lastArg === "function") { this.addQueue(i, _args2); return; } return promise; } else if (!syncCollectionMethods[i] && typeof lastArg === "function") { callback = function collectionOperationCallback(err, res) { if (err != null) { _this.conn.emit("operation-end", { _id: opId, modelName: _this.modelName, collectionName: _this.name, method: i, error: err }); } else { _this.conn.emit("operation-end", { _id: opId, modelName: _this.modelName, collectionName: _this.name, method: i, result: res }); } return lastArg.apply(this, arguments); }; _args = args.slice(0, args.length - 1).concat([callback]); } if (debug) { if (typeof debug === "function") { let argsToAdd = null; if (typeof args[args.length - 1] == "function") { argsToAdd = args.slice(0, args.length - 1); } else { argsToAdd = args; } debug.apply( _this, [_this.name, i].concat(argsToAdd) ); } else if (debug instanceof stream.Writable) { this.$printToStream(_this.name, i, args, debug); } else { const color = debug.color == null ? true : debug.color; const shell = debug.shell == null ? false : debug.shell; this.$print(_this.name, i, args, color, shell); } } this.conn.emit("operation-start", { _id: opId, modelName: _this.modelName, collectionName: this.name, method: i, params: _args }); try { if (collection == null) { const message = "Cannot call `" + this.name + "." + i + "()` before initial connection is complete if `bufferCommands = false`. Make sure you `await mongoose.connect()` if you have `bufferCommands = false`."; throw new MongooseError(message); } if (syncCollectionMethods[i] && typeof lastArg === "function") { const result = collection[i].apply(collection, _args.slice(0, _args.length - 1)); this.conn.emit("operation-end", { _id: opId, modelName: _this.modelName, collectionName: this.name, method: i, result }); return lastArg.call(this, null, result); } const ret = collection[i].apply(collection, _args); if (ret != null && typeof ret.then === "function") { return ret.then( (result) => { if (typeof lastArg === "function") { lastArg(null, result); } else { this.conn.emit("operation-end", { _id: opId, modelName: _this.modelName, collectionName: this.name, method: i, result }); } return result; }, (error) => { if (typeof lastArg === "function") { lastArg(error); return; } else { this.conn.emit("operation-end", { _id: opId, modelName: _this.modelName, collectionName: this.name, method: i, error }); } throw error; } ); } return ret; } catch (error) { if (typeof lastArg === "function") { return lastArg(error); } else { this.conn.emit("operation-end", { _id: opId, modelName: _this.modelName, collectionName: this.name, method: i, error }); throw error; } } }; } for (const key of Object.getOwnPropertyNames(Collection.prototype)) { const descriptor = Object.getOwnPropertyDescriptor(Collection.prototype, key); if (descriptor.get !== void 0) { continue; } if (typeof Collection.prototype[key] !== "function") { continue; } iter(key); } NativeCollection.prototype.$print = function(name, i, args, color, shell) { const moduleName = color ? "\x1B[0;36mMongoose:\x1B[0m " : "Mongoose: "; const functionCall = [name, i].join("."); const _args = []; for (let j = args.length - 1; j >= 0; --j) { if (this.$format(args[j]) || _args.length) { _args.unshift(this.$format(args[j], color, shell)); } } const params = "(" + _args.join(", ") + ")"; console.info(moduleName + functionCall + params); }; NativeCollection.prototype.$printToStream = function(name, i, args, stream2) { const functionCall = [name, i].join("."); const _args = []; for (let j = args.length - 1; j >= 0; --j) { if (this.$format(args[j]) || _args.length) { _args.unshift(this.$format(args[j])); } } const params = "(" + _args.join(", ") + ")"; stream2.write(functionCall + params, "utf8"); }; NativeCollection.prototype.$format = function(arg, color, shell) { const type = typeof arg; if (type === "function" || type === "undefined") return ""; return format(arg, false, color, shell); }; function inspectable(representation) { const ret = { inspect: function() { return representation; } }; if (util.inspect.custom) { ret[util.inspect.custom] = ret.inspect; } return ret; } function map(o) { return format(o, true); } function formatObjectId(x, key) { x[key] = inspectable('ObjectId("' + x[key].toHexString() + '")'); } function formatDate(x, key, shell) { if (shell) { x[key] = inspectable('ISODate("' + x[key].toUTCString() + '")'); } else { x[key] = inspectable('new Date("' + x[key].toUTCString() + '")'); } } function format(obj, sub, color, shell) { if (obj && typeof obj.toBSON === "function") { obj = obj.toBSON(); } if (obj == null) { return obj; } const clone = require_clone(); let x = sub ? obj : clone(obj, formatToObjectOptions); const constructorName = getConstructorName(x); if (constructorName === "Binary") { x = "BinData(" + x.sub_type + ', "' + x.toString("base64") + '")'; } else if (constructorName === "ObjectId") { x = inspectable('ObjectId("' + x.toHexString() + '")'); } else if (constructorName === "Date") { x = inspectable('new Date("' + x.toUTCString() + '")'); } else if (constructorName === "Object") { const keys = Object.keys(x); const numKeys = keys.length; let key; for (let i = 0; i < numKeys; ++i) { key = keys[i]; if (x[key]) { let error; if (typeof x[key].toBSON === "function") { try { x[key] = x[key].toBSON(); } catch (_error) { error = _error; } } const _constructorName = getConstructorName(x[key]); if (_constructorName === "Binary") { x[key] = "BinData(" + x[key].sub_type + ', "' + x[key].buffer.toString("base64") + '")'; } else if (_constructorName === "Object") { x[key] = format(x[key], true); } else if (_constructorName === "ObjectId") { formatObjectId(x, key); } else if (_constructorName === "Date") { formatDate(x, key, shell); } else if (_constructorName === "ClientSession") { x[key] = inspectable('ClientSession("' + (x[key] && x[key].id && x[key].id.id && x[key].id.id.buffer || "").toString("hex") + '")'); } else if (Array.isArray(x[key])) { x[key] = x[key].map(map); } else if (error != null) { throw error; } } } } if (sub) { return x; } return util.inspect(x, false, 10, color).replace(/\n/g, "").replace(/\s{2,}/g, " "); } NativeCollection.prototype.getIndexes = NativeCollection.prototype.indexInformation; module2.exports = NativeCollection; } }); // netlify/functions/node_modules/mongoose/lib/cursor/changeStream.js var require_changeStream = __commonJS({ "netlify/functions/node_modules/mongoose/lib/cursor/changeStream.js"(exports2, module2) { "use strict"; var EventEmitter = require("events").EventEmitter; var MongooseError = require_mongooseError(); var driverChangeStreamEvents = ["close", "change", "end", "error", "resumeTokenChanged"]; var ChangeStream = class extends EventEmitter { constructor(changeStreamThunk, pipeline, options) { super(); this.driverChangeStream = null; this.closed = false; this.bindedEvents = false; this.pipeline = pipeline; this.options = options; this.errored = false; if (options && options.hydrate && !options.model) { throw new Error( "Cannot create change stream with `hydrate: true` unless calling `Model.watch()`" ); } let syncError = null; this.$driverChangeStreamPromise = new Promise((resolve, reject) => { try { changeStreamThunk((err, driverChangeStream) => { if (err != null) { this.errored = true; this.emit("error", err); return reject(err); } this.driverChangeStream = driverChangeStream; this.emit("ready"); resolve(); }); } catch (err) { syncError = err; this.errored = true; this.emit("error", err); reject(err); } }); if (syncError != null) { throw syncError; } } _bindEvents() { if (this.bindedEvents) { return; } this.bindedEvents = true; if (this.driverChangeStream == null) { this.$driverChangeStreamPromise.then( () => { this.driverChangeStream.on("close", () => { this.closed = true; }); driverChangeStreamEvents.forEach((ev) => { this.driverChangeStream.on(ev, (data) => { if (data != null && data.fullDocument != null && this.options && this.options.hydrate) { data.fullDocument = this.options.model.hydrate(data.fullDocument); } this.emit(ev, data); }); }); }, () => { } // No need to register events if opening change stream failed ); return; } this.driverChangeStream.on("close", () => { this.closed = true; }); driverChangeStreamEvents.forEach((ev) => { this.driverChangeStream.on(ev, (data) => { if (data != null && data.fullDocument != null && this.options && this.options.hydrate) { data.fullDocument = this.options.model.hydrate(data.fullDocument); } this.emit(ev, data); }); }); } hasNext(cb) { if (this.errored) { throw new MongooseError("Cannot call hasNext() on errored ChangeStream"); } return this.driverChangeStream.hasNext(cb); } next(cb) { if (this.errored) { throw new MongooseError("Cannot call next() on errored ChangeStream"); } if (this.options && this.options.hydrate) { if (cb != null) { const originalCb = cb; cb = (err, data) => { if (err != null) { return originalCb(err); } if (data.fullDocument != null) { data.fullDocument = this.options.model.hydrate(data.fullDocument); } return originalCb(null, data); }; } let maybePromise = this.driverChangeStream.next(cb); if (maybePromise && typeof maybePromise.then === "function") { maybePromise = maybePromise.then((data) => { if (data.fullDocument != null) { data.fullDocument = this.options.model.hydrate(data.fullDocument); } return data; }); } return maybePromise; } return this.driverChangeStream.next(cb); } addListener(event, handler) { if (this.errored) { throw new MongooseError("Cannot call addListener() on errored ChangeStream"); } this._bindEvents(); return super.addListener(event, handler); } on(event, handler) { if (this.errored) { throw new MongooseError("Cannot call on() on errored ChangeStream"); } this._bindEvents(); return super.on(event, handler); } once(event, handler) { if (this.errored) { throw new MongooseError("Cannot call once() on errored ChangeStream"); } this._bindEvents(); return super.once(event, handler); } _queue(cb) { this.once("ready", () => cb()); } close() { this.closed = true; if (this.driverChangeStream) { return this.driverChangeStream.close(); } else { return this.$driverChangeStreamPromise.then( () => this.driverChangeStream.close(), () => { } // No need to close if opening the change stream failed ); } } }; module2.exports = ChangeStream; } }); // netlify/functions/node_modules/kareem/index.js var require_kareem = __commonJS({ "netlify/functions/node_modules/kareem/index.js"(exports2, module2) { "use strict"; function Kareem() { this._pres = /* @__PURE__ */ new Map(); this._posts = /* @__PURE__ */ new Map(); } Kareem.skipWrappedFunction = function skipWrappedFunction() { if (!(this instanceof Kareem.skipWrappedFunction)) { return new Kareem.skipWrappedFunction(...arguments); } this.args = [...arguments]; }; Kareem.overwriteResult = function overwriteResult() { if (!(this instanceof Kareem.overwriteResult)) { return new Kareem.overwriteResult(...arguments); } this.args = [...arguments]; }; Kareem.prototype.execPre = function(name, context, args, callback) { if (arguments.length === 3) { callback = args; args = []; } const pres = this._pres.get(name) || []; const numPres = pres.length; const numAsyncPres = pres.numAsync || 0; let currentPre = 0; let asyncPresLeft = numAsyncPres; let done = false; const $args = args; let shouldSkipWrappedFunction = null; if (!numPres) { return nextTick(function() { callback(null); }); } function next() { if (currentPre >= numPres) { return; } const pre = pres[currentPre]; if (pre.isAsync) { const args2 = [ decorateNextFn(_next), decorateNextFn(function(error) { if (error) { if (done) { return; } if (error instanceof Kareem.skipWrappedFunction) { shouldSkipWrappedFunction = error; } else { done = true; return callback(error); } } if (--asyncPresLeft === 0 && currentPre >= numPres) { return callback(shouldSkipWrappedFunction); } }) ]; callMiddlewareFunction(pre.fn, context, args2, args2[0]); } else if (pre.fn.length > 0) { const args2 = [decorateNextFn(_next)]; const _args = arguments.length >= 2 ? arguments : [null].concat($args); for (let i = 1; i < _args.length; ++i) { if (i === _args.length - 1 && typeof _args[i] === "function") { continue; } args2.push(_args[i]); } callMiddlewareFunction(pre.fn, context, args2, args2[0]); } else { let maybePromiseLike = null; try { maybePromiseLike = pre.fn.call(context); } catch (err) { if (err != null) { return callback(err); } } if (isPromiseLike(maybePromiseLike)) { maybePromiseLike.then(() => _next(), (err) => _next(err)); } else { if (++currentPre >= numPres) { if (asyncPresLeft > 0) { return; } else { return nextTick(function() { callback(shouldSkipWrappedFunction); }); } } next(); } } } next.apply(null, [null].concat(args)); function _next(error) { if (error) { if (done) { return; } if (error instanceof Kareem.skipWrappedFunction) { shouldSkipWrappedFunction = error; } else { done = true; return callback(error); } } if (++currentPre >= numPres) { if (asyncPresLeft > 0) { return; } else { return callback(shouldSkipWrappedFunction); } } next.apply(context, arguments); } }; Kareem.prototype.execPreSync = function(name, context, args) { const pres = this._pres.get(name) || []; const numPres = pres.length; for (let i = 0; i < numPres; ++i) { pres[i].fn.apply(context, args || []); } }; Kareem.prototype.execPost = function(name, context, args, options, callback) { if (arguments.length < 5) { callback = options; options = null; } const posts = this._posts.get(name) || []; const numPosts = posts.length; let currentPost = 0; let firstError = null; if (options && options.error) { firstError = options.error; } if (!numPosts) { return nextTick(function() { callback.apply(null, [firstError].concat(args)); }); } function next() { const post = posts[currentPost].fn; let numArgs = 0; const argLength = args.length; const newArgs = []; for (let i = 0; i < argLength; ++i) { numArgs += args[i] && args[i]._kareemIgnore ? 0 : 1; if (!args[i] || !args[i]._kareemIgnore) { newArgs.push(args[i]); } } if (firstError) { if (isErrorHandlingMiddleware(posts[currentPost], numArgs)) { const _cb = decorateNextFn(function(error) { if (error) { if (error instanceof Kareem.overwriteResult) { args = error.args; if (++currentPost >= numPosts) { return callback.call(null, firstError); } return next(); } firstError = error; } if (++currentPost >= numPosts) { return callback.call(null, firstError); } next(); }); callMiddlewareFunction( post, context, [firstError].concat(newArgs).concat([_cb]), _cb ); } else { if (++currentPost >= numPosts) { return callback.call(null, firstError); } next(); } } else { const _cb = decorateNextFn(function(error) { if (error) { if (error instanceof Kareem.overwriteResult) { args = error.args; if (++currentPost >= numPosts) { return callback.apply(null, [null].concat(args)); } return next(); } firstError = error; return next(); } if (++currentPost >= numPosts) { return callback.apply(null, [null].concat(args)); } next(); }); if (isErrorHandlingMiddleware(posts[currentPost], numArgs)) { if (++currentPost >= numPosts) { return callback.apply(null, [null].concat(args)); } return next(); } if (post.length === numArgs + 1) { callMiddlewareFunction(post, context, newArgs.concat([_cb]), _cb); } else { let error; let maybePromiseLike; try { maybePromiseLike = post.apply(context, newArgs); } catch (err) { error = err; firstError = err; } if (isPromiseLike(maybePromiseLike)) { return maybePromiseLike.then( (res) => { _cb(res instanceof Kareem.overwriteResult ? res : null); }, (err) => _cb(err) ); } if (maybePromiseLike instanceof Kareem.overwriteResult) { args = maybePromiseLike.args; } if (++currentPost >= numPosts) { return callback.apply(null, [error].concat(args)); } next(); } } } next(); }; Kareem.prototype.execPostSync = function(name, context, args) { const posts = this._posts.get(name) || []; const numPosts = posts.length; for (let i = 0; i < numPosts; ++i) { const res = posts[i].fn.apply(context, args || []); if (res instanceof Kareem.overwriteResult) { args = res.args; } } return args; }; Kareem.prototype.createWrapperSync = function(name, fn) { const _this = this; return function syncWrapper() { _this.execPreSync(name, this, arguments); const toReturn = fn.apply(this, arguments); const result = _this.execPostSync(name, this, [toReturn]); return result[0]; }; }; function _handleWrapError(instance, error, name, context, args, options, callback) { if (options.useErrorHandlers) { return instance.execPost(name, context, args, { error }, function(error2) { return typeof callback === "function" && callback(error2); }); } else { return typeof callback === "function" && callback(error); } } Kareem.prototype.wrap = function(name, fn, context, args, options) { const lastArg = args.length > 0 ? args[args.length - 1] : null; const argsWithoutCb = Array.from(args); typeof lastArg === "function" && argsWithoutCb.pop(); const _this = this; options = options || {}; const checkForPromise = options.checkForPromise; this.execPre(name, context, args, function(error) { if (error && !(error instanceof Kareem.skipWrappedFunction)) { const numCallbackParams = options.numCallbackParams || 0; const errorArgs = options.contextParameter ? [context] : []; for (let i = errorArgs.length; i < numCallbackParams; ++i) { errorArgs.push(null); } return _handleWrapError( _this, error, name, context, errorArgs, options, lastArg ); } const numParameters = fn.length; let ret; if (error instanceof Kareem.skipWrappedFunction) { ret = error.args[0]; return _cb(null, ...error.args); } else { try { ret = fn.apply(context, argsWithoutCb.concat(_cb)); } catch (err) { return _cb(err); } } if (checkForPromise) { if (isPromiseLike(ret)) { return ret.then( (res) => _cb(null, res), (err) => _cb(err) ); } if (numParameters < argsWithoutCb.length + 1) { return _cb(null, ret); } } function _cb() { const argsWithoutError = Array.from(arguments); argsWithoutError.shift(); if (options.nullResultByDefault && argsWithoutError.length === 0) { argsWithoutError.push(null); } if (arguments[0]) { return _handleWrapError( _this, arguments[0], name, context, argsWithoutError, options, lastArg ); } else { _this.execPost(name, context, argsWithoutError, function() { if (lastArg === null) { return; } arguments[0] ? lastArg(arguments[0]) : lastArg.apply(context, arguments); }); } } }); }; Kareem.prototype.filter = function(fn) { const clone = this.clone(); const pres = Array.from(clone._pres.keys()); for (const name of pres) { const hooks = this._pres.get(name).map((h) => Object.assign({}, h, { name })).filter(fn); if (hooks.length === 0) { clone._pres.delete(name); continue; } hooks.numAsync = hooks.filter((h) => h.isAsync).length; clone._pres.set(name, hooks); } const posts = Array.from(clone._posts.keys()); for (const name of posts) { const hooks = this._posts.get(name).map((h) => Object.assign({}, h, { name })).filter(fn); if (hooks.length === 0) { clone._posts.delete(name); continue; } clone._posts.set(name, hooks); } return clone; }; Kareem.prototype.hasHooks = function(name) { return this._pres.has(name) || this._posts.has(name); }; Kareem.prototype.createWrapper = function(name, fn, context, options) { const _this = this; if (!this.hasHooks(name)) { return function() { nextTick(() => fn.apply(this, arguments)); }; } return function() { const _context = context || this; _this.wrap(name, fn, _context, Array.from(arguments), options); }; }; Kareem.prototype.pre = function(name, isAsync, fn, error, unshift) { let options = {}; if (typeof isAsync === "object" && isAsync !== null) { options = isAsync; isAsync = options.isAsync; } else if (typeof arguments[1] !== "boolean") { fn = isAsync; isAsync = false; } const pres = this._pres.get(name) || []; this._pres.set(name, pres); if (isAsync) { pres.numAsync = pres.numAsync || 0; ++pres.numAsync; } if (typeof fn !== "function") { throw new Error('pre() requires a function, got "' + typeof fn + '"'); } if (unshift) { pres.unshift(Object.assign({}, options, { fn, isAsync })); } else { pres.push(Object.assign({}, options, { fn, isAsync })); } return this; }; Kareem.prototype.post = function(name, options, fn, unshift) { const posts = this._posts.get(name) || []; if (typeof options === "function") { unshift = !!fn; fn = options; options = {}; } if (typeof fn !== "function") { throw new Error('post() requires a function, got "' + typeof fn + '"'); } if (unshift) { posts.unshift(Object.assign({}, options, { fn })); } else { posts.push(Object.assign({}, options, { fn })); } this._posts.set(name, posts); return this; }; Kareem.prototype.clone = function() { const n = new Kareem(); for (const key of this._pres.keys()) { const clone = this._pres.get(key).slice(); clone.numAsync = this._pres.get(key).numAsync; n._pres.set(key, clone); } for (const key of this._posts.keys()) { n._posts.set(key, this._posts.get(key).slice()); } return n; }; Kareem.prototype.merge = function(other, clone) { clone = arguments.length === 1 ? true : clone; const ret = clone ? this.clone() : this; for (const key of other._pres.keys()) { const sourcePres = ret._pres.get(key) || []; const deduplicated = other._pres.get(key).filter((p) => sourcePres.map((_p) => _p.fn).indexOf(p.fn) === -1); const combined = sourcePres.concat(deduplicated); combined.numAsync = sourcePres.numAsync || 0; combined.numAsync += deduplicated.filter((p) => p.isAsync).length; ret._pres.set(key, combined); } for (const key of other._posts.keys()) { const sourcePosts = ret._posts.get(key) || []; const deduplicated = other._posts.get(key).filter((p) => sourcePosts.indexOf(p) === -1); ret._posts.set(key, sourcePosts.concat(deduplicated)); } return ret; }; function callMiddlewareFunction(fn, context, args, next) { let maybePromiseLike; try { maybePromiseLike = fn.apply(context, args); } catch (error) { return next(error); } if (isPromiseLike(maybePromiseLike)) { maybePromiseLike.then(() => next(), (err) => next(err)); } } function isPromiseLike(v) { return typeof v === "object" && v !== null && typeof v.then === "function"; } function decorateNextFn(fn) { let called = false; const _this = this; return function() { if (called) { return; } called = true; return nextTick(() => fn.apply(_this, arguments)); }; } var nextTick = typeof process === "object" && process !== null && process.nextTick || function nextTick2(cb) { setTimeout(cb, 0); }; function isErrorHandlingMiddleware(post, numArgs) { if (post.errorHandler) { return true; } return post.fn.length === numArgs + 2; } module2.exports = Kareem; } }); // netlify/functions/node_modules/mongoose/lib/error/messages.js var require_messages = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/messages.js"(exports2, module2) { "use strict"; var msg = module2.exports = exports2 = {}; msg.DocumentNotFoundError = null; msg.general = {}; msg.general.default = "Validator failed for path `{PATH}` with value `{VALUE}`"; msg.general.required = "Path `{PATH}` is required."; msg.Number = {}; msg.Number.min = "Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN})."; msg.Number.max = "Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX})."; msg.Number.enum = "`{VALUE}` is not a valid enum value for path `{PATH}`."; msg.Date = {}; msg.Date.min = "Path `{PATH}` ({VALUE}) is before minimum allowed value ({MIN})."; msg.Date.max = "Path `{PATH}` ({VALUE}) is after maximum allowed value ({MAX})."; msg.String = {}; msg.String.enum = "`{VALUE}` is not a valid enum value for path `{PATH}`."; msg.String.match = "Path `{PATH}` is invalid ({VALUE})."; msg.String.minlength = "Path `{PATH}` (`{VALUE}`, length {LENGTH}) is shorter than the minimum allowed length ({MINLENGTH})."; msg.String.maxlength = "Path `{PATH}` (`{VALUE}`, length {LENGTH}) is longer than the maximum allowed length ({MAXLENGTH})."; } }); // netlify/functions/node_modules/mongoose/lib/error/cast.js var require_cast = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/cast.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var util = require("util"); var CastError = class extends MongooseError { constructor(type, value, path, reason, schemaType) { if (arguments.length > 0) { const valueType = getValueType(value); const messageFormat = getMessageFormat(schemaType); const msg = formatMessage(null, type, value, path, messageFormat, valueType, reason); super(msg); this.init(type, value, path, reason, schemaType); } else { super(formatMessage()); } } toJSON() { return { stringValue: this.stringValue, valueType: this.valueType, kind: this.kind, value: this.value, path: this.path, reason: this.reason, name: this.name, message: this.message }; } /*! * ignore */ init(type, value, path, reason, schemaType) { this.stringValue = getStringValue(value); this.messageFormat = getMessageFormat(schemaType); this.kind = type; this.value = value; this.path = path; this.reason = reason; this.valueType = getValueType(value); } /** * ignore * @param {Readonly} other * @api private */ copy(other) { this.messageFormat = other.messageFormat; this.stringValue = other.stringValue; this.kind = other.kind; this.value = other.value; this.path = other.path; this.reason = other.reason; this.message = other.message; this.valueType = other.valueType; } /*! * ignore */ setModel(model) { this.message = formatMessage( model, this.kind, this.value, this.path, this.messageFormat, this.valueType ); } }; Object.defineProperty(CastError.prototype, "name", { value: "CastError" }); function getStringValue(value) { let stringValue = util.inspect(value); stringValue = stringValue.replace(/^'|'$/g, '"'); if (!stringValue.startsWith('"')) { stringValue = '"' + stringValue + '"'; } return stringValue; } function getValueType(value) { if (value == null) { return "" + value; } const t = typeof value; if (t !== "object") { return t; } if (typeof value.constructor !== "function") { return t; } return value.constructor.name; } function getMessageFormat(schemaType) { const messageFormat = schemaType && schemaType._castErrorMessage || null; if (typeof messageFormat === "string" || typeof messageFormat === "function") { return messageFormat; } } function formatMessage(model, kind, value, path, messageFormat, valueType, reason) { if (typeof messageFormat === "string") { const stringValue = getStringValue(value); let ret = messageFormat.replace("{KIND}", kind).replace("{VALUE}", stringValue).replace("{PATH}", path); if (model != null) { ret = ret.replace("{MODEL}", model.modelName); } return ret; } else if (typeof messageFormat === "function") { return messageFormat(value, path, model, kind); } else { const stringValue = getStringValue(value); const valueTypeMsg = valueType ? " (type " + valueType + ")" : ""; let ret = "Cast to " + kind + " failed for value " + stringValue + valueTypeMsg + ' at path "' + path + '"'; if (model != null) { ret += ' for model "' + model.modelName + '"'; } if (reason != null && typeof reason.constructor === "function" && reason.constructor.name !== "AssertionError" && reason.constructor.name !== "Error") { ret += ' because of "' + reason.constructor.name + '"'; } return ret; } } module2.exports = CastError; } }); // netlify/functions/node_modules/mongoose/lib/error/notFound.js var require_notFound = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/notFound.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var util = require("util"); var DocumentNotFoundError = class extends MongooseError { constructor(filter, model, numAffected, result) { let msg; const messages = MongooseError.messages; if (messages.DocumentNotFoundError != null) { msg = typeof messages.DocumentNotFoundError === "function" ? messages.DocumentNotFoundError(filter, model) : messages.DocumentNotFoundError; } else { msg = 'No document found for query "' + util.inspect(filter) + '" on model "' + model + '"'; } super(msg); this.result = result; this.numAffected = numAffected; this.filter = filter; this.query = filter; } }; Object.defineProperty(DocumentNotFoundError.prototype, "name", { value: "DocumentNotFoundError" }); module2.exports = DocumentNotFoundError; } }); // netlify/functions/node_modules/mongoose/lib/helpers/error/combinePathErrors.js var require_combinePathErrors = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/error/combinePathErrors.js"(exports2, module2) { "use strict"; module2.exports = function combinePathErrors(err) { const keys = Object.keys(err.errors || {}); const len = keys.length; const msgs = []; let key; for (let i = 0; i < len; ++i) { key = keys[i]; if (err === err.errors[key]) { continue; } msgs.push(key + ": " + err.errors[key].message); } return msgs.join(", "); }; } }); // netlify/functions/node_modules/mongoose/lib/error/validation.js var require_validation = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/validation.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var getConstructorName = require_getConstructorName(); var util = require("util"); var combinePathErrors = require_combinePathErrors(); var ValidationError = class _ValidationError extends MongooseError { constructor(instance) { let _message; if (getConstructorName(instance) === "model") { _message = instance.constructor.modelName + " validation failed"; } else { _message = "Validation failed"; } super(_message); this.errors = {}; this._message = _message; if (instance) { instance.$errors = this.errors; } } /** * Console.log helper */ toString() { return this.name + ": " + combinePathErrors(this); } /** * inspect helper * @api private */ inspect() { return Object.assign(new Error(this.message), this); } /** * add message * @param {String} path * @param {String|Error} error * @api private */ addError(path, error) { if (error instanceof _ValidationError) { const { errors } = error; for (const errorPath of Object.keys(errors)) { this.addError(`${path}.${errorPath}`, errors[errorPath]); } return; } this.errors[path] = error; this.message = this._message + ": " + combinePathErrors(this); } }; if (util.inspect.custom) { ValidationError.prototype[util.inspect.custom] = ValidationError.prototype.inspect; } Object.defineProperty(ValidationError.prototype, "toJSON", { enumerable: false, writable: false, configurable: true, value: function() { return Object.assign({}, this, { name: this.name, message: this.message }); } }); Object.defineProperty(ValidationError.prototype, "name", { value: "ValidationError" }); module2.exports = ValidationError; } }); // netlify/functions/node_modules/mongoose/lib/error/validator.js var require_validator = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/validator.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var ValidatorError = class extends MongooseError { constructor(properties, doc) { let msg = properties.message; if (!msg) { msg = MongooseError.messages.general.default; } const message = formatMessage(msg, properties, doc); super(message); properties = Object.assign({}, properties, { message }); this.properties = properties; this.kind = properties.type; this.path = properties.path; this.value = properties.value; this.reason = properties.reason; } /** * toString helper * TODO remove? This defaults to `${this.name}: ${this.message}` * @api private */ toString() { return this.message; } /** * Ensure `name` and `message` show up in toJSON output re: gh-9296 * @api private */ toJSON() { return Object.assign({ name: this.name, message: this.message }, this); } }; Object.defineProperty(ValidatorError.prototype, "name", { value: "ValidatorError" }); Object.defineProperty(ValidatorError.prototype, "properties", { enumerable: false, writable: true, value: null }); ValidatorError.prototype.formatMessage = formatMessage; function formatMessage(msg, properties, doc) { if (typeof msg === "function") { return msg(properties, doc); } const propertyNames = Object.keys(properties); for (const propertyName of propertyNames) { if (propertyName === "message") { continue; } msg = msg.replace("{" + propertyName.toUpperCase() + "}", properties[propertyName]); } return msg; } module2.exports = ValidatorError; } }); // netlify/functions/node_modules/mongoose/lib/error/version.js var require_version = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/version.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var VersionError = class extends MongooseError { constructor(doc, currentVersion, modifiedPaths) { const modifiedPathsStr = modifiedPaths.join(", "); super('No matching document found for id "' + doc._doc._id + '" version ' + currentVersion + ' modifiedPaths "' + modifiedPathsStr + '"'); this.version = currentVersion; this.modifiedPaths = modifiedPaths; } }; Object.defineProperty(VersionError.prototype, "name", { value: "VersionError" }); module2.exports = VersionError; } }); // netlify/functions/node_modules/mongoose/lib/error/parallelSave.js var require_parallelSave = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/parallelSave.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var ParallelSaveError = class extends MongooseError { constructor(doc) { const msg = "Can't save() the same doc multiple times in parallel. Document: "; super(msg + doc._doc._id); } }; Object.defineProperty(ParallelSaveError.prototype, "name", { value: "ParallelSaveError" }); module2.exports = ParallelSaveError; } }); // netlify/functions/node_modules/mongoose/lib/error/overwriteModel.js var require_overwriteModel = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/overwriteModel.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var OverwriteModelError = class extends MongooseError { constructor(name) { super("Cannot overwrite `" + name + "` model once compiled."); } }; Object.defineProperty(OverwriteModelError.prototype, "name", { value: "OverwriteModelError" }); module2.exports = OverwriteModelError; } }); // netlify/functions/node_modules/mongoose/lib/error/missingSchema.js var require_missingSchema = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/missingSchema.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var MissingSchemaError = class extends MongooseError { constructor(name) { const msg = `Schema hasn't been registered for model "` + name + '".\nUse mongoose.model(name, schema)'; super(msg); } }; Object.defineProperty(MissingSchemaError.prototype, "name", { value: "MissingSchemaError" }); module2.exports = MissingSchemaError; } }); // netlify/functions/node_modules/mongoose/lib/error/bulkSaveIncompleteError.js var require_bulkSaveIncompleteError = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/bulkSaveIncompleteError.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var MongooseBulkSaveIncompleteError = class extends MongooseError { constructor(modelName, documents, bulkWriteResult) { const matchedCount = bulkWriteResult?.matchedCount ?? 0; const insertedCount = bulkWriteResult?.insertedCount ?? 0; let preview = documents.map((doc) => doc._id).join(", "); if (preview.length > 100) { preview = preview.slice(0, 100) + "..."; } const numDocumentsNotUpdated = documents.length - matchedCount - insertedCount; super(`${modelName}.bulkSave() was not able to update ${numDocumentsNotUpdated} of the given documents due to incorrect version or optimistic concurrency, document ids: ${preview}`); this.modelName = modelName; this.documents = documents; this.bulkWriteResult = bulkWriteResult; this.numDocumentsNotUpdated = numDocumentsNotUpdated; } }; Object.defineProperty(MongooseBulkSaveIncompleteError.prototype, "name", { value: "MongooseBulkSaveIncompleteError" }); module2.exports = MongooseBulkSaveIncompleteError; } }); // netlify/functions/node_modules/mongoose/lib/helpers/topology/allServersUnknown.js var require_allServersUnknown = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/topology/allServersUnknown.js"(exports2, module2) { "use strict"; var getConstructorName = require_getConstructorName(); module2.exports = function allServersUnknown(topologyDescription) { if (getConstructorName(topologyDescription) !== "TopologyDescription") { return false; } const servers = Array.from(topologyDescription.servers.values()); return servers.length > 0 && servers.every((server) => server.type === "Unknown"); }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/topology/isAtlas.js var require_isAtlas = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/topology/isAtlas.js"(exports2, module2) { "use strict"; var getConstructorName = require_getConstructorName(); module2.exports = function isAtlas(topologyDescription) { if (getConstructorName(topologyDescription) !== "TopologyDescription") { return false; } if (topologyDescription.servers.size === 0) { return false; } for (const server of topologyDescription.servers.values()) { if (server.host.endsWith(".mongodb.net") === false || server.port !== 27017) { return false; } } return true; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/topology/isSSLError.js var require_isSSLError = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/topology/isSSLError.js"(exports2, module2) { "use strict"; var getConstructorName = require_getConstructorName(); var nonSSLMessage = "Client network socket disconnected before secure TLS connection was established"; module2.exports = function isSSLError(topologyDescription) { if (getConstructorName(topologyDescription) !== "TopologyDescription") { return false; } const descriptions = Array.from(topologyDescription.servers.values()); return descriptions.length > 0 && descriptions.every((descr) => descr.error && descr.error.message.indexOf(nonSSLMessage) !== -1); }; } }); // netlify/functions/node_modules/mongoose/lib/error/serverSelection.js var require_serverSelection = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/serverSelection.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var allServersUnknown = require_allServersUnknown(); var isAtlas = require_isAtlas(); var isSSLError = require_isSSLError(); var atlasMessage = "Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://www.mongodb.com/docs/atlas/security-whitelist/"; var sslMessage = "Mongoose is connecting with SSL enabled, but the server is not accepting SSL connections. Please ensure that the MongoDB server you are connecting to is configured to accept SSL connections. Learn more: https://mongoosejs.com/docs/tutorials/ssl.html"; var MongooseServerSelectionError = class extends MongooseError { /** * MongooseServerSelectionError constructor * * @api private */ assimilateError(err) { const reason = err.reason; const isAtlasWhitelistError = isAtlas(reason) && allServersUnknown(reason) && err.message.indexOf("bad auth") === -1 && err.message.indexOf("Authentication failed") === -1; if (isAtlasWhitelistError) { this.message = atlasMessage; } else if (isSSLError(reason)) { this.message = sslMessage; } else { this.message = err.message; } for (const key in err) { if (key !== "name") { this[key] = err[key]; } } this.cause = reason; return this; } }; Object.defineProperty(MongooseServerSelectionError.prototype, "name", { value: "MongooseServerSelectionError" }); module2.exports = MongooseServerSelectionError; } }); // netlify/functions/node_modules/mongoose/lib/error/divergentArray.js var require_divergentArray = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/divergentArray.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var DivergentArrayError = class extends MongooseError { constructor(paths) { const msg = "For your own good, using `document.save()` to update an array which was selected using an $elemMatch projection OR populated using skip, limit, query conditions, or exclusion of the _id field when the operation results in a $pop or $set of the entire array is not supported. The following path(s) would have been modified unsafely:\n " + paths.join("\n ") + "\nUse Model.updateOne() to update these arrays instead."; super(msg); } }; Object.defineProperty(DivergentArrayError.prototype, "name", { value: "DivergentArrayError" }); module2.exports = DivergentArrayError; } }); // netlify/functions/node_modules/mongoose/lib/error/strict.js var require_strict = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/strict.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var StrictModeError = class extends MongooseError { constructor(path, msg, immutable) { msg = msg || "Field `" + path + "` is not in schema and strict mode is set to throw."; super(msg); this.isImmutableError = !!immutable; this.path = path; } }; Object.defineProperty(StrictModeError.prototype, "name", { value: "StrictModeError" }); module2.exports = StrictModeError; } }); // netlify/functions/node_modules/mongoose/lib/error/strictPopulate.js var require_strictPopulate = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/strictPopulate.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var StrictPopulateError = class extends MongooseError { constructor(path, msg) { msg = msg || "Cannot populate path `" + path + "` because it is not in your schema. Set the `strictPopulate` option to false to override."; super(msg); this.path = path; } }; Object.defineProperty(StrictPopulateError.prototype, "name", { value: "StrictPopulateError" }); module2.exports = StrictPopulateError; } }); // netlify/functions/node_modules/mongoose/lib/error/index.js var require_error2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/index.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); module2.exports = exports2 = MongooseError; MongooseError.messages = require_messages(); MongooseError.Messages = MongooseError.messages; MongooseError.CastError = require_cast(); MongooseError.DocumentNotFoundError = require_notFound(); MongooseError.ValidationError = require_validation(); MongooseError.ValidatorError = require_validator(); MongooseError.VersionError = require_version(); MongooseError.ParallelSaveError = require_parallelSave(); MongooseError.OverwriteModelError = require_overwriteModel(); MongooseError.MissingSchemaError = require_missingSchema(); MongooseError.MongooseBulkSaveIncompleteError = require_bulkSaveIncompleteError(); MongooseError.MongooseServerSelectionError = require_serverSelection(); MongooseError.DivergentArrayError = require_divergentArray(); MongooseError.StrictModeError = require_strict(); MongooseError.StrictPopulateError = require_strictPopulate(); } }); // netlify/functions/node_modules/mongoose/lib/options/propertyOptions.js var require_propertyOptions = __commonJS({ "netlify/functions/node_modules/mongoose/lib/options/propertyOptions.js"(exports2, module2) { "use strict"; module2.exports = Object.freeze({ enumerable: true, configurable: true, writable: true, value: void 0 }); } }); // netlify/functions/node_modules/mongoose/lib/options/schemaTypeOptions.js var require_schemaTypeOptions = __commonJS({ "netlify/functions/node_modules/mongoose/lib/options/schemaTypeOptions.js"(exports2, module2) { "use strict"; var clone = require_clone(); var SchemaTypeOptions = class { constructor(obj) { if (obj == null) { return this; } Object.assign(this, clone(obj)); } }; var opts = require_propertyOptions(); Object.defineProperty(SchemaTypeOptions.prototype, "type", opts); Object.defineProperty(SchemaTypeOptions.prototype, "validate", opts); Object.defineProperty(SchemaTypeOptions.prototype, "cast", opts); Object.defineProperty(SchemaTypeOptions.prototype, "required", opts); Object.defineProperty(SchemaTypeOptions.prototype, "default", opts); Object.defineProperty(SchemaTypeOptions.prototype, "ref", opts); Object.defineProperty(SchemaTypeOptions.prototype, "refPath", opts); Object.defineProperty(SchemaTypeOptions.prototype, "select", opts); Object.defineProperty(SchemaTypeOptions.prototype, "index", opts); Object.defineProperty(SchemaTypeOptions.prototype, "unique", opts); Object.defineProperty(SchemaTypeOptions.prototype, "immutable", opts); Object.defineProperty(SchemaTypeOptions.prototype, "sparse", opts); Object.defineProperty(SchemaTypeOptions.prototype, "text", opts); Object.defineProperty(SchemaTypeOptions.prototype, "transform", opts); module2.exports = SchemaTypeOptions; } }); // netlify/functions/node_modules/mongoose/lib/cast/boolean.js var require_boolean = __commonJS({ "netlify/functions/node_modules/mongoose/lib/cast/boolean.js"(exports2, module2) { "use strict"; var CastError = require_cast(); module2.exports = function castBoolean(value, path) { if (module2.exports.convertToTrue.has(value)) { return true; } if (module2.exports.convertToFalse.has(value)) { return false; } if (value == null) { return value; } throw new CastError("boolean", value, path); }; module2.exports.convertToTrue = /* @__PURE__ */ new Set([true, "true", 1, "1", "yes"]); module2.exports.convertToFalse = /* @__PURE__ */ new Set([false, "false", 0, "0", "no"]); } }); // netlify/functions/node_modules/mongoose/lib/schema/operators/exists.js var require_exists = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/operators/exists.js"(exports2, module2) { "use strict"; var castBoolean = require_boolean(); module2.exports = function(val) { const path = this != null ? this.path : null; return castBoolean(val, path); }; } }); // netlify/functions/node_modules/mongoose/lib/schema/operators/type.js var require_type = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/operators/type.js"(exports2, module2) { "use strict"; module2.exports = function(val) { if (Array.isArray(val)) { if (!val.every((v) => typeof v === "number" || typeof v === "string")) { throw new Error("$type array values must be strings or numbers"); } return val; } if (typeof val !== "number" && typeof val !== "string") { throw new Error("$type parameter must be number, string, or array of numbers and strings"); } return val; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/schematype/handleImmutable.js var require_handleImmutable = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/schematype/handleImmutable.js"(exports2, module2) { "use strict"; var StrictModeError = require_strict(); module2.exports = function(schematype) { if (schematype.$immutable) { schematype.$immutableSetter = createImmutableSetter( schematype.path, schematype.options.immutable ); schematype.set(schematype.$immutableSetter); } else if (schematype.$immutableSetter) { schematype.setters = schematype.setters.filter((fn) => fn !== schematype.$immutableSetter); delete schematype.$immutableSetter; } }; function createImmutableSetter(path, immutable) { return function immutableSetter(v, _priorVal, _doc, options) { if (this == null || this.$__ == null) { return v; } if (this.isNew) { return v; } if (options && options.overwriteImmutable) { return v; } const _immutable = typeof immutable === "function" ? immutable.call(this, this) : immutable; if (!_immutable) { return v; } const _value = this.$__.priorDoc != null ? this.$__.priorDoc.$__getValue(path) : this.$__getValue(path); if (this.$__.strictMode === "throw" && v !== _value) { throw new StrictModeError(path, "Path `" + path + "` is immutable and strict mode is set to throw.", true); } return _value; }; } } }); // netlify/functions/node_modules/mongoose/lib/helpers/isAsyncFunction.js var require_isAsyncFunction = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/isAsyncFunction.js"(exports2, module2) { "use strict"; module2.exports = function isAsyncFunction(v) { return typeof v === "function" && v.constructor && v.constructor.name === "AsyncFunction"; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/isSimpleValidator.js var require_isSimpleValidator = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/isSimpleValidator.js"(exports2, module2) { "use strict"; module2.exports = function isSimpleValidator(obj) { const keys = Object.keys(obj); let result = true; for (let i = 0, len = keys.length; i < len; ++i) { if (typeof obj[keys[i]] === "object" && obj[keys[i]] !== null) { result = false; break; } } return result; }; } }); // netlify/functions/node_modules/ms/index.js var require_ms = __commonJS({ "netlify/functions/node_modules/ms/index.js"(exports2, module2) { var s = 1e3; var m = s * 60; var h = m * 60; var d = h * 24; var w = d * 7; var y = d * 365.25; module2.exports = function(val, options) { options = options || {}; var type = typeof val; if (type === "string" && val.length > 0) { return parse(val); } else if (type === "number" && isFinite(val)) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( "val is not a non-empty string or a valid number. val=" + JSON.stringify(val) ); }; function parse(str) { str = String(str); if (str.length > 100) { return; } var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || "ms").toLowerCase(); switch (type) { case "years": case "year": case "yrs": case "yr": case "y": return n * y; case "weeks": case "week": case "w": return n * w; case "days": case "day": case "d": return n * d; case "hours": case "hour": case "hrs": case "hr": case "h": return n * h; case "minutes": case "minute": case "mins": case "min": case "m": return n * m; case "seconds": case "second": case "secs": case "sec": case "s": return n * s; case "milliseconds": case "millisecond": case "msecs": case "msec": case "ms": return n; default: return void 0; } } function fmtShort(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return Math.round(ms / d) + "d"; } if (msAbs >= h) { return Math.round(ms / h) + "h"; } if (msAbs >= m) { return Math.round(ms / m) + "m"; } if (msAbs >= s) { return Math.round(ms / s) + "s"; } return ms + "ms"; } function fmtLong(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return plural(ms, msAbs, d, "day"); } if (msAbs >= h) { return plural(ms, msAbs, h, "hour"); } if (msAbs >= m) { return plural(ms, msAbs, m, "minute"); } if (msAbs >= s) { return plural(ms, msAbs, s, "second"); } return ms + " ms"; } function plural(ms, msAbs, n, name) { var isPlural = msAbs >= n * 1.5; return Math.round(ms / n) + " " + name + (isPlural ? "s" : ""); } } }); // netlify/functions/node_modules/mpath/lib/stringToParts.js var require_stringToParts = __commonJS({ "netlify/functions/node_modules/mpath/lib/stringToParts.js"(exports2, module2) { "use strict"; module2.exports = function stringToParts(str) { const result = []; let curPropertyName = ""; let state = "DEFAULT"; for (let i = 0; i < str.length; ++i) { if (state === "IN_SQUARE_BRACKETS" && !/\d/.test(str[i]) && str[i] !== "]") { state = "DEFAULT"; curPropertyName = result[result.length - 1] + "[" + curPropertyName; result.splice(result.length - 1, 1); } if (str[i] === "[") { if (state !== "IMMEDIATELY_AFTER_SQUARE_BRACKETS") { result.push(curPropertyName); curPropertyName = ""; } state = "IN_SQUARE_BRACKETS"; } else if (str[i] === "]") { if (state === "IN_SQUARE_BRACKETS") { state = "IMMEDIATELY_AFTER_SQUARE_BRACKETS"; result.push(curPropertyName); curPropertyName = ""; } else { state = "DEFAULT"; curPropertyName += str[i]; } } else if (str[i] === ".") { if (state !== "IMMEDIATELY_AFTER_SQUARE_BRACKETS") { result.push(curPropertyName); curPropertyName = ""; } state = "DEFAULT"; } else { curPropertyName += str[i]; } } if (state !== "IMMEDIATELY_AFTER_SQUARE_BRACKETS") { result.push(curPropertyName); } return result; }; } }); // netlify/functions/node_modules/mpath/lib/index.js var require_lib4 = __commonJS({ "netlify/functions/node_modules/mpath/lib/index.js"(exports2) { var stringToParts = require_stringToParts(); var ignoreProperties = ["__proto__", "constructor", "prototype"]; exports2.get = function(path, o, special, map) { var lookup; if ("function" == typeof special) { if (special.length < 2) { map = special; special = void 0; } else { lookup = special; special = void 0; } } map || (map = K); var parts = "string" == typeof path ? stringToParts(path) : path; if (!Array.isArray(parts)) { throw new TypeError("Invalid `path`. Must be either string or array"); } var obj = o, part; for (var i = 0; i < parts.length; ++i) { part = parts[i]; if (typeof parts[i] !== "string" && typeof parts[i] !== "number") { throw new TypeError("Each segment of path to `get()` must be a string or number, got " + typeof parts[i]); } if (Array.isArray(obj) && !/^\d+$/.test(part)) { var paths = parts.slice(i); return [].concat(obj).map(function(item) { return item ? exports2.get(paths, item, special || lookup, map) : map(void 0); }); } if (lookup) { obj = lookup(obj, part); } else { var _from = special && obj[special] ? obj[special] : obj; obj = _from instanceof Map ? _from.get(part) : _from[part]; } if (!obj) return map(obj); } return map(obj); }; exports2.has = function(path, o) { var parts = typeof path === "string" ? stringToParts(path) : path; if (!Array.isArray(parts)) { throw new TypeError("Invalid `path`. Must be either string or array"); } var len = parts.length; var cur = o; for (var i = 0; i < len; ++i) { if (typeof parts[i] !== "string" && typeof parts[i] !== "number") { throw new TypeError("Each segment of path to `has()` must be a string or number, got " + typeof parts[i]); } if (cur == null || typeof cur !== "object" || !(parts[i] in cur)) { return false; } cur = cur[parts[i]]; } return true; }; exports2.unset = function(path, o) { var parts = typeof path === "string" ? stringToParts(path) : path; if (!Array.isArray(parts)) { throw new TypeError("Invalid `path`. Must be either string or array"); } var len = parts.length; var cur = o; for (var i = 0; i < len; ++i) { if (cur == null || typeof cur !== "object" || !(parts[i] in cur)) { return false; } if (typeof parts[i] !== "string" && typeof parts[i] !== "number") { throw new TypeError("Each segment of path to `unset()` must be a string or number, got " + typeof parts[i]); } if (ignoreProperties.indexOf(parts[i]) !== -1) { return false; } if (i === len - 1) { delete cur[parts[i]]; return true; } cur = cur instanceof Map ? cur.get(parts[i]) : cur[parts[i]]; } return true; }; exports2.set = function(path, val, o, special, map, _copying) { var lookup; if ("function" == typeof special) { if (special.length < 2) { map = special; special = void 0; } else { lookup = special; special = void 0; } } map || (map = K); var parts = "string" == typeof path ? stringToParts(path) : path; if (!Array.isArray(parts)) { throw new TypeError("Invalid `path`. Must be either string or array"); } if (null == o) return; for (var i = 0; i < parts.length; ++i) { if (typeof parts[i] !== "string" && typeof parts[i] !== "number") { throw new TypeError("Each segment of path to `set()` must be a string or number, got " + typeof parts[i]); } if (ignoreProperties.indexOf(parts[i]) !== -1) { return; } } var copy = _copying || /\$/.test(path) && _copying !== false, obj = o, part; for (var i = 0, len = parts.length - 1; i < len; ++i) { part = parts[i]; if ("$" == part) { if (i == len - 1) { break; } else { continue; } } if (Array.isArray(obj) && !/^\d+$/.test(part)) { var paths = parts.slice(i); if (!copy && Array.isArray(val)) { for (var j = 0; j < obj.length && j < val.length; ++j) { exports2.set(paths, val[j], obj[j], special || lookup, map, copy); } } else { for (var j = 0; j < obj.length; ++j) { exports2.set(paths, val, obj[j], special || lookup, map, copy); } } return; } if (lookup) { obj = lookup(obj, part); } else { var _to = special && obj[special] ? obj[special] : obj; obj = _to instanceof Map ? _to.get(part) : _to[part]; } if (!obj) return; } part = parts[len]; if (special && obj[special]) { obj = obj[special]; } if (Array.isArray(obj) && !/^\d+$/.test(part)) { if (!copy && Array.isArray(val)) { _setArray(obj, val, part, lookup, special, map); } else { for (var j = 0; j < obj.length; ++j) { var item = obj[j]; if (item) { if (lookup) { lookup(item, part, map(val)); } else { if (item[special]) item = item[special]; item[part] = map(val); } } } } } else { if (lookup) { lookup(obj, part, map(val)); } else if (obj instanceof Map) { obj.set(part, map(val)); } else { obj[part] = map(val); } } }; exports2.stringToParts = stringToParts; function _setArray(obj, val, part, lookup, special, map) { for (var item, j = 0; j < obj.length && j < val.length; ++j) { item = obj[j]; if (Array.isArray(item) && Array.isArray(val[j])) { _setArray(item, val[j], part, lookup, special, map); } else if (item) { if (lookup) { lookup(item, part, map(val[j])); } else { if (item[special]) item = item[special]; item[part] = map(val[j]); } } } } function K(v) { return v; } } }); // netlify/functions/node_modules/mpath/index.js var require_mpath = __commonJS({ "netlify/functions/node_modules/mpath/index.js"(exports2, module2) { "use strict"; module2.exports = exports2 = require_lib4(); } }); // netlify/functions/node_modules/mongoose/lib/options/populateOptions.js var require_populateOptions = __commonJS({ "netlify/functions/node_modules/mongoose/lib/options/populateOptions.js"(exports2, module2) { "use strict"; var clone = require_clone(); var PopulateOptions = class { constructor(obj) { this._docs = {}; this._childDocs = []; if (obj == null) { return; } obj = clone(obj); Object.assign(this, obj); if (typeof obj.subPopulate === "object") { this.populate = obj.subPopulate; } if (obj.perDocumentLimit != null && obj.limit != null) { throw new Error("Can not use `limit` and `perDocumentLimit` at the same time. Path: `" + obj.path + "`."); } } }; module2.exports = PopulateOptions; } }); // netlify/functions/node_modules/mongoose/lib/types/documentArray/isMongooseDocumentArray.js var require_isMongooseDocumentArray = __commonJS({ "netlify/functions/node_modules/mongoose/lib/types/documentArray/isMongooseDocumentArray.js"(exports2) { "use strict"; exports2.isMongooseDocumentArray = function(mongooseDocumentArray) { return Array.isArray(mongooseDocumentArray) && mongooseDocumentArray.isMongooseDocumentArray; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/promiseOrCallback.js var require_promiseOrCallback = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/promiseOrCallback.js"(exports2, module2) { "use strict"; var immediate = require_immediate(); var emittedSymbol = Symbol("mongoose#emitted"); module2.exports = function promiseOrCallback(callback, fn, ee, Promise2) { if (typeof callback === "function") { try { return fn(function(error) { if (error != null) { if (ee != null && ee.listeners != null && ee.listeners("error").length > 0 && !error[emittedSymbol]) { error[emittedSymbol] = true; ee.emit("error", error); } try { callback(error); } catch (error2) { return immediate(() => { throw error2; }); } return; } callback.apply(this, arguments); }); } catch (error) { if (ee != null && ee.listeners != null && ee.listeners("error").length > 0 && !error[emittedSymbol]) { error[emittedSymbol] = true; ee.emit("error", error); } return callback(error); } } Promise2 = Promise2 || global.Promise; return new Promise2((resolve, reject) => { fn(function(error, res) { if (error != null) { if (ee != null && ee.listeners != null && ee.listeners("error").length > 0 && !error[emittedSymbol]) { error[emittedSymbol] = true; ee.emit("error", error); } return reject(error); } if (arguments.length > 2) { return resolve(Array.prototype.slice.call(arguments, 1)); } resolve(res); }); }); }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/schema/merge.js var require_merge = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/schema/merge.js"(exports2, module2) { "use strict"; module2.exports = function merge(s1, s2, skipConflictingPaths) { const paths = Object.keys(s2.tree); const pathsToAdd = {}; for (const key of paths) { if (skipConflictingPaths && (s1.paths[key] || s1.nested[key] || s1.singleNestedPaths[key])) { continue; } pathsToAdd[key] = s2.tree[key]; } s1.options._isMerging = true; s1.add(pathsToAdd, null); delete s1.options._isMerging; s1.callQueue = s1.callQueue.concat(s2.callQueue); s1.method(s2.methods); s1.static(s2.statics); for (const [option, value] of Object.entries(s2._userProvidedOptions)) { if (!(option in s1._userProvidedOptions)) { s1.set(option, value); } } for (const query in s2.query) { s1.query[query] = s2.query[query]; } for (const virtual in s2.virtuals) { s1.virtuals[virtual] = s2.virtuals[virtual].clone(); } s1._indexes = s1._indexes.concat(s2._indexes || []); s1.s.hooks.merge(s2.s.hooks, false); }; } }); // netlify/functions/node_modules/mongoose/lib/stateMachine.js var require_stateMachine = __commonJS({ "netlify/functions/node_modules/mongoose/lib/stateMachine.js"(exports2, module2) { "use strict"; var utils = require_utils3(); var StateMachine = module2.exports = exports2 = function StateMachine2() { }; StateMachine.ctor = function() { const states = [...arguments]; const ctor = function() { StateMachine.apply(this, arguments); this.paths = {}; this.states = {}; }; ctor.prototype = new StateMachine(); ctor.prototype.constructor = ctor; ctor.prototype.stateNames = states; states.forEach(function(state) { ctor.prototype[state] = function(path) { this._changeState(path, state); }; }); return ctor; }; StateMachine.prototype._changeState = function _changeState(path, nextState) { const prevState = this.paths[path]; if (prevState === nextState) { return; } const prevBucket = this.states[prevState]; if (prevBucket) delete prevBucket[path]; this.paths[path] = nextState; this.states[nextState] = this.states[nextState] || {}; this.states[nextState][path] = true; }; StateMachine.prototype.clear = function clear(state) { if (this.states[state] == null) { return; } const keys = Object.keys(this.states[state]); let i = keys.length; let path; while (i--) { path = keys[i]; delete this.states[state][path]; delete this.paths[path]; } }; StateMachine.prototype.clearPath = function clearPath(path) { const state = this.paths[path]; if (!state) { return; } delete this.paths[path]; delete this.states[state][path]; }; StateMachine.prototype.getStatePaths = function getStatePaths(state) { if (this.states[state] != null) { return this.states[state]; } return {}; }; StateMachine.prototype.some = function some() { const _this = this; const what = arguments.length ? arguments : this.stateNames; return Array.prototype.some.call(what, function(state) { if (_this.states[state] == null) { return false; } return Object.keys(_this.states[state]).length; }); }; StateMachine.prototype._iter = function _iter(iterMethod) { return function() { let states = [...arguments]; const callback = states.pop(); if (!states.length) states = this.stateNames; const _this = this; const paths = states.reduce(function(paths2, state) { if (_this.states[state] == null) { return paths2; } return paths2.concat(Object.keys(_this.states[state])); }, []); return paths[iterMethod](function(path, i, paths2) { return callback(path, i, paths2); }); }; }; StateMachine.prototype.forEach = function forEach() { this.forEach = this._iter("forEach"); return this.forEach.apply(this, arguments); }; StateMachine.prototype.map = function map() { this.map = this._iter("map"); return this.map.apply(this, arguments); }; StateMachine.prototype.clone = function clone() { const result = new this.constructor(); result.paths = { ...this.paths }; for (const state of this.stateNames) { if (!(state in this.states)) { continue; } result.states[state] = this.states[state] == null ? this.states[state] : { ...this.states[state] }; } return result; }; } }); // netlify/functions/node_modules/mongoose/lib/internal.js var require_internal = __commonJS({ "netlify/functions/node_modules/mongoose/lib/internal.js"(exports2, module2) { "use strict"; var StateMachine = require_stateMachine(); var ActiveRoster = StateMachine.ctor("require", "modify", "init", "default", "ignore"); module2.exports = exports2 = InternalCache; function InternalCache() { this.activePaths = new ActiveRoster(); } InternalCache.prototype.strictMode = true; InternalCache.prototype.fullPath = void 0; InternalCache.prototype.selected = void 0; InternalCache.prototype.shardval = void 0; InternalCache.prototype.saveError = void 0; InternalCache.prototype.validationError = void 0; InternalCache.prototype.adhocPaths = void 0; InternalCache.prototype.removing = void 0; InternalCache.prototype.inserting = void 0; InternalCache.prototype.saving = void 0; InternalCache.prototype.version = void 0; InternalCache.prototype._id = void 0; InternalCache.prototype.ownerDocument = void 0; InternalCache.prototype.populate = void 0; InternalCache.prototype.populated = void 0; InternalCache.prototype.primitiveAtomics = void 0; InternalCache.prototype.wasPopulated = false; InternalCache.prototype.scope = void 0; InternalCache.prototype.session = null; InternalCache.prototype.pathsToScopes = null; InternalCache.prototype.cachedRequired = null; } }); // netlify/functions/node_modules/mongoose/lib/types/buffer.js var require_buffer = __commonJS({ "netlify/functions/node_modules/mongoose/lib/types/buffer.js"(exports2, module2) { "use strict"; var Binary = require_bson().Binary; var UUID = require_bson().UUID; var utils = require_utils3(); function MongooseBuffer(value, encode, offset) { let val = value; if (value == null) { val = 0; } let encoding; let path; let doc; if (Array.isArray(encode)) { path = encode[0]; doc = encode[1]; } else { encoding = encode; } let buf; if (typeof val === "number" || val instanceof Number) { buf = Buffer.alloc(val); } else { buf = Buffer.from(val, encoding, offset); } utils.decorate(buf, MongooseBuffer.mixin); buf.isMongooseBuffer = true; buf[MongooseBuffer.pathSymbol] = path; buf[parentSymbol] = doc; buf._subtype = 0; return buf; } var pathSymbol = Symbol.for("mongoose#Buffer#_path"); var parentSymbol = Symbol.for("mongoose#Buffer#_parent"); MongooseBuffer.pathSymbol = pathSymbol; MongooseBuffer.mixin = { /** * Default subtype for the Binary representing this Buffer * * @api private * @property _subtype * @memberOf MongooseBuffer.mixin * @static */ _subtype: void 0, /** * Marks this buffer as modified. * * @api private * @method _markModified * @memberOf MongooseBuffer.mixin * @static */ _markModified: function() { const parent = this[parentSymbol]; if (parent) { parent.markModified(this[MongooseBuffer.pathSymbol]); } return this; }, /** * Writes the buffer. * * @api public * @method write * @memberOf MongooseBuffer.mixin * @static */ write: function() { const written = Buffer.prototype.write.apply(this, arguments); if (written > 0) { this._markModified(); } return written; }, /** * Copies the buffer. * * #### Note: * * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this. * * @return {Number} The number of bytes copied. * @param {Buffer} target * @method copy * @memberOf MongooseBuffer.mixin * @static */ copy: function(target) { const ret = Buffer.prototype.copy.apply(this, arguments); if (target && target.isMongooseBuffer) { target._markModified(); } return ret; } }; utils.each( [ // node < 0.5 "writeUInt8", "writeUInt16", "writeUInt32", "writeInt8", "writeInt16", "writeInt32", "writeFloat", "writeDouble", "fill", "utf8Write", "binaryWrite", "asciiWrite", "set", // node >= 0.5 "writeUInt16LE", "writeUInt16BE", "writeUInt32LE", "writeUInt32BE", "writeInt16LE", "writeInt16BE", "writeInt32LE", "writeInt32BE", "writeFloatLE", "writeFloatBE", "writeDoubleLE", "writeDoubleBE" ], function(method) { if (!Buffer.prototype[method]) { return; } MongooseBuffer.mixin[method] = function() { const ret = Buffer.prototype[method].apply(this, arguments); this._markModified(); return ret; }; } ); MongooseBuffer.mixin.toObject = function(options) { const subtype = typeof options === "number" ? options : this._subtype || 0; return new Binary(Buffer.from(this), subtype); }; MongooseBuffer.mixin.$toObject = MongooseBuffer.mixin.toObject; MongooseBuffer.mixin.toBSON = function() { return new Binary(this, this._subtype || 0); }; MongooseBuffer.mixin.toUUID = function() { if (this._subtype !== 4) { throw new Error("Cannot convert a Buffer with subtype " + this._subtype + " to a UUID"); } return new UUID(this); }; MongooseBuffer.mixin.equals = function(other) { if (!Buffer.isBuffer(other)) { return false; } if (this.length !== other.length) { return false; } for (let i = 0; i < this.length; ++i) { if (this[i] !== other[i]) { return false; } } return true; }; MongooseBuffer.mixin.subtype = function(subtype) { if (typeof subtype !== "number") { throw new TypeError("Invalid subtype. Expected a number"); } if (this._subtype !== subtype) { this._markModified(); } this._subtype = subtype; }; MongooseBuffer.Binary = Binary; module2.exports = MongooseBuffer; } }); // netlify/functions/node_modules/mongoose/lib/schema/symbols.js var require_symbols2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/symbols.js"(exports2) { "use strict"; exports2.schemaMixedSymbol = Symbol.for("mongoose:schema_mixed"); exports2.builtInMiddleware = Symbol.for("mongoose:built-in-middleware"); } }); // netlify/functions/node_modules/mongoose/lib/schema/mixed.js var require_mixed = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/mixed.js"(exports2, module2) { "use strict"; var SchemaType = require_schemaType(); var symbols = require_symbols2(); var isObject = require_isObject(); var utils = require_utils3(); function SchemaMixed(path, options) { if (options && options.default) { const def = options.default; if (Array.isArray(def) && def.length === 0) { options.default = Array; } else if (!options.shared && isObject(def) && Object.keys(def).length === 0) { options.default = function() { return {}; }; } } SchemaType.call(this, path, options, "Mixed"); this[symbols.schemaMixedSymbol] = true; } SchemaMixed.schemaName = "Mixed"; SchemaMixed.defaultOptions = {}; SchemaMixed.prototype = Object.create(SchemaType.prototype); SchemaMixed.prototype.constructor = SchemaMixed; SchemaMixed.get = SchemaType.get; SchemaMixed.set = SchemaType.set; SchemaMixed.setters = []; SchemaMixed.prototype.cast = function(val) { if (val instanceof Error) { return utils.errorToPOJO(val); } return val; }; SchemaMixed.prototype.castForQuery = function($cond, val) { return val; }; SchemaMixed.prototype.toJSONSchema = function toJSONSchema(_options) { return {}; }; module2.exports = SchemaMixed; } }); // netlify/functions/node_modules/mongoose/lib/modifiedPathsSnapshot.js var require_modifiedPathsSnapshot = __commonJS({ "netlify/functions/node_modules/mongoose/lib/modifiedPathsSnapshot.js"(exports2, module2) { "use strict"; module2.exports = class ModifiedPathsSnapshot { constructor(subdocSnapshot, activePaths, version) { this.subdocSnapshot = subdocSnapshot; this.activePaths = activePaths; this.version = version; } }; } }); // netlify/functions/node_modules/mongoose/lib/error/objectExpected.js var require_objectExpected = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/objectExpected.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var ObjectExpectedError = class extends MongooseError { constructor(path, val) { const typeDescription = Array.isArray(val) ? "array" : "primitive value"; super("Tried to set nested object field `" + path + `\` to ${typeDescription} \`` + val + "`"); this.path = path; } }; Object.defineProperty(ObjectExpectedError.prototype, "name", { value: "ObjectExpectedError" }); module2.exports = ObjectExpectedError; } }); // netlify/functions/node_modules/mongoose/lib/error/objectParameter.js var require_objectParameter = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/objectParameter.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var ObjectParameterError = class extends MongooseError { constructor(value, paramName, fnName) { super('Parameter "' + paramName + '" to ' + fnName + '() must be an object, got "' + value.toString() + '" (type ' + typeof value + ")"); } }; Object.defineProperty(ObjectParameterError.prototype, "name", { value: "ObjectParameterError" }); module2.exports = ObjectParameterError; } }); // netlify/functions/node_modules/mongoose/lib/error/parallelValidate.js var require_parallelValidate = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/parallelValidate.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var ParallelValidateError = class extends MongooseError { constructor(doc) { const msg = "Can't validate() the same doc multiple times in parallel. Document: "; super(msg + doc._doc._id); } }; Object.defineProperty(ParallelValidateError.prototype, "name", { value: "ParallelValidateError" }); module2.exports = ParallelValidateError; } }); // netlify/functions/node_modules/mongoose/lib/helpers/projection/hasIncludedChildren.js var require_hasIncludedChildren = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/projection/hasIncludedChildren.js"(exports2, module2) { "use strict"; module2.exports = function hasIncludedChildren(fields) { const hasIncludedChildren2 = {}; const keys = Object.keys(fields); for (const key of keys) { if (key.indexOf(".") === -1) { hasIncludedChildren2[key] = 1; continue; } const parts = key.split("."); let c = parts[0]; for (let i = 0; i < parts.length; ++i) { hasIncludedChildren2[c] = 1; if (i + 1 < parts.length) { c = c + "." + parts[i + 1]; } } } return hasIncludedChildren2; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/projection/isNestedProjection.js var require_isNestedProjection = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/projection/isNestedProjection.js"(exports2, module2) { "use strict"; module2.exports = function isNestedProjection(val) { if (val == null || typeof val !== "object") { return false; } return val.$slice == null && val.$elemMatch == null && val.$meta == null && val.$ == null; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/document/applyDefaults.js var require_applyDefaults = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/document/applyDefaults.js"(exports2, module2) { "use strict"; var isNestedProjection = require_isNestedProjection(); module2.exports = function applyDefaults(doc, fields, exclude, hasIncludedChildren, isBeforeSetters, pathsToSkip, options) { const paths = Object.keys(doc.$__schema.paths); const plen = paths.length; const skipParentChangeTracking = options && options.skipParentChangeTracking; for (let i = 0; i < plen; ++i) { let def; let curPath = ""; const p = paths[i]; if (p === "_id" && doc.$__.skipId) { continue; } const type = doc.$__schema.paths[p]; const path = type.splitPath(); const len = path.length; if (path[len - 1] === "$*") { continue; } let included = false; let doc_ = doc._doc; for (let j = 0; j < len; ++j) { if (doc_ == null) { break; } const piece = path[j]; curPath += (!curPath.length ? "" : ".") + piece; if (exclude === true) { if (curPath in fields) { break; } } else if (exclude === false && fields && !included) { const hasSubpaths = type.$isSingleNested || type.$isMongooseDocumentArray; if (curPath in fields && !isNestedProjection(fields[curPath]) || j === len - 1 && hasSubpaths && hasIncludedChildren != null && hasIncludedChildren[curPath]) { included = true; } else if (hasIncludedChildren != null && !hasIncludedChildren[curPath]) { break; } } if (j === len - 1) { if (doc_[piece] !== void 0) { break; } if (isBeforeSetters != null) { if (typeof type.defaultValue === "function") { if (!type.defaultValue.$runBeforeSetters && isBeforeSetters) { break; } if (type.defaultValue.$runBeforeSetters && !isBeforeSetters) { break; } } else if (!isBeforeSetters) { continue; } } if (pathsToSkip && pathsToSkip[curPath]) { break; } if (fields && exclude !== null) { if (exclude === true) { if (p in fields) { continue; } try { def = type.getDefault(doc, false); } catch (err) { doc.invalidate(p, err); break; } if (typeof def !== "undefined") { doc_[piece] = def; applyChangeTracking(doc, p, skipParentChangeTracking); } } else if (included) { try { def = type.getDefault(doc, false); } catch (err) { doc.invalidate(p, err); break; } if (typeof def !== "undefined") { doc_[piece] = def; applyChangeTracking(doc, p, skipParentChangeTracking); } } } else { try { def = type.getDefault(doc, false); } catch (err) { doc.invalidate(p, err); break; } if (typeof def !== "undefined") { doc_[piece] = def; applyChangeTracking(doc, p, skipParentChangeTracking); } } } else { doc_ = doc_[piece]; } } } }; function applyChangeTracking(doc, fullPath, skipParentChangeTracking) { doc.$__.activePaths.default(fullPath); if (!skipParentChangeTracking && doc.$isSubdocument && doc.$isSingleNested && doc.$parent() != null) { doc.$parent().$__.activePaths.default(doc.$__pathRelativeToParent(fullPath)); } } } }); // netlify/functions/node_modules/mongoose/lib/helpers/document/cleanModifiedSubpaths.js var require_cleanModifiedSubpaths = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/document/cleanModifiedSubpaths.js"(exports2, module2) { "use strict"; module2.exports = function cleanModifiedSubpaths(doc, path, options) { options = options || {}; const skipDocArrays = options.skipDocArrays; let deleted = 0; if (!doc) { return deleted; } for (const modifiedPath of Object.keys(doc.$__.activePaths.getStatePaths("modify"))) { if (skipDocArrays) { const schemaType = doc.$__schema.path(modifiedPath); if (schemaType && schemaType.$isMongooseDocumentArray) { continue; } } if (modifiedPath.startsWith(path + ".")) { doc.$__.activePaths.clearPath(modifiedPath); ++deleted; if (doc.$isSubdocument) { cleanParent(doc, modifiedPath); } } } return deleted; }; function cleanParent(doc, path, seen = /* @__PURE__ */ new Set()) { if (seen.has(doc)) { throw new Error("Infinite subdocument loop: subdoc with _id " + doc._id + " is a parent of itself"); } const parent = doc.$parent(); const newPath = doc.$__pathRelativeToParent(void 0, false) + "." + path; parent.$__.activePaths.clearPath(newPath); if (parent.$isSubdocument) { cleanParent(parent, newPath, seen); } } } }); // netlify/functions/node_modules/mongoose/lib/helpers/document/compile.js var require_compile = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/document/compile.js"(exports2) { "use strict"; var clone = require_clone(); var documentSchemaSymbol = require_symbols().documentSchemaSymbol; var internalToObjectOptions = require_options().internalToObjectOptions; var utils = require_utils3(); var Document; var getSymbol = require_symbols().getSymbol; var scopeSymbol = require_symbols().scopeSymbol; var isPOJO = utils.isPOJO; exports2.compile = compile; exports2.defineKey = defineKey; var _isEmptyOptions = Object.freeze({ minimize: true, virtuals: false, getters: false, transform: false }); var noDottedPathGetOptions = Object.freeze({ noDottedPath: true }); function compile(tree, proto, prefix, options) { Document = Document || require_document2(); const typeKey = options.typeKey; for (const key of Object.keys(tree)) { const limb = tree[key]; const hasSubprops = isPOJO(limb) && Object.keys(limb).length > 0 && (!limb[typeKey] || typeKey === "type" && isPOJO(limb.type) && limb.type.type); const subprops = hasSubprops ? limb : null; defineKey({ prop: key, subprops, prototype: proto, prefix, options }); } } function defineKey({ prop, subprops, prototype, prefix, options }) { Document = Document || require_document2(); const path = (prefix ? prefix + "." : "") + prop; prefix = prefix || ""; const useGetOptions = prefix ? Object.freeze({}) : noDottedPathGetOptions; if (subprops) { Object.defineProperty(prototype, prop, { enumerable: true, configurable: true, get: function() { const _this = this; if (!this.$__.getters) { this.$__.getters = {}; } if (!this.$__.getters[path]) { const nested = Object.create(Document.prototype, getOwnPropertyDescriptors(this)); if (!prefix) { nested.$__[scopeSymbol] = this; } nested.$__.nestedPath = path; Object.defineProperty(nested, "schema", { enumerable: false, configurable: true, writable: false, value: prototype.schema }); Object.defineProperty(nested, "$__schema", { enumerable: false, configurable: true, writable: false, value: prototype.schema }); Object.defineProperty(nested, documentSchemaSymbol, { enumerable: false, configurable: true, writable: false, value: prototype.schema }); Object.defineProperty(nested, "toObject", { enumerable: false, configurable: true, writable: false, value: function() { return clone(_this.get(path, null, { virtuals: this && this.schema && this.schema.options && this.schema.options.toObject && this.schema.options.toObject.virtuals || null })); } }); Object.defineProperty(nested, "$__get", { enumerable: false, configurable: true, writable: false, value: function() { return _this.get(path, null, { virtuals: this && this.schema && this.schema.options && this.schema.options.toObject && this.schema.options.toObject.virtuals || null }); } }); Object.defineProperty(nested, "toJSON", { enumerable: false, configurable: true, writable: false, value: function() { return _this.get(path, null, { virtuals: this && this.schema && this.schema.options && this.schema.options.toJSON && this.schema.options.toJSON.virtuals || null }); } }); Object.defineProperty(nested, "$__isNested", { enumerable: false, configurable: true, writable: false, value: true }); Object.defineProperty(nested, "$isEmpty", { enumerable: false, configurable: true, writable: false, value: function() { return Object.keys(this.get(path, null, _isEmptyOptions) || {}).length === 0; } }); Object.defineProperty(nested, "$__parent", { enumerable: false, configurable: true, writable: false, value: this }); compile(subprops, nested, path, options); this.$__.getters[path] = nested; } return this.$__.getters[path]; }, set: function(v) { if (v != null && v.$__isNested) { v = v.$__get(); } else if (v instanceof Document && !v.$__isNested) { v = v.$toObject(internalToObjectOptions); } const doc = this.$__[scopeSymbol] || this; doc.$set(path, v); } }); } else { Object.defineProperty(prototype, prop, { enumerable: true, configurable: true, get: function() { return this[getSymbol].call( this.$__[scopeSymbol] || this, path, null, useGetOptions ); }, set: function(v) { this.$set.call(this.$__[scopeSymbol] || this, path, v); } }); } } function getOwnPropertyDescriptors(object) { const result = {}; Object.getOwnPropertyNames(object).forEach(function(key) { const skip = [ "isNew", "$__", "$errors", "errors", "_doc", "$locals", "$op", "__parentArray", "__index", "$isDocumentArrayElement" ].indexOf(key) === -1; if (skip) { return; } result[key] = Object.getOwnPropertyDescriptor(object, key); result[key].enumerable = false; }); return result; } } }); // netlify/functions/node_modules/mongoose/lib/helpers/firstKey.js var require_firstKey = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/firstKey.js"(exports2, module2) { "use strict"; module2.exports = function firstKey(obj) { if (obj == null) { return null; } return Object.keys(obj)[0]; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/common.js var require_common3 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/common.js"(exports2) { "use strict"; var Binary = require_bson().Binary; var isBsonType = require_isBsonType(); var isMongooseObject = require_isMongooseObject(); var MongooseError = require_error2(); var util = require("util"); exports2.flatten = flatten; exports2.modifiedPaths = modifiedPaths; function flatten(update, path, options, schema) { let keys; if (update && isMongooseObject(update) && !Buffer.isBuffer(update)) { keys = Object.keys(update.toObject({ transform: false, virtuals: false }) || {}); } else { keys = Object.keys(update || {}); } const numKeys = keys.length; const result = {}; path = path ? path + "." : ""; for (let i = 0; i < numKeys; ++i) { const key = keys[i]; const val = update[key]; result[path + key] = val; const keySchema = schema && schema.path && schema.path(path + key); const isNested = schema && schema.nested && schema.nested[path + key]; if (keySchema && keySchema.instance === "Mixed") continue; if (shouldFlatten(val)) { if (options && options.skipArrays && Array.isArray(val)) { continue; } const flat = flatten(val, path + key, options, schema); for (const k in flat) { result[k] = flat[k]; } if (Array.isArray(val)) { result[path + key] = val; } } if (isNested) { const paths = Object.keys(schema.paths); for (const p of paths) { if (p.startsWith(path + key + ".") && !result.hasOwnProperty(p)) { result[p] = void 0; } } } } return result; } function modifiedPaths(update, path, result, recursion = null) { if (update == null || typeof update !== "object") { return; } if (recursion == null) { recursion = { raw: { update, path }, trace: /* @__PURE__ */ new WeakSet() }; } if (recursion.trace.has(update)) { throw new MongooseError(`a circular reference in the update value, updateValue: ${util.inspect(recursion.raw.update, { showHidden: false, depth: 1 })} updatePath: '${recursion.raw.path}'`); } recursion.trace.add(update); const keys = Object.keys(update || {}); const numKeys = keys.length; result = result || {}; path = path ? path + "." : ""; for (let i = 0; i < numKeys; ++i) { const key = keys[i]; let val = update[key]; const _path = path + key; result[_path] = true; if (!Buffer.isBuffer(val) && isMongooseObject(val)) { val = val.toObject({ transform: false, virtuals: false }); } if (shouldFlatten(val)) { modifiedPaths(val, path + key, result, recursion); } } recursion.trace.delete(update); return result; } function shouldFlatten(val) { return val && typeof val === "object" && !(val instanceof Date) && !isBsonType(val, "ObjectId") && (!Array.isArray(val) || val.length !== 0) && !(val instanceof Buffer) && !isBsonType(val, "Decimal128") && !(val instanceof Binary); } } }); // netlify/functions/node_modules/mongoose/lib/helpers/get.js var require_get = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/get.js"(exports2, module2) { "use strict"; module2.exports = function get(obj, path, def) { let parts; let isPathArray = false; if (typeof path === "string") { if (path.indexOf(".") === -1) { const _v = getProperty(obj, path); if (_v == null) { return def; } return _v; } parts = path.split("."); } else { isPathArray = true; parts = path; if (parts.length === 1) { const _v = getProperty(obj, parts[0]); if (_v == null) { return def; } return _v; } } let rest = path; let cur = obj; for (const part of parts) { if (cur == null) { return def; } if (!isPathArray && cur[rest] != null) { return cur[rest]; } cur = getProperty(cur, part); if (!isPathArray) { rest = rest.substr(part.length + 1); } } return cur == null ? def : cur; }; function getProperty(obj, prop) { if (obj == null) { return obj; } if (obj instanceof Map) { return obj.get(prop); } return obj[prop]; } } }); // netlify/functions/node_modules/mongoose/lib/helpers/discriminator/areDiscriminatorValuesEqual.js var require_areDiscriminatorValuesEqual = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/discriminator/areDiscriminatorValuesEqual.js"(exports2, module2) { "use strict"; var isBsonType = require_isBsonType(); module2.exports = function areDiscriminatorValuesEqual(a, b) { if (typeof a === "string" && typeof b === "string") { return a === b; } if (typeof a === "number" && typeof b === "number") { return a === b; } if (isBsonType(a, "ObjectId") && isBsonType(b, "ObjectId")) { return a.toString() === b.toString(); } return false; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/discriminator/getSchemaDiscriminatorByValue.js var require_getSchemaDiscriminatorByValue = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/discriminator/getSchemaDiscriminatorByValue.js"(exports2, module2) { "use strict"; var areDiscriminatorValuesEqual = require_areDiscriminatorValuesEqual(); module2.exports = function getSchemaDiscriminatorByValue(schema, value) { if (schema == null || schema.discriminators == null) { return null; } for (const key of Object.keys(schema.discriminators)) { const discriminatorSchema = schema.discriminators[key]; if (discriminatorSchema.discriminatorMapping == null) { continue; } if (areDiscriminatorValuesEqual(discriminatorSchema.discriminatorMapping.value, value)) { return discriminatorSchema; } } return null; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/document/getEmbeddedDiscriminatorPath.js var require_getEmbeddedDiscriminatorPath = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/document/getEmbeddedDiscriminatorPath.js"(exports2, module2) { "use strict"; var get = require_get(); var getSchemaDiscriminatorByValue = require_getSchemaDiscriminatorByValue(); module2.exports = function getEmbeddedDiscriminatorPath(doc, path, options) { options = options || {}; const typeOnly = options.typeOnly; const parts = Array.isArray(path) ? path : path.indexOf(".") === -1 ? [path] : path.split("."); let schemaType = null; let type = "adhocOrUndefined"; const schema = getSchemaDiscriminatorByValue(doc.schema, doc.get(doc.schema.options.discriminatorKey)) || doc.schema; for (let i = 0; i < parts.length; ++i) { const subpath = parts.slice(0, i + 1).join("."); schemaType = schema.path(subpath); if (schemaType == null) { type = "adhocOrUndefined"; continue; } if (schemaType.instance === "Mixed") { return typeOnly ? "real" : schemaType; } type = schema.pathType(subpath); if ((schemaType.$isSingleNested || schemaType.$isMongooseDocumentArrayElement) && schemaType.schema.discriminators != null) { const discriminators = schemaType.schema.discriminators; const discriminatorKey = doc.get(subpath + "." + get(schemaType, "schema.options.discriminatorKey")); if (discriminatorKey == null || discriminators[discriminatorKey] == null) { continue; } const rest = parts.slice(i + 1).join("."); return getEmbeddedDiscriminatorPath(doc.get(subpath), rest, options); } } return typeOnly ? type : schemaType; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/schema/getKeysInSchemaOrder.js var require_getKeysInSchemaOrder = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/schema/getKeysInSchemaOrder.js"(exports2, module2) { "use strict"; var get = require_get(); module2.exports = function getKeysInSchemaOrder(schema, val, path) { const schemaKeys = path != null ? Object.keys(get(schema.tree, path, {})) : Object.keys(schema.tree); const valKeys = new Set(Object.keys(val)); let keys; if (valKeys.size > 1) { keys = /* @__PURE__ */ new Set(); for (const key of schemaKeys) { if (valKeys.has(key)) { keys.add(key); } } for (const key of valKeys) { if (!keys.has(key)) { keys.add(key); } } keys = Array.from(keys); } else { keys = Array.from(valKeys); } return keys; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/schema/getSubdocumentStrictValue.js var require_getSubdocumentStrictValue = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/schema/getSubdocumentStrictValue.js"(exports2, module2) { "use strict"; module2.exports = function getSubdocumentStrictValue(schema, parts) { if (parts.length === 1) { return void 0; } let cur = parts[0]; let strict = void 0; for (let i = 0; i < parts.length - 1; ++i) { const curSchemaType = schema.path(cur); if (curSchemaType && curSchemaType.schema) { strict = curSchemaType.schema.options.strict; schema = curSchemaType.schema; cur = curSchemaType.$isMongooseDocumentArray && !isNaN(parts[i + 1]) ? "" : parts[i + 1]; } else { cur += cur.length ? "." + parts[i + 1] : parts[i + 1]; } } return strict; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/document/handleSpreadDoc.js var require_handleSpreadDoc = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/document/handleSpreadDoc.js"(exports2, module2) { "use strict"; var utils = require_utils3(); var keysToSkip = /* @__PURE__ */ new Set(["__index", "__parentArray", "_doc"]); module2.exports = function handleSpreadDoc(v, includeExtraKeys) { if (utils.isPOJO(v) && v.$__ != null && v._doc != null) { if (includeExtraKeys) { const extraKeys = {}; for (const key of Object.keys(v)) { if (typeof key === "symbol") { continue; } if (key[0] === "$") { continue; } if (keysToSkip.has(key)) { continue; } extraKeys[key] = v[key]; } return { ...v._doc, ...extraKeys }; } return v._doc; } return v; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/projection/isDefiningProjection.js var require_isDefiningProjection = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/projection/isDefiningProjection.js"(exports2, module2) { "use strict"; module2.exports = function isDefiningProjection(val) { if (val == null) { return true; } if (typeof val === "object") { return !("$meta" in val) && !("$slice" in val); } return true; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/projection/isExclusive.js var require_isExclusive = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/projection/isExclusive.js"(exports2, module2) { "use strict"; var isDefiningProjection = require_isDefiningProjection(); var isPOJO = require_isPOJO(); module2.exports = function isExclusive(projection) { if (projection == null) { return null; } const keys = Object.keys(projection); let exclude = null; if (keys.length === 1 && keys[0] === "_id") { exclude = !projection._id; } else { for (let ki = 0; ki < keys.length; ++ki) { const key = keys[ki]; if (key !== "_id" && isDefiningProjection(projection[key])) { exclude = isPOJO(projection[key]) ? isExclusive(projection[key]) ?? exclude : !projection[key]; if (exclude != null) { break; } } } } return exclude; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/projection/isPathExcluded.js var require_isPathExcluded = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/projection/isPathExcluded.js"(exports2, module2) { "use strict"; var isDefiningProjection = require_isDefiningProjection(); module2.exports = function isPathExcluded(projection, path) { if (projection == null) { return false; } if (path === "_id") { return projection._id === 0; } const paths = Object.keys(projection); let type = null; for (const _path of paths) { if (isDefiningProjection(projection[_path])) { type = projection[path] === 1 ? "inclusive" : "exclusive"; break; } } if (type === "inclusive") { return projection[path] !== 1; } if (type === "exclusive") { return projection[path] === 0; } return false; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/populate/markArraySubdocsPopulated.js var require_markArraySubdocsPopulated = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/populate/markArraySubdocsPopulated.js"(exports2, module2) { "use strict"; var utils = require_utils3(); module2.exports = function markArraySubdocsPopulated(doc, populated) { if (doc._doc._id == null || populated == null || populated.length === 0) { return; } const id = String(doc._doc._id); for (const item of populated) { if (item.isVirtual) { continue; } const path = item.path; const pieces = path.split("."); for (let i = 0; i < pieces.length - 1; ++i) { const subpath = pieces.slice(0, i + 1).join("."); const rest = pieces.slice(i + 1).join("."); const val = doc.get(subpath); if (val == null) { continue; } if (utils.isMongooseDocumentArray(val)) { for (let j = 0; j < val.length; ++j) { if (val[j]) { val[j].populated(rest, item._docs[id] == null ? void 0 : item._docs[id][j], item); } } break; } } } }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/minimize.js var require_minimize = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/minimize.js"(exports2, module2) { "use strict"; var { isPOJO } = require_utils3(); module2.exports = minimize; function minimize(obj) { const keys = Object.keys(obj); let i = keys.length; let hasKeys; let key; let val; while (i--) { key = keys[i]; val = obj[key]; if (isPOJO(val)) { obj[key] = minimize(val); } if (void 0 === obj[key]) { delete obj[key]; continue; } hasKeys = true; } return hasKeys ? obj : void 0; } } }); // netlify/functions/node_modules/mongoose/lib/helpers/path/parentPaths.js var require_parentPaths = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/path/parentPaths.js"(exports2, module2) { "use strict"; var dotRE = /\./g; module2.exports = function parentPaths(path) { if (path.indexOf(".") === -1) { return [path]; } const pieces = path.split(dotRE); const len = pieces.length; const ret = new Array(len); let cur = ""; for (let i = 0; i < len; ++i) { cur += cur.length !== 0 ? "." + pieces[i] : pieces[i]; ret[i] = cur; } return ret; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection.js var require_checkEmbeddedDiscriminatorKeyProjection = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection.js"(exports2, module2) { "use strict"; module2.exports = function checkEmbeddedDiscriminatorKeyProjection(userProjection, path, schema, selected, addedPaths) { const userProjectedInPath = Object.keys(userProjection).reduce((cur, key) => cur || key.startsWith(path + "."), false); const _discriminatorKey = path + "." + schema.options.discriminatorKey; if (!userProjectedInPath && addedPaths.length === 1 && addedPaths[0] === _discriminatorKey) { selected.splice(selected.indexOf(_discriminatorKey), 1); } }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/discriminator/getDiscriminatorByValue.js var require_getDiscriminatorByValue = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/discriminator/getDiscriminatorByValue.js"(exports2, module2) { "use strict"; var areDiscriminatorValuesEqual = require_areDiscriminatorValuesEqual(); module2.exports = function getDiscriminatorByValue(discriminators, value) { if (discriminators == null) { return null; } for (const name of Object.keys(discriminators)) { const it = discriminators[name]; if (it.schema && it.schema.discriminatorMapping && areDiscriminatorValuesEqual(it.schema.discriminatorMapping.value, value)) { return it; } } return null; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/projection/isPathSelectedInclusive.js var require_isPathSelectedInclusive = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/projection/isPathSelectedInclusive.js"(exports2, module2) { "use strict"; module2.exports = function isPathSelectedInclusive(fields, path) { const chunks = path.split("."); let cur = ""; let j; let keys; let numKeys; for (let i = 0; i < chunks.length; ++i) { cur += cur.length ? "." : "" + chunks[i]; if (fields[cur]) { keys = Object.keys(fields); numKeys = keys.length; for (j = 0; j < numKeys; ++j) { if (keys[i].indexOf(cur + ".") === 0 && keys[i].indexOf(path) !== 0) { continue; } } return true; } } return false; }; } }); // netlify/functions/node_modules/mongoose/lib/queryHelpers.js var require_queryHelpers = __commonJS({ "netlify/functions/node_modules/mongoose/lib/queryHelpers.js"(exports2) { "use strict"; var PopulateOptions = require_populateOptions(); var checkEmbeddedDiscriminatorKeyProjection = require_checkEmbeddedDiscriminatorKeyProjection(); var get = require_get(); var getDiscriminatorByValue = require_getDiscriminatorByValue(); var isDefiningProjection = require_isDefiningProjection(); var clone = require_clone(); var isPathSelectedInclusive = require_isPathSelectedInclusive(); exports2.preparePopulationOptionsMQ = function preparePopulationOptionsMQ(query, options) { const _populate = query._mongooseOptions.populate; const pop = Object.keys(_populate).reduce((vals, key) => vals.concat([_populate[key]]), []); if (options.lean != null) { pop.filter((p) => (p && p.options && p.options.lean) == null).forEach(makeLean(options.lean)); } const session = query && query.options && query.options.session || null; if (session != null) { pop.forEach((path) => { if (path.options == null) { path.options = { session }; return; } if (!("session" in path.options)) { path.options.session = session; } }); } const projection = query._fieldsForExec(); for (let i = 0; i < pop.length; ++i) { if (pop[i] instanceof PopulateOptions) { pop[i] = new PopulateOptions({ ...pop[i], _queryProjection: projection, _localModel: query.model }); } else { pop[i]._queryProjection = projection; pop[i]._localModel = query.model; } } return pop; }; exports2.createModel = function createModel(model, doc, fields, userProvidedFields, options) { model.hooks.execPreSync("createModel", doc); const discriminatorMapping = model.schema ? model.schema.discriminatorMapping : null; const key = discriminatorMapping && discriminatorMapping.isRoot ? discriminatorMapping.key : null; const value = doc[key]; if (key && value && model.discriminators) { const discriminator = model.discriminators[value] || getDiscriminatorByValue(model.discriminators, value); if (discriminator) { const _fields = clone(userProvidedFields); exports2.applyPaths(_fields, discriminator.schema); return new discriminator(void 0, _fields, true); } } const _opts = { skipId: true, isNew: false, willInit: true }; if (options != null && "defaults" in options) { _opts.defaults = options.defaults; } return new model(void 0, fields, _opts); }; exports2.createModelAndInit = function createModelAndInit(model, doc, fields, userProvidedFields, options, populatedIds, callback) { const initOpts = populatedIds ? { populated: populatedIds } : void 0; const casted = exports2.createModel(model, doc, fields, userProvidedFields, options); try { casted.$init(doc, initOpts, callback); } catch (error) { callback(error, casted); } }; exports2.applyPaths = function applyPaths(fields, schema, sanitizeProjection) { let exclude; let keys; const minusPathsToSkip = /* @__PURE__ */ new Set(); if (fields) { keys = Object.keys(fields); const minusPaths = []; for (let i = 0; i < keys.length; ++i) { const key = keys[i]; if (keys[i][0] !== "-") { continue; } delete fields[key]; if (key === "-_id") { fields["_id"] = 0; } else { minusPaths.push(key.slice(1)); } } keys = Object.keys(fields); for (let keyIndex = 0; keyIndex < keys.length; ++keyIndex) { if (keys[keyIndex][0] === "+") { continue; } const field = fields[keys[keyIndex]]; if (!isDefiningProjection(field)) { continue; } if (keys[keyIndex] === "_id" && keys.length > 1) { continue; } if (keys[keyIndex] === schema.options.discriminatorKey && keys.length > 1 && field != null && !field) { continue; } exclude = !field; break; } for (const path of minusPaths) { const type = schema.path(path); if (!type || !type.selected || exclude !== false) { fields[path] = 0; exclude = true; } else if (type && type.selected && exclude === false) { minusPathsToSkip.add(path); } } } const selected = []; const excluded = []; const stack = []; analyzeSchema(schema); switch (exclude) { case true: for (const fieldName of excluded) { fields[fieldName] = 0; } break; case false: if (schema && schema.paths["_id"] && schema.paths["_id"].options && schema.paths["_id"].options.select === false) { fields._id = 0; } for (const fieldName of selected) { if (minusPathsToSkip.has(fieldName)) { continue; } if (isPathSelectedInclusive(fields, fieldName)) { continue; } fields[fieldName] = fields[fieldName] || 1; } break; case void 0: if (fields == null) { break; } for (const key of Object.keys(fields || {})) { if (key.startsWith("+")) { delete fields[key]; } } for (const fieldName of excluded) { if (fields[fieldName] != null) { continue; } fields[fieldName] = 0; } break; } function analyzeSchema(schema2, prefix) { prefix || (prefix = ""); if (stack.indexOf(schema2) !== -1) { return []; } stack.push(schema2); const addedPaths = []; schema2.eachPath(function(path, type) { if (prefix) path = prefix + "." + path; if (type.$isSchemaMap || path.endsWith(".$*")) { const plusPath = "+" + path; const hasPlusPath = fields && plusPath in fields; if (type.options && type.options.select === false && !hasPlusPath) { excluded.push(path); } return; } let addedPath = analyzePath(path, type); if (addedPath == null && !Array.isArray(type) && type.$isMongooseArray && !type.$isMongooseDocumentArray) { addedPath = analyzePath(path, type.caster); } if (addedPath != null) { addedPaths.push(addedPath); } if (type.schema) { const _addedPaths = analyzeSchema(type.schema, path); if (exclude === false) { checkEmbeddedDiscriminatorKeyProjection( fields, path, type.schema, selected, _addedPaths ); } } }); stack.pop(); return addedPaths; } function analyzePath(path, type) { if (fields == null) { return; } if (typeof type.selected !== "boolean") { return; } if (type.selected === false && fields[path]) { if (sanitizeProjection) { fields[path] = 0; } return; } if (!exclude && type.selected && path === schema.options.discriminatorKey && fields[path] != null && !fields[path]) { delete fields[path]; return; } if (exclude === false && type.selected && fields[path] != null && !fields[path]) { delete fields[path]; return; } const plusPath = "+" + path; const hasPlusPath = fields && plusPath in fields; if (hasPlusPath) { delete fields[plusPath]; if (exclude === false && keys.length > 1 && !~keys.indexOf(path) && !sanitizeProjection) { fields[path] = 1; } else if (exclude == null && sanitizeProjection && type.selected === false) { fields[path] = 0; } return; } const pieces = path.split("."); let cur = ""; for (let i = 0; i < pieces.length; ++i) { cur += cur.length ? "." + pieces[i] : pieces[i]; if (excluded.indexOf(cur) !== -1) { return; } } if (!exclude && (type && type.options && type.options.$skipDiscriminatorCheck || false)) { let cur2 = ""; for (let i = 0; i < pieces.length; ++i) { cur2 += (cur2.length === 0 ? "" : ".") + pieces[i]; const projection = get(fields, cur2, false) || get(fields, cur2 + ".$", false); if (projection && typeof projection !== "object") { return; } } } (type.selected ? selected : excluded).push(path); return path; } }; function makeLean(val) { return function(option) { option.options || (option.options = {}); if (val != null && Array.isArray(val.virtuals)) { val = Object.assign({}, val); val.virtuals = val.virtuals.filter((path) => typeof path === "string" && path.startsWith(option.path + ".")).map((path) => path.slice(option.path.length + 1)); } option.options.lean = val; }; } } }); // netlify/functions/node_modules/mongoose/lib/helpers/isPromise.js var require_isPromise = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/isPromise.js"(exports2, module2) { "use strict"; function isPromise(val) { return !!val && (typeof val === "object" || typeof val === "function") && typeof val.then === "function"; } module2.exports = isPromise; } }); // netlify/functions/node_modules/mongoose/lib/helpers/document/getDeepestSubdocumentForPath.js var require_getDeepestSubdocumentForPath = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/document/getDeepestSubdocumentForPath.js"(exports2, module2) { "use strict"; module2.exports = function getDeepestSubdocumentForPath(doc, parts, schema) { let curPath = parts[0]; let curSchema = schema; let subdoc = doc; for (let i = 0; i < parts.length - 1; ++i) { const curSchemaType = curSchema.path(curPath); if (curSchemaType && curSchemaType.schema) { let newSubdoc = subdoc.get(curPath); curSchema = curSchemaType.schema; curPath = parts[i + 1]; if (Array.isArray(newSubdoc) && !isNaN(curPath)) { newSubdoc = newSubdoc[curPath]; curPath = ""; } if (newSubdoc == null) { break; } subdoc = newSubdoc; } else { curPath += curPath.length ? "." + parts[i + 1] : parts[i + 1]; } } return subdoc; }; } }); // netlify/functions/node_modules/mongoose/lib/types/subdocument.js var require_subdocument = __commonJS({ "netlify/functions/node_modules/mongoose/lib/types/subdocument.js"(exports2, module2) { "use strict"; var Document = require_document2(); var immediate = require_immediate(); var internalToObjectOptions = require_options().internalToObjectOptions; var util = require("util"); var utils = require_utils3(); module2.exports = Subdocument; function Subdocument(value, fields, parent, skipId, options) { if (typeof skipId === "object" && skipId != null && options == null) { options = skipId; skipId = void 0; } if (parent != null) { const parentOptions = { isNew: parent.isNew }; if ("defaults" in parent.$__) { parentOptions.defaults = parent.$__.defaults; } options = Object.assign(parentOptions, options); } if (options != null && options.path != null) { this.$basePath = options.path; } Document.call(this, value, fields, skipId, options); delete this.$__.priorDoc; } Subdocument.prototype = Object.create(Document.prototype); Object.defineProperty(Subdocument.prototype, "$isSubdocument", { configurable: false, writable: false, value: true }); Object.defineProperty(Subdocument.prototype, "$isSingleNested", { configurable: false, writable: false, value: true }); Subdocument.prototype.toBSON = function() { return this.toObject(internalToObjectOptions); }; Subdocument.prototype.save = async function save(options) { options = options || {}; if (!options.suppressWarning) { utils.warn("mongoose: calling `save()` on a subdoc does **not** save the document to MongoDB, it only runs save middleware. Use `subdoc.save({ suppressWarning: true })` to hide this warning if you're sure this behavior is right for your app."); } return new Promise((resolve, reject) => { this.$__save((err) => { if (err != null) { return reject(err); } resolve(this); }); }); }; Subdocument.prototype.$__fullPath = function(path) { if (!this.$__.fullPath) { this.ownerDocument(); } return path ? this.$__.fullPath + "." + path : this.$__.fullPath; }; Subdocument.prototype.$__pathRelativeToParent = function(p) { if (p == null) { return this.$basePath; } return [this.$basePath, p].join("."); }; Subdocument.prototype.$__save = function(fn) { return immediate(() => fn(null, this)); }; Subdocument.prototype.$isValid = function(path) { const parent = this.$parent(); const fullPath = this.$__pathRelativeToParent(path); if (parent != null && fullPath != null) { return parent.$isValid(fullPath); } return Document.prototype.$isValid.call(this, path); }; Subdocument.prototype.markModified = function(path) { Document.prototype.markModified.call(this, path); const parent = this.$parent(); const fullPath = this.$__pathRelativeToParent(path); if (parent == null || fullPath == null) { return; } const myPath = this.$__pathRelativeToParent().replace(/\.$/, ""); if (parent.isDirectModified(myPath) || this.isNew) { return; } this.$__parent.markModified(fullPath, this); }; Subdocument.prototype.isModified = function(paths, options, modifiedPaths) { const parent = this.$parent(); if (parent != null) { if (Array.isArray(paths) || typeof paths === "string") { paths = Array.isArray(paths) ? paths : paths.split(" "); paths = paths.map((p) => this.$__pathRelativeToParent(p)).filter((p) => p != null); } else if (!paths) { paths = this.$__pathRelativeToParent(); } return parent.$isModified(paths, options, modifiedPaths); } return Document.prototype.isModified.call(this, paths, options, modifiedPaths); }; Subdocument.prototype.$markValid = function(path) { Document.prototype.$markValid.call(this, path); const parent = this.$parent(); const fullPath = this.$__pathRelativeToParent(path); if (parent != null && fullPath != null) { parent.$markValid(fullPath); } }; Subdocument.prototype.invalidate = function(path, err, val) { Document.prototype.invalidate.call(this, path, err, val); const parent = this.$parent(); const fullPath = this.$__pathRelativeToParent(path); if (parent != null && fullPath != null) { parent.invalidate(fullPath, err, val); } else if (err.kind === "cast" || err.name === "CastError" || fullPath == null) { throw err; } return this.ownerDocument().$__.validationError; }; Subdocument.prototype.$ignore = function(path) { Document.prototype.$ignore.call(this, path); const parent = this.$parent(); const fullPath = this.$__pathRelativeToParent(path); if (parent != null && fullPath != null) { parent.$ignore(fullPath); } }; Subdocument.prototype.ownerDocument = function() { if (this.$__.ownerDocument) { return this.$__.ownerDocument; } let parent = this; const paths = []; const seenDocs = /* @__PURE__ */ new Set([parent]); while (true) { if (typeof parent.$__pathRelativeToParent !== "function") { break; } paths.unshift(parent.$__pathRelativeToParent(void 0, true)); const _parent = parent.$parent(); if (_parent == null) { break; } parent = _parent; if (seenDocs.has(parent)) { throw new Error("Infinite subdocument loop: subdoc with _id " + parent._id + " is a parent of itself"); } seenDocs.add(parent); } this.$__.fullPath = paths.join("."); this.$__.ownerDocument = parent; return this.$__.ownerDocument; }; Subdocument.prototype.$__fullPathWithIndexes = function() { let parent = this; const paths = []; const seenDocs = /* @__PURE__ */ new Set([parent]); while (true) { if (typeof parent.$__pathRelativeToParent !== "function") { break; } paths.unshift(parent.$__pathRelativeToParent(void 0, false)); const _parent = parent.$parent(); if (_parent == null) { break; } parent = _parent; if (seenDocs.has(parent)) { throw new Error("Infinite subdocument loop: subdoc with _id " + parent._id + " is a parent of itself"); } seenDocs.add(parent); } return paths.join("."); }; Subdocument.prototype.parent = function() { return this.$__parent; }; Subdocument.prototype.$parent = Subdocument.prototype.parent; Subdocument.prototype.$__deleteOne = function(cb) { if (cb == null) { return; } return cb(null, this); }; Subdocument.prototype.$__removeFromParent = function() { this.$__parent.set(this.$basePath, null); }; Subdocument.prototype.deleteOne = function(options, callback) { if (typeof options === "function") { callback = options; options = null; } registerRemoveListener(this); if (!options || !options.noop) { this.$__removeFromParent(); const owner = this.ownerDocument(); owner.$__.removedSubdocs = owner.$__.removedSubdocs || []; owner.$__.removedSubdocs.push(this); } return this.$__deleteOne(callback); }; Subdocument.prototype.populate = function() { throw new Error('Mongoose does not support calling populate() on nested docs. Instead of `doc.nested.populate("path")`, use `doc.populate("nested.path")`'); }; Subdocument.prototype.inspect = function() { return this.toObject(); }; if (util.inspect.custom) { Subdocument.prototype[util.inspect.custom] = Subdocument.prototype.inspect; } Subdocument.prototype.$toObject = function $toObject(options, json) { const ret = Document.prototype.$toObject.call(this, options, json); if (Object.keys(ret).length === 0 && options?._calledWithOptions != null) { const minimize = options._calledWithOptions?.minimize ?? this?.$__schemaTypeOptions?.minimize ?? options.minimize; if (minimize && !this.constructor.$__required) { return void 0; } } return ret; }; function registerRemoveListener(sub) { const owner = sub.ownerDocument(); function emitRemove() { owner.$removeListener("save", emitRemove); owner.$removeListener("deleteOne", emitRemove); sub.emit("deleteOne", sub); sub.constructor.emit("deleteOne", sub); } owner.$on("save", emitRemove); owner.$on("deleteOne", emitRemove); } } }); // netlify/functions/node_modules/mongoose/lib/types/arraySubdocument.js var require_arraySubdocument = __commonJS({ "netlify/functions/node_modules/mongoose/lib/types/arraySubdocument.js"(exports2, module2) { "use strict"; var EventEmitter = require("events").EventEmitter; var Subdocument = require_subdocument(); var utils = require_utils3(); var documentArrayParent = require_symbols().documentArrayParent; function ArraySubdocument(obj, parentArr, skipId, fields, index) { if (utils.isMongooseDocumentArray(parentArr)) { this.__parentArray = parentArr; this[documentArrayParent] = parentArr.$parent(); } else { this.__parentArray = void 0; this[documentArrayParent] = void 0; } this.$setIndex(index); this.$__parent = this[documentArrayParent]; let options; if (typeof skipId === "object" && skipId != null) { options = { isNew: true, ...skipId }; skipId = void 0; } else { options = { isNew: true }; } Subdocument.call(this, obj, fields, this[documentArrayParent], skipId, options); } ArraySubdocument.prototype = Object.create(Subdocument.prototype); ArraySubdocument.prototype.constructor = ArraySubdocument; Object.defineProperty(ArraySubdocument.prototype, "$isSingleNested", { configurable: false, writable: false, value: false }); Object.defineProperty(ArraySubdocument.prototype, "$isDocumentArrayElement", { configurable: false, writable: false, value: true }); for (const i in EventEmitter.prototype) { ArraySubdocument[i] = EventEmitter.prototype[i]; } ArraySubdocument.prototype.$setIndex = function(index) { this.__index = index; if (this.$__ != null && this.$__.validationError != null) { const keys = Object.keys(this.$__.validationError.errors); for (const key of keys) { this.invalidate(key, this.$__.validationError.errors[key]); } } }; ArraySubdocument.prototype.populate = function() { throw new Error('Mongoose does not support calling populate() on nested docs. Instead of `doc.arr[0].populate("path")`, use `doc.populate("arr.0.path")`'); }; ArraySubdocument.prototype.$__removeFromParent = function() { const _id = this._doc._id; if (!_id) { throw new Error("For your own good, Mongoose does not know how to remove an ArraySubdocument that has no _id"); } this.__parentArray.pull({ _id }); }; ArraySubdocument.prototype.$__fullPath = function(path, skipIndex) { if (this.__index == null) { return null; } if (!this.$__.fullPath) { this.ownerDocument(); } if (skipIndex) { return path ? this.$__.fullPath + "." + path : this.$__.fullPath; } return path ? this.$__.fullPath + "." + this.__index + "." + path : this.$__.fullPath + "." + this.__index; }; ArraySubdocument.prototype.$__pathRelativeToParent = function(path, skipIndex) { if (this.__index == null || (!this.__parentArray || !this.__parentArray.$path)) { return null; } if (skipIndex) { return path == null ? this.__parentArray.$path() : this.__parentArray.$path() + "." + path; } if (path == null) { return this.__parentArray.$path() + "." + this.__index; } return this.__parentArray.$path() + "." + this.__index + "." + path; }; ArraySubdocument.prototype.$parent = function() { return this[documentArrayParent]; }; ArraySubdocument.prototype.parentArray = function() { return this.__parentArray; }; module2.exports = ArraySubdocument; } }); // netlify/functions/node_modules/mongoose/lib/types/array/methods/index.js var require_methods = __commonJS({ "netlify/functions/node_modules/mongoose/lib/types/array/methods/index.js"(exports2, module2) { "use strict"; var Document = require_document2(); var ArraySubdocument = require_arraySubdocument(); var MongooseError = require_mongooseError(); var cleanModifiedSubpaths = require_cleanModifiedSubpaths(); var clone = require_clone(); var internalToObjectOptions = require_options().internalToObjectOptions; var mpath = require_mpath(); var utils = require_utils3(); var isBsonType = require_isBsonType(); var arrayAtomicsSymbol = require_symbols().arrayAtomicsSymbol; var arrayParentSymbol = require_symbols().arrayParentSymbol; var arrayPathSymbol = require_symbols().arrayPathSymbol; var arraySchemaSymbol = require_symbols().arraySchemaSymbol; var populateModelSymbol = require_symbols().populateModelSymbol; var slicedSymbol = Symbol("mongoose#Array#sliced"); var _basePush = Array.prototype.push; var methods = { /** * Depopulates stored atomic operation values as necessary for direct insertion to MongoDB. * * If no atomics exist, we return all array values after conversion. * * @return {Array} * @method $__getAtomics * @memberOf MongooseArray * @instance * @api private */ $__getAtomics() { const ret = []; const keys = Object.keys(this[arrayAtomicsSymbol] || {}); let i = keys.length; const opts = Object.assign({}, internalToObjectOptions, { _isNested: true }); if (i === 0) { ret[0] = ["$set", this.toObject(opts)]; return ret; } while (i--) { const op = keys[i]; let val = this[arrayAtomicsSymbol][op]; if (utils.isMongooseObject(val)) { val = val.toObject(opts); } else if (Array.isArray(val)) { val = this.toObject.call(val, opts); } else if (val != null && Array.isArray(val.$each)) { val.$each = this.toObject.call(val.$each, opts); } else if (val != null && typeof val.valueOf === "function") { val = val.valueOf(); } if (op === "$addToSet") { val = { $each: val }; } ret.push([op, val]); } return ret; }, /*! * ignore */ $atomics() { return this[arrayAtomicsSymbol]; }, /*! * ignore */ $parent() { return this[arrayParentSymbol]; }, /*! * ignore */ $path() { return this[arrayPathSymbol]; }, /*! * ignore */ $schemaType() { return this[arraySchemaSymbol]; }, /** * Atomically shifts the array at most one time per document `save()`. * * #### Note: * * _Calling this multiple times on an array before saving sends the same command as calling it once._ * _This update is implemented using the MongoDB [$pop](https://www.mongodb.com/docs/manual/reference/operator/update/pop/) method which enforces this restriction._ * * doc.array = [1,2,3]; * * const shifted = doc.array.$shift(); * console.log(shifted); // 1 * console.log(doc.array); // [2,3] * * // no affect * shifted = doc.array.$shift(); * console.log(doc.array); // [2,3] * * doc.save(function (err) { * if (err) return handleError(err); * * // we saved, now $shift works again * shifted = doc.array.$shift(); * console.log(shifted ); // 2 * console.log(doc.array); // [3] * }) * * @api public * @memberOf MongooseArray * @instance * @method $shift * @see mongodb https://www.mongodb.com/docs/manual/reference/operator/update/pop/ */ $shift() { this._registerAtomic("$pop", -1); this._markModified(); const __array = this.__array; if (__array._shifted) { return; } __array._shifted = true; return [].shift.call(__array); }, /** * Pops the array atomically at most one time per document `save()`. * * #### NOTE: * * _Calling this multiple times on an array before saving sends the same command as calling it once._ * _This update is implemented using the MongoDB [$pop](https://www.mongodb.com/docs/manual/reference/operator/update/pop/) method which enforces this restriction._ * * doc.array = [1,2,3]; * * const popped = doc.array.$pop(); * console.log(popped); // 3 * console.log(doc.array); // [1,2] * * // no affect * popped = doc.array.$pop(); * console.log(doc.array); // [1,2] * * doc.save(function (err) { * if (err) return handleError(err); * * // we saved, now $pop works again * popped = doc.array.$pop(); * console.log(popped); // 2 * console.log(doc.array); // [1] * }) * * @api public * @method $pop * @memberOf MongooseArray * @instance * @see mongodb https://www.mongodb.com/docs/manual/reference/operator/update/pop/ * @method $pop * @memberOf MongooseArray */ $pop() { this._registerAtomic("$pop", 1); this._markModified(); if (this._popped) { return; } this._popped = true; return [].pop.call(this); }, /*! * ignore */ $schema() { return this[arraySchemaSymbol]; }, /** * Casts a member based on this arrays schema. * * @param {any} value * @return value the casted value * @method _cast * @api private * @memberOf MongooseArray */ _cast(value) { let populated = false; let Model; const parent = this[arrayParentSymbol]; if (parent) { populated = parent.$populated(this[arrayPathSymbol], true); } if (populated && value !== null && value !== void 0) { Model = populated.options[populateModelSymbol]; if (Model == null) { throw new MongooseError("No populated model found for path `" + this[arrayPathSymbol] + "`. This is likely a bug in Mongoose, please report an issue on github.com/Automattic/mongoose."); } if (Buffer.isBuffer(value) || isBsonType(value, "ObjectId") || !utils.isObject(value)) { value = { _id: value }; } const isDisc = value.schema && value.schema.discriminatorMapping && value.schema.discriminatorMapping.key !== void 0; if (!isDisc) { value = new Model(value); } return this[arraySchemaSymbol].caster.applySetters(value, parent, true); } return this[arraySchemaSymbol].caster.applySetters(value, parent, false); }, /** * Internal helper for .map() * * @api private * @return {Number} * @method _mapCast * @memberOf MongooseArray */ _mapCast(val, index) { return this._cast(val, this.length + index); }, /** * Marks this array as modified. * * If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments) * * @param {ArraySubdocument} subdoc the embedded doc that invoked this method on the Array * @param {String} embeddedPath the path which changed in the subdoc * @method _markModified * @api private * @memberOf MongooseArray */ _markModified(elem) { const parent = this[arrayParentSymbol]; let dirtyPath; if (parent) { dirtyPath = this[arrayPathSymbol]; if (arguments.length) { dirtyPath = dirtyPath + "." + elem; } if (dirtyPath != null && dirtyPath.endsWith(".$")) { return this; } parent.markModified(dirtyPath, arguments.length !== 0 ? elem : parent); } return this; }, /** * Register an atomic operation with the parent. * * @param {Array} op operation * @param {any} val * @method _registerAtomic * @api private * @memberOf MongooseArray */ _registerAtomic(op, val) { if (this[slicedSymbol]) { return; } if (op === "$set") { this[arrayAtomicsSymbol] = { $set: val }; cleanModifiedSubpaths(this[arrayParentSymbol], this[arrayPathSymbol]); this._markModified(); return this; } const atomics = this[arrayAtomicsSymbol]; if (op === "$pop" && !("$pop" in atomics)) { const _this = this; this[arrayParentSymbol].once("save", function() { _this._popped = _this._shifted = null; }); } if (atomics.$set || Object.keys(atomics).length && !(op in atomics)) { this[arrayAtomicsSymbol] = { $set: this }; return this; } let selector; if (op === "$pullAll" || op === "$addToSet") { atomics[op] || (atomics[op] = []); atomics[op] = atomics[op].concat(val); } else if (op === "$pullDocs") { const pullOp = atomics["$pull"] || (atomics["$pull"] = {}); if (val[0] instanceof ArraySubdocument) { selector = pullOp["$or"] || (pullOp["$or"] = []); Array.prototype.push.apply(selector, val.map((v) => { return v.toObject({ transform: (doc, ret) => { if (v == null || v.$__ == null) { return ret; } Object.keys(v.$__.activePaths.getStatePaths("default")).forEach((path) => { mpath.unset(path, ret); _minimizePath(ret, path); }); return ret; }, virtuals: false }); })); } else { selector = pullOp["_id"] || (pullOp["_id"] = { $in: [] }); selector["$in"] = selector["$in"].concat(val); } } else if (op === "$push") { atomics.$push = atomics.$push || { $each: [] }; if (val != null && utils.hasUserDefinedProperty(val, "$each")) { atomics.$push = val; } else { if (val.length === 1) { atomics.$push.$each.push(val[0]); } else if (val.length < 1e4) { atomics.$push.$each.push(...val); } else { for (const v of val) { atomics.$push.$each.push(v); } } } } else { atomics[op] = val; } return this; }, /** * Adds values to the array if not already present. * * #### Example: * * console.log(doc.array) // [2,3,4] * const added = doc.array.addToSet(4,5); * console.log(doc.array) // [2,3,4,5] * console.log(added) // [5] * * @param {...any} [args] * @return {Array} the values that were added * @memberOf MongooseArray * @api public * @method addToSet */ addToSet() { _checkManualPopulation(this, arguments); _depopulateIfNecessary(this, arguments); const values = [].map.call(arguments, this._mapCast, this); const added = []; let type = ""; if (values[0] instanceof ArraySubdocument) { type = "doc"; } else if (values[0] instanceof Date) { type = "date"; } else if (isBsonType(values[0], "ObjectId")) { type = "ObjectId"; } const rawValues = utils.isMongooseArray(values) ? values.__array : values; const rawArray = utils.isMongooseArray(this) ? this.__array : this; rawValues.forEach(function(v) { let found; const val = +v; switch (type) { case "doc": found = this.some(function(doc) { return doc.equals(v); }); break; case "date": found = this.some(function(d) { return +d === val; }); break; case "ObjectId": found = this.find((o) => o.toString() === v.toString()); break; default: found = ~this.indexOf(v); break; } if (!found) { this._markModified(); rawArray.push(v); this._registerAtomic("$addToSet", v); [].push.call(added, v); } }, this); return added; }, /** * Returns the number of pending atomic operations to send to the db for this array. * * @api private * @return {Number} * @method hasAtomics * @memberOf MongooseArray */ hasAtomics() { if (!utils.isPOJO(this[arrayAtomicsSymbol])) { return 0; } return Object.keys(this[arrayAtomicsSymbol]).length; }, /** * Return whether or not the `obj` is included in the array. * * @param {Object} obj the item to check * @param {Number} fromIndex * @return {Boolean} * @api public * @method includes * @memberOf MongooseArray */ includes(obj, fromIndex) { const ret = this.indexOf(obj, fromIndex); return ret !== -1; }, /** * Return the index of `obj` or `-1` if not found. * * @param {Object} obj the item to look for * @param {Number} fromIndex * @return {Number} * @api public * @method indexOf * @memberOf MongooseArray */ indexOf(obj, fromIndex) { if (isBsonType(obj, "ObjectId")) { obj = obj.toString(); } fromIndex = fromIndex == null ? 0 : fromIndex; const len = this.length; for (let i = fromIndex; i < len; ++i) { if (obj == this[i]) { return i; } } return -1; }, /** * Helper for console.log * * @api public * @method inspect * @memberOf MongooseArray */ inspect() { return JSON.stringify(this); }, /** * Pushes items to the array non-atomically. * * #### Note: * * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ * * @param {...any} [args] * @api public * @method nonAtomicPush * @memberOf MongooseArray */ nonAtomicPush() { const values = [].map.call(arguments, this._mapCast, this); this._markModified(); const ret = [].push.apply(this, values); this._registerAtomic("$set", this); return ret; }, /** * Wraps [`Array#pop`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop) with proper change tracking. * * #### Note: * * _marks the entire array as modified which will pass the entire thing to $set potentially overwriting any changes that happen between when you retrieved the object and when you save it._ * * @see MongooseArray#$pop https://mongoosejs.com/docs/api/array.html#MongooseArray.prototype.$pop() * @api public * @method pop * @memberOf MongooseArray */ pop() { this._markModified(); const ret = [].pop.call(this); this._registerAtomic("$set", this); return ret; }, /** * Pulls items from the array atomically. Equality is determined by casting * the provided value to an embedded document and comparing using * [the `Document.equals()` function.](https://mongoosejs.com/docs/api/document.html#Document.prototype.equals()) * * #### Example: * * doc.array.pull(ObjectId) * doc.array.pull({ _id: 'someId' }) * doc.array.pull(36) * doc.array.pull('tag 1', 'tag 2') * * To remove a document from a subdocument array we may pass an object with a matching `_id`. * * doc.subdocs.push({ _id: 4815162342 }) * doc.subdocs.pull({ _id: 4815162342 }) // removed * * Or we may passing the _id directly and let mongoose take care of it. * * doc.subdocs.push({ _id: 4815162342 }) * doc.subdocs.pull(4815162342); // works * * The first pull call will result in a atomic operation on the database, if pull is called repeatedly without saving the document, a $set operation is used on the complete array instead, overwriting possible changes that happened on the database in the meantime. * * @param {...any} [args] * @see mongodb https://www.mongodb.com/docs/manual/reference/operator/update/pull/ * @api public * @method pull * @memberOf MongooseArray */ pull() { const values = [].map.call(arguments, (v, i2) => this._cast(v, i2, { defaults: false }), this); let cur = this[arrayParentSymbol].get(this[arrayPathSymbol]); if (utils.isMongooseArray(cur)) { cur = cur.__array; } let i = cur.length; let mem; this._markModified(); while (i--) { mem = cur[i]; if (mem instanceof Document) { const some = values.some(function(v) { return mem.equals(v); }); if (some) { cur.splice(i, 1); } } else if (~this.indexOf.call(values, mem)) { cur.splice(i, 1); } } if (values[0] instanceof ArraySubdocument) { this._registerAtomic("$pullDocs", values.map(function(v) { const _id = v.$__getValue("_id"); if (_id === void 0 || v.$isDefault("_id")) { return v; } return _id; })); } else { this._registerAtomic("$pullAll", values); } if (cleanModifiedSubpaths(this[arrayParentSymbol], this[arrayPathSymbol]) > 0) { this._registerAtomic("$set", this); } return this; }, /** * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. * * #### Example: * * const schema = Schema({ nums: [Number] }); * const Model = mongoose.model('Test', schema); * * const doc = await Model.create({ nums: [3, 4] }); * doc.nums.push(5); // Add 5 to the end of the array * await doc.save(); * * // You can also pass an object with `$each` as the * // first parameter to use MongoDB's `$position` * doc.nums.push({ * $each: [1, 2], * $position: 0 * }); * doc.nums; // [1, 2, 3, 4, 5] * * @param {...Object} [args] * @api public * @method push * @memberOf MongooseArray */ push() { let values = arguments; let atomic = values; const isOverwrite = values[0] != null && utils.hasUserDefinedProperty(values[0], "$each"); const arr = utils.isMongooseArray(this) ? this.__array : this; if (isOverwrite) { atomic = values[0]; values = values[0].$each; } if (this[arraySchemaSymbol] == null) { return _basePush.apply(this, values); } _checkManualPopulation(this, values); _depopulateIfNecessary(this, values); values = [].map.call(values, this._mapCast, this); let ret; const atomics = this[arrayAtomicsSymbol]; this._markModified(); if (isOverwrite) { atomic.$each = values; if ((atomics.$push && atomics.$push.$each && atomics.$push.$each.length || 0) !== 0 && atomics.$push.$position != atomic.$position) { if (atomic.$position != null) { [].splice.apply(arr, [atomic.$position, 0].concat(values)); ret = arr.length; } else { ret = [].push.apply(arr, values); } this._registerAtomic("$set", this); } else if (atomic.$position != null) { [].splice.apply(arr, [atomic.$position, 0].concat(values)); ret = this.length; } else { ret = [].push.apply(arr, values); } } else { atomic = values; ret = _basePush.apply(arr, values); } this._registerAtomic("$push", atomic); return ret; }, /** * Alias of [pull](https://mongoosejs.com/docs/api/array.html#MongooseArray.prototype.pull()) * * @see MongooseArray#pull https://mongoosejs.com/docs/api/array.html#MongooseArray.prototype.pull() * @see mongodb https://www.mongodb.com/docs/manual/reference/operator/update/pull/ * @api public * @memberOf MongooseArray * @instance * @method remove */ remove() { return this.pull.apply(this, arguments); }, /** * Sets the casted `val` at index `i` and marks the array modified. * * #### Example: * * // given documents based on the following * const Doc = mongoose.model('Doc', new Schema({ array: [Number] })); * * const doc = new Doc({ array: [2,3,4] }) * * console.log(doc.array) // [2,3,4] * * doc.array.set(1,"5"); * console.log(doc.array); // [2,5,4] // properly cast to number * doc.save() // the change is saved * * // VS not using array#set * doc.array[1] = "5"; * console.log(doc.array); // [2,"5",4] // no casting * doc.save() // change is not saved * * @return {Array} this * @api public * @method set * @memberOf MongooseArray */ set(i, val, skipModified) { const arr = this.__array; if (skipModified) { arr[i] = val; return this; } const value = methods._cast.call(this, val, i); methods._markModified.call(this, i); arr[i] = value; return this; }, /** * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. * * #### Example: * * doc.array = [2,3]; * const res = doc.array.shift(); * console.log(res) // 2 * console.log(doc.array) // [3] * * #### Note: * * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ * * @api public * @method shift * @memberOf MongooseArray */ shift() { const arr = utils.isMongooseArray(this) ? this.__array : this; this._markModified(); const ret = [].shift.call(arr); this._registerAtomic("$set", this); return ret; }, /** * Wraps [`Array#sort`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) with proper change tracking. * * #### Note: * * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ * * @api public * @method sort * @memberOf MongooseArray * @see MasteringJS: Array sort https://masteringjs.io/tutorials/fundamentals/array-sort */ sort() { const arr = utils.isMongooseArray(this) ? this.__array : this; const ret = [].sort.apply(arr, arguments); this._registerAtomic("$set", this); return ret; }, /** * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting. * * #### Note: * * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ * * @api public * @method splice * @memberOf MongooseArray * @see MasteringJS: Array splice https://masteringjs.io/tutorials/fundamentals/array-splice */ splice() { let ret; const arr = utils.isMongooseArray(this) ? this.__array : this; this._markModified(); _checkManualPopulation(this, Array.prototype.slice.call(arguments, 2)); if (arguments.length) { let vals; if (this[arraySchemaSymbol] == null) { vals = arguments; } else { vals = []; for (let i = 0; i < arguments.length; ++i) { vals[i] = i < 2 ? arguments[i] : this._cast(arguments[i], arguments[0] + (i - 2)); } } ret = [].splice.apply(arr, vals); this._registerAtomic("$set", this); } return ret; }, /*! * ignore */ toBSON() { return this.toObject(internalToObjectOptions); }, /** * Returns a native js Array. * * @param {Object} options * @return {Array} * @api public * @method toObject * @memberOf MongooseArray */ toObject(options) { const arr = utils.isMongooseArray(this) ? this.__array : this; if (options && options.depopulate) { options = clone(options); options._isNested = true; return [].concat(arr).map(function(doc) { return doc instanceof Document ? doc.toObject(options) : doc; }); } return [].concat(arr); }, $toObject() { return this.constructor.prototype.toObject.apply(this, arguments); }, /** * Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. * * #### Note: * * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwriting any changes that happen between when you retrieved the object and when you save it._ * * @api public * @method unshift * @memberOf MongooseArray */ unshift() { _checkManualPopulation(this, arguments); let values; if (this[arraySchemaSymbol] == null) { values = arguments; } else { values = [].map.call(arguments, this._cast, this); } const arr = utils.isMongooseArray(this) ? this.__array : this; this._markModified(); [].unshift.apply(arr, values); this._registerAtomic("$set", this); return this.length; } }; function _isAllSubdocs(docs, ref) { if (!ref) { return false; } for (const arg of docs) { if (arg == null) { return false; } const model = arg.constructor; if (!(arg instanceof Document) || model.modelName !== ref && model.baseModelName !== ref) { return false; } } return true; } function _minimizePath(obj, parts, i) { if (typeof parts === "string") { if (parts.indexOf(".") === -1) { return; } parts = mpath.stringToParts(parts); } i = i || 0; if (i >= parts.length) { return; } if (obj == null || typeof obj !== "object") { return; } _minimizePath(obj[parts[0]], parts, i + 1); if (obj[parts[0]] != null && typeof obj[parts[0]] === "object" && Object.keys(obj[parts[0]]).length === 0) { delete obj[parts[0]]; } } function _checkManualPopulation(arr, docs) { const ref = arr == null ? null : arr[arraySchemaSymbol] && arr[arraySchemaSymbol].caster && arr[arraySchemaSymbol].caster.options && arr[arraySchemaSymbol].caster.options.ref || null; if (arr.length === 0 && docs.length !== 0) { if (_isAllSubdocs(docs, ref)) { arr[arrayParentSymbol].$populated(arr[arrayPathSymbol], [], { [populateModelSymbol]: docs[0].constructor }); } } } function _depopulateIfNecessary(arr, docs) { const ref = arr == null ? null : arr[arraySchemaSymbol] && arr[arraySchemaSymbol].caster && arr[arraySchemaSymbol].caster.options && arr[arraySchemaSymbol].caster.options.ref || null; const parentDoc = arr[arrayParentSymbol]; const path = arr[arrayPathSymbol]; if (!ref || !parentDoc.populated(path)) { return; } for (const doc of docs) { if (doc == null) { continue; } if (typeof doc !== "object" || doc instanceof String || doc instanceof Number || doc instanceof Buffer || utils.isMongooseType(doc)) { parentDoc.depopulate(path); break; } } } var returnVanillaArrayMethods = [ "filter", "flat", "flatMap", "map", "slice" ]; for (const method of returnVanillaArrayMethods) { if (Array.prototype[method] == null) { continue; } methods[method] = function() { const _arr = utils.isMongooseArray(this) ? this.__array : this; const arr = [].concat(_arr); return arr[method].apply(arr, arguments); }; } module2.exports = methods; } }); // netlify/functions/node_modules/mongoose/lib/types/array/index.js var require_array = __commonJS({ "netlify/functions/node_modules/mongoose/lib/types/array/index.js"(exports2, module2) { "use strict"; var mongooseArrayMethods = require_methods(); var arrayAtomicsSymbol = require_symbols().arrayAtomicsSymbol; var arrayAtomicsBackupSymbol = require_symbols().arrayAtomicsBackupSymbol; var arrayParentSymbol = require_symbols().arrayParentSymbol; var arrayPathSymbol = require_symbols().arrayPathSymbol; var arraySchemaSymbol = require_symbols().arraySchemaSymbol; var _basePush = Array.prototype.push; var numberRE = /^\d+$/; function MongooseArray(values, path, doc, schematype) { let __array; if (Array.isArray(values)) { const len = values.length; if (len === 0) { __array = new Array(); } else if (len === 1) { __array = new Array(1); __array[0] = values[0]; } else if (len < 1e4) { __array = new Array(); _basePush.apply(__array, values); } else { __array = new Array(); for (let i = 0; i < len; ++i) { _basePush.call(__array, values[i]); } } } else { __array = []; } const internals = { [arrayAtomicsSymbol]: {}, [arrayAtomicsBackupSymbol]: void 0, [arrayPathSymbol]: path, [arraySchemaSymbol]: schematype, [arrayParentSymbol]: void 0, isMongooseArray: true, isMongooseArrayProxy: true, __array }; if (values && values[arrayAtomicsSymbol] != null) { internals[arrayAtomicsSymbol] = values[arrayAtomicsSymbol]; } if (doc != null && doc.$__) { internals[arrayParentSymbol] = doc; internals[arraySchemaSymbol] = schematype || doc.schema.path(path); } const proxy = new Proxy(__array, { get: function(target, prop) { if (internals.hasOwnProperty(prop)) { return internals[prop]; } if (mongooseArrayMethods.hasOwnProperty(prop)) { return mongooseArrayMethods[prop]; } if (schematype && schematype.virtuals && schematype.virtuals.hasOwnProperty(prop)) { return schematype.virtuals[prop].applyGetters(void 0, target); } if (typeof prop === "string" && numberRE.test(prop) && schematype?.$embeddedSchemaType != null) { return schematype.$embeddedSchemaType.applyGetters(__array[prop], doc); } return __array[prop]; }, set: function(target, prop, value) { if (typeof prop === "string" && numberRE.test(prop)) { mongooseArrayMethods.set.call(proxy, prop, value, false); } else if (internals.hasOwnProperty(prop)) { internals[prop] = value; } else if (schematype && schematype.virtuals && schematype.virtuals.hasOwnProperty(prop)) { schematype.virtuals[prop].applySetters(value, target); } else { __array[prop] = value; } return true; } }); return proxy; } module2.exports = exports2 = MongooseArray; } }); // netlify/functions/node_modules/mongoose/lib/cast/objectid.js var require_objectid2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/cast/objectid.js"(exports2, module2) { "use strict"; var isBsonType = require_isBsonType(); var ObjectId2 = require_objectid(); module2.exports = function castObjectId(value) { if (value == null) { return value; } if (isBsonType(value, "ObjectId")) { return value; } if (value._id) { if (isBsonType(value._id, "ObjectId")) { return value._id; } if (value._id.toString instanceof Function) { return new ObjectId2(value._id.toString()); } } if (value.toString instanceof Function) { return new ObjectId2(value.toString()); } return new ObjectId2(value); }; } }); // netlify/functions/node_modules/mongoose/lib/types/documentArray/methods/index.js var require_methods2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/types/documentArray/methods/index.js"(exports2, module2) { "use strict"; var ArrayMethods = require_methods(); var Document = require_document2(); var castObjectId = require_objectid2(); var getDiscriminatorByValue = require_getDiscriminatorByValue(); var internalToObjectOptions = require_options().internalToObjectOptions; var utils = require_utils3(); var isBsonType = require_isBsonType(); var arrayParentSymbol = require_symbols().arrayParentSymbol; var arrayPathSymbol = require_symbols().arrayPathSymbol; var arraySchemaSymbol = require_symbols().arraySchemaSymbol; var documentArrayParent = require_symbols().documentArrayParent; var _baseToString = Array.prototype.toString; var methods = { /*! * ignore */ toBSON() { return this.toObject(internalToObjectOptions); }, toString() { return _baseToString.call(this.__array.map((subdoc) => { if (subdoc != null && subdoc.$__ != null) { return subdoc.toString(); } return subdoc; })); }, /*! * ignore */ getArrayParent() { return this[arrayParentSymbol]; }, /*! * ignore */ $schemaType() { return this[arraySchemaSymbol]; }, /** * Overrides MongooseArray#cast * * @method _cast * @api private * @memberOf MongooseDocumentArray */ _cast(value, index, options) { if (this[arraySchemaSymbol] == null) { return value; } let Constructor = this[arraySchemaSymbol].casterConstructor; const isInstance = Constructor.$isMongooseDocumentArray ? utils.isMongooseDocumentArray(value) : value instanceof Constructor; if (isInstance || // Hack re: #5001, see #5005 value && value.constructor && value.constructor.baseCasterConstructor === Constructor) { if (!(value[documentArrayParent] && value.__parentArray)) { value[documentArrayParent] = this[arrayParentSymbol]; value.__parentArray = this; } value.$setIndex(index); return value; } if (value === void 0 || value === null) { return null; } if (Buffer.isBuffer(value) || isBsonType(value, "ObjectId") || !utils.isObject(value)) { value = { _id: value }; } if (value && Constructor.discriminators && Constructor.schema && Constructor.schema.options && Constructor.schema.options.discriminatorKey) { if (typeof value[Constructor.schema.options.discriminatorKey] === "string" && Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]]) { Constructor = Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]]; } else { const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, value[Constructor.schema.options.discriminatorKey]); if (constructorByValue) { Constructor = constructorByValue; } } } if (Constructor.$isMongooseDocumentArray) { return Constructor.cast(value, this, void 0, void 0, index); } const ret = new Constructor(value, this, options, void 0, index); ret.isNew = true; return ret; }, /** * Searches array items for the first document with a matching _id. * * #### Example: * * const embeddedDoc = m.array.id(some_id); * * @return {EmbeddedDocument|null} the subdocument or null if not found. * @param {ObjectId|String|Number|Buffer} id * @TODO cast to the _id based on schema for proper comparison * @method id * @api public * @memberOf MongooseDocumentArray */ id(id) { let casted; let sid; let _id; try { casted = castObjectId(id).toString(); } catch (e) { casted = null; } for (const val of this) { if (!val) { continue; } _id = val.get("_id"); if (_id === null || typeof _id === "undefined") { continue; } else if (_id instanceof Document) { sid || (sid = String(id)); if (sid == _id._id) { return val; } } else if (!isBsonType(id, "ObjectId") && !isBsonType(_id, "ObjectId")) { if (id == _id || utils.deepEqual(id, _id)) { return val; } } else if (casted == _id) { return val; } } return null; }, /** * Returns a native js Array of plain js objects * * #### Note: * * _Each sub-document is converted to a plain object by calling its `#toObject` method._ * * @param {Object} [options] optional options to pass to each documents `toObject` method call during conversion * @return {Array} * @method toObject * @api public * @memberOf MongooseDocumentArray */ toObject(options) { return [].concat(this.map(function(doc) { if (doc == null) { return null; } if (typeof doc.toObject !== "function") { return doc; } return doc.toObject(options); })); }, $toObject() { return this.constructor.prototype.toObject.apply(this, arguments); }, /** * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. * * @param {...Object} [args] * @api public * @method push * @memberOf MongooseDocumentArray */ push() { const ret = ArrayMethods.push.apply(this, arguments); _updateParentPopulated(this); return ret; }, /** * Pulls items from the array atomically. * * @param {...Object} [args] * @api public * @method pull * @memberOf MongooseDocumentArray */ pull() { const ret = ArrayMethods.pull.apply(this, arguments); _updateParentPopulated(this); return ret; }, /** * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. * @api private */ shift() { const ret = ArrayMethods.shift.apply(this, arguments); _updateParentPopulated(this); return ret; }, /** * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting. * @api private */ splice() { const ret = ArrayMethods.splice.apply(this, arguments); _updateParentPopulated(this); return ret; }, /** * Helper for console.log * * @method inspect * @api public * @memberOf MongooseDocumentArray */ inspect() { return this.toObject(); }, /** * Creates a subdocument casted to this schema. * * This is the same subdocument constructor used for casting. * * @param {Object} obj the value to cast to this arrays SubDocument schema * @method create * @api public * @memberOf MongooseDocumentArray */ create(obj) { let Constructor = this[arraySchemaSymbol].casterConstructor; if (obj && Constructor.discriminators && Constructor.schema && Constructor.schema.options && Constructor.schema.options.discriminatorKey) { if (typeof obj[Constructor.schema.options.discriminatorKey] === "string" && Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]) { Constructor = Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]; } else { const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, obj[Constructor.schema.options.discriminatorKey]); if (constructorByValue) { Constructor = constructorByValue; } } } return new Constructor(obj, this); }, /*! * ignore */ notify(event) { const _this = this; return function notify(val, _arr) { _arr = _arr || _this; let i = _arr.length; while (i--) { if (_arr[i] == null) { continue; } switch (event) { // only swap for save event for now, we may change this to all event types later case "save": val = _this[i]; break; default: break; } if (utils.isMongooseArray(_arr[i])) { notify(val, _arr[i]); } else if (_arr[i]) { _arr[i].emit(event, val); } } }; }, set(i, val, skipModified) { const arr = this.__array; if (skipModified) { arr[i] = val; return this; } const value = methods._cast.call(this, val, i); methods._markModified.call(this, i); arr[i] = value; return this; }, _markModified(elem, embeddedPath) { const parent = this[arrayParentSymbol]; let dirtyPath; if (parent) { dirtyPath = this[arrayPathSymbol]; if (arguments.length) { if (embeddedPath != null) { const index = elem.__index; dirtyPath = dirtyPath + "." + index + "." + embeddedPath; } else { dirtyPath = dirtyPath + "." + elem; } } if (dirtyPath != null && dirtyPath.endsWith(".$")) { return this; } parent.markModified(dirtyPath, arguments.length !== 0 ? elem : parent); } return this; } }; module2.exports = methods; function _updateParentPopulated(arr) { const parent = arr[arrayParentSymbol]; if (!parent || parent.$__.populated == null) return; const populatedPaths = Object.keys(parent.$__.populated).filter((p) => p.startsWith(arr[arrayPathSymbol] + ".")); for (const path of populatedPaths) { const remnant = path.slice((arr[arrayPathSymbol] + ".").length); if (!Array.isArray(parent.$__.populated[path].value)) { continue; } parent.$__.populated[path].value = arr.map((val) => val.$populated(remnant)); } } } }); // netlify/functions/node_modules/mongoose/lib/types/documentArray/index.js var require_documentArray = __commonJS({ "netlify/functions/node_modules/mongoose/lib/types/documentArray/index.js"(exports2, module2) { "use strict"; var ArrayMethods = require_methods(); var DocumentArrayMethods = require_methods2(); var arrayAtomicsSymbol = require_symbols().arrayAtomicsSymbol; var arrayAtomicsBackupSymbol = require_symbols().arrayAtomicsBackupSymbol; var arrayParentSymbol = require_symbols().arrayParentSymbol; var arrayPathSymbol = require_symbols().arrayPathSymbol; var arraySchemaSymbol = require_symbols().arraySchemaSymbol; var _basePush = Array.prototype.push; var numberRE = /^\d+$/; function MongooseDocumentArray(values, path, doc, schematype) { const __array = []; const internals = { [arrayAtomicsSymbol]: {}, [arrayAtomicsBackupSymbol]: void 0, [arrayPathSymbol]: path, [arraySchemaSymbol]: void 0, [arrayParentSymbol]: void 0 }; if (Array.isArray(values)) { if (values[arrayPathSymbol] === path && values[arrayParentSymbol] === doc) { internals[arrayAtomicsSymbol] = Object.assign({}, values[arrayAtomicsSymbol]); } values.forEach((v) => { _basePush.call(__array, v); }); } internals[arrayPathSymbol] = path; internals.__array = __array; if (doc && doc.$__) { internals[arrayParentSymbol] = doc; internals[arraySchemaSymbol] = doc.$__schema.path(path); while (internals[arraySchemaSymbol] != null && internals[arraySchemaSymbol].$isMongooseArray && !internals[arraySchemaSymbol].$isMongooseDocumentArray) { internals[arraySchemaSymbol] = internals[arraySchemaSymbol].casterConstructor; } } const proxy = new Proxy(__array, { get: function(target, prop) { if (prop === "isMongooseArray" || prop === "isMongooseArrayProxy" || prop === "isMongooseDocumentArray" || prop === "isMongooseDocumentArrayProxy") { return true; } if (internals.hasOwnProperty(prop)) { return internals[prop]; } if (DocumentArrayMethods.hasOwnProperty(prop)) { return DocumentArrayMethods[prop]; } if (schematype && schematype.virtuals && schematype.virtuals.hasOwnProperty(prop)) { return schematype.virtuals[prop].applyGetters(void 0, target); } if (ArrayMethods.hasOwnProperty(prop)) { return ArrayMethods[prop]; } return __array[prop]; }, set: function(target, prop, value) { if (typeof prop === "string" && numberRE.test(prop)) { DocumentArrayMethods.set.call(proxy, prop, value, false); } else if (internals.hasOwnProperty(prop)) { internals[prop] = value; } else if (schematype && schematype.virtuals && schematype.virtuals.hasOwnProperty(prop)) { schematype.virtuals[prop].applySetters(value, target); } else { __array[prop] = value; } return true; } }); return proxy; } module2.exports = MongooseDocumentArray; } }); // netlify/functions/node_modules/mongoose/lib/document.js var require_document2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/document.js"(exports2, module2) { "use strict"; var DivergentArrayError = require_divergentArray(); var EventEmitter = require("events").EventEmitter; var InternalCache = require_internal(); var MongooseBuffer = require_buffer(); var MongooseError = require_error2(); var MixedSchema = require_mixed(); var ModifiedPathsSnapshot = require_modifiedPathsSnapshot(); var ObjectExpectedError = require_objectExpected(); var ObjectParameterError = require_objectParameter(); var ParallelValidateError = require_parallelValidate(); var Schema = require_schema2(); var StrictModeError = require_strict(); var ValidationError = require_validation(); var ValidatorError = require_validator(); var $__hasIncludedChildren = require_hasIncludedChildren(); var applyDefaults = require_applyDefaults(); var cleanModifiedSubpaths = require_cleanModifiedSubpaths(); var clone = require_clone(); var compile = require_compile().compile; var defineKey = require_compile().defineKey; var firstKey = require_firstKey(); var flatten = require_common3().flatten; var getEmbeddedDiscriminatorPath = require_getEmbeddedDiscriminatorPath(); var getKeysInSchemaOrder = require_getKeysInSchemaOrder(); var getSubdocumentStrictValue = require_getSubdocumentStrictValue(); var handleSpreadDoc = require_handleSpreadDoc(); var immediate = require_immediate(); var isBsonType = require_isBsonType(); var isDefiningProjection = require_isDefiningProjection(); var isExclusive = require_isExclusive(); var isPathExcluded = require_isPathExcluded(); var inspect = require("util").inspect; var internalToObjectOptions = require_options().internalToObjectOptions; var markArraySubdocsPopulated = require_markArraySubdocsPopulated(); var minimize = require_minimize(); var mpath = require_mpath(); var parentPaths = require_parentPaths(); var queryhelpers = require_queryHelpers(); var utils = require_utils3(); var isPromise = require_isPromise(); var deepEqual = utils.deepEqual; var isMongooseObject = utils.isMongooseObject; var arrayAtomicsBackupSymbol = require_symbols().arrayAtomicsBackupSymbol; var arrayAtomicsSymbol = require_symbols().arrayAtomicsSymbol; var documentArrayParent = require_symbols().documentArrayParent; var documentIsModified = require_symbols().documentIsModified; var documentModifiedPaths = require_symbols().documentModifiedPaths; var documentSchemaSymbol = require_symbols().documentSchemaSymbol; var getSymbol = require_symbols().getSymbol; var modelSymbol = require_symbols().modelSymbol; var populateModelSymbol = require_symbols().populateModelSymbol; var scopeSymbol = require_symbols().scopeSymbol; var schemaMixedSymbol = require_symbols2().schemaMixedSymbol; var getDeepestSubdocumentForPath = require_getDeepestSubdocumentForPath(); var sessionNewDocuments = require_symbols().sessionNewDocuments; var DocumentArray; var MongooseArray; var Embedded; var specialProperties = utils.specialProperties; var VERSION_WHERE = 1; var VERSION_INC = 2; var VERSION_ALL = VERSION_WHERE | VERSION_INC; function Document(obj, fields, skipId, options) { if (typeof skipId === "object" && skipId != null) { options = skipId; skipId = options.skipId; } options = Object.assign({}, options); if (this.$__schema == null) { const _schema = utils.isObject(fields) && !fields.instanceOfSchema ? new Schema(fields) : fields; this.$__setSchema(_schema); fields = skipId; skipId = options; options = arguments[4] || {}; } this.$__ = new InternalCache(); if (options.isNew != null && options.isNew !== true) { this.$isNew = options.isNew; } if (options.priorDoc != null) { this.$__.priorDoc = options.priorDoc; } if (skipId) { this.$__.skipId = skipId; } if (obj != null && typeof obj !== "object") { throw new ObjectParameterError(obj, "obj", "Document"); } let defaults = true; if (options.defaults !== void 0) { this.$__.defaults = options.defaults; defaults = options.defaults; } const schema = this.$__schema; if (typeof fields === "boolean" || fields === "throw") { if (fields !== true) { this.$__.strictMode = fields; } fields = void 0; } else if (schema.options.strict !== true) { this.$__.strictMode = schema.options.strict; } const requiredPaths = schema.requiredPaths(true); for (const path of requiredPaths) { this.$__.activePaths.require(path); } let exclude = null; if (utils.isPOJO(fields) && Object.keys(fields).length > 0) { exclude = isExclusive(fields); this.$__.selected = fields; this.$__.exclude = exclude; } const hasIncludedChildren = exclude === false && fields ? $__hasIncludedChildren(fields) : null; if (this._doc == null) { this.$__buildDoc(obj, fields, skipId, exclude, hasIncludedChildren, false); if (defaults) { applyDefaults(this, fields, exclude, hasIncludedChildren, true, null, { skipParentChangeTracking: true }); } } if (obj) { if (this.$__original_set) { this.$__original_set(obj, void 0, true, options); } else { this.$set(obj, void 0, true, options); } if (obj instanceof Document) { this.$isNew = obj.$isNew; } } if (options.willInit && defaults) { if (options.skipDefaults) { this.$__.skipDefaults = options.skipDefaults; } } else if (defaults) { applyDefaults(this, fields, exclude, hasIncludedChildren, false, options.skipDefaults); } if (!this.$__.strictMode && obj) { const _this = this; const keys = Object.keys(this._doc); keys.forEach(function(key) { if (!(key in schema.tree) && !(key in schema.methods) && !(key in schema.virtuals) && !key.startsWith("$")) { defineKey({ prop: key, subprops: null, prototype: _this }); } }); } applyQueue(this); } Document.prototype.$isMongooseDocumentPrototype = true; Object.defineProperty(Document.prototype, "isNew", { get: function() { return this.$isNew; }, set: function(value) { this.$isNew = value; } }); Object.defineProperty(Document.prototype, "errors", { get: function() { return this.$errors; }, set: function(value) { this.$errors = value; } }); Document.prototype.$isNew = true; utils.each( [ "on", "once", "emit", "listeners", "removeListener", "setMaxListeners", "removeAllListeners", "addListener" ], function(emitterFn) { Document.prototype[emitterFn] = function() { if (!this.$__.emitter) { if (emitterFn === "emit") { return; } this.$__.emitter = new EventEmitter(); this.$__.emitter.setMaxListeners(0); } return this.$__.emitter[emitterFn].apply(this.$__.emitter, arguments); }; Document.prototype[`$${emitterFn}`] = Document.prototype[emitterFn]; } ); Document.prototype.constructor = Document; for (const i in EventEmitter.prototype) { Document[i] = EventEmitter.prototype[i]; } Document.prototype.$__schema; Document.prototype.schema; Object.defineProperty(Document.prototype, "$locals", { configurable: false, enumerable: false, get: function() { if (this.$__.locals == null) { this.$__.locals = {}; } return this.$__.locals; }, set: function(v) { this.$__.locals = v; } }); Document.prototype.isNew; Object.defineProperty(Document.prototype, "$where", { configurable: false, enumerable: false, writable: true }); Document.prototype.id; Document.prototype.$errors; Object.defineProperty(Document.prototype, "$op", { get: function() { return this.$__.op || null; }, set: function(value) { this.$__.op = value; } }); function $applyDefaultsToNested(val, path, doc) { if (val == null) { return; } const paths = Object.keys(doc.$__schema.paths); const plen = paths.length; const pathPieces = path.indexOf(".") === -1 ? [path] : path.split("."); for (let i = 0; i < plen; ++i) { let curPath = ""; const p = paths[i]; if (!p.startsWith(path + ".")) { continue; } const type = doc.$__schema.paths[p]; const pieces = type.splitPath().slice(pathPieces.length); const len = pieces.length; if (type.defaultValue === void 0) { continue; } let cur = val; for (let j = 0; j < len; ++j) { if (cur == null) { break; } const piece = pieces[j]; if (j === len - 1) { if (cur[piece] !== void 0) { break; } try { const def = type.getDefault(doc, false); if (def !== void 0) { cur[piece] = def; } } catch (err) { doc.invalidate(path + "." + curPath, err); break; } break; } curPath += (!curPath.length ? "" : ".") + piece; cur[piece] = cur[piece] || {}; cur = cur[piece]; } } } Document.prototype.$__buildDoc = function(obj, fields, skipId, exclude, hasIncludedChildren) { const doc = {}; const paths = Object.keys(this.$__schema.paths).filter((p) => !p.includes("$*")); const plen = paths.length; let ii = 0; for (; ii < plen; ++ii) { const p = paths[ii]; if (p === "_id") { if (skipId) { continue; } if (obj && "_id" in obj) { continue; } } const path = this.$__schema.paths[p].splitPath(); const len = path.length; const last = len - 1; let curPath = ""; let doc_ = doc; let included = false; for (let i = 0; i < len; ++i) { const piece = path[i]; if (!curPath.length) { curPath = piece; } else { curPath += "." + piece; } if (exclude === true) { if (curPath in fields) { break; } } else if (exclude === false && fields && !included) { if (curPath in fields) { included = true; } else if (!hasIncludedChildren[curPath]) { break; } } if (i < last) { doc_ = doc_[piece] || (doc_[piece] = {}); } } } this._doc = doc; }; Document.prototype.toBSON = function() { return this.toObject(internalToObjectOptions); }; Document.prototype.init = function(doc, opts, fn) { if (typeof opts === "function") { fn = opts; opts = null; } this.$__init(doc, opts); if (fn) { fn(null, this); } return this; }; Document.prototype.$init = function() { return this.constructor.prototype.init.apply(this, arguments); }; Document.prototype.$__init = function(doc, opts) { this.$isNew = false; opts = opts || {}; if (doc._id != null && opts.populated && opts.populated.length) { const id = String(doc._id); for (const item of opts.populated) { if (item.isVirtual) { this.$populated(item.path, utils.getValue(item.path, doc), item); } else { this.$populated(item.path, item._docs[id], item); } if (item._childDocs == null) { continue; } for (const child of item._childDocs) { if (child == null || child.$__ == null) { continue; } child.$__.parent = this; } item._childDocs = []; } } init(this, doc, this._doc, opts); markArraySubdocsPopulated(this, opts.populated); this.$emit("init", this); this.constructor.emit("init", this); const hasIncludedChildren = this.$__.exclude === false && this.$__.selected ? $__hasIncludedChildren(this.$__.selected) : null; applyDefaults(this, this.$__.selected, this.$__.exclude, hasIncludedChildren, false, this.$__.skipDefaults); return this; }; function init(self2, obj, doc, opts, prefix) { prefix = prefix || ""; if (obj.$__ != null) { obj = obj._doc; } const keys = Object.keys(obj); const len = keys.length; let schemaType; let path; let i; const strict = self2.$__.strictMode; const docSchema = self2.$__schema; for (let index = 0; index < len; ++index) { i = keys[index]; if (specialProperties.has(i)) { continue; } path = prefix ? prefix + i : i; schemaType = docSchema.path(path); if (docSchema.$isRootDiscriminator && !self2.$__isSelected(path)) { continue; } const value = obj[i]; if (!schemaType && utils.isPOJO(value)) { if (!doc[i]) { doc[i] = {}; if (!strict && !(i in docSchema.tree) && !(i in docSchema.methods) && !(i in docSchema.virtuals)) { self2[i] = doc[i]; } } init(self2, value, doc[i], opts, path + "."); } else if (!schemaType) { doc[i] = value; if (!strict && !prefix) { self2[i] = value; } } else { if (doc.hasOwnProperty(i) && value !== void 0 && !opts.hydratedPopulatedDocs) { delete doc[i]; } if (value === null) { doc[i] = schemaType._castNullish(null); } else if (value !== void 0) { const wasPopulated = value.$__ == null ? null : value.$__.wasPopulated; if (schemaType && !wasPopulated && !opts.hydratedPopulatedDocs) { try { if (opts && opts.setters) { const overrideInit = false; doc[i] = schemaType.applySetters(value, self2, overrideInit); } else { doc[i] = schemaType.cast(value, self2, true); } } catch (e) { self2.invalidate(e.path, new ValidatorError({ path: e.path, message: e.message, type: "cast", value: e.value, reason: e })); } } else if (schemaType && opts.hydratedPopulatedDocs) { doc[i] = schemaType.cast(value, self2, true, void 0, { hydratedPopulatedDocs: true }); if (doc[i] && doc[i].$__ && doc[i].$__.wasPopulated) { self2.$populated(path, doc[i].$__.wasPopulated.value, doc[i].$__.wasPopulated.options); } else if (Array.isArray(doc[i]) && doc[i].length && doc[i][0]?.$__?.wasPopulated) { self2.$populated(path, doc[i].map((populatedDoc) => populatedDoc?.$__?.wasPopulated?.value).filter((val) => val != null), doc[i][0].$__.wasPopulated.options); } } else { doc[i] = value; } } if (!self2.$isModified(path)) { self2.$__.activePaths.init(path); } } } } Document.prototype.updateOne = function updateOne(doc, options, callback) { const query = this.constructor.updateOne({ _id: this._doc._id }, doc, options); const self2 = this; query.pre(function queryPreUpdateOne(cb) { self2.constructor._middleware.execPre("updateOne", self2, [self2], cb); }); query.post(function queryPostUpdateOne(cb) { self2.constructor._middleware.execPost("updateOne", self2, [self2], {}, cb); }); if (this.$session() != null) { if (!("session" in query.options)) { query.options.session = this.$session(); } } if (callback != null) { return query.exec(callback); } return query; }; Document.prototype.replaceOne = function replaceOne() { const args = [...arguments]; args.unshift({ _id: this._doc._id }); return this.constructor.replaceOne.apply(this.constructor, args); }; Document.prototype.$session = function $session(session) { if (arguments.length === 0) { if (this.$__.session != null && this.$__.session.hasEnded) { this.$__.session = null; return null; } return this.$__.session; } if (session != null && session.hasEnded) { throw new MongooseError("Cannot set a document's session to a session that has ended. Make sure you haven't called `endSession()` on the session you are passing to `$session()`."); } if (session == null && this.$__.session == null) { return; } this.$__.session = session; if (!this.$isSubdocument) { const subdocs = this.$getAllSubdocs(); for (const child of subdocs) { child.$session(session); } } return session; }; Document.prototype.$timestamps = function $timestamps(value) { if (arguments.length === 0) { if (this.$__.timestamps != null) { return this.$__.timestamps; } if (this.$__schema) { return this.$__schema.options.timestamps; } return void 0; } const currentValue = this.$timestamps(); if (value !== currentValue) { this.$__.timestamps = value; } return this; }; Document.prototype.overwrite = function overwrite(obj) { const keys = Array.from(new Set(Object.keys(this._doc).concat(Object.keys(obj)))); for (const key of keys) { if (key === "_id") { continue; } if (this.$__schema.options.versionKey && key === this.$__schema.options.versionKey) { continue; } if (this.$__schema.options.discriminatorKey && key === this.$__schema.options.discriminatorKey) { continue; } this.$set(key, obj[key]); } return this; }; Document.prototype.$set = function $set(path, val, type, options) { if (utils.isPOJO(type)) { options = type; type = void 0; } const merge = options && options.merge; const adhoc = type && type !== true; const constructing = type === true; let adhocs; let keys; let i = 0; let pathtype; let key; let prefix; const userSpecifiedStrict = options && "strict" in options; let strict = userSpecifiedStrict ? options.strict : this.$__.strictMode; if (adhoc) { adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {}); adhocs[path] = this.$__schema.interpretAsType(path, type, this.$__schema.options); } if (path == null) { [path, val] = [val, path]; } else if (typeof path !== "string") { if (path instanceof Document) { if (path.$__isNested) { path = path.toObject(); } else { path = path.$__schema === this.$__schema ? applyVirtuals(path, { ...path._doc }) : path._doc; } } if (path == null) { [path, val] = [val, path]; } prefix = val ? val + "." : ""; keys = getKeysInSchemaOrder(this.$__schema, path); const len = keys.length; const _skipMinimizeTopLevel = options && options._skipMinimizeTopLevel || false; if (len === 0 && _skipMinimizeTopLevel) { delete options._skipMinimizeTopLevel; if (val) { this.$set(val, {}); } return this; } options = Object.assign({}, options, { _skipMinimizeTopLevel: false }); for (let i2 = 0; i2 < len; ++i2) { key = keys[i2]; const pathName = prefix ? prefix + key : key; pathtype = this.$__schema.pathType(pathName); const valForKey = path[key]; if (type === true && !prefix && valForKey != null && pathtype === "nested" && this._doc[key] != null) { delete this._doc[key]; } if (utils.isNonBuiltinObject(valForKey) && pathtype === "nested") { this.$set(pathName, valForKey, constructing, options); $applyDefaultsToNested(this.$get(pathName), pathName, this); continue; } else if (strict) { if (constructing && valForKey === void 0 && this.$get(pathName) !== void 0) { continue; } if (pathtype === "adhocOrUndefined") { pathtype = getEmbeddedDiscriminatorPath(this, pathName, { typeOnly: true }); } if (pathtype === "real" || pathtype === "virtual") { this.$set(pathName, valForKey, constructing, options); } else if (pathtype === "nested" && valForKey instanceof Document) { this.$set( pathName, valForKey.toObject({ transform: false }), constructing, options ); } else if (strict === "throw") { if (pathtype === "nested") { throw new ObjectExpectedError(key, valForKey); } else { throw new StrictModeError(key); } } else if (pathtype === "nested" && valForKey == null) { this.$set(pathName, valForKey, constructing, options); } } else { this.$set(pathName, valForKey, constructing, options); } } const orderedDoc = {}; const orderedKeys = Object.keys(this.$__schema.tree); for (let i2 = 0, len2 = orderedKeys.length; i2 < len2; ++i2) { (key = orderedKeys[i2]) && this._doc.hasOwnProperty(key) && (orderedDoc[key] = void 0); } this._doc = Object.assign(orderedDoc, this._doc); return this; } let pathType = this.$__schema.pathType(path); let parts = null; if (pathType === "adhocOrUndefined") { parts = path.indexOf(".") === -1 ? [path] : path.split("."); pathType = getEmbeddedDiscriminatorPath(this, parts, { typeOnly: true }); } if (pathType === "adhocOrUndefined" && !userSpecifiedStrict) { if (parts == null) { parts = path.indexOf(".") === -1 ? [path] : path.split("."); } const subdocStrict = getSubdocumentStrictValue(this.$__schema, parts); if (subdocStrict !== void 0) { strict = subdocStrict; } } val = handleSpreadDoc(val, true); const priorVal = (() => { if (this.$__.priorDoc != null) { return this.$__.priorDoc.$__getValue(path); } if (constructing) { return void 0; } return this.$__getValue(path); })(); if (pathType === "nested" && val) { if (typeof val === "object" && val != null) { if (val.$__ != null) { val = val.toObject(internalToObjectOptions); } if (val == null) { this.invalidate(path, new MongooseError.CastError("Object", val, path)); return this; } const wasModified = this.$isModified(path); const hasInitialVal = this.$__.savedState != null && this.$__.savedState.hasOwnProperty(path); if (this.$__.savedState != null && !this.$isNew && !this.$__.savedState.hasOwnProperty(path)) { const initialVal = this.$__getValue(path); this.$__.savedState[path] = initialVal; const keys3 = Object.keys(initialVal || {}); for (const key2 of keys3) { this.$__.savedState[path + "." + key2] = initialVal[key2]; } } if (!merge) { this.$__setValue(path, null); cleanModifiedSubpaths(this, path); } else { return this.$set(val, path, constructing, options); } const keys2 = getKeysInSchemaOrder(this.$__schema, val, path); this.$__setValue(path, {}); for (const key2 of keys2) { this.$set(path + "." + key2, val[key2], constructing, { ...options, _skipMarkModified: true }); } if (priorVal != null && (!wasModified || hasInitialVal) && utils.deepEqual(hasInitialVal ? this.$__.savedState[path] : priorVal, val)) { this.unmarkModified(path); } else { this.markModified(path); } return this; } this.invalidate(path, new MongooseError.CastError("Object", val, path)); return this; } let schema; if (parts == null) { parts = path.indexOf(".") === -1 ? [path] : path.split("."); } if (typeof this.$__schema.aliases[parts[0]] === "string") { parts[0] = this.$__schema.aliases[parts[0]]; } if (pathType === "adhocOrUndefined" && strict) { let mixed; for (i = 0; i < parts.length; ++i) { const subpath = parts.slice(0, i + 1).join("."); if (i + 1 < parts.length && this.$__schema.pathType(subpath) === "virtual") { mpath.set(path, val, this); return this; } schema = this.$__schema.path(subpath); if (schema == null) { continue; } if (schema instanceof MixedSchema) { mixed = true; break; } else if (schema.$isSchemaMap && schema.$__schemaType instanceof MixedSchema && i < parts.length - 1) { mixed = true; schema = schema.$__schemaType; break; } } if (schema == null) { schema = getEmbeddedDiscriminatorPath(this, path); } if (!mixed && !schema) { if (strict === "throw") { throw new StrictModeError(path); } return this; } } else if (pathType === "virtual") { schema = this.$__schema.virtualpath(path); schema.applySetters(val, this); return this; } else { schema = this.$__path(path); } let cur = this._doc; let curPath = ""; for (i = 0; i < parts.length - 1; ++i) { cur = cur instanceof Map ? cur.get(parts[i]) : cur[parts[i]]; curPath += (curPath.length !== 0 ? "." : "") + parts[i]; if (!cur) { this.$set(curPath, {}); if (!this.$__isSelected(curPath)) { this.unmarkModified(curPath); } cur = this.$__getValue(curPath); } } let pathToMark; if (parts.length <= 1) { pathToMark = path; } else { const len = parts.length; for (i = 0; i < len; ++i) { const subpath = parts.slice(0, i + 1).join("."); if (this.$get(subpath, null, { getters: false }) === null) { pathToMark = subpath; break; } } if (!pathToMark) { pathToMark = path; } } if (!schema) { this.$__set(pathToMark, path, options, constructing, parts, schema, val, priorVal); if (pathType === "nested" && val == null) { cleanModifiedSubpaths(this, path); } return this; } if (schema.$isSingleNested || schema.$isMongooseArray) { _markValidSubpaths(this, path); } if (val != null && merge && schema.$isSingleNested) { if (val instanceof Document) { val = val.toObject({ virtuals: false, transform: false }); } const keys2 = Object.keys(val); for (const key2 of keys2) { this.$set(path + "." + key2, val[key2], constructing, options); } return this; } let shouldSet = true; try { const refMatches = (() => { if (schema.options == null) { return false; } if (!(val instanceof Document)) { return false; } const model = val.constructor; const refOpt = typeof schema.options.ref === "function" && !schema.options.ref[modelSymbol] ? schema.options.ref.call(this, this) : schema.options.ref; const ref = refOpt?.modelName || refOpt; if (ref != null && (ref === model.modelName || ref === model.baseModelName)) { return true; } const refPath = schema.options.refPath; if (refPath == null) { return false; } const modelName = val.get(refPath); return modelName === model.modelName || modelName === model.baseModelName; })(); let didPopulate = false; if (refMatches && val instanceof Document && (!val.$__.wasPopulated || utils.deepEqual(val.$__.wasPopulated.value, val._doc._id))) { const unpopulatedValue = schema && schema.$isSingleNested ? schema.cast(val, this) : val._doc._id; this.$populated(path, unpopulatedValue, { [populateModelSymbol]: val.constructor }); val.$__.wasPopulated = { value: unpopulatedValue }; didPopulate = true; } let popOpts; const typeKey = this.$__schema.options.typeKey; if (schema.options && Array.isArray(schema.options[typeKey]) && schema.options[typeKey].length && schema.options[typeKey][0] && schema.options[typeKey][0].ref && _isManuallyPopulatedArray(val, schema.options[typeKey][0].ref)) { popOpts = { [populateModelSymbol]: val[0].constructor }; this.$populated(path, val.map(function(v) { return v._doc._id; }), popOpts); for (const doc of val) { doc.$__.wasPopulated = { value: doc._doc._id }; } didPopulate = true; } if (!refMatches || !schema.$isSingleNested || !val.$__) { let setterContext = this; if (this.$__schema.singleNestedPaths[path] != null && parts.length > 1) { setterContext = getDeepestSubdocumentForPath(this, parts, this.schema); } if (options != null && options.overwriteImmutable) { val = schema.applySetters(val, setterContext, false, priorVal, { path, overwriteImmutable: true }); } else { val = schema.applySetters(val, setterContext, false, priorVal, { path }); } } if (Array.isArray(val) && !Array.isArray(schema) && schema.$isMongooseDocumentArray && val.length !== 0 && val[0] != null && val[0].$__ != null && val[0].$__.populated != null) { const populatedPaths = Object.keys(val[0].$__.populated); for (const populatedPath of populatedPaths) { this.$populated( path + "." + populatedPath, val.map((v) => v.$populated(populatedPath)), val[0].$__.populated[populatedPath].options ); } didPopulate = true; } if (!didPopulate && this.$__.populated) { if (Array.isArray(val) && this.$__.populated[path]) { for (let i2 = 0; i2 < val.length; ++i2) { if (val[i2] instanceof Document) { val.set(i2, val[i2]._doc._id, true); } } } delete this.$__.populated[path]; } if (val != null && schema.$isSingleNested) { _checkImmutableSubpaths(val, schema, priorVal); } this.$markValid(path); } catch (e) { if (e instanceof MongooseError.StrictModeError && e.isImmutableError) { this.invalidate(path, e); } else if (e instanceof MongooseError.CastError) { this.invalidate(e.path, e); if (e.$originalErrorPath) { this.invalidate( path, new MongooseError.CastError(schema.instance, val, path, e.$originalErrorPath) ); } } else { this.invalidate( path, new MongooseError.CastError(schema.instance, val, path, e) ); } shouldSet = false; } if (shouldSet) { let savedState = null; let savedStatePath = null; if (!constructing) { const doc = this.$isSubdocument ? this.ownerDocument() : this; savedState = doc.$__.savedState; savedStatePath = this.$isSubdocument ? this.$__.fullPath + "." + path : path; doc.$__saveInitialState(savedStatePath); } this.$__set(pathToMark, path, options, constructing, parts, schema, val, priorVal); const isInTransaction = !!this.$__.session?.transaction; const isModifiedWithinTransaction = this.$__.session && this.$__.session[sessionNewDocuments] && this.$__.session[sessionNewDocuments].has(this) && this.$__.session[sessionNewDocuments].get(this).modifiedPaths && !this.$__.session[sessionNewDocuments].get(this).modifiedPaths.has(savedStatePath); if (savedState != null && savedState.hasOwnProperty(savedStatePath) && (!isInTransaction || isModifiedWithinTransaction) && utils.deepEqual(val, savedState[savedStatePath])) { this.unmarkModified(path); } } if (schema.$isSingleNested && (this.isDirectModified(path) || val == null)) { cleanModifiedSubpaths(this, path); } else if (schema.$isSchemaMap && val == null) { cleanModifiedSubpaths(this, path); } return this; }; function _isManuallyPopulatedArray(val, ref) { if (!Array.isArray(val)) { return false; } if (val.length === 0) { return false; } for (const el of val) { if (!(el instanceof Document)) { return false; } const modelName = el.constructor.modelName; if (modelName == null) { return false; } if (el.constructor.modelName != ref && el.constructor.baseModelName != ref) { return false; } } return true; } Document.prototype.set = Document.prototype.$set; Document.prototype.$__shouldModify = function(pathToMark, path, options, constructing, parts, schema, val, priorVal) { if (options && options._skipMarkModified) { return false; } if (this.$isNew) { return true; } if (path in this.$__.activePaths.getStatePaths("modify")) { return true; } if (val === void 0 && !this.$__isSelected(path)) { return true; } if (val === void 0 && path in this.$__.activePaths.getStatePaths("default")) { return false; } if (this.$populated(path) && val instanceof Document && deepEqual(val._doc._id, priorVal)) { return false; } if (!deepEqual(val, priorVal !== void 0 ? priorVal : utils.getValue(path, this))) { return true; } if (!constructing && val !== null && val !== void 0 && path in this.$__.activePaths.getStatePaths("default") && deepEqual(val, schema.getDefault(this, constructing))) { return true; } return false; }; Document.prototype.$__set = function(pathToMark, path, options, constructing, parts, schema, val, priorVal) { Embedded = Embedded || require_arraySubdocument(); const shouldModify = this.$__shouldModify( pathToMark, path, options, constructing, parts, schema, val, priorVal ); if (shouldModify) { if (this.$__.primitiveAtomics && this.$__.primitiveAtomics[path]) { delete this.$__.primitiveAtomics[path]; if (Object.keys(this.$__.primitiveAtomics).length === 0) { delete this.$__.primitiveAtomics; } } this.markModified(pathToMark); MongooseArray || (MongooseArray = require_array()); if (val && utils.isMongooseArray(val)) { val._registerAtomic("$set", val); if (utils.isMongooseDocumentArray(val)) { val.forEach(function(item) { item && item.__parentArray && (item.__parentArray = val); }); } } } else if (Array.isArray(val) && Array.isArray(priorVal) && utils.isMongooseArray(val) && utils.isMongooseArray(priorVal)) { val[arrayAtomicsSymbol] = priorVal[arrayAtomicsSymbol]; val[arrayAtomicsBackupSymbol] = priorVal[arrayAtomicsBackupSymbol]; if (utils.isMongooseDocumentArray(val)) { val.forEach((doc) => { if (doc != null) { doc.$isNew = false; } }); } } let obj = this._doc; let i = 0; const l = parts.length; let cur = ""; for (; i < l; i++) { const next = i + 1; const last = next === l; cur += cur ? "." + parts[i] : parts[i]; if (specialProperties.has(parts[i])) { continue; } if (last) { if (obj instanceof Map) { obj.set(parts[i], val); } else if (obj.$isSingleNested) { if (!(parts[i] in obj)) { obj[parts[i]] = val; obj._doc[parts[i]] = val; } else { obj._doc[parts[i]] = val; } if (shouldModify) { obj.markModified(parts[i]); } } else { obj[parts[i]] = val; } } else { const isMap = obj instanceof Map; let value = isMap ? obj.get(parts[i]) : obj[parts[i]]; if (utils.isPOJO(value)) { obj = value; } else if (value && value instanceof Embedded) { obj = value; } else if (value && !Array.isArray(value) && value.$isSingleNested) { obj = value; } else if (value && Array.isArray(value)) { obj = value; } else if (value == null) { value = {}; if (isMap) { obj.set(parts[i], value); } else { obj[parts[i]] = value; } obj = value; } else { obj = value; } } } }; Document.prototype.$__getValue = function(path) { if (typeof path !== "string" && !Array.isArray(path)) { throw new TypeError( `Invalid \`path\`. Must be either string or array. Got "${path}" (type ${typeof path})` ); } return utils.getValue(path, this._doc); }; Document.prototype.$inc = function $inc(path, val) { if (val == null) { val = 1; } if (Array.isArray(path)) { path.forEach((p) => this.$inc(p, val)); return this; } const schemaType = this.$__path(path); if (schemaType == null) { if (this.$__.strictMode === "throw") { throw new StrictModeError(path); } else if (this.$__.strictMode === true) { return this; } } else if (schemaType.instance !== "Number") { this.invalidate(path, new MongooseError.CastError(schemaType.instance, val, path)); return this; } const currentValue = this.$__getValue(path) || 0; let shouldSet = false; let valToSet = null; let valToInc = val; try { val = schemaType.cast(val); valToSet = schemaType.applySetters(currentValue + val, this); valToInc = valToSet - currentValue; shouldSet = true; } catch (err) { this.invalidate(path, new MongooseError.CastError("number", val, path, err)); } if (shouldSet) { this.$__.primitiveAtomics = this.$__.primitiveAtomics || {}; if (this.$__.primitiveAtomics[path] == null) { this.$__.primitiveAtomics[path] = { $inc: valToInc }; } else { this.$__.primitiveAtomics[path].$inc += valToInc; } this.markModified(path); this.$__setValue(path, valToSet); } return this; }; Document.prototype.$__setValue = function(path, val) { utils.setValue(path, val, this._doc); return this; }; Document.prototype.get = function(path, type, options) { let adhoc; if (options == null) { options = {}; } if (type) { adhoc = this.$__schema.interpretAsType(path, type, this.$__schema.options); } const noDottedPath = options.noDottedPath; let schema = noDottedPath ? this.$__schema.paths[path] : this.$__path(path); if (schema == null) { schema = this.$__schema.virtualpath(path); if (schema != null) { return schema.applyGetters(void 0, this); } } if (noDottedPath) { let obj2 = this._doc[path]; if (adhoc) { obj2 = adhoc.cast(obj2); } if (schema != null && options.getters !== false) { return schema.applyGetters(obj2, this); } return obj2; } if (schema != null && schema.instance === "Mixed") { const virtual = this.$__schema.virtualpath(path); if (virtual != null) { schema = virtual; } } const hasDot = path.indexOf(".") !== -1; let obj = this._doc; const pieces = hasDot ? path.split(".") : [path]; if (typeof this.$__schema.aliases[pieces[0]] === "string") { pieces[0] = this.$__schema.aliases[pieces[0]]; } for (let i = 0, l = pieces.length; i < l; i++) { if (obj && obj._doc) { obj = obj._doc; } if (obj == null) { obj = void 0; } else if (obj instanceof Map) { obj = obj.get(pieces[i], { getters: false }); } else if (i === l - 1) { obj = utils.getValue(pieces[i], obj); } else { obj = obj[pieces[i]]; } } if (adhoc) { obj = adhoc.cast(obj); } if (schema != null && options.getters !== false) { obj = schema.applyGetters(obj, this); } else if (this.$__schema.nested[path] && options.virtuals) { return applyVirtuals(this, clone(obj) || {}, { path }); } return obj; }; Document.prototype[getSymbol] = Document.prototype.get; Document.prototype.$get = Document.prototype.get; Document.prototype.$__path = function(path) { const adhocs = this.$__.adhocPaths; const adhocType = adhocs && adhocs.hasOwnProperty(path) ? adhocs[path] : null; if (adhocType) { return adhocType; } return this.$__schema.path(path); }; Document.prototype.markModified = function(path, scope) { this.$__saveInitialState(path); this.$__.activePaths.modify(path); if (scope != null && !this.$isSubdocument) { this.$__.pathsToScopes = this.$__pathsToScopes || {}; this.$__.pathsToScopes[path] = scope; } }; Document.prototype.$__saveInitialState = function $__saveInitialState(path) { const savedState = this.$__.savedState; const savedStatePath = path; if (savedState != null) { const firstDot = savedStatePath.indexOf("."); const topLevelPath = firstDot === -1 ? savedStatePath : savedStatePath.slice(0, firstDot); if (!savedState.hasOwnProperty(topLevelPath)) { savedState[topLevelPath] = clone(this.$__getValue(topLevelPath)); } } }; Document.prototype.unmarkModified = function(path) { this.$__.activePaths.init(path); if (this.$__.pathsToScopes != null) { delete this.$__.pathsToScopes[path]; } }; Document.prototype.$ignore = function(path) { this.$__.activePaths.ignore(path); }; Document.prototype.directModifiedPaths = function() { return Object.keys(this.$__.activePaths.getStatePaths("modify")); }; Document.prototype.$isEmpty = function(path) { const isEmptyOptions = { minimize: true, virtuals: false, getters: false, transform: false }; if (arguments.length !== 0) { const v = this.$get(path); if (v == null) { return true; } if (typeof v !== "object") { return false; } if (utils.isPOJO(v)) { return _isEmpty(v); } return Object.keys(v.toObject(isEmptyOptions)).length === 0; } return Object.keys(this.toObject(isEmptyOptions)).length === 0; }; function _isEmpty(v) { if (v == null) { return true; } if (typeof v !== "object" || Array.isArray(v)) { return false; } for (const key of Object.keys(v)) { if (!_isEmpty(v[key])) { return false; } } return true; } Document.prototype.modifiedPaths = function(options) { options = options || {}; const directModifiedPaths = Object.keys(this.$__.activePaths.getStatePaths("modify")); const result = /* @__PURE__ */ new Set(); let i = 0; let j = 0; const len = directModifiedPaths.length; for (i = 0; i < len; ++i) { const path = directModifiedPaths[i]; const parts = parentPaths(path); const pLen = parts.length; for (j = 0; j < pLen; ++j) { result.add(parts[j]); } if (!options.includeChildren) { continue; } let ii = 0; let cur = this.$get(path); if (typeof cur === "object" && cur !== null) { if (cur._doc) { cur = cur._doc; } const len2 = cur.length; if (Array.isArray(cur)) { for (ii = 0; ii < len2; ++ii) { const subPath = path + "." + ii; if (!result.has(subPath)) { result.add(subPath); if (cur[ii] != null && cur[ii].$__) { const modified = cur[ii].modifiedPaths(); let iii = 0; const iiiLen = modified.length; for (iii = 0; iii < iiiLen; ++iii) { result.add(subPath + "." + modified[iii]); } } } } } else { const keys = Object.keys(cur); let ii2 = 0; const len3 = keys.length; for (ii2 = 0; ii2 < len3; ++ii2) { result.add(path + "." + keys[ii2]); } } } } return Array.from(result); }; Document.prototype[documentModifiedPaths] = Document.prototype.modifiedPaths; Document.prototype.isModified = function(paths, options, modifiedPaths) { if (paths) { const ignoreAtomics = options && options.ignoreAtomics; const directModifiedPathsObj = this.$__.activePaths.states.modify; if (directModifiedPathsObj == null) { return false; } if (typeof paths === "string") { paths = paths.indexOf(" ") === -1 ? [paths] : paths.split(" "); } for (const path of paths) { if (directModifiedPathsObj[path] != null) { return true; } } const modified = modifiedPaths || this[documentModifiedPaths](); const isModifiedChild = paths.some(function(path) { return !!~modified.indexOf(path); }); let directModifiedPaths = Object.keys(directModifiedPathsObj); if (ignoreAtomics) { directModifiedPaths = directModifiedPaths.filter((path) => { const value = this.$__getValue(path); if (value != null && value[arrayAtomicsSymbol] != null && value[arrayAtomicsSymbol].$set === void 0) { return false; } return true; }); } return isModifiedChild || paths.some(function(path) { return directModifiedPaths.some(function(mod) { return mod === path || path.startsWith(mod + "."); }); }); } return this.$__.activePaths.some("modify"); }; Document.prototype.$isModified = Document.prototype.isModified; Document.prototype[documentIsModified] = Document.prototype.isModified; Document.prototype.$isDefault = function(path) { if (path == null) { return this.$__.activePaths.some("default"); } if (typeof path === "string" && path.indexOf(" ") === -1) { return this.$__.activePaths.getStatePaths("default").hasOwnProperty(path); } let paths = path; if (!Array.isArray(paths)) { paths = paths.split(" "); } return paths.some((path2) => this.$__.activePaths.getStatePaths("default").hasOwnProperty(path2)); }; Document.prototype.$isDeleted = function(val) { if (arguments.length === 0) { return !!this.$__.isDeleted; } this.$__.isDeleted = !!val; return this; }; Document.prototype.isDirectModified = function(path) { if (path == null) { return this.$__.activePaths.some("modify"); } if (typeof path === "string" && path.indexOf(" ") === -1) { const res = this.$__.activePaths.getStatePaths("modify").hasOwnProperty(path); if (res || path.indexOf(".") === -1) { return res; } const pieces = path.split("."); for (let i = 0; i < pieces.length - 1; ++i) { const subpath = pieces.slice(0, i + 1).join("."); const subdoc = this.$get(subpath); if (subdoc != null && subdoc.$__ != null && subdoc.isDirectModified(pieces.slice(i + 1).join("."))) { return true; } } return false; } let paths = path; if (typeof paths === "string") { paths = paths.split(" "); } return paths.some((path2) => this.isDirectModified(path2)); }; Document.prototype.isInit = function(path) { if (path == null) { return this.$__.activePaths.some("init"); } if (typeof path === "string" && path.indexOf(" ") === -1) { return this.$__.activePaths.getStatePaths("init").hasOwnProperty(path); } let paths = path; if (!Array.isArray(paths)) { paths = paths.split(" "); } return paths.some((path2) => this.$__.activePaths.getStatePaths("init").hasOwnProperty(path2)); }; Document.prototype.isSelected = function isSelected(path) { if (this.$__.selected == null) { return true; } if (!path) { return false; } if (path === "_id") { return this.$__.selected._id !== 0; } if (path.indexOf(" ") !== -1) { path = path.split(" "); } if (Array.isArray(path)) { return path.some((p) => this.$__isSelected(p)); } const paths = Object.keys(this.$__.selected); let inclusive = null; if (paths.length === 1 && paths[0] === "_id") { return this.$__.selected._id === 0; } for (const cur of paths) { if (cur === "_id") { continue; } if (!isDefiningProjection(this.$__.selected[cur])) { continue; } inclusive = !!this.$__.selected[cur]; break; } if (inclusive === null) { return true; } if (path in this.$__.selected) { return inclusive; } const pathDot = path + "."; for (const cur of paths) { if (cur === "_id") { continue; } if (cur.startsWith(pathDot)) { return inclusive || cur !== pathDot; } if (pathDot.startsWith(cur + ".")) { return inclusive; } } return !inclusive; }; Document.prototype.$__isSelected = Document.prototype.isSelected; Document.prototype.isDirectSelected = function isDirectSelected(path) { if (this.$__.selected == null) { return true; } if (path === "_id") { return this.$__.selected._id !== 0; } if (path.indexOf(" ") !== -1) { path = path.split(" "); } if (Array.isArray(path)) { return path.some((p) => this.isDirectSelected(p)); } const paths = Object.keys(this.$__.selected); let inclusive = null; if (paths.length === 1 && paths[0] === "_id") { return this.$__.selected._id === 0; } for (const cur of paths) { if (cur === "_id") { continue; } if (!isDefiningProjection(this.$__.selected[cur])) { continue; } inclusive = !!this.$__.selected[cur]; break; } if (inclusive === null) { return true; } if (this.$__.selected.hasOwnProperty(path)) { return inclusive; } return !inclusive; }; Document.prototype.validate = async function validate(pathsToValidate, options) { if (typeof pathsToValidate === "function" || typeof options === "function" || typeof arguments[2] === "function") { throw new MongooseError("Document.prototype.validate() no longer accepts a callback"); } this.$op = "validate"; if (arguments.length === 1) { if (typeof arguments[0] === "object" && !Array.isArray(arguments[0])) { options = arguments[0]; pathsToValidate = null; } } if (options && typeof options.pathsToSkip === "string") { const isOnePathOnly = options.pathsToSkip.indexOf(" ") === -1; options.pathsToSkip = isOnePathOnly ? [options.pathsToSkip] : options.pathsToSkip.split(" "); } const _skipParallelValidateCheck = options && options._skipParallelValidateCheck; if (this.$isSubdocument != null) { } else if (this.$__.validating && !_skipParallelValidateCheck) { throw new ParallelValidateError(this); } else if (!_skipParallelValidateCheck) { this.$__.validating = true; } return new Promise((resolve, reject) => { this.$__validate(pathsToValidate, options, (error) => { this.$op = null; this.$__.validating = null; if (error != null) { return reject(error); } resolve(); }); }); }; Document.prototype.$validate = Document.prototype.validate; function _evaluateRequiredFunctions(doc) { const requiredFields = Object.keys(doc.$__.activePaths.getStatePaths("require")); let i = 0; const len = requiredFields.length; for (i = 0; i < len; ++i) { const path = requiredFields[i]; const p = doc.$__schema.path(path); if (p != null && typeof p.originalRequiredValue === "function") { doc.$__.cachedRequired = doc.$__.cachedRequired || {}; try { doc.$__.cachedRequired[path] = p.originalRequiredValue.call(doc, doc); } catch (err) { doc.invalidate(path, err); } } } } function _getPathsToValidate(doc, pathsToValidate, pathsToSkip, isNestedValidate) { const doValidateOptions = {}; _evaluateRequiredFunctions(doc); let paths = new Set(Object.keys(doc.$__.activePaths.getStatePaths("require")).filter(function(path) { if (!doc.$__isSelected(path) && !doc.$isModified(path)) { return false; } if (path.endsWith(".$*")) { return false; } if (doc.$__.cachedRequired != null && path in doc.$__.cachedRequired) { return doc.$__.cachedRequired[path]; } return true; })); Object.keys(doc.$__.activePaths.getStatePaths("init")).forEach(addToPaths); Object.keys(doc.$__.activePaths.getStatePaths("modify")).forEach(addToPaths); Object.keys(doc.$__.activePaths.getStatePaths("default")).forEach(addToPaths); function addToPaths(p) { if (p.endsWith(".$*")) { return; } paths.add(p); } if (!isNestedValidate) { const topLevelSubdocs = []; for (const path of Object.keys(doc.$__schema.paths)) { const schemaType = doc.$__schema.path(path); if (schemaType.$isSingleNested) { const subdoc = doc.$get(path); if (subdoc) { topLevelSubdocs.push(subdoc); } } else if (schemaType.$isMongooseDocumentArray) { const arr = doc.$get(path); if (arr && arr.length) { for (const subdoc of arr) { if (subdoc) { topLevelSubdocs.push(subdoc); } } } } } const modifiedPaths = doc.modifiedPaths(); for (const subdoc of topLevelSubdocs) { if (subdoc.$basePath) { const fullPathToSubdoc = subdoc.$__pathRelativeToParent(); for (const modifiedPath of subdoc.modifiedPaths()) { paths.delete(fullPathToSubdoc + "." + modifiedPath); } const subdocParent = subdoc.$parent(); if (subdocParent == null) { throw new Error("Cannot validate subdocument that does not have a parent"); } if (doc.$isModified(fullPathToSubdoc, null, modifiedPaths) && // Avoid using isDirectModified() here because that does additional checks on whether the parent path // is direct modified, which can cause performance issues re: gh-14897 !subdocParent.$__.activePaths.getStatePaths("modify").hasOwnProperty(fullPathToSubdoc) && !subdocParent.$isDefault(fullPathToSubdoc)) { paths.add(fullPathToSubdoc); if (doc.$__.pathsToScopes == null) { doc.$__.pathsToScopes = {}; } doc.$__.pathsToScopes[fullPathToSubdoc] = subdoc.$isDocumentArrayElement ? subdoc.__parentArray : subdoc.$parent(); doValidateOptions[fullPathToSubdoc] = { skipSchemaValidators: true }; if (subdoc.$isDocumentArrayElement && subdoc.__index != null) { doValidateOptions[fullPathToSubdoc].index = subdoc.__index; } } } } } for (const path of paths) { const _pathType = doc.$__schema.path(path); if (!_pathType) { continue; } if (_pathType.$isMongooseDocumentArray) { for (const p of paths) { if (p == null || p.startsWith(_pathType.path + ".")) { paths.delete(p); } } } if (!_pathType.caster && _pathType.validators.length === 0 && !_pathType.$parentSchemaDocArray) { paths.delete(path); } else if (_pathType.$isMongooseArray && !_pathType.$isMongooseDocumentArray && // Skip document arrays... !_pathType.$embeddedSchemaType.$isMongooseArray && // and arrays of arrays _pathType.validators.length === 0 && // and arrays with top-level validators _pathType.$embeddedSchemaType.validators.length === 0) { paths.delete(path); } } if (Array.isArray(pathsToValidate)) { paths = _handlePathsToValidate(paths, pathsToValidate); } else if (Array.isArray(pathsToSkip)) { paths = _handlePathsToSkip(paths, pathsToSkip); } _addArrayPathsToValidate(doc, paths); const flattenOptions = { skipArrays: true }; for (const pathToCheck of paths) { if (doc.$__schema.nested[pathToCheck]) { let _v = doc.$__getValue(pathToCheck); if (isMongooseObject(_v)) { _v = _v.toObject({ transform: false }); } const flat = flatten(_v, pathToCheck, flattenOptions, doc.$__schema); Object.keys(flat).filter((path) => !doc.$__schema.singleNestedPaths.hasOwnProperty(path)).forEach(addToPaths); } } for (const path of paths) { const _pathType = doc.$__schema.path(path); if (!_pathType) { continue; } if (_pathType.$parentSchemaDocArray && typeof _pathType.$parentSchemaDocArray.path === "string") { paths.add(_pathType.$parentSchemaDocArray.path); } if (!_pathType.$isSchemaMap) { continue; } const val = doc.$__getValue(path); if (val == null) { continue; } for (const key of val.keys()) { paths.add(path + "." + key); } } paths = Array.from(paths); return [paths, doValidateOptions]; } function _addArrayPathsToValidate(doc, paths) { for (const path of paths) { const _pathType = doc.$__schema.path(path); if (!_pathType) { continue; } if (!_pathType.$isMongooseArray || // To avoid potential performance issues, skip doc arrays whose children // are not required. `getPositionalPathType()` may be slow, so avoid // it unless we have a case of #6364 !Array.isArray(_pathType) && _pathType.$isMongooseDocumentArray && !(_pathType && _pathType.schemaOptions && _pathType.schemaOptions.required)) { continue; } if (_pathType.$isMongooseArray && !_pathType.$isMongooseDocumentArray && // Skip document arrays... !_pathType.$embeddedSchemaType.$isMongooseArray && // and arrays of arrays _pathType.$embeddedSchemaType.validators.length === 0) { continue; } const val = doc.$__getValue(path); _pushNestedArrayPaths(val, paths, path); } } function _pushNestedArrayPaths(val, paths, path) { if (val != null) { const numElements = val.length; for (let j = 0; j < numElements; ++j) { if (Array.isArray(val[j])) { _pushNestedArrayPaths(val[j], paths, path + "." + j); } else { paths.add(path + "." + j); } } } } Document.prototype.$__validate = function(pathsToValidate, options, callback) { if (this.$__.saveOptions && this.$__.saveOptions.pathsToSave && !pathsToValidate) { pathsToValidate = [...this.$__.saveOptions.pathsToSave]; } else if (typeof pathsToValidate === "function") { callback = pathsToValidate; options = null; pathsToValidate = null; } else if (typeof options === "function") { callback = options; options = null; } const hasValidateModifiedOnlyOption = options && typeof options === "object" && "validateModifiedOnly" in options; const pathsToSkip = options && options.pathsToSkip || null; let shouldValidateModifiedOnly; if (hasValidateModifiedOnlyOption) { shouldValidateModifiedOnly = !!options.validateModifiedOnly; } else { shouldValidateModifiedOnly = this.$__schema.options.validateModifiedOnly; } const validateAllPaths = options && options.validateAllPaths; if (validateAllPaths) { if (pathsToSkip) { throw new TypeError("Cannot set both `validateAllPaths` and `pathsToSkip`"); } if (pathsToValidate) { throw new TypeError("Cannot set both `validateAllPaths` and `pathsToValidate`"); } if (hasValidateModifiedOnlyOption && shouldValidateModifiedOnly) { throw new TypeError("Cannot set both `validateAllPaths` and `validateModifiedOnly`"); } } const _this = this; const _complete = () => { let validationError = this.$__.validationError; this.$__.validationError = null; this.$__.validating = null; if (shouldValidateModifiedOnly && validationError != null) { const errors = Object.keys(validationError.errors); for (const errPath of errors) { if (!this.$isModified(errPath)) { delete validationError.errors[errPath]; } } if (Object.keys(validationError.errors).length === 0) { validationError = void 0; } } this.$__.cachedRequired = {}; this.$emit("validate", _this); this.constructor.emit("validate", _this); if (validationError) { for (const key in validationError.errors) { if (!this[documentArrayParent] && validationError.errors[key] instanceof MongooseError.CastError) { this.invalidate(key, validationError.errors[key]); } } return validationError; } }; let paths; let doValidateOptionsByPath; if (validateAllPaths) { paths = new Set(Object.keys(this.$__schema.paths)); for (const path of paths) { const schemaType = this.$__schema.path(path); if (!schemaType || !schemaType.$isMongooseArray) { continue; } const val = this.$__getValue(path); if (!val) { continue; } _pushNestedArrayPaths(val, paths, path); } paths = [...paths]; doValidateOptionsByPath = {}; } else { const pathDetails = _getPathsToValidate(this, pathsToValidate, pathsToSkip, options && options._nestedValidate); paths = shouldValidateModifiedOnly ? pathDetails[0].filter((path) => this.$isModified(path)) : pathDetails[0]; doValidateOptionsByPath = pathDetails[1]; } if (typeof pathsToValidate === "string") { pathsToValidate = pathsToValidate.split(" "); } if (paths.length === 0) { return immediate(function() { const error = _complete(); if (error) { return _this.$__schema.s.hooks.execPost("validate:error", _this, [_this], { error }, function(error2) { callback(error2); }); } callback(null, _this); }); } const validated = {}; let total = 0; let pathsToSave = this.$__.saveOptions?.pathsToSave; if (Array.isArray(pathsToSave)) { pathsToSave = new Set(pathsToSave); for (const path of paths) { if (!pathsToSave.has(path)) { continue; } validatePath(path); } } else { for (const path of paths) { validatePath(path); } } function validatePath(path) { if (path == null || validated[path]) { return; } validated[path] = true; total++; immediate(function() { const schemaType = _this.$__schema.path(path); if (!schemaType) { return --total || complete(); } if (!_this.$isValid(path)) { --total || complete(); return; } if (schemaType[schemaMixedSymbol] != null && path !== schemaType.path) { return --total || complete(); } let val = _this.$__getValue(path); let pop; if (pop = _this.$populated(path)) { val = pop; } else if (val != null && val.$__ != null && val.$__.wasPopulated) { val = val._doc._id; } const scope = _this.$__.pathsToScopes != null && path in _this.$__.pathsToScopes ? _this.$__.pathsToScopes[path] : _this; const doValidateOptions = { ...doValidateOptionsByPath[path], path, validateAllPaths, _nestedValidate: true }; schemaType.doValidate(val, function(err) { if (err) { const isSubdoc = schemaType.$isSingleNested || schemaType.$isArraySubdocument || schemaType.$isMongooseDocumentArray; if (isSubdoc && err instanceof ValidationError) { return --total || complete(); } _this.invalidate(path, err, void 0, true); } --total || complete(); }, scope, doValidateOptions); }); } function complete() { const error = _complete(); if (error) { return _this.$__schema.s.hooks.execPost("validate:error", _this, [_this], { error }, function(error2) { callback(error2); }); } callback(null, _this); } }; function _handlePathsToValidate(paths, pathsToValidate) { const _pathsToValidate = new Set(pathsToValidate); const parentPaths2 = /* @__PURE__ */ new Map([]); for (const path of pathsToValidate) { if (path.indexOf(".") === -1) { continue; } const pieces = path.split("."); let cur = pieces[0]; for (let i = 1; i < pieces.length; ++i) { parentPaths2.set(cur, path); cur = cur + "." + pieces[i]; } } const ret = /* @__PURE__ */ new Set(); for (const path of paths) { if (_pathsToValidate.has(path)) { ret.add(path); } else if (parentPaths2.has(path)) { ret.add(parentPaths2.get(path)); } } return ret; } function _handlePathsToSkip(paths, pathsToSkip) { pathsToSkip = new Set(pathsToSkip); paths = Array.from(paths).filter((p) => !pathsToSkip.has(p)); return new Set(paths); } Document.prototype.validateSync = function(pathsToValidate, options) { const _this = this; if (arguments.length === 1 && typeof arguments[0] === "object" && !Array.isArray(arguments[0])) { options = arguments[0]; pathsToValidate = null; } const hasValidateModifiedOnlyOption = options && typeof options === "object" && "validateModifiedOnly" in options; let shouldValidateModifiedOnly; if (hasValidateModifiedOnlyOption) { shouldValidateModifiedOnly = !!options.validateModifiedOnly; } else { shouldValidateModifiedOnly = this.$__schema.options.validateModifiedOnly; } let pathsToSkip = options && options.pathsToSkip; const validateAllPaths = options && options.validateAllPaths; if (validateAllPaths) { if (pathsToSkip) { throw new TypeError("Cannot set both `validateAllPaths` and `pathsToSkip`"); } if (pathsToValidate) { throw new TypeError("Cannot set both `validateAllPaths` and `pathsToValidate`"); } } if (typeof pathsToValidate === "string") { const isOnePathOnly = pathsToValidate.indexOf(" ") === -1; pathsToValidate = isOnePathOnly ? [pathsToValidate] : pathsToValidate.split(" "); } else if (typeof pathsToSkip === "string" && pathsToSkip.indexOf(" ") !== -1) { pathsToSkip = pathsToSkip.split(" "); } let paths; let skipSchemaValidators; if (validateAllPaths) { paths = new Set(Object.keys(this.$__schema.paths)); for (const path of paths) { const schemaType = this.$__schema.path(path); if (!schemaType || !schemaType.$isMongooseArray) { continue; } const val = this.$__getValue(path); if (!val) { continue; } _pushNestedArrayPaths(val, paths, path); } paths = [...paths]; skipSchemaValidators = {}; } else { const pathDetails = _getPathsToValidate(this, pathsToValidate, pathsToSkip); paths = shouldValidateModifiedOnly ? pathDetails[0].filter((path) => this.$isModified(path)) : pathDetails[0]; skipSchemaValidators = pathDetails[1]; } const validating = {}; for (let i = 0, len = paths.length; i < len; ++i) { const path = paths[i]; if (validating[path]) { continue; } validating[path] = true; const p = _this.$__schema.path(path); if (!p) { continue; } if (!_this.$isValid(path)) { continue; } const val = _this.$__getValue(path); const err2 = p.doValidateSync(val, _this, { skipSchemaValidators: skipSchemaValidators[path], path, validateModifiedOnly: shouldValidateModifiedOnly, validateAllPaths }); if (err2) { const isSubdoc = p.$isSingleNested || p.$isArraySubdocument || p.$isMongooseDocumentArray; if (isSubdoc && err2 instanceof ValidationError) { continue; } _this.invalidate(path, err2, void 0, true); } } const err = _this.$__.validationError; _this.$__.validationError = void 0; _this.$emit("validate", _this); _this.constructor.emit("validate", _this); if (err) { for (const key in err.errors) { if (err.errors[key] instanceof MongooseError.CastError) { _this.invalidate(key, err.errors[key]); } } } return err; }; Document.prototype.invalidate = function(path, err, val, kind) { if (!this.$__.validationError) { this.$__.validationError = new ValidationError(this); } if (this.$__.validationError.errors[path]) { return; } if (!err || typeof err === "string") { err = new ValidatorError({ path, message: err, type: kind || "user defined", value: val }); } if (this.$__.validationError === err) { return this.$__.validationError; } this.$__.validationError.addError(path, err); return this.$__.validationError; }; Document.prototype.$markValid = function(path) { if (!this.$__.validationError || !this.$__.validationError.errors[path]) { return; } delete this.$__.validationError.errors[path]; if (Object.keys(this.$__.validationError.errors).length === 0) { this.$__.validationError = null; } }; function _markValidSubpaths(doc, path) { if (!doc.$__.validationError) { return; } const keys = Object.keys(doc.$__.validationError.errors); for (const key of keys) { if (key.startsWith(path + ".")) { delete doc.$__.validationError.errors[key]; } } if (Object.keys(doc.$__.validationError.errors).length === 0) { doc.$__.validationError = null; } } function _checkImmutableSubpaths(subdoc, schematype, priorVal) { const schema = schematype.schema; if (schema == null) { return; } for (const key of Object.keys(schema.paths)) { const path = schema.paths[key]; if (path.$immutableSetter == null) { continue; } const oldVal = priorVal == null ? void 0 : priorVal.$__getValue(key); path.$immutableSetter.call(subdoc, oldVal); } } Document.prototype.$isValid = function(path) { if (this.$__.validationError == null || Object.keys(this.$__.validationError.errors).length === 0) { return true; } if (path == null) { return false; } if (path.indexOf(" ") !== -1) { path = path.split(" "); } if (Array.isArray(path)) { return path.some((p) => this.$__.validationError.errors[p] == null); } return this.$__.validationError.errors[path] == null; }; Document.prototype.$__reset = function reset() { let _this = this; const subdocs = !this.$isSubdocument ? this.$getAllSubdocs({ useCache: true }) : null; if (subdocs && subdocs.length > 0) { for (const subdoc of subdocs) { subdoc.$__reset(); } } this.$__dirty().forEach(function(dirt) { const type = dirt.value; if (type && type[arrayAtomicsSymbol]) { type[arrayAtomicsBackupSymbol] = type[arrayAtomicsSymbol]; type[arrayAtomicsSymbol] = {}; } }); this.$__.backup = {}; this.$__.backup.activePaths = { modify: Object.assign({}, this.$__.activePaths.getStatePaths("modify")), default: Object.assign({}, this.$__.activePaths.getStatePaths("default")) }; this.$__.backup.validationError = this.$__.validationError; this.$__.backup.errors = this.$errors; this.$__.activePaths.clear("modify"); this.$__.activePaths.clear("default"); this.$__.validationError = void 0; this.$errors = void 0; _this = this; this.$__schema.requiredPaths().forEach(function(path) { _this.$__.activePaths.require(path); }); return this; }; Document.prototype.$__undoReset = function $__undoReset() { if (this.$__.backup == null || this.$__.backup.activePaths == null) { return; } this.$__.activePaths.states.modify = this.$__.backup.activePaths.modify; this.$__.activePaths.states.default = this.$__.backup.activePaths.default; this.$__.validationError = this.$__.backup.validationError; this.$errors = this.$__.backup.errors; for (const dirt of this.$__dirty()) { const type = dirt.value; if (type && type[arrayAtomicsSymbol] && type[arrayAtomicsBackupSymbol]) { type[arrayAtomicsSymbol] = type[arrayAtomicsBackupSymbol]; } } if (!this.$isSubdocument) { for (const subdoc of this.$getAllSubdocs()) { subdoc.$__undoReset(); } } }; Document.prototype.$__dirty = function() { const _this = this; let all = this.$__.activePaths.map("modify", function(path) { return { path, value: _this.$__getValue(path), schema: _this.$__path(path) }; }); all = all.concat(this.$__.activePaths.map("default", function(path) { if (path === "_id" || _this.$__getValue(path) == null) { return; } return { path, value: _this.$__getValue(path), schema: _this.$__path(path) }; })); const allPaths = new Map(all.filter((el) => el != null).map((el) => [el.path, el.value])); const minimal = []; all.forEach(function(item) { if (!item) { return; } let top = null; const array = parentPaths(item.path); for (let i = 0; i < array.length - 1; i++) { if (allPaths.has(array[i])) { top = allPaths.get(array[i]); break; } } if (top == null) { minimal.push(item); } else if (top != null && top[arrayAtomicsSymbol] != null && top.hasAtomics()) { top[arrayAtomicsSymbol] = {}; top[arrayAtomicsSymbol].$set = top; } }); return minimal; }; Document.prototype.$__setSchema = function(schema) { compile(schema.tree, this, void 0, schema.options); for (const key of Object.keys(schema.virtuals)) { schema.virtuals[key]._applyDefaultGetters(); } if (schema.path("schema") == null) { this.schema = schema; } this.$__schema = schema; this[documentSchemaSymbol] = schema; }; Document.prototype.$__getArrayPathsToValidate = function() { DocumentArray || (DocumentArray = require_documentArray()); return this.$__.activePaths.map("init", "modify", function(i) { return this.$__getValue(i); }.bind(this)).filter(function(val) { return val && Array.isArray(val) && utils.isMongooseDocumentArray(val) && val.length; }).reduce(function(seed, array) { return seed.concat(array); }, []).filter(function(doc) { return doc; }); }; Document.prototype.$getAllSubdocs = function(options) { if (options?.useCache && this.$__.saveOptions?.__subdocs) { return this.$__.saveOptions.__subdocs; } DocumentArray || (DocumentArray = require_documentArray()); Embedded = Embedded || require_arraySubdocument(); const subDocs = []; function getSubdocs(doc) { const newSubdocs = []; for (const { model } of doc.$__schema.childSchemas) { const val = doc.$__getValue(model.path); if (val == null) { continue; } if (val.$__) { newSubdocs.push(val); } if (Array.isArray(val)) { for (const el of val) { if (el != null && el.$__) { newSubdocs.push(el); } } } if (val instanceof Map) { for (const el of val.values()) { if (el != null && el.$__) { newSubdocs.push(el); } } } } for (const subdoc of newSubdocs) { getSubdocs(subdoc); } subDocs.push(...newSubdocs); } getSubdocs(this); if (this.$__.saveOptions) { this.$__.saveOptions.__subdocs = subDocs; } return subDocs; }; function applyQueue(doc) { const q = doc.$__schema && doc.$__schema.callQueue; if (!q.length) { return; } for (const pair of q) { if (pair[0] !== "pre" && pair[0] !== "post" && pair[0] !== "on") { doc[pair[0]].apply(doc, pair[1]); } } } Document.prototype.$__handleReject = function handleReject(err) { if (this.$listeners("error").length) { this.$emit("error", err); } else if (this.constructor.listeners && this.constructor.listeners("error").length) { this.constructor.emit("error", err); } }; Document.prototype.$toObject = function(options, json) { const defaultOptions = this.$__schema._defaultToObjectOptions(json); const hasOnlyPrimitiveValues = this.$__hasOnlyPrimitiveValues(); options = utils.isPOJO(options) ? { ...options } : {}; options._calledWithOptions = options._calledWithOptions || { ...options }; let _minimize; if (options._calledWithOptions.minimize != null) { _minimize = options.minimize; } else if (this.$__schemaTypeOptions?.minimize != null) { _minimize = this.$__schemaTypeOptions.minimize; } else if (defaultOptions != null && defaultOptions.minimize != null) { _minimize = defaultOptions.minimize; } else { _minimize = this.$__schema.options.minimize; } options.minimize = _minimize; if (!hasOnlyPrimitiveValues) { options._seen = options._seen || /* @__PURE__ */ new Map(); } const depopulate = options._calledWithOptions.depopulate ?? defaultOptions?.depopulate ?? options.depopulate ?? false; if (depopulate && options._isNested && this.$__.wasPopulated) { return clone(this.$__.wasPopulated.value || this._doc._id, options); } if (depopulate) { options.depopulate = true; } if (defaultOptions != null) { for (const key of Object.keys(defaultOptions)) { if (options[key] == null) { options[key] = defaultOptions[key]; } } } options._isNested = true; options.json = json; options.minimize = _minimize; const parentOptions = options._parentOptions; options._parentOptions = this.$isSubdocument ? options : null; const schemaFieldsOnly = options._calledWithOptions.schemaFieldsOnly ?? options.schemaFieldsOnly ?? defaultOptions.schemaFieldsOnly ?? false; let ret; if (hasOnlyPrimitiveValues && !options.flattenObjectIds) { ret = this.$__toObjectShallow(schemaFieldsOnly); } else if (schemaFieldsOnly) { ret = {}; for (const path of Object.keys(this.$__schema.paths)) { const value = this.$__getValue(path); if (value === void 0) { continue; } let pathToSet = path; let objToSet = ret; if (path.indexOf(".") !== -1) { const segments = path.split("."); pathToSet = segments[segments.length - 1]; for (let i = 0; i < segments.length - 1; ++i) { objToSet[segments[i]] = objToSet[segments[i]] ?? {}; objToSet = objToSet[segments[i]]; } } if (value === null) { objToSet[pathToSet] = null; continue; } objToSet[pathToSet] = clone(value, options); } } else { ret = clone(this._doc, options) || {}; } const getters = options._calledWithOptions.getters ?? options.getters ?? defaultOptions.getters ?? false; if (getters) { applyGetters(this, ret); if (options.minimize) { ret = minimize(ret) || {}; } } const virtuals = options._calledWithOptions.virtuals ?? defaultOptions.virtuals ?? parentOptions?.virtuals ?? void 0; if (virtuals || getters && virtuals !== false) { applyVirtuals(this, ret, options, options); } if (options.versionKey === false && this.$__schema.options.versionKey) { delete ret[this.$__schema.options.versionKey]; } const transform = options._calledWithOptions.transform ?? true; let transformFunction = void 0; if (transform === true) { transformFunction = defaultOptions.transform; } else if (typeof transform === "function") { transformFunction = transform; } if (transform) { applySchemaTypeTransforms(this, ret); } if (options.useProjection) { omitDeselectedFields(this, ret); } if (typeof transformFunction === "function") { const xformed = transformFunction(this, ret, options); if (typeof xformed !== "undefined") { ret = xformed; } } return ret; }; Document.prototype.$__toObjectShallow = function $__toObjectShallow(schemaFieldsOnly) { const ret = {}; if (this._doc != null) { const keys = schemaFieldsOnly ? Object.keys(this.$__schema.paths) : Object.keys(this._doc); for (const key of keys) { const value = this._doc[key]; if (value instanceof Date) { ret[key] = new Date(value); } else if (value !== void 0) { ret[key] = value; } } } return ret; }; Document.prototype.toObject = function(options) { return this.$toObject(options); }; function applyVirtuals(self2, json, options, toObjectOptions) { const schema = self2.$__schema; const virtuals = schema.virtuals; const paths = Object.keys(virtuals); let i = paths.length; const numPaths = i; let path; let assignPath; let cur = self2._doc; let v; const aliases = typeof (toObjectOptions && toObjectOptions.aliases) === "boolean" ? toObjectOptions.aliases : true; options = options || {}; let virtualsToApply = null; if (Array.isArray(options.virtuals)) { virtualsToApply = new Set(options.virtuals); } else if (options.virtuals && options.virtuals.pathsToSkip) { virtualsToApply = new Set(paths); for (let i2 = 0; i2 < options.virtuals.pathsToSkip.length; i2++) { if (virtualsToApply.has(options.virtuals.pathsToSkip[i2])) { virtualsToApply.delete(options.virtuals.pathsToSkip[i2]); } } } if (!cur) { return json; } for (i = 0; i < numPaths; ++i) { path = paths[i]; if (virtualsToApply != null && !virtualsToApply.has(path)) { continue; } if (!aliases && schema.aliases.hasOwnProperty(path)) { continue; } assignPath = path; if (options.path != null) { if (!path.startsWith(options.path + ".")) { continue; } assignPath = path.substring(options.path.length + 1); } if (assignPath.indexOf(".") === -1 && assignPath === path) { v = virtuals[path].applyGetters(void 0, self2); if (v === void 0) { continue; } v = clone(v, options); json[assignPath] = v; continue; } const parts = assignPath.split("."); v = clone(self2.get(path), options); if (v === void 0) { continue; } const plen = parts.length; cur = json; for (let j = 0; j < plen - 1; ++j) { cur[parts[j]] = cur[parts[j]] || {}; cur = cur[parts[j]]; } cur[parts[plen - 1]] = v; } return json; } function applyGetters(self2, json) { const schema = self2.$__schema; const paths = Object.keys(schema.paths); let i = paths.length; let path; let cur = self2._doc; let v; if (!cur) { return json; } while (i--) { path = paths[i]; const parts = path.split("."); const plen = parts.length; const last = plen - 1; let branch = json; let part; cur = self2._doc; if (!self2.$__isSelected(path)) { continue; } for (let ii = 0; ii < plen; ++ii) { part = parts[ii]; v = cur[part]; if (branch != null && typeof branch !== "object") { break; } else if (ii === last) { branch[part] = schema.paths[path].applyGetters( branch[part], self2 ); if (Array.isArray(branch[part]) && schema.paths[path].$embeddedSchemaType) { for (let i2 = 0; i2 < branch[part].length; ++i2) { branch[part][i2] = schema.paths[path].$embeddedSchemaType.applyGetters( branch[part][i2], self2 ); } } } else if (v == null) { if (part in cur) { branch[part] = v; } break; } else { branch = branch[part] || (branch[part] = {}); } cur = v; } } return json; } function applySchemaTypeTransforms(self2, json) { const schema = self2.$__schema; const paths = Object.keys(schema.paths || {}); const cur = self2._doc; if (!cur) { return json; } for (const path of paths) { const schematype = schema.paths[path]; const topLevelTransformFunction = schematype.options.transform ?? schematype.constructor?.defaultOptions?.transform; const embeddedSchemaTypeTransformFunction = schematype.$embeddedSchemaType?.options?.transform ?? schematype.$embeddedSchemaType?.constructor?.defaultOptions?.transform; if (typeof topLevelTransformFunction === "function") { const val = self2.$get(path); if (val === void 0) { continue; } const transformedValue = topLevelTransformFunction.call(self2, val); throwErrorIfPromise(path, transformedValue); utils.setValue(path, transformedValue, json); } else if (typeof embeddedSchemaTypeTransformFunction === "function") { const val = self2.$get(path); if (val === void 0) { continue; } const vals = [].concat(val); for (let i = 0; i < vals.length; ++i) { const transformedValue = embeddedSchemaTypeTransformFunction.call(self2, vals[i]); vals[i] = transformedValue; throwErrorIfPromise(path, transformedValue); } json[path] = vals; } } return json; } function throwErrorIfPromise(path, transformedValue) { if (isPromise(transformedValue)) { throw new Error("`transform` function must be synchronous, but the transform on path `" + path + "` returned a promise."); } } function omitDeselectedFields(self2, json) { const schema = self2.$__schema; const paths = Object.keys(schema.paths || {}); const cur = self2._doc; if (!cur) { return json; } let selected = self2.$__.selected; if (selected === void 0) { selected = {}; queryhelpers.applyPaths(selected, schema); } if (selected == null || Object.keys(selected).length === 0) { return json; } for (const path of paths) { if (selected[path] != null && !selected[path]) { delete json[path]; } } return json; } Document.prototype.toJSON = function(options) { return this.$toObject(options, true); }; Document.prototype.ownerDocument = function() { return this; }; Document.prototype.parent = function() { if (this.$isSubdocument || this.$__.wasPopulated) { return this.$__.parent; } return this; }; Document.prototype.$parent = Document.prototype.parent; Document.prototype.inspect = function(options) { const isPOJO = utils.isPOJO(options); let opts; if (isPOJO) { opts = options; opts.minimize = false; } const ret = arguments.length > 0 ? this.toObject(opts) : this.toObject(); if (ret == null) { return "MongooseDocument { " + ret + " }"; } return ret; }; if (inspect.custom) { Document.prototype[inspect.custom] = Document.prototype.inspect; } Document.prototype.toString = function() { const ret = this.inspect(); if (typeof ret === "string") { return ret; } return inspect(ret); }; Document.prototype.equals = function(doc) { if (!doc) { return false; } const tid = this.$__getValue("_id"); const docid = doc.$__ != null ? doc.$__getValue("_id") : doc; if (!tid && !docid) { return deepEqual(this, doc); } return tid && tid.equals ? tid.equals(docid) : tid === docid; }; Document.prototype.populate = async function populate() { const pop = {}; const args = [...arguments]; if (typeof args[args.length - 1] === "function") { throw new MongooseError("Document.prototype.populate() no longer accepts a callback"); } if (args.length !== 0) { const res = utils.populate.apply(null, args); for (const populateOptions of res) { pop[populateOptions.path] = populateOptions; } } const paths = utils.object.vals(pop); let topLevelModel = this.constructor; if (this.$__isNested) { topLevelModel = this.$__[scopeSymbol].constructor; const nestedPath = this.$__.nestedPath; paths.forEach(function(populateOptions) { populateOptions.path = nestedPath + "." + populateOptions.path; }); } if (this.$session() != null) { const session = this.$session(); paths.forEach((path) => { if (path.options == null) { path.options = { session }; return; } if (!("session" in path.options)) { path.options.session = session; } }); } paths.forEach((p) => { p._localModel = topLevelModel; }); return topLevelModel.populate(this, paths); }; Document.prototype.$getPopulatedDocs = function $getPopulatedDocs() { let keys = []; if (this.$__.populated != null) { keys = keys.concat(Object.keys(this.$__.populated)); } let result = []; for (const key of keys) { const value = this.$get(key); if (Array.isArray(value)) { result = result.concat(value); } else if (value instanceof Document) { result.push(value); } } return result; }; Document.prototype.populated = function(path, val, options) { if (val == null || val === true) { if (!this.$__.populated) { return void 0; } if (typeof path !== "string") { return void 0; } const _path = path.endsWith(".$*") ? path.replace(/\.\$\*$/, "") : path; const v = this.$__.populated[_path]; if (v) { return val === true ? v : v.value; } return void 0; } this.$__.populated || (this.$__.populated = {}); this.$__.populated[path] = { value: val, options }; const pieces = path.split("."); for (let i = 0; i < pieces.length - 1; ++i) { const subpath = pieces.slice(0, i + 1).join("."); const subdoc = this.$get(subpath); if (subdoc != null && subdoc.$__ != null && this.$populated(subpath)) { const rest = pieces.slice(i + 1).join("."); subdoc.$populated(rest, val, options); break; } } return val; }; Document.prototype.$populated = Document.prototype.populated; Document.prototype.$assertPopulated = function $assertPopulated(path, values) { if (Array.isArray(path)) { path.forEach((p) => this.$assertPopulated(p, values)); return this; } if (arguments.length > 1) { this.$set(values); } if (!this.$populated(path)) { throw new MongooseError(`Expected path "${path}" to be populated`); } return this; }; Document.prototype.depopulate = function(path) { if (typeof path === "string") { path = path.indexOf(" ") === -1 ? [path] : path.split(" "); } let populatedIds; const virtualKeys = this.$$populatedVirtuals ? Object.keys(this.$$populatedVirtuals) : []; const populated = this.$__ && this.$__.populated || {}; if (arguments.length === 0) { for (const virtualKey of virtualKeys) { delete this.$$populatedVirtuals[virtualKey]; delete this._doc[virtualKey]; delete populated[virtualKey]; } const keys = Object.keys(populated); for (const key of keys) { populatedIds = this.$populated(key); if (!populatedIds) { continue; } delete populated[key]; if (Array.isArray(populatedIds)) { const arr = utils.getValue(key, this._doc); if (arr.isMongooseArray) { const rawArray = arr.__array; for (let i = 0; i < rawArray.length; ++i) { const subdoc = rawArray[i]; if (subdoc == null) { continue; } rawArray[i] = subdoc instanceof Document ? subdoc._doc._id : subdoc._id; } } else { utils.setValue(key, populatedIds, this._doc); } } else { utils.setValue(key, populatedIds, this._doc); } } return this; } for (const singlePath of path) { populatedIds = this.$populated(singlePath); delete populated[singlePath]; if (virtualKeys.indexOf(singlePath) !== -1) { delete this.$$populatedVirtuals[singlePath]; delete this._doc[singlePath]; } else if (populatedIds) { if (Array.isArray(populatedIds)) { const arr = utils.getValue(singlePath, this._doc); if (arr.isMongooseArray) { const rawArray = arr.__array; for (let i = 0; i < rawArray.length; ++i) { const subdoc = rawArray[i]; if (subdoc == null) { continue; } rawArray[i] = subdoc instanceof Document ? subdoc._doc._id : subdoc._id; } } else { utils.setValue(singlePath, populatedIds, this._doc); } } else { utils.setValue(singlePath, populatedIds, this._doc); } } } return this; }; Document.prototype.$__fullPath = function(path) { return path || ""; }; Document.prototype.getChanges = function() { const delta = this.$__delta(); const changes = delta ? delta[1] : {}; return changes; }; Document.prototype.$__delta = function $__delta() { const dirty = this.$__dirty(); const optimisticConcurrency = this.$__schema.options.optimisticConcurrency; if (optimisticConcurrency) { if (Array.isArray(optimisticConcurrency)) { const optCon = new Set(optimisticConcurrency); const modPaths = this.modifiedPaths(); if (modPaths.find((path) => optCon.has(path))) { this.$__.version = dirty.length ? VERSION_ALL : VERSION_WHERE; } } else { this.$__.version = dirty.length ? VERSION_ALL : VERSION_WHERE; } } if (!dirty.length && VERSION_ALL !== this.$__.version) { return; } const where = {}; const delta = {}; const len = dirty.length; const divergent = []; let d = 0; where._id = this._doc._id; if ((where && where._id && where._id.$__ || null) != null) { where._id = where._id.toObject({ transform: false, depopulate: true }); } for (; d < len; ++d) { const data = dirty[d]; let value = data.value; const match = checkDivergentArray(this, data.path, value); if (match) { divergent.push(match); continue; } const pop = this.$populated(data.path, true); if (!pop && this.$__.selected) { const pathSplit = data.path.split("."); const top = pathSplit[0]; if (this.$__.selected[top] && this.$__.selected[top].$elemMatch) { if (pathSplit.length > 1 && pathSplit[1] == 0 && typeof where[top] === "undefined") { where[top] = this.$__.selected[top]; pathSplit[1] = "$"; data.path = pathSplit.join("."); } else { divergent.push(data.path); continue; } } } if (this.$isDefault(data.path) && this.$__.selected) { if (data.path.indexOf(".") === -1 && isPathExcluded(this.$__.selected, data.path)) { continue; } const pathsToCheck = parentPaths(data.path); if (pathsToCheck.find((path) => isPathExcluded(this.$__.isSelected, path))) { continue; } } if (divergent.length) continue; if (value === void 0) { operand(this, where, delta, data, 1, "$unset"); } else if (value === null) { operand(this, where, delta, data, null); } else if (utils.isMongooseArray(value) && value.$path() && value[arrayAtomicsSymbol]) { handleAtomics(this, where, delta, data, value); } else if (value[MongooseBuffer.pathSymbol] && Buffer.isBuffer(value)) { value = value.toObject(); operand(this, where, delta, data, value); } else { if (this.$__.primitiveAtomics && this.$__.primitiveAtomics[data.path] != null) { const val = this.$__.primitiveAtomics[data.path]; const op = firstKey(val); operand(this, where, delta, data, val[op], op); } else { value = clone(value, { depopulate: true, transform: false, virtuals: false, getters: false, omitUndefined: true, _isNested: true }); operand(this, where, delta, data, value); } } } if (divergent.length) { return new DivergentArrayError(divergent); } if (this.$__.version) { this.$__version(where, delta); } if (Object.keys(delta).length === 0) { return [where, null]; } return [where, delta]; }; function checkDivergentArray(doc, path, array) { const pop = doc.$populated(path, true); if (!pop && doc.$__.selected) { const top = path.split(".")[0]; if (doc.$__.selected[top + ".$"]) { return top; } } if (!(pop && utils.isMongooseArray(array))) return; const check = pop.options.match || pop.options.options && utils.object.hasOwnProperty(pop.options.options, "limit") || // 0 is not permitted pop.options.options && pop.options.options.skip || // 0 is permitted pop.options.select && // deselected _id? (pop.options.select._id === 0 || /\s?-_id\s?/.test(pop.options.select)); if (check) { const atomics = array[arrayAtomicsSymbol]; if (Object.keys(atomics).length === 0 || atomics.$set || atomics.$pop) { return path; } } } function operand(self2, where, delta, data, val, op) { op || (op = "$set"); if (!delta[op]) delta[op] = {}; delta[op][data.path] = val; if (self2.$__schema.options.versionKey === false) return; if (shouldSkipVersioning(self2, data.path)) return; if (VERSION_ALL === (VERSION_ALL & self2.$__.version)) return; if (self2.$__schema.options.optimisticConcurrency) { return; } switch (op) { case "$set": case "$unset": case "$pop": case "$pull": case "$pullAll": case "$push": case "$addToSet": case "$inc": break; default: return; } if (op === "$push" || op === "$addToSet" || op === "$pullAll" || op === "$pull") { if (/\.\d+\.|\.\d+$/.test(data.path)) { self2.$__.version = VERSION_ALL; } else { self2.$__.version = VERSION_INC; } } else if (/^\$p/.test(op)) { self2.$__.version = VERSION_ALL; } else if (Array.isArray(val)) { self2.$__.version = VERSION_ALL; } else if (/\.\d+\.|\.\d+$/.test(data.path)) { self2.$__.version = VERSION_WHERE; } } function handleAtomics(self2, where, delta, data, value) { if (delta.$set && delta.$set[data.path]) { return; } if (typeof value.$__getAtomics === "function") { value.$__getAtomics().forEach(function(atomic) { const op2 = atomic[0]; const val2 = atomic[1]; operand(self2, where, delta, data, val2, op2); }); return; } const atomics = value[arrayAtomicsSymbol]; const ops = Object.keys(atomics); let i = ops.length; let val; let op; if (i === 0) { if (utils.isMongooseObject(value)) { value = value.toObject({ depopulate: 1, _isNested: true }); } else if (value.valueOf) { value = value.valueOf(); } return operand(self2, where, delta, data, value); } function iter(mem) { return utils.isMongooseObject(mem) ? mem.toObject({ depopulate: 1, _isNested: true }) : mem; } while (i--) { op = ops[i]; val = atomics[op]; if (utils.isMongooseObject(val)) { val = val.toObject({ depopulate: true, transform: false, _isNested: true }); } else if (Array.isArray(val)) { val = val.map(iter); } else if (val.valueOf) { val = val.valueOf(); } if (op === "$addToSet") { val = { $each: val }; } operand(self2, where, delta, data, val, op); } } function shouldSkipVersioning(self2, path) { const skipVersioning = self2.$__schema.options.skipVersioning; if (!skipVersioning) return false; path = path.replace(/\.\d+\./, "."); return skipVersioning[path]; } Document.prototype.$clone = function() { const Model = this.constructor; const clonedDoc = new Model(); clonedDoc.$isNew = this.$isNew; if (this._doc) { clonedDoc._doc = clone(this._doc, { retainDocuments: true }); } if (this.$__) { const Cache = this.$__.constructor; const clonedCache = new Cache(); for (const key of Object.getOwnPropertyNames(this.$__)) { if (key === "activePaths") { continue; } clonedCache[key] = clone(this.$__[key]); } Object.assign(clonedCache.activePaths, clone({ ...this.$__.activePaths })); clonedDoc.$__ = clonedCache; } return clonedDoc; }; Document.prototype.$createModifiedPathsSnapshot = function $createModifiedPathsSnapshot() { const subdocSnapshot = /* @__PURE__ */ new WeakMap(); if (!this.$isSubdocument) { const subdocs = this.$getAllSubdocs(); for (const child of subdocs) { subdocSnapshot.set(child, child.$__.activePaths.clone()); } } return new ModifiedPathsSnapshot( subdocSnapshot, this.$__.activePaths.clone(), this.$__.version ); }; Document.prototype.$restoreModifiedPathsSnapshot = function $restoreModifiedPathsSnapshot(snapshot) { this.$__.activePaths = snapshot.activePaths.clone(); this.$__.version = snapshot.version; if (!this.$isSubdocument) { const subdocs = this.$getAllSubdocs(); for (const child of subdocs) { if (snapshot.subdocSnapshot.has(child)) { child.$__.activePaths = snapshot.subdocSnapshot.get(child); } } } return this; }; Document.prototype.$clearModifiedPaths = function $clearModifiedPaths() { this.$__.activePaths.clear("modify"); this.$__.activePaths.clear("init"); this.$__.version = 0; if (!this.$isSubdocument) { const subdocs = this.$getAllSubdocs(); for (const child of subdocs) { child.$clearModifiedPaths(); } } return this; }; Document.prototype.$__hasOnlyPrimitiveValues = function $__hasOnlyPrimitiveValues() { return !this.$__.populated && !this.$__.wasPopulated && (this._doc == null || Object.values(this._doc).every((v) => { return v == null || typeof v !== "object" || utils.isNativeObject(v) && !Array.isArray(v) || isBsonType(v, "ObjectId") || isBsonType(v, "Decimal128"); })); }; Document.VERSION_WHERE = VERSION_WHERE; Document.VERSION_INC = VERSION_INC; Document.VERSION_ALL = VERSION_ALL; Document.ValidationError = ValidationError; module2.exports = exports2 = Document; } }); // netlify/functions/node_modules/mongoose/lib/utils.js var require_utils3 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/utils.js"(exports2) { "use strict"; var UUID = require_bson().UUID; var ms = require_ms(); var mpath = require_mpath(); var ObjectId2 = require_objectid(); var PopulateOptions = require_populateOptions(); var clone = require_clone(); var immediate = require_immediate(); var isObject = require_isObject(); var isMongooseArray = require_isMongooseArray(); var isMongooseDocumentArray = require_isMongooseDocumentArray(); var isBsonType = require_isBsonType(); var isPOJO = require_isPOJO(); var getFunctionName = require_getFunctionName(); var isMongooseObject = require_isMongooseObject(); var promiseOrCallback = require_promiseOrCallback(); var schemaMerge = require_merge(); var specialProperties = require_specialProperties(); var { trustedSymbol } = require_trusted(); var Document; exports2.specialProperties = specialProperties; exports2.isMongooseArray = isMongooseArray.isMongooseArray; exports2.isMongooseDocumentArray = isMongooseDocumentArray.isMongooseDocumentArray; exports2.registerMongooseArray = isMongooseArray.registerMongooseArray; exports2.registerMongooseDocumentArray = isMongooseDocumentArray.registerMongooseDocumentArray; var oneSpaceRE = /\s/; var manySpaceRE = /\s+/; exports2.toCollectionName = function(name, pluralize) { if (name === "system.profile") { return name; } if (name === "system.indexes") { return name; } if (typeof pluralize === "function") { if (typeof name !== "string") { throw new TypeError("Collection name must be a string"); } if (name.length === 0) { throw new TypeError("Collection name cannot be empty"); } return pluralize(name); } return name; }; exports2.deepEqual = function deepEqual(a, b) { if (a === b) { return true; } if (typeof a !== "object" || typeof b !== "object") { return a === b; } if (a instanceof Date && b instanceof Date) { return a.getTime() === b.getTime(); } if (isBsonType(a, "ObjectId") && isBsonType(b, "ObjectId") || isBsonType(a, "Decimal128") && isBsonType(b, "Decimal128")) { return a.toString() === b.toString(); } if (a instanceof RegExp && b instanceof RegExp) { return a.source === b.source && a.ignoreCase === b.ignoreCase && a.multiline === b.multiline && a.global === b.global && a.dotAll === b.dotAll && a.unicode === b.unicode && a.sticky === b.sticky && a.hasIndices === b.hasIndices; } if (a == null || b == null) { return false; } if (a.prototype !== b.prototype) { return false; } if (a instanceof Map || b instanceof Map) { if (!(a instanceof Map) || !(b instanceof Map)) { return false; } return deepEqual(Array.from(a.keys()), Array.from(b.keys())) && deepEqual(Array.from(a.values()), Array.from(b.values())); } if (a instanceof Number && b instanceof Number) { return a.valueOf() === b.valueOf(); } if (Buffer.isBuffer(a)) { return exports2.buffer.areEqual(a, b); } if (Array.isArray(a) || Array.isArray(b)) { if (!Array.isArray(a) || !Array.isArray(b)) { return false; } const len = a.length; if (len !== b.length) { return false; } for (let i = 0; i < len; ++i) { if (!deepEqual(a[i], b[i])) { return false; } } return true; } if (a.$__ != null) { a = a._doc; } else if (isMongooseObject(a)) { a = a.toObject(); } if (b.$__ != null) { b = b._doc; } else if (isMongooseObject(b)) { b = b.toObject(); } const ka = Object.keys(a); const kb = Object.keys(b); const kaLength = ka.length; if (kaLength !== kb.length) { return false; } for (let i = kaLength - 1; i >= 0; i--) { if (ka[i] !== kb[i]) { return false; } } for (const key of ka) { if (!deepEqual(a[key], b[key])) { return false; } } return true; }; exports2.last = function(arr) { if (arr.length > 0) { return arr[arr.length - 1]; } return void 0; }; exports2.promiseOrCallback = promiseOrCallback; exports2.cloneArrays = function cloneArrays(arr) { if (!Array.isArray(arr)) { return arr; } return arr.map((el) => exports2.cloneArrays(el)); }; exports2.omit = function omit(obj, keys) { if (keys == null) { return Object.assign({}, obj); } if (!Array.isArray(keys)) { keys = [keys]; } const ret = Object.assign({}, obj); for (const key of keys) { delete ret[key]; } return ret; }; exports2.clonePOJOsAndArrays = function clonePOJOsAndArrays(val) { if (val == null) { return val; } if (val.$__ != null) { return val; } if (isPOJO(val)) { val = { ...val }; for (const key of Object.keys(val)) { val[key] = exports2.clonePOJOsAndArrays(val[key]); } return val; } if (Array.isArray(val)) { val = [...val]; for (let i = 0; i < val.length; ++i) { val[i] = exports2.clonePOJOsAndArrays(val[i]); } return val; } return val; }; exports2.merge = function merge(to, from, options, path) { options = options || {}; const keys = Object.keys(from); let i = 0; const len = keys.length; let key; if (from[trustedSymbol]) { to[trustedSymbol] = from[trustedSymbol]; } path = path || ""; const omitNested = options.omitNested || {}; while (i < len) { key = keys[i++]; if (options.omit && options.omit[key]) { continue; } if (omitNested[path]) { continue; } if (specialProperties.has(key)) { continue; } if (to[key] == null) { to[key] = exports2.clonePOJOsAndArrays(from[key]); } else if (exports2.isObject(from[key])) { if (!exports2.isObject(to[key])) { to[key] = {}; } if (from[key] != null) { if (options.isDiscriminatorSchemaMerge && (from[key].$isSingleNested && to[key].$isMongooseDocumentArray) || from[key].$isMongooseDocumentArray && to[key].$isSingleNested) { continue; } else if (from[key].instanceOfSchema) { if (to[key].instanceOfSchema) { schemaMerge(to[key], from[key].clone(), options.isDiscriminatorSchemaMerge); } else { to[key] = from[key].clone(); } continue; } else if (isBsonType(from[key], "ObjectId")) { to[key] = new ObjectId2(from[key]); continue; } } merge(to[key], from[key], options, path ? path + "." + key : key); } else if (options.overwrite) { to[key] = from[key]; } } return to; }; exports2.toObject = function toObject(obj) { Document || (Document = require_document2()); let ret; if (obj == null) { return obj; } if (obj instanceof Document) { return obj.toObject(); } if (Array.isArray(obj)) { ret = []; for (const doc of obj) { ret.push(toObject(doc)); } return ret; } if (exports2.isPOJO(obj)) { ret = {}; if (obj[trustedSymbol]) { ret[trustedSymbol] = obj[trustedSymbol]; } for (const k of Object.keys(obj)) { if (specialProperties.has(k)) { continue; } ret[k] = toObject(obj[k]); } return ret; } return obj; }; exports2.isObject = isObject; exports2.isPOJO = require_isPOJO(); exports2.isNonBuiltinObject = function isNonBuiltinObject(val) { return typeof val === "object" && !exports2.isNativeObject(val) && !exports2.isMongooseType(val) && !(val instanceof UUID) && val != null; }; exports2.isNativeObject = function(arg) { return Array.isArray(arg) || arg instanceof Date || arg instanceof Boolean || arg instanceof Number || arg instanceof String; }; exports2.isEmptyObject = function(val) { return val != null && typeof val === "object" && Object.keys(val).length === 0; }; exports2.hasKey = function hasKey(obj, key) { const props = Object.keys(obj); for (const prop of props) { if (prop === key) { return true; } if (exports2.isPOJO(obj[prop]) && exports2.hasKey(obj[prop], key)) { return true; } } return false; }; exports2.tick = function tick(callback) { if (typeof callback !== "function") { return; } return function() { try { callback.apply(this, arguments); } catch (err) { immediate(function() { throw err; }); } }; }; exports2.isMongooseType = function(v) { return isBsonType(v, "ObjectId") || isBsonType(v, "Decimal128") || v instanceof Buffer; }; exports2.isMongooseObject = isMongooseObject; exports2.expires = function expires(object) { if (!(object && object.constructor.name === "Object")) { return; } if (!("expires" in object)) { return; } object.expireAfterSeconds = typeof object.expires !== "string" ? object.expires : Math.round(ms(object.expires) / 1e3); delete object.expires; }; exports2.populate = function populate(path, select, model, match, options, subPopulate, justOne, count) { let obj = null; if (arguments.length === 1) { if (path instanceof PopulateOptions) { path._docs = {}; path._childDocs = []; return [path]; } if (Array.isArray(path)) { const singles = makeSingles(path); return singles.map((o) => exports2.populate(o)[0]); } if (exports2.isObject(path)) { obj = Object.assign({}, path); } else { obj = { path }; } } else if (typeof model === "object") { obj = { path, select, match: model, options: match }; } else { obj = { path, select, model, match, options, populate: subPopulate, justOne, count }; } if (typeof obj.path !== "string" && !(Array.isArray(obj.path) && obj.path.every((el) => typeof el === "string"))) { throw new TypeError("utils.populate: invalid path. Expected string or array of strings. Got typeof `" + typeof path + "`"); } return _populateObj(obj); function makeSingles(arr) { const ret = []; arr.forEach(function(obj2) { if (oneSpaceRE.test(obj2.path)) { const paths = obj2.path.split(manySpaceRE); paths.forEach(function(p) { const copy = Object.assign({}, obj2); copy.path = p; ret.push(copy); }); } else { ret.push(obj2); } }); return ret; } }; function _populateObj(obj) { if (Array.isArray(obj.populate)) { const ret2 = []; obj.populate.forEach(function(obj2) { if (oneSpaceRE.test(obj2.path)) { const copy = Object.assign({}, obj2); const paths2 = copy.path.split(manySpaceRE); paths2.forEach(function(p) { copy.path = p; ret2.push(exports2.populate(copy)[0]); }); } else { ret2.push(exports2.populate(obj2)[0]); } }); obj.populate = exports2.populate(ret2); } else if (obj.populate != null && typeof obj.populate === "object") { obj.populate = exports2.populate(obj.populate); } const ret = []; const paths = oneSpaceRE.test(obj.path) ? obj.path.split(manySpaceRE) : Array.isArray(obj.path) ? obj.path : [obj.path]; if (obj.options != null) { obj.options = clone(obj.options); } for (const path of paths) { ret.push(new PopulateOptions(Object.assign({}, obj, { path }))); } return ret; } exports2.getValue = function(path, obj, map) { return mpath.get(path, obj, getValueLookup, map); }; var mapGetterOptions = Object.freeze({ getters: false }); function getValueLookup(obj, part) { if (part === "$*" && obj instanceof Map) { return obj; } let _from = obj?._doc || obj; if (_from != null && _from.isMongooseArrayProxy) { _from = _from.__array; } return _from instanceof Map ? _from.get(part, mapGetterOptions) : _from[part]; } exports2.setValue = function(path, val, obj, map, _copying) { mpath.set(path, val, obj, "_doc", map, _copying); }; exports2.object = {}; exports2.object.vals = function vals(o) { const keys = Object.keys(o); let i = keys.length; const ret = []; while (i--) { ret.push(o[keys[i]]); } return ret; }; var hop = Object.prototype.hasOwnProperty; exports2.object.hasOwnProperty = function(obj, prop) { return hop.call(obj, prop); }; exports2.isNullOrUndefined = function(val) { return val === null || val === void 0; }; exports2.array = {}; exports2.array.flatten = function flatten(arr, filter, ret) { ret || (ret = []); arr.forEach(function(item) { if (Array.isArray(item)) { flatten(item, filter, ret); } else { if (!filter || filter(item)) { ret.push(item); } } }); return ret; }; var _hasOwnProperty = Object.prototype.hasOwnProperty; exports2.hasUserDefinedProperty = function(obj, key) { if (obj == null) { return false; } if (Array.isArray(key)) { for (const k of key) { if (exports2.hasUserDefinedProperty(obj, k)) { return true; } } return false; } if (_hasOwnProperty.call(obj, key)) { return true; } if (typeof obj === "object" && key in obj) { const v = obj[key]; return v !== Object.prototype[key] && v !== Array.prototype[key]; } return false; }; var MAX_ARRAY_INDEX = Math.pow(2, 32) - 1; exports2.isArrayIndex = function(val) { if (typeof val === "number") { return val >= 0 && val <= MAX_ARRAY_INDEX; } if (typeof val === "string") { if (!/^\d+$/.test(val)) { return false; } val = +val; return val >= 0 && val <= MAX_ARRAY_INDEX; } return false; }; exports2.array.unique = function(arr) { const primitives = /* @__PURE__ */ new Set(); const ids = /* @__PURE__ */ new Set(); const ret = []; for (const item of arr) { if (typeof item === "number" || typeof item === "string" || item == null) { if (primitives.has(item)) { continue; } ret.push(item); primitives.add(item); } else if (isBsonType(item, "ObjectId")) { if (ids.has(item.toString())) { continue; } ret.push(item); ids.add(item.toString()); } else { ret.push(item); } } return ret; }; exports2.buffer = {}; exports2.buffer.areEqual = function(a, b) { if (!Buffer.isBuffer(a)) { return false; } if (!Buffer.isBuffer(b)) { return false; } if (a.length !== b.length) { return false; } for (let i = 0, len = a.length; i < len; ++i) { if (a[i] !== b[i]) { return false; } } return true; }; exports2.getFunctionName = getFunctionName; exports2.decorate = function(destination, source) { for (const key in source) { if (specialProperties.has(key)) { continue; } destination[key] = source[key]; } }; exports2.mergeClone = function(to, fromObj) { if (isMongooseObject(fromObj)) { fromObj = fromObj.toObject({ transform: false, virtuals: false, depopulate: true, getters: false, flattenDecimals: false }); } const keys = Object.keys(fromObj); const len = keys.length; let i = 0; let key; while (i < len) { key = keys[i++]; if (specialProperties.has(key)) { continue; } if (typeof to[key] === "undefined") { to[key] = clone(fromObj[key], { transform: false, virtuals: false, depopulate: true, getters: false, flattenDecimals: false }); } else { let val = fromObj[key]; if (val != null && val.valueOf && !(val instanceof Date)) { val = val.valueOf(); } if (exports2.isObject(val)) { let obj = val; if (isMongooseObject(val) && !val.isMongooseBuffer) { obj = obj.toObject({ transform: false, virtuals: false, depopulate: true, getters: false, flattenDecimals: false }); } if (val.isMongooseBuffer) { obj = Buffer.from(obj); } exports2.mergeClone(to[key], obj); } else { to[key] = clone(val, { flattenDecimals: false }); } } } }; exports2.each = function(arr, fn) { for (const item of arr) { fn(item); } }; exports2.renameObjKey = function(oldObj, oldKey, newKey) { const keys = Object.keys(oldObj); return keys.reduce( (acc, val) => { if (val === oldKey) { acc[newKey] = oldObj[oldKey]; } else { acc[val] = oldObj[val]; } return acc; }, {} ); }; exports2.getOption = function(name) { const sources = Array.prototype.slice.call(arguments, 1); for (const source of sources) { if (source == null) { continue; } if (source[name] != null) { return source[name]; } } return null; }; exports2.noop = function() { }; exports2.errorToPOJO = function errorToPOJO(error) { const isError = error instanceof Error; if (!isError) { throw new Error("`error` must be `instanceof Error`."); } const ret = {}; for (const properyName of Object.getOwnPropertyNames(error)) { ret[properyName] = error[properyName]; } return ret; }; exports2.warn = function warn(message) { return process.emitWarning(message, { code: "MONGOOSE" }); }; exports2.injectTimestampsOption = function injectTimestampsOption(writeOperation, timestampsOption) { if (timestampsOption == null) { return; } writeOperation.timestamps = timestampsOption; }; } }); // netlify/functions/node_modules/mongoose/lib/schemaType.js var require_schemaType = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schemaType.js"(exports2, module2) { "use strict"; var MongooseError = require_error2(); var SchemaTypeOptions = require_schemaTypeOptions(); var $exists = require_exists(); var $type = require_type(); var clone = require_clone(); var handleImmutable = require_handleImmutable(); var isAsyncFunction = require_isAsyncFunction(); var isSimpleValidator = require_isSimpleValidator(); var immediate = require_immediate(); var schemaTypeSymbol = require_symbols().schemaTypeSymbol; var utils = require_utils3(); var validatorErrorSymbol = require_symbols().validatorErrorSymbol; var documentIsModified = require_symbols().documentIsModified; var populateModelSymbol = require_symbols().populateModelSymbol; var CastError = MongooseError.CastError; var ValidatorError = MongooseError.ValidatorError; var setOptionsForDefaults = { _skipMarkModified: true }; function SchemaType(path, options, instance) { this[schemaTypeSymbol] = true; this.path = path; this.instance = instance; this.validators = []; this.getters = this.constructor.hasOwnProperty("getters") ? this.constructor.getters.slice() : []; this.setters = this.constructor.hasOwnProperty("setters") ? this.constructor.setters.slice() : []; this.splitPath(); options = options || {}; const defaultOptions = this.constructor.defaultOptions || {}; const defaultOptionsKeys = Object.keys(defaultOptions); for (const option of defaultOptionsKeys) { if (option === "validate") { this.validate(defaultOptions.validate); } else if (defaultOptions.hasOwnProperty(option) && !Object.prototype.hasOwnProperty.call(options, option)) { options[option] = defaultOptions[option]; } } if (options.select == null) { delete options.select; } const Options = this.OptionsConstructor || SchemaTypeOptions; this.options = new Options(options); this._index = null; if (utils.hasUserDefinedProperty(this.options, "immutable")) { this.$immutable = this.options.immutable; handleImmutable(this); } const keys = Object.keys(this.options); for (const prop of keys) { if (prop === "cast") { if (Array.isArray(this.options[prop])) { this.castFunction.apply(this, this.options[prop]); } else { this.castFunction(this.options[prop]); } continue; } if (utils.hasUserDefinedProperty(this.options, prop) && typeof this[prop] === "function") { if (prop === "index" && this._index) { if (options.index === false) { const index = this._index; if (typeof index === "object" && index != null) { if (index.unique) { throw new Error('Path "' + this.path + '" may not have `index` set to false and `unique` set to true'); } if (index.sparse) { throw new Error('Path "' + this.path + '" may not have `index` set to false and `sparse` set to true'); } } this._index = false; } continue; } const val = options[prop]; if (prop === "default") { this.default(val); continue; } const opts = Array.isArray(val) ? val : [val]; this[prop].apply(this, opts); } } Object.defineProperty(this, "$$context", { enumerable: false, configurable: false, writable: true, value: null }); } SchemaType.prototype.OptionsConstructor = SchemaTypeOptions; SchemaType.prototype.path; SchemaType.prototype.validators; SchemaType.prototype.isRequired; SchemaType.prototype.splitPath = function() { if (this._presplitPath != null) { return this._presplitPath; } if (this.path == null) { return void 0; } this._presplitPath = this.path.indexOf(".") === -1 ? [this.path] : this.path.split("."); return this._presplitPath; }; SchemaType.cast = function cast(caster) { if (arguments.length === 0) { return this._cast; } if (caster === false) { caster = (v) => v; } this._cast = caster; return this._cast; }; SchemaType.prototype.castFunction = function castFunction(caster, message) { if (arguments.length === 0) { return this._castFunction; } if (caster === false) { caster = this.constructor._defaultCaster || ((v) => v); } if (typeof caster === "string") { this._castErrorMessage = caster; return this._castFunction; } if (caster != null) { this._castFunction = caster; } if (message != null) { this._castErrorMessage = message; } return this._castFunction; }; SchemaType.prototype.cast = function cast() { throw new Error("Base SchemaType class does not implement a `cast()` function"); }; SchemaType.set = function set(option, value) { if (!this.hasOwnProperty("defaultOptions")) { this.defaultOptions = Object.assign({}, this.defaultOptions); } this.defaultOptions[option] = value; }; SchemaType.get = function(getter) { this.getters = this.hasOwnProperty("getters") ? this.getters : []; this.getters.push(getter); }; SchemaType.prototype.default = function(val) { if (arguments.length === 1) { if (val === void 0) { this.defaultValue = void 0; return void 0; } if (val != null && val.instanceOfSchema) { throw new MongooseError("Cannot set default value of path `" + this.path + "` to a mongoose Schema instance."); } this.defaultValue = val; return this.defaultValue; } else if (arguments.length > 1) { this.defaultValue = [...arguments]; } return this.defaultValue; }; SchemaType.prototype.index = function(options) { this._index = options; utils.expires(this._index); return this; }; SchemaType.prototype.unique = function unique(value, message) { if (this._index === false) { if (!value) { return; } throw new Error('Path "' + this.path + '" may not have `index` set to false and `unique` set to true'); } if (!this.options.hasOwnProperty("index") && value === false) { return this; } if (this._index == null || this._index === true) { this._index = {}; } else if (typeof this._index === "string") { this._index = { type: this._index }; } this._index.unique = !!value; if (typeof message === "string") { this._duplicateKeyErrorMessage = message; } return this; }; SchemaType.prototype.text = function(bool) { if (this._index === false) { if (!bool) { return this; } throw new Error('Path "' + this.path + '" may not have `index` set to false and `text` set to true'); } if (!this.options.hasOwnProperty("index") && bool === false) { return this; } if (this._index === null || this._index === void 0 || typeof this._index === "boolean") { this._index = {}; } else if (typeof this._index === "string") { this._index = { type: this._index }; } this._index.text = bool; return this; }; SchemaType.prototype.sparse = function(bool) { if (this._index === false) { if (!bool) { return this; } throw new Error('Path "' + this.path + '" may not have `index` set to false and `sparse` set to true'); } if (!this.options.hasOwnProperty("index") && bool === false) { return this; } if (this._index == null || typeof this._index === "boolean") { this._index = {}; } else if (typeof this._index === "string") { this._index = { type: this._index }; } this._index.sparse = bool; return this; }; SchemaType.prototype.immutable = function(bool) { this.$immutable = bool; handleImmutable(this); return this; }; SchemaType.prototype.transform = function(fn) { this.options.transform = fn; return this; }; SchemaType.prototype.set = function(fn) { if (typeof fn !== "function") { throw new TypeError("A setter must be a function."); } this.setters.push(fn); return this; }; SchemaType.prototype.get = function(fn) { if (typeof fn !== "function") { throw new TypeError("A getter must be a function."); } this.getters.push(fn); return this; }; SchemaType.prototype.validateAll = function(validators) { for (let i = 0; i < validators.length; i++) { this.validate(validators[i]); } return this; }; SchemaType.prototype.validate = function(obj, message, type) { if (typeof obj === "function" || obj && utils.getFunctionName(obj.constructor) === "RegExp") { let properties; if (typeof message === "function") { properties = { validator: obj, message }; properties.type = type || "user defined"; } else if (message instanceof Object && !type) { properties = isSimpleValidator(message) ? Object.assign({}, message) : clone(message); if (!properties.message) { properties.message = properties.msg; } properties.validator = obj; properties.type = properties.type || "user defined"; } else { if (message == null) { message = MongooseError.messages.general.default; } if (!type) { type = "user defined"; } properties = { message, type, validator: obj }; } this.validators.push(properties); return this; } let i; let length; let arg; for (i = 0, length = arguments.length; i < length; i++) { arg = arguments[i]; if (!utils.isPOJO(arg)) { const msg = "Invalid validator. Received (" + typeof arg + ") " + arg + ". See https://mongoosejs.com/docs/api/schematype.html#SchemaType.prototype.validate()"; throw new Error(msg); } this.validate(arg.validator, arg); } return this; }; SchemaType.prototype.required = function(required, message) { let customOptions = {}; if (arguments.length > 0 && required == null) { this.validators = this.validators.filter(function(v) { return v.validator !== this.requiredValidator; }, this); this.isRequired = false; delete this.originalRequiredValue; return this; } if (typeof required === "object") { customOptions = required; message = customOptions.message || message; required = required.isRequired; } if (required === false) { this.validators = this.validators.filter(function(v) { return v.validator !== this.requiredValidator; }, this); this.isRequired = false; delete this.originalRequiredValue; return this; } const _this = this; this.isRequired = true; this.requiredValidator = function(v) { const cachedRequired = this && this.$__ && this.$__.cachedRequired; if (cachedRequired != null && !this.$__isSelected(_this.path) && !this[documentIsModified](_this.path)) { return true; } if (cachedRequired != null && _this.path in cachedRequired) { const res = cachedRequired[_this.path] ? _this.checkRequired(v, this) : true; delete cachedRequired[_this.path]; return res; } else if (typeof required === "function") { return required.apply(this) ? _this.checkRequired(v, this) : true; } return _this.checkRequired(v, this); }; this.originalRequiredValue = required; if (typeof required === "string") { message = required; required = void 0; } const msg = message || MongooseError.messages.general.required; this.validators.unshift(Object.assign({}, customOptions, { validator: this.requiredValidator, message: msg, type: "required" })); return this; }; SchemaType.prototype.ref = function(ref) { this.options.ref = ref; return this; }; SchemaType.prototype.getDefault = function(scope, init, options) { let ret; if (typeof this.defaultValue === "function") { if (this.defaultValue === Date.now || this.defaultValue === Array || this.defaultValue.name.toLowerCase() === "objectid") { ret = this.defaultValue.call(scope); } else { ret = this.defaultValue.call(scope, scope); } } else { ret = this.defaultValue; } if (ret !== null && ret !== void 0) { if (typeof ret === "object" && (!this.options || !this.options.shared)) { ret = clone(ret); } if (options && options.skipCast) { return this._applySetters(ret, scope); } const casted = this.applySetters(ret, scope, init, void 0, setOptionsForDefaults); if (casted && !Array.isArray(casted) && casted.$isSingleNested) { casted.$__parent = scope; } return casted; } return ret; }; SchemaType.prototype._applySetters = function(value, scope, init, priorVal, options) { let v = value; if (init) { return v; } const setters = this.setters; for (let i = setters.length - 1; i >= 0; i--) { v = setters[i].call(scope, v, priorVal, this, options); } return v; }; SchemaType.prototype._castNullish = function _castNullish(v) { return v; }; SchemaType.prototype.applySetters = function(value, scope, init, priorVal, options) { let v = this._applySetters(value, scope, init, priorVal, options); if (v == null) { return this._castNullish(v); } v = this.cast(v, scope, init, priorVal, options); return v; }; SchemaType.prototype.applyGetters = function(value, scope) { let v = value; const getters = this.getters; const len = getters.length; if (len === 0) { return v; } for (let i = 0; i < len; ++i) { v = getters[i].call(scope, v, this); } return v; }; SchemaType.prototype.select = function select(val) { this.selected = !!val; return this; }; SchemaType.prototype.doValidate = function(value, fn, scope, options) { let err = false; const path = this.path; if (typeof fn !== "function") { throw new TypeError(`Must pass callback function to doValidate(), got ${typeof fn}`); } const validators = this.validators.filter((v) => typeof v === "object" && v !== null); let count = validators.length; if (!count) { return fn(null); } for (let i = 0, len = validators.length; i < len; ++i) { if (err) { break; } const v = validators[i]; const validator = v.validator; let ok; const validatorProperties = isSimpleValidator(v) ? Object.assign({}, v) : clone(v); validatorProperties.path = options && options.path ? options.path : path; validatorProperties.fullPath = this.$fullPath; validatorProperties.value = value; if (typeof value === "string") { validatorProperties.length = value.length; if (validatorProperties.value.length > 30) { validatorProperties.value = validatorProperties.value.slice(0, 30) + "..."; } } if (validator instanceof RegExp) { validate(validator.test(value), validatorProperties, scope); continue; } if (typeof validator !== "function") { continue; } if (value === void 0 && validator !== this.requiredValidator) { validate(true, validatorProperties, scope); continue; } try { if (validatorProperties.propsParameter) { ok = validator.call(scope, value, validatorProperties); } else { ok = validator.call(scope, value); } } catch (error) { ok = false; validatorProperties.reason = error; if (error.message) { validatorProperties.message = error.message; } } if (ok != null && typeof ok.then === "function") { ok.then( function(ok2) { validate(ok2, validatorProperties, scope); }, function(error) { validatorProperties.reason = error; validatorProperties.message = error.message; ok = false; validate(ok, validatorProperties, scope); } ); } else { validate(ok, validatorProperties, scope); } } function validate(ok, validatorProperties, scope2) { if (err) { return; } if (ok === void 0 || ok) { if (--count <= 0) { immediate(function() { fn(null); }); } } else { const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError; err = new ErrorConstructor(validatorProperties, scope2); err[validatorErrorSymbol] = true; immediate(function() { fn(err); }); } } }; function _validate(ok, validatorProperties) { if (ok !== void 0 && !ok) { const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError; const err = new ErrorConstructor(validatorProperties); err[validatorErrorSymbol] = true; return err; } } SchemaType.prototype.doValidateSync = function(value, scope, options) { const path = this.path; const count = this.validators.length; if (!count) { return null; } let validators = this.validators; if (value === void 0) { if (this.validators.length !== 0 && this.validators[0].type === "required") { validators = [this.validators[0]]; } else { return null; } } let err = null; let i = 0; const len = validators.length; for (i = 0; i < len; ++i) { const v = validators[i]; if (v === null || typeof v !== "object") { continue; } const validator = v.validator; const validatorProperties = isSimpleValidator(v) ? Object.assign({}, v) : clone(v); validatorProperties.path = options && options.path ? options.path : path; validatorProperties.fullPath = this.$fullPath; validatorProperties.value = value; if (typeof value === "string") { validatorProperties.length = value.length; if (validatorProperties.value.length > 30) { validatorProperties.value = validatorProperties.value.slice(0, 30) + "..."; } } let ok = false; if (isAsyncFunction(validator)) { continue; } if (validator instanceof RegExp) { err = _validate(validator.test(value), validatorProperties); continue; } if (typeof validator !== "function") { continue; } try { if (validatorProperties.propsParameter) { ok = validator.call(scope, value, validatorProperties); } else { ok = validator.call(scope, value); } } catch (error) { ok = false; validatorProperties.reason = error; } if (ok != null && typeof ok.then === "function") { continue; } err = _validate(ok, validatorProperties); if (err) { break; } } return err; }; SchemaType._isRef = function(self2, value, doc, init) { let ref = init && self2.options && (self2.options.ref || self2.options.refPath); if (!ref && doc && doc.$__ != null) { const path = doc.$__fullPath(self2.path, true); const owner = doc.ownerDocument(); ref = path != null && owner.$populated(path) || doc.$populated(self2.path); } if (ref) { if (value == null) { return true; } if (!Buffer.isBuffer(value) && // buffers are objects too value._bsontype !== "Binary" && utils.isObject(value)) { return true; } return init; } return false; }; SchemaType.prototype._castRef = function _castRef(value, doc, init, options) { if (value == null) { return value; } if (value.$__ != null) { value.$__.wasPopulated = value.$__.wasPopulated || { value: value._doc._id }; return value; } if (Buffer.isBuffer(value) || !utils.isObject(value)) { if (init) { return value; } throw new CastError(this.instance, value, this.path, null, this); } const path = doc.$__fullPath(this.path, true); const owner = doc.ownerDocument(); const pop = owner.$populated(path, true); let ret = value; if (!doc.$__.populated || !doc.$__.populated[path] || !doc.$__.populated[path].options || !doc.$__.populated[path].options.options || !doc.$__.populated[path].options.options.lean) { const PopulatedModel = pop ? pop.options[populateModelSymbol] : doc.constructor.db.model(this.options.ref); ret = PopulatedModel.hydrate(value, null, options); ret.$__.wasPopulated = { value: ret._doc._id, options: { [populateModelSymbol]: PopulatedModel } }; } return ret; }; function handleSingle(val, context) { return this.castForQuery(null, val, context); } function handleArray(val, context) { const _this = this; if (!Array.isArray(val)) { return [this.castForQuery(null, val, context)]; } return val.map(function(m) { return _this.castForQuery(null, m, context); }); } function handle$in(val, context) { const _this = this; if (!Array.isArray(val)) { return [this.castForQuery(null, val, context)]; } return val.map(function(m) { if (Array.isArray(m) && m.length === 0) { return m; } return _this.castForQuery(null, m, context); }); } SchemaType.prototype.$conditionalHandlers = { $all: handleArray, $eq: handleSingle, $in: handle$in, $ne: handleSingle, $nin: handle$in, $exists, $type }; SchemaType.prototype.castForQuery = function($conditional, val, context) { let handler; if ($conditional != null) { handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new Error("Can't use " + $conditional); } return handler.call(this, val, context); } try { return this.applySetters(val, context); } catch (err) { if (err instanceof CastError && err.path === this.path && this.$fullPath != null) { err.path = this.$fullPath; } throw err; } }; SchemaType.checkRequired = function(fn) { if (arguments.length !== 0) { this._checkRequired = fn; } return this._checkRequired; }; SchemaType.prototype.checkRequired = function(val) { return val != null; }; SchemaType.prototype.clone = function() { const options = Object.assign({}, this.options); const schematype = new this.constructor(this.path, options, this.instance); schematype.validators = this.validators.slice(); if (this.requiredValidator !== void 0) schematype.requiredValidator = this.requiredValidator; if (this.defaultValue !== void 0) schematype.defaultValue = this.defaultValue; if (this.$immutable !== void 0 && this.options.immutable === void 0) { schematype.$immutable = this.$immutable; handleImmutable(schematype); } if (this._index !== void 0) schematype._index = this._index; if (this.selected !== void 0) schematype.selected = this.selected; if (this.isRequired !== void 0) schematype.isRequired = this.isRequired; if (this.originalRequiredValue !== void 0) schematype.originalRequiredValue = this.originalRequiredValue; schematype.getters = this.getters.slice(); schematype.setters = this.setters.slice(); return schematype; }; SchemaType.prototype.getEmbeddedSchemaType = function getEmbeddedSchemaType() { return this.$embeddedSchemaType; }; SchemaType.prototype._duplicateKeyErrorMessage = null; SchemaType.prototype.toJSONSchema = function toJSONSchema(_options) { throw new Error(`Converting unsupported SchemaType to JSON Schema: ${this.instance} at path "${this.path}"`); }; SchemaType.prototype.autoEncryptionType = function autoEncryptionType() { return null; }; module2.exports = exports2 = SchemaType; exports2.CastError = CastError; exports2.ValidatorError = ValidatorError; } }); // netlify/functions/node_modules/mongoose/lib/options/virtualOptions.js var require_virtualOptions = __commonJS({ "netlify/functions/node_modules/mongoose/lib/options/virtualOptions.js"(exports2, module2) { "use strict"; var opts = require_propertyOptions(); var VirtualOptions = class { constructor(obj) { Object.assign(this, obj); if (obj != null && obj.options != null) { this.options = Object.assign({}, obj.options); } } }; Object.defineProperty(VirtualOptions.prototype, "ref", opts); Object.defineProperty(VirtualOptions.prototype, "refPath", opts); Object.defineProperty(VirtualOptions.prototype, "localField", opts); Object.defineProperty(VirtualOptions.prototype, "foreignField", opts); Object.defineProperty(VirtualOptions.prototype, "justOne", opts); Object.defineProperty(VirtualOptions.prototype, "count", opts); Object.defineProperty(VirtualOptions.prototype, "match", opts); Object.defineProperty(VirtualOptions.prototype, "options", opts); Object.defineProperty(VirtualOptions.prototype, "skip", opts); Object.defineProperty(VirtualOptions.prototype, "limit", opts); Object.defineProperty(VirtualOptions.prototype, "perDocumentLimit", opts); module2.exports = VirtualOptions; } }); // netlify/functions/node_modules/mongoose/lib/helpers/populate/lookupLocalFields.js var require_lookupLocalFields = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/populate/lookupLocalFields.js"(exports2, module2) { "use strict"; module2.exports = function lookupLocalFields(cur, path, val) { if (cur == null) { return cur; } if (cur._doc != null) { cur = cur._doc; } if (arguments.length >= 3) { if (typeof cur !== "object") { return void 0; } if (val === void 0) { return void 0; } if (cur instanceof Map) { cur.set(path, val); } else { cur[path] = val; } return val; } if (path === "$*") { return cur instanceof Map ? Array.from(cur.values()) : Object.keys(cur).map((key) => cur[key]); } if (cur instanceof Map) { return cur.get(path); } return cur[path]; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/populate/modelNamesFromRefPath.js var require_modelNamesFromRefPath = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/populate/modelNamesFromRefPath.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var isPathExcluded = require_isPathExcluded(); var lookupLocalFields = require_lookupLocalFields(); var mpath = require_mpath(); var util = require("util"); var utils = require_utils3(); var hasNumericPropRE = /(\.\d+$|\.\d+\.)/g; module2.exports = function modelNamesFromRefPath(refPath, doc, populatedPath, modelSchema, queryProjection) { if (refPath == null) { return []; } if (typeof refPath === "string" && queryProjection != null && isPathExcluded(queryProjection, refPath)) { throw new MongooseError("refPath `" + refPath + "` must not be excluded in projection, got " + util.inspect(queryProjection)); } if (hasNumericPropRE.test(populatedPath)) { const chunks = populatedPath.split(hasNumericPropRE); if (chunks[chunks.length - 1] === "") { throw new Error("Can't populate individual element in an array"); } let _refPath = ""; let _remaining = refPath; for (let i = 0; i < chunks.length; i += 2) { const chunk = chunks[i]; if (_remaining.startsWith(chunk + ".")) { _refPath += _remaining.substring(0, chunk.length) + chunks[i + 1]; _remaining = _remaining.substring(chunk.length + 1); } else if (i === chunks.length - 1) { _refPath += _remaining; _remaining = ""; break; } else { throw new Error("Could not normalize ref path, chunk " + chunk + " not in populated path"); } } const refValue2 = mpath.get(_refPath, doc, lookupLocalFields); let modelNames2 = Array.isArray(refValue2) ? refValue2 : [refValue2]; modelNames2 = utils.array.flatten(modelNames2); return modelNames2; } const refValue = mpath.get(refPath, doc, lookupLocalFields); let modelNames; if (modelSchema != null && modelSchema.virtuals.hasOwnProperty(refPath)) { modelNames = [modelSchema.virtuals[refPath].applyGetters(void 0, doc)]; } else { modelNames = Array.isArray(refValue) ? refValue : [refValue]; } return modelNames; }; } }); // netlify/functions/node_modules/mongoose/lib/virtualType.js var require_virtualType = __commonJS({ "netlify/functions/node_modules/mongoose/lib/virtualType.js"(exports2, module2) { "use strict"; var modelNamesFromRefPath = require_modelNamesFromRefPath(); var utils = require_utils3(); var modelSymbol = require_symbols().modelSymbol; function VirtualType(options, name) { this.path = name; this.getters = []; this.setters = []; this.options = Object.assign({}, options); } VirtualType.prototype._applyDefaultGetters = function() { if (this.getters.length > 0 || this.setters.length > 0) { return; } const path = this.path; const internalProperty = "$" + path; this.getters.push(function() { return this.$locals[internalProperty]; }); this.setters.push(function(v) { this.$locals[internalProperty] = v; }); }; VirtualType.prototype.clone = function() { const clone = new VirtualType(this.options, this.path); clone.getters = [].concat(this.getters); clone.setters = [].concat(this.setters); return clone; }; VirtualType.prototype.get = function(fn) { this.getters.push(fn); return this; }; VirtualType.prototype.set = function(fn) { this.setters.push(fn); return this; }; VirtualType.prototype.applyGetters = function(value, doc) { if (utils.hasUserDefinedProperty(this.options, ["ref", "refPath"]) && doc.$$populatedVirtuals && doc.$$populatedVirtuals.hasOwnProperty(this.path)) { value = doc.$$populatedVirtuals[this.path]; } let v = value; for (const getter of this.getters) { v = getter.call(doc, v, this, doc); } return v; }; VirtualType.prototype.applySetters = function(value, doc) { let v = value; for (const setter of this.setters) { v = setter.call(doc, v, this, doc); } return v; }; VirtualType.prototype._getModelNamesForPopulate = function _getModelNamesForPopulate(doc) { if (this.options.refPath) { return modelNamesFromRefPath(this.options.refPath, doc, this.path); } let normalizedRef = null; if (typeof this.options.ref === "function" && !this.options.ref[modelSymbol]) { normalizedRef = this.options.ref.call(doc, doc); } else { normalizedRef = this.options.ref; } if (normalizedRef != null && !Array.isArray(normalizedRef)) { return [normalizedRef]; } return normalizedRef; }; module2.exports = VirtualType; } }); // netlify/functions/node_modules/mongoose/lib/helpers/schema/addAutoId.js var require_addAutoId = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/schema/addAutoId.js"(exports2, module2) { "use strict"; module2.exports = function addAutoId(schema) { const _obj = { _id: { auto: true } }; _obj._id[schema.options.typeKey] = "ObjectId"; schema.add(_obj); }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/indexes/decorateDiscriminatorIndexOptions.js var require_decorateDiscriminatorIndexOptions = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/indexes/decorateDiscriminatorIndexOptions.js"(exports2, module2) { "use strict"; module2.exports = function decorateDiscriminatorIndexOptions(schema, indexOptions) { const discriminatorName = schema.discriminatorMapping && schema.discriminatorMapping.value; if (discriminatorName && !("sparse" in indexOptions)) { const discriminatorKey = schema.options.discriminatorKey; indexOptions.partialFilterExpression = indexOptions.partialFilterExpression || {}; indexOptions.partialFilterExpression[discriminatorKey] = discriminatorName; } return indexOptions; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/schema/getIndexes.js var require_getIndexes = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/schema/getIndexes.js"(exports2, module2) { "use strict"; var get = require_get(); var helperIsObject = require_isObject(); var decorateDiscriminatorIndexOptions = require_decorateDiscriminatorIndexOptions(); module2.exports = function getIndexes(schema) { let indexes = []; const schemaStack = /* @__PURE__ */ new WeakMap(); const indexTypes = schema.constructor.indexTypes; const indexByName = /* @__PURE__ */ new Map(); collectIndexes(schema); return indexes; function collectIndexes(schema2, prefix, baseSchema) { if (schemaStack.has(schema2)) { return; } schemaStack.set(schema2, true); prefix = prefix || ""; const keys = Object.keys(schema2.paths); for (const key of keys) { const path = schema2.paths[key]; if (baseSchema != null && baseSchema.paths[key]) { continue; } if (path._duplicateKeyErrorMessage != null) { schema2._duplicateKeyErrorMessagesByPath = schema2._duplicateKeyErrorMessagesByPath || {}; schema2._duplicateKeyErrorMessagesByPath[key] = path._duplicateKeyErrorMessage; } if (path.$isMongooseDocumentArray || path.$isSingleNested) { if (get(path, "options.excludeIndexes") !== true && get(path, "schemaOptions.excludeIndexes") !== true && get(path, "schema.options.excludeIndexes") !== true) { collectIndexes(path.schema, prefix + key + "."); } if (path.schema.discriminators != null) { const discriminators = path.schema.discriminators; const discriminatorKeys = Object.keys(discriminators); for (const discriminatorKey of discriminatorKeys) { collectIndexes( discriminators[discriminatorKey], prefix + key + ".", path.schema ); } } if (path.$isMongooseDocumentArray) { continue; } } const index = path._index || path.caster && path.caster._index; if (index !== false && index !== null && index !== void 0) { const field = {}; const isObject = helperIsObject(index); const options = isObject ? index : {}; const type = typeof index === "string" ? index : isObject ? index.type : false; if (type && indexTypes.indexOf(type) !== -1) { field[prefix + key] = type; } else if (options.text) { field[prefix + key] = "text"; delete options.text; } else { let isDescendingIndex = false; if (index === "descending" || index === "desc") { isDescendingIndex = true; } else if (index === "ascending" || index === "asc") { isDescendingIndex = false; } else { isDescendingIndex = Number(index) === -1; } field[prefix + key] = isDescendingIndex ? -1 : 1; } delete options.type; if (!("background" in options)) { options.background = true; } if (schema2.options.autoIndex != null) { options._autoIndex = schema2.options.autoIndex; } const indexName = options && options.name; if (typeof indexName === "string") { if (indexByName.has(indexName)) { Object.assign(indexByName.get(indexName), field); } else { indexes.push([field, options]); indexByName.set(indexName, field); } } else { indexes.push([field, options]); indexByName.set(indexName, field); } } } schemaStack.delete(schema2); if (prefix) { fixSubIndexPaths(schema2, prefix); } else { schema2._indexes.forEach(function(index) { const options = index[1]; if (!("background" in options)) { options.background = true; } decorateDiscriminatorIndexOptions(schema2, options); }); indexes = indexes.concat(schema2._indexes); } } function fixSubIndexPaths(schema2, prefix) { const subindexes = schema2._indexes; const len = subindexes.length; for (let i = 0; i < len; ++i) { const indexObj = subindexes[i][0]; const indexOptions = subindexes[i][1]; const keys = Object.keys(indexObj); const klen = keys.length; const newindex = {}; for (let j = 0; j < klen; ++j) { const key = keys[j]; newindex[prefix + key] = indexObj[key]; } const newIndexOptions = Object.assign({}, indexOptions); if (indexOptions != null && indexOptions.partialFilterExpression != null) { newIndexOptions.partialFilterExpression = {}; const partialFilterExpression = indexOptions.partialFilterExpression; for (const key of Object.keys(partialFilterExpression)) { newIndexOptions.partialFilterExpression[prefix + key] = partialFilterExpression[key]; } } indexes.push([newindex, newIndexOptions]); } } }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/query/handleReadPreferenceAliases.js var require_handleReadPreferenceAliases = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/query/handleReadPreferenceAliases.js"(exports2, module2) { "use strict"; module2.exports = function handleReadPreferenceAliases(pref) { switch (pref) { case "p": pref = "primary"; break; case "pp": pref = "primaryPreferred"; break; case "s": pref = "secondary"; break; case "sp": pref = "secondaryPreferred"; break; case "n": pref = "nearest"; break; } return pref; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/schema/idGetter.js var require_idGetter = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/schema/idGetter.js"(exports2, module2) { "use strict"; module2.exports = function addIdGetter(schema) { const autoIdGetter = !schema.paths["id"] && schema.paths["_id"] && schema.options.id; if (!autoIdGetter) { return schema; } if (schema.aliases && schema.aliases.id) { return schema; } schema.virtual("id").get(idGetter); return schema; }; function idGetter() { if (this._id != null) { return this._id.toString(); } return null; } } }); // netlify/functions/node_modules/mongoose/lib/helpers/indexes/isIndexSpecEqual.js var require_isIndexSpecEqual = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/indexes/isIndexSpecEqual.js"(exports2, module2) { "use strict"; module2.exports = function isIndexSpecEqual(spec1, spec2) { const spec1Keys = Object.keys(spec1); const spec2Keys = Object.keys(spec2); if (spec1Keys.length !== spec2Keys.length) { return false; } for (let i = 0; i < spec1Keys.length; i++) { const key = spec1Keys[i]; if (key !== spec2Keys[i] || spec1[key] !== spec2[key]) { return false; } } return true; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/populate/setPopulatedVirtualValue.js var require_setPopulatedVirtualValue = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/populate/setPopulatedVirtualValue.js"(exports2, module2) { "use strict"; module2.exports = function setPopulatedVirtualValue(populatedVirtuals, name, v, options) { if (options.justOne || options.count) { populatedVirtuals[name] = Array.isArray(v) ? v[0] : v; if (typeof populatedVirtuals[name] !== "object") { populatedVirtuals[name] = options.count ? v : null; } } else { populatedVirtuals[name] = Array.isArray(v) ? v : v == null ? [] : [v]; populatedVirtuals[name] = populatedVirtuals[name].filter(function(doc) { return doc && typeof doc === "object"; }); } return populatedVirtuals[name]; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/schema/cleanPositionalOperators.js var require_cleanPositionalOperators = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/schema/cleanPositionalOperators.js"(exports2, module2) { "use strict"; module2.exports = function cleanPositionalOperators(path) { return path.replace(/\.\$(\[[^\]]*\])?(?=\.)/g, ".0").replace(/\.\$(\[[^\]]*\])?$/g, ".0"); }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/schema/handleTimestampOption.js var require_handleTimestampOption = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/schema/handleTimestampOption.js"(exports2, module2) { "use strict"; module2.exports = handleTimestampOption; function handleTimestampOption(arg, prop) { if (arg == null) { return null; } if (typeof arg === "boolean") { return prop; } if (typeof arg[prop] === "boolean") { return arg[prop] ? prop : null; } if (!(prop in arg)) { return prop; } return arg[prop]; } } }); // netlify/functions/node_modules/mongoose/lib/helpers/update/applyTimestampsToChildren.js var require_applyTimestampsToChildren = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/update/applyTimestampsToChildren.js"(exports2, module2) { "use strict"; var cleanPositionalOperators = require_cleanPositionalOperators(); var handleTimestampOption = require_handleTimestampOption(); module2.exports = applyTimestampsToChildren; function applyTimestampsToChildren(now, update, schema) { if (update == null) { return; } const keys = Object.keys(update); const hasDollarKey = keys.some((key) => key[0] === "$"); if (hasDollarKey) { if (update.$push) { _applyTimestampToUpdateOperator(update.$push); } if (update.$addToSet) { _applyTimestampToUpdateOperator(update.$addToSet); } if (update.$set != null) { const keys2 = Object.keys(update.$set); for (const key of keys2) { applyTimestampsToUpdateKey(schema, key, update.$set, now); } } if (update.$setOnInsert != null) { const keys2 = Object.keys(update.$setOnInsert); for (const key of keys2) { applyTimestampsToUpdateKey(schema, key, update.$setOnInsert, now); } } } const updateKeys = Object.keys(update).filter((key) => key[0] !== "$"); for (const key of updateKeys) { applyTimestampsToUpdateKey(schema, key, update, now); } function _applyTimestampToUpdateOperator(op) { for (const key of Object.keys(op)) { const $path = schema.path(key.replace(/\.\$\./i, ".").replace(/.\$$/, "")); if (op[key] && $path && $path.$isMongooseDocumentArray && $path.schema.options.timestamps) { const timestamps = $path.schema.options.timestamps; const createdAt = handleTimestampOption(timestamps, "createdAt"); const updatedAt = handleTimestampOption(timestamps, "updatedAt"); if (op[key].$each) { op[key].$each.forEach(function(subdoc) { if (updatedAt != null) { subdoc[updatedAt] = now; } if (createdAt != null) { subdoc[createdAt] = now; } applyTimestampsToChildren(now, subdoc, $path.schema); }); } else { if (updatedAt != null) { op[key][updatedAt] = now; } if (createdAt != null) { op[key][createdAt] = now; } applyTimestampsToChildren(now, op[key], $path.schema); } } } } } function applyTimestampsToDocumentArray(arr, schematype, now) { const timestamps = schematype.schema.options.timestamps; const len = arr.length; if (!timestamps) { for (let i = 0; i < len; ++i) { applyTimestampsToChildren(now, arr[i], schematype.schema); } return; } const createdAt = handleTimestampOption(timestamps, "createdAt"); const updatedAt = handleTimestampOption(timestamps, "updatedAt"); for (let i = 0; i < len; ++i) { if (updatedAt != null) { arr[i][updatedAt] = now; } if (createdAt != null) { arr[i][createdAt] = now; } applyTimestampsToChildren(now, arr[i], schematype.schema); } } function applyTimestampsToSingleNested(subdoc, schematype, now) { const timestamps = schematype.schema.options.timestamps; if (!timestamps) { applyTimestampsToChildren(now, subdoc, schematype.schema); return; } const createdAt = handleTimestampOption(timestamps, "createdAt"); const updatedAt = handleTimestampOption(timestamps, "updatedAt"); if (updatedAt != null) { subdoc[updatedAt] = now; } if (createdAt != null) { subdoc[createdAt] = now; } applyTimestampsToChildren(now, subdoc, schematype.schema); } function applyTimestampsToUpdateKey(schema, key, update, now) { const keyToSearch = cleanPositionalOperators(key); const path = schema.path(keyToSearch); if (!path) { return; } const parentSchemaTypes = []; const pieces = keyToSearch.split("."); for (let i = pieces.length - 1; i > 0; --i) { const s = schema.path(pieces.slice(0, i).join(".")); if (s != null && (s.$isMongooseDocumentArray || s.$isSingleNested)) { parentSchemaTypes.push({ parentPath: key.split(".").slice(0, i).join("."), parentSchemaType: s }); } } if (Array.isArray(update[key]) && path.$isMongooseDocumentArray) { applyTimestampsToDocumentArray(update[key], path, now); } else if (update[key] && path.$isSingleNested) { applyTimestampsToSingleNested(update[key], path, now); } else if (parentSchemaTypes.length > 0) { for (const item of parentSchemaTypes) { const parentPath = item.parentPath; const parentSchemaType = item.parentSchemaType; const timestamps = parentSchemaType.schema.options.timestamps; const updatedAt = handleTimestampOption(timestamps, "updatedAt"); if (!timestamps || updatedAt == null) { continue; } if (parentSchemaType.$isSingleNested) { update[parentPath + "." + updatedAt] = now; } else if (parentSchemaType.$isMongooseDocumentArray) { let childPath = key.substring(parentPath.length + 1); if (/^\d+$/.test(childPath)) { update[parentPath + "." + childPath][updatedAt] = now; continue; } const firstDot = childPath.indexOf("."); childPath = firstDot !== -1 ? childPath.substring(0, firstDot) : childPath; update[parentPath + "." + childPath + "." + updatedAt] = now; } } } else if (path.schema != null && path.schema != schema && update[key]) { const timestamps = path.schema.options.timestamps; const createdAt = handleTimestampOption(timestamps, "createdAt"); const updatedAt = handleTimestampOption(timestamps, "updatedAt"); if (!timestamps) { return; } if (updatedAt != null) { update[key][updatedAt] = now; } if (createdAt != null) { update[key][createdAt] = now; } } } } }); // netlify/functions/node_modules/mongoose/lib/helpers/update/applyTimestampsToUpdate.js var require_applyTimestampsToUpdate = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/update/applyTimestampsToUpdate.js"(exports2, module2) { "use strict"; var get = require_get(); module2.exports = applyTimestampsToUpdate; function applyTimestampsToUpdate(now, createdAt, updatedAt, currentUpdate, options, isReplace) { const updates = currentUpdate; let _updates = updates; const timestamps = get(options, "timestamps", true); if (!timestamps || updates == null) { return currentUpdate; } const skipCreatedAt = timestamps != null && timestamps.createdAt === false; const skipUpdatedAt = timestamps != null && timestamps.updatedAt === false; if (isReplace) { if (currentUpdate && currentUpdate.$set) { currentUpdate = currentUpdate.$set; updates.$set = {}; _updates = updates.$set; } if (!skipUpdatedAt && updatedAt && !currentUpdate[updatedAt]) { _updates[updatedAt] = now; } if (!skipCreatedAt && createdAt && !currentUpdate[createdAt]) { _updates[createdAt] = now; } return updates; } currentUpdate = currentUpdate || {}; if (Array.isArray(updates)) { if (updatedAt == null) { return updates; } updates.push({ $set: { [updatedAt]: now } }); return updates; } updates.$set = updates.$set || {}; if (!skipUpdatedAt && updatedAt && (!currentUpdate.$currentDate || !currentUpdate.$currentDate[updatedAt])) { let timestampSet = false; if (updatedAt.indexOf(".") !== -1) { const pieces = updatedAt.split("."); for (let i = 1; i < pieces.length; ++i) { const remnant = pieces.slice(-i).join("."); const start = pieces.slice(0, -i).join("."); if (currentUpdate[start] != null) { currentUpdate[start][remnant] = now; timestampSet = true; break; } else if (currentUpdate.$set && currentUpdate.$set[start]) { currentUpdate.$set[start][remnant] = now; timestampSet = true; break; } } } if (!timestampSet) { updates.$set[updatedAt] = now; } if (updates.hasOwnProperty(updatedAt)) { delete updates[updatedAt]; } } if (!skipCreatedAt && createdAt) { if (currentUpdate[createdAt]) { delete currentUpdate[createdAt]; } if (currentUpdate.$set && currentUpdate.$set[createdAt]) { delete currentUpdate.$set[createdAt]; } let timestampSet = false; if (createdAt.indexOf(".") !== -1) { const pieces = createdAt.split("."); for (let i = 1; i < pieces.length; ++i) { const remnant = pieces.slice(-i).join("."); const start = pieces.slice(0, -i).join("."); if (currentUpdate[start] != null) { currentUpdate[start][remnant] = now; timestampSet = true; break; } else if (currentUpdate.$set && currentUpdate.$set[start]) { currentUpdate.$set[start][remnant] = now; timestampSet = true; break; } } } if (!timestampSet) { updates.$setOnInsert = updates.$setOnInsert || {}; updates.$setOnInsert[createdAt] = now; } } if (Object.keys(updates.$set).length === 0) { delete updates.$set; } return updates; } } }); // netlify/functions/node_modules/mongoose/lib/helpers/timestamps/setDocumentTimestamps.js var require_setDocumentTimestamps = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/timestamps/setDocumentTimestamps.js"(exports2, module2) { "use strict"; module2.exports = function setDocumentTimestamps(doc, timestampOption, currentTime, createdAt, updatedAt) { const skipUpdatedAt = timestampOption != null && timestampOption.updatedAt === false; const skipCreatedAt = timestampOption != null && timestampOption.createdAt === false; const defaultTimestamp = currentTime != null ? currentTime() : doc.ownerDocument().constructor.base.now(); if (!skipCreatedAt && (doc.isNew || doc.$isSubdocument) && createdAt && !doc.$__getValue(createdAt) && doc.$__isSelected(createdAt)) { doc.$set(createdAt, defaultTimestamp, void 0, { overwriteImmutable: true }); } if (!skipUpdatedAt && updatedAt && (doc.isNew || doc.$isModified())) { let ts = defaultTimestamp; if (doc.isNew && createdAt != null) { ts = doc.$__getValue(createdAt); } doc.$set(updatedAt, ts); } }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/timestamps/setupTimestamps.js var require_setupTimestamps = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/timestamps/setupTimestamps.js"(exports2, module2) { "use strict"; var applyTimestampsToChildren = require_applyTimestampsToChildren(); var applyTimestampsToUpdate = require_applyTimestampsToUpdate(); var get = require_get(); var handleTimestampOption = require_handleTimestampOption(); var setDocumentTimestamps = require_setDocumentTimestamps(); var symbols = require_symbols2(); var replaceOps = /* @__PURE__ */ new Set([ "replaceOne", "findOneAndReplace" ]); module2.exports = function setupTimestamps(schema, timestamps) { const childHasTimestamp = schema.childSchemas.find(withTimestamp); function withTimestamp(s) { const ts = s.schema.options.timestamps; return !!ts; } if (!timestamps && !childHasTimestamp) { return; } const createdAt = handleTimestampOption(timestamps, "createdAt"); const updatedAt = handleTimestampOption(timestamps, "updatedAt"); const currentTime = timestamps != null && timestamps.hasOwnProperty("currentTime") ? timestamps.currentTime : null; const schemaAdditions = {}; schema.$timestamps = { createdAt, updatedAt }; if (createdAt && !schema.paths[createdAt]) { const baseImmutableCreatedAt = schema.base != null ? schema.base.get("timestamps.createdAt.immutable") : null; const immutable = baseImmutableCreatedAt != null ? baseImmutableCreatedAt : true; schemaAdditions[createdAt] = { [schema.options.typeKey || "type"]: Date, immutable }; } if (updatedAt && !schema.paths[updatedAt]) { schemaAdditions[updatedAt] = Date; } schema.add(schemaAdditions); schema.pre("save", function timestampsPreSave(next) { const timestampOption = get(this, "$__.saveOptions.timestamps"); if (timestampOption === false) { return next(); } setDocumentTimestamps(this, timestampOption, currentTime, createdAt, updatedAt); next(); }); schema.methods.initializeTimestamps = function() { const ts = currentTime != null ? currentTime() : this.constructor.base.now(); if (createdAt && !this.get(createdAt)) { this.$set(createdAt, ts); } if (updatedAt && !this.get(updatedAt)) { this.$set(updatedAt, ts); } if (this.$isSubdocument) { return this; } const subdocs = this.$getAllSubdocs(); for (const subdoc of subdocs) { if (subdoc.initializeTimestamps) { subdoc.initializeTimestamps(); } } return this; }; _setTimestampsOnUpdate[symbols.builtInMiddleware] = true; const opts = { query: true, model: false }; schema.pre("findOneAndReplace", opts, _setTimestampsOnUpdate); schema.pre("findOneAndUpdate", opts, _setTimestampsOnUpdate); schema.pre("replaceOne", opts, _setTimestampsOnUpdate); schema.pre("update", opts, _setTimestampsOnUpdate); schema.pre("updateOne", opts, _setTimestampsOnUpdate); schema.pre("updateMany", opts, _setTimestampsOnUpdate); function _setTimestampsOnUpdate(next) { const now = currentTime != null ? currentTime() : this.model.base.now(); if (replaceOps.has(this.op) && this.getUpdate() == null) { this.setUpdate({}); } applyTimestampsToUpdate( now, createdAt, updatedAt, this.getUpdate(), this._mongooseOptions, replaceOps.has(this.op) ); applyTimestampsToChildren(now, this.getUpdate(), this.model.schema); next(); } }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/populate/validateRef.js var require_validateRef = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/populate/validateRef.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var util = require("util"); module2.exports = validateRef; function validateRef(ref, path) { if (typeof ref === "string") { return; } if (typeof ref === "function") { return; } throw new MongooseError('Invalid ref at path "' + path + '". Got ' + util.inspect(ref, { depth: 0 })); } } }); // netlify/functions/node_modules/mongoose/lib/constants.js var require_constants3 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/constants.js"(exports2) { "use strict"; var queryOperations = Object.freeze([ // Read "countDocuments", "distinct", "estimatedDocumentCount", "find", "findOne", // Update "findOneAndReplace", "findOneAndUpdate", "replaceOne", "updateMany", "updateOne", // Delete "deleteMany", "deleteOne", "findOneAndDelete" ]); exports2.queryOperations = queryOperations; var queryMiddlewareFunctions = queryOperations.concat([ "validate" ]); exports2.queryMiddlewareFunctions = queryMiddlewareFunctions; var aggregateMiddlewareFunctions = [ "aggregate" ]; exports2.aggregateMiddlewareFunctions = aggregateMiddlewareFunctions; var modelMiddlewareFunctions = [ "bulkWrite", "createCollection", "insertMany" ]; exports2.modelMiddlewareFunctions = modelMiddlewareFunctions; var documentMiddlewareFunctions = [ "validate", "save", "remove", "updateOne", "deleteOne", "init" ]; exports2.documentMiddlewareFunctions = documentMiddlewareFunctions; } }); // netlify/functions/node_modules/mongoose/lib/helpers/model/applyHooks.js var require_applyHooks = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/model/applyHooks.js"(exports2, module2) { "use strict"; var symbols = require_symbols2(); var promiseOrCallback = require_promiseOrCallback(); module2.exports = applyHooks; applyHooks.middlewareFunctions = [ "deleteOne", "save", "validate", "remove", "updateOne", "init" ]; var alreadyHookedFunctions = new Set(applyHooks.middlewareFunctions.flatMap((fn) => [fn, `$__${fn}`])); function applyHooks(model, schema, options) { options = options || {}; const kareemOptions = { useErrorHandlers: true, numCallbackParams: 1, nullResultByDefault: true, contextParameter: true }; const objToDecorate = options.decorateDoc ? model : model.prototype; model.$appliedHooks = true; for (const key of Object.keys(schema.paths)) { const type = schema.paths[key]; let childModel = null; if (type.$isSingleNested) { childModel = type.caster; } else if (type.$isMongooseDocumentArray) { childModel = type.Constructor; } else { continue; } if (childModel.$appliedHooks) { continue; } applyHooks(childModel, type.schema, { ...options, isChildSchema: true }); if (childModel.discriminators != null) { const keys = Object.keys(childModel.discriminators); for (const key2 of keys) { applyHooks( childModel.discriminators[key2], childModel.discriminators[key2].schema, options ); } } } const middleware = schema.s.hooks.filter((hook) => { if (hook.name === "updateOne" || hook.name === "deleteOne") { return !!hook["document"]; } if (hook.name === "remove" || hook.name === "init") { return hook["document"] == null || !!hook["document"]; } if (hook.query != null || hook.document != null) { return hook.document !== false; } return true; }).filter((hook) => { if (schema.methods[hook.name]) { return !hook.fn[symbols.builtInMiddleware]; } return true; }); model._middleware = middleware; objToDecorate.$__originalValidate = objToDecorate.$__originalValidate || objToDecorate.$__validate; const internalMethodsToWrap = options && options.isChildSchema ? ["save", "validate", "deleteOne"] : ["save", "validate"]; for (const method of internalMethodsToWrap) { const toWrap = method === "validate" ? "$__originalValidate" : `$__${method}`; const wrapped = middleware.createWrapper(method, objToDecorate[toWrap], null, kareemOptions); objToDecorate[`$__${method}`] = wrapped; } objToDecorate.$__init = middleware.createWrapperSync("init", objToDecorate.$__init, null, kareemOptions); const customMethods = Object.keys(schema.methods); const customMethodOptions = Object.assign({}, kareemOptions, { // Only use `checkForPromise` for custom methods, because mongoose // query thunks are not as consistent as I would like about returning // a nullish value rather than the query. If a query thunk returns // a query, `checkForPromise` causes infinite recursion checkForPromise: true }); for (const method of customMethods) { if (alreadyHookedFunctions.has(method)) { continue; } if (!middleware.hasHooks(method)) { continue; } const originalMethod = objToDecorate[method]; objToDecorate[method] = function() { const args = Array.prototype.slice.call(arguments); const cb = args.slice(-1).pop(); const argsWithoutCallback = typeof cb === "function" ? args.slice(0, args.length - 1) : args; return promiseOrCallback(cb, (callback) => { return this[`$__${method}`].apply( this, argsWithoutCallback.concat([callback]) ); }, model.events); }; objToDecorate[`$__${method}`] = middleware.createWrapper(method, originalMethod, null, customMethodOptions); } } } }); // netlify/functions/node_modules/mongoose/lib/types/double.js var require_double = __commonJS({ "netlify/functions/node_modules/mongoose/lib/types/double.js"(exports2, module2) { "use strict"; module2.exports = require_bson().Double; } }); // netlify/functions/node_modules/mongoose/lib/types/map.js var require_map = __commonJS({ "netlify/functions/node_modules/mongoose/lib/types/map.js"(exports2, module2) { "use strict"; var Mixed = require_mixed(); var MongooseError = require_mongooseError(); var clone = require_clone(); var deepEqual = require_utils3().deepEqual; var getConstructorName = require_getConstructorName(); var handleSpreadDoc = require_handleSpreadDoc(); var util = require("util"); var specialProperties = require_specialProperties(); var isBsonType = require_isBsonType(); var cleanModifiedSubpaths = require_cleanModifiedSubpaths(); var populateModelSymbol = require_symbols().populateModelSymbol; var MongooseMap = class extends Map { constructor(v, path, doc, schemaType) { if (getConstructorName(v) === "Object") { v = Object.keys(v).reduce((arr, key) => arr.concat([[key, v[key]]]), []); } super(v); this.$__parent = doc != null && doc.$__ != null ? doc : null; this.$__path = path; this.$__schemaType = schemaType == null ? new Mixed(path) : schemaType; this.$__runDeferred(); } $init(key, value) { checkValidKey(key); super.set(key, value); if (value != null && value.$isSingleNested) { value.$basePath = this.$__path + "." + key; } } $__set(key, value) { super.set(key, value); } /** * Overwrites native Map's `get()` function to support Mongoose getters. * * @api public * @method get * @memberOf Map */ get(key, options) { if (isBsonType(key, "ObjectId")) { key = key.toString(); } options = options || {}; if (options.getters === false) { return super.get(key); } return this.$__schemaType.applyGetters(super.get(key), this.$__parent); } /** * Overwrites native Map's `set()` function to support setters, `populate()`, * and change tracking. Note that Mongoose maps _only_ support strings and * ObjectIds as keys. * * Keys also cannot: * - be named after special properties `prototype`, `constructor`, and `__proto__` * - start with a dollar sign (`$`) * - contain any dots (`.`) * * #### Example: * * doc.myMap.set('test', 42); // works * doc.myMap.set({ obj: 42 }, 42); // Throws "Mongoose maps only support string keys" * doc.myMap.set(10, 42); // Throws "Mongoose maps only support string keys" * doc.myMap.set("$test", 42); // Throws "Mongoose maps do not support keys that start with "$", got "$test"" * * @api public * @method set * @memberOf Map */ set(key, value) { if (isBsonType(key, "ObjectId")) { key = key.toString(); } checkValidKey(key); value = handleSpreadDoc(value); if (this.$__schemaType == null) { this.$__deferred = this.$__deferred || []; this.$__deferred.push({ key, value }); return; } let _fullPath; const parent = this.$__parent; const populated = parent != null && parent.$__ && parent.$__.populated ? parent.$populated(fullPath.call(this), true) || parent.$populated(this.$__path, true) : null; const priorVal = this.get(key); if (populated != null) { if (this.$__schemaType.$isSingleNested) { throw new MongooseError( `Cannot manually populate single nested subdoc underneath Map at path "${this.$__path}". Try using an array instead of a Map.` ); } if (Array.isArray(value) && this.$__schemaType.$isMongooseArray) { value = value.map((v) => { if (v.$__ == null) { v = new populated.options[populateModelSymbol](v); } v.$__.wasPopulated = { value: v._doc._id }; return v; }); } else if (value != null) { if (value.$__ == null) { value = new populated.options[populateModelSymbol](value); } value.$__.wasPopulated = { value: value._doc._id }; } } else { try { const options = this.$__schemaType.$isMongooseDocumentArray || this.$__schemaType.$isSingleNested || this.$__schemaType.$isMongooseArray || this.$__schemaType.$isSchemaMap ? { path: fullPath.call(this) } : null; value = this.$__schemaType.applySetters( value, this.$__parent, false, this.get(key), options ); } catch (error) { if (this.$__parent != null && this.$__parent.$__ != null) { this.$__parent.invalidate(fullPath.call(this), error); return; } throw error; } } super.set(key, value); if (parent != null && parent.$__ != null && !deepEqual(value, priorVal)) { const path = fullPath.call(this); parent.markModified(path); if (this.$__schemaType.$isMongooseDocumentArray || this.$__schemaType.$isSingleNested) { cleanModifiedSubpaths(parent, path); } } function fullPath() { if (_fullPath) { return _fullPath; } _fullPath = this.$__path + "." + key; return _fullPath; } } /** * Overwrites native Map's `clear()` function to support change tracking. * * @api public * @method clear * @memberOf Map */ clear() { super.clear(); const parent = this.$__parent; if (parent != null) { parent.markModified(this.$__path); } } /** * Overwrites native Map's `delete()` function to support change tracking. * * @api public * @method delete * @memberOf Map */ delete(key) { if (isBsonType(key, "ObjectId")) { key = key.toString(); } this.set(key, void 0); return super.delete(key); } /** * Converts this map to a native JavaScript Map so the MongoDB driver can serialize it. * * @api public * @method toBSON * @memberOf Map */ toBSON() { return new Map(this); } toObject(options) { if (options && options.flattenMaps) { const ret = {}; const keys = this.keys(); for (const key of keys) { ret[key] = clone(this.get(key), options); } return ret; } return new Map(this); } $toObject() { return this.constructor.prototype.toObject.apply(this, arguments); } /** * Converts this map to a native JavaScript Map for `JSON.stringify()`. Set * the `flattenMaps` option to convert this map to a POJO instead. * * #### Example: * * doc.myMap.toJSON() instanceof Map; // true * doc.myMap.toJSON({ flattenMaps: true }) instanceof Map; // false * * @api public * @method toJSON * @param {Object} [options] * @param {Boolean} [options.flattenMaps=false] set to `true` to convert the map to a POJO rather than a native JavaScript map * @memberOf Map */ toJSON(options) { if (typeof (options && options.flattenMaps) === "boolean" ? options.flattenMaps : true) { const ret = {}; const keys = this.keys(); for (const key of keys) { ret[key] = clone(this.get(key), options); } return ret; } return new Map(this); } inspect() { return new Map(this); } $__runDeferred() { if (!this.$__deferred) { return; } for (const keyValueObject of this.$__deferred) { this.set(keyValueObject.key, keyValueObject.value); } this.$__deferred = null; } }; if (util.inspect.custom) { Object.defineProperty(MongooseMap.prototype, util.inspect.custom, { enumerable: false, writable: false, configurable: false, value: MongooseMap.prototype.inspect }); } Object.defineProperty(MongooseMap.prototype, "$__set", { enumerable: false, writable: true, configurable: false }); Object.defineProperty(MongooseMap.prototype, "$__parent", { enumerable: false, writable: true, configurable: false }); Object.defineProperty(MongooseMap.prototype, "$__path", { enumerable: false, writable: true, configurable: false }); Object.defineProperty(MongooseMap.prototype, "$__schemaType", { enumerable: false, writable: true, configurable: false }); Object.defineProperty(MongooseMap.prototype, "$isMongooseMap", { enumerable: false, writable: false, configurable: false, value: true }); Object.defineProperty(MongooseMap.prototype, "$__deferredCalls", { enumerable: false, writable: false, configurable: false, value: true }); function checkValidKey(key) { const keyType = typeof key; if (keyType !== "string") { throw new TypeError(`Mongoose maps only support string keys, got ${keyType}`); } if (key.startsWith("$")) { throw new Error(`Mongoose maps do not support keys that start with "$", got "${key}"`); } if (key.includes(".")) { throw new Error(`Mongoose maps do not support keys that contain ".", got "${key}"`); } if (specialProperties.has(key)) { throw new Error(`Mongoose maps do not support reserved key name "${key}"`); } } module2.exports = MongooseMap; } }); // netlify/functions/node_modules/mongoose/lib/types/uuid.js var require_uuid = __commonJS({ "netlify/functions/node_modules/mongoose/lib/types/uuid.js"(exports2, module2) { "use strict"; module2.exports = require_bson().UUID; } }); // netlify/functions/node_modules/mongoose/lib/types/index.js var require_types = __commonJS({ "netlify/functions/node_modules/mongoose/lib/types/index.js"(exports2) { "use strict"; exports2.Array = require_array(); exports2.Buffer = require_buffer(); exports2.Document = // @deprecate exports2.Embedded = require_arraySubdocument(); exports2.DocumentArray = require_documentArray(); exports2.Double = require_double(); exports2.Decimal128 = require_decimal128(); exports2.ObjectId = require_objectid(); exports2.Map = require_map(); exports2.Subdocument = require_subdocument(); exports2.UUID = require_uuid(); } }); // netlify/functions/node_modules/mongoose/lib/options/schemaArrayOptions.js var require_schemaArrayOptions = __commonJS({ "netlify/functions/node_modules/mongoose/lib/options/schemaArrayOptions.js"(exports2, module2) { "use strict"; var SchemaTypeOptions = require_schemaTypeOptions(); var SchemaArrayOptions = class extends SchemaTypeOptions { }; var opts = require_propertyOptions(); Object.defineProperty(SchemaArrayOptions.prototype, "enum", opts); Object.defineProperty(SchemaArrayOptions.prototype, "of", opts); Object.defineProperty(SchemaArrayOptions.prototype, "castNonArrays", opts); module2.exports = SchemaArrayOptions; } }); // netlify/functions/node_modules/mongoose/lib/helpers/arrayDepth.js var require_arrayDepth = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/arrayDepth.js"(exports2, module2) { "use strict"; module2.exports = arrayDepth; function arrayDepth(arr) { if (!Array.isArray(arr)) { return { min: 0, max: 0, containsNonArrayItem: true }; } if (arr.length === 0) { return { min: 1, max: 1, containsNonArrayItem: false }; } if (arr.length === 1 && !Array.isArray(arr[0])) { return { min: 1, max: 1, containsNonArrayItem: false }; } const res = arrayDepth(arr[0]); for (let i = 1; i < arr.length; ++i) { const _res = arrayDepth(arr[i]); if (_res.min < res.min) { res.min = _res.min; } if (_res.max > res.max) { res.max = _res.max; } res.containsNonArrayItem = res.containsNonArrayItem || _res.containsNonArrayItem; } res.min = res.min + 1; res.max = res.max + 1; return res; } } }); // netlify/functions/node_modules/mongoose/lib/cast/number.js var require_number = __commonJS({ "netlify/functions/node_modules/mongoose/lib/cast/number.js"(exports2, module2) { "use strict"; var assert = require("assert"); module2.exports = function castNumber(val) { if (val == null) { return val; } if (val === "") { return null; } if (typeof val === "string" || typeof val === "boolean") { val = Number(val); } assert.ok(!isNaN(val)); if (val instanceof Number) { return val.valueOf(); } if (typeof val === "number") { return val; } if (!Array.isArray(val) && typeof val.valueOf === "function") { return Number(val.valueOf()); } if (val.toString && !Array.isArray(val) && val.toString() == Number(val)) { return Number(val); } assert.ok(false); }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/omitUndefined.js var require_omitUndefined = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/omitUndefined.js"(exports2, module2) { "use strict"; module2.exports = function omitUndefined(val) { if (val == null || typeof val !== "object") { return val; } if (Array.isArray(val)) { for (let i = val.length - 1; i >= 0; --i) { if (val[i] === void 0) { val.splice(i, 1); } } } for (const key of Object.keys(val)) { if (val[key] === void 0) { delete val[key]; } } return val; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/query/cast$expr.js var require_cast_expr = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/query/cast$expr.js"(exports2, module2) { "use strict"; var CastError = require_cast(); var StrictModeError = require_strict(); var castNumber = require_number(); var omitUndefined = require_omitUndefined(); var booleanComparison = /* @__PURE__ */ new Set(["$and", "$or"]); var comparisonOperator = /* @__PURE__ */ new Set(["$cmp", "$eq", "$lt", "$lte", "$gt", "$gte"]); var arithmeticOperatorArray = /* @__PURE__ */ new Set([ // avoid casting '$add' or '$subtract', because expressions can be either number or date, // and we don't have a good way of inferring which arguments should be numbers and which should // be dates. "$multiply", "$divide", "$log", "$mod", "$trunc", "$avg", "$max", "$min", "$stdDevPop", "$stdDevSamp", "$sum" ]); var arithmeticOperatorNumber = /* @__PURE__ */ new Set([ "$abs", "$exp", "$ceil", "$floor", "$ln", "$log10", "$sqrt", "$sin", "$cos", "$tan", "$asin", "$acos", "$atan", "$atan2", "$asinh", "$acosh", "$atanh", "$sinh", "$cosh", "$tanh", "$degreesToRadians", "$radiansToDegrees" ]); var arrayElementOperators = /* @__PURE__ */ new Set([ "$arrayElemAt", "$first", "$last" ]); var dateOperators = /* @__PURE__ */ new Set([ "$year", "$month", "$week", "$dayOfMonth", "$dayOfYear", "$hour", "$minute", "$second", "$isoDayOfWeek", "$isoWeekYear", "$isoWeek", "$millisecond" ]); var expressionOperator = /* @__PURE__ */ new Set(["$not"]); module2.exports = function cast$expr(val, schema, strictQuery) { if (typeof val === "boolean") { return val; } if (typeof val !== "object" || val === null) { throw new Error("`$expr` must be an object or boolean literal"); } return _castExpression(val, schema, strictQuery); }; function _castExpression(val, schema, strictQuery) { if (isPath(val) || val === null) { return val; } if (val.$cond != null) { if (Array.isArray(val.$cond)) { val.$cond = val.$cond.map((expr) => _castExpression(expr, schema, strictQuery)); } else { val.$cond.if = _castExpression(val.$cond.if, schema, strictQuery); val.$cond.then = _castExpression(val.$cond.then, schema, strictQuery); val.$cond.else = _castExpression(val.$cond.else, schema, strictQuery); } } else if (val.$ifNull != null) { val.$ifNull.map((v) => _castExpression(v, schema, strictQuery)); } else if (val.$switch != null) { if (Array.isArray(val.$switch.branches)) { val.$switch.branches = val.$switch.branches.map((v) => _castExpression(v, schema, strictQuery)); } if ("default" in val.$switch) { val.$switch.default = _castExpression(val.$switch.default, schema, strictQuery); } } const keys = Object.keys(val); for (const key of keys) { if (booleanComparison.has(key)) { val[key] = val[key].map((v) => _castExpression(v, schema, strictQuery)); } else if (comparisonOperator.has(key)) { val[key] = castComparison(val[key], schema, strictQuery); } else if (arithmeticOperatorArray.has(key)) { val[key] = castArithmetic(val[key], schema, strictQuery); } else if (arithmeticOperatorNumber.has(key)) { val[key] = castNumberOperator(val[key], schema, strictQuery); } else if (expressionOperator.has(key)) { val[key] = _castExpression(val[key], schema, strictQuery); } } if (val.$in) { val.$in = castIn(val.$in, schema, strictQuery); } if (val.$size) { val.$size = castNumberOperator(val.$size, schema, strictQuery); } if (val.$round) { const $round = val.$round; if (!Array.isArray($round) || $round.length < 1 || $round.length > 2) { throw new CastError("Array", $round, "$round"); } val.$round = $round.map((v) => castNumberOperator(v, schema, strictQuery)); } omitUndefined(val); return val; } function castNumberOperator(val) { if (!isLiteral(val)) { return val; } try { return castNumber(val); } catch (err) { throw new CastError("Number", val); } } function castIn(val, schema, strictQuery) { const path = val[1]; if (!isPath(path)) { return val; } const search = val[0]; const schematype = schema.path(path.slice(1)); if (schematype === null) { if (strictQuery === false) { return val; } else if (strictQuery === "throw") { throw new StrictModeError("$in"); } return void 0; } if (!schematype.$isMongooseArray) { throw new Error("Path must be an array for $in"); } return [ schematype.$isMongooseDocumentArray ? schematype.$embeddedSchemaType.cast(search) : schematype.caster.cast(search), path ]; } function castArithmetic(val) { if (!Array.isArray(val)) { if (!isLiteral(val)) { return val; } try { return castNumber(val); } catch (err) { throw new CastError("Number", val); } } return val.map((v) => { if (!isLiteral(v)) { return v; } try { return castNumber(v); } catch (err) { throw new CastError("Number", v); } }); } function castComparison(val, schema, strictQuery) { if (!Array.isArray(val) || val.length !== 2) { throw new Error("Comparison operator must be an array of length 2"); } val[0] = _castExpression(val[0], schema, strictQuery); const lhs = val[0]; if (isLiteral(val[1])) { let path = null; let schematype = null; let caster = null; if (isPath(lhs)) { path = lhs.slice(1); schematype = schema.path(path); } else if (typeof lhs === "object" && lhs != null) { for (const key of Object.keys(lhs)) { if (dateOperators.has(key) && isPath(lhs[key])) { path = lhs[key].slice(1) + "." + key; caster = castNumber; } else if (arrayElementOperators.has(key) && isPath(lhs[key])) { path = lhs[key].slice(1) + "." + key; schematype = schema.path(lhs[key].slice(1)); if (schematype != null) { if (schematype.$isMongooseDocumentArray) { schematype = schematype.$embeddedSchemaType; } else if (schematype.$isMongooseArray) { schematype = schematype.caster; } } } } } const is$literal = typeof val[1] === "object" && val[1] != null && val[1].$literal != null; if (schematype != null) { if (is$literal) { val[1] = { $literal: schematype.cast(val[1].$literal) }; } else { val[1] = schematype.cast(val[1]); } } else if (caster != null) { if (is$literal) { try { val[1] = { $literal: caster(val[1].$literal) }; } catch (err) { throw new CastError(caster.name.replace(/^cast/, ""), val[1], path + ".$literal"); } } else { try { val[1] = caster(val[1]); } catch (err) { throw new CastError(caster.name.replace(/^cast/, ""), val[1], path); } } } else if (path != null && strictQuery === true) { return void 0; } else if (path != null && strictQuery === "throw") { throw new StrictModeError(path); } } else { val[1] = _castExpression(val[1]); } return val; } function isPath(val) { return typeof val === "string" && val[0] === "$"; } function isLiteral(val) { if (typeof val === "string" && val[0] === "$") { return false; } if (typeof val === "object" && val !== null && Object.keys(val).find((key) => key[0] === "$")) { return val.$literal != null; } return true; } } }); // netlify/functions/node_modules/mongoose/lib/cast/string.js var require_string = __commonJS({ "netlify/functions/node_modules/mongoose/lib/cast/string.js"(exports2, module2) { "use strict"; var CastError = require_cast(); module2.exports = function castString(value, path) { if (value == null) { return value; } if (value._id && typeof value._id === "string") { return value._id; } if (value.toString && value.toString !== Object.prototype.toString && !Array.isArray(value)) { return value.toString(); } throw new CastError("string", value, path); }; } }); // netlify/functions/node_modules/mongoose/lib/schema/operators/text.js var require_text = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/operators/text.js"(exports2, module2) { "use strict"; var CastError = require_cast(); var castBoolean = require_boolean(); var castString = require_string(); module2.exports = function castTextSearch(val, path) { if (val == null || typeof val !== "object") { throw new CastError("$text", val, path); } if (val.$search != null) { val.$search = castString(val.$search, path + ".$search"); } if (val.$language != null) { val.$language = castString(val.$language, path + ".$language"); } if (val.$caseSensitive != null) { val.$caseSensitive = castBoolean( val.$caseSensitive, path + ".$castSensitive" ); } if (val.$diacriticSensitive != null) { val.$diacriticSensitive = castBoolean( val.$diacriticSensitive, path + ".$diacriticSensitive" ); } return val; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/query/isOperator.js var require_isOperator = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/query/isOperator.js"(exports2, module2) { "use strict"; var specialKeys = /* @__PURE__ */ new Set([ "$ref", "$id", "$db" ]); module2.exports = function isOperator(path) { return path[0] === "$" && !specialKeys.has(path); }; } }); // netlify/functions/node_modules/mongoose/lib/cast.js var require_cast2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/cast.js"(exports2, module2) { "use strict"; var CastError = require_cast(); var StrictModeError = require_strict(); var Types = require_schema(); var cast$expr = require_cast_expr(); var castString = require_string(); var castTextSearch = require_text(); var get = require_get(); var getSchemaDiscriminatorByValue = require_getSchemaDiscriminatorByValue(); var isOperator = require_isOperator(); var util = require("util"); var isObject = require_isObject(); var isMongooseObject = require_isMongooseObject(); var utils = require_utils3(); var ALLOWED_GEOWITHIN_GEOJSON_TYPES = ["Polygon", "MultiPolygon"]; module2.exports = function cast(schema, obj, options, context) { if (Array.isArray(obj)) { throw new Error("Query filter must be an object, got an array ", util.inspect(obj)); } if (obj == null) { return obj; } if (schema != null && schema.discriminators != null && obj[schema.options.discriminatorKey] != null) { schema = getSchemaDiscriminatorByValue(schema, obj[schema.options.discriminatorKey]) || schema; } const paths = Object.keys(obj); let i = paths.length; let _keys; let any$conditionals; let schematype; let nested; let path; let type; let val; options = options || {}; while (i--) { path = paths[i]; val = obj[path]; if (path === "$or" || path === "$nor" || path === "$and") { if (!Array.isArray(val)) { throw new CastError("Array", val, path); } for (let k = val.length - 1; k >= 0; k--) { if (val[k] == null || typeof val[k] !== "object") { throw new CastError("Object", val[k], path + "." + k); } const beforeCastKeysLength = Object.keys(val[k]).length; const discriminatorValue = val[k][schema.options.discriminatorKey]; if (discriminatorValue == null) { val[k] = cast(schema, val[k], options, context); } else { const discriminatorSchema = getSchemaDiscriminatorByValue(context.schema, discriminatorValue); val[k] = cast(discriminatorSchema ? discriminatorSchema : schema, val[k], options, context); } if (Object.keys(val[k]).length === 0 && beforeCastKeysLength !== 0) { val.splice(k, 1); } } if (val.length === 0) { delete obj[path]; } } else if (path === "$where") { type = typeof val; if (type !== "string" && type !== "function") { throw new Error("Must have a string or function for $where"); } if (type === "function") { obj[path] = val.toString(); } continue; } else if (path === "$expr") { val = cast$expr(val, schema); continue; } else if (path === "$elemMatch") { val = cast(schema, val, options, context); } else if (path === "$text") { val = castTextSearch(val, path); } else if (path === "$comment" && !schema.paths.hasOwnProperty("$comment")) { val = castString(val, path); obj[path] = val; } else { if (!schema) { continue; } schematype = schema.path(path); if (!schematype) { const split = path.split("."); let j = split.length; while (j--) { const pathFirstHalf = split.slice(0, j).join("."); const pathLastHalf = split.slice(j).join("."); const _schematype = schema.path(pathFirstHalf); const discriminatorKey = _schematype && _schematype.schema && _schematype.schema.options && _schematype.schema.options.discriminatorKey; if (_schematype != null && (_schematype.schema && _schematype.schema.discriminators) != null && discriminatorKey != null && pathLastHalf !== discriminatorKey) { const discriminatorVal = get(obj, pathFirstHalf + "." + discriminatorKey); const discriminators = _schematype.schema.discriminators; if (typeof discriminatorVal === "string" && discriminators[discriminatorVal] != null) { schematype = discriminators[discriminatorVal].path(pathLastHalf); } else if (discriminatorVal != null && Object.keys(discriminatorVal).length === 1 && Array.isArray(discriminatorVal.$in) && discriminatorVal.$in.length === 1 && typeof discriminatorVal.$in[0] === "string" && discriminators[discriminatorVal.$in[0]] != null) { schematype = discriminators[discriminatorVal.$in[0]].path(pathLastHalf); } } } } if (!schematype) { const split = path.split("."); let j = split.length; let pathFirstHalf; let pathLastHalf; let remainingConds; while (j--) { pathFirstHalf = split.slice(0, j).join("."); schematype = schema.path(pathFirstHalf); if (schematype) { break; } } if (schematype) { if (schematype.caster && schematype.caster.schema) { remainingConds = {}; pathLastHalf = split.slice(j).join("."); remainingConds[pathLastHalf] = val; const ret = cast(schematype.caster.schema, remainingConds, options, context)[pathLastHalf]; if (ret === void 0) { delete obj[path]; } else { obj[path] = ret; } } else { obj[path] = val; } continue; } if (isObject(val)) { let geo = ""; if (val.$near) { geo = "$near"; } else if (val.$nearSphere) { geo = "$nearSphere"; } else if (val.$within) { geo = "$within"; } else if (val.$geoIntersects) { geo = "$geoIntersects"; } else if (val.$geoWithin) { geo = "$geoWithin"; } if (geo) { const numbertype = new Types.Number("__QueryCasting__"); let value = val[geo]; if (val.$maxDistance != null) { val.$maxDistance = numbertype.castForQuery( null, val.$maxDistance, context ); } if (val.$minDistance != null) { val.$minDistance = numbertype.castForQuery( null, val.$minDistance, context ); } if (geo === "$within") { const withinType = value.$center || value.$centerSphere || value.$box || value.$polygon; if (!withinType) { throw new Error("Bad $within parameter: " + JSON.stringify(val)); } value = withinType; } else if (geo === "$near" && typeof value.type === "string" && Array.isArray(value.coordinates)) { value = value.coordinates; } else if ((geo === "$near" || geo === "$nearSphere" || geo === "$geoIntersects") && value.$geometry && typeof value.$geometry.type === "string" && Array.isArray(value.$geometry.coordinates)) { if (value.$maxDistance != null) { value.$maxDistance = numbertype.castForQuery( null, value.$maxDistance, context ); } if (value.$minDistance != null) { value.$minDistance = numbertype.castForQuery( null, value.$minDistance, context ); } if (isMongooseObject(value.$geometry)) { value.$geometry = value.$geometry.toObject({ transform: false, virtuals: false }); } value = value.$geometry.coordinates; } else if (geo === "$geoWithin") { if (value.$geometry) { if (isMongooseObject(value.$geometry)) { value.$geometry = value.$geometry.toObject({ virtuals: false }); } const geoWithinType = value.$geometry.type; if (ALLOWED_GEOWITHIN_GEOJSON_TYPES.indexOf(geoWithinType) === -1) { throw new Error('Invalid geoJSON type for $geoWithin "' + geoWithinType + '", must be "Polygon" or "MultiPolygon"'); } value = value.$geometry.coordinates; } else { value = value.$box || value.$polygon || value.$center || value.$centerSphere; if (isMongooseObject(value)) { value = value.toObject({ virtuals: false }); } } } _cast(value, numbertype, context); continue; } } if (schema.nested[path]) { continue; } const strict = "strict" in options ? options.strict : schema.options.strict; const strictQuery = getStrictQuery(options, schema._userProvidedOptions, schema.options, context); if (options.upsert && strict) { if (strict === "throw") { throw new StrictModeError(path); } throw new StrictModeError(path, 'Path "' + path + '" is not in schema, strict mode is `true`, and upsert is `true`.'); } if (strictQuery === "throw") { throw new StrictModeError(path, 'Path "' + path + `" is not in schema and strictQuery is 'throw'.`); } else if (strictQuery) { delete obj[path]; } } else if (val == null) { continue; } else if (utils.isPOJO(val)) { any$conditionals = Object.keys(val).some(isOperator); if (!any$conditionals) { obj[path] = schematype.castForQuery( null, val, context ); } else { const ks = Object.keys(val); let $cond; let k = ks.length; while (k--) { $cond = ks[k]; nested = val[$cond]; if ($cond === "$elemMatch") { if (nested && schematype != null && schematype.schema != null) { cast(schematype.schema, nested, options, context); } else if (nested && schematype != null && schematype.$isMongooseArray) { if (utils.isPOJO(nested) && nested.$not != null) { cast(schema, nested, options, context); } else { val[$cond] = schematype.castForQuery( $cond, nested, context ); } } } else if ($cond === "$not") { if (nested && schematype) { _keys = Object.keys(nested); if (_keys.length && isOperator(_keys[0])) { for (const key in nested) { nested[key] = schematype.castForQuery( key, nested[key], context ); } } else { val[$cond] = schematype.castForQuery( $cond, nested, context ); } continue; } } else { val[$cond] = schematype.castForQuery( $cond, nested, context ); } } } } else if (Array.isArray(val) && ["Buffer", "Array"].indexOf(schematype.instance) === -1 && !options.sanitizeFilter) { const casted = []; const valuesArray = val; for (const _val of valuesArray) { casted.push(schematype.castForQuery( null, _val, context )); } obj[path] = { $in: casted }; } else { obj[path] = schematype.castForQuery( null, val, context ); } } } return obj; }; function _cast(val, numbertype, context) { if (Array.isArray(val)) { val.forEach(function(item, i) { if (Array.isArray(item) || isObject(item)) { return _cast(item, numbertype, context); } val[i] = numbertype.castForQuery(null, item, context); }); } else { const nearKeys = Object.keys(val); let nearLen = nearKeys.length; while (nearLen--) { const nkey = nearKeys[nearLen]; const item = val[nkey]; if (Array.isArray(item) || isObject(item)) { _cast(item, numbertype, context); val[nkey] = item; } else { val[nkey] = numbertype.castForQuery({ val: item, context }); } } } } function getStrictQuery(queryOptions, schemaUserProvidedOptions, schemaOptions, context) { if ("strictQuery" in queryOptions) { return queryOptions.strictQuery; } if ("strictQuery" in schemaUserProvidedOptions) { return schemaUserProvidedOptions.strictQuery; } const mongooseOptions = context && context.mongooseCollection && context.mongooseCollection.conn && context.mongooseCollection.conn.base && context.mongooseCollection.conn.base.options; if (mongooseOptions) { if ("strictQuery" in mongooseOptions) { return mongooseOptions.strictQuery; } } return schemaOptions.strictQuery; } } }); // netlify/functions/node_modules/mongoose/lib/options/schemaNumberOptions.js var require_schemaNumberOptions = __commonJS({ "netlify/functions/node_modules/mongoose/lib/options/schemaNumberOptions.js"(exports2, module2) { "use strict"; var SchemaTypeOptions = require_schemaTypeOptions(); var SchemaNumberOptions = class extends SchemaTypeOptions { }; var opts = require_propertyOptions(); Object.defineProperty(SchemaNumberOptions.prototype, "min", opts); Object.defineProperty(SchemaNumberOptions.prototype, "max", opts); Object.defineProperty(SchemaNumberOptions.prototype, "enum", opts); Object.defineProperty(SchemaNumberOptions.prototype, "populate", opts); module2.exports = SchemaNumberOptions; } }); // netlify/functions/node_modules/mongoose/lib/helpers/createJSONSchemaTypeDefinition.js var require_createJSONSchemaTypeDefinition = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/createJSONSchemaTypeDefinition.js"(exports2, module2) { "use strict"; module2.exports = function createJSONSchemaTypeArray(type, bsonType, useBsonType, isRequired) { if (useBsonType) { if (isRequired) { return { bsonType }; } return { bsonType: [bsonType, "null"] }; } else { if (isRequired) { return { type }; } return { type: [type, "null"] }; } }; } }); // netlify/functions/node_modules/mongoose/lib/schema/operators/bitwise.js var require_bitwise = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/operators/bitwise.js"(exports2, module2) { "use strict"; var CastError = require_cast(); function handleBitwiseOperator(val) { const _this = this; if (Array.isArray(val)) { return val.map(function(v) { return _castNumber(_this.path, v); }); } else if (Buffer.isBuffer(val)) { return val; } return _castNumber(_this.path, val); } function _castNumber(path, num) { const v = Number(num); if (isNaN(v)) { throw new CastError("number", num, path); } return v; } module2.exports = handleBitwiseOperator; } }); // netlify/functions/node_modules/mongoose/lib/schema/number.js var require_number2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/number.js"(exports2, module2) { "use strict"; var MongooseError = require_error2(); var SchemaNumberOptions = require_schemaNumberOptions(); var SchemaType = require_schemaType(); var castNumber = require_number(); var createJSONSchemaTypeDefinition = require_createJSONSchemaTypeDefinition(); var handleBitwiseOperator = require_bitwise(); var utils = require_utils3(); var CastError = SchemaType.CastError; function SchemaNumber(key, options) { SchemaType.call(this, key, options, "Number"); } SchemaNumber.get = SchemaType.get; SchemaNumber.set = SchemaType.set; SchemaNumber.setters = []; SchemaNumber._cast = castNumber; SchemaNumber.cast = function cast(caster) { if (arguments.length === 0) { return this._cast; } if (caster === false) { caster = this._defaultCaster; } this._cast = caster; return this._cast; }; SchemaNumber._defaultCaster = (v) => { if (typeof v !== "number") { throw new Error(); } return v; }; SchemaNumber.schemaName = "Number"; SchemaNumber.defaultOptions = {}; SchemaNumber.prototype = Object.create(SchemaType.prototype); SchemaNumber.prototype.constructor = SchemaNumber; SchemaNumber.prototype.OptionsConstructor = SchemaNumberOptions; SchemaNumber._checkRequired = (v) => typeof v === "number" || v instanceof Number; SchemaNumber.checkRequired = SchemaType.checkRequired; SchemaNumber.prototype.checkRequired = function checkRequired(value, doc) { if (typeof value === "object" && SchemaType._isRef(this, value, doc, true)) { return value != null; } const _checkRequired = typeof this.constructor.checkRequired === "function" ? this.constructor.checkRequired() : SchemaNumber.checkRequired(); return _checkRequired(value); }; SchemaNumber.prototype.min = function(value, message) { if (this.minValidator) { this.validators = this.validators.filter(function(v) { return v.validator !== this.minValidator; }, this); } if (value !== null && value !== void 0) { let msg = message || MongooseError.messages.Number.min; msg = msg.replace(/{MIN}/, value); this.validators.push({ validator: this.minValidator = function(v) { return v == null || v >= value; }, message: msg, type: "min", min: value }); } return this; }; SchemaNumber.prototype.max = function(value, message) { if (this.maxValidator) { this.validators = this.validators.filter(function(v) { return v.validator !== this.maxValidator; }, this); } if (value !== null && value !== void 0) { let msg = message || MongooseError.messages.Number.max; msg = msg.replace(/{MAX}/, value); this.validators.push({ validator: this.maxValidator = function(v) { return v == null || v <= value; }, message: msg, type: "max", max: value }); } return this; }; SchemaNumber.prototype.enum = function(values, message) { if (this.enumValidator) { this.validators = this.validators.filter(function(v) { return v.validator !== this.enumValidator; }, this); } if (!Array.isArray(values)) { const isObjectSyntax = utils.isPOJO(values) && values.values != null; if (isObjectSyntax) { message = values.message; values = values.values; } else if (typeof values === "number") { values = Array.prototype.slice.call(arguments); message = null; } if (utils.isPOJO(values)) { values = Object.values(values); } message = message || MongooseError.messages.Number.enum; } message = message == null ? MongooseError.messages.Number.enum : message; this.enumValidator = (v) => v == null || values.indexOf(v) !== -1; this.validators.push({ validator: this.enumValidator, message, type: "enum", enumValues: values }); return this; }; SchemaNumber.prototype.cast = function(value, doc, init, prev, options) { if (typeof value !== "number" && SchemaType._isRef(this, value, doc, init)) { if (value == null || utils.isNonBuiltinObject(value)) { return this._castRef(value, doc, init, options); } } const val = value && typeof value._id !== "undefined" ? value._id : ( // documents value ); let castNumber2; if (typeof this._castFunction === "function") { castNumber2 = this._castFunction; } else if (typeof this.constructor.cast === "function") { castNumber2 = this.constructor.cast(); } else { castNumber2 = SchemaNumber.cast(); } try { return castNumber2(val); } catch (err) { throw new CastError("Number", val, this.path, err, this); } }; function handleSingle(val) { return this.cast(val); } function handleArray(val) { const _this = this; if (!Array.isArray(val)) { return [this.cast(val)]; } return val.map(function(m) { return _this.cast(m); }); } var $conditionalHandlers = { ...SchemaType.prototype.$conditionalHandlers, $bitsAllClear: handleBitwiseOperator, $bitsAnyClear: handleBitwiseOperator, $bitsAllSet: handleBitwiseOperator, $bitsAnySet: handleBitwiseOperator, $gt: handleSingle, $gte: handleSingle, $lt: handleSingle, $lte: handleSingle, $mod: handleArray }; Object.defineProperty(SchemaNumber.prototype, "$conditionalHandlers", { enumerable: false, value: $conditionalHandlers }); SchemaNumber.prototype.castForQuery = function($conditional, val, context) { let handler; if ($conditional != null) { handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new CastError("number", val, this.path, null, this); } return handler.call(this, val, context); } try { val = this.applySetters(val, context); } catch (err) { if (err instanceof CastError && err.path === this.path && this.$fullPath != null) { err.path = this.$fullPath; } throw err; } return val; }; SchemaNumber.prototype.toJSONSchema = function toJSONSchema(options) { const isRequired = this.options.required && typeof this.options.required !== "function" || this.path === "_id"; return createJSONSchemaTypeDefinition("number", "number", options?.useBsonType, isRequired); }; module2.exports = SchemaNumber; } }); // netlify/functions/node_modules/mongoose/lib/schema/operators/helpers.js var require_helpers = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/operators/helpers.js"(exports2) { "use strict"; var SchemaNumber = require_number2(); exports2.castToNumber = castToNumber; exports2.castArraysOfNumbers = castArraysOfNumbers; function castToNumber(val) { return SchemaNumber.cast()(val); } function castArraysOfNumbers(arr, self2) { arr.forEach(function(v, i) { if (Array.isArray(v)) { castArraysOfNumbers(v, self2); } else { arr[i] = castToNumber.call(self2, v); } }); } } }); // netlify/functions/node_modules/mongoose/lib/schema/operators/geospatial.js var require_geospatial = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/operators/geospatial.js"(exports2) { "use strict"; var castArraysOfNumbers = require_helpers().castArraysOfNumbers; var castToNumber = require_helpers().castToNumber; exports2.cast$geoIntersects = cast$geoIntersects; exports2.cast$near = cast$near; exports2.cast$within = cast$within; function cast$near(val) { const SchemaArray = require_array2(); if (Array.isArray(val)) { castArraysOfNumbers(val, this); return val; } _castMinMaxDistance(this, val); if (val && val.$geometry) { return cast$geometry(val, this); } if (!Array.isArray(val)) { throw new TypeError("$near must be either an array or an object with a $geometry property"); } return SchemaArray.prototype.castForQuery.call(this, null, val); } function cast$geometry(val, self2) { switch (val.$geometry.type) { case "Polygon": case "LineString": case "Point": castArraysOfNumbers(val.$geometry.coordinates, self2); break; default: break; } _castMinMaxDistance(self2, val); return val; } function cast$within(val) { _castMinMaxDistance(this, val); if (val.$box || val.$polygon) { const type = val.$box ? "$box" : "$polygon"; val[type].forEach((arr) => { if (!Array.isArray(arr)) { const msg = "Invalid $within $box argument. Expected an array, received " + arr; throw new TypeError(msg); } arr.forEach((v, i) => { arr[i] = castToNumber.call(this, v); }); }); } else if (val.$center || val.$centerSphere) { const type = val.$center ? "$center" : "$centerSphere"; val[type].forEach((item, i) => { if (Array.isArray(item)) { item.forEach((v, j) => { item[j] = castToNumber.call(this, v); }); } else { val[type][i] = castToNumber.call(this, item); } }); } else if (val.$geometry) { cast$geometry(val, this); } return val; } function cast$geoIntersects(val) { const geo = val.$geometry; if (!geo) { return; } cast$geometry(val, this); return val; } function _castMinMaxDistance(self2, val) { if (val.$maxDistance) { val.$maxDistance = castToNumber.call(self2, val.$maxDistance); } if (val.$minDistance) { val.$minDistance = castToNumber.call(self2, val.$minDistance); } } } }); // netlify/functions/node_modules/mongoose/lib/schema/array.js var require_array2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/array.js"(exports2, module2) { "use strict"; var $exists = require_exists(); var $type = require_type(); var MongooseError = require_mongooseError(); var SchemaArrayOptions = require_schemaArrayOptions(); var SchemaType = require_schemaType(); var CastError = SchemaType.CastError; var Mixed = require_mixed(); var VirtualOptions = require_virtualOptions(); var VirtualType = require_virtualType(); var arrayDepth = require_arrayDepth(); var cast = require_cast2(); var clone = require_clone(); var getConstructorName = require_getConstructorName(); var isOperator = require_isOperator(); var util = require("util"); var utils = require_utils3(); var castToNumber = require_helpers().castToNumber; var createJSONSchemaTypeDefinition = require_createJSONSchemaTypeDefinition(); var geospatial = require_geospatial(); var getDiscriminatorByValue = require_getDiscriminatorByValue(); var MongooseArray; var EmbeddedDoc; var isNestedArraySymbol = Symbol("mongoose#isNestedArray"); var emptyOpts = Object.freeze({}); function SchemaArray(key, cast2, options, schemaOptions) { EmbeddedDoc || (EmbeddedDoc = require_types().Embedded); let typeKey = "type"; if (schemaOptions && schemaOptions.typeKey) { typeKey = schemaOptions.typeKey; } this.schemaOptions = schemaOptions; if (cast2) { let castOptions = {}; if (utils.isPOJO(cast2)) { if (cast2[typeKey]) { castOptions = clone(cast2); delete castOptions[typeKey]; cast2 = cast2[typeKey]; } else { cast2 = Mixed; } } if (options != null && options.ref != null && castOptions.ref == null) { castOptions.ref = options.ref; } if (cast2 === Object) { cast2 = Mixed; } const name = typeof cast2 === "string" ? cast2 : utils.getFunctionName(cast2); const Types = require_schema(); const caster = Types.hasOwnProperty(name) ? Types[name] : cast2; this.casterConstructor = caster; if (this.casterConstructor instanceof SchemaArray) { this.casterConstructor[isNestedArraySymbol] = true; } if (typeof caster === "function" && !caster.$isArraySubdocument && !caster.$isSchemaMap) { const path = this.caster instanceof EmbeddedDoc ? null : key; this.caster = new caster(path, castOptions); } else { this.caster = caster; if (!(this.caster instanceof EmbeddedDoc)) { this.caster.path = key; } } this.$embeddedSchemaType = this.caster; } this.$isMongooseArray = true; SchemaType.call(this, key, options, "Array"); let defaultArr; let fn; if (this.defaultValue != null) { defaultArr = this.defaultValue; fn = typeof defaultArr === "function"; } if (!("defaultValue" in this) || this.defaultValue != null) { const defaultFn = function() { return fn ? defaultArr.call(this) : defaultArr != null ? [].concat(defaultArr) : []; }; defaultFn.$runBeforeSetters = !fn; this.default(defaultFn); } } SchemaArray.schemaName = "Array"; SchemaArray.options = { castNonArrays: true }; SchemaArray.defaultOptions = {}; SchemaArray.set = SchemaType.set; SchemaArray.setters = []; SchemaArray.get = SchemaType.get; SchemaArray.prototype = Object.create(SchemaType.prototype); SchemaArray.prototype.constructor = SchemaArray; SchemaArray.prototype.OptionsConstructor = SchemaArrayOptions; SchemaArray._checkRequired = SchemaType.prototype.checkRequired; SchemaArray.checkRequired = SchemaType.checkRequired; SchemaArray.prototype.virtuals = null; SchemaArray.prototype.checkRequired = function checkRequired(value, doc) { if (typeof value === "object" && SchemaType._isRef(this, value, doc, true)) { return !!value; } const _checkRequired = typeof this.constructor.checkRequired === "function" ? this.constructor.checkRequired() : SchemaArray.checkRequired(); return _checkRequired(value); }; SchemaArray.prototype.enum = function() { let arr = this; while (true) { const instance = arr && arr.caster && arr.caster.instance; if (instance === "Array") { arr = arr.caster; continue; } if (instance !== "String" && instance !== "Number") { throw new Error("`enum` can only be set on an array of strings or numbers , not " + instance); } break; } let enumArray = arguments; if (!Array.isArray(arguments) && utils.isObject(arguments)) { enumArray = utils.object.vals(enumArray); } arr.caster.enum.apply(arr.caster, enumArray); return this; }; SchemaArray.prototype.applyGetters = function(value, scope) { if (scope != null && scope.$__ != null && scope.$populated(this.path)) { return value; } const ret = SchemaType.prototype.applyGetters.call(this, value, scope); return ret; }; SchemaArray.prototype._applySetters = function(value, scope, init, priorVal) { if (this.casterConstructor.$isMongooseArray && SchemaArray.options.castNonArrays && !this[isNestedArraySymbol]) { let depth = 0; let arr = this; while (arr != null && arr.$isMongooseArray && !arr.$isMongooseDocumentArray) { ++depth; arr = arr.casterConstructor; } if (value != null && value.length !== 0) { const valueDepth = arrayDepth(value); if (valueDepth.min === valueDepth.max && valueDepth.max < depth && valueDepth.containsNonArrayItem) { for (let i = valueDepth.max; i < depth; ++i) { value = [value]; } } } } return SchemaType.prototype._applySetters.call(this, value, scope, init, priorVal); }; SchemaArray.prototype.cast = function(value, doc, init, prev, options) { MongooseArray || (MongooseArray = require_types().Array); let i; let l; if (Array.isArray(value)) { const len = value.length; if (!len && doc) { const indexes = doc.schema.indexedPaths(); const arrayPath = this.path; for (i = 0, l = indexes.length; i < l; ++i) { const pathIndex = indexes[i][0][arrayPath]; if (pathIndex === "2dsphere" || pathIndex === "2d") { return; } } const arrayGeojsonPath = this.path.endsWith(".coordinates") ? this.path.substring(0, this.path.lastIndexOf(".")) : null; if (arrayGeojsonPath != null) { for (i = 0, l = indexes.length; i < l; ++i) { const pathIndex = indexes[i][0][arrayGeojsonPath]; if (pathIndex === "2dsphere") { return; } } } } options = options || emptyOpts; let rawValue = utils.isMongooseArray(value) ? value.__array : value; let path = options.path || this.path; if (options.arrayPathIndex != null) { path += "." + options.arrayPathIndex; } value = MongooseArray(rawValue, path, doc, this); rawValue = value.__array; if (init && doc != null && doc.$__ != null && doc.$populated(this.path)) { return value; } const caster = this.caster; const isMongooseArray = caster.$isMongooseArray; if (caster && this.casterConstructor !== Mixed) { try { const len2 = rawValue.length; for (i = 0; i < len2; i++) { const opts = {}; if (isMongooseArray) { if (options.arrayPath != null) { opts.arrayPathIndex = i; } else if (caster._arrayParentPath != null) { opts.arrayPathIndex = i; } } if (options.hydratedPopulatedDocs) { opts.hydratedPopulatedDocs = options.hydratedPopulatedDocs; } rawValue[i] = caster.applySetters(rawValue[i], doc, init, void 0, opts); } } catch (e) { throw new CastError("[" + e.kind + "]", util.inspect(value), this.path + "." + i, e, this); } } return value; } const castNonArraysOption = this.options.castNonArrays != null ? this.options.castNonArrays : SchemaArray.options.castNonArrays; if (init || castNonArraysOption) { if (!!doc && !!init) { doc.markModified(this.path); } return this.cast([value], doc, init); } throw new CastError("Array", util.inspect(value), this.path, null, this); }; SchemaArray.prototype._castForPopulate = function _castForPopulate(value, doc) { MongooseArray || (MongooseArray = require_types().Array); if (Array.isArray(value)) { let i; const rawValue = value.__array ? value.__array : value; const len = rawValue.length; const caster = this.caster; if (caster && this.casterConstructor !== Mixed) { try { for (i = 0; i < len; i++) { const opts = {}; if (caster.$isMongooseArray && caster._arrayParentPath != null) { opts.arrayPathIndex = i; } rawValue[i] = caster.cast(rawValue[i], doc, false, void 0, opts); } } catch (e) { throw new CastError("[" + e.kind + "]", util.inspect(value), this.path + "." + i, e, this); } } return value; } throw new CastError("Array", util.inspect(value), this.path, null, this); }; SchemaArray.prototype.$toObject = SchemaArray.prototype.toObject; SchemaArray.prototype.discriminator = function(...args) { let arr = this; while (arr.$isMongooseArray && !arr.$isMongooseDocumentArray) { arr = arr.casterConstructor; if (arr == null || typeof arr === "function") { throw new MongooseError("You can only add an embedded discriminator on a document array, " + this.path + " is a plain array"); } } return arr.discriminator(...args); }; SchemaArray.prototype.clone = function() { const options = Object.assign({}, this.options); const schematype = new this.constructor(this.path, this.caster, options, this.schemaOptions); schematype.validators = this.validators.slice(); if (this.requiredValidator !== void 0) { schematype.requiredValidator = this.requiredValidator; } return schematype; }; SchemaArray.prototype._castForQuery = function(val, context) { let Constructor = this.casterConstructor; if (val && Constructor.discriminators && Constructor.schema && Constructor.schema.options && Constructor.schema.options.discriminatorKey) { if (typeof val[Constructor.schema.options.discriminatorKey] === "string" && Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]) { Constructor = Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]; } else { const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, val[Constructor.schema.options.discriminatorKey]); if (constructorByValue) { Constructor = constructorByValue; } } } const proto = this.casterConstructor.prototype; const protoCastForQuery = proto && proto.castForQuery; const protoCast = proto && proto.cast; const constructorCastForQuery = Constructor.castForQuery; const caster = this.caster; if (Array.isArray(val)) { this.setters.reverse().forEach((setter) => { val = setter.call(this, val, this); }); val = val.map(function(v) { if (utils.isObject(v) && v.$elemMatch) { return v; } if (protoCastForQuery) { v = protoCastForQuery.call(caster, null, v, context); return v; } else if (protoCast) { v = protoCast.call(caster, v); return v; } else if (constructorCastForQuery) { v = constructorCastForQuery.call(caster, null, v, context); return v; } if (v != null) { v = new Constructor(v); return v; } return v; }); } else if (protoCastForQuery) { val = protoCastForQuery.call(caster, null, val, context); } else if (protoCast) { val = protoCast.call(caster, val); } else if (constructorCastForQuery) { val = constructorCastForQuery.call(caster, null, val, context); } else if (val != null) { val = new Constructor(val); } return val; }; SchemaArray.prototype.castForQuery = function($conditional, val, context) { let handler; if ($conditional != null) { handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new Error("Can't use " + $conditional + " with Array."); } return handler.call(this, val, context); } else { return this._castForQuery(val, context); } }; SchemaArray.prototype.virtual = function virtual(name, options) { if (name instanceof VirtualType || getConstructorName(name) === "VirtualType") { return this.virtual(name.path, name.options); } options = new VirtualOptions(options); if (utils.hasUserDefinedProperty(options, ["ref", "refPath"])) { throw new MongooseError("Cannot set populate virtual as a property of an array"); } const virtual2 = new VirtualType(options, name); if (this.virtuals === null) { this.virtuals = {}; } this.virtuals[name] = virtual2; return virtual2; }; function cast$all(val, context) { if (!Array.isArray(val)) { val = [val]; } val = val.map((v) => { if (!utils.isObject(v)) { return v; } if (v.$elemMatch != null) { return { $elemMatch: cast(this.casterConstructor.schema, v.$elemMatch, null, this && this.$$context) }; } const o = {}; o[this.path] = v; return cast(this.casterConstructor.schema, o, null, this && this.$$context)[this.path]; }, this); return this.castForQuery(null, val, context); } function cast$elemMatch(val, context) { const keys = Object.keys(val); const numKeys = keys.length; for (let i = 0; i < numKeys; ++i) { const key = keys[i]; const value = val[key]; if (isOperator(key) && value != null) { val[key] = this.castForQuery(key, value, context); } } return val; } var handle = SchemaArray.prototype.$conditionalHandlers = {}; handle.$all = cast$all; handle.$options = String; handle.$elemMatch = cast$elemMatch; handle.$geoIntersects = geospatial.cast$geoIntersects; handle.$or = createLogicalQueryOperatorHandler("$or"); handle.$and = createLogicalQueryOperatorHandler("$and"); handle.$nor = createLogicalQueryOperatorHandler("$nor"); function createLogicalQueryOperatorHandler(op) { return function logicalQueryOperatorHandler(val, context) { if (!Array.isArray(val)) { throw new TypeError("conditional " + op + " requires an array"); } const ret = []; for (const obj of val) { ret.push(cast(this.casterConstructor.schema ?? context.schema, obj, null, this && this.$$context)); } return ret; }; } handle.$near = handle.$nearSphere = geospatial.cast$near; handle.$within = handle.$geoWithin = geospatial.cast$within; handle.$size = handle.$minDistance = handle.$maxDistance = castToNumber; handle.$exists = $exists; handle.$type = $type; handle.$eq = handle.$gt = handle.$gte = handle.$lt = handle.$lte = handle.$not = handle.$regex = handle.$ne = SchemaArray.prototype._castForQuery; handle.$nin = SchemaType.prototype.$conditionalHandlers.$nin; handle.$in = SchemaType.prototype.$conditionalHandlers.$in; SchemaArray.prototype.toJSONSchema = function toJSONSchema(options) { const embeddedSchemaType = this.getEmbeddedSchemaType(); const isRequired = this.options.required && typeof this.options.required !== "function"; return { ...createJSONSchemaTypeDefinition("array", "array", options?.useBsonType, isRequired), items: embeddedSchemaType.toJSONSchema(options) }; }; SchemaArray.prototype.autoEncryptionType = function autoEncryptionType() { return "array"; }; module2.exports = SchemaArray; } }); // netlify/functions/node_modules/mongoose/lib/cast/bigint.js var require_bigint = __commonJS({ "netlify/functions/node_modules/mongoose/lib/cast/bigint.js"(exports2, module2) { "use strict"; var { Long } = require_bson(); var MAX_BIGINT = 9223372036854775807n; var MIN_BIGINT = -9223372036854775808n; var ERROR_MESSAGE = `Mongoose only supports BigInts between ${MIN_BIGINT} and ${MAX_BIGINT} because MongoDB does not support arbitrary precision integers`; module2.exports = function castBigInt(val) { if (val == null) { return val; } if (val === "") { return null; } if (typeof val === "bigint") { if (val > MAX_BIGINT || val < MIN_BIGINT) { throw new Error(ERROR_MESSAGE); } return val; } if (val instanceof Long) { return val.toBigInt(); } if (typeof val === "string" || typeof val === "number") { val = BigInt(val); if (val > MAX_BIGINT || val < MIN_BIGINT) { throw new Error(ERROR_MESSAGE); } return val; } throw new Error(`Cannot convert value to BigInt: "${val}"`); }; } }); // netlify/functions/node_modules/mongoose/lib/schema/bigint.js var require_bigint2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/bigint.js"(exports2, module2) { "use strict"; var CastError = require_cast(); var SchemaType = require_schemaType(); var castBigInt = require_bigint(); var createJSONSchemaTypeDefinition = require_createJSONSchemaTypeDefinition(); function SchemaBigInt(path, options) { SchemaType.call(this, path, options, "BigInt"); } SchemaBigInt.schemaName = "BigInt"; SchemaBigInt.defaultOptions = {}; SchemaBigInt.prototype = Object.create(SchemaType.prototype); SchemaBigInt.prototype.constructor = SchemaBigInt; SchemaBigInt._cast = castBigInt; SchemaBigInt.set = SchemaType.set; SchemaBigInt.setters = []; SchemaBigInt.get = SchemaType.get; SchemaBigInt.cast = function cast(caster) { if (arguments.length === 0) { return this._cast; } if (caster === false) { caster = this._defaultCaster; } this._cast = caster; return this._cast; }; SchemaBigInt._checkRequired = (v) => v != null; SchemaBigInt.checkRequired = SchemaType.checkRequired; SchemaBigInt.prototype.checkRequired = function(value) { return this.constructor._checkRequired(value); }; SchemaBigInt.prototype.cast = function(value) { let castBigInt2; if (typeof this._castFunction === "function") { castBigInt2 = this._castFunction; } else if (typeof this.constructor.cast === "function") { castBigInt2 = this.constructor.cast(); } else { castBigInt2 = SchemaBigInt.cast(); } try { return castBigInt2(value); } catch (error) { throw new CastError("BigInt", value, this.path, error, this); } }; var $conditionalHandlers = { ...SchemaType.prototype.$conditionalHandlers, $gt: handleSingle, $gte: handleSingle, $lt: handleSingle, $lte: handleSingle }; Object.defineProperty(SchemaBigInt.prototype, "$conditionalHandlers", { enumerable: false, value: $conditionalHandlers }); function handleSingle(val, context) { return this.castForQuery(null, val, context); } SchemaBigInt.prototype.castForQuery = function($conditional, val, context) { let handler; if ($conditional != null) { handler = this.$conditionalHandlers[$conditional]; if (handler) { return handler.call(this, val); } return this.applySetters(val, context); } try { return this.applySetters(val, context); } catch (err) { if (err instanceof CastError && err.path === this.path && this.$fullPath != null) { err.path = this.$fullPath; } throw err; } }; SchemaBigInt.prototype._castNullish = function _castNullish(v) { if (typeof v === "undefined") { return v; } const castBigInt2 = typeof this.constructor.cast === "function" ? this.constructor.cast() : SchemaBigInt.cast(); if (castBigInt2 == null) { return v; } return v; }; SchemaBigInt.prototype.toJSONSchema = function toJSONSchema(options) { const isRequired = this.options.required && typeof this.options.required !== "function"; return createJSONSchemaTypeDefinition("string", "long", options?.useBsonType, isRequired); }; SchemaBigInt.prototype.autoEncryptionType = function autoEncryptionType() { return "long"; }; module2.exports = SchemaBigInt; } }); // netlify/functions/node_modules/mongoose/lib/schema/boolean.js var require_boolean2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/boolean.js"(exports2, module2) { "use strict"; var CastError = require_cast(); var SchemaType = require_schemaType(); var castBoolean = require_boolean(); var createJSONSchemaTypeDefinition = require_createJSONSchemaTypeDefinition(); function SchemaBoolean(path, options) { SchemaType.call(this, path, options, "Boolean"); } SchemaBoolean.schemaName = "Boolean"; SchemaBoolean.defaultOptions = {}; SchemaBoolean.prototype = Object.create(SchemaType.prototype); SchemaBoolean.prototype.constructor = SchemaBoolean; SchemaBoolean._cast = castBoolean; SchemaBoolean.set = SchemaType.set; SchemaBoolean.setters = []; SchemaBoolean.get = SchemaType.get; SchemaBoolean.cast = function cast(caster) { if (arguments.length === 0) { return this._cast; } if (caster === false) { caster = this._defaultCaster; } this._cast = caster; return this._cast; }; SchemaBoolean._defaultCaster = (v) => { if (v != null && typeof v !== "boolean") { throw new Error(); } return v; }; SchemaBoolean._checkRequired = (v) => v === true || v === false; SchemaBoolean.checkRequired = SchemaType.checkRequired; SchemaBoolean.prototype.checkRequired = function(value) { return this.constructor._checkRequired(value); }; Object.defineProperty(SchemaBoolean, "convertToTrue", { get: () => castBoolean.convertToTrue, set: (v) => { castBoolean.convertToTrue = v; } }); Object.defineProperty(SchemaBoolean, "convertToFalse", { get: () => castBoolean.convertToFalse, set: (v) => { castBoolean.convertToFalse = v; } }); SchemaBoolean.prototype.cast = function(value) { let castBoolean2; if (typeof this._castFunction === "function") { castBoolean2 = this._castFunction; } else if (typeof this.constructor.cast === "function") { castBoolean2 = this.constructor.cast(); } else { castBoolean2 = SchemaBoolean.cast(); } try { return castBoolean2(value); } catch (error) { throw new CastError("Boolean", value, this.path, error, this); } }; var $conditionalHandlers = { ...SchemaType.prototype.$conditionalHandlers }; Object.defineProperty(SchemaBoolean.prototype, "$conditionalHandlers", { enumerable: false, value: $conditionalHandlers }); SchemaBoolean.prototype.castForQuery = function($conditional, val, context) { let handler; if ($conditional != null) { handler = this.$conditionalHandlers[$conditional]; if (handler) { return handler.call(this, val); } return this.applySetters(val, context); } try { return this.applySetters(val, context); } catch (err) { if (err instanceof CastError && err.path === this.path && this.$fullPath != null) { err.path = this.$fullPath; } throw err; } }; SchemaBoolean.prototype._castNullish = function _castNullish(v) { if (typeof v === "undefined") { return v; } const castBoolean2 = typeof this.constructor.cast === "function" ? this.constructor.cast() : SchemaBoolean.cast(); if (castBoolean2 == null) { return v; } if (castBoolean2.convertToFalse instanceof Set && castBoolean2.convertToFalse.has(v)) { return false; } if (castBoolean2.convertToTrue instanceof Set && castBoolean2.convertToTrue.has(v)) { return true; } return v; }; SchemaBoolean.prototype.toJSONSchema = function toJSONSchema(options) { const isRequired = this.options.required && typeof this.options.required !== "function"; return createJSONSchemaTypeDefinition("boolean", "bool", options?.useBsonType, isRequired); }; SchemaBoolean.prototype.autoEncryptionType = function autoEncryptionType() { return "bool"; }; module2.exports = SchemaBoolean; } }); // netlify/functions/node_modules/mongoose/lib/options/schemaBufferOptions.js var require_schemaBufferOptions = __commonJS({ "netlify/functions/node_modules/mongoose/lib/options/schemaBufferOptions.js"(exports2, module2) { "use strict"; var SchemaTypeOptions = require_schemaTypeOptions(); var SchemaBufferOptions = class extends SchemaTypeOptions { }; var opts = require_propertyOptions(); Object.defineProperty(SchemaBufferOptions.prototype, "subtype", opts); module2.exports = SchemaBufferOptions; } }); // netlify/functions/node_modules/mongoose/lib/schema/buffer.js var require_buffer2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/buffer.js"(exports2, module2) { "use strict"; var MongooseBuffer = require_buffer(); var SchemaBufferOptions = require_schemaBufferOptions(); var SchemaType = require_schemaType(); var createJSONSchemaTypeDefinition = require_createJSONSchemaTypeDefinition(); var handleBitwiseOperator = require_bitwise(); var utils = require_utils3(); var Binary = MongooseBuffer.Binary; var CastError = SchemaType.CastError; function SchemaBuffer(key, options) { SchemaType.call(this, key, options, "Buffer"); } SchemaBuffer.schemaName = "Buffer"; SchemaBuffer.defaultOptions = {}; SchemaBuffer.prototype = Object.create(SchemaType.prototype); SchemaBuffer.prototype.constructor = SchemaBuffer; SchemaBuffer.prototype.OptionsConstructor = SchemaBufferOptions; SchemaBuffer._checkRequired = (v) => !!(v && v.length); SchemaBuffer.set = SchemaType.set; SchemaBuffer.setters = []; SchemaBuffer.get = SchemaType.get; SchemaBuffer.checkRequired = SchemaType.checkRequired; SchemaBuffer.prototype.checkRequired = function(value, doc) { if (SchemaType._isRef(this, value, doc, true)) { return !!value; } return this.constructor._checkRequired(value); }; SchemaBuffer.prototype.cast = function(value, doc, init, prev, options) { let ret; if (SchemaType._isRef(this, value, doc, init)) { if (value && value.isMongooseBuffer) { return value; } if (Buffer.isBuffer(value)) { if (!value || !value.isMongooseBuffer) { value = new MongooseBuffer(value, [this.path, doc]); if (this.options.subtype != null) { value._subtype = this.options.subtype; } } return value; } if (value instanceof Binary) { ret = new MongooseBuffer(value.value(true), [this.path, doc]); if (typeof value.sub_type !== "number") { throw new CastError("Buffer", value, this.path, null, this); } ret._subtype = value.sub_type; return ret; } if (value == null || utils.isNonBuiltinObject(value)) { return this._castRef(value, doc, init, options); } } if (value && value._id) { value = value._id; } if (value && value.isMongooseBuffer) { return value; } if (Buffer.isBuffer(value)) { if (!value || !value.isMongooseBuffer) { value = new MongooseBuffer(value, [this.path, doc]); if (this.options.subtype != null) { value._subtype = this.options.subtype; } } return value; } if (value instanceof Binary) { ret = new MongooseBuffer(value.value(true), [this.path, doc]); if (typeof value.sub_type !== "number") { throw new CastError("Buffer", value, this.path, null, this); } ret._subtype = value.sub_type; return ret; } if (value === null) { return value; } const type = typeof value; if (type === "string" || type === "number" || Array.isArray(value) || type === "object" && value.type === "Buffer" && Array.isArray(value.data)) { if (type === "number") { value = [value]; } ret = new MongooseBuffer(value, [this.path, doc]); if (this.options.subtype != null) { ret._subtype = this.options.subtype; } return ret; } if (utils.isPOJO(value) && (value.$binary instanceof Binary || typeof value.$binary === "string")) { const buf = this.cast(Buffer.from(value.$binary, "base64")); if (value.$type != null) { buf._subtype = value.$type; return buf; } } throw new CastError("Buffer", value, this.path, null, this); }; SchemaBuffer.prototype.subtype = function(subtype) { this.options.subtype = subtype; return this; }; function handleSingle(val, context) { return this.castForQuery(null, val, context); } var $conditionalHandlers = { ...SchemaType.prototype.$conditionalHandlers, $bitsAllClear: handleBitwiseOperator, $bitsAnyClear: handleBitwiseOperator, $bitsAllSet: handleBitwiseOperator, $bitsAnySet: handleBitwiseOperator, $gt: handleSingle, $gte: handleSingle, $lt: handleSingle, $lte: handleSingle }; Object.defineProperty(SchemaBuffer.prototype, "$conditionalHandlers", { enumerable: false, value: $conditionalHandlers }); SchemaBuffer.prototype.castForQuery = function($conditional, val, context) { let handler; if ($conditional != null) { handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new Error("Can't use " + $conditional + " with Buffer."); } return handler.call(this, val); } let casted; try { casted = this.applySetters(val, context); } catch (err) { if (err instanceof CastError && err.path === this.path && this.$fullPath != null) { err.path = this.$fullPath; } throw err; } return casted ? casted.toObject({ transform: false, virtuals: false }) : casted; }; SchemaBuffer.prototype.toJSONSchema = function toJSONSchema(options) { const isRequired = this.options.required && typeof this.options.required !== "function"; return createJSONSchemaTypeDefinition("string", "binData", options?.useBsonType, isRequired); }; SchemaBuffer.prototype.autoEncryptionType = function autoEncryptionType() { return "binData"; }; module2.exports = SchemaBuffer; } }); // netlify/functions/node_modules/mongoose/lib/options/schemaDateOptions.js var require_schemaDateOptions = __commonJS({ "netlify/functions/node_modules/mongoose/lib/options/schemaDateOptions.js"(exports2, module2) { "use strict"; var SchemaTypeOptions = require_schemaTypeOptions(); var SchemaDateOptions = class extends SchemaTypeOptions { }; var opts = require_propertyOptions(); Object.defineProperty(SchemaDateOptions.prototype, "min", opts); Object.defineProperty(SchemaDateOptions.prototype, "max", opts); Object.defineProperty(SchemaDateOptions.prototype, "expires", opts); module2.exports = SchemaDateOptions; } }); // netlify/functions/node_modules/mongoose/lib/cast/date.js var require_date = __commonJS({ "netlify/functions/node_modules/mongoose/lib/cast/date.js"(exports2, module2) { "use strict"; var assert = require("assert"); module2.exports = function castDate(value) { if (value == null || value === "") { return null; } if (value instanceof Date) { assert.ok(!isNaN(value.valueOf())); return value; } let date; assert.ok(typeof value !== "boolean"); if (value instanceof Number || typeof value === "number") { date = new Date(value); } else if (typeof value === "string" && !isNaN(Number(value)) && (Number(value) >= 275761 || Number(value) < -271820)) { date = new Date(Number(value)); } else if (typeof value.valueOf === "function") { date = new Date(value.valueOf()); } else { date = new Date(value); } if (!isNaN(date.valueOf())) { return date; } assert.ok(false); }; } }); // netlify/functions/node_modules/mongoose/lib/schema/date.js var require_date2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/date.js"(exports2, module2) { "use strict"; var MongooseError = require_error2(); var SchemaDateOptions = require_schemaDateOptions(); var SchemaType = require_schemaType(); var castDate = require_date(); var createJSONSchemaTypeDefinition = require_createJSONSchemaTypeDefinition(); var getConstructorName = require_getConstructorName(); var utils = require_utils3(); var CastError = SchemaType.CastError; function SchemaDate(key, options) { SchemaType.call(this, key, options, "Date"); } SchemaDate.schemaName = "Date"; SchemaDate.defaultOptions = {}; SchemaDate.prototype = Object.create(SchemaType.prototype); SchemaDate.prototype.constructor = SchemaDate; SchemaDate.prototype.OptionsConstructor = SchemaDateOptions; SchemaDate._cast = castDate; SchemaDate.set = SchemaType.set; SchemaDate.setters = []; SchemaDate.get = SchemaType.get; SchemaDate.cast = function cast(caster) { if (arguments.length === 0) { return this._cast; } if (caster === false) { caster = this._defaultCaster; } this._cast = caster; return this._cast; }; SchemaDate._defaultCaster = (v) => { if (v != null && !(v instanceof Date)) { throw new Error(); } return v; }; SchemaDate.prototype.expires = function(when) { if (getConstructorName(this._index) !== "Object") { this._index = {}; } this._index.expires = when; utils.expires(this._index); return this; }; SchemaDate._checkRequired = (v) => v instanceof Date; SchemaDate.checkRequired = SchemaType.checkRequired; SchemaDate.prototype.checkRequired = function(value, doc) { if (typeof value === "object" && SchemaType._isRef(this, value, doc, true)) { return value != null; } const _checkRequired = typeof this.constructor.checkRequired === "function" ? this.constructor.checkRequired() : SchemaDate.checkRequired(); return _checkRequired(value); }; SchemaDate.prototype.min = function(value, message) { if (this.minValidator) { this.validators = this.validators.filter(function(v) { return v.validator !== this.minValidator; }, this); } if (value) { let msg = message || MongooseError.messages.Date.min; if (typeof msg === "string") { msg = msg.replace(/{MIN}/, value === Date.now ? "Date.now()" : value.toString()); } const _this = this; this.validators.push({ validator: this.minValidator = function(val) { let _value = value; if (typeof value === "function" && value !== Date.now) { _value = _value.call(this); } const min = _value === Date.now ? _value() : _this.cast(_value); return val === null || val.valueOf() >= min.valueOf(); }, message: msg, type: "min", min: value }); } return this; }; SchemaDate.prototype.max = function(value, message) { if (this.maxValidator) { this.validators = this.validators.filter(function(v) { return v.validator !== this.maxValidator; }, this); } if (value) { let msg = message || MongooseError.messages.Date.max; if (typeof msg === "string") { msg = msg.replace(/{MAX}/, value === Date.now ? "Date.now()" : value.toString()); } const _this = this; this.validators.push({ validator: this.maxValidator = function(val) { let _value = value; if (typeof _value === "function" && _value !== Date.now) { _value = _value.call(this); } const max = _value === Date.now ? _value() : _this.cast(_value); return val === null || val.valueOf() <= max.valueOf(); }, message: msg, type: "max", max: value }); } return this; }; SchemaDate.prototype.cast = function(value) { let castDate2; if (typeof this._castFunction === "function") { castDate2 = this._castFunction; } else if (typeof this.constructor.cast === "function") { castDate2 = this.constructor.cast(); } else { castDate2 = SchemaDate.cast(); } try { return castDate2(value); } catch (error) { throw new CastError("date", value, this.path, error, this); } }; function handleSingle(val) { return this.cast(val); } var $conditionalHandlers = { ...SchemaType.prototype.$conditionalHandlers, $gt: handleSingle, $gte: handleSingle, $lt: handleSingle, $lte: handleSingle }; Object.defineProperty(SchemaDate.prototype, "$conditionalHandlers", { enumerable: false, value: $conditionalHandlers }); SchemaDate.prototype.castForQuery = function($conditional, val, context) { if ($conditional == null) { try { return this.applySetters(val, context); } catch (err) { if (err instanceof CastError && err.path === this.path && this.$fullPath != null) { err.path = this.$fullPath; } throw err; } } const handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new Error("Can't use " + $conditional + " with Date."); } return handler.call(this, val); }; SchemaDate.prototype.toJSONSchema = function toJSONSchema(options) { const isRequired = this.options.required && typeof this.options.required !== "function"; return createJSONSchemaTypeDefinition("string", "date", options?.useBsonType, isRequired); }; SchemaDate.prototype.autoEncryptionType = function autoEncryptionType() { return "date"; }; module2.exports = SchemaDate; } }); // netlify/functions/node_modules/mongoose/lib/cast/decimal128.js var require_decimal1282 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/cast/decimal128.js"(exports2, module2) { "use strict"; var Decimal128Type = require_decimal128(); var assert = require("assert"); module2.exports = function castDecimal128(value) { if (value == null) { return value; } if (typeof value === "object" && typeof value.$numberDecimal === "string") { return Decimal128Type.fromString(value.$numberDecimal); } if (value instanceof Decimal128Type) { return value; } if (typeof value === "string") { return Decimal128Type.fromString(value); } if (typeof Buffer === "function" && Buffer.isBuffer(value)) { return new Decimal128Type(value); } if (typeof Uint8Array === "function" && value instanceof Uint8Array) { return new Decimal128Type(value); } if (typeof value === "number") { return Decimal128Type.fromString(String(value)); } if (typeof value.valueOf === "function" && typeof value.valueOf() === "string") { return Decimal128Type.fromString(value.valueOf()); } assert.ok(false); }; } }); // netlify/functions/node_modules/mongoose/lib/schema/decimal128.js var require_decimal1283 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/decimal128.js"(exports2, module2) { "use strict"; var SchemaType = require_schemaType(); var CastError = SchemaType.CastError; var castDecimal128 = require_decimal1282(); var createJSONSchemaTypeDefinition = require_createJSONSchemaTypeDefinition(); var isBsonType = require_isBsonType(); function SchemaDecimal128(key, options) { SchemaType.call(this, key, options, "Decimal128"); } SchemaDecimal128.schemaName = "Decimal128"; SchemaDecimal128.defaultOptions = {}; SchemaDecimal128.prototype = Object.create(SchemaType.prototype); SchemaDecimal128.prototype.constructor = SchemaDecimal128; SchemaDecimal128._cast = castDecimal128; SchemaDecimal128.set = SchemaType.set; SchemaDecimal128.setters = []; SchemaDecimal128.get = SchemaType.get; SchemaDecimal128.cast = function cast(caster) { if (arguments.length === 0) { return this._cast; } if (caster === false) { caster = this._defaultCaster; } this._cast = caster; return this._cast; }; SchemaDecimal128._defaultCaster = (v) => { if (v != null && !isBsonType(v, "Decimal128")) { throw new Error(); } return v; }; SchemaDecimal128._checkRequired = (v) => isBsonType(v, "Decimal128"); SchemaDecimal128.checkRequired = SchemaType.checkRequired; SchemaDecimal128.prototype.checkRequired = function checkRequired(value, doc) { if (SchemaType._isRef(this, value, doc, true)) { return !!value; } const _checkRequired = typeof this.constructor.checkRequired === "function" ? this.constructor.checkRequired() : SchemaDecimal128.checkRequired(); return _checkRequired(value); }; SchemaDecimal128.prototype.cast = function(value, doc, init, prev, options) { if (SchemaType._isRef(this, value, doc, init)) { if (isBsonType(value, "Decimal128")) { return value; } return this._castRef(value, doc, init, options); } let castDecimal1282; if (typeof this._castFunction === "function") { castDecimal1282 = this._castFunction; } else if (typeof this.constructor.cast === "function") { castDecimal1282 = this.constructor.cast(); } else { castDecimal1282 = SchemaDecimal128.cast(); } try { return castDecimal1282(value); } catch (error) { throw new CastError("Decimal128", value, this.path, error, this); } }; function handleSingle(val) { return this.cast(val); } var $conditionalHandlers = { ...SchemaType.prototype.$conditionalHandlers, $gt: handleSingle, $gte: handleSingle, $lt: handleSingle, $lte: handleSingle }; Object.defineProperty(SchemaDecimal128.prototype, "$conditionalHandlers", { enumerable: false, value: $conditionalHandlers }); SchemaDecimal128.prototype.toJSONSchema = function toJSONSchema(options) { const isRequired = this.options.required && typeof this.options.required !== "function"; return createJSONSchemaTypeDefinition("string", "decimal", options?.useBsonType, isRequired); }; SchemaDecimal128.prototype.autoEncryptionType = function autoEncryptionType() { return "decimal"; }; module2.exports = SchemaDecimal128; } }); // netlify/functions/node_modules/mongoose/lib/options/schemaSubdocumentOptions.js var require_schemaSubdocumentOptions = __commonJS({ "netlify/functions/node_modules/mongoose/lib/options/schemaSubdocumentOptions.js"(exports2, module2) { "use strict"; var SchemaTypeOptions = require_schemaTypeOptions(); var SchemaSubdocumentOptions = class extends SchemaTypeOptions { }; var opts = require_propertyOptions(); Object.defineProperty(SchemaSubdocumentOptions.prototype, "_id", opts); Object.defineProperty(SchemaSubdocumentOptions.prototype, "minimize", opts); module2.exports = SchemaSubdocumentOptions; } }); // netlify/functions/node_modules/mongoose/lib/helpers/each.js var require_each = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/each.js"(exports2, module2) { "use strict"; module2.exports = function each(arr, cb, done) { if (arr.length === 0) { return done(); } let remaining = arr.length; let err = null; for (const v of arr) { cb(v, function(_err) { if (err != null) { return; } if (_err != null) { err = _err; return done(err); } if (--remaining <= 0) { return done(); } }); } }; } }); // netlify/functions/node_modules/mongoose/lib/plugins/saveSubdocs.js var require_saveSubdocs = __commonJS({ "netlify/functions/node_modules/mongoose/lib/plugins/saveSubdocs.js"(exports2, module2) { "use strict"; var each = require_each(); module2.exports = function saveSubdocs(schema) { const unshift = true; schema.s.hooks.pre("save", false, function saveSubdocsPreSave(next) { if (this.$isSubdocument) { next(); return; } const _this = this; const subdocs = this.$getAllSubdocs({ useCache: true }); if (!subdocs.length) { next(); return; } each(subdocs, function(subdoc, cb) { subdoc.$__schema.s.hooks.execPre("save", subdoc, function(err) { cb(err); }); }, function(error) { if (_this.$__.saveOptions) { _this.$__.saveOptions.__subdocs = null; } if (error) { return _this.$__schema.s.hooks.execPost("save:error", _this, [_this], { error }, function(error2) { next(error2); }); } next(); }); }, null, unshift); schema.s.hooks.post("save", async function saveSubdocsPostDeleteOne() { const removedSubdocs = this.$__.removedSubdocs; if (!removedSubdocs || !removedSubdocs.length) { return; } const promises = []; for (const subdoc of removedSubdocs) { promises.push(new Promise((resolve, reject) => { subdoc.$__schema.s.hooks.execPost("deleteOne", subdoc, [subdoc], function(err) { if (err) { return reject(err); } resolve(); }); })); } this.$__.removedSubdocs = null; await Promise.all(promises); }); schema.s.hooks.post("save", async function saveSubdocsPostSave() { if (this.$isSubdocument) { return; } const _this = this; const subdocs = this.$getAllSubdocs({ useCache: true }); if (!subdocs.length) { return; } const promises = []; for (const subdoc of subdocs) { promises.push(new Promise((resolve, reject) => { subdoc.$__schema.s.hooks.execPost("save", subdoc, [subdoc], function(err) { if (err) { return reject(err); } resolve(); }); })); } try { await Promise.all(promises); } catch (error) { await new Promise((resolve, reject) => { this.$__schema.s.hooks.execPost("save:error", _this, [_this], { error }, function(error2) { if (error2) { return reject(error2); } resolve(); }); }); } }, null, unshift); }; } }); // netlify/functions/node_modules/mongoose/lib/plugins/sharding.js var require_sharding = __commonJS({ "netlify/functions/node_modules/mongoose/lib/plugins/sharding.js"(exports2, module2) { "use strict"; var objectIdSymbol = require_symbols().objectIdSymbol; var utils = require_utils3(); module2.exports = function shardingPlugin(schema) { schema.post("init", function shardingPluginPostInit() { storeShard.call(this); return this; }); schema.pre("save", function shardingPluginPreSave(next) { applyWhere.call(this); next(); }); schema.pre("remove", function shardingPluginPreRemove(next) { applyWhere.call(this); next(); }); schema.post("save", function shardingPluginPostSave() { storeShard.call(this); }); }; function applyWhere() { let paths; let len; if (this.$__.shardval) { paths = Object.keys(this.$__.shardval); len = paths.length; this.$where = this.$where || {}; for (let i = 0; i < len; ++i) { this.$where[paths[i]] = this.$__.shardval[paths[i]]; } } } module2.exports.storeShard = storeShard; function storeShard() { const key = this.$__schema.options.shardKey || this.$__schema.options.shardkey; if (!utils.isPOJO(key)) { return; } const orig = this.$__.shardval = {}; const paths = Object.keys(key); const len = paths.length; let val; for (let i = 0; i < len; ++i) { val = this.$__getValue(paths[i]); if (val == null) { orig[paths[i]] = val; } else if (utils.isMongooseObject(val)) { orig[paths[i]] = val.toObject({ depopulate: true, _isNested: true }); } else if (val instanceof Date || val[objectIdSymbol]) { orig[paths[i]] = val; } else if (typeof val.valueOf === "function") { orig[paths[i]] = val.valueOf(); } else { orig[paths[i]] = val; } } } } }); // netlify/functions/node_modules/mongoose/lib/plugins/trackTransaction.js var require_trackTransaction = __commonJS({ "netlify/functions/node_modules/mongoose/lib/plugins/trackTransaction.js"(exports2, module2) { "use strict"; var arrayAtomicsSymbol = require_symbols().arrayAtomicsSymbol; var sessionNewDocuments = require_symbols().sessionNewDocuments; var utils = require_utils3(); module2.exports = function trackTransaction(schema) { schema.pre("save", function trackTransactionPreSave() { const session = this.$session(); if (session == null) { return; } if (session.transaction == null || session[sessionNewDocuments] == null) { return; } if (!session[sessionNewDocuments].has(this)) { const initialState = {}; if (this.isNew) { initialState.isNew = true; } if (this.$__schema.options.versionKey) { initialState.versionKey = this.get(this.$__schema.options.versionKey); } initialState.modifiedPaths = new Set(Object.keys(this.$__.activePaths.getStatePaths("modify"))); initialState.atomics = _getAtomics(this); session[sessionNewDocuments].set(this, initialState); } }); }; function _getAtomics(doc, previous) { const pathToAtomics = /* @__PURE__ */ new Map(); previous = previous || /* @__PURE__ */ new Map(); const pathsToCheck = Object.keys(doc.$__.activePaths.init).concat(Object.keys(doc.$__.activePaths.modify)); for (const path of pathsToCheck) { const val = doc.$__getValue(path); if (val != null && Array.isArray(val) && utils.isMongooseDocumentArray(val) && val.length && val[arrayAtomicsSymbol] != null && Object.keys(val[arrayAtomicsSymbol]).length !== 0) { const existing = previous.get(path) || {}; pathToAtomics.set(path, mergeAtomics(existing, val[arrayAtomicsSymbol])); } } const dirty = doc.$__dirty(); for (const dirt of dirty) { const path = dirt.path; const val = dirt.value; if (val != null && val[arrayAtomicsSymbol] != null && Object.keys(val[arrayAtomicsSymbol]).length !== 0) { const existing = previous.get(path) || {}; pathToAtomics.set(path, mergeAtomics(existing, val[arrayAtomicsSymbol])); } } return pathToAtomics; } function mergeAtomics(destination, source) { destination = destination || {}; if (source.$pullAll != null) { destination.$pullAll = (destination.$pullAll || []).concat(source.$pullAll); } if (source.$push != null) { destination.$push = destination.$push || {}; destination.$push.$each = (destination.$push.$each || []).concat(source.$push.$each); } if (source.$addToSet != null) { destination.$addToSet = (destination.$addToSet || []).concat(source.$addToSet); } if (source.$set != null) { destination.$set = Array.isArray(source.$set) ? [...source.$set] : Object.assign({}, source.$set); } return destination; } } }); // netlify/functions/node_modules/mongoose/lib/plugins/validateBeforeSave.js var require_validateBeforeSave = __commonJS({ "netlify/functions/node_modules/mongoose/lib/plugins/validateBeforeSave.js"(exports2, module2) { "use strict"; module2.exports = function validateBeforeSave(schema) { const unshift = true; schema.pre("save", false, function validateBeforeSave2(next, options) { const _this = this; if (this.$isSubdocument) { return next(); } const hasValidateBeforeSaveOption = options && typeof options === "object" && "validateBeforeSave" in options; let shouldValidate; if (hasValidateBeforeSaveOption) { shouldValidate = !!options.validateBeforeSave; } else { shouldValidate = this.$__schema.options.validateBeforeSave; } if (shouldValidate) { const hasValidateModifiedOnlyOption = options && typeof options === "object" && "validateModifiedOnly" in options; const validateOptions = hasValidateModifiedOnlyOption ? { validateModifiedOnly: options.validateModifiedOnly } : null; this.$validate(validateOptions).then( () => { this.$op = "save"; next(); }, (error) => { _this.$__schema.s.hooks.execPost("save:error", _this, [_this], { error }, function(error2) { _this.$op = "save"; next(error2); }); } ); } else { next(); } }, null, unshift); }; } }); // netlify/functions/node_modules/mongoose/lib/plugins/index.js var require_plugins = __commonJS({ "netlify/functions/node_modules/mongoose/lib/plugins/index.js"(exports2) { "use strict"; exports2.saveSubdocs = require_saveSubdocs(); exports2.sharding = require_sharding(); exports2.trackTransaction = require_trackTransaction(); exports2.validateBeforeSave = require_validateBeforeSave(); } }); // netlify/functions/node_modules/mongoose/lib/helpers/schema/applyBuiltinPlugins.js var require_applyBuiltinPlugins = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/schema/applyBuiltinPlugins.js"(exports2, module2) { "use strict"; var builtinPlugins = require_plugins(); module2.exports = function applyBuiltinPlugins(schema) { for (const plugin of Object.values(builtinPlugins)) { plugin(schema, { deduplicate: true }); } schema.plugins = Object.values(builtinPlugins).map((fn) => ({ fn, opts: { deduplicate: true } })).concat(schema.plugins); }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/discriminator/mergeDiscriminatorSchema.js var require_mergeDiscriminatorSchema = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/discriminator/mergeDiscriminatorSchema.js"(exports2, module2) { "use strict"; var schemaMerge = require_merge(); var specialProperties = require_specialProperties(); var isBsonType = require_isBsonType(); var ObjectId2 = require_objectid(); var isObject = require_isObject(); module2.exports = function mergeDiscriminatorSchema(to, from, path, seen) { const keys = Object.keys(from); let i = 0; const len = keys.length; let key; path = path || ""; seen = seen || /* @__PURE__ */ new WeakSet(); if (seen.has(from)) { return; } seen.add(from); while (i < len) { key = keys[i++]; if (!path) { if (key === "discriminators" || key === "base" || key === "_applyDiscriminators" || key === "_userProvidedOptions" || key === "options" || key === "tree") { continue; } } if (path === "tree" && from != null && from.instanceOfSchema) { continue; } if (specialProperties.has(key)) { continue; } if (to[key] == null) { to[key] = from[key]; } else if (isObject(from[key])) { if (!isObject(to[key])) { to[key] = {}; } if (from[key] != null) { if (from[key].$isSingleNested && to[key].$isMongooseDocumentArray || from[key].$isMongooseDocumentArray && to[key].$isSingleNested || from[key].$isMongooseDocumentArrayElement && to[key].$isMongooseDocumentArrayElement) { continue; } else if (from[key].instanceOfSchema) { if (to[key].instanceOfSchema) { schemaMerge(to[key], from[key].clone(), true); } else { to[key] = from[key].clone(); } continue; } else if (isBsonType(from[key], "ObjectId")) { to[key] = new ObjectId2(from[key]); continue; } } mergeDiscriminatorSchema(to[key], from[key], path ? path + "." + key : key, seen); } } if (from != null && from.instanceOfSchema) { to.tree = Object.assign({}, from.tree, to.tree); } }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/model/discriminator.js var require_discriminator = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/model/discriminator.js"(exports2, module2) { "use strict"; var Mixed = require_mixed(); var applyBuiltinPlugins = require_applyBuiltinPlugins(); var clone = require_clone(); var defineKey = require_compile().defineKey; var get = require_get(); var utils = require_utils3(); var mergeDiscriminatorSchema = require_mergeDiscriminatorSchema(); var CUSTOMIZABLE_DISCRIMINATOR_OPTIONS = { toJSON: true, toObject: true, _id: true, id: true, virtuals: true, methods: true, statics: true }; function validateDiscriminatorSchemasForEncryption(parentSchema, childSchema) { if (parentSchema.encryptionType() == null && childSchema.encryptionType() == null) return; const allSharedNestedPaths = setIntersection( allNestedPaths(parentSchema), allNestedPaths(childSchema) ); for (const path of allSharedNestedPaths) { if (parentSchema._hasEncryptedField(path) && childSchema._hasEncryptedField(path)) { throw new Error(`encrypted fields cannot be declared on both the base schema and the child schema in a discriminator. path=${path}`); } if (parentSchema._hasEncryptedField(path) || childSchema._hasEncryptedField(path)) { throw new Error(`encrypted fields cannot have the same path as a non-encrypted field for discriminators. path=${path}`); } } function allNestedPaths(schema) { return [...Object.keys(schema.paths), ...Object.keys(schema.singleNestedPaths)]; } function* setIntersection(i1, i2) { const s1 = new Set(i1); for (const item of i2) { if (s1.has(item)) { yield item; } } } } module2.exports = function discriminator(model, name, schema, tiedValue, applyPlugins, mergeHooks, overwriteExisting) { if (!(schema && schema.instanceOfSchema)) { throw new Error("You must pass a valid discriminator Schema"); } mergeHooks = mergeHooks == null ? true : mergeHooks; if (model.schema.discriminatorMapping && !model.schema.discriminatorMapping.isRoot) { throw new Error('Discriminator "' + name + '" can only be a discriminator of the root model'); } if (applyPlugins) { const applyPluginsToDiscriminators = get( model.base, "options.applyPluginsToDiscriminators", false ) || !mergeHooks; model.base._applyPlugins(schema, { skipTopLevel: !applyPluginsToDiscriminators }); } else if (!mergeHooks) { applyBuiltinPlugins(schema); } const key = model.schema.options.discriminatorKey; const existingPath = model.schema.path(key); if (existingPath != null) { if (!utils.hasUserDefinedProperty(existingPath.options, "select")) { existingPath.options.select = true; } existingPath.options.$skipDiscriminatorCheck = true; } else { const baseSchemaAddition = {}; baseSchemaAddition[key] = { default: void 0, select: true, $skipDiscriminatorCheck: true }; baseSchemaAddition[key][model.schema.options.typeKey] = String; model.schema.add(baseSchemaAddition); defineKey({ prop: key, prototype: model.prototype, options: model.schema.options }); } if (schema.path(key) && schema.path(key).options.$skipDiscriminatorCheck !== true) { throw new Error('Discriminator "' + name + '" cannot have field with name "' + key + '"'); } let value = name; if (typeof tiedValue === "string" && tiedValue.length || tiedValue != null) { value = tiedValue; } validateDiscriminatorSchemasForEncryption(model.schema, schema); function merge(schema2, baseSchema) { schema2._baseSchema = baseSchema; if (baseSchema.paths._id && baseSchema.paths._id.options && !baseSchema.paths._id.options.auto) { schema2.remove("_id"); } const baseSchemaPaths = Object.keys(baseSchema.paths); const conflictingPaths = []; for (const path of baseSchemaPaths) { if (schema2.nested[path]) { conflictingPaths.push(path); continue; } if (path.indexOf(".") === -1) { continue; } const sp = path.split(".").slice(0, -1); let cur = ""; for (const piece of sp) { cur += (cur.length ? "." : "") + piece; if (schema2.paths[cur] instanceof Mixed || schema2.singleNestedPaths[cur] instanceof Mixed) { conflictingPaths.push(path); } } } schema2.obj = { ...schema2.obj }; mergeDiscriminatorSchema(schema2, baseSchema); schema2._gatherChildSchemas(); for (const conflictingPath of conflictingPaths) { delete schema2.paths[conflictingPath]; } schema2.childSchemas.forEach((obj2) => { obj2.model.prototype.$__setSchema(obj2.schema); }); const obj = {}; obj[key] = { default: value, select: true, set: function(newName) { if (newName === value || Array.isArray(value) && utils.deepEqual(newName, value)) { return value; } throw new Error(`Can't set discriminator key "` + key + '"'); }, $skipDiscriminatorCheck: true }; obj[key][schema2.options.typeKey] = existingPath ? existingPath.options[schema2.options.typeKey] : String; schema2.add(obj); schema2.discriminatorMapping = { key, value, isRoot: false }; if (baseSchema.options.collection) { schema2.options.collection = baseSchema.options.collection; } const toJSON = schema2.options.toJSON; const toObject = schema2.options.toObject; const _id = schema2.options._id; const id = schema2.options.id; const keys = Object.keys(schema2.options); schema2.options.discriminatorKey = baseSchema.options.discriminatorKey; const userProvidedOptions = schema2._userProvidedOptions; for (const _key of keys) { if (!CUSTOMIZABLE_DISCRIMINATOR_OPTIONS[_key]) { if (_key in userProvidedOptions && !utils.deepEqual(schema2.options[_key], baseSchema.options[_key])) { throw new Error("Can't customize discriminator option " + _key + " (can only modify " + Object.keys(CUSTOMIZABLE_DISCRIMINATOR_OPTIONS).join(", ") + ")"); } } } schema2.options = clone(baseSchema.options); for (const _key of Object.keys(userProvidedOptions)) { schema2.options[_key] = userProvidedOptions[_key]; } if (toJSON) schema2.options.toJSON = toJSON; if (toObject) schema2.options.toObject = toObject; if (typeof _id !== "undefined") { schema2.options._id = _id; } schema2.options.id = id; if (mergeHooks) { schema2.s.hooks = model.schema.s.hooks.merge(schema2.s.hooks); } if (applyPlugins) { schema2.plugins = Array.prototype.slice.call(baseSchema.plugins); } schema2.callQueue = baseSchema.callQueue.concat(schema2.callQueue); delete schema2._requiredpaths; } merge(schema, model.schema); if (!model.discriminators) { model.discriminators = {}; } if (!model.schema.discriminatorMapping) { model.schema.discriminatorMapping = { key, value: null, isRoot: true }; } if (!model.schema.discriminators) { model.schema.discriminators = {}; } model.schema.discriminators[name] = schema; if (model.discriminators[name] && !schema.options.overwriteModels && !overwriteExisting) { throw new Error('Discriminator with name "' + name + '" already exists'); } return schema; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/discriminator/getConstructor.js var require_getConstructor = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/discriminator/getConstructor.js"(exports2, module2) { "use strict"; var getDiscriminatorByValue = require_getDiscriminatorByValue(); module2.exports = function getConstructor(Constructor, value, defaultDiscriminatorValue) { const discriminatorKey = Constructor.schema.options.discriminatorKey; let discriminatorValue = value != null && value[discriminatorKey]; if (discriminatorValue == null) { discriminatorValue = defaultDiscriminatorValue; } if (Constructor.discriminators && discriminatorValue != null) { if (Constructor.discriminators[discriminatorValue]) { Constructor = Constructor.discriminators[discriminatorValue]; } else { const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, discriminatorValue); if (constructorByValue) { Constructor = constructorByValue; } } } return Constructor; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/schema/handleIdOption.js var require_handleIdOption = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/schema/handleIdOption.js"(exports2, module2) { "use strict"; var addAutoId = require_addAutoId(); module2.exports = function handleIdOption(schema, options) { if (options == null || options._id == null) { return schema; } schema = schema.clone(); if (!options._id) { schema.remove("_id"); schema.options._id = false; } else if (!schema.paths["_id"]) { addAutoId(schema); schema.options._id = true; } return schema; }; } }); // netlify/functions/node_modules/mongoose/lib/error/invalidSchemaOption.js var require_invalidSchemaOption = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/invalidSchemaOption.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var InvalidSchemaOptionError = class extends MongooseError { constructor(name, option) { const msg = `Cannot create use schema for property "${name}" because the schema has the ${option} option enabled.`; super(msg); } }; Object.defineProperty(InvalidSchemaOptionError.prototype, "name", { value: "InvalidSchemaOptionError" }); module2.exports = InvalidSchemaOptionError; } }); // netlify/functions/node_modules/mongoose/lib/schema/subdocument.js var require_subdocument2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/subdocument.js"(exports2, module2) { "use strict"; var CastError = require_cast(); var EventEmitter = require("events").EventEmitter; var ObjectExpectedError = require_objectExpected(); var SchemaSubdocumentOptions = require_schemaSubdocumentOptions(); var SchemaType = require_schemaType(); var applyDefaults = require_applyDefaults(); var $exists = require_exists(); var castToNumber = require_helpers().castToNumber; var createJSONSchemaTypeDefinition = require_createJSONSchemaTypeDefinition(); var discriminator = require_discriminator(); var geospatial = require_geospatial(); var getConstructor = require_getConstructor(); var handleIdOption = require_handleIdOption(); var internalToObjectOptions = require_options().internalToObjectOptions; var isExclusive = require_isExclusive(); var utils = require_utils3(); var InvalidSchemaOptionError = require_invalidSchemaOption(); var SubdocumentType; module2.exports = SchemaSubdocument; function SchemaSubdocument(schema, path, options) { if (schema.options.timeseries) { throw new InvalidSchemaOptionError(path, "timeseries"); } const schemaTypeIdOption = SchemaSubdocument.defaultOptions && SchemaSubdocument.defaultOptions._id; if (schemaTypeIdOption != null) { options = options || {}; options._id = schemaTypeIdOption; } schema = handleIdOption(schema, options); this.caster = _createConstructor(schema, null, options); this.caster.path = path; this.caster.prototype.$basePath = path; this.schema = schema; this.$isSingleNested = true; this.base = schema.base; SchemaType.call(this, path, options, "Embedded"); } SchemaSubdocument.prototype = Object.create(SchemaType.prototype); SchemaSubdocument.prototype.constructor = SchemaSubdocument; SchemaSubdocument.prototype.OptionsConstructor = SchemaSubdocumentOptions; function _createConstructor(schema, baseClass, options) { SubdocumentType || (SubdocumentType = require_subdocument()); const _embedded = function SingleNested(value, path, parent) { this.$__parent = parent; SubdocumentType.apply(this, arguments); if (parent == null) { return; } this.$session(parent.$session()); }; schema._preCompile(); const proto = baseClass != null ? baseClass.prototype : SubdocumentType.prototype; _embedded.prototype = Object.create(proto); _embedded.prototype.$__setSchema(schema); _embedded.prototype.constructor = _embedded; _embedded.prototype.$__schemaTypeOptions = options; _embedded.$__required = options?.required; _embedded.base = schema.base; _embedded.schema = schema; _embedded.$isSingleNested = true; _embedded.events = new EventEmitter(); _embedded.prototype.toBSON = function() { return this.toObject(internalToObjectOptions); }; for (const i in schema.methods) { _embedded.prototype[i] = schema.methods[i]; } for (const i in schema.statics) { _embedded[i] = schema.statics[i]; } for (const i in EventEmitter.prototype) { _embedded[i] = EventEmitter.prototype[i]; } return _embedded; } var $conditionalHandlers = { ...SchemaType.prototype.$conditionalHandlers }; $conditionalHandlers.$geoWithin = function handle$geoWithin(val, context) { return { $geometry: this.castForQuery(null, val.$geometry, context) }; }; $conditionalHandlers.$near = $conditionalHandlers.$nearSphere = geospatial.cast$near; $conditionalHandlers.$within = $conditionalHandlers.$geoWithin = geospatial.cast$within; $conditionalHandlers.$geoIntersects = geospatial.cast$geoIntersects; $conditionalHandlers.$minDistance = castToNumber; $conditionalHandlers.$maxDistance = castToNumber; $conditionalHandlers.$exists = $exists; Object.defineProperty(SchemaSubdocument.prototype, "$conditionalHandlers", { enumerable: false, value: $conditionalHandlers }); SchemaSubdocument.prototype.cast = function(val, doc, init, priorVal, options) { if (val && val.$isSingleNested && val.parent === doc) { return val; } if (val != null && (typeof val !== "object" || Array.isArray(val))) { throw new ObjectExpectedError(this.path, val); } const discriminatorKeyPath = this.schema.path(this.schema.options.discriminatorKey); const defaultDiscriminatorValue = discriminatorKeyPath == null ? null : discriminatorKeyPath.getDefault(doc); const Constructor = getConstructor(this.caster, val, defaultDiscriminatorValue); let subdoc; const parentSelected = doc && doc.$__ && doc.$__.selected; const path = this.path; const selected = parentSelected == null ? null : Object.keys(parentSelected).reduce((obj, key) => { if (key.startsWith(path + ".")) { obj = obj || {}; obj[key.substring(path.length + 1)] = parentSelected[key]; } return obj; }, null); if (init) { subdoc = new Constructor(void 0, selected, doc, false, { defaults: false }); delete subdoc.$__.defaults; subdoc.$init(val); const exclude = isExclusive(selected); applyDefaults(subdoc, selected, exclude); } else { options = Object.assign({}, options, { priorDoc: priorVal }); if (Object.keys(val).length === 0) { return new Constructor({}, selected, doc, void 0, options); } return new Constructor(val, selected, doc, void 0, options); } return subdoc; }; SchemaSubdocument.prototype.castForQuery = function($conditional, val, context, options) { let handler; if ($conditional != null) { handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new Error("Can't use " + $conditional); } return handler.call(this, val); } if (val == null) { return val; } const Constructor = getConstructor(this.caster, val); if (val instanceof Constructor) { return val; } if (this.options.runSetters) { val = this._applySetters(val, context); } const overrideStrict = options != null && options.strict != null ? options.strict : void 0; try { val = new Constructor(val, overrideStrict); } catch (error) { if (!(error instanceof CastError)) { throw new CastError("Embedded", val, this.path, error, this); } throw error; } return val; }; SchemaSubdocument.prototype.doValidate = function(value, fn, scope, options) { const Constructor = getConstructor(this.caster, value); if (value && !(value instanceof Constructor)) { value = new Constructor(value, null, scope != null && scope.$__ != null ? scope : null); } if (options && options.skipSchemaValidators) { if (!value) { return fn(null); } return value.validate().then(() => fn(null), (err) => fn(err)); } SchemaType.prototype.doValidate.call(this, value, function(error) { if (error) { return fn(error); } if (!value) { return fn(null); } value.validate().then(() => fn(null), (err) => fn(err)); }, scope, options); }; SchemaSubdocument.prototype.doValidateSync = function(value, scope, options) { if (!options || !options.skipSchemaValidators) { const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, value, scope); if (schemaTypeError) { return schemaTypeError; } } if (!value) { return; } return value.validateSync(); }; SchemaSubdocument.prototype.discriminator = function(name, schema, options) { options = options || {}; const value = utils.isPOJO(options) ? options.value : options; const clone = typeof options.clone === "boolean" ? options.clone : true; if (schema.instanceOfSchema && clone) { schema = schema.clone(); } schema = discriminator(this.caster, name, schema, value, null, null, options.overwriteExisting); this.caster.discriminators[name] = _createConstructor(schema, this.caster); return this.caster.discriminators[name]; }; SchemaSubdocument.defaultOptions = {}; SchemaSubdocument.set = SchemaType.set; SchemaSubdocument.setters = []; SchemaSubdocument.get = SchemaType.get; SchemaSubdocument.prototype.toJSON = function toJSON() { return { path: this.path, options: this.options }; }; SchemaSubdocument.prototype.clone = function() { const schematype = new this.constructor( this.schema, this.path, { ...this.options, _skipApplyDiscriminators: true } ); schematype.validators = this.validators.slice(); if (this.requiredValidator !== void 0) { schematype.requiredValidator = this.requiredValidator; } schematype.caster.discriminators = Object.assign({}, this.caster.discriminators); schematype._appliedDiscriminators = this._appliedDiscriminators; return schematype; }; SchemaSubdocument.prototype.toJSONSchema = function toJSONSchema(options) { const isRequired = this.options.required && typeof this.options.required !== "function"; return { ...this.schema.toJSONSchema(options), ...createJSONSchemaTypeDefinition("object", "object", options?.useBsonType, isRequired) }; }; } }); // netlify/functions/node_modules/mongoose/lib/schema/documentArrayElement.js var require_documentArrayElement = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/documentArrayElement.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var SchemaType = require_schemaType(); var SchemaSubdocument = require_subdocument2(); var getConstructor = require_getConstructor(); function SchemaDocumentArrayElement(path, options) { this.$parentSchemaType = options && options.$parentSchemaType; if (!this.$parentSchemaType) { throw new MongooseError("Cannot create DocumentArrayElement schematype without a parent"); } delete options.$parentSchemaType; SchemaType.call(this, path, options, "DocumentArrayElement"); this.$isMongooseDocumentArrayElement = true; } SchemaDocumentArrayElement.schemaName = "DocumentArrayElement"; SchemaDocumentArrayElement.defaultOptions = {}; SchemaDocumentArrayElement.prototype = Object.create(SchemaType.prototype); SchemaDocumentArrayElement.prototype.constructor = SchemaDocumentArrayElement; SchemaDocumentArrayElement.prototype.cast = function(...args) { return this.$parentSchemaType.cast(...args)[0]; }; SchemaDocumentArrayElement.prototype.doValidate = function(value, fn, scope, options) { const Constructor = getConstructor(this.caster, value); if (value && !(value instanceof Constructor)) { value = new Constructor(value, scope, null, null, options && options.index != null ? options.index : null); } return SchemaSubdocument.prototype.doValidate.call(this, value, fn, scope, options); }; SchemaDocumentArrayElement.prototype.clone = function() { this.options.$parentSchemaType = this.$parentSchemaType; const ret = SchemaType.prototype.clone.apply(this, arguments); delete this.options.$parentSchemaType; ret.caster = this.caster; ret.schema = this.schema; return ret; }; module2.exports = SchemaDocumentArrayElement; } }); // netlify/functions/node_modules/mongoose/lib/options/schemaDocumentArrayOptions.js var require_schemaDocumentArrayOptions = __commonJS({ "netlify/functions/node_modules/mongoose/lib/options/schemaDocumentArrayOptions.js"(exports2, module2) { "use strict"; var SchemaTypeOptions = require_schemaTypeOptions(); var SchemaDocumentArrayOptions = class extends SchemaTypeOptions { }; var opts = require_propertyOptions(); Object.defineProperty(SchemaDocumentArrayOptions.prototype, "excludeIndexes", opts); Object.defineProperty(SchemaDocumentArrayOptions.prototype, "_id", opts); module2.exports = SchemaDocumentArrayOptions; } }); // netlify/functions/node_modules/mongoose/lib/schema/documentArray.js var require_documentArray2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/documentArray.js"(exports2, module2) { "use strict"; var CastError = require_cast(); var DocumentArrayElement = require_documentArrayElement(); var EventEmitter = require("events").EventEmitter; var SchemaArray = require_array2(); var SchemaDocumentArrayOptions = require_schemaDocumentArrayOptions(); var SchemaType = require_schemaType(); var cast = require_cast2(); var createJSONSchemaTypeDefinition = require_createJSONSchemaTypeDefinition(); var discriminator = require_discriminator(); var handleIdOption = require_handleIdOption(); var handleSpreadDoc = require_handleSpreadDoc(); var isOperator = require_isOperator(); var utils = require_utils3(); var getConstructor = require_getConstructor(); var InvalidSchemaOptionError = require_invalidSchemaOption(); var arrayAtomicsSymbol = require_symbols().arrayAtomicsSymbol; var arrayPathSymbol = require_symbols().arrayPathSymbol; var documentArrayParent = require_symbols().documentArrayParent; var MongooseDocumentArray; var Subdocument; function SchemaDocumentArray(key, schema, options, schemaOptions) { if (schema.options && schema.options.timeseries) { throw new InvalidSchemaOptionError(key, "timeseries"); } const schemaTypeIdOption = SchemaDocumentArray.defaultOptions && SchemaDocumentArray.defaultOptions._id; if (schemaTypeIdOption != null) { schemaOptions = schemaOptions || {}; schemaOptions._id = schemaTypeIdOption; } if (schemaOptions != null && schemaOptions._id != null) { schema = handleIdOption(schema, schemaOptions); } else if (options != null && options._id != null) { schema = handleIdOption(schema, options); } const EmbeddedDocument = _createConstructor(schema, options); EmbeddedDocument.prototype.$basePath = key; SchemaArray.call(this, key, EmbeddedDocument, options); this.schema = schema; this.schemaOptions = schemaOptions || {}; this.$isMongooseDocumentArray = true; this.Constructor = EmbeddedDocument; EmbeddedDocument.base = schema.base; const fn = this.defaultValue; if (!("defaultValue" in this) || fn != null) { this.default(function() { let arr = fn.call(this); if (arr != null && !Array.isArray(arr)) { arr = [arr]; } return arr; }); } const $parentSchemaType = this; this.$embeddedSchemaType = new DocumentArrayElement(key + ".$", { ...schemaOptions || {}, $parentSchemaType }); this.$embeddedSchemaType.caster = this.Constructor; this.$embeddedSchemaType.schema = this.schema; } SchemaDocumentArray.schemaName = "DocumentArray"; SchemaDocumentArray.options = { castNonArrays: true }; SchemaDocumentArray.prototype = Object.create(SchemaArray.prototype); SchemaDocumentArray.prototype.constructor = SchemaDocumentArray; SchemaDocumentArray.prototype.OptionsConstructor = SchemaDocumentArrayOptions; Object.defineProperty(SchemaDocumentArray.prototype, "$conditionalHandlers", { enumerable: false, value: { ...SchemaArray.prototype.$conditionalHandlers } }); function _createConstructor(schema, options, baseClass) { Subdocument || (Subdocument = require_arraySubdocument()); function EmbeddedDocument() { Subdocument.apply(this, arguments); if (this.__parentArray == null || this.__parentArray.getArrayParent() == null) { return; } this.$session(this.__parentArray.getArrayParent().$session()); } schema._preCompile(); const proto = baseClass != null ? baseClass.prototype : Subdocument.prototype; EmbeddedDocument.prototype = Object.create(proto); EmbeddedDocument.prototype.$__setSchema(schema); EmbeddedDocument.schema = schema; EmbeddedDocument.prototype.constructor = EmbeddedDocument; EmbeddedDocument.$isArraySubdocument = true; EmbeddedDocument.events = new EventEmitter(); EmbeddedDocument.base = schema.base; for (const i in schema.methods) { EmbeddedDocument.prototype[i] = schema.methods[i]; } for (const i in schema.statics) { EmbeddedDocument[i] = schema.statics[i]; } for (const i in EventEmitter.prototype) { EmbeddedDocument[i] = EventEmitter.prototype[i]; } EmbeddedDocument.options = options; return EmbeddedDocument; } SchemaDocumentArray.prototype.discriminator = function(name, schema, options) { if (typeof name === "function") { name = utils.getFunctionName(name); } options = options || {}; const tiedValue = utils.isPOJO(options) ? options.value : options; const clone = typeof options.clone === "boolean" ? options.clone : true; if (schema.instanceOfSchema && clone) { schema = schema.clone(); } schema = discriminator(this.casterConstructor, name, schema, tiedValue, null, null, options?.overwriteExisting); const EmbeddedDocument = _createConstructor(schema, null, this.casterConstructor); EmbeddedDocument.baseCasterConstructor = this.casterConstructor; try { Object.defineProperty(EmbeddedDocument, "name", { value: name }); } catch (error) { } this.casterConstructor.discriminators[name] = EmbeddedDocument; return this.casterConstructor.discriminators[name]; }; SchemaDocumentArray.prototype.doValidate = function(array, fn, scope, options) { MongooseDocumentArray || (MongooseDocumentArray = require_documentArray()); const _this = this; try { SchemaType.prototype.doValidate.call(this, array, cb, scope); } catch (err) { return fn(err); } function cb(err) { if (err) { return fn(err); } let count = array && array.length; let error; if (!count) { return fn(); } if (options && options.updateValidator) { return fn(); } if (!utils.isMongooseDocumentArray(array)) { array = new MongooseDocumentArray(array, _this.path, scope); } function callback(err2) { if (err2 != null) { error = err2; } --count || fn(error); } for (let i = 0, len = count; i < len; ++i) { let doc = array[i]; if (doc == null) { --count || fn(error); continue; } if (!(doc instanceof Subdocument)) { const Constructor = getConstructor(_this.casterConstructor, array[i]); doc = array[i] = new Constructor(doc, array, void 0, void 0, i); } if (options != null && options.validateModifiedOnly && !doc.$isModified()) { --count || fn(error); continue; } doc.$__validate(null, options, callback); } } }; SchemaDocumentArray.prototype.doValidateSync = function(array, scope, options) { const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, array, scope); if (schemaTypeError != null) { return schemaTypeError; } const count = array && array.length; let resultError = null; if (!count) { return; } for (let i = 0, len = count; i < len; ++i) { let doc = array[i]; if (!doc) { continue; } if (!(doc instanceof Subdocument)) { const Constructor = getConstructor(this.casterConstructor, array[i]); doc = array[i] = new Constructor(doc, array, void 0, void 0, i); } if (options != null && options.validateModifiedOnly && !doc.$isModified()) { continue; } const subdocValidateError = doc.validateSync(options); if (subdocValidateError && resultError == null) { resultError = subdocValidateError; } } return resultError; }; SchemaDocumentArray.prototype.getDefault = function(scope, init, options) { let ret = typeof this.defaultValue === "function" ? this.defaultValue.call(scope) : this.defaultValue; if (ret == null) { return ret; } if (options && options.skipCast) { return ret; } MongooseDocumentArray || (MongooseDocumentArray = require_documentArray()); if (!Array.isArray(ret)) { ret = [ret]; } ret = new MongooseDocumentArray(ret, this.path, scope); for (let i = 0; i < ret.length; ++i) { const Constructor = getConstructor(this.casterConstructor, ret[i]); const _subdoc = new Constructor( {}, ret, void 0, void 0, i ); _subdoc.$init(ret[i]); _subdoc.isNew = true; Object.assign(_subdoc.$__.activePaths.default, _subdoc.$__.activePaths.init); _subdoc.$__.activePaths.init = {}; ret[i] = _subdoc; } return ret; }; var _toObjectOptions = Object.freeze({ transform: false, virtuals: false }); var initDocumentOptions = Object.freeze({ skipId: false, willInit: true }); SchemaDocumentArray.prototype.cast = function(value, doc, init, prev, options) { MongooseDocumentArray || (MongooseDocumentArray = require_documentArray()); if (value != null && value[arrayPathSymbol] != null && value === prev) { return value; } let selected; let subdoc; options = options || {}; const path = options.path || this.path; if (!Array.isArray(value)) { if (!init && !SchemaDocumentArray.options.castNonArrays) { throw new CastError("DocumentArray", value, this.path, null, this); } if (!!doc && init) { doc.markModified(path); } return this.cast([value], doc, init, prev, options); } if (!options.skipDocumentArrayCast || utils.isMongooseDocumentArray(value)) { value = new MongooseDocumentArray(value, path, doc, this); } if (prev != null) { value[arrayAtomicsSymbol] = prev[arrayAtomicsSymbol] || {}; } if (options.arrayPathIndex != null) { value[arrayPathSymbol] = path + "." + options.arrayPathIndex; } const rawArray = utils.isMongooseDocumentArray(value) ? value.__array : value; const len = rawArray.length; for (let i = 0; i < len; ++i) { if (!rawArray[i]) { continue; } const Constructor = getConstructor(this.casterConstructor, rawArray[i]); const spreadDoc = handleSpreadDoc(rawArray[i], true); if (rawArray[i] !== spreadDoc) { rawArray[i] = spreadDoc; } if (rawArray[i] instanceof Subdocument) { if (rawArray[i][documentArrayParent] !== doc) { if (init) { const subdoc2 = new Constructor(null, value, initDocumentOptions, selected, i); rawArray[i] = subdoc2.$init(rawArray[i]); } else { const subdoc2 = new Constructor(rawArray[i], value, void 0, void 0, i); rawArray[i] = subdoc2; } } if (rawArray[i].__index == null) { rawArray[i].$setIndex(i); } } else if (rawArray[i] != null) { if (init) { if (doc) { selected || (selected = scopePaths(this, doc.$__.selected, init)); } else { selected = true; } subdoc = new Constructor(null, value, initDocumentOptions, selected, i); rawArray[i] = subdoc.$init(rawArray[i]); } else { if (prev && typeof prev.id === "function") { subdoc = prev.id(rawArray[i]._id); } if (prev && subdoc && utils.deepEqual(subdoc.toObject(_toObjectOptions), rawArray[i])) { subdoc.set(rawArray[i]); rawArray[i] = subdoc; } else { try { subdoc = new Constructor( rawArray[i], value, void 0, void 0, i ); rawArray[i] = subdoc; } catch (error) { throw new CastError( "embedded", rawArray[i], value[arrayPathSymbol], error, this ); } } } } } return value; }; SchemaDocumentArray.prototype.clone = function() { const options = Object.assign({}, this.options); const schematype = new this.constructor(this.path, this.schema, options, this.schemaOptions); schematype.validators = this.validators.slice(); if (this.requiredValidator !== void 0) { schematype.requiredValidator = this.requiredValidator; } schematype.Constructor.discriminators = Object.assign( {}, this.Constructor.discriminators ); schematype._appliedDiscriminators = this._appliedDiscriminators; return schematype; }; SchemaDocumentArray.prototype.applyGetters = function(value, scope) { return SchemaType.prototype.applyGetters.call(this, value, scope); }; function scopePaths(array, fields, init) { if (!(init && fields)) { return void 0; } const path = array.path + "."; const keys = Object.keys(fields); let i = keys.length; const selected = {}; let hasKeys; let key; let sub; while (i--) { key = keys[i]; if (key.startsWith(path)) { sub = key.substring(path.length); if (sub === "$") { continue; } if (sub.startsWith("$.")) { sub = sub.substring(2); } hasKeys || (hasKeys = true); selected[sub] = fields[key]; } } return hasKeys && selected || void 0; } SchemaDocumentArray.defaultOptions = {}; SchemaDocumentArray.set = SchemaType.set; SchemaDocumentArray.setters = []; SchemaDocumentArray.get = SchemaType.get; SchemaDocumentArray.prototype.$conditionalHandlers.$elemMatch = cast$elemMatch; function cast$elemMatch(val, context) { const keys = Object.keys(val); const numKeys = keys.length; for (let i = 0; i < numKeys; ++i) { const key = keys[i]; const value = val[key]; if (isOperator(key) && value != null) { val[key] = this.castForQuery(key, value, context); } } const discriminatorKey = this && this.casterConstructor && this.casterConstructor.schema && this.casterConstructor.schema.options && this.casterConstructor.schema.options.discriminatorKey; const discriminators = this && this.casterConstructor && this.casterConstructor.schema && this.casterConstructor.schema.discriminators || {}; if (discriminatorKey != null && val[discriminatorKey] != null && discriminators[val[discriminatorKey]] != null) { return cast(discriminators[val[discriminatorKey]], val, null, this && this.$$context); } const schema = this.casterConstructor.schema ?? context.schema; return cast(schema, val, null, this && this.$$context); } SchemaDocumentArray.prototype.toJSONSchema = function toJSONSchema(options) { const itemsTypeDefinition = createJSONSchemaTypeDefinition("object", "object", options?.useBsonType, false); const isRequired = this.options.required && typeof this.options.required !== "function"; return { ...createJSONSchemaTypeDefinition("array", "array", options?.useBsonType, isRequired), items: { ...itemsTypeDefinition, ...this.schema.toJSONSchema(options) } }; }; module2.exports = SchemaDocumentArray; } }); // netlify/functions/node_modules/mongoose/lib/cast/double.js var require_double2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/cast/double.js"(exports2, module2) { "use strict"; var assert = require("assert"); var BSON = require_bson(); var isBsonType = require_isBsonType(); module2.exports = function castDouble(val) { if (val == null || val === "") { return null; } let coercedVal; if (isBsonType(val, "Long")) { coercedVal = val.toNumber(); } else if (typeof val === "string") { try { coercedVal = BSON.Double.fromString(val); return coercedVal; } catch { assert.ok(false); } } else if (typeof val === "object") { const tempVal = val.valueOf() ?? val.toString(); if (typeof tempVal === "string") { try { coercedVal = BSON.Double.fromString(val); return coercedVal; } catch { assert.ok(false); } } else { coercedVal = Number(tempVal); } } else { coercedVal = Number(val); } return new BSON.Double(coercedVal); }; } }); // netlify/functions/node_modules/mongoose/lib/schema/double.js var require_double3 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/double.js"(exports2, module2) { "use strict"; var CastError = require_cast(); var SchemaType = require_schemaType(); var castDouble = require_double2(); var createJSONSchemaTypeDefinition = require_createJSONSchemaTypeDefinition(); function SchemaDouble(path, options) { SchemaType.call(this, path, options, "Double"); } SchemaDouble.schemaName = "Double"; SchemaDouble.defaultOptions = {}; SchemaDouble.prototype = Object.create(SchemaType.prototype); SchemaDouble.prototype.constructor = SchemaDouble; SchemaDouble._cast = castDouble; SchemaDouble.set = SchemaType.set; SchemaDouble.setters = []; SchemaDouble.get = SchemaType.get; SchemaDouble._defaultCaster = (v) => { if (v != null) { if (v._bsontype !== "Double") { throw new Error(); } } return v; }; SchemaDouble.cast = function cast(caster) { if (arguments.length === 0) { return this._cast; } if (caster === false) { caster = this._defaultCaster; } this._cast = caster; return this._cast; }; SchemaDouble._checkRequired = (v) => v != null; SchemaDouble.checkRequired = SchemaType.checkRequired; SchemaDouble.prototype.checkRequired = function(value) { return this.constructor._checkRequired(value); }; SchemaDouble.prototype.cast = function(value) { let castDouble2; if (typeof this._castFunction === "function") { castDouble2 = this._castFunction; } else if (typeof this.constructor.cast === "function") { castDouble2 = this.constructor.cast(); } else { castDouble2 = SchemaDouble.cast(); } try { return castDouble2(value); } catch (error) { throw new CastError("Double", value, this.path, error, this); } }; function handleSingle(val) { return this.cast(val); } var $conditionalHandlers = { ...SchemaType.prototype.$conditionalHandlers, $gt: handleSingle, $gte: handleSingle, $lt: handleSingle, $lte: handleSingle }; Object.defineProperty(SchemaDouble.prototype, "$conditionalHandlers", { enumerable: false, value: $conditionalHandlers }); SchemaDouble.prototype.toJSONSchema = function toJSONSchema(options) { const isRequired = this.options.required && typeof this.options.required !== "function"; return createJSONSchemaTypeDefinition("number", "double", options?.useBsonType, isRequired); }; SchemaDouble.prototype.autoEncryptionType = function autoEncryptionType() { return "double"; }; module2.exports = SchemaDouble; } }); // netlify/functions/node_modules/mongoose/lib/cast/int32.js var require_int32 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/cast/int32.js"(exports2, module2) { "use strict"; var isBsonType = require_isBsonType(); var assert = require("assert"); module2.exports = function castInt32(val) { if (val == null) { return val; } if (val === "") { return null; } const coercedVal = isBsonType(val, "Long") ? val.toNumber() : Number(val); const INT32_MAX = 2147483647; const INT32_MIN = -2147483648; if (coercedVal === (coercedVal | 0) && coercedVal >= INT32_MIN && coercedVal <= INT32_MAX) { return coercedVal; } assert.ok(false); }; } }); // netlify/functions/node_modules/mongoose/lib/schema/int32.js var require_int322 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/int32.js"(exports2, module2) { "use strict"; var CastError = require_cast(); var SchemaType = require_schemaType(); var castInt32 = require_int32(); var createJSONSchemaTypeDefinition = require_createJSONSchemaTypeDefinition(); var handleBitwiseOperator = require_bitwise(); function SchemaInt32(path, options) { SchemaType.call(this, path, options, "Int32"); } SchemaInt32.schemaName = "Int32"; SchemaInt32.defaultOptions = {}; SchemaInt32.prototype = Object.create(SchemaType.prototype); SchemaInt32.prototype.constructor = SchemaInt32; SchemaInt32._cast = castInt32; SchemaInt32.set = SchemaType.set; SchemaInt32.setters = []; SchemaInt32.get = SchemaType.get; SchemaInt32._defaultCaster = (v) => { const INT32_MAX = 2147483647; const INT32_MIN = -2147483648; if (v != null) { if (typeof v !== "number" || v !== (v | 0) || v < INT32_MIN || v > INT32_MAX) { throw new Error(); } } return v; }; SchemaInt32.cast = function cast(caster) { if (arguments.length === 0) { return this._cast; } if (caster === false) { caster = this._defaultCaster; } this._cast = caster; return this._cast; }; SchemaInt32._checkRequired = (v) => v != null; SchemaInt32.checkRequired = SchemaType.checkRequired; SchemaInt32.prototype.checkRequired = function(value) { return this.constructor._checkRequired(value); }; SchemaInt32.prototype.cast = function(value) { let castInt322; if (typeof this._castFunction === "function") { castInt322 = this._castFunction; } else if (typeof this.constructor.cast === "function") { castInt322 = this.constructor.cast(); } else { castInt322 = SchemaInt32.cast(); } try { return castInt322(value); } catch (error) { throw new CastError("Int32", value, this.path, error, this); } }; var $conditionalHandlers = { ...SchemaType.prototype.$conditionalHandlers, $gt: handleSingle, $gte: handleSingle, $lt: handleSingle, $lte: handleSingle, $bitsAllClear: handleBitwiseOperator, $bitsAnyClear: handleBitwiseOperator, $bitsAllSet: handleBitwiseOperator, $bitsAnySet: handleBitwiseOperator }; Object.defineProperty(SchemaInt32.prototype, "$conditionalHandlers", { enumerable: false, value: $conditionalHandlers }); function handleSingle(val, context) { return this.castForQuery(null, val, context); } SchemaInt32.prototype.castForQuery = function($conditional, val, context) { let handler; if ($conditional != null) { handler = this.$conditionalHandlers[$conditional]; if (handler) { return handler.call(this, val); } return this.applySetters(val, context); } try { return this.applySetters(val, context); } catch (err) { if (err instanceof CastError && err.path === this.path && this.$fullPath != null) { err.path = this.$fullPath; } throw err; } }; SchemaInt32.prototype.toJSONSchema = function toJSONSchema(options) { const isRequired = this.options.required && typeof this.options.required !== "function"; return createJSONSchemaTypeDefinition("number", "int", options?.useBsonType, isRequired); }; SchemaInt32.prototype.autoEncryptionType = function autoEncryptionType() { return "int"; }; module2.exports = SchemaInt32; } }); // netlify/functions/node_modules/mongoose/lib/options/schemaMapOptions.js var require_schemaMapOptions = __commonJS({ "netlify/functions/node_modules/mongoose/lib/options/schemaMapOptions.js"(exports2, module2) { "use strict"; var SchemaTypeOptions = require_schemaTypeOptions(); var SchemaMapOptions = class extends SchemaTypeOptions { }; var opts = require_propertyOptions(); Object.defineProperty(SchemaMapOptions.prototype, "of", opts); module2.exports = SchemaMapOptions; } }); // netlify/functions/node_modules/mongoose/lib/schema/map.js var require_map2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/map.js"(exports2, module2) { "use strict"; var MongooseMap = require_map(); var SchemaMapOptions = require_schemaMapOptions(); var SchemaType = require_schemaType(); var createJSONSchemaTypeDefinition = require_createJSONSchemaTypeDefinition(); var SchemaMap = class extends SchemaType { constructor(key, options) { super(key, options, "Map"); this.$isSchemaMap = true; } set(option, value) { return SchemaType.set(option, value); } cast(val, doc, init, prev, options) { if (val instanceof MongooseMap) { return val; } const path = options?.path ?? this.path; if (init) { const map = new MongooseMap({}, path, doc, this.$__schemaType); if (val instanceof global.Map) { for (const key of val.keys()) { let _val = val.get(key); if (_val == null) { _val = map.$__schemaType._castNullish(_val); } else { _val = map.$__schemaType.cast(_val, doc, true, null, { path: path + "." + key }); } map.$init(key, _val); } } else { for (const key of Object.keys(val)) { let _val = val[key]; if (_val == null) { _val = map.$__schemaType._castNullish(_val); } else { _val = map.$__schemaType.cast(_val, doc, true, null, { path: path + "." + key }); } map.$init(key, _val); } } return map; } return new MongooseMap(val, path, doc, this.$__schemaType); } clone() { const schematype = super.clone(); if (this.$__schemaType != null) { schematype.$__schemaType = this.$__schemaType.clone(); } return schematype; } /** * Returns the embedded schema type (i.e. the `.$*` path) */ getEmbeddedSchemaType() { return this.$__schemaType; } /** * Returns this schema type's representation in a JSON schema. * * @param [options] * @param [options.useBsonType=false] If true, return a representation with `bsonType` for use with MongoDB's `$jsonSchema`. * @returns {Object} JSON schema properties */ toJSONSchema(options) { const useBsonType = options?.useBsonType; const embeddedSchemaType = this.getEmbeddedSchemaType(); const isRequired = this.options.required && typeof this.options.required !== "function"; const result = createJSONSchemaTypeDefinition("object", "object", useBsonType, isRequired); result.additionalProperties = embeddedSchemaType.toJSONSchema(options); return result; } autoEncryptionType() { return "object"; } }; SchemaMap.schemaName = "Map"; SchemaMap.prototype.OptionsConstructor = SchemaMapOptions; SchemaMap.defaultOptions = {}; module2.exports = SchemaMap; } }); // netlify/functions/node_modules/mongoose/lib/options/schemaObjectIdOptions.js var require_schemaObjectIdOptions = __commonJS({ "netlify/functions/node_modules/mongoose/lib/options/schemaObjectIdOptions.js"(exports2, module2) { "use strict"; var SchemaTypeOptions = require_schemaTypeOptions(); var SchemaObjectIdOptions = class extends SchemaTypeOptions { }; var opts = require_propertyOptions(); Object.defineProperty(SchemaObjectIdOptions.prototype, "auto", opts); Object.defineProperty(SchemaObjectIdOptions.prototype, "populate", opts); module2.exports = SchemaObjectIdOptions; } }); // netlify/functions/node_modules/mongoose/lib/schema/objectId.js var require_objectId = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/objectId.js"(exports2, module2) { "use strict"; var SchemaObjectIdOptions = require_schemaObjectIdOptions(); var SchemaType = require_schemaType(); var castObjectId = require_objectid2(); var createJSONSchemaTypeDefinition = require_createJSONSchemaTypeDefinition(); var getConstructorName = require_getConstructorName(); var oid = require_objectid(); var isBsonType = require_isBsonType(); var utils = require_utils3(); var CastError = SchemaType.CastError; var Document; function SchemaObjectId(key, options) { const isKeyHexStr = typeof key === "string" && key.length === 24 && /^[a-f0-9]+$/i.test(key); const suppressWarning = options && options.suppressWarning; if ((isKeyHexStr || typeof key === "undefined") && !suppressWarning) { utils.warn("mongoose: To create a new ObjectId please try `Mongoose.Types.ObjectId` instead of using `Mongoose.Schema.ObjectId`. Set the `suppressWarning` option if you're trying to create a hex char path in your schema."); } SchemaType.call(this, key, options, "ObjectId"); } SchemaObjectId.schemaName = "ObjectId"; SchemaObjectId.defaultOptions = {}; SchemaObjectId.prototype = Object.create(SchemaType.prototype); SchemaObjectId.prototype.constructor = SchemaObjectId; SchemaObjectId.prototype.OptionsConstructor = SchemaObjectIdOptions; SchemaObjectId.get = SchemaType.get; SchemaObjectId.set = SchemaType.set; SchemaObjectId.setters = []; SchemaObjectId.prototype.auto = function(turnOn) { if (turnOn) { this.default(defaultId); this.set(resetId); } return this; }; SchemaObjectId._checkRequired = (v) => isBsonType(v, "ObjectId"); SchemaObjectId._cast = castObjectId; SchemaObjectId.cast = function cast(caster) { if (arguments.length === 0) { return this._cast; } if (caster === false) { caster = this._defaultCaster; } this._cast = caster; return this._cast; }; SchemaObjectId._defaultCaster = (v) => { if (!isBsonType(v, "ObjectId")) { throw new Error(v + " is not an instance of ObjectId"); } return v; }; SchemaObjectId.checkRequired = SchemaType.checkRequired; SchemaObjectId.prototype.checkRequired = function checkRequired(value, doc) { if (SchemaType._isRef(this, value, doc, true)) { return !!value; } const _checkRequired = typeof this.constructor.checkRequired === "function" ? this.constructor.checkRequired() : SchemaObjectId.checkRequired(); return _checkRequired(value); }; SchemaObjectId.prototype.cast = function(value, doc, init, prev, options) { if (!isBsonType(value, "ObjectId") && SchemaType._isRef(this, value, doc, init)) { if ((getConstructorName(value) || "").toLowerCase() === "objectid") { return new oid(value.toHexString()); } if (value == null || utils.isNonBuiltinObject(value)) { return this._castRef(value, doc, init, options); } } let castObjectId2; if (typeof this._castFunction === "function") { castObjectId2 = this._castFunction; } else if (typeof this.constructor.cast === "function") { castObjectId2 = this.constructor.cast(); } else { castObjectId2 = SchemaObjectId.cast(); } try { return castObjectId2(value); } catch (error) { throw new CastError("ObjectId", value, this.path, error, this); } }; function handleSingle(val) { return this.cast(val); } var $conditionalHandlers = { ...SchemaType.prototype.$conditionalHandlers, $gt: handleSingle, $gte: handleSingle, $lt: handleSingle, $lte: handleSingle }; Object.defineProperty(SchemaObjectId.prototype, "$conditionalHandlers", { enumerable: false, value: $conditionalHandlers }); function defaultId() { return new oid(); } defaultId.$runBeforeSetters = true; function resetId(v) { Document || (Document = require_document2()); if (this instanceof Document) { if (v === void 0) { const _v = new oid(); return _v; } } return v; } SchemaObjectId.prototype.toJSONSchema = function toJSONSchema(options) { const isRequired = this.options.required && typeof this.options.required !== "function" || this.path === "_id"; return createJSONSchemaTypeDefinition("string", "objectId", options?.useBsonType, isRequired); }; SchemaObjectId.prototype.autoEncryptionType = function autoEncryptionType() { return "objectId"; }; module2.exports = SchemaObjectId; } }); // netlify/functions/node_modules/mongoose/lib/options/schemaStringOptions.js var require_schemaStringOptions = __commonJS({ "netlify/functions/node_modules/mongoose/lib/options/schemaStringOptions.js"(exports2, module2) { "use strict"; var SchemaTypeOptions = require_schemaTypeOptions(); var SchemaStringOptions = class extends SchemaTypeOptions { }; var opts = require_propertyOptions(); Object.defineProperty(SchemaStringOptions.prototype, "enum", opts); Object.defineProperty(SchemaStringOptions.prototype, "match", opts); Object.defineProperty(SchemaStringOptions.prototype, "lowercase", opts); Object.defineProperty(SchemaStringOptions.prototype, "trim", opts); Object.defineProperty(SchemaStringOptions.prototype, "uppercase", opts); Object.defineProperty(SchemaStringOptions.prototype, "minLength", opts); Object.defineProperty(SchemaStringOptions.prototype, "minlength", opts); Object.defineProperty(SchemaStringOptions.prototype, "maxLength", opts); Object.defineProperty(SchemaStringOptions.prototype, "maxlength", opts); Object.defineProperty(SchemaStringOptions.prototype, "populate", opts); module2.exports = SchemaStringOptions; } }); // netlify/functions/node_modules/mongoose/lib/schema/string.js var require_string2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/string.js"(exports2, module2) { "use strict"; var SchemaType = require_schemaType(); var MongooseError = require_error2(); var SchemaStringOptions = require_schemaStringOptions(); var castString = require_string(); var createJSONSchemaTypeDefinition = require_createJSONSchemaTypeDefinition(); var utils = require_utils3(); var isBsonType = require_isBsonType(); var CastError = SchemaType.CastError; function SchemaString(key, options) { this.enumValues = []; this.regExp = null; SchemaType.call(this, key, options, "String"); } SchemaString.schemaName = "String"; SchemaString.defaultOptions = {}; SchemaString.prototype = Object.create(SchemaType.prototype); SchemaString.prototype.constructor = SchemaString; Object.defineProperty(SchemaString.prototype, "OptionsConstructor", { configurable: false, enumerable: false, writable: false, value: SchemaStringOptions }); SchemaString._cast = castString; SchemaString.cast = function cast(caster) { if (arguments.length === 0) { return this._cast; } if (caster === false) { caster = this._defaultCaster; } this._cast = caster; return this._cast; }; SchemaString._defaultCaster = (v) => { if (v != null && typeof v !== "string") { throw new Error(); } return v; }; SchemaString.get = SchemaType.get; SchemaString.set = SchemaType.set; SchemaString.setters = []; SchemaString._checkRequired = (v) => (v instanceof String || typeof v === "string") && v.length; SchemaString.checkRequired = SchemaType.checkRequired; SchemaString.prototype.enum = function() { if (this.enumValidator) { this.validators = this.validators.filter(function(v) { return v.validator !== this.enumValidator; }, this); this.enumValidator = false; } if (arguments[0] === void 0 || arguments[0] === false) { return this; } let values; let errorMessage; if (utils.isObject(arguments[0])) { if (Array.isArray(arguments[0].values)) { values = arguments[0].values; errorMessage = arguments[0].message; } else { values = utils.object.vals(arguments[0]); errorMessage = MongooseError.messages.String.enum; } } else { values = arguments; errorMessage = MongooseError.messages.String.enum; } for (const value of values) { if (value !== void 0) { this.enumValues.push(this.cast(value)); } } const vals = this.enumValues; this.enumValidator = function(v) { return null == v || ~vals.indexOf(v); }; this.validators.push({ validator: this.enumValidator, message: errorMessage, type: "enum", enumValues: vals }); return this; }; SchemaString.prototype.lowercase = function(shouldApply) { if (arguments.length > 0 && !shouldApply) { return this; } return this.set((v) => { if (typeof v !== "string") { v = this.cast(v); } if (v) { return v.toLowerCase(); } return v; }); }; SchemaString.prototype.uppercase = function(shouldApply) { if (arguments.length > 0 && !shouldApply) { return this; } return this.set((v) => { if (typeof v !== "string") { v = this.cast(v); } if (v) { return v.toUpperCase(); } return v; }); }; SchemaString.prototype.trim = function(shouldTrim) { if (arguments.length > 0 && !shouldTrim) { return this; } return this.set((v) => { if (typeof v !== "string") { v = this.cast(v); } if (v) { return v.trim(); } return v; }); }; SchemaString.prototype.minlength = function(value, message) { if (this.minlengthValidator) { this.validators = this.validators.filter(function(v) { return v.validator !== this.minlengthValidator; }, this); } if (value !== null && value !== void 0) { let msg = message || MongooseError.messages.String.minlength; msg = msg.replace(/{MINLENGTH}/, value); this.validators.push({ validator: this.minlengthValidator = function(v) { return v === null || v.length >= value; }, message: msg, type: "minlength", minlength: value }); } return this; }; SchemaString.prototype.minLength = SchemaString.prototype.minlength; SchemaString.prototype.maxlength = function(value, message) { if (this.maxlengthValidator) { this.validators = this.validators.filter(function(v) { return v.validator !== this.maxlengthValidator; }, this); } if (value !== null && value !== void 0) { let msg = message || MongooseError.messages.String.maxlength; msg = msg.replace(/{MAXLENGTH}/, value); this.validators.push({ validator: this.maxlengthValidator = function(v) { return v === null || v.length <= value; }, message: msg, type: "maxlength", maxlength: value }); } return this; }; SchemaString.prototype.maxLength = SchemaString.prototype.maxlength; SchemaString.prototype.match = function match(regExp, message) { const msg = message || MongooseError.messages.String.match; const matchValidator = function(v) { if (!regExp) { return false; } regExp.lastIndex = 0; const ret = v != null && v !== "" ? regExp.test(v) : true; return ret; }; this.validators.push({ validator: matchValidator, message: msg, type: "regexp", regexp: regExp }); return this; }; SchemaString.prototype.checkRequired = function checkRequired(value, doc) { if (typeof value === "object" && SchemaType._isRef(this, value, doc, true)) { return value != null; } const _checkRequired = typeof this.constructor.checkRequired === "function" ? this.constructor.checkRequired() : SchemaString.checkRequired(); return _checkRequired(value); }; SchemaString.prototype.cast = function(value, doc, init, prev, options) { if (typeof value !== "string" && SchemaType._isRef(this, value, doc, init)) { return this._castRef(value, doc, init, options); } let castString2; if (typeof this._castFunction === "function") { castString2 = this._castFunction; } else if (typeof this.constructor.cast === "function") { castString2 = this.constructor.cast(); } else { castString2 = SchemaString.cast(); } try { return castString2(value); } catch (error) { throw new CastError("string", value, this.path, null, this); } }; function handleSingle(val, context) { return this.castForQuery(null, val, context); } function handleArray(val, context) { const _this = this; if (!Array.isArray(val)) { return [this.castForQuery(null, val, context)]; } return val.map(function(m) { return _this.castForQuery(null, m, context); }); } function handleSingleNoSetters(val) { if (val == null) { return this._castNullish(val); } return this.cast(val, this); } var $conditionalHandlers = { ...SchemaType.prototype.$conditionalHandlers, $all: handleArray, $gt: handleSingle, $gte: handleSingle, $lt: handleSingle, $lte: handleSingle, $options: handleSingleNoSetters, $regex: function handle$regex(val) { if (Object.prototype.toString.call(val) === "[object RegExp]") { return val; } return handleSingleNoSetters.call(this, val); }, $not: handleSingle }; Object.defineProperty(SchemaString.prototype, "$conditionalHandlers", { enumerable: false, value: $conditionalHandlers }); SchemaString.prototype.castForQuery = function($conditional, val, context) { let handler; if ($conditional != null) { handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new Error("Can't use " + $conditional + " with String."); } return handler.call(this, val, context); } if (Object.prototype.toString.call(val) === "[object RegExp]" || isBsonType(val, "BSONRegExp")) { return val; } try { return this.applySetters(val, context); } catch (err) { if (err instanceof CastError && err.path === this.path && this.$fullPath != null) { err.path = this.$fullPath; } throw err; } }; SchemaString.prototype.toJSONSchema = function toJSONSchema(options) { const isRequired = this.options.required && typeof this.options.required !== "function"; return createJSONSchemaTypeDefinition("string", "string", options?.useBsonType, isRequired); }; SchemaString.prototype.autoEncryptionType = function autoEncryptionType() { return "string"; }; module2.exports = SchemaString; } }); // netlify/functions/node_modules/mongoose/lib/cast/uuid.js var require_uuid2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/cast/uuid.js"(exports2, module2) { "use strict"; var MongooseBuffer = require_buffer(); var UUID_FORMAT = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i; var Binary = MongooseBuffer.Binary; module2.exports = function castUUID(value) { if (value == null) { return value; } function newBuffer(initbuff) { const buff = new MongooseBuffer(initbuff); buff._subtype = 4; return buff; } if (typeof value === "string") { if (UUID_FORMAT.test(value)) { return stringToBinary(value); } else { throw new Error(`"${value}" is not a valid UUID string`); } } if (Buffer.isBuffer(value)) { return newBuffer(value); } if (value instanceof Binary) { return newBuffer(value.value(true)); } if (value.toString && value.toString !== Object.prototype.toString) { if (UUID_FORMAT.test(value.toString())) { return stringToBinary(value.toString()); } } throw new Error(`"${value}" cannot be casted to a UUID`); }; module2.exports.UUID_FORMAT = UUID_FORMAT; function hex2buffer(hex) { const buff = hex != null && Buffer.from(hex, "hex"); return buff; } function stringToBinary(uuidStr) { if (typeof uuidStr !== "string") uuidStr = ""; const hex = uuidStr.replace(/[{}-]/g, ""); const bytes = hex2buffer(hex); const buff = new MongooseBuffer(bytes); buff._subtype = 4; return buff; } } }); // netlify/functions/node_modules/mongoose/lib/schema/uuid.js var require_uuid3 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/uuid.js"(exports2, module2) { "use strict"; var MongooseBuffer = require_buffer(); var SchemaType = require_schemaType(); var CastError = SchemaType.CastError; var castUUID = require_uuid2(); var createJSONSchemaTypeDefinition = require_createJSONSchemaTypeDefinition(); var utils = require_utils3(); var handleBitwiseOperator = require_bitwise(); var UUID_FORMAT = castUUID.UUID_FORMAT; var Binary = MongooseBuffer.Binary; function binaryToString(uuidBin) { let hex; if (typeof uuidBin !== "string" && uuidBin != null) { hex = uuidBin.toString("hex"); const uuidStr = hex.substring(0, 8) + "-" + hex.substring(8, 8 + 4) + "-" + hex.substring(12, 12 + 4) + "-" + hex.substring(16, 16 + 4) + "-" + hex.substring(20, 20 + 12); return uuidStr; } return uuidBin; } function SchemaUUID(key, options) { SchemaType.call(this, key, options, "UUID"); this.getters.push(function(value) { if (value != null && value.$__ != null) { return value; } if (Buffer.isBuffer(value)) { return binaryToString(value); } else if (value instanceof Binary) { return binaryToString(value.buffer); } else if (utils.isPOJO(value) && value.type === "Buffer" && Array.isArray(value.data)) { return binaryToString(Buffer.from(value.data)); } return value; }); } SchemaUUID.schemaName = "UUID"; SchemaUUID.defaultOptions = {}; SchemaUUID.prototype = Object.create(SchemaType.prototype); SchemaUUID.prototype.constructor = SchemaUUID; SchemaUUID._cast = castUUID; SchemaUUID.get = SchemaType.get; SchemaUUID.set = SchemaType.set; SchemaUUID.setters = []; SchemaUUID.cast = function cast(caster) { if (arguments.length === 0) { return this._cast; } if (caster === false) { caster = this._defaultCaster; } this._cast = caster; return this._cast; }; SchemaUUID._checkRequired = (v) => v != null; SchemaUUID.checkRequired = SchemaType.checkRequired; SchemaUUID.prototype.checkRequired = function checkRequired(value) { if (Buffer.isBuffer(value)) { value = binaryToString(value); } return value != null && UUID_FORMAT.test(value); }; SchemaUUID.prototype.cast = function(value, doc, init, prev, options) { if (utils.isNonBuiltinObject(value) && SchemaType._isRef(this, value, doc, init)) { return this._castRef(value, doc, init, options); } let castFn; if (typeof this._castFunction === "function") { castFn = this._castFunction; } else if (typeof this.constructor.cast === "function") { castFn = this.constructor.cast(); } else { castFn = SchemaUUID.cast(); } try { return castFn(value); } catch (error) { throw new CastError(SchemaUUID.schemaName, value, this.path, error, this); } }; function handleSingle(val) { return this.cast(val); } function handleArray(val) { return val.map((m) => { return this.cast(m); }); } var $conditionalHandlers = { ...SchemaType.prototype.$conditionalHandlers, $bitsAllClear: handleBitwiseOperator, $bitsAnyClear: handleBitwiseOperator, $bitsAllSet: handleBitwiseOperator, $bitsAnySet: handleBitwiseOperator, $all: handleArray, $gt: handleSingle, $gte: handleSingle, $in: handleArray, $lt: handleSingle, $lte: handleSingle, $ne: handleSingle, $nin: handleArray }; Object.defineProperty(SchemaUUID.prototype, "$conditionalHandlers", { enumerable: false, value: $conditionalHandlers }); SchemaUUID.prototype.castForQuery = function($conditional, val, context) { let handler; if ($conditional != null) { handler = this.$conditionalHandlers[$conditional]; if (!handler) throw new Error("Can't use " + $conditional + " with UUID."); return handler.call(this, val, context); } try { return this.applySetters(val, context); } catch (err) { if (err instanceof CastError && err.path === this.path && this.$fullPath != null) { err.path = this.$fullPath; } throw err; } }; SchemaUUID.prototype.toJSONSchema = function toJSONSchema(options) { const isRequired = this.options.required && typeof this.options.required !== "function"; return createJSONSchemaTypeDefinition("string", "binData", options?.useBsonType, isRequired); }; SchemaUUID.prototype.autoEncryptionType = function autoEncryptionType() { return "binData"; }; module2.exports = SchemaUUID; } }); // netlify/functions/node_modules/mongoose/lib/options/schemaUnionOptions.js var require_schemaUnionOptions = __commonJS({ "netlify/functions/node_modules/mongoose/lib/options/schemaUnionOptions.js"(exports2, module2) { "use strict"; var SchemaTypeOptions = require_schemaTypeOptions(); var SchemaUnionOptions = class extends SchemaTypeOptions { }; var opts = require_propertyOptions(); Object.defineProperty(SchemaUnionOptions.prototype, "of", opts); module2.exports = SchemaUnionOptions; } }); // netlify/functions/node_modules/mongoose/lib/schema/union.js var require_union = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/union.js"(exports2, module2) { "use strict"; var SchemaUnionOptions = require_schemaUnionOptions(); var SchemaType = require_schemaType(); var firstValueSymbol = Symbol("firstValue"); var Union = class extends SchemaType { constructor(key, options, schemaOptions = {}) { super(key, options, "Union"); if (!options || !Array.isArray(options.of) || options.of.length === 0) { throw new Error("Union schema type requires an array of types"); } this.schemaTypes = options.of.map((obj) => options.parentSchema.interpretAsType(key, obj, schemaOptions)); } cast(val, doc, init, prev, options) { let firstValue = firstValueSymbol; let lastError; for (let i = 0; i < this.schemaTypes.length; ++i) { try { const casted = this.schemaTypes[i].cast(val, doc, init, prev, options); if (casted === val) { return casted; } if (firstValue === firstValueSymbol) { firstValue = casted; } } catch (error) { lastError = error; } } if (firstValue !== firstValueSymbol) { return firstValue; } throw lastError; } // Setters also need to be aware of casting - we need to apply the setters of the entry in the union we choose. applySetters(val, doc, init, prev, options) { let firstValue = firstValueSymbol; let lastError; for (let i = 0; i < this.schemaTypes.length; ++i) { try { let castedVal = this.schemaTypes[i]._applySetters(val, doc, init, prev, options); if (castedVal == null) { castedVal = this.schemaTypes[i]._castNullish(castedVal); } else { castedVal = this.schemaTypes[i].cast(castedVal, doc, init, prev, options); } if (castedVal === val) { return castedVal; } if (firstValue === firstValueSymbol) { firstValue = castedVal; } } catch (error) { lastError = error; } } if (firstValue !== firstValueSymbol) { return firstValue; } throw lastError; } clone() { const schematype = super.clone(); schematype.schemaTypes = this.schemaTypes.map((schemaType) => schemaType.clone()); return schematype; } }; Union.schemaName = "Union"; Union.defaultOptions = {}; Union.prototype.OptionsConstructor = SchemaUnionOptions; module2.exports = Union; } }); // netlify/functions/node_modules/mongoose/lib/schema/index.js var require_schema = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema/index.js"(exports2) { "use strict"; exports2.Array = require_array2(); exports2.BigInt = require_bigint2(); exports2.Boolean = require_boolean2(); exports2.Buffer = require_buffer2(); exports2.Date = require_date2(); exports2.Decimal128 = exports2.Decimal = require_decimal1283(); exports2.DocumentArray = require_documentArray2(); exports2.Double = require_double3(); exports2.Int32 = require_int322(); exports2.Map = require_map2(); exports2.Mixed = require_mixed(); exports2.Number = require_number2(); exports2.ObjectId = require_objectId(); exports2.String = require_string2(); exports2.Subdocument = require_subdocument2(); exports2.UUID = require_uuid3(); exports2.Union = require_union(); exports2.Oid = exports2.ObjectId; exports2.Object = exports2.Mixed; exports2.Bool = exports2.Boolean; exports2.ObjectID = exports2.ObjectId; } }); // netlify/functions/node_modules/mongoose/lib/schema.js var require_schema2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/schema.js"(exports2, module2) { "use strict"; var EventEmitter = require("events").EventEmitter; var Kareem = require_kareem(); var MongooseError = require_mongooseError(); var SchemaType = require_schemaType(); var SchemaTypeOptions = require_schemaTypeOptions(); var VirtualOptions = require_virtualOptions(); var VirtualType = require_virtualType(); var addAutoId = require_addAutoId(); var clone = require_clone(); var get = require_get(); var getConstructorName = require_getConstructorName(); var getIndexes = require_getIndexes(); var handleReadPreferenceAliases = require_handleReadPreferenceAliases(); var idGetter = require_idGetter(); var isIndexSpecEqual = require_isIndexSpecEqual(); var merge = require_merge(); var mpath = require_mpath(); var setPopulatedVirtualValue = require_setPopulatedVirtualValue(); var setupTimestamps = require_setupTimestamps(); var utils = require_utils3(); var validateRef = require_validateRef(); var hasNumericSubpathRegex = /\.\d+(\.|$)/; var MongooseTypes; var queryHooks = require_constants3().queryMiddlewareFunctions; var documentHooks = require_applyHooks().middlewareFunctions; var hookNames = queryHooks.concat(documentHooks).reduce((s, hook) => s.add(hook), /* @__PURE__ */ new Set()); var isPOJO = utils.isPOJO; var id = 0; var numberRE = /^\d+$/; function Schema(obj, options) { if (!(this instanceof Schema)) { return new Schema(obj, options); } this.obj = obj; this.paths = {}; this.aliases = {}; this.subpaths = {}; this.virtuals = {}; this.singleNestedPaths = {}; this.nested = {}; this.inherits = {}; this.callQueue = []; this._indexes = []; this._searchIndexes = []; this.methods = options && options.methods || {}; this.methodOptions = {}; this.statics = options && options.statics || {}; this.tree = {}; this.query = options && options.query || {}; this.childSchemas = []; this.plugins = []; this.$id = ++id; this.mapPaths = []; this.encryptedFields = {}; this.s = { hooks: new Kareem() }; this.options = this.defaultOptions(options); if (Array.isArray(obj)) { for (const definition of obj) { this.add(definition); } } else if (obj) { this.add(obj); } if (options && options.virtuals) { const virtuals = options.virtuals; const pathNames = Object.keys(virtuals); for (const pathName of pathNames) { const pathOptions = virtuals[pathName].options ? virtuals[pathName].options : void 0; const virtual = this.virtual(pathName, pathOptions); if (virtuals[pathName].get) { virtual.get(virtuals[pathName].get); } if (virtuals[pathName].set) { virtual.set(virtuals[pathName].set); } } } const _idSubDoc = obj && obj._id && utils.isObject(obj._id); const auto_id = !this.paths["_id"] && this.options._id && !_idSubDoc; if (auto_id) { addAutoId(this); } this.setupTimestamp(this.options.timestamps); } function aliasFields(schema, paths) { for (const path of Object.keys(paths)) { let alias = null; if (paths[path] != null) { alias = paths[path]; } else { const options = get(schema.paths[path], "options"); if (options == null) { continue; } alias = options.alias; } if (!alias) { continue; } const prop = schema.paths[path].path; if (Array.isArray(alias)) { for (const a of alias) { if (typeof a !== "string") { throw new Error("Invalid value for alias option on " + prop + ", got " + a); } schema.aliases[a] = prop; schema.virtual(a).get(/* @__PURE__ */ (function(p) { return function() { if (typeof this.get === "function") { return this.get(p); } return this[p]; }; })(prop)).set(/* @__PURE__ */ (function(p) { return function(v) { return this.$set(p, v); }; })(prop)); } continue; } if (typeof alias !== "string") { throw new Error("Invalid value for alias option on " + prop + ", got " + alias); } schema.aliases[alias] = prop; schema.virtual(alias).get(/* @__PURE__ */ (function(p) { return function() { if (typeof this.get === "function") { return this.get(p); } return this[p]; }; })(prop)).set(/* @__PURE__ */ (function(p) { return function(v) { return this.$set(p, v); }; })(prop)); } } Schema.prototype = Object.create(EventEmitter.prototype); Schema.prototype.constructor = Schema; Schema.prototype.instanceOfSchema = true; Object.defineProperty(Schema.prototype, "$schemaType", { configurable: false, enumerable: false, writable: true }); Object.defineProperty(Schema.prototype, "childSchemas", { configurable: false, enumerable: true, writable: true }); Object.defineProperty(Schema.prototype, "virtuals", { configurable: false, enumerable: true, writable: true }); Schema.prototype.obj; Schema.prototype.paths; Schema.prototype.tree; Schema.prototype.clone = function() { const s = this._clone(); s.on("init", (v) => this.emit("init", v)); return s; }; Schema.prototype._clone = function _clone(Constructor) { Constructor = Constructor || (this.base == null ? Schema : this.base.Schema); const s = new Constructor({}, this._userProvidedOptions); s.base = this.base; s.obj = this.obj; s.options = clone(this.options); s.callQueue = this.callQueue.map(function(f) { return f; }); s.methods = clone(this.methods); s.methodOptions = clone(this.methodOptions); s.statics = clone(this.statics); s.query = clone(this.query); s.plugins = Array.prototype.slice.call(this.plugins); s._indexes = clone(this._indexes); s._searchIndexes = clone(this._searchIndexes); s.s.hooks = this.s.hooks.clone(); s.tree = clone(this.tree); s.paths = Object.fromEntries( Object.entries(this.paths).map(([key, value]) => [key, value.clone()]) ); s.nested = clone(this.nested); s.subpaths = clone(this.subpaths); for (const schemaType of Object.values(s.paths)) { if (schemaType.$isSingleNested) { const path = schemaType.path; for (const key of Object.keys(schemaType.schema.paths)) { s.singleNestedPaths[path + "." + key] = schemaType.schema.paths[key]; } for (const key of Object.keys(schemaType.schema.singleNestedPaths)) { s.singleNestedPaths[path + "." + key] = schemaType.schema.singleNestedPaths[key]; } for (const key of Object.keys(schemaType.schema.subpaths)) { s.singleNestedPaths[path + "." + key] = schemaType.schema.subpaths[key]; } for (const key of Object.keys(schemaType.schema.nested)) { s.singleNestedPaths[path + "." + key] = "nested"; } } } s._gatherChildSchemas(); s.virtuals = clone(this.virtuals); s.$globalPluginsApplied = this.$globalPluginsApplied; s.$isRootDiscriminator = this.$isRootDiscriminator; s.$implicitlyCreated = this.$implicitlyCreated; s.$id = ++id; s.$originalSchemaId = this.$id; s.mapPaths = [].concat(this.mapPaths); if (this.discriminatorMapping != null) { s.discriminatorMapping = Object.assign({}, this.discriminatorMapping); } if (this.discriminators != null) { s.discriminators = Object.assign({}, this.discriminators); } if (this._applyDiscriminators != null) { s._applyDiscriminators = new Map(this._applyDiscriminators); } s.aliases = Object.assign({}, this.aliases); s.encryptedFields = clone(this.encryptedFields); return s; }; Schema.prototype.pick = function(paths, options) { const newSchema = new Schema({}, options || this.options); if (!Array.isArray(paths)) { throw new MongooseError('Schema#pick() only accepts an array argument, got "' + typeof paths + '"'); } for (const path of paths) { if (this._hasEncryptedField(path)) { const encrypt = this.encryptedFields[path]; const schemaType = this.path(path); newSchema.add({ [path]: { encrypt, [this.options.typeKey]: schemaType } }); } else if (this.nested[path]) { newSchema.add({ [path]: get(this.tree, path) }); } else { const schematype = this.path(path); if (schematype == null) { throw new MongooseError("Path `" + path + "` is not in the schema"); } newSchema.add({ [path]: schematype }); } } if (!this._hasEncryptedFields()) { newSchema.options.encryptionType = null; } return newSchema; }; Schema.prototype.omit = function(paths, options) { const newSchema = new Schema(this, options || this.options); if (!Array.isArray(paths)) { throw new MongooseError( 'Schema#omit() only accepts an array argument, got "' + typeof paths + '"' ); } newSchema.remove(paths); for (const nested in newSchema.singleNestedPaths) { if (paths.includes(nested)) { delete newSchema.singleNestedPaths[nested]; } } return newSchema; }; Schema.prototype.defaultOptions = function(options) { this._userProvidedOptions = options == null ? {} : clone(options); const baseOptions = this.base && this.base.options || {}; const strict = "strict" in baseOptions ? baseOptions.strict : true; const strictQuery = "strictQuery" in baseOptions ? baseOptions.strictQuery : false; const id2 = "id" in baseOptions ? baseOptions.id : true; options = { strict, strictQuery, bufferCommands: true, capped: false, // { size, max, autoIndexId } versionKey: "__v", optimisticConcurrency: false, minimize: true, autoIndex: null, discriminatorKey: "__t", shardKey: null, read: null, validateBeforeSave: true, validateModifiedOnly: false, // the following are only applied at construction time _id: true, id: id2, typeKey: "type", ...options }; if (options.versionKey && typeof options.versionKey !== "string") { throw new MongooseError("`versionKey` must be falsy or string, got `" + typeof options.versionKey + "`"); } if (typeof options.read === "string") { options.read = handleReadPreferenceAliases(options.read); } else if (Array.isArray(options.read) && typeof options.read[0] === "string") { options.read = { mode: handleReadPreferenceAliases(options.read[0]), tags: options.read[1] }; } if (options.optimisticConcurrency && !options.versionKey) { throw new MongooseError("Must set `versionKey` if using `optimisticConcurrency`"); } return options; }; Schema.prototype.discriminator = function(name, schema, options) { this._applyDiscriminators = this._applyDiscriminators || /* @__PURE__ */ new Map(); this._applyDiscriminators.set(name, { schema, options }); return this; }; Schema.prototype._defaultToObjectOptions = function(json) { const path = json ? "toJSON" : "toObject"; if (this._defaultToObjectOptionsMap && this._defaultToObjectOptionsMap[path]) { return this._defaultToObjectOptionsMap[path]; } const baseOptions = this.base && this.base.options && this.base.options[path] || {}; const schemaOptions = this.options[path] || {}; const defaultOptions = Object.assign({}, baseOptions, schemaOptions); this._defaultToObjectOptionsMap = this._defaultToObjectOptionsMap || {}; this._defaultToObjectOptionsMap[path] = defaultOptions; return defaultOptions; }; Schema.prototype.encryptionType = function encryptionType(encryptionType) { if (arguments.length === 0) { return this.options.encryptionType; } if (!(typeof encryptionType === "string" || encryptionType === null)) { throw new Error("invalid `encryptionType`: ${encryptionType}"); } this.options.encryptionType = encryptionType; }; Schema.prototype.add = function add(obj, prefix) { if (obj instanceof Schema || obj != null && obj.instanceOfSchema) { merge(this, obj); return this; } if (obj._id === false && prefix == null) { this.options._id = false; } prefix = prefix || ""; if (prefix === "__proto__." || prefix === "constructor." || prefix === "prototype.") { return this; } const keys = Object.keys(obj); const typeKey = this.options.typeKey; for (const key of keys) { if (utils.specialProperties.has(key)) { continue; } const fullPath = prefix + key; const val = obj[key]; if (val == null) { throw new TypeError("Invalid value for schema path `" + fullPath + '`, got value "' + val + '"'); } if (key === "_id" && val === false) { continue; } let isMongooseTypeString = false; if (typeof val === "string") { const MongooseTypes2 = this.base != null ? this.base.Schema.Types : Schema.Types; const upperVal = val.charAt(0).toUpperCase() + val.substring(1); isMongooseTypeString = MongooseTypes2[upperVal] != null; } if (key !== "_id" && (typeof val !== "object" && typeof val !== "function" && !isMongooseTypeString || val == null)) { throw new TypeError(`Invalid schema configuration: \`${val}\` is not a valid type at path \`${key}\`. See https://bit.ly/mongoose-schematypes for a list of valid schema types.`); } if (val instanceof VirtualType || (val.constructor && val.constructor.name || null) === "VirtualType") { this.virtual(val); continue; } if (Array.isArray(val) && val.length === 1 && val[0] == null) { throw new TypeError("Invalid value for schema Array path `" + fullPath + '`, got value "' + val[0] + '"'); } if (!(isPOJO(val) || val instanceof SchemaTypeOptions)) { if (prefix) { this.nested[prefix.substring(0, prefix.length - 1)] = true; } this.path(prefix + key, val); if (val[0] != null && !val[0].instanceOfSchema && utils.isPOJO(val[0].discriminators)) { const schemaType = this.path(prefix + key); for (const key2 in val[0].discriminators) { schemaType.discriminator(key2, val[0].discriminators[key2]); } } } else if (Object.keys(val).length < 1) { if (prefix) { this.nested[prefix.substring(0, prefix.length - 1)] = true; } this.path(fullPath, val); } else if (!val[typeKey] || typeKey === "type" && isPOJO(val.type) && val.type.type) { this.nested[fullPath] = true; this.add(val, fullPath + "."); } else { const _typeDef = val[typeKey]; if (isPOJO(_typeDef) && Object.keys(_typeDef).length > 0) { if (prefix) { this.nested[prefix.substring(0, prefix.length - 1)] = true; } const childSchemaOptions = {}; if (this._userProvidedOptions.typeKey) { childSchemaOptions.typeKey = this._userProvidedOptions.typeKey; } if (this._userProvidedOptions.strict != null) { childSchemaOptions.strict = this._userProvidedOptions.strict; } if (this._userProvidedOptions.toObject != null) { childSchemaOptions.toObject = utils.omit(this._userProvidedOptions.toObject, ["transform"]); } if (this._userProvidedOptions.toJSON != null) { childSchemaOptions.toJSON = utils.omit(this._userProvidedOptions.toJSON, ["transform"]); } const _schema = new Schema(_typeDef, childSchemaOptions); _schema.$implicitlyCreated = true; const schemaWrappedPath = Object.assign({}, val, { [typeKey]: _schema }); this.path(prefix + key, schemaWrappedPath); } else { if (prefix) { this.nested[prefix.substring(0, prefix.length - 1)] = true; } this.path(prefix + key, val); if (val != null && !val.instanceOfSchema && utils.isPOJO(val.discriminators)) { const schemaType = this.path(prefix + key); for (const key2 in val.discriminators) { schemaType.discriminator(key2, val.discriminators[key2]); } } } } if (val.instanceOfSchema && val.encryptionType() != null) { if (this.encryptionType() != val.encryptionType()) { throw new Error("encryptionType of a nested schema must match the encryption type of the parent schema."); } for (const [encryptedField, encryptedFieldConfig] of Object.entries(val.encryptedFields)) { const path = fullPath + "." + encryptedField; this._addEncryptedField(path, encryptedFieldConfig); } } else if (typeof val === "object" && "encrypt" in val) { const { encrypt } = val; if (this.encryptionType() == null) { throw new Error("encryptionType must be provided"); } this._addEncryptedField(fullPath, encrypt); } else { this._removeEncryptedField(fullPath); } } const aliasObj = Object.fromEntries( Object.entries(obj).map(([key]) => [prefix + key, null]) ); aliasFields(this, aliasObj); return this; }; Schema.prototype._addEncryptedField = function _addEncryptedField(path, fieldConfig) { const type = this.path(path).autoEncryptionType(); if (type == null) { throw new Error(`Invalid BSON type for FLE field: '${path}'`); } this.encryptedFields[path] = clone(fieldConfig); }; Schema.prototype._removeEncryptedField = function _removeEncryptedField(path) { delete this.encryptedFields[path]; }; Schema.prototype._hasEncryptedFields = function _hasEncryptedFields() { return Object.keys(this.encryptedFields).length > 0; }; Schema.prototype._hasEncryptedField = function _hasEncryptedField(path) { return path in this.encryptedFields; }; Schema.prototype._buildEncryptedFields = function() { const fields = Object.entries(this.encryptedFields).map( ([path, config]) => { const bsonType = this.path(path).autoEncryptionType(); return { path, bsonType, ...config }; } ); return { fields }; }; Schema.prototype._buildSchemaMap = function() { function buildNestedPath(path, object, value) { let i = 0, component = path[i]; for (; i < path.length - 1; ++i, component = path[i]) { object[component] = object[component] == null ? { bsonType: "object", properties: {} } : object[component]; object = object[component].properties; } object[component] = value; } const schemaMapPropertyReducer = (accum, [path, propertyConfig]) => { const bsonType = this.path(path).autoEncryptionType(); const pathComponents = path.split("."); const configuration = { encrypt: { ...propertyConfig, bsonType } }; buildNestedPath(pathComponents, accum, configuration); return accum; }; const properties = Object.entries(this.encryptedFields).reduce( schemaMapPropertyReducer, {} ); return { bsonType: "object", properties }; }; Schema.prototype.alias = function alias(path, alias) { aliasFields(this, { [path]: alias }); return this; }; Schema.prototype.removeIndex = function removeIndex(index) { if (arguments.length > 1) { throw new Error("removeIndex() takes only 1 argument"); } if (typeof index !== "object" && typeof index !== "string") { throw new Error("removeIndex() may only take either an object or a string as an argument"); } if (typeof index === "object") { for (let i = this._indexes.length - 1; i >= 0; --i) { if (isIndexSpecEqual(this._indexes[i][0], index)) { this._indexes.splice(i, 1); } } } else { for (let i = this._indexes.length - 1; i >= 0; --i) { if (this._indexes[i][1] != null && this._indexes[i][1].name === index) { this._indexes.splice(i, 1); } } } return this; }; Schema.prototype.clearIndexes = function clearIndexes() { this._indexes.length = 0; return this; }; Schema.prototype.searchIndex = function searchIndex(description) { this._searchIndexes.push(description); return this; }; Schema.reserved = /* @__PURE__ */ Object.create(null); Schema.prototype.reserved = Schema.reserved; var reserved = Schema.reserved; reserved["prototype"] = // EventEmitter reserved.emit = reserved.listeners = reserved.removeListener = // document properties and functions reserved.collection = reserved.errors = reserved.get = reserved.init = reserved.isModified = reserved.isNew = reserved.populated = reserved.remove = reserved.save = reserved.toObject = reserved.validate = 1; reserved.collection = 1; Schema.prototype.path = function(path, obj) { if (obj === void 0) { if (this.paths[path] != null) { return this.paths[path]; } const cleanPath = _pathToPositionalSyntax(path); let schematype = _getPath(this, path, cleanPath); if (schematype != null) { return schematype; } const mapPath = getMapPath(this, path); if (mapPath != null) { return mapPath; } schematype = this.hasMixedParent(cleanPath); if (schematype != null) { return schematype; } return hasNumericSubpathRegex.test(path) ? getPositionalPath(this, path, cleanPath) : void 0; } const firstPieceOfPath = path.split(".")[0]; if (reserved[firstPieceOfPath] && !this.options.suppressReservedKeysWarning) { const errorMessage = `\`${firstPieceOfPath}\` is a reserved schema pathname and may break some functionality. You are allowed to use it, but use at your own risk. To disable this warning pass \`suppressReservedKeysWarning\` as a schema option.`; utils.warn(errorMessage); } if (typeof obj === "object" && utils.hasUserDefinedProperty(obj, "ref")) { validateRef(obj.ref, path); } const subpaths = path.split(/\./); const last = subpaths.pop(); let branch = this.tree; let fullPath = ""; for (const sub of subpaths) { if (utils.specialProperties.has(sub)) { throw new Error("Cannot set special property `" + sub + "` on a schema"); } fullPath = fullPath += (fullPath.length > 0 ? "." : "") + sub; if (!branch[sub]) { this.nested[fullPath] = true; branch[sub] = {}; } if (typeof branch[sub] !== "object") { const msg = "Cannot set nested path `" + path + "`. Parent path `" + fullPath + "` already set to type " + branch[sub].name + "."; throw new Error(msg); } branch = branch[sub]; } branch[last] = clone(obj); this.paths[path] = this.interpretAsType(path, obj, this.options); const schemaType = this.paths[path]; this.childSchemas = this.childSchemas.filter((childSchema) => childSchema.path !== path); if (schemaType.$isSchemaMap) { const mapPath = path + ".$*"; this.paths[mapPath] = schemaType.$__schemaType; this.mapPaths.push(this.paths[mapPath]); if (schemaType.$__schemaType.$isSingleNested) { this.childSchemas.push({ schema: schemaType.$__schemaType.schema, model: schemaType.$__schemaType.caster, path }); } } if (schemaType.$isSingleNested) { for (const key of Object.keys(schemaType.schema.paths)) { this.singleNestedPaths[path + "." + key] = schemaType.schema.paths[key]; } for (const key of Object.keys(schemaType.schema.singleNestedPaths)) { this.singleNestedPaths[path + "." + key] = schemaType.schema.singleNestedPaths[key]; } for (const key of Object.keys(schemaType.schema.subpaths)) { this.singleNestedPaths[path + "." + key] = schemaType.schema.subpaths[key]; } for (const key of Object.keys(schemaType.schema.nested)) { this.singleNestedPaths[path + "." + key] = "nested"; } Object.defineProperty(schemaType.schema, "base", { configurable: true, enumerable: false, writable: false, value: this.base }); schemaType.caster.base = this.base; this.childSchemas.push({ schema: schemaType.schema, model: schemaType.caster, path }); } else if (schemaType.$isMongooseDocumentArray) { Object.defineProperty(schemaType.schema, "base", { configurable: true, enumerable: false, writable: false, value: this.base }); schemaType.casterConstructor.base = this.base; this.childSchemas.push({ schema: schemaType.schema, model: schemaType.casterConstructor, path }); } if (schemaType.$isMongooseArray && schemaType.caster instanceof SchemaType) { let arrayPath = path; let _schemaType = schemaType; const toAdd = []; while (_schemaType.$isMongooseArray) { arrayPath = arrayPath + ".$"; if (_schemaType.$isMongooseDocumentArray) { _schemaType.$embeddedSchemaType._arrayPath = arrayPath; _schemaType.$embeddedSchemaType._arrayParentPath = path; _schemaType = _schemaType.$embeddedSchemaType; } else { _schemaType.caster._arrayPath = arrayPath; _schemaType.caster._arrayParentPath = path; _schemaType = _schemaType.caster; } this.subpaths[arrayPath] = _schemaType; } for (const _schemaType2 of toAdd) { this.subpaths[_schemaType2.path] = _schemaType2; } } if (schemaType.$isMongooseDocumentArray) { for (const key of Object.keys(schemaType.schema.paths)) { const _schemaType = schemaType.schema.paths[key]; this.subpaths[path + "." + key] = _schemaType; if (typeof _schemaType === "object" && _schemaType != null && _schemaType.$parentSchemaDocArray == null) { _schemaType.$parentSchemaDocArray = schemaType; } } for (const key of Object.keys(schemaType.schema.subpaths)) { const _schemaType = schemaType.schema.subpaths[key]; this.subpaths[path + "." + key] = _schemaType; if (typeof _schemaType === "object" && _schemaType != null && _schemaType.$parentSchemaDocArray == null) { _schemaType.$parentSchemaDocArray = schemaType; } } for (const key of Object.keys(schemaType.schema.singleNestedPaths)) { const _schemaType = schemaType.schema.singleNestedPaths[key]; this.subpaths[path + "." + key] = _schemaType; if (typeof _schemaType === "object" && _schemaType != null && _schemaType.$parentSchemaDocArray == null) { _schemaType.$parentSchemaDocArray = schemaType; } } } return this; }; Schema.prototype._gatherChildSchemas = function _gatherChildSchemas() { const childSchemas = []; for (const path of Object.keys(this.paths)) { if (typeof path !== "string") { continue; } const schematype = this.paths[path]; if (schematype.$isMongooseDocumentArray || schematype.$isSingleNested) { childSchemas.push({ schema: schematype.schema, model: schematype.caster, path }); } else if (schematype.$isSchemaMap && schematype.$__schemaType.$isSingleNested) { childSchemas.push({ schema: schematype.$__schemaType.schema, model: schematype.$__schemaType.caster, path }); } } this.childSchemas = childSchemas; return childSchemas; }; function _getPath(schema, path, cleanPath) { if (schema.paths.hasOwnProperty(path)) { return schema.paths[path]; } if (schema.subpaths.hasOwnProperty(cleanPath)) { const subpath = schema.subpaths[cleanPath]; if (subpath === "nested") { return void 0; } return subpath; } if (schema.singleNestedPaths.hasOwnProperty(cleanPath) && typeof schema.singleNestedPaths[cleanPath] === "object") { const singleNestedPath = schema.singleNestedPaths[cleanPath]; if (singleNestedPath === "nested") { return void 0; } return singleNestedPath; } return null; } function _pathToPositionalSyntax(path) { if (!/\.\d+/.test(path)) { return path; } return path.replace(/\.\d+\./g, ".$.").replace(/\.\d+$/, ".$"); } function getMapPath(schema, path) { if (schema.mapPaths.length === 0) { return null; } for (const val of schema.mapPaths) { const cleanPath = val.path.replace(/\.\$\*/g, ""); if (path === cleanPath || path.startsWith(cleanPath + ".") && path.slice(cleanPath.length + 1).indexOf(".") === -1) { return val; } else if (val.schema && path.startsWith(cleanPath + ".")) { let remnant = path.slice(cleanPath.length + 1); remnant = remnant.slice(remnant.indexOf(".") + 1); return val.schema.paths[remnant]; } else if (val.$isSchemaMap && path.startsWith(cleanPath + ".")) { let remnant = path.slice(cleanPath.length + 1); remnant = remnant.slice(remnant.indexOf(".") + 1); const presplitPath = val.$__schemaType._presplitPath; if (remnant.indexOf(".") === -1 && presplitPath[presplitPath.length - 1] === "$*") { return val.$__schemaType; } else if (remnant.indexOf(".") !== -1 && val.$__schemaType.schema && presplitPath[presplitPath.length - 1] === "$*") { return val.$__schemaType.schema.path(remnant.slice(remnant.indexOf(".") + 1)); } } } return null; } Object.defineProperty(Schema.prototype, "base", { configurable: true, enumerable: false, writable: true, value: null }); Schema.prototype.interpretAsType = function(path, obj, options) { if (obj instanceof SchemaType) { if (obj.path === path) { return obj; } const clone2 = obj.clone(); clone2.path = path; return clone2; } const MongooseTypes2 = this.base != null ? this.base.Schema.Types : Schema.Types; const Types = this.base != null ? this.base.Types : require_types(); if (!utils.isPOJO(obj) && !(obj instanceof SchemaTypeOptions)) { const constructorName = utils.getFunctionName(obj.constructor); if (constructorName !== "Object") { const oldObj = obj; obj = {}; obj[options.typeKey] = oldObj; } } let type = obj[options.typeKey] && (obj[options.typeKey] instanceof Function || options.typeKey !== "type" || !obj.type.type) ? obj[options.typeKey] : {}; if (type instanceof SchemaType) { if (type.path === path) { return type; } const clone2 = type.clone(); clone2.path = path; return clone2; } let name; if (utils.isPOJO(type) || type === "mixed") { return new MongooseTypes2.Mixed(path, obj); } if (Array.isArray(type) || type === Array || type === "array" || type === MongooseTypes2.Array) { let cast = type === Array || type === "array" ? obj.cast || obj.of : type[0]; if (cast && cast.instanceOfSchema) { if (!(cast instanceof Schema)) { if (this.options._isMerging) { cast = new Schema(cast); } else { throw new TypeError("Schema for array path `" + path + `\` is from a different copy of the Mongoose module. Please make sure you're using the same version of Mongoose everywhere with \`npm list mongoose\`. If you are still getting this error, please add \`new Schema()\` around the path: ${path}: new Schema(...)`); } } return new MongooseTypes2.DocumentArray(path, cast, obj); } if (cast && cast[options.typeKey] && cast[options.typeKey].instanceOfSchema) { if (!(cast[options.typeKey] instanceof Schema)) { if (this.options._isMerging) { cast[options.typeKey] = new Schema(cast[options.typeKey]); } else { throw new TypeError("Schema for array path `" + path + `\` is from a different copy of the Mongoose module. Please make sure you're using the same version of Mongoose everywhere with \`npm list mongoose\`. If you are still getting this error, please add \`new Schema()\` around the path: ${path}: new Schema(...)`); } } return new MongooseTypes2.DocumentArray(path, cast[options.typeKey], obj, cast); } if (typeof cast !== "undefined") { if (Array.isArray(cast) || cast.type === Array || cast.type == "Array") { if (cast && cast.type == "Array") { cast.type = Array; } return new MongooseTypes2.Array(path, this.interpretAsType(path, cast, options), obj); } } const castFromTypeKey = cast != null && cast[options.typeKey] && (options.typeKey !== "type" || !cast.type.type) ? cast[options.typeKey] : cast; if (typeof cast === "string") { cast = MongooseTypes2[cast.charAt(0).toUpperCase() + cast.substring(1)]; } else if (utils.isPOJO(castFromTypeKey)) { if (Object.keys(castFromTypeKey).length) { const childSchemaOptions = { minimize: options.minimize }; if (options.typeKey) { childSchemaOptions.typeKey = options.typeKey; } if (options.hasOwnProperty("strict")) { childSchemaOptions.strict = options.strict; } if (options.hasOwnProperty("strictQuery")) { childSchemaOptions.strictQuery = options.strictQuery; } if (options.hasOwnProperty("toObject")) { childSchemaOptions.toObject = utils.omit(options.toObject, ["transform"]); } if (options.hasOwnProperty("toJSON")) { childSchemaOptions.toJSON = utils.omit(options.toJSON, ["transform"]); } if (this._userProvidedOptions.hasOwnProperty("_id")) { childSchemaOptions._id = this._userProvidedOptions._id; } else if (Schema.Types.DocumentArray.defaultOptions._id != null) { childSchemaOptions._id = Schema.Types.DocumentArray.defaultOptions._id; } const childSchema = new Schema(castFromTypeKey, childSchemaOptions); childSchema.$implicitlyCreated = true; return new MongooseTypes2.DocumentArray(path, childSchema, obj); } else { return new MongooseTypes2.Array(path, MongooseTypes2.Mixed, obj); } } if (cast) { type = cast[options.typeKey] && (options.typeKey !== "type" || !cast.type.type) ? cast[options.typeKey] : cast; if (Array.isArray(type)) { return new MongooseTypes2.Array(path, this.interpretAsType(path, type, options), obj); } name = typeof type === "string" ? type : type.schemaName || utils.getFunctionName(type); if (name === "ClockDate") { name = "Date"; } if (name === void 0) { throw new TypeError(`Invalid schema configuration: Could not determine the embedded type for array \`${path}\`. See https://mongoosejs.com/docs/guide.html#definition for more info on supported schema syntaxes.`); } if (!MongooseTypes2.hasOwnProperty(name)) { throw new TypeError(`Invalid schema configuration: \`${name}\` is not a valid type within the array \`${path}\`.See https://bit.ly/mongoose-schematypes for a list of valid schema types.`); } } return new MongooseTypes2.Array(path, cast || MongooseTypes2.Mixed, obj, options); } if (type && type.instanceOfSchema) { return new MongooseTypes2.Subdocument(type, path, obj); } if (Buffer.isBuffer(type)) { name = "Buffer"; } else if (typeof type === "function" || typeof type === "object") { name = type.schemaName || utils.getFunctionName(type); } else if (type === Types.ObjectId) { name = "ObjectId"; } else if (type === Types.Decimal128) { name = "Decimal128"; } else { name = type == null ? "" + type : type.toString(); } if (name) { name = name.charAt(0).toUpperCase() + name.substring(1); } if (name === "ObjectID") { name = "ObjectId"; } if (name === "ClockDate") { name = "Date"; } if (name === void 0) { throw new TypeError(`Invalid schema configuration: \`${path}\` schematype definition is invalid. See https://mongoosejs.com/docs/guide.html#definition for more info on supported schema syntaxes.`); } if (MongooseTypes2[name] == null) { throw new TypeError(`Invalid schema configuration: \`${name}\` is not a valid type at path \`${path}\`. See https://bit.ly/mongoose-schematypes for a list of valid schema types.`); } if (name === "Union") { obj.parentSchema = this; } const schemaType = new MongooseTypes2[name](path, obj, options); if (schemaType.$isSchemaMap) { createMapNestedSchemaType(this, schemaType, path, obj, options); } return schemaType; }; function createMapNestedSchemaType(schema, schemaType, path, obj, options) { const mapPath = path + ".$*"; let _mapType = { type: {} }; if (utils.hasUserDefinedProperty(obj, "of")) { const isInlineSchema = utils.isPOJO(obj.of) && Object.keys(obj.of).length > 0 && !utils.hasUserDefinedProperty(obj.of, schema.options.typeKey); if (isInlineSchema) { _mapType = { [schema.options.typeKey]: new Schema(obj.of) }; } else if (utils.isPOJO(obj.of)) { _mapType = Object.assign({}, obj.of); } else { _mapType = { [schema.options.typeKey]: obj.of }; } if (_mapType[schema.options.typeKey] && _mapType[schema.options.typeKey].instanceOfSchema) { const subdocumentSchema = _mapType[schema.options.typeKey]; subdocumentSchema.eachPath((subpath, type) => { if (type.options.select === true || type.options.select === false) { throw new MongooseError('Cannot use schema-level projections (`select: true` or `select: false`) within maps at path "' + path + "." + subpath + '"'); } }); } if (utils.hasUserDefinedProperty(obj, "ref")) { _mapType.ref = obj.ref; } } schemaType.$__schemaType = schema.interpretAsType(mapPath, _mapType, options); } Schema.prototype.eachPath = function(fn) { const keys = Object.keys(this.paths); const len = keys.length; for (let i = 0; i < len; ++i) { fn(keys[i], this.paths[keys[i]]); } return this; }; Schema.prototype.requiredPaths = function requiredPaths(invalidate) { if (this._requiredpaths && !invalidate) { return this._requiredpaths; } const paths = Object.keys(this.paths); let i = paths.length; const ret = []; while (i--) { const path = paths[i]; if (this.paths[path].isRequired) { ret.push(path); } } this._requiredpaths = ret; return this._requiredpaths; }; Schema.prototype.indexedPaths = function indexedPaths() { if (this._indexedpaths) { return this._indexedpaths; } this._indexedpaths = this.indexes(); return this._indexedpaths; }; Schema.prototype.pathType = function(path) { if (this.paths.hasOwnProperty(path)) { return "real"; } if (this.virtuals.hasOwnProperty(path)) { return "virtual"; } if (this.nested.hasOwnProperty(path)) { return "nested"; } const cleanPath = _pathToPositionalSyntax(path); if (this.subpaths.hasOwnProperty(cleanPath) || this.subpaths.hasOwnProperty(path)) { return "real"; } const singleNestedPath = this.singleNestedPaths.hasOwnProperty(cleanPath) || this.singleNestedPaths.hasOwnProperty(path); if (singleNestedPath) { return singleNestedPath === "nested" ? "nested" : "real"; } const mapPath = getMapPath(this, path); if (mapPath != null) { return "real"; } if (/\.\d+\.|\.\d+$/.test(path)) { return getPositionalPathType(this, path, cleanPath); } return "adhocOrUndefined"; }; Schema.prototype.hasMixedParent = function(path) { const subpaths = path.split(/\./g); path = ""; for (let i = 0; i < subpaths.length; ++i) { path = i > 0 ? path + "." + subpaths[i] : subpaths[i]; if (this.paths.hasOwnProperty(path) && this.paths[path] instanceof MongooseTypes.Mixed) { return this.paths[path]; } } return null; }; Schema.prototype.setupTimestamp = function(timestamps) { return setupTimestamps(this, timestamps); }; function getPositionalPathType(self2, path, cleanPath) { const subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean); if (subpaths.length < 2) { return self2.paths.hasOwnProperty(subpaths[0]) ? self2.paths[subpaths[0]] : "adhocOrUndefined"; } let val = self2.path(subpaths[0]); let isNested = false; if (!val) { return "adhocOrUndefined"; } const last = subpaths.length - 1; for (let i = 1; i < subpaths.length; ++i) { isNested = false; const subpath = subpaths[i]; if (i === last && val && !/\D/.test(subpath)) { if (val.$isMongooseDocumentArray) { val = val.$embeddedSchemaType; } else if (val instanceof MongooseTypes.Array) { val = val.caster; } else { val = void 0; } break; } if (!/\D/.test(subpath)) { if (val instanceof MongooseTypes.Array && i !== last) { val = val.caster; } continue; } if (!(val && val.schema)) { val = void 0; break; } const type = val.schema.pathType(subpath); isNested = type === "nested"; val = val.schema.path(subpath); } self2.subpaths[cleanPath] = val; if (val) { return "real"; } if (isNested) { return "nested"; } return "adhocOrUndefined"; } function getPositionalPath(self2, path, cleanPath) { getPositionalPathType(self2, path, cleanPath); return self2.subpaths[cleanPath]; } Schema.prototype.queue = function(name, args) { this.callQueue.push([name, args]); return this; }; Schema.prototype.pre = function(name) { if (name instanceof RegExp) { const remainingArgs = Array.prototype.slice.call(arguments, 1); for (const fn of hookNames) { if (name.test(fn)) { this.pre.apply(this, [fn].concat(remainingArgs)); } } return this; } if (Array.isArray(name)) { const remainingArgs = Array.prototype.slice.call(arguments, 1); for (const el of name) { this.pre.apply(this, [el].concat(remainingArgs)); } return this; } this.s.hooks.pre.apply(this.s.hooks, arguments); return this; }; Schema.prototype.post = function(name) { if (name instanceof RegExp) { const remainingArgs = Array.prototype.slice.call(arguments, 1); for (const fn of hookNames) { if (name.test(fn)) { this.post.apply(this, [fn].concat(remainingArgs)); } } return this; } if (Array.isArray(name)) { const remainingArgs = Array.prototype.slice.call(arguments, 1); for (const el of name) { this.post.apply(this, [el].concat(remainingArgs)); } return this; } this.s.hooks.post.apply(this.s.hooks, arguments); return this; }; Schema.prototype.plugin = function(fn, opts) { if (typeof fn !== "function") { throw new Error('First param to `schema.plugin()` must be a function, got "' + typeof fn + '"'); } if (opts && opts.deduplicate) { for (const plugin of this.plugins) { if (plugin.fn === fn) { return this; } } } this.plugins.push({ fn, opts }); fn(this, opts); return this; }; Schema.prototype.method = function(name, fn, options) { if (typeof name !== "string") { for (const i in name) { this.methods[i] = name[i]; this.methodOptions[i] = clone(options); } } else { this.methods[name] = fn; this.methodOptions[name] = clone(options); } return this; }; Schema.prototype.static = function(name, fn) { if (typeof name !== "string") { for (const i in name) { this.statics[i] = name[i]; } } else { this.statics[name] = fn; } return this; }; Schema.prototype.index = function(fields, options) { fields || (fields = {}); options || (options = {}); if (options.expires) { utils.expires(options); } for (const key in fields) { if (this.aliases[key]) { fields = utils.renameObjKey(fields, key, this.aliases[key]); } } for (const field of Object.keys(fields)) { if (fields[field] === "ascending" || fields[field] === "asc") { fields[field] = 1; } else if (fields[field] === "descending" || fields[field] === "desc") { fields[field] = -1; } } for (const existingIndex of this.indexes()) { if (options.name == null && existingIndex[1].name == null && isIndexSpecEqual(existingIndex[0], fields)) { utils.warn(`Duplicate schema index on ${JSON.stringify(fields)} found. This is often due to declaring an index using both "index: true" and "schema.index()". Please remove the duplicate index definition.`); } } this._indexes.push([fields, options]); return this; }; Schema.prototype.set = function(key, value, tags) { if (arguments.length === 1) { return this.options[key]; } switch (key) { case "read": if (typeof value === "string") { this.options[key] = { mode: handleReadPreferenceAliases(value), tags }; } else if (Array.isArray(value) && typeof value[0] === "string") { this.options[key] = { mode: handleReadPreferenceAliases(value[0]), tags: value[1] }; } else { this.options[key] = value; } this._userProvidedOptions[key] = this.options[key]; break; case "timestamps": this.setupTimestamp(value); this.options[key] = value; this._userProvidedOptions[key] = this.options[key]; break; case "_id": this.options[key] = value; this._userProvidedOptions[key] = this.options[key]; if (value && !this.paths["_id"]) { addAutoId(this); } else if (!value && this.paths["_id"] != null && this.paths["_id"].auto) { this.remove("_id"); } break; default: this.options[key] = value; this._userProvidedOptions[key] = this.options[key]; break; } if (key === "strict") { _propagateOptionsToImplicitlyCreatedSchemas(this, { strict: value }); } if (key === "strictQuery") { _propagateOptionsToImplicitlyCreatedSchemas(this, { strictQuery: value }); } if (key === "toObject") { value = { ...value }; delete value.transform; _propagateOptionsToImplicitlyCreatedSchemas(this, { toObject: value }); } if (key === "toJSON") { value = { ...value }; delete value.transform; _propagateOptionsToImplicitlyCreatedSchemas(this, { toJSON: value }); } return this; }; function _propagateOptionsToImplicitlyCreatedSchemas(baseSchema, options) { for (const { schema } of baseSchema.childSchemas) { if (!schema.$implicitlyCreated) { continue; } Object.assign(schema.options, options); _propagateOptionsToImplicitlyCreatedSchemas(schema, options); } } Schema.prototype.get = function(key) { return this.options[key]; }; var indexTypes = "2d 2dsphere hashed text".split(" "); Object.defineProperty(Schema, "indexTypes", { get: function() { return indexTypes; }, set: function() { throw new Error("Cannot overwrite Schema.indexTypes"); } }); Schema.prototype.indexes = function() { return getIndexes(this); }; Schema.prototype.virtual = function(name, options) { if (name instanceof VirtualType || getConstructorName(name) === "VirtualType") { return this.virtual(name.path, name.options); } options = new VirtualOptions(options); if (utils.hasUserDefinedProperty(options, ["ref", "refPath"])) { if (options.localField == null) { throw new Error("Reference virtuals require `localField` option"); } if (options.foreignField == null) { throw new Error("Reference virtuals require `foreignField` option"); } const virtual = this.virtual(name); virtual.options = options; this.pre("init", function virtualPreInit(obj, opts) { if (mpath.has(name, obj)) { const _v = mpath.get(name, obj); if (!this.$$populatedVirtuals) { this.$$populatedVirtuals = {}; } if (options.justOne || options.count) { this.$$populatedVirtuals[name] = Array.isArray(_v) ? _v[0] : _v; } else { this.$$populatedVirtuals[name] = Array.isArray(_v) ? _v : _v == null ? [] : [_v]; } if (opts?.hydratedPopulatedDocs && !options.count) { const modelNames = virtual._getModelNamesForPopulate(this); const populatedVal = this.$$populatedVirtuals[name]; if (!Array.isArray(populatedVal) && !populatedVal.$__ && modelNames?.length === 1) { const PopulateModel = this.db.model(modelNames[0]); this.$$populatedVirtuals[name] = PopulateModel.hydrate(populatedVal); } else if (Array.isArray(populatedVal) && modelNames?.length === 1) { const PopulateModel = this.db.model(modelNames[0]); for (let i = 0; i < populatedVal.length; ++i) { if (!populatedVal[i].$__) { populatedVal[i] = PopulateModel.hydrate(populatedVal[i], null, { hydratedPopulatedDocs: true }); } } const foreignField = options.foreignField; this.$populated( name, populatedVal.map((doc) => doc == null ? doc : doc.get(typeof foreignField === "function" ? foreignField.call(doc, doc) : foreignField)), { populateModelSymbol: PopulateModel } ); } } mpath.unset(name, obj); } }); virtual.set(function(v) { if (!this.$$populatedVirtuals) { this.$$populatedVirtuals = {}; } return setPopulatedVirtualValue( this.$$populatedVirtuals, name, v, options ); }); if (typeof options.get === "function") { virtual.get(options.get); } const parts2 = name.split("."); let cur = parts2[0]; for (let i = 0; i < parts2.length - 1; ++i) { if (this.paths[cur] == null) { continue; } if (this.paths[cur].$isMongooseDocumentArray || this.paths[cur].$isSingleNested) { const remnant = parts2.slice(i + 1).join("."); this.paths[cur].schema.virtual(remnant, options); break; } else if (this.paths[cur].$isSchemaMap) { const remnant = parts2.slice(i + 2).join("."); this.paths[cur].$__schemaType.schema.virtual(remnant, options); break; } cur += "." + parts2[i + 1]; } return virtual; } const virtuals = this.virtuals; const parts = name.split("."); if (this.pathType(name) === "real") { throw new Error('Virtual path "' + name + '" conflicts with a real path in the schema'); } virtuals[name] = parts.reduce(function(mem, part, i) { mem[part] || (mem[part] = i === parts.length - 1 ? new VirtualType(options, name) : {}); return mem[part]; }, this.tree); if (options && options.applyToArray && parts.length > 1) { const path = this.path(parts.slice(0, -1).join(".")); if (path && path.$isMongooseArray) { return path.virtual(parts[parts.length - 1], options); } else { throw new MongooseError(`Path "${path}" is not an array`); } } return virtuals[name]; }; Schema.prototype.virtualpath = function(name) { return this.virtuals.hasOwnProperty(name) ? this.virtuals[name] : null; }; Schema.prototype.remove = function(path) { if (typeof path === "string") { path = [path]; } if (Array.isArray(path)) { path.forEach(function(name) { if (this.path(name) == null && !this.nested[name]) { return; } if (this.nested[name]) { const allKeys = Object.keys(this.paths).concat(Object.keys(this.nested)); for (const path2 of allKeys) { if (path2.startsWith(name + ".")) { delete this.paths[path2]; delete this.nested[path2]; _deletePath(this, path2); } } delete this.nested[name]; _deletePath(this, name); return; } delete this.paths[name]; _deletePath(this, name); this._removeEncryptedField(name); }, this); } return this; }; function _deletePath(schema, name) { const pieces = name.split("."); const last = pieces.pop(); let branch = schema.tree; for (const piece of pieces) { branch = branch[piece]; } delete branch[last]; } Schema.prototype.removeVirtual = function(path) { if (typeof path === "string") { path = [path]; } if (Array.isArray(path)) { for (const virtual of path) { if (this.virtuals[virtual] == null) { throw new MongooseError(`Attempting to remove virtual "${virtual}" that does not exist.`); } } for (const virtual of path) { delete this.paths[virtual]; delete this.virtuals[virtual]; if (virtual.indexOf(".") !== -1) { mpath.unset(virtual, this.tree); } else { delete this.tree[virtual]; } } } return this; }; Schema.prototype.loadClass = function(model, virtualsOnly) { if (model === Object.prototype || model === Function.prototype || model.prototype.hasOwnProperty("$isMongooseModelPrototype") || model.prototype.hasOwnProperty("$isMongooseDocumentPrototype")) { return this; } this.loadClass(Object.getPrototypeOf(model), virtualsOnly); if (!virtualsOnly) { Object.getOwnPropertyNames(model).forEach(function(name) { if (name.match(/^(length|name|prototype|constructor|__proto__)$/)) { return; } const prop = Object.getOwnPropertyDescriptor(model, name); if (prop.hasOwnProperty("value")) { this.static(name, prop.value); } }, this); } Object.getOwnPropertyNames(model.prototype).forEach(function(name) { if (name.match(/^(constructor)$/)) { return; } const method = Object.getOwnPropertyDescriptor(model.prototype, name); if (!virtualsOnly) { if (typeof method.value === "function") { this.method(name, method.value); } } if (typeof method.get === "function") { if (this.virtuals[name]) { this.virtuals[name].getters = []; } this.virtual(name).get(method.get); } if (typeof method.set === "function") { if (this.virtuals[name]) { this.virtuals[name].setters = []; } this.virtual(name).set(method.set); } }, this); return this; }; Schema.prototype._getSchema = function(path) { const _this = this; const pathschema = _this.path(path); const resultPath = []; if (pathschema) { pathschema.$fullPath = path; return pathschema; } function search(parts2, schema) { let p = parts2.length + 1; let foundschema; let trypath; while (p--) { trypath = parts2.slice(0, p).join("."); foundschema = schema.path(trypath); if (foundschema) { resultPath.push(trypath); if (foundschema.caster) { if (foundschema.caster instanceof MongooseTypes.Mixed) { foundschema.caster.$fullPath = resultPath.join("."); return foundschema.caster; } if (p !== parts2.length) { if (p + 1 === parts2.length && foundschema.$embeddedSchemaType && (parts2[p] === "$" || isArrayFilter(parts2[p]))) { return foundschema.$embeddedSchemaType; } if (foundschema.schema) { let ret; if (parts2[p] === "$" || isArrayFilter(parts2[p])) { if (p + 1 === parts2.length) { return foundschema.$embeddedSchemaType; } ret = search(parts2.slice(p + 1), foundschema.schema); if (ret) { ret.$parentSchemaDocArray = ret.$parentSchemaDocArray || (foundschema.schema.$isSingleNested ? null : foundschema); } return ret; } ret = search(parts2.slice(p), foundschema.schema); if (ret) { ret.$parentSchemaDocArray = ret.$parentSchemaDocArray || (foundschema.schema.$isSingleNested ? null : foundschema); } return ret; } } } else if (foundschema.$isSchemaMap) { if (p >= parts2.length) { return foundschema; } if (p + 1 >= parts2.length) { return foundschema.$__schemaType; } if (foundschema.$__schemaType instanceof MongooseTypes.Mixed) { return foundschema.$__schemaType; } if (foundschema.$__schemaType.schema != null) { const ret = search(parts2.slice(p + 1), foundschema.$__schemaType.schema); return ret; } } foundschema.$fullPath = resultPath.join("."); return foundschema; } } } const parts = path.split("."); for (let i = 0; i < parts.length; ++i) { if (parts[i] === "$" || isArrayFilter(parts[i])) { parts[i] = "0"; } if (numberRE.test(parts[i])) { parts[i] = "$"; } } return search(parts, _this); }; Schema.prototype._getPathType = function(path) { const _this = this; const pathschema = _this.path(path); if (pathschema) { return "real"; } function search(parts, schema) { let p = parts.length + 1, foundschema, trypath; while (p--) { trypath = parts.slice(0, p).join("."); foundschema = schema.path(trypath); if (foundschema) { if (foundschema.caster) { if (foundschema.caster instanceof MongooseTypes.Mixed) { return { schema: foundschema, pathType: "mixed" }; } if (p !== parts.length && foundschema.schema) { if (parts[p] === "$" || isArrayFilter(parts[p])) { if (p === parts.length - 1) { return { schema: foundschema, pathType: "nested" }; } return search(parts.slice(p + 1), foundschema.schema); } return search(parts.slice(p), foundschema.schema); } return { schema: foundschema, pathType: foundschema.$isSingleNested ? "nested" : "array" }; } return { schema: foundschema, pathType: "real" }; } else if (p === parts.length && schema.nested[trypath]) { return { schema, pathType: "nested" }; } } return { schema: foundschema || schema, pathType: "undefined" }; } return search(path.split("."), _this); }; Schema.prototype._transformDuplicateKeyError = function _transformDuplicateKeyError(error) { if (!this._duplicateKeyErrorMessagesByPath) { return error; } if (error.code !== 11e3 && error.code !== 11001) { return error; } if (error.keyPattern != null) { const keyPattern = error.keyPattern; const keys = Object.keys(keyPattern); if (keys.length !== 1) { return error; } const firstKey = keys[0]; if (!this._duplicateKeyErrorMessagesByPath.hasOwnProperty(firstKey)) { return error; } return new MongooseError(this._duplicateKeyErrorMessagesByPath[firstKey], { cause: error }); } return error; }; function isArrayFilter(piece) { return piece.startsWith("$[") && piece.endsWith("]"); } Schema.prototype._preCompile = function _preCompile() { this.plugin(idGetter, { deduplicate: true }); }; Schema.prototype.toJSONSchema = function toJSONSchema(options) { const useBsonType = options?.useBsonType ?? false; const result = useBsonType ? { required: [], properties: {} } : { type: "object", required: [], properties: {} }; for (const path of Object.keys(this.paths)) { const schemaType = this.paths[path]; if (schemaType._presplitPath.indexOf("$*") !== -1) { continue; } const isNested = schemaType._presplitPath.length > 1; let jsonSchemaForPath = result; if (isNested) { for (let i = 0; i < schemaType._presplitPath.length - 1; ++i) { const subpath = schemaType._presplitPath[i]; if (jsonSchemaForPath.properties[subpath] == null) { jsonSchemaForPath.properties[subpath] = useBsonType ? { bsonType: ["object", "null"], properties: {} } : { type: ["object", "null"], properties: {} }; } jsonSchemaForPath = jsonSchemaForPath.properties[subpath]; } } const lastSubpath = schemaType._presplitPath[schemaType._presplitPath.length - 1]; let isRequired = false; if (path === "_id") { if (!jsonSchemaForPath.required) { jsonSchemaForPath.required = []; } jsonSchemaForPath.required.push("_id"); isRequired = true; } else if (schemaType.options.required && typeof schemaType.options.required !== "function") { if (!jsonSchemaForPath.required) { jsonSchemaForPath.required = []; } jsonSchemaForPath.required.push(lastSubpath); isRequired = true; } jsonSchemaForPath.properties[lastSubpath] = schemaType.toJSONSchema(options); if (schemaType.options.enum) { jsonSchemaForPath.properties[lastSubpath].enum = isRequired ? schemaType.options.enum : [...schemaType.options.enum, null]; } } if (result.required.length === 0) { delete result.required; } return result; }; module2.exports = exports2 = Schema; Schema.Types = MongooseTypes = require_schema(); exports2.ObjectId = MongooseTypes.ObjectId; } }); // netlify/functions/node_modules/mongoose/lib/error/bulkWriteError.js var require_bulkWriteError = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/bulkWriteError.js"(exports2, module2) { "use strict"; var MongooseError = require_error2(); var MongooseBulkWriteError = class extends MongooseError { constructor(validationErrors, results, rawResult, operation) { let preview = validationErrors.map((e) => e.message).join(", "); if (preview.length > 200) { preview = preview.slice(0, 200) + "..."; } super(`${operation} failed with ${validationErrors.length} Mongoose validation errors: ${preview}`); this.validationErrors = validationErrors; this.results = results; this.rawResult = rawResult; this.operation = operation; } }; Object.defineProperty(MongooseBulkWriteError.prototype, "name", { value: "MongooseBulkWriteError" }); module2.exports = MongooseBulkWriteError; } }); // netlify/functions/node_modules/mongoose/lib/error/syncIndexes.js var require_syncIndexes = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/syncIndexes.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var SyncIndexesError = class extends MongooseError { constructor(message, errorsMap) { super(message); this.errors = errorsMap; } }; Object.defineProperty(SyncIndexesError.prototype, "name", { value: "SyncIndexesError" }); module2.exports = SyncIndexesError; } }); // netlify/functions/node_modules/mongoose/lib/helpers/schema/applyPlugins.js var require_applyPlugins = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/schema/applyPlugins.js"(exports2, module2) { "use strict"; module2.exports = function applyPlugins(schema, plugins, options, cacheKey) { if (schema[cacheKey]) { return; } schema[cacheKey] = true; if (!options || !options.skipTopLevel) { let pluginTags = null; for (const plugin of plugins) { const tags = plugin[1] == null ? null : plugin[1].tags; if (!Array.isArray(tags)) { schema.plugin(plugin[0], plugin[1]); continue; } pluginTags = pluginTags || new Set(schema.options.pluginTags || []); if (!tags.find((tag) => pluginTags.has(tag))) { continue; } schema.plugin(plugin[0], plugin[1]); } } options = Object.assign({}, options); delete options.skipTopLevel; if (options.applyPluginsToChildSchemas !== false) { for (const path of Object.keys(schema.paths)) { const type = schema.paths[path]; if (type.schema != null) { applyPlugins(type.schema, plugins, options, cacheKey); type.caster.prototype.$__setSchema(type.schema); } } } const discriminators = schema.discriminators; if (discriminators == null) { return; } const applyPluginsToDiscriminators = options.applyPluginsToDiscriminators; const keys = Object.keys(discriminators); for (const discriminatorKey of keys) { const discriminatorSchema = discriminators[discriminatorKey]; applyPlugins( discriminatorSchema, plugins, { skipTopLevel: !applyPluginsToDiscriminators }, cacheKey ); } }; } }); // netlify/functions/node_modules/mongoose/lib/driver.js var require_driver = __commonJS({ "netlify/functions/node_modules/mongoose/lib/driver.js"(exports2, module2) { "use strict"; var driver = null; module2.exports.get = function() { return driver; }; module2.exports.set = function(v) { driver = v; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/getDefaultBulkwriteResult.js var require_getDefaultBulkwriteResult = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/getDefaultBulkwriteResult.js"(exports2, module2) { "use strict"; function getDefaultBulkwriteResult() { return { ok: 1, nInserted: 0, nUpserted: 0, nMatched: 0, nModified: 0, nRemoved: 0, upserted: [], writeErrors: [], insertedIds: [], writeConcernErrors: [] }; } module2.exports = getDefaultBulkwriteResult; } }); // netlify/functions/node_modules/mongoose/lib/error/createCollectionsError.js var require_createCollectionsError = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/createCollectionsError.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var CreateCollectionsError = class extends MongooseError { constructor(message, errorsMap) { super(message); this.errors = errorsMap; } }; Object.defineProperty(CreateCollectionsError.prototype, "name", { value: "CreateCollectionsError" }); module2.exports = CreateCollectionsError; } }); // netlify/functions/node_modules/mongoose/lib/helpers/update/modifiedPaths.js var require_modifiedPaths = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/update/modifiedPaths.js"(exports2, module2) { "use strict"; var _modifiedPaths = require_common3().modifiedPaths; module2.exports = function modifiedPaths(update) { const keys = Object.keys(update); const res = {}; const withoutDollarKeys = {}; for (const key of keys) { if (key.startsWith("$")) { _modifiedPaths(update[key], "", res); continue; } withoutDollarKeys[key] = update[key]; } _modifiedPaths(withoutDollarKeys, "", res); return res; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/update/updatedPathsByArrayFilter.js var require_updatedPathsByArrayFilter = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/update/updatedPathsByArrayFilter.js"(exports2, module2) { "use strict"; var modifiedPaths = require_modifiedPaths(); module2.exports = function updatedPathsByArrayFilter(update) { if (update == null) { return {}; } const updatedPaths = modifiedPaths(update); return Object.keys(updatedPaths).reduce((cur, path) => { const matches = path.match(/\$\[[^\]]+\]/g); if (matches == null) { return cur; } for (const match of matches) { const firstMatch = path.indexOf(match); if (firstMatch !== path.lastIndexOf(match)) { throw new Error(`Path '${path}' contains the same array filter multiple times`); } cur[match.substring(2, match.length - 1)] = path.substring(0, firstMatch - 1).replace(/\$\[[^\]]+\]/g, "0"); } return cur; }, {}); }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/query/getEmbeddedDiscriminatorPath.js var require_getEmbeddedDiscriminatorPath2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/query/getEmbeddedDiscriminatorPath.js"(exports2, module2) { "use strict"; var cleanPositionalOperators = require_cleanPositionalOperators(); var get = require_get(); var getDiscriminatorByValue = require_getDiscriminatorByValue(); var updatedPathsByArrayFilter = require_updatedPathsByArrayFilter(); module2.exports = function getEmbeddedDiscriminatorPath(schema, update, filter, path, options) { const parts = path.indexOf(".") === -1 ? [path] : path.split("."); let schematype = null; let type = "adhocOrUndefined"; filter = filter || {}; update = update || {}; const arrayFilters = options != null && Array.isArray(options.arrayFilters) ? options.arrayFilters : []; const updatedPathsByFilter = updatedPathsByArrayFilter(update); let startIndex = 0; for (let i = 0; i < parts.length; ++i) { const originalSubpath = parts.slice(startIndex, i + 1).join("."); const subpath = cleanPositionalOperators(originalSubpath); schematype = schema.path(subpath); if (schematype == null) { continue; } type = schema.pathType(subpath); if ((schematype.$isSingleNested || schematype.$isMongooseDocumentArrayElement) && schematype.schema.discriminators != null) { const key = get(schematype, "schema.options.discriminatorKey"); const discriminatorValuePath = subpath + "." + key; const discriminatorFilterPath = discriminatorValuePath.replace(/\.\d+\./, "."); let discriminatorKey = null; if (discriminatorValuePath in filter) { discriminatorKey = filter[discriminatorValuePath]; } if (discriminatorFilterPath in filter) { discriminatorKey = filter[discriminatorFilterPath]; } const wrapperPath = subpath.replace(/\.\d+$/, ""); if (schematype.$isMongooseDocumentArrayElement && get(filter[wrapperPath], "$elemMatch." + key) != null) { discriminatorKey = filter[wrapperPath].$elemMatch[key]; } const discriminatorKeyUpdatePath = originalSubpath + "." + key; if (discriminatorKeyUpdatePath in update) { discriminatorKey = update[discriminatorKeyUpdatePath]; } if (discriminatorValuePath in update) { discriminatorKey = update[discriminatorValuePath]; } for (const filterKey of Object.keys(updatedPathsByFilter)) { const schemaKey = updatedPathsByFilter[filterKey] + "." + key; const arrayFilterKey = filterKey + "." + key; if (schemaKey === discriminatorFilterPath) { const filter2 = arrayFilters.find((filter3) => filter3.hasOwnProperty(arrayFilterKey)); if (filter2 != null) { discriminatorKey = filter2[arrayFilterKey]; } } } if (discriminatorKey == null) { continue; } const discriminator = getDiscriminatorByValue(schematype.caster.discriminators, discriminatorKey); const discriminatorSchema = discriminator && discriminator.schema; if (discriminatorSchema == null) { continue; } const rest = parts.slice(i + 1).join("."); schematype = discriminatorSchema.path(rest); schema = discriminatorSchema; startIndex = i + 1; if (schematype != null) { type = discriminatorSchema._getPathType(rest); break; } } } return { type, schematype }; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/query/handleImmutable.js var require_handleImmutable2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/query/handleImmutable.js"(exports2, module2) { "use strict"; var StrictModeError = require_strict(); module2.exports = function handleImmutable(schematype, strict, obj, key, fullPath, options, ctx) { if (schematype == null || !schematype.options || !schematype.options.immutable) { return false; } let immutable = schematype.options.immutable; if (typeof immutable === "function") { immutable = immutable.call(ctx, ctx); } if (!immutable) { return false; } if (options && options.overwriteImmutable) { return false; } if (strict === false) { return false; } if (strict === "throw") { throw new StrictModeError( null, `Field ${fullPath} is immutable and strict = 'throw'` ); } delete obj[key]; return true; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/update/moveImmutableProperties.js var require_moveImmutableProperties = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/update/moveImmutableProperties.js"(exports2, module2) { "use strict"; var get = require_get(); module2.exports = function moveImmutableProperties(schema, update, ctx) { if (update == null) { return; } const keys = Object.keys(update); for (const key of keys) { const isDollarKey = key.startsWith("$"); if (key === "$set") { const updatedPaths = Object.keys(update[key]); for (const path of updatedPaths) { _walkUpdatePath(schema, update[key], path, update, ctx); } } else if (!isDollarKey) { _walkUpdatePath(schema, update, key, update, ctx); } } }; function _walkUpdatePath(schema, op, path, update, ctx) { const schematype = schema.path(path); if (schematype == null) { return; } let immutable = get(schematype, "options.immutable", null); if (immutable == null) { return; } if (typeof immutable === "function") { immutable = immutable.call(ctx, ctx); } if (!immutable) { return; } update.$setOnInsert = update.$setOnInsert || {}; update.$setOnInsert[path] = op[path]; delete op[path]; } } }); // netlify/functions/node_modules/mongoose/lib/helpers/path/setDottedPath.js var require_setDottedPath = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/path/setDottedPath.js"(exports2, module2) { "use strict"; var specialProperties = require_specialProperties(); module2.exports = function setDottedPath(obj, path, val) { if (path.indexOf(".") === -1) { if (specialProperties.has(path)) { return; } obj[path] = val; return; } const parts = path.split("."); const last = parts.pop(); let cur = obj; for (const part of parts) { if (specialProperties.has(part)) { continue; } if (cur[part] == null) { cur[part] = {}; } cur = cur[part]; } if (!specialProperties.has(last)) { cur[last] = val; } }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/query/castUpdate.js var require_castUpdate = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/query/castUpdate.js"(exports2, module2) { "use strict"; var CastError = require_cast(); var MongooseError = require_mongooseError(); var SchemaString = require_string2(); var StrictModeError = require_strict(); var ValidationError = require_validation(); var castNumber = require_number(); var cast = require_cast2(); var getConstructorName = require_getConstructorName(); var getDiscriminatorByValue = require_getDiscriminatorByValue(); var getEmbeddedDiscriminatorPath = require_getEmbeddedDiscriminatorPath2(); var handleImmutable = require_handleImmutable2(); var moveImmutableProperties = require_moveImmutableProperties(); var schemaMixedSymbol = require_symbols2().schemaMixedSymbol; var setDottedPath = require_setDottedPath(); var utils = require_utils3(); var { internalToObjectOptions } = require_options(); var mongodbUpdateOperators = /* @__PURE__ */ new Set([ "$currentDate", "$inc", "$min", "$max", "$mul", "$rename", "$set", "$setOnInsert", "$unset", "$addToSet", "$pop", "$pull", "$push", "$pullAll", "$bit" ]); module2.exports = function castUpdate(schema, obj, options, context, filter) { if (obj == null) { return void 0; } options = options || {}; if (Array.isArray(obj)) { const len = obj.length; for (let i2 = 0; i2 < len; ++i2) { const ops2 = Object.keys(obj[i2]); for (const op of ops2) { obj[i2][op] = castPipelineOperator(op, obj[i2][op]); } } return obj; } if (schema != null && filter != null && utils.hasUserDefinedProperty(filter, schema.options.discriminatorKey) && typeof filter[schema.options.discriminatorKey] !== "object" && schema.discriminators != null) { const discriminatorValue = filter[schema.options.discriminatorKey]; const byValue = getDiscriminatorByValue(context.model.discriminators, discriminatorValue); schema = schema.discriminators[discriminatorValue] || byValue && byValue.schema || schema; } else if (schema != null && options.overwriteDiscriminatorKey && utils.hasUserDefinedProperty(obj, schema.options.discriminatorKey) && schema.discriminators != null) { const discriminatorValue = obj[schema.options.discriminatorKey]; const byValue = getDiscriminatorByValue(context.model.discriminators, discriminatorValue); schema = schema.discriminators[discriminatorValue] || byValue && byValue.schema || schema; } else if (schema != null && options.overwriteDiscriminatorKey && obj.$set != null && utils.hasUserDefinedProperty(obj.$set, schema.options.discriminatorKey) && schema.discriminators != null) { const discriminatorValue = obj.$set[schema.options.discriminatorKey]; const byValue = getDiscriminatorByValue(context.model.discriminators, discriminatorValue); schema = schema.discriminators[discriminatorValue] || byValue && byValue.schema || schema; } if (options.upsert) { moveImmutableProperties(schema, obj, context); } const ops = Object.keys(obj); let i = ops.length; const ret = {}; let val; let hasDollarKey = false; filter = filter || {}; while (i--) { const op = ops[i]; if (!mongodbUpdateOperators.has(op)) { if (!ret.$set) { if (obj.$set) { ret.$set = obj.$set; } else { ret.$set = {}; } } ret.$set[op] = obj[op]; ops.splice(i, 1); if (!~ops.indexOf("$set")) ops.push("$set"); } else if (op === "$set") { if (!ret.$set) { ret[op] = obj[op]; } } else { ret[op] = obj[op]; } } i = ops.length; while (i--) { const op = ops[i]; val = ret[op]; hasDollarKey = hasDollarKey || op.startsWith("$"); if (val != null && val.$__) { val = val.toObject(internalToObjectOptions); ret[op] = val; } if (val && typeof val === "object" && !Buffer.isBuffer(val) && mongodbUpdateOperators.has(op)) { walkUpdatePath(schema, val, op, options, context, filter); } else { const msg = "Invalid atomic update value for " + op + ". Expected an object, received " + typeof val; throw new Error(msg); } if (op.startsWith("$") && utils.isEmptyObject(val)) { delete ret[op]; } } if (Object.keys(ret).length === 0 && options.upsert && Object.keys(filter).length > 0) { return { $setOnInsert: { ...filter } }; } return ret; }; function castPipelineOperator(op, val) { if (op === "$unset") { if (typeof val !== "string" && (!Array.isArray(val) || val.find((v) => typeof v !== "string"))) { throw new MongooseError("Invalid $unset in pipeline, must be a string or an array of strings"); } return val; } if (op === "$project") { if (val == null || typeof val !== "object") { throw new MongooseError("Invalid $project in pipeline, must be an object"); } return val; } if (op === "$addFields" || op === "$set") { if (val == null || typeof val !== "object") { throw new MongooseError("Invalid " + op + " in pipeline, must be an object"); } return val; } else if (op === "$replaceRoot" || op === "$replaceWith") { if (val == null || typeof val !== "object") { throw new MongooseError("Invalid " + op + " in pipeline, must be an object"); } return val; } throw new MongooseError('Invalid update pipeline operator: "' + op + '"'); } function walkUpdatePath(schema, obj, op, options, context, filter, pref) { const strict = options.strict; const prefix = pref ? pref + "." : ""; const keys = Object.keys(obj); let i = keys.length; let hasKeys = false; let schematype; let key; let val; let aggregatedError = null; const strictMode = strict != null ? strict : schema.options.strict; while (i--) { key = keys[i]; val = obj[key]; if (op === "$pull") { schematype = schema._getSchema(prefix + key); if (schematype == null) { const _res = getEmbeddedDiscriminatorPath(schema, obj, filter, prefix + key, options); if (_res.schematype != null) { schematype = _res.schematype; } } if (schematype != null && schematype.schema != null) { obj[key] = cast(schematype.schema, obj[key], options, context); hasKeys = true; continue; } } const discriminatorKey = prefix ? prefix + key : key; if (schema.discriminatorMapping != null && discriminatorKey === schema.options.discriminatorKey && schema.discriminatorMapping.value !== obj[key] && !options.overwriteDiscriminatorKey) { if (strictMode === "throw") { const err = new Error(`Can't modify discriminator key "` + discriminatorKey + '" on discriminator model'); aggregatedError = _appendError(err, context, discriminatorKey, aggregatedError); continue; } else if (strictMode) { delete obj[key]; continue; } } if (getConstructorName(val) === "Object") { schematype = schema._getSchema(prefix + key); if (schematype == null) { const _res = getEmbeddedDiscriminatorPath(schema, obj, filter, prefix + key, options); if (_res.schematype != null) { schematype = _res.schematype; } } if (op !== "$setOnInsert" && handleImmutable(schematype, strict, obj, key, prefix + key, options, context)) { continue; } if (schematype && schematype.caster && op in castOps) { if ("$each" in val) { hasKeys = true; try { obj[key] = { $each: castUpdateVal(schematype, val.$each, op, key, context, prefix + key) }; } catch (error) { aggregatedError = _appendError(error, context, key, aggregatedError); } if (val.$slice != null) { obj[key].$slice = val.$slice | 0; } if (val.$sort) { obj[key].$sort = val.$sort; } if (val.$position != null) { obj[key].$position = castNumber(val.$position); } } else { if (schematype != null && schematype.$isSingleNested) { const _strict = strict == null ? schematype.schema.options.strict : strict; try { obj[key] = schematype.castForQuery(null, val, context, { strict: _strict }); } catch (error) { aggregatedError = _appendError(error, context, key, aggregatedError); } } else { try { obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key); } catch (error) { aggregatedError = _appendError(error, context, key, aggregatedError); } } if (obj[key] === void 0) { delete obj[key]; continue; } hasKeys = true; } } else if (op === "$currentDate" || op in castOps && schematype) { try { obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key); } catch (error) { aggregatedError = _appendError(error, context, key, aggregatedError); } if (obj[key] === void 0) { delete obj[key]; continue; } hasKeys = true; } else if (op === "$rename") { const schematype2 = new SchemaString(`${prefix}${key}.$rename`); try { obj[key] = castUpdateVal(schematype2, val, op, key, context, prefix + key); } catch (error) { aggregatedError = _appendError(error, context, key, aggregatedError); } if (obj[key] === void 0) { delete obj[key]; continue; } hasKeys = true; } else { const pathToCheck = prefix + key; const v = schema._getPathType(pathToCheck); let _strict = strict; if (v && v.schema && _strict == null) { _strict = v.schema.options.strict; } if (v.pathType === "undefined") { if (_strict === "throw") { throw new StrictModeError(pathToCheck); } else if (_strict) { delete obj[key]; continue; } } hasKeys |= walkUpdatePath(schema, val, op, options, context, filter, prefix + key) || utils.isObject(val) && Object.keys(val).length === 0; } } else { const checkPath = key === "$each" || key === "$or" || key === "$and" || key === "$in" ? pref : prefix + key; schematype = schema._getSchema(checkPath); if (op !== "$setOnInsert" && handleImmutable(schematype, strict, obj, key, prefix + key, options, context)) { continue; } let pathDetails = schema._getPathType(checkPath); if (schematype == null) { const _res = getEmbeddedDiscriminatorPath(schema, obj, filter, checkPath, options); if (_res.schematype != null) { schematype = _res.schematype; pathDetails = _res.type; } } let isStrict = strict; if (pathDetails && pathDetails.schema && strict == null) { isStrict = pathDetails.schema.options.strict; } const skip = isStrict && !schematype && !/real|nested/.test(pathDetails.pathType); if (skip) { if (isStrict === "throw" && schema.virtuals[checkPath] == null) { throw new StrictModeError(prefix + key); } else { delete obj[key]; } } else { if (op === "$rename") { if (obj[key] == null) { throw new CastError("String", obj[key], `${prefix}${key}.$rename`); } const schematype2 = new SchemaString(`${prefix}${key}.$rename`); obj[key] = schematype2.castForQuery(null, obj[key], context); continue; } try { if (prefix.length === 0 || key.indexOf(".") === -1) { obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key); } else if (isStrict !== false || schematype != null) { setDottedPath(obj, key, castUpdateVal(schematype, val, op, key, context, prefix + key)); delete obj[key]; } } catch (error) { aggregatedError = _appendError(error, context, key, aggregatedError); } if (Array.isArray(obj[key]) && (op === "$addToSet" || op === "$push") && key !== "$each") { if (schematype && schematype.caster && !schematype.caster.$isMongooseArray && !schematype.caster[schemaMixedSymbol]) { obj[key] = { $each: obj[key] }; } } if (obj[key] === void 0) { delete obj[key]; continue; } hasKeys = true; } } } if (aggregatedError != null) { throw aggregatedError; } return hasKeys; } function _appendError(error, query, key, aggregatedError) { if (typeof query !== "object" || !query.options.multipleCastError) { throw error; } aggregatedError = aggregatedError || new ValidationError(); aggregatedError.addError(key, error); return aggregatedError; } var numberOps = { $pop: 1, $inc: 1 }; var noCastOps = { $unset: 1 }; var castOps = { $push: 1, $addToSet: 1, $set: 1, $setOnInsert: 1 }; var overwriteOps = { $set: 1, $setOnInsert: 1 }; function castUpdateVal(schema, val, op, $conditional, context, path) { if (!schema) { if (op in numberOps) { try { return castNumber(val); } catch (err) { throw new CastError("number", val, path); } } return val; } const cond = schema.caster && op in castOps && (utils.isObject(val) || Array.isArray(val)); if (cond && !overwriteOps[op]) { let schemaArrayDepth = 0; let cur = schema; while (cur.$isMongooseArray) { ++schemaArrayDepth; cur = cur.caster; } let arrayDepth = 0; let _val = val; while (Array.isArray(_val)) { ++arrayDepth; _val = _val[0]; } const additionalNesting = schemaArrayDepth - arrayDepth; while (arrayDepth < schemaArrayDepth) { val = [val]; ++arrayDepth; } let tmp = schema.applySetters(Array.isArray(val) ? val : [val], context); for (let i = 0; i < additionalNesting; ++i) { tmp = tmp[0]; } return tmp; } if (op in noCastOps) { return val; } if (op in numberOps) { if (val == null) { throw new CastError("number", val, schema.path); } if (op === "$inc") { return schema.castForQuery( null, val, context ); } try { return castNumber(val); } catch (error) { throw new CastError("number", val, schema.path); } } if (op === "$currentDate") { if (typeof val === "object") { return { $type: val.$type }; } return Boolean(val); } if (mongodbUpdateOperators.has($conditional)) { return schema.castForQuery( $conditional, val, context ); } if (overwriteOps[op]) { const skipQueryCastForUpdate = val != null && schema.$isMongooseArray && schema.$fullPath != null && !schema.$fullPath.match(/\d+$/); const applySetters = schema[schemaMixedSymbol] != null; if (skipQueryCastForUpdate || applySetters) { return schema.applySetters(val, context); } return schema.castForQuery( null, val, context ); } return schema.castForQuery(null, val, context); } } }); // netlify/functions/node_modules/mongoose/lib/helpers/update/decorateUpdateWithVersionKey.js var require_decorateUpdateWithVersionKey = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/update/decorateUpdateWithVersionKey.js"(exports2, module2) { "use strict"; var modifiedPaths = require_modifiedPaths(); module2.exports = function decorateUpdateWithVersionKey(update, options, versionKey) { if (!versionKey || !(options && options.upsert || false)) { return; } const updatedPaths = modifiedPaths(update); if (!updatedPaths[versionKey]) { if (options.overwrite) { update[versionKey] = 0; } else { if (!update.$setOnInsert) { update.$setOnInsert = {}; } update.$setOnInsert[versionKey] = 0; } } }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/setDefaultsOnInsert.js var require_setDefaultsOnInsert = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/setDefaultsOnInsert.js"(exports2, module2) { "use strict"; var modifiedPaths = require_common3().modifiedPaths; var get = require_get(); module2.exports = function(filter, schema, castedDoc, options) { options = options || {}; const shouldSetDefaultsOnInsert = options.setDefaultsOnInsert != null ? options.setDefaultsOnInsert : schema.base.options.setDefaultsOnInsert; if (!options.upsert || shouldSetDefaultsOnInsert === false) { return castedDoc; } const keys = Object.keys(castedDoc || {}); const updatedKeys = {}; const updatedValues = {}; const numKeys = keys.length; const modified = {}; let hasDollarUpdate = false; for (let i = 0; i < numKeys; ++i) { if (keys[i].startsWith("$")) { modifiedPaths(castedDoc[keys[i]], "", modified); hasDollarUpdate = true; } } if (!hasDollarUpdate) { modifiedPaths(castedDoc, "", modified); } const paths = Object.keys(filter); const numPaths = paths.length; for (let i = 0; i < numPaths; ++i) { const path = paths[i]; const condition = filter[path]; if (condition && typeof condition === "object") { const conditionKeys = Object.keys(condition); const numConditionKeys = conditionKeys.length; let hasDollarKey = false; for (let j = 0; j < numConditionKeys; ++j) { if (conditionKeys[j].startsWith("$")) { hasDollarKey = true; break; } } if (hasDollarKey) { continue; } } updatedKeys[path] = true; modified[path] = true; } if (options && options.overwrite && !hasDollarUpdate) { return castedDoc; } schema.eachPath(function(path, schemaType) { if (schemaType.path === "_id" && schemaType.options.auto) { return; } const def = schemaType.getDefault(null, true); if (isModified(modified, path)) { return; } if (typeof def === "undefined") { return; } if (schemaType.splitPath().includes("$*")) { return; } castedDoc = castedDoc || {}; castedDoc.$setOnInsert = castedDoc.$setOnInsert || {}; if (get(castedDoc, path) == null) { castedDoc.$setOnInsert[path] = def; } updatedValues[path] = def; }); return castedDoc; }; function isModified(modified, path) { if (modified[path]) { return true; } const sp = path.split("."); let cur = sp[0]; for (let i = 1; i < sp.length; ++i) { if (modified[cur]) { return true; } cur += "." + sp[i]; } const modifiedKeys = Object.keys(modified); if (modifiedKeys.length) { const parentPath = path + "."; for (const modifiedPath of modifiedKeys) { if (modifiedPath.slice(0, path.length + 1) === parentPath) { return true; } } } return false; } } }); // netlify/functions/node_modules/mongoose/lib/helpers/model/castBulkWrite.js var require_castBulkWrite = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/model/castBulkWrite.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var getDiscriminatorByValue = require_getDiscriminatorByValue(); var applyTimestampsToChildren = require_applyTimestampsToChildren(); var applyTimestampsToUpdate = require_applyTimestampsToUpdate(); var cast = require_cast2(); var castUpdate = require_castUpdate(); var clone = require_clone(); var decorateUpdateWithVersionKey = require_decorateUpdateWithVersionKey(); var { inspect } = require("util"); var setDefaultsOnInsert = require_setDefaultsOnInsert(); module2.exports = function castBulkWrite(originalModel, op, options) { const now = originalModel.base.now(); if (op["insertOne"]) { return (callback) => module2.exports.castInsertOne(originalModel, op["insertOne"], options).then(() => callback(null), (err) => callback(err)); } else if (op["updateOne"]) { return (callback) => { try { module2.exports.castUpdateOne(originalModel, op["updateOne"], options, now); callback(null); } catch (err) { callback(err); } }; } else if (op["updateMany"]) { return (callback) => { try { module2.exports.castUpdateMany(originalModel, op["updateMany"], options, now); callback(null); } catch (err) { callback(err); } }; } else if (op["replaceOne"]) { return (callback) => { module2.exports.castReplaceOne(originalModel, op["replaceOne"], options).then(() => callback(null), (err) => callback(err)); }; } else if (op["deleteOne"]) { return (callback) => { try { module2.exports.castDeleteOne(originalModel, op["deleteOne"]); callback(null); } catch (err) { callback(err); } }; } else if (op["deleteMany"]) { return (callback) => { try { module2.exports.castDeleteMany(originalModel, op["deleteMany"]); callback(null); } catch (err) { callback(err); } }; } else { return (callback) => { const error = new MongooseError(`Invalid op passed to \`bulkWrite()\`: ${inspect(op)}`); callback(error, null); }; } }; module2.exports.castInsertOne = async function castInsertOne(originalModel, insertOne, options) { const model = decideModelByObject(originalModel, insertOne["document"]); const doc = new model(insertOne["document"]); if (model.schema.options.timestamps && getTimestampsOpt(insertOne, options)) { doc.initializeTimestamps(); } if (options.session != null) { doc.$session(options.session); } const versionKey = model?.schema?.options?.versionKey; if (versionKey && doc[versionKey] == null) { doc[versionKey] = 0; } insertOne["document"] = doc; if (options.skipValidation || insertOne.skipValidation) { return insertOne; } await insertOne["document"].$validate(); return insertOne; }; module2.exports.castUpdateOne = function castUpdateOne(originalModel, updateOne, options, now) { if (!updateOne["filter"]) { throw new Error("Must provide a filter object."); } if (!updateOne["update"]) { throw new Error("Must provide an update object."); } const model = decideModelByObject(originalModel, updateOne["filter"]); const schema = model.schema; const strict = options.strict != null ? options.strict : model.schema.options.strict; const update = clone(updateOne["update"]); _addDiscriminatorToObject(schema, updateOne["filter"]); const doInitTimestamps = getTimestampsOpt(updateOne, options); if (model.schema.$timestamps != null && doInitTimestamps) { const createdAt = model.schema.$timestamps.createdAt; const updatedAt = model.schema.$timestamps.updatedAt; applyTimestampsToUpdate(now, createdAt, updatedAt, update, {}); } if (doInitTimestamps) { applyTimestampsToChildren(now, update, model.schema); } const globalSetDefaultsOnInsert = originalModel.base.options.setDefaultsOnInsert; const shouldSetDefaultsOnInsert = updateOne.setDefaultsOnInsert == null ? globalSetDefaultsOnInsert : updateOne.setDefaultsOnInsert; if (shouldSetDefaultsOnInsert !== false) { setDefaultsOnInsert(updateOne["filter"], model.schema, update, { setDefaultsOnInsert: true, upsert: updateOne.upsert }); } decorateUpdateWithVersionKey( update, updateOne, model.schema.options.versionKey ); updateOne["filter"] = cast(model.schema, updateOne["filter"], { strict, upsert: updateOne.upsert }); updateOne["update"] = castUpdate(model.schema, update, { strict, upsert: updateOne.upsert, arrayFilters: updateOne.arrayFilters, overwriteDiscriminatorKey: updateOne.overwriteDiscriminatorKey }, model, updateOne["filter"]); return updateOne; }; module2.exports.castUpdateMany = function castUpdateMany(originalModel, updateMany, options, now) { if (!updateMany["filter"]) { throw new Error("Must provide a filter object."); } if (!updateMany["update"]) { throw new Error("Must provide an update object."); } const model = decideModelByObject(originalModel, updateMany["filter"]); const schema = model.schema; const strict = options.strict != null ? options.strict : model.schema.options.strict; const globalSetDefaultsOnInsert = originalModel.base.options.setDefaultsOnInsert; const shouldSetDefaultsOnInsert = updateMany.setDefaultsOnInsert == null ? globalSetDefaultsOnInsert : updateMany.setDefaultsOnInsert; if (shouldSetDefaultsOnInsert !== false) { setDefaultsOnInsert(updateMany["filter"], model.schema, updateMany["update"], { setDefaultsOnInsert: true, upsert: updateMany.upsert }); } const doInitTimestamps = getTimestampsOpt(updateMany, options); if (model.schema.$timestamps != null && doInitTimestamps) { const createdAt = model.schema.$timestamps.createdAt; const updatedAt = model.schema.$timestamps.updatedAt; applyTimestampsToUpdate(now, createdAt, updatedAt, updateMany["update"], {}); } if (doInitTimestamps) { applyTimestampsToChildren(now, updateMany["update"], model.schema); } _addDiscriminatorToObject(schema, updateMany["filter"]); decorateUpdateWithVersionKey( updateMany["update"], updateMany, model.schema.options.versionKey ); updateMany["filter"] = cast(model.schema, updateMany["filter"], { strict, upsert: updateMany.upsert }); updateMany["update"] = castUpdate(model.schema, updateMany["update"], { strict, upsert: updateMany.upsert, arrayFilters: updateMany.arrayFilters, overwriteDiscriminatorKey: updateMany.overwriteDiscriminatorKey }, model, updateMany["filter"]); }; module2.exports.castReplaceOne = async function castReplaceOne(originalModel, replaceOne, options) { const model = decideModelByObject(originalModel, replaceOne["filter"]); const schema = model.schema; const strict = options.strict != null ? options.strict : model.schema.options.strict; _addDiscriminatorToObject(schema, replaceOne["filter"]); replaceOne["filter"] = cast(model.schema, replaceOne["filter"], { strict, upsert: replaceOne.upsert }); const doc = new model(replaceOne["replacement"], strict, true); if (model.schema.options.timestamps && getTimestampsOpt(replaceOne, options)) { doc.initializeTimestamps(); } if (options.session != null) { doc.$session(options.session); } const versionKey = model?.schema?.options?.versionKey; if (versionKey && doc[versionKey] == null) { doc[versionKey] = 0; } replaceOne["replacement"] = doc; if (options.skipValidation || replaceOne.skipValidation) { replaceOne["replacement"] = replaceOne["replacement"].toBSON(); return; } await replaceOne["replacement"].$validate(); replaceOne["replacement"] = replaceOne["replacement"].toBSON(); }; module2.exports.castDeleteOne = function castDeleteOne(originalModel, deleteOne) { const model = decideModelByObject(originalModel, deleteOne["filter"]); const schema = model.schema; _addDiscriminatorToObject(schema, deleteOne["filter"]); deleteOne["filter"] = cast(model.schema, deleteOne["filter"]); }; module2.exports.castDeleteMany = function castDeleteMany(originalModel, deleteMany) { const model = decideModelByObject(originalModel, deleteMany["filter"]); const schema = model.schema; _addDiscriminatorToObject(schema, deleteMany["filter"]); deleteMany["filter"] = cast(model.schema, deleteMany["filter"]); }; module2.exports.cast = { insertOne: module2.exports.castInsertOne, updateOne: module2.exports.castUpdateOne, updateMany: module2.exports.castUpdateMany, replaceOne: module2.exports.castReplaceOne, deleteOne: module2.exports.castDeleteOne, deleteMany: module2.exports.castDeleteMany }; function _addDiscriminatorToObject(schema, obj) { if (schema == null) { return; } if (schema.discriminatorMapping && !schema.discriminatorMapping.isRoot) { obj[schema.discriminatorMapping.key] = schema.discriminatorMapping.value; } } function decideModelByObject(model, object) { const discriminatorKey = model.schema.options.discriminatorKey; if (object != null && object.hasOwnProperty(discriminatorKey)) { model = getDiscriminatorByValue(model.discriminators, object[discriminatorKey]) || model; } return model; } function getTimestampsOpt(opCommand, options) { const opLevelOpt = opCommand.timestamps; const bulkLevelOpt = options.timestamps; if (opLevelOpt != null) { return opLevelOpt; } else if (bulkLevelOpt != null) { return bulkLevelOpt; } return true; } } }); // netlify/functions/node_modules/mongoose/lib/helpers/model/decorateBulkWriteResult.js var require_decorateBulkWriteResult = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/model/decorateBulkWriteResult.js"(exports2, module2) { "use strict"; module2.exports = function decorateBulkWriteResult(resultOrError, validationErrors, results) { resultOrError.mongoose = resultOrError.mongoose || {}; resultOrError.mongoose.validationErrors = validationErrors; resultOrError.mongoose.results = results; return resultOrError; }; } }); // netlify/functions/node_modules/mongoose/lib/connection.js var require_connection2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/connection.js"(exports2, module2) { "use strict"; var ChangeStream = require_changeStream(); var EventEmitter = require("events").EventEmitter; var Schema = require_schema2(); var STATES = require_connectionState(); var MongooseBulkWriteError = require_bulkWriteError(); var MongooseError = require_error2(); var ServerSelectionError = require_serverSelection(); var SyncIndexesError = require_syncIndexes(); var applyPlugins = require_applyPlugins(); var clone = require_clone(); var driver = require_driver(); var get = require_get(); var getDefaultBulkwriteResult = require_getDefaultBulkwriteResult(); var immediate = require_immediate(); var utils = require_utils3(); var CreateCollectionsError = require_createCollectionsError(); var castBulkWrite = require_castBulkWrite(); var { modelSymbol } = require_symbols(); var isPromise = require_isPromise(); var decorateBulkWriteResult = require_decorateBulkWriteResult(); var arrayAtomicsSymbol = require_symbols().arrayAtomicsSymbol; var sessionNewDocuments = require_symbols().sessionNewDocuments; var noPasswordAuthMechanisms = [ "MONGODB-X509" ]; function Connection(base) { this.base = base; this.collections = {}; this.models = {}; this.config = {}; this.replica = false; this.options = null; this.otherDbs = []; this.relatedDbs = {}; this.states = STATES; this._readyState = STATES.disconnected; this._closeCalled = false; this._hasOpened = false; this.plugins = []; if (typeof base === "undefined" || !base.connections.length) { this.id = 0; } else { this.id = base.nextConnectionId; } this._queue = []; } Object.setPrototypeOf(Connection.prototype, EventEmitter.prototype); Object.defineProperty(Connection.prototype, "readyState", { get: function() { if (this._readyState === STATES.connected && this._lastHeartbeatAt != null && // LoadBalanced topology (behind haproxy, including Atlas serverless instances) don't use heartbeats, // so we can't use this check in that case. this.client?.topology?.s?.description?.type !== "LoadBalanced" && typeof this.client?.topology?.s?.description?.heartbeatFrequencyMS === "number" && Date.now() - this._lastHeartbeatAt >= this.client.topology.s.description.heartbeatFrequencyMS * 2) { return STATES.disconnected; } return this._readyState; }, set: function(val) { if (!(val in STATES)) { throw new Error("Invalid connection state: " + val); } if (this._readyState !== val) { this._readyState = val; for (const db of this.otherDbs) { db.readyState = val; } if (STATES.connected === val) { this._hasOpened = true; } this.emit(STATES[val]); } } }); Connection.prototype.get = function getOption(key) { if (this.config.hasOwnProperty(key)) { return this.config[key]; } return get(this.options, key); }; Connection.prototype.set = function setOption(key, val) { if (this.config.hasOwnProperty(key)) { this.config[key] = val; return val; } this.options = this.options || {}; this.options[key] = val; return val; }; Connection.prototype.collections; Connection.prototype.name; Connection.prototype.models; Connection.prototype.id; Object.defineProperty(Connection.prototype, "plugins", { configurable: false, enumerable: true, writable: true }); Object.defineProperty(Connection.prototype, "host", { configurable: true, enumerable: true, writable: true }); Object.defineProperty(Connection.prototype, "port", { configurable: true, enumerable: true, writable: true }); Object.defineProperty(Connection.prototype, "user", { configurable: true, enumerable: true, writable: true }); Object.defineProperty(Connection.prototype, "pass", { configurable: true, enumerable: true, writable: true }); Connection.prototype.db; Connection.prototype.client; Connection.prototype.config; Connection.prototype.createCollection = async function createCollection(collection, options) { if (typeof options === "function" || arguments.length >= 3 && typeof arguments[2] === "function") { throw new MongooseError("Connection.prototype.createCollection() no longer accepts a callback"); } await this._waitForConnect(); return this.db.createCollection(collection, options); }; Connection.prototype.bulkWrite = async function bulkWrite(ops, options) { await this._waitForConnect(); options = options || {}; const ordered = options.ordered == null ? true : options.ordered; const asyncLocalStorage = this.base.transactionAsyncLocalStorage?.getStore(); if ((!options || !options.hasOwnProperty("session")) && asyncLocalStorage?.session != null) { options = { ...options, session: asyncLocalStorage.session }; } const now = this.base.now(); let res = null; if (ordered) { const opsToSend = []; for (const op of ops) { if (typeof op.model !== "string" && !op.model?.[modelSymbol]) { throw new MongooseError("Must specify model in Connection.prototype.bulkWrite() operations"); } const Model = op.model[modelSymbol] ? op.model : this.model(op.model); if (op.name == null) { throw new MongooseError("Must specify operation name in Connection.prototype.bulkWrite()"); } if (!castBulkWrite.cast.hasOwnProperty(op.name)) { throw new MongooseError(`Unrecognized bulkWrite() operation name ${op.name}`); } await castBulkWrite.cast[op.name](Model, op, options, now); opsToSend.push({ ...op, namespace: Model.namespace() }); } res = await this.client.bulkWrite(opsToSend, options); } else { const validOps = []; const validOpIndexes = []; let validationErrors = []; const asyncValidations = []; const results = []; for (let i = 0; i < ops.length; ++i) { const op = ops[i]; if (typeof op.model !== "string" && !op.model?.[modelSymbol]) { const error2 = new MongooseError("Must specify model in Connection.prototype.bulkWrite() operations"); validationErrors.push({ index: i, error: error2 }); results[i] = error2; continue; } let Model; try { Model = op.model[modelSymbol] ? op.model : this.model(op.model); } catch (error2) { validationErrors.push({ index: i, error: error2 }); continue; } if (op.name == null) { const error2 = new MongooseError("Must specify operation name in Connection.prototype.bulkWrite()"); validationErrors.push({ index: i, error: error2 }); results[i] = error2; continue; } if (!castBulkWrite.cast.hasOwnProperty(op.name)) { const error2 = new MongooseError(`Unrecognized bulkWrite() operation name ${op.name}`); validationErrors.push({ index: i, error: error2 }); results[i] = error2; continue; } let maybePromise = null; try { maybePromise = castBulkWrite.cast[op.name](Model, op, options, now); } catch (error2) { validationErrors.push({ index: i, error: error2 }); results[i] = error2; continue; } if (isPromise(maybePromise)) { asyncValidations.push( maybePromise.then( () => { validOps.push({ ...op, namespace: Model.namespace() }); validOpIndexes.push(i); }, (error2) => { validationErrors.push({ index: i, error: error2 }); results[i] = error2; } ) ); } else { validOps.push({ ...op, namespace: Model.namespace() }); validOpIndexes.push(i); } } if (asyncValidations.length > 0) { await Promise.all(asyncValidations); } validationErrors = validationErrors.sort((v1, v2) => v1.index - v2.index).map((v) => v.error); if (validOps.length === 0) { if (options.throwOnValidationError && validationErrors.length) { throw new MongooseBulkWriteError( validationErrors, results, res2, "bulkWrite" ); } const BulkWriteResult = this.base.driver.get().BulkWriteResult; const res2 = new BulkWriteResult(getDefaultBulkwriteResult(), false); return decorateBulkWriteResult(res2, validationErrors, results); } let error; [res, error] = await this.client.bulkWrite(validOps, options).then((res2) => [res2, null]).catch((err) => [null, err]); for (let i = 0; i < validOpIndexes.length; ++i) { results[validOpIndexes[i]] = null; } if (error) { if (validationErrors.length > 0) { decorateBulkWriteResult(error, validationErrors, results); error.mongoose = error.mongoose || {}; error.mongoose.validationErrors = validationErrors; } } if (validationErrors.length > 0) { if (options.throwOnValidationError) { throw new MongooseBulkWriteError( validationErrors, results, res, "bulkWrite" ); } else { decorateBulkWriteResult(res, validationErrors, results); } } } return res; }; Connection.prototype.createCollections = async function createCollections(options = {}) { const result = {}; const errorsMap = {}; const { continueOnError } = options; delete options.continueOnError; for (const model of Object.values(this.models)) { try { result[model.modelName] = await model.createCollection({}); } catch (err) { if (!continueOnError) { errorsMap[model.modelName] = err; break; } else { result[model.modelName] = err; } } } if (!continueOnError && Object.keys(errorsMap).length) { const message = Object.entries(errorsMap).map(([modelName, err]) => `${modelName}: ${err.message}`).join(", "); const createCollectionsError = new CreateCollectionsError(message, errorsMap); throw createCollectionsError; } return result; }; Connection.prototype.withSession = async function withSession(executor) { if (arguments.length === 0) { throw new Error("Please provide an executor function"); } return await this.client.withSession(executor); }; Connection.prototype.startSession = async function startSession(options) { if (arguments.length >= 2 && typeof arguments[1] === "function") { throw new MongooseError("Connection.prototype.startSession() no longer accepts a callback"); } await this._waitForConnect(); const session = this.client.startSession(options); return session; }; Connection.prototype.transaction = function transaction(fn, options) { return this.startSession().then((session) => { session[sessionNewDocuments] = /* @__PURE__ */ new Map(); return session.withTransaction(() => _wrapUserTransaction(fn, session, this.base), options).then((res) => { delete session[sessionNewDocuments]; return res; }).catch((err) => { delete session[sessionNewDocuments]; throw err; }).finally(() => { session.endSession().catch(() => { }); }); }); }; async function _wrapUserTransaction(fn, session, mongoose) { try { const res = mongoose.transactionAsyncLocalStorage == null ? await fn(session) : await new Promise((resolve) => { mongoose.transactionAsyncLocalStorage.run( { session }, () => resolve(fn(session)) ); }); return res; } catch (err) { _resetSessionDocuments(session); throw err; } } function _resetSessionDocuments(session) { for (const doc of session[sessionNewDocuments].keys()) { const state = session[sessionNewDocuments].get(doc); if (state.hasOwnProperty("isNew")) { doc.$isNew = state.isNew; } if (state.hasOwnProperty("versionKey")) { doc.set(doc.schema.options.versionKey, state.versionKey); } if (state.modifiedPaths.length > 0 && doc.$__.activePaths.states.modify == null) { doc.$__.activePaths.states.modify = {}; } for (const path of state.modifiedPaths) { const currentState = doc.$__.activePaths.paths[path]; if (currentState != null) { delete doc.$__.activePaths[currentState][path]; } doc.$__.activePaths.paths[path] = "modify"; doc.$__.activePaths.states.modify[path] = true; } for (const path of state.atomics.keys()) { const val = doc.$__getValue(path); if (val == null) { continue; } val[arrayAtomicsSymbol] = state.atomics.get(path); } } } Connection.prototype.dropCollection = async function dropCollection(collection) { if (arguments.length >= 2 && typeof arguments[1] === "function") { throw new MongooseError("Connection.prototype.dropCollection() no longer accepts a callback"); } await this._waitForConnect(); return this.db.dropCollection(collection); }; Connection.prototype._waitForConnect = async function _waitForConnect(noTimeout) { if ((this.readyState === STATES.connecting || this.readyState === STATES.disconnected) && this._shouldBufferCommands()) { const bufferTimeoutMS = this._getBufferTimeoutMS(); let timeout = null; let timedOut = false; const queueElement = {}; const waitForConnectPromise = new Promise((resolve) => { queueElement.fn = resolve; this._queue.push(queueElement); }); if (noTimeout) { await waitForConnectPromise; } else { await Promise.race([ waitForConnectPromise, new Promise((resolve) => { timeout = setTimeout( () => { timedOut = true; resolve(); }, bufferTimeoutMS ); }) ]); } if (timedOut) { const index = this._queue.indexOf(queueElement); if (index !== -1) { this._queue.splice(index, 1); } const message = "Connection operation buffering timed out after " + bufferTimeoutMS + "ms"; throw new MongooseError(message); } else if (timeout != null) { clearTimeout(timeout); } } }; Connection.prototype._getBufferTimeoutMS = function _getBufferTimeoutMS() { if (this.config.bufferTimeoutMS != null) { return this.config.bufferTimeoutMS; } if (this.base != null && this.base.get("bufferTimeoutMS") != null) { return this.base.get("bufferTimeoutMS"); } return 1e4; }; Connection.prototype.listCollections = async function listCollections() { await this._waitForConnect(); const cursor = this.db.listCollections(); return await cursor.toArray(); }; Connection.prototype.listDatabases = async function listDatabases() { throw new MongooseError("listDatabases() not implemented by driver"); }; Connection.prototype.dropDatabase = async function dropDatabase() { if (arguments.length >= 1 && typeof arguments[0] === "function") { throw new MongooseError("Connection.prototype.dropDatabase() no longer accepts a callback"); } await this._waitForConnect(); for (const model of Object.values(this.models)) { delete model.$init; } return this.db.dropDatabase(); }; Connection.prototype._shouldBufferCommands = function _shouldBufferCommands() { if (this.config.bufferCommands != null) { return this.config.bufferCommands; } if (this.base.get("bufferCommands") != null) { return this.base.get("bufferCommands"); } return true; }; Connection.prototype.error = function error(err, callback) { if (callback) { callback(err); return null; } if (this.listeners("error").length > 0) { this.emit("error", err); } return Promise.reject(err); }; Connection.prototype.onOpen = function() { this.readyState = STATES.connected; for (const d of this._queue) { d.fn.apply(d.ctx, d.args); } this._queue = []; for (const i in this.collections) { if (utils.object.hasOwnProperty(this.collections, i)) { this.collections[i].onOpen(); } } this.emit("open"); }; Connection.prototype.openUri = async function openUri(uri, options) { if (this.readyState === STATES.connecting || this.readyState === STATES.connected) { if (this._connectionString === uri) { return this; } } this._closeCalled = false; let _fireAndForget = false; if (options && "_fireAndForget" in options) { _fireAndForget = options._fireAndForget; delete options._fireAndForget; } try { _validateArgs.apply(arguments); } catch (err) { if (_fireAndForget) { throw err; } this.$initialConnection = Promise.reject(err); throw err; } this.$initialConnection = this.createClient(uri, options).then(() => this).catch((err) => { this.readyState = STATES.disconnected; if (this.listeners("error").length > 0) { immediate(() => this.emit("error", err)); } throw err; }); for (const model of Object.values(this.models)) { model.init().catch(function $modelInitNoop() { }); } if (_fireAndForget) { return this; } try { await this.$initialConnection; } catch (err) { throw _handleConnectionErrors(err); } return this; }; Connection.prototype.on = function on(event, callback) { if (event === "error" && this.$initialConnection) { this.$initialConnection.catch(() => { }); } return EventEmitter.prototype.on.call(this, event, callback); }; Connection.prototype.once = function on(event, callback) { if (event === "error" && this.$initialConnection) { this.$initialConnection.catch(() => { }); } return EventEmitter.prototype.once.call(this, event, callback); }; function _validateArgs(uri, options, callback) { if (typeof options === "function" && callback == null) { throw new MongooseError("Connection.prototype.openUri() no longer accepts a callback"); } else if (typeof callback === "function") { throw new MongooseError("Connection.prototype.openUri() no longer accepts a callback"); } } function _handleConnectionErrors(err) { if (err?.name === "MongoServerSelectionError") { const originalError = err; err = new ServerSelectionError(); err.assimilateError(originalError); } return err; } Connection.prototype.destroy = async function destroy(force) { if (typeof force === "function" || arguments.length === 2 && typeof arguments[1] === "function") { throw new MongooseError("Connection.prototype.destroy() no longer accepts a callback"); } if (force != null && typeof force === "object") { this.$wasForceClosed = !!force.force; } else { this.$wasForceClosed = !!force; } return this._close(force, true); }; Connection.prototype.close = async function close(force) { if (typeof force === "function" || arguments.length === 2 && typeof arguments[1] === "function") { throw new MongooseError("Connection.prototype.close() no longer accepts a callback"); } if (force != null && typeof force === "object") { this.$wasForceClosed = !!force.force; } else { this.$wasForceClosed = !!force; } if (this._lastHeartbeatAt != null) { this._lastHeartbeatAt = null; } for (const model of Object.values(this.models)) { delete model.$init; } return this._close(force, false); }; Connection.prototype._close = async function _close(force, destroy) { const _this = this; const closeCalled = this._closeCalled; this._closeCalled = true; this._destroyCalled = destroy; if (this.client != null) { this.client._closeCalled = true; this.client._destroyCalled = destroy; } const conn = this; switch (this.readyState) { case STATES.disconnected: if (destroy && this.base.connections.indexOf(conn) !== -1) { this.base.connections.splice(this.base.connections.indexOf(conn), 1); } if (!closeCalled) { await this.doClose(force); this.onClose(force); } break; case STATES.connected: this.readyState = STATES.disconnecting; await this.doClose(force); if (destroy && _this.base.connections.indexOf(conn) !== -1) { this.base.connections.splice(this.base.connections.indexOf(conn), 1); } this.onClose(force); break; case STATES.connecting: return new Promise((resolve, reject) => { const _rerunClose = () => { this.removeListener("open", _rerunClose); this.removeListener("error", _rerunClose); if (destroy) { this.destroy(force).then(resolve, reject); } else { this.close(force).then(resolve, reject); } }; this.once("open", _rerunClose); this.once("error", _rerunClose); }); case STATES.disconnecting: return new Promise((resolve) => { this.once("close", () => { if (destroy && this.base.connections.indexOf(conn) !== -1) { this.base.connections.splice(this.base.connections.indexOf(conn), 1); } resolve(); }); }); } return this; }; Connection.prototype.doClose = function doClose() { throw new Error("Connection#doClose unimplemented by driver"); }; Connection.prototype.onClose = function onClose(force) { this.readyState = STATES.disconnected; for (const i in this.collections) { if (utils.object.hasOwnProperty(this.collections, i)) { this.collections[i].onClose(force); } } this.emit("close", force); const wasForceClosed = typeof force === "object" && force !== null ? force.force : force; for (const db of this.otherDbs) { this._destroyCalled ? db.destroy({ force: wasForceClosed, skipCloseClient: true }) : db.close({ force: wasForceClosed, skipCloseClient: true }); } }; Connection.prototype.collection = function(name, options) { const defaultOptions = { autoIndex: this.config.autoIndex != null ? this.config.autoIndex : this.base.options.autoIndex, autoCreate: this.config.autoCreate != null ? this.config.autoCreate : this.base.options.autoCreate, autoSearchIndex: this.config.autoSearchIndex != null ? this.config.autoSearchIndex : this.base.options.autoSearchIndex }; options = Object.assign({}, defaultOptions, options ? clone(options) : {}); options.$wasForceClosed = this.$wasForceClosed; const Collection = this.base && this.base.__driver && this.base.__driver.Collection || driver.get().Collection; if (!(name in this.collections)) { this.collections[name] = new Collection(name, this, options); } return this.collections[name]; }; Connection.prototype.plugin = function(fn, opts) { this.plugins.push([fn, opts]); return this; }; Connection.prototype.model = function model(name, schema, collection, options) { if (!(this instanceof Connection)) { throw new MongooseError("`connection.model()` should not be run with `new`. If you are doing `new db.model(foo)(bar)`, use `db.model(foo)(bar)` instead"); } let fn; if (typeof name === "function") { fn = name; name = fn.name; } if (typeof schema === "string") { collection = schema; schema = false; } if (utils.isObject(schema)) { if (!schema.instanceOfSchema) { schema = new Schema(schema); } else if (!(schema instanceof this.base.Schema)) { schema = schema._clone(this.base.Schema); } } if (schema && !schema.instanceOfSchema) { throw new Error("The 2nd parameter to `mongoose.model()` should be a schema or a POJO"); } const defaultOptions = { cache: false, overwriteModels: this.base.options.overwriteModels }; const opts = Object.assign(defaultOptions, options, { connection: this }); if (this.models[name] && !collection && opts.overwriteModels !== true) { if (schema && schema.instanceOfSchema && schema !== this.models[name].schema) { throw new MongooseError.OverwriteModelError(name); } return this.models[name]; } let model2; if (schema && schema.instanceOfSchema) { applyPlugins(schema, this.plugins, null, "$connectionPluginsApplied"); model2 = this.base._model(fn || name, schema, collection, opts); if (!this.models[name]) { this.models[name] = model2; } model2.init().catch(function $modelInitNoop() { }); return model2; } if (this.models[name] && collection) { model2 = this.models[name]; schema = model2.prototype.schema; const sub = model2.__subclass(this, schema, collection); return sub; } if (arguments.length === 1) { model2 = this.models[name]; if (!model2) { throw new MongooseError.MissingSchemaError(name); } return model2; } if (!model2) { throw new MongooseError.MissingSchemaError(name); } if (this === model2.prototype.db && (!collection || collection === model2.collection.name)) { if (!this.models[name]) { this.models[name] = model2; } return model2; } this.models[name] = model2.__subclass(this, schema, collection); return this.models[name]; }; Connection.prototype.deleteModel = function deleteModel(name) { if (typeof name === "string") { const model = this.model(name); if (model == null) { return this; } const collectionName = model.collection.name; delete this.models[name]; delete this.collections[collectionName]; this.emit("deleteModel", model); } else if (name instanceof RegExp) { const pattern = name; const names = this.modelNames(); for (const name2 of names) { if (pattern.test(name2)) { this.deleteModel(name2); } } } else { throw new Error('First parameter to `deleteModel()` must be a string or regexp, got "' + name + '"'); } return this; }; Connection.prototype.watch = function watch(pipeline, options) { const changeStreamThunk = (cb) => { immediate(() => { if (this.readyState === STATES.connecting) { this.once("open", function() { const driverChangeStream = this.db.watch(pipeline, options); cb(null, driverChangeStream); }); } else { const driverChangeStream = this.db.watch(pipeline, options); cb(null, driverChangeStream); } }); }; const changeStream = new ChangeStream(changeStreamThunk, pipeline, options); return changeStream; }; Connection.prototype.asPromise = async function asPromise() { try { await this.$initialConnection; return this; } catch (err) { throw _handleConnectionErrors(err); } }; Connection.prototype.modelNames = function modelNames() { return Object.keys(this.models); }; Connection.prototype.shouldAuthenticate = function shouldAuthenticate() { return this.user != null && (this.pass != null || this.authMechanismDoesNotRequirePassword()); }; Connection.prototype.authMechanismDoesNotRequirePassword = function authMechanismDoesNotRequirePassword() { if (this.options && this.options.auth) { return noPasswordAuthMechanisms.indexOf(this.options.auth.authMechanism) >= 0; } return true; }; Connection.prototype.optionsProvideAuthenticationData = function optionsProvideAuthenticationData(options) { return options && options.user && (options.pass || this.authMechanismDoesNotRequirePassword()); }; Connection.prototype.getClient = function getClient() { return this.client; }; Connection.prototype.setClient = function setClient() { throw new MongooseError("Connection#setClient not implemented by driver"); }; Connection.prototype.createClient = function createClient() { throw new MongooseError("Connection#createClient not implemented by driver"); }; Connection.prototype.syncIndexes = async function syncIndexes(options = {}) { const result = {}; const errorsMap = {}; const { continueOnError } = options; delete options.continueOnError; for (const model of Object.values(this.models)) { try { result[model.modelName] = await model.syncIndexes(options); } catch (err) { if (!continueOnError) { errorsMap[model.modelName] = err; break; } else { result[model.modelName] = err; } } } if (!continueOnError && Object.keys(errorsMap).length) { const message = Object.entries(errorsMap).map(([modelName, err]) => `${modelName}: ${err.message}`).join(", "); const syncIndexesError = new SyncIndexesError(message, errorsMap); throw syncIndexesError; } return result; }; Connection.STATES = STATES; module2.exports = Connection; } }); // netlify/functions/node_modules/mongoose/package.json var require_package2 = __commonJS({ "netlify/functions/node_modules/mongoose/package.json"(exports2, module2) { module2.exports = { name: "mongoose", description: "Mongoose MongoDB ODM", version: "8.18.2", author: "Guillermo Rauch ", keywords: [ "mongodb", "document", "model", "schema", "database", "odm", "data", "datastore", "query", "nosql", "orm", "db" ], type: "commonjs", license: "MIT", dependencies: { bson: "^6.10.4", kareem: "2.6.3", mongodb: "~6.18.0", mpath: "0.9.0", mquery: "5.0.0", ms: "2.1.3", sift: "17.1.3" }, devDependencies: { "@babel/core": "7.28.3", "@babel/preset-env": "7.28.3", "@mongodb-js/mongodb-downloader": "^0.4.2", "@typescript-eslint/eslint-plugin": "^8.19.1", "@typescript-eslint/parser": "^8.19.1", acquit: "1.4.0", "acquit-ignore": "0.2.1", "acquit-require": "0.1.1", ajv: "8.17.1", "assert-browserify": "2.0.0", "babel-loader": "8.2.5", "broken-link-checker": "^0.7.8", buffer: "^5.6.0", cheerio: "1.1.2", "crypto-browserify": "3.12.1", dox: "1.0.0", eslint: "8.57.1", "eslint-plugin-markdown": "^5.1.0", "eslint-plugin-mocha-no-only": "1.2.0", express: "^4.19.2", "fs-extra": "~11.3.0", "highlight.js": "11.11.1", "lodash.isequal": "4.5.0", "lodash.isequalwith": "4.4.0", "markdownlint-cli2": "^0.18.1", marked: "15.0.12", mkdirp: "^3.0.1", mocha: "11.7.2", moment: "2.30.1", "mongodb-memory-server": "10.2.0", "mongodb-runner": "^5.8.2", ncp: "^2.0.0", nyc: "15.1.0", pug: "3.0.3", q: "1.5.1", sinon: "21.0.0", "stream-browserify": "3.0.0", tsd: "0.33.0", typescript: "5.9.2", uuid: "11.1.0", webpack: "5.101.3" }, directories: { lib: "./lib/mongoose" }, scripts: { "docs:clean": "npm run docs:clean:stable", "docs:clean:stable": "rimraf index.html && rimraf -rf ./docs/*.html && rimraf -rf ./docs/api && rimraf -rf ./docs/tutorials/*.html && rimraf -rf ./docs/typescript/*.html && rimraf -rf ./docs/*.html && rimraf -rf ./docs/source/_docs && rimraf -rf ./tmp", "docs:clean:5x": "rimraf index.html && rimraf -rf ./docs/5.x && rimraf -rf ./docs/source/_docs && rimraf -rf ./tmp", "docs:clean:6x": "rimraf index.html && rimraf -rf ./docs/6.x && rimraf -rf ./docs/source/_docs && rimraf -rf ./tmp", "docs:copy:tmp": "mkdirp ./tmp/docs/css && mkdirp ./tmp/docs/js && mkdirp ./tmp/docs/images && mkdirp ./tmp/docs/tutorials && mkdirp ./tmp/docs/typescript && mkdirp ./tmp/docs/api && ncp ./docs/css ./tmp/docs/css --filter=.css$ && ncp ./docs/js ./tmp/docs/js --filter=.js$ && ncp ./docs/images ./tmp/docs/images && ncp ./docs/tutorials ./tmp/docs/tutorials && ncp ./docs/typescript ./tmp/docs/typescript && ncp ./docs/api ./tmp/docs/api && cp index.html ./tmp && cp docs/*.html ./tmp/docs/", "docs:copy:tmp:5x": "rimraf ./docs/5.x && ncp ./tmp ./docs/5.x", "docs:copy:tmp:6x": "rimraf ./docs/6.x && ncp ./tmp ./docs/6.x", "docs:generate": "node ./scripts/website.js", "docs:generate:sponsorData": "node ./scripts/loadSponsorData.js", "docs:test": "npm run docs:generate", "docs:view": "node ./scripts/static.js", "docs:prepare:publish:stable": "git checkout gh-pages && git merge master && npm run docs:generate", "docs:prepare:publish:5x": "git checkout 5.x && git merge 5.x && npm run docs:clean:stable && npm run docs:generate && npm run docs:copy:tmp && git checkout gh-pages && npm run docs:copy:tmp:5x", "docs:prepare:publish:6x": "git checkout 6.x && git merge 6.x && npm run docs:clean:stable && env DOCS_DEPLOY=true npm run docs:generate && mv ./docs/6.x ./tmp && git checkout gh-pages && npm run docs:copy:tmp:6x", "docs:prepare:publish:7x": "env DOCS_DEPLOY=true npm run docs:generate && git checkout gh-pages && rimraf ./docs/7.x && mv ./tmp ./docs/7.x", "docs:check-links": "blc http://127.0.0.1:8089 -ro", lint: "eslint .", "lint-js": "eslint . --ext .js --ext .cjs", "lint-ts": "eslint . --ext .ts", "lint-md": 'markdownlint-cli2 "**/*.md" "#node_modules" "#benchmarks"', "build-browser": "(rm ./dist/* || true) && node ./scripts/build-browser.js", prepublishOnly: "npm run build-browser", release: "git pull && git push origin master --tags && npm publish", "release-5x": "git pull origin 5.x && git push origin 5.x && git push origin 5.x --tags && npm publish --tag 5x", "release-6x": "git pull origin 6.x && git push origin 6.x && git push origin 6.x --tags && npm publish --tag 6x", mongo: "node ./tools/repl.js", "publish-7x": "npm publish --tag 7x", "create-separate-require-instance": "rm -rf ./node_modules/mongoose-separate-require-instance && node ./scripts/create-tarball && tar -xzf mongoose.tgz -C ./node_modules && mv ./node_modules/package ./node_modules/mongoose-separate-require-instance", test: "mocha --exit ./test/*.test.js", "test-deno": "deno run --allow-env --allow-read --allow-net --allow-run --allow-sys --allow-write ./test/deno.mjs", "test-rs": "START_REPLICA_SET=1 mocha --timeout 30000 --exit ./test/*.test.js", "test-tsd": "node ./test/types/check-types-filename && tsd", "setup-test-encryption": "node scripts/setup-encryption-tests.js", "test-encryption": "mocha --exit ./test/encryption/*.test.js", tdd: "mocha ./test/*.test.js --inspect --watch --recursive --watch-files ./**/*.{js,ts}", "test-coverage": "nyc --reporter=html --reporter=text npm test", "ts-benchmark": "cd ./benchmarks/typescript/simple && npm install && npm run benchmark | node ../../../scripts/tsc-diagnostics-check" }, main: "./index.js", types: "./types/index.d.ts", engines: { node: ">=16.20.1" }, bugs: { url: "https://github.com/Automattic/mongoose/issues/new" }, repository: { type: "git", url: "git://github.com/Automattic/mongoose.git" }, homepage: "https://mongoosejs.com", browser: "./dist/browser.umd.js", config: { mongodbMemoryServer: { disablePostinstall: true } }, funding: { type: "opencollective", url: "https://opencollective.com/mongoose" }, tsd: { directory: "test/types", compilerOptions: { esModuleInterop: false, strict: true, allowSyntheticDefaultImports: true, strictPropertyInitialization: false, noImplicitAny: false, strictNullChecks: true, module: "commonjs", target: "ES2017" } } }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/processConnectionOptions.js var require_processConnectionOptions = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/processConnectionOptions.js"(exports2, module2) { "use strict"; var clone = require_clone(); var MongooseError = require_error2(); function processConnectionOptions(uri, options) { const opts = options ? options : {}; const readPreference = opts.readPreference ? opts.readPreference : getUriReadPreference(uri); const clonedOpts = clone(opts); const resolvedOpts = readPreference && readPreference !== "primary" && readPreference !== "primaryPreferred" ? resolveOptsConflicts(readPreference, clonedOpts) : clonedOpts; return resolvedOpts; } function resolveOptsConflicts(pref, opts) { if (setsIndexOptions(opts) && setsSecondaryRead(pref)) { throwReadPreferenceError(); } else { return defaultIndexOptsToFalse(opts); } } function setsIndexOptions(opts) { const configIdx = opts.config && opts.config.autoIndex; const { autoCreate, autoIndex } = opts; return !!(configIdx || autoCreate || autoIndex); } function setsSecondaryRead(prefString) { return !!(prefString === "secondary" || prefString === "secondaryPreferred"); } function getUriReadPreference(connectionString) { const exp = /(?:&|\?)readPreference=(\w+)(?:&|$)/; const match = exp.exec(connectionString); return match ? match[1] : null; } function defaultIndexOptsToFalse(opts) { opts.config = { autoIndex: false }; opts.autoCreate = false; opts.autoIndex = false; return opts; } function throwReadPreferenceError() { throw new MongooseError( 'MongoDB prohibits index creation on connections that read from non-primary replicas. Connections that set "readPreference" to "secondary" or "secondaryPreferred" may not opt-in to the following connection options: autoCreate, autoIndex' ); } module2.exports = processConnectionOptions; } }); // netlify/functions/node_modules/mongoose/lib/helpers/timers.js var require_timers = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/timers.js"(exports2) { "use strict"; exports2.setTimeout = setTimeout; } }); // netlify/functions/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js var require_connection3 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js"(exports2, module2) { "use strict"; var MongooseConnection = require_connection2(); var MongooseError = require_error2(); var STATES = require_connectionState(); var mongodb = require_lib3(); var pkg = require_package2(); var processConnectionOptions = require_processConnectionOptions(); var setTimeout2 = require_timers().setTimeout; var utils = require_utils3(); var Schema = require_schema2(); function NativeConnection() { MongooseConnection.apply(this, arguments); this._listening = false; this._lastHeartbeatAt = null; } NativeConnection.STATES = STATES; Object.setPrototypeOf(NativeConnection.prototype, MongooseConnection.prototype); NativeConnection.prototype.useDb = function(name, options) { options = options || {}; if (options.useCache && this.relatedDbs[name]) { return this.relatedDbs[name]; } const newConn = new this.constructor(); newConn.name = name; newConn.base = this.base; newConn.collections = {}; newConn.models = {}; newConn.replica = this.replica; newConn.config = Object.assign({}, this.config, newConn.config); newConn.name = this.name; newConn.options = this.options; newConn._readyState = this._readyState; newConn._closeCalled = this._closeCalled; newConn._hasOpened = this._hasOpened; newConn._listening = false; newConn._parent = this; newConn.host = this.host; newConn.port = this.port; newConn.user = this.user; newConn.pass = this.pass; const _this = this; newConn.client = _this.client; if (this.db && this._readyState === STATES.connected) { wireup(); } else { this._queue.push({ fn: wireup }); } function wireup() { newConn.client = _this.client; const _opts = {}; if (options.hasOwnProperty("noListener")) { _opts.noListener = options.noListener; } newConn.db = _this.client.db(name, _opts); newConn._lastHeartbeatAt = _this._lastHeartbeatAt; newConn.onOpen(); } newConn.name = name; if (options.noListener !== true) { this.otherDbs.push(newConn); } newConn.otherDbs.push(this); if (options && options.useCache) { this.relatedDbs[newConn.name] = newConn; newConn.relatedDbs = this.relatedDbs; } return newConn; }; NativeConnection.prototype.aggregate = function aggregate(pipeline, options) { return new this.base.Aggregate(null, this).append(pipeline).option(options ?? {}); }; NativeConnection.prototype.removeDb = function removeDb(name) { const dbs = this.otherDbs.filter((db) => db.name === name); if (!dbs.length) { throw new MongooseError(`No connections to database "${name}" found`); } for (const db of dbs) { db._closeCalled = true; db._destroyCalled = true; db._readyState = STATES.disconnected; db.$wasForceClosed = true; } delete this.relatedDbs[name]; this.otherDbs = this.otherDbs.filter((db) => db.name !== name); }; NativeConnection.prototype.doClose = async function doClose(force) { if (this.client == null) { return this; } let skipCloseClient = false; if (force != null && typeof force === "object") { skipCloseClient = force.skipCloseClient; force = force.force; } if (skipCloseClient) { return this; } await this.client.close(force); await new Promise((resolve) => setTimeout2(resolve, 1)); return this; }; NativeConnection.prototype.listDatabases = async function listDatabases() { await this._waitForConnect(); return await this.db.admin().listDatabases(); }; NativeConnection.prototype.createClient = async function createClient(uri, options) { if (typeof uri !== "string") { throw new MongooseError(`The \`uri\` parameter to \`openUri()\` must be a string, got "${typeof uri}". Make sure the first parameter to \`mongoose.connect()\` or \`mongoose.createConnection()\` is a string.`); } if (this._destroyCalled) { throw new MongooseError( "Connection has been closed and destroyed, and cannot be used for re-opening the connection. Please create a new connection with `mongoose.createConnection()` or `mongoose.connect()`." ); } if (this.readyState === STATES.connecting || this.readyState === STATES.connected) { if (this._connectionString !== uri) { throw new MongooseError("Can't call `openUri()` on an active connection with different connection strings. Make sure you aren't calling `mongoose.connect()` multiple times. See: https://mongoosejs.com/docs/connections.html#multiple_connections"); } } options = processConnectionOptions(uri, options); if (options) { const autoIndex = options.config && options.config.autoIndex != null ? options.config.autoIndex : options.autoIndex; if (autoIndex != null) { this.config.autoIndex = autoIndex !== false; delete options.config; delete options.autoIndex; } if ("autoCreate" in options) { this.config.autoCreate = !!options.autoCreate; delete options.autoCreate; } if ("sanitizeFilter" in options) { this.config.sanitizeFilter = options.sanitizeFilter; delete options.sanitizeFilter; } if ("autoSearchIndex" in options) { this.config.autoSearchIndex = options.autoSearchIndex; delete options.autoSearchIndex; } if ("bufferTimeoutMS" in options) { this.config.bufferTimeoutMS = options.bufferTimeoutMS; delete options.bufferTimeoutMS; } if (options.user || options.pass) { options.auth = options.auth || {}; options.auth.username = options.user; options.auth.password = options.pass; this.user = options.user; this.pass = options.pass; } delete options.user; delete options.pass; if (options.bufferCommands != null) { this.config.bufferCommands = options.bufferCommands; delete options.bufferCommands; } } else { options = {}; } this._connectionOptions = options; const dbName = options.dbName; if (dbName != null) { this.$dbName = dbName; } delete options.dbName; if (!utils.hasUserDefinedProperty(options, "driverInfo")) { options.driverInfo = { name: "Mongoose", version: pkg.version }; } const { schemaMap, encryptedFieldsMap } = this._buildEncryptionSchemas(); if ((Object.keys(schemaMap).length > 0 || Object.keys(encryptedFieldsMap).length) && !options.autoEncryption) { throw new Error("Must provide `autoEncryption` when connecting with encrypted schemas."); } if (Object.keys(schemaMap).length > 0) { options.autoEncryption.schemaMap = schemaMap; } if (Object.keys(encryptedFieldsMap).length > 0) { options.autoEncryption.encryptedFieldsMap = encryptedFieldsMap; } this.readyState = STATES.connecting; this._connectionString = uri; let client; try { client = new mongodb.MongoClient(uri, options); } catch (error) { this.readyState = STATES.disconnected; throw error; } this.client = client; client.setMaxListeners(0); await client.connect(); _setClient(this, client, options, dbName); for (const db of this.otherDbs) { _setClient(db, client, {}, db.name); } return this; }; NativeConnection.prototype._buildEncryptionSchemas = function() { const qeMappings = {}; const csfleMappings = {}; const encryptedModels = Object.values(this.models).filter((model) => model.schema._hasEncryptedFields()); for (const model of encryptedModels) { const { schema, collection: { collectionName } } = model; const namespace = `${this.$dbName}.${collectionName}`; const mappings = schema.encryptionType() === "csfle" ? csfleMappings : qeMappings; mappings[namespace] ??= new Schema({}, { encryptionType: schema.encryptionType() }); const isNonRootDiscriminator = schema.discriminatorMapping && !schema.discriminatorMapping.isRoot; if (isNonRootDiscriminator) { const rootSchema = schema._baseSchema; schema.eachPath((pathname) => { if (rootSchema.path(pathname)) return; if (!mappings[namespace]._hasEncryptedField(pathname)) return; throw new Error(`Cannot have duplicate keys in discriminators with encryption. key=${pathname}`); }); } mappings[namespace].add(schema); } const schemaMap = Object.fromEntries(Object.entries(csfleMappings).map( ([namespace, schema]) => [namespace, schema._buildSchemaMap()] )); const encryptedFieldsMap = Object.fromEntries(Object.entries(qeMappings).map( ([namespace, schema]) => [namespace, schema._buildEncryptedFields()] )); return { schemaMap, encryptedFieldsMap }; }; NativeConnection.prototype.setClient = function setClient(client) { if (!(client instanceof mongodb.MongoClient)) { throw new MongooseError("Must call `setClient()` with an instance of MongoClient"); } if (this.readyState !== STATES.disconnected) { throw new MongooseError("Cannot call `setClient()` on a connection that is already connected."); } if (client.topology == null) { throw new MongooseError("Cannot call `setClient()` with a MongoClient that you have not called `connect()` on yet."); } this._connectionString = client.s.url; _setClient(this, client, {}, client.s.options.dbName); for (const model of Object.values(this.models)) { model.init().catch(function $modelInitNoop() { }); } return this; }; function _setClient(conn, client, options, dbName) { const db = dbName != null ? client.db(dbName) : client.db(); conn.db = db; conn.client = client; conn.host = client && client.s && client.s.options && client.s.options.hosts && client.s.options.hosts[0] && client.s.options.hosts[0].host || void 0; conn.port = client && client.s && client.s.options && client.s.options.hosts && client.s.options.hosts[0] && client.s.options.hosts[0].port || void 0; conn.name = dbName != null ? dbName : db.databaseName; conn._closeCalled = client._closeCalled; const _handleReconnect = () => { if (conn.readyState !== STATES.connected) { conn.readyState = STATES.connected; conn.emit("reconnect"); conn.emit("reconnected"); conn.onOpen(); } }; const type = client && client.topology && client.topology.description && client.topology.description.type || ""; if (type === "Single") { client.on("serverDescriptionChanged", (ev) => { const newDescription = ev.newDescription; if (newDescription.type === "Unknown") { conn.readyState = STATES.disconnected; } else { _handleReconnect(); } }); } else if (type.startsWith("ReplicaSet")) { client.on("topologyDescriptionChanged", (ev) => { const description = ev.newDescription; if (conn.readyState === STATES.connected && description.type !== "ReplicaSetWithPrimary") { conn.readyState = STATES.disconnected; } else if (conn.readyState === STATES.disconnected && description.type === "ReplicaSetWithPrimary") { _handleReconnect(); } }); } conn._lastHeartbeatAt = null; client.on("serverHeartbeatSucceeded", () => { conn._lastHeartbeatAt = Date.now(); for (const otherDb of conn.otherDbs) { otherDb._lastHeartbeatAt = conn._lastHeartbeatAt; } }); if (options.monitorCommands) { client.on("commandStarted", (data) => conn.emit("commandStarted", data)); client.on("commandFailed", (data) => conn.emit("commandFailed", data)); client.on("commandSucceeded", (data) => conn.emit("commandSucceeded", data)); } conn.onOpen(); for (const i in conn.collections) { if (utils.object.hasOwnProperty(conn.collections, i)) { conn.collections[i].onOpen(); } } } module2.exports = NativeConnection; } }); // netlify/functions/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js var require_node_mongodb_native = __commonJS({ "netlify/functions/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js"(exports2) { "use strict"; exports2.BulkWriteResult = require_bulkWriteResult(); exports2.Collection = require_collection3(); exports2.Connection = require_connection3(); exports2.ClientEncryption = require_lib3().ClientEncryption; } }); // netlify/functions/node_modules/mongoose/lib/validOptions.js var require_validOptions = __commonJS({ "netlify/functions/node_modules/mongoose/lib/validOptions.js"(exports2, module2) { "use strict"; var VALID_OPTIONS = Object.freeze([ "allowDiskUse", "applyPluginsToChildSchemas", "applyPluginsToDiscriminators", "autoCreate", "autoIndex", "autoSearchIndex", "bufferCommands", "bufferTimeoutMS", "cloneSchemas", "createInitialConnection", "debug", "forceRepopulate", "id", "timestamps.createdAt.immutable", "maxTimeMS", "objectIdGetter", "overwriteModels", "returnOriginal", "runValidators", "sanitizeFilter", "sanitizeProjection", "selectPopulatedPaths", "setDefaultsOnInsert", "skipOriginalStackTraces", "strict", "strictPopulate", "strictQuery", "toJSON", "toObject", "transactionAsyncLocalStorage", "translateAliases" ]); module2.exports = VALID_OPTIONS; } }); // netlify/functions/node_modules/mongoose/lib/error/eachAsyncMultiError.js var require_eachAsyncMultiError = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/eachAsyncMultiError.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var EachAsyncMultiError = class extends MongooseError { /** * @param {String} connectionString */ constructor(errors) { let preview = errors.map((e) => e.message).join(", "); if (preview.length > 50) { preview = preview.slice(0, 50) + "..."; } super(`eachAsync() finished with ${errors.length} errors: ${preview}`); this.errors = errors; } }; Object.defineProperty(EachAsyncMultiError.prototype, "name", { value: "EachAsyncMultiError" }); module2.exports = EachAsyncMultiError; } }); // netlify/functions/node_modules/mongoose/lib/helpers/cursor/eachAsync.js var require_eachAsync = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/cursor/eachAsync.js"(exports2, module2) { "use strict"; var EachAsyncMultiError = require_eachAsyncMultiError(); var immediate = require_immediate(); module2.exports = async function eachAsync(next, fn, options) { const parallel = options.parallel || 1; const batchSize = options.batchSize; const signal = options.signal; const continueOnError = options.continueOnError; const aggregatedErrors = []; const enqueue = asyncQueue(); let aborted = false; return new Promise((resolve, reject) => { if (signal != null) { if (signal.aborted) { return resolve(null); } signal.addEventListener("abort", () => { aborted = true; return resolve(null); }, { once: true }); } if (batchSize != null) { if (typeof batchSize !== "number") { throw new TypeError("batchSize must be a number"); } else if (!Number.isInteger(batchSize)) { throw new TypeError("batchSize must be an integer"); } else if (batchSize < 1) { throw new TypeError("batchSize must be at least 1"); } } iterate((err, res) => { if (err != null) { return reject(err); } resolve(res); }); }); function iterate(finalCallback) { let handleResultsInProgress = 0; let currentDocumentIndex = 0; let error = null; for (let i = 0; i < parallel; ++i) { enqueue(createFetch()); } function createFetch() { let documentsBatch = []; let drained = false; return fetch; function fetch(done) { if (drained || aborted) { return done(); } else if (error) { return done(); } next(function(err, doc) { if (error != null) { return done(); } if (err != null) { if (err.name === "MongoCursorExhaustedError") { doc = null; } else if (continueOnError) { aggregatedErrors.push(err); } else { error = err; finalCallback(err); return done(); } } if (doc == null) { drained = true; if (handleResultsInProgress <= 0) { const finalErr = continueOnError ? createEachAsyncMultiError(aggregatedErrors) : error; finalCallback(finalErr); } else if (batchSize && documentsBatch.length) { handleNextResult(documentsBatch, currentDocumentIndex++, handleNextResultCallBack); } return done(); } ++handleResultsInProgress; immediate(() => done()); if (batchSize) { documentsBatch.push(doc); } if (batchSize && documentsBatch.length !== batchSize) { immediate(() => enqueue(fetch)); return; } const docsToProcess = batchSize ? documentsBatch : doc; function handleNextResultCallBack(err2) { if (batchSize) { handleResultsInProgress -= documentsBatch.length; documentsBatch = []; } else { --handleResultsInProgress; } if (err2 != null) { if (continueOnError) { aggregatedErrors.push(err2); } else { error = err2; return finalCallback(err2); } } if ((drained || aborted) && handleResultsInProgress <= 0) { const finalErr = continueOnError ? createEachAsyncMultiError(aggregatedErrors) : error; return finalCallback(finalErr); } immediate(() => enqueue(fetch)); } handleNextResult(docsToProcess, currentDocumentIndex++, handleNextResultCallBack); }); } } } function handleNextResult(doc, i, callback) { let maybePromise; try { maybePromise = fn(doc, i); } catch (err) { return callback(err); } if (maybePromise && typeof maybePromise.then === "function") { maybePromise.then( function() { callback(null); }, function(error) { callback(error || new Error("`eachAsync()` promise rejected without error")); } ); } else { callback(null); } } }; function asyncQueue() { const _queue = []; let inProgress = null; let id = 0; return function enqueue(fn) { if (inProgress === null && _queue.length === 0) { inProgress = id++; return fn(_step); } _queue.push(fn); }; function _step() { if (_queue.length !== 0) { inProgress = id++; const fn = _queue.shift(); fn(_step); } else { inProgress = null; } } } function createEachAsyncMultiError(aggregatedErrors) { if (aggregatedErrors.length === 0) { return null; } return new EachAsyncMultiError(aggregatedErrors); } } }); // netlify/functions/node_modules/mongoose/lib/cursor/queryCursor.js var require_queryCursor = __commonJS({ "netlify/functions/node_modules/mongoose/lib/cursor/queryCursor.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var Readable = require("stream").Readable; var eachAsync = require_eachAsync(); var helpers = require_queryHelpers(); var kareem = require_kareem(); var immediate = require_immediate(); var { once } = require("events"); var util = require("util"); function QueryCursor(query) { Readable.call(this, { autoDestroy: true, objectMode: true }); this.cursor = null; this.skipped = false; this.query = query; this._closed = false; const model = query.model; this._mongooseOptions = {}; this._transforms = []; this.model = model; this.options = {}; model.hooks.execPre("find", query, (err) => { if (err != null) { if (err instanceof kareem.skipWrappedFunction) { const resultValue = err.args[0]; if (resultValue != null && (!Array.isArray(resultValue) || resultValue.length)) { const err2 = new MongooseError( 'Cannot `skipMiddlewareFunction()` with a value when using `.find().cursor()`, value must be nullish or empty array, got "' + util.inspect(resultValue) + '".' ); this._markError(err2); this.listeners("error").length > 0 && this.emit("error", err2); return; } this.skipped = true; this.emit("cursor", null); return; } this._markError(err); this.listeners("error").length > 0 && this.emit("error", err); return; } Object.assign(this.options, query._optionsForExec()); this._transforms = this._transforms.concat(query._transforms.slice()); if (this.options.transform) { this._transforms.push(this.options.transform); } if (this.options.batchSize) { this.options._populateBatchSize = Math.min(this.options.batchSize, 5e3); } if (query._mongooseOptions._asyncIterator) { this._mongooseOptions._asyncIterator = true; } if (model.collection._shouldBufferCommands() && model.collection.buffer) { model.collection.queue.push([ () => _getRawCursor(query, this) ]); } else { _getRawCursor(query, this); } }); } util.inherits(QueryCursor, Readable); function _getRawCursor(query, queryCursor) { try { const cursor = query.model.collection.find(query._conditions, queryCursor.options); queryCursor.cursor = cursor; queryCursor.emit("cursor", cursor); } catch (err) { queryCursor._markError(err); queryCursor.listeners("error").length > 0 && queryCursor.emit("error", queryCursor._error); } } QueryCursor.prototype._read = function() { _next(this, (error, doc) => { if (error) { return this.emit("error", error); } if (!doc) { this.push(null); this.cursor.close(function(error2) { if (error2) { return this.emit("error", error2); } }); return; } this.push(doc); }); }; QueryCursor.prototype.getDriverCursor = async function getDriverCursor() { if (this.cursor) { return this.cursor; } await once(this, "cursor"); return this.cursor; }; Object.defineProperty(QueryCursor.prototype, "map", { value: function(fn) { this._transforms.push(fn); return this; }, enumerable: true, configurable: true, writable: true }); QueryCursor.prototype._markError = function(error) { this._error = error; return this; }; QueryCursor.prototype.close = async function close() { if (typeof arguments[0] === "function") { throw new MongooseError("QueryCursor.prototype.close() no longer accepts a callback"); } try { await this.cursor.close(); this._closed = true; this.emit("close"); } catch (error) { this.listeners("error").length > 0 && this.emit("error", error); throw error; } }; QueryCursor.prototype._destroy = function _destroy(_err, callback) { let waitForCursor = null; if (!this.cursor) { waitForCursor = new Promise((resolve) => { this.once("cursor", resolve); }); } else { waitForCursor = Promise.resolve(); } waitForCursor.then(() => { this.cursor.close(); }).then(() => { this._closed = true; callback(); }).catch((error) => { callback(error); }); return this; }; QueryCursor.prototype.rewind = function() { _waitForCursor(this, () => { this.cursor.rewind(); }); return this; }; QueryCursor.prototype.next = async function next() { if (typeof arguments[0] === "function") { throw new MongooseError("QueryCursor.prototype.next() no longer accepts a callback"); } if (this._closed) { throw new MongooseError("Cannot call `next()` on a closed cursor"); } return new Promise((resolve, reject) => { _next(this, function(error, doc) { if (error) { return reject(error); } resolve(doc); }); }); }; QueryCursor.prototype.eachAsync = function(fn, opts) { if (typeof arguments[2] === "function") { throw new MongooseError("QueryCursor.prototype.eachAsync() no longer accepts a callback"); } if (typeof opts === "function") { opts = {}; } opts = opts || {}; return eachAsync((cb) => _next(this, cb), fn, opts); }; QueryCursor.prototype.options; QueryCursor.prototype.addCursorFlag = function(flag, value) { _waitForCursor(this, () => { this.cursor.addCursorFlag(flag, value); }); return this; }; if (Symbol.asyncIterator != null) { QueryCursor.prototype[Symbol.asyncIterator] = function queryCursorAsyncIterator() { this._mongooseOptions._asyncIterator = true; return this; }; } function _next(ctx, cb) { let callback = cb; callback = function(err, doc) { if (err) { return cb(err); } if (doc === null) { if (ctx._mongooseOptions._asyncIterator) { return cb(null, { done: true }); } else { return cb(null, null); } } if (ctx._transforms.length && doc !== null) { doc = ctx._transforms.reduce(function(doc2, fn) { return fn.call(ctx, doc2); }, doc); } if (ctx._mongooseOptions._asyncIterator) { return cb(null, { value: doc, done: false }); } return cb(null, doc); }; if (ctx._error) { return immediate(function() { callback(ctx._error); }); } if (ctx.skipped) { return immediate(() => callback(null, null)); } if (ctx.cursor) { if (ctx.query._mongooseOptions.populate && !ctx._pop) { ctx._pop = helpers.preparePopulationOptionsMQ( ctx.query, ctx.query._mongooseOptions ); ctx._pop.__noPromise = true; } if (ctx.query._mongooseOptions.populate && ctx.options._populateBatchSize > 1) { if (ctx._batchDocs && ctx._batchDocs.length) { return _nextDoc(ctx, ctx._batchDocs.shift(), ctx._pop, callback); } else if (ctx._batchExhausted) { return callback(null, null); } else { ctx._batchDocs = []; ctx.cursor.next().then( (res) => { _onNext.call({ ctx, callback }, null, res); }, (err) => { _onNext.call({ ctx, callback }, err); } ); return; } } else { return ctx.cursor.next().then( (doc) => { if (!doc) { callback(null, null); return; } if (!ctx.query._mongooseOptions.populate) { return _nextDoc(ctx, doc, null, callback); } _nextDoc(ctx, doc, ctx._pop, (err, doc2) => { if (err != null) { return callback(err); } ctx.query.model.populate(doc2, ctx._pop).then( (doc3) => callback(null, doc3), (err2) => callback(err2) ); }); }, (error) => { callback(error); } ); } } else { ctx.once("error", cb); ctx.once("cursor", function(cursor) { ctx.removeListener("error", cb); if (cursor == null) { if (ctx.skipped) { return cb(null, null); } return; } _next(ctx, cb); }); } } function _onNext(error, doc) { if (error) { return this.callback(error); } if (!doc) { this.ctx._batchExhausted = true; return _populateBatch.call(this); } this.ctx._batchDocs.push(doc); if (this.ctx._batchDocs.length < this.ctx.options._populateBatchSize) { immediate(() => this.ctx.cursor.next().then( (res) => { _onNext.call(this, null, res); }, (err) => { _onNext.call(this, err); } )); } else { _populateBatch.call(this); } } function _populateBatch() { if (!this.ctx._batchDocs.length) { return this.callback(null, null); } this.ctx.query.model.populate(this.ctx._batchDocs, this.ctx._pop).then( () => { _nextDoc(this.ctx, this.ctx._batchDocs.shift(), this.ctx._pop, this.callback); }, (err) => { this.callback(err); } ); } function _nextDoc(ctx, doc, pop, callback) { if (ctx.query._mongooseOptions.lean) { return ctx.model.hooks.execPost("find", ctx.query, [[doc]], (err) => { if (err != null) { return callback(err); } callback(null, doc); }); } const { model, _fields, _userProvidedFields, options } = ctx.query; helpers.createModelAndInit(model, doc, _fields, _userProvidedFields, options, pop, (err, doc2) => { if (err != null) { return callback(err); } ctx.model.hooks.execPost("find", ctx.query, [[doc2]], (err2) => { if (err2 != null) { return callback(err2); } callback(null, doc2); }); }); } function _waitForCursor(ctx, cb) { if (ctx.cursor) { return cb(); } ctx.once("cursor", function(cursor) { if (cursor == null) { return; } cb(); }); } module2.exports = QueryCursor; } }); // netlify/functions/node_modules/mongoose/lib/helpers/query/applyGlobalOption.js var require_applyGlobalOption = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/query/applyGlobalOption.js"(exports2, module2) { "use strict"; var utils = require_utils3(); function applyGlobalMaxTimeMS(options, connectionOptions, baseOptions) { applyGlobalOption(options, connectionOptions, baseOptions, "maxTimeMS"); } function applyGlobalDiskUse(options, connectionOptions, baseOptions) { applyGlobalOption(options, connectionOptions, baseOptions, "allowDiskUse"); } module2.exports = { applyGlobalMaxTimeMS, applyGlobalDiskUse }; function applyGlobalOption(options, connectionOptions, baseOptions, optionName) { if (utils.hasUserDefinedProperty(options, optionName)) { return; } if (utils.hasUserDefinedProperty(connectionOptions, optionName)) { options[optionName] = connectionOptions[optionName]; } else if (utils.hasUserDefinedProperty(baseOptions, optionName)) { options[optionName] = baseOptions[optionName]; } } } }); // netlify/functions/node_modules/mongoose/lib/helpers/schema/applyReadConcern.js var require_applyReadConcern = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/schema/applyReadConcern.js"(exports2, module2) { "use strict"; module2.exports = function applyReadConcern(schema, options) { if (options.readConcern !== void 0) { return; } if (options && options.session && options.session.transaction) { return; } const level = schema.options?.readConcern?.level; if (level != null) { options.readConcern = { level }; } }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/schema/applyWriteConcern.js var require_applyWriteConcern = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/schema/applyWriteConcern.js"(exports2, module2) { "use strict"; module2.exports = function applyWriteConcern(schema, options) { if (options.writeConcern != null) { return; } if (options && options.session && options.session.transaction) { return; } const writeConcern = schema.options.writeConcern ?? {}; if (Object.keys(writeConcern).length != 0) { options.writeConcern = {}; if (!("w" in options) && writeConcern.w != null) { options.writeConcern.w = writeConcern.w; } if (!("j" in options) && writeConcern.j != null) { options.writeConcern.j = writeConcern.j; } if (!("wtimeout" in options) && writeConcern.wtimeout != null) { options.writeConcern.wtimeout = writeConcern.wtimeout; } } else { if (!("w" in options) && writeConcern.w != null) { options.w = writeConcern.w; } if (!("j" in options) && writeConcern.j != null) { options.j = writeConcern.j; } if (!("wtimeout" in options) && writeConcern.wtimeout != null) { options.wtimeout = writeConcern.wtimeout; } } }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/query/castFilterPath.js var require_castFilterPath = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/query/castFilterPath.js"(exports2, module2) { "use strict"; var isOperator = require_isOperator(); module2.exports = function castFilterPath(ctx, schematype, val) { const any$conditionals = Object.keys(val).some(isOperator); if (!any$conditionals) { return schematype.castForQuery( null, val, ctx ); } const ks = Object.keys(val); let k = ks.length; while (k--) { const $cond = ks[k]; const nested = val[$cond]; if ($cond === "$not") { if (nested && schematype && !schematype.caster) { const _keys = Object.keys(nested); if (_keys.length && isOperator(_keys[0])) { for (const key of Object.keys(nested)) { nested[key] = schematype.castForQuery( key, nested[key], ctx ); } } else { val[$cond] = schematype.castForQuery( $cond, nested, ctx ); } continue; } } else { val[$cond] = schematype.castForQuery( $cond, nested, ctx ); } } return val; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/schema/getPath.js var require_getPath = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/schema/getPath.js"(exports2, module2) { "use strict"; var numberRE = /^\d+$/; module2.exports = function getPath(schema, path, discriminatorValueMap) { let schematype = schema.path(path); if (schematype != null) { return schematype; } const pieces = path.split("."); let cur = ""; let isArray = false; for (const piece of pieces) { if (isArray && numberRE.test(piece)) { continue; } cur = cur.length === 0 ? piece : cur + "." + piece; schematype = schema.path(cur); if (schematype != null && schematype.schema) { schema = schematype.schema; if (!isArray && schematype.$isMongooseDocumentArray) { isArray = true; } if (discriminatorValueMap && discriminatorValueMap[cur]) { schema = schema.discriminators[discriminatorValueMap[cur]] ?? schema; } cur = ""; } } return schematype; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/update/castArrayFilters.js var require_castArrayFilters = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/update/castArrayFilters.js"(exports2, module2) { "use strict"; var castFilterPath = require_castFilterPath(); var cleanPositionalOperators = require_cleanPositionalOperators(); var getPath = require_getPath(); var updatedPathsByArrayFilter = require_updatedPathsByArrayFilter(); module2.exports = function castArrayFilters(query) { const arrayFilters = query.options.arrayFilters; const update = query.getUpdate(); const schema = query.schema; const updatedPathsByFilter = updatedPathsByArrayFilter(update); let strictQuery = schema.options.strict; if (query._mongooseOptions.strict != null) { strictQuery = query._mongooseOptions.strict; } if (query.model && query.model.base.options.strictQuery != null) { strictQuery = query.model.base.options.strictQuery; } if (schema._userProvidedOptions.strictQuery != null) { strictQuery = schema._userProvidedOptions.strictQuery; } if (query._mongooseOptions.strictQuery != null) { strictQuery = query._mongooseOptions.strictQuery; } _castArrayFilters(arrayFilters, schema, strictQuery, updatedPathsByFilter, query); }; function _castArrayFilters(arrayFilters, schema, strictQuery, updatedPathsByFilter, query) { if (!Array.isArray(arrayFilters)) { return; } const discriminatorValueMap = {}; for (const filter of arrayFilters) { if (filter == null) { throw new Error(`Got null array filter in ${arrayFilters}`); } const keys = Object.keys(filter).filter((key) => filter[key] != null); if (keys.length === 0) { continue; } const firstKey = keys[0]; if (firstKey === "$and" || firstKey === "$or") { for (const key of keys) { _castArrayFilters(filter[key], schema, strictQuery, updatedPathsByFilter, query); } continue; } const dot = firstKey.indexOf("."); const filterWildcardPath = dot === -1 ? firstKey : firstKey.substring(0, dot); if (updatedPathsByFilter[filterWildcardPath] == null) { continue; } const baseFilterPath = cleanPositionalOperators( updatedPathsByFilter[filterWildcardPath] ); const baseSchematype = getPath(schema, baseFilterPath, discriminatorValueMap); let filterBaseSchema = baseSchematype != null ? baseSchematype.schema : null; if (filterBaseSchema != null && filterBaseSchema.discriminators != null && filter[filterWildcardPath + "." + filterBaseSchema.options.discriminatorKey]) { filterBaseSchema = filterBaseSchema.discriminators[filter[filterWildcardPath + "." + filterBaseSchema.options.discriminatorKey]] || filterBaseSchema; discriminatorValueMap[baseFilterPath] = filter[filterWildcardPath + "." + filterBaseSchema.options.discriminatorKey]; } for (const key of keys) { if (updatedPathsByFilter[key] === null) { continue; } if (Object.keys(updatedPathsByFilter).length === 0) { continue; } const dot2 = key.indexOf("."); let filterPathRelativeToBase = dot2 === -1 ? null : key.substring(dot2); let schematype; if (filterPathRelativeToBase == null || filterBaseSchema == null) { schematype = baseSchematype; } else { filterPathRelativeToBase = cleanPositionalOperators(filterPathRelativeToBase); schematype = getPath(filterBaseSchema, filterPathRelativeToBase, discriminatorValueMap); } if (schematype == null) { if (!strictQuery) { return; } const filterPath = filterPathRelativeToBase == null ? baseFilterPath + ".0" : baseFilterPath + ".0" + filterPathRelativeToBase; throw new Error(`Could not find path "${filterPath}" in schema`); } if (typeof filter[key] === "object") { filter[key] = castFilterPath(query, schematype, filter[key]); } else { filter[key] = schematype.castForQuery(null, filter[key]); } } } } } }); // netlify/functions/node_modules/mongoose/lib/helpers/projection/isInclusive.js var require_isInclusive = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/projection/isInclusive.js"(exports2, module2) { "use strict"; var isDefiningProjection = require_isDefiningProjection(); var isPOJO = require_isPOJO(); module2.exports = function isInclusive(projection) { if (projection == null) { return false; } const props = Object.keys(projection); const numProps = props.length; if (numProps === 0) { return false; } for (let i = 0; i < numProps; ++i) { const prop = props[i]; if (prop.startsWith("+")) { continue; } if (isDefiningProjection(projection[prop]) && !!projection[prop]) { if (isPOJO(projection[prop])) { return isInclusive(projection[prop]); } else { return !!projection[prop]; } } } return false; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/projection/isSubpath.js var require_isSubpath = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/projection/isSubpath.js"(exports2, module2) { "use strict"; module2.exports = function isSubpath(path1, path2) { return path1 === path2 || path2.startsWith(path1 + "."); }; } }); // netlify/functions/node_modules/mquery/lib/utils.js var require_utils4 = __commonJS({ "netlify/functions/node_modules/mquery/lib/utils.js"(exports2) { "use strict"; var specialProperties = ["__proto__", "constructor", "prototype"]; var clone = exports2.clone = function clone2(obj, options) { if (obj === void 0 || obj === null) return obj; if (Array.isArray(obj)) return exports2.cloneArray(obj, options); if (obj.constructor) { if (/ObjectI[dD]$/.test(obj.constructor.name)) { return "function" == typeof obj.clone ? obj.clone() : new obj.constructor(obj.id); } if (obj.constructor.name === "ReadPreference") { return new obj.constructor(obj.mode, clone2(obj.tags, options)); } if ("Binary" == obj._bsontype && obj.buffer && obj.value) { return "function" == typeof obj.clone ? obj.clone() : new obj.constructor(obj.value(true), obj.sub_type); } if ("Date" === obj.constructor.name || "Function" === obj.constructor.name) return new obj.constructor(+obj); if ("RegExp" === obj.constructor.name) return new RegExp(obj); if ("Buffer" === obj.constructor.name) return Buffer.from(obj); } if (isObject(obj)) return exports2.cloneObject(obj, options); if (obj.valueOf) return obj.valueOf(); }; exports2.cloneObject = function cloneObject(obj, options) { const minimize = options && options.minimize, ret = {}, keys = Object.keys(obj), len = keys.length; let hasKeys = false, val, k = "", i = 0; for (i = 0; i < len; ++i) { k = keys[i]; if (specialProperties.indexOf(k) !== -1) { continue; } val = clone(obj[k], options); if (!minimize || "undefined" !== typeof val) { hasKeys || (hasKeys = true); ret[k] = val; } } return minimize ? hasKeys && ret : ret; }; exports2.cloneArray = function cloneArray(arr, options) { const ret = [], l = arr.length; let i = 0; for (; i < l; i++) ret.push(clone(arr[i], options)); return ret; }; exports2.merge = function merge(to, from) { const keys = Object.keys(from); for (const key of keys) { if (specialProperties.indexOf(key) !== -1) { continue; } if ("undefined" === typeof to[key]) { to[key] = from[key]; } else { if (exports2.isObject(from[key])) { merge(to[key], from[key]); } else { to[key] = from[key]; } } } }; exports2.mergeClone = function mergeClone(to, from) { const keys = Object.keys(from); for (const key of keys) { if (specialProperties.indexOf(key) !== -1) { continue; } if ("undefined" === typeof to[key]) { to[key] = clone(from[key]); } else { if (exports2.isObject(from[key])) { mergeClone(to[key], from[key]); } else { to[key] = clone(from[key]); } } } }; exports2.readPref = function readPref(pref) { switch (pref) { case "p": pref = "primary"; break; case "pp": pref = "primaryPreferred"; break; case "s": pref = "secondary"; break; case "sp": pref = "secondaryPreferred"; break; case "n": pref = "nearest"; break; } return pref; }; exports2.readConcern = function readConcern(concern) { if ("string" === typeof concern) { switch (concern) { case "l": concern = "local"; break; case "a": concern = "available"; break; case "m": concern = "majority"; break; case "lz": concern = "linearizable"; break; case "s": concern = "snapshot"; break; } concern = { level: concern }; } return concern; }; var _toString = Object.prototype.toString; exports2.toString = function(arg) { return _toString.call(arg); }; var isObject = exports2.isObject = function(arg) { return "[object Object]" == exports2.toString(arg); }; exports2.keys = Object.keys; exports2.create = "function" == typeof Object.create ? Object.create : create; function create(proto) { if (arguments.length > 1) { throw new Error("Adding properties is not supported"); } function F() { } F.prototype = proto; return new F(); } exports2.inherits = function(ctor, superCtor) { ctor.prototype = exports2.create(superCtor.prototype); ctor.prototype.constructor = ctor; }; exports2.isArgumentsObject = function(v) { return Object.prototype.toString.call(v) === "[object Arguments]"; }; } }); // netlify/functions/node_modules/debug/src/common.js var require_common4 = __commonJS({ "netlify/functions/node_modules/debug/src/common.js"(exports2, module2) { function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; createDebug.coerce = coerce; createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; createDebug.humanize = require_ms(); createDebug.destroy = destroy; Object.keys(env).forEach((key) => { createDebug[key] = env[key]; }); createDebug.names = []; createDebug.skips = []; createDebug.formatters = {}; function selectColor(namespace) { let hash = 0; for (let i = 0; i < namespace.length; i++) { hash = (hash << 5) - hash + namespace.charCodeAt(i); hash |= 0; } return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; } createDebug.selectColor = selectColor; function createDebug(namespace) { let prevTime; let enableOverride = null; let namespacesCache; let enabledCache; function debug(...args) { if (!debug.enabled) { return; } const self2 = debug; const curr = Number(/* @__PURE__ */ new Date()); const ms = curr - (prevTime || curr); self2.diff = ms; self2.prev = prevTime; self2.curr = curr; prevTime = curr; args[0] = createDebug.coerce(args[0]); if (typeof args[0] !== "string") { args.unshift("%O"); } let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { if (match === "%%") { return "%"; } index++; const formatter = createDebug.formatters[format]; if (typeof formatter === "function") { const val = args[index]; match = formatter.call(self2, val); args.splice(index, 1); index--; } return match; }); createDebug.formatArgs.call(self2, args); const logFn = self2.log || createDebug.log; logFn.apply(self2, args); } debug.namespace = namespace; debug.useColors = createDebug.useColors(); debug.color = createDebug.selectColor(namespace); debug.extend = extend; debug.destroy = createDebug.destroy; Object.defineProperty(debug, "enabled", { enumerable: true, configurable: false, get: () => { if (enableOverride !== null) { return enableOverride; } if (namespacesCache !== createDebug.namespaces) { namespacesCache = createDebug.namespaces; enabledCache = createDebug.enabled(namespace); } return enabledCache; }, set: (v) => { enableOverride = v; } }); if (typeof createDebug.init === "function") { createDebug.init(debug); } return debug; } function extend(namespace, delimiter) { const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); newDebug.log = this.log; return newDebug; } function enable(namespaces) { createDebug.save(namespaces); createDebug.namespaces = namespaces; createDebug.names = []; createDebug.skips = []; const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); for (const ns of split) { if (ns[0] === "-") { createDebug.skips.push(ns.slice(1)); } else { createDebug.names.push(ns); } } } function matchesTemplate(search, template) { let searchIndex = 0; let templateIndex = 0; let starIndex = -1; let matchIndex = 0; while (searchIndex < search.length) { if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { if (template[templateIndex] === "*") { starIndex = templateIndex; matchIndex = searchIndex; templateIndex++; } else { searchIndex++; templateIndex++; } } else if (starIndex !== -1) { templateIndex = starIndex + 1; matchIndex++; searchIndex = matchIndex; } else { return false; } } while (templateIndex < template.length && template[templateIndex] === "*") { templateIndex++; } return templateIndex === template.length; } function disable() { const namespaces = [ ...createDebug.names, ...createDebug.skips.map((namespace) => "-" + namespace) ].join(","); createDebug.enable(""); return namespaces; } function enabled(name) { for (const skip of createDebug.skips) { if (matchesTemplate(name, skip)) { return false; } } for (const ns of createDebug.names) { if (matchesTemplate(name, ns)) { return true; } } return false; } function coerce(val) { if (val instanceof Error) { return val.stack || val.message; } return val; } function destroy() { console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); } createDebug.enable(createDebug.load()); return createDebug; } module2.exports = setup; } }); // netlify/functions/node_modules/debug/src/browser.js var require_browser = __commonJS({ "netlify/functions/node_modules/debug/src/browser.js"(exports2, module2) { exports2.formatArgs = formatArgs; exports2.save = save; exports2.load = load; exports2.useColors = useColors; exports2.storage = localstorage(); exports2.destroy = /* @__PURE__ */ (() => { let warned = false; return () => { if (!warned) { warned = true; console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); } }; })(); exports2.colors = [ "#0000CC", "#0000FF", "#0033CC", "#0033FF", "#0066CC", "#0066FF", "#0099CC", "#0099FF", "#00CC00", "#00CC33", "#00CC66", "#00CC99", "#00CCCC", "#00CCFF", "#3300CC", "#3300FF", "#3333CC", "#3333FF", "#3366CC", "#3366FF", "#3399CC", "#3399FF", "#33CC00", "#33CC33", "#33CC66", "#33CC99", "#33CCCC", "#33CCFF", "#6600CC", "#6600FF", "#6633CC", "#6633FF", "#66CC00", "#66CC33", "#9900CC", "#9900FF", "#9933CC", "#9933FF", "#99CC00", "#99CC33", "#CC0000", "#CC0033", "#CC0066", "#CC0099", "#CC00CC", "#CC00FF", "#CC3300", "#CC3333", "#CC3366", "#CC3399", "#CC33CC", "#CC33FF", "#CC6600", "#CC6633", "#CC9900", "#CC9933", "#CCCC00", "#CCCC33", "#FF0000", "#FF0033", "#FF0066", "#FF0099", "#FF00CC", "#FF00FF", "#FF3300", "#FF3333", "#FF3366", "#FF3399", "#FF33CC", "#FF33FF", "#FF6600", "#FF6633", "#FF9900", "#FF9933", "#FFCC00", "#FFCC33" ]; function useColors() { if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { return true; } if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } let m; return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); } function formatArgs(args) { args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff); if (!this.useColors) { return; } const c = "color: " + this.color; args.splice(1, 0, c, "color: inherit"); let index = 0; let lastC = 0; args[0].replace(/%[a-zA-Z%]/g, (match) => { if (match === "%%") { return; } index++; if (match === "%c") { lastC = index; } }); args.splice(lastC, 0, c); } exports2.log = console.debug || console.log || (() => { }); function save(namespaces) { try { if (namespaces) { exports2.storage.setItem("debug", namespaces); } else { exports2.storage.removeItem("debug"); } } catch (error) { } } function load() { let r; try { r = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG"); } catch (error) { } if (!r && typeof process !== "undefined" && "env" in process) { r = process.env.DEBUG; } return r; } function localstorage() { try { return localStorage; } catch (error) { } } module2.exports = require_common4()(exports2); var { formatters } = module2.exports; formatters.j = function(v) { try { return JSON.stringify(v); } catch (error) { return "[UnexpectedJSONParseError]: " + error.message; } }; } }); // node_modules/has-flag/index.js var require_has_flag = __commonJS({ "node_modules/has-flag/index.js"(exports2, module2) { "use strict"; module2.exports = (flag, argv = process.argv) => { const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; const position = argv.indexOf(prefix + flag); const terminatorPosition = argv.indexOf("--"); return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); }; } }); // node_modules/supports-color/index.js var require_supports_color = __commonJS({ "node_modules/supports-color/index.js"(exports2, module2) { "use strict"; var os = require("os"); var tty = require("tty"); var hasFlag = require_has_flag(); var { env } = process; var forceColor; if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) { forceColor = 0; } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) { forceColor = 1; } if ("FORCE_COLOR" in env) { if (env.FORCE_COLOR === "true") { forceColor = 1; } else if (env.FORCE_COLOR === "false") { forceColor = 0; } else { forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); } } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function supportsColor(haveStream, streamIsTTY) { if (forceColor === 0) { return 0; } if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { return 3; } if (hasFlag("color=256")) { return 2; } if (haveStream && !streamIsTTY && forceColor === void 0) { return 0; } const min = forceColor || 0; if (env.TERM === "dumb") { return min; } if (process.platform === "win32") { const osRelease = os.release().split("."); if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ("CI" in env) { if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env) || env.CI_NAME === "codeship") { return 1; } return min; } if ("TEAMCITY_VERSION" in env) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; } if (env.COLORTERM === "truecolor") { return 3; } if ("TERM_PROGRAM" in env) { const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); switch (env.TERM_PROGRAM) { case "iTerm.app": return version >= 3 ? 3 : 2; case "Apple_Terminal": return 2; } } if (/-256(color)?$/i.test(env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { return 1; } if ("COLORTERM" in env) { return 1; } return min; } function getSupportLevel(stream) { const level = supportsColor(stream, stream && stream.isTTY); return translateLevel(level); } module2.exports = { supportsColor: getSupportLevel, stdout: translateLevel(supportsColor(true, tty.isatty(1))), stderr: translateLevel(supportsColor(true, tty.isatty(2))) }; } }); // netlify/functions/node_modules/debug/src/node.js var require_node2 = __commonJS({ "netlify/functions/node_modules/debug/src/node.js"(exports2, module2) { var tty = require("tty"); var util = require("util"); exports2.init = init; exports2.log = log; exports2.formatArgs = formatArgs; exports2.save = save; exports2.load = load; exports2.useColors = useColors; exports2.destroy = util.deprecate( () => { }, "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`." ); exports2.colors = [6, 2, 3, 4, 5, 1]; try { const supportsColor = require_supports_color(); if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { exports2.colors = [ 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221 ]; } } catch (error) { } exports2.inspectOpts = Object.keys(process.env).filter((key) => { return /^debug_/i.test(key); }).reduce((obj, key) => { const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => { return k.toUpperCase(); }); let val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) { val = true; } else if (/^(no|off|false|disabled)$/i.test(val)) { val = false; } else if (val === "null") { val = null; } else { val = Number(val); } obj[prop] = val; return obj; }, {}); function useColors() { return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd); } function formatArgs(args) { const { namespace: name, useColors: useColors2 } = this; if (useColors2) { const c = this.color; const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c); const prefix = ` ${colorCode};1m${name} \x1B[0m`; args[0] = prefix + args[0].split("\n").join("\n" + prefix); args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m"); } else { args[0] = getDate() + name + " " + args[0]; } } function getDate() { if (exports2.inspectOpts.hideDate) { return ""; } return (/* @__PURE__ */ new Date()).toISOString() + " "; } function log(...args) { return process.stderr.write(util.formatWithOptions(exports2.inspectOpts, ...args) + "\n"); } function save(namespaces) { if (namespaces) { process.env.DEBUG = namespaces; } else { delete process.env.DEBUG; } } function load() { return process.env.DEBUG; } function init(debug) { debug.inspectOpts = {}; const keys = Object.keys(exports2.inspectOpts); for (let i = 0; i < keys.length; i++) { debug.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]]; } } module2.exports = require_common4()(exports2); var { formatters } = module2.exports; formatters.o = function(v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" "); }; formatters.O = function(v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts); }; } }); // netlify/functions/node_modules/debug/src/index.js var require_src = __commonJS({ "netlify/functions/node_modules/debug/src/index.js"(exports2, module2) { if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) { module2.exports = require_browser(); } else { module2.exports = require_node2(); } } }); // netlify/functions/node_modules/mquery/lib/permissions.js var require_permissions = __commonJS({ "netlify/functions/node_modules/mquery/lib/permissions.js"(exports2) { "use strict"; var denied = exports2; denied.distinct = function(self2) { if (self2._fields && Object.keys(self2._fields).length > 0) { return "field selection and slice"; } const keys = Object.keys(denied.distinct); let err; keys.every(function(option) { if (self2.options[option]) { err = option; return false; } return true; }); return err; }; denied.distinct.select = denied.distinct.slice = denied.distinct.sort = denied.distinct.limit = denied.distinct.skip = denied.distinct.batchSize = denied.distinct.hint = denied.distinct.tailable = true; denied.findOneAndUpdate = denied.findOneAndRemove = function(self2) { const keys = Object.keys(denied.findOneAndUpdate); let err; keys.every(function(option) { if (self2.options[option]) { err = option; return false; } return true; }); return err; }; denied.findOneAndUpdate.limit = denied.findOneAndUpdate.skip = denied.findOneAndUpdate.batchSize = denied.findOneAndUpdate.tailable = true; denied.count = function(self2) { if (self2._fields && Object.keys(self2._fields).length > 0) { return "field selection and slice"; } const keys = Object.keys(denied.count); let err; keys.every(function(option) { if (self2.options[option]) { err = option; return false; } return true; }); return err; }; denied.count.slice = denied.count.batchSize = denied.count.tailable = true; } }); // netlify/functions/node_modules/mquery/lib/env.js var require_env = __commonJS({ "netlify/functions/node_modules/mquery/lib/env.js"(exports2, module2) { "use strict"; exports2.isNode = "undefined" != typeof process && "object" == typeof module2 && "object" == typeof global && "function" == typeof Buffer && process.argv; exports2.isMongo = !exports2.isNode && "function" == typeof printjson && "function" == typeof ObjectId && "function" == typeof rs && "function" == typeof sh; exports2.isBrowser = !exports2.isNode && !exports2.isMongo && "undefined" != typeof window; exports2.type = exports2.isNode ? "node" : exports2.isMongo ? "mongo" : exports2.isBrowser ? "browser" : "unknown"; } }); // netlify/functions/node_modules/mquery/lib/collection/collection.js var require_collection4 = __commonJS({ "netlify/functions/node_modules/mquery/lib/collection/collection.js"(exports2, module2) { "use strict"; var methods = [ "find", "findOne", "updateMany", "updateOne", "replaceOne", "count", "distinct", "findOneAndDelete", "findOneAndUpdate", "aggregate", "findCursor", "deleteOne", "deleteMany" ]; function Collection() { } for (let i = 0, len = methods.length; i < len; ++i) { const method = methods[i]; Collection.prototype[method] = notImplemented(method); } module2.exports = exports2 = Collection; Collection.methods = methods; function notImplemented(method) { return function() { throw new Error("collection." + method + " not implemented"); }; } } }); // netlify/functions/node_modules/mquery/lib/collection/node.js var require_node3 = __commonJS({ "netlify/functions/node_modules/mquery/lib/collection/node.js"(exports2, module2) { "use strict"; var Collection = require_collection4(); var NodeCollection = class extends Collection { constructor(col) { super(); this.collection = col; this.collectionName = col.collectionName; } /** * find(match, options) */ async find(match, options) { const cursor = this.collection.find(match, options); return cursor.toArray(); } /** * findOne(match, options) */ async findOne(match, options) { return this.collection.findOne(match, options); } /** * count(match, options) */ async count(match, options) { return this.collection.count(match, options); } /** * distinct(prop, match, options) */ async distinct(prop, match, options) { return this.collection.distinct(prop, match, options); } /** * updateMany(match, update, options) */ async updateMany(match, update, options) { return this.collection.updateMany(match, update, options); } /** * updateOne(match, update, options) */ async updateOne(match, update, options) { return this.collection.updateOne(match, update, options); } /** * replaceOne(match, update, options) */ async replaceOne(match, update, options) { return this.collection.replaceOne(match, update, options); } /** * deleteOne(match, options) */ async deleteOne(match, options) { return this.collection.deleteOne(match, options); } /** * deleteMany(match, options) */ async deleteMany(match, options) { return this.collection.deleteMany(match, options); } /** * findOneAndDelete(match, options, function(err[, result]) */ async findOneAndDelete(match, options) { return this.collection.findOneAndDelete(match, options); } /** * findOneAndUpdate(match, update, options) */ async findOneAndUpdate(match, update, options) { return this.collection.findOneAndUpdate(match, update, options); } /** * var cursor = findCursor(match, options) */ findCursor(match, options) { return this.collection.find(match, options); } /** * aggregation(operators...) * TODO */ }; module2.exports = exports2 = NodeCollection; } }); // netlify/functions/node_modules/mquery/lib/collection/index.js var require_collection5 = __commonJS({ "netlify/functions/node_modules/mquery/lib/collection/index.js"(exports2, module2) { "use strict"; var env = require_env(); if ("unknown" == env.type) { throw new Error("Unknown environment"); } module2.exports = env.isNode ? require_node3() : env.isMongo ? require_collection4() : require_collection4(); } }); // netlify/functions/node_modules/mquery/lib/mquery.js var require_mquery = __commonJS({ "netlify/functions/node_modules/mquery/lib/mquery.js"(exports2, module2) { "use strict"; var assert = require("assert"); var util = require("util"); var utils = require_utils4(); var debug = require_src()("mquery"); function Query(criteria, options) { if (!(this instanceof Query)) return new Query(criteria, options); const proto = this.constructor.prototype; this.op = proto.op || void 0; this.options = Object.assign({}, proto.options); this._conditions = proto._conditions ? utils.clone(proto._conditions) : {}; this._fields = proto._fields ? utils.clone(proto._fields) : void 0; this._updateDoc = proto._updateDoc ? utils.clone(proto._updateDoc) : void 0; this._path = proto._path || void 0; this._distinctDoc = proto._distinctDoc || void 0; this._collection = proto._collection || void 0; this._traceFunction = proto._traceFunction || void 0; if (options) { this.setOptions(options); } if (criteria) { this.find(criteria); } } var $withinCmd = "$geoWithin"; Object.defineProperty(Query, "use$geoWithin", { get: function() { return $withinCmd == "$geoWithin"; }, set: function(v) { if (true === v) { $withinCmd = "$geoWithin"; } else { $withinCmd = "$within"; } } }); Query.prototype.toConstructor = function toConstructor() { function CustomQuery(criteria, options) { if (!(this instanceof CustomQuery)) return new CustomQuery(criteria, options); Query.call(this, criteria, options); } utils.inherits(CustomQuery, Query); const p = CustomQuery.prototype; p.options = {}; p.setOptions(this.options); p.op = this.op; p._conditions = utils.clone(this._conditions); p._fields = utils.clone(this._fields); p._updateDoc = utils.clone(this._updateDoc); p._path = this._path; p._distinctDoc = this._distinctDoc; p._collection = this._collection; p._traceFunction = this._traceFunction; return CustomQuery; }; Query.prototype.setOptions = function(options) { if (!(options && utils.isObject(options))) return this; const methods = utils.keys(options); let method; for (let i = 0; i < methods.length; ++i) { method = methods[i]; if ("function" == typeof this[method]) { const args = Array.isArray(options[method]) ? options[method] : [options[method]]; this[method].apply(this, args); } else { this.options[method] = options[method]; } } return this; }; Query.prototype.collection = function collection(coll) { this._collection = new Query.Collection(coll); return this; }; Query.prototype.collation = function(value) { this.options.collation = value; return this; }; Query.prototype.$where = function(js) { this._conditions.$where = js; return this; }; Query.prototype.where = function() { if (!arguments.length) return this; if (!this.op) this.op = "find"; const type = typeof arguments[0]; if ("string" == type) { this._path = arguments[0]; if (2 === arguments.length) { this._conditions[this._path] = arguments[1]; } return this; } if ("object" == type && !Array.isArray(arguments[0])) { return this.merge(arguments[0]); } throw new TypeError("path must be a string or object"); }; Query.prototype.equals = function equals(val) { this._ensurePath("equals"); const path = this._path; this._conditions[path] = val; return this; }; Query.prototype.eq = function eq(val) { this._ensurePath("eq"); const path = this._path; this._conditions[path] = val; return this; }; Query.prototype.or = function or(array) { const or2 = this._conditions.$or || (this._conditions.$or = []); if (!Array.isArray(array)) array = [array]; or2.push.apply(or2, array); return this; }; Query.prototype.nor = function nor(array) { const nor2 = this._conditions.$nor || (this._conditions.$nor = []); if (!Array.isArray(array)) array = [array]; nor2.push.apply(nor2, array); return this; }; Query.prototype.and = function and(array) { const and2 = this._conditions.$and || (this._conditions.$and = []); if (!Array.isArray(array)) array = [array]; and2.push.apply(and2, array); return this; }; "gt gte lt lte ne in nin all regex size maxDistance minDistance".split(" ").forEach(function($conditional) { Query.prototype[$conditional] = function() { let path, val; if (1 === arguments.length) { this._ensurePath($conditional); val = arguments[0]; path = this._path; } else { val = arguments[1]; path = arguments[0]; } const conds = this._conditions[path] === null || typeof this._conditions[path] === "object" ? this._conditions[path] : this._conditions[path] = {}; conds["$" + $conditional] = val; return this; }; }); Query.prototype.mod = function() { let val, path; if (1 === arguments.length) { this._ensurePath("mod"); val = arguments[0]; path = this._path; } else if (2 === arguments.length && !Array.isArray(arguments[1])) { this._ensurePath("mod"); val = [arguments[0], arguments[1]]; path = this._path; } else if (3 === arguments.length) { val = [arguments[1], arguments[2]]; path = arguments[0]; } else { val = arguments[1]; path = arguments[0]; } const conds = this._conditions[path] || (this._conditions[path] = {}); conds.$mod = val; return this; }; Query.prototype.exists = function() { let path, val; if (0 === arguments.length) { this._ensurePath("exists"); path = this._path; val = true; } else if (1 === arguments.length) { if ("boolean" === typeof arguments[0]) { this._ensurePath("exists"); path = this._path; val = arguments[0]; } else { path = arguments[0]; val = true; } } else if (2 === arguments.length) { path = arguments[0]; val = arguments[1]; } const conds = this._conditions[path] || (this._conditions[path] = {}); conds.$exists = val; return this; }; Query.prototype.elemMatch = function() { if (null == arguments[0]) throw new TypeError("Invalid argument"); let fn, path, criteria; if ("function" === typeof arguments[0]) { this._ensurePath("elemMatch"); path = this._path; fn = arguments[0]; } else if (utils.isObject(arguments[0])) { this._ensurePath("elemMatch"); path = this._path; criteria = arguments[0]; } else if ("function" === typeof arguments[1]) { path = arguments[0]; fn = arguments[1]; } else if (arguments[1] && utils.isObject(arguments[1])) { path = arguments[0]; criteria = arguments[1]; } else { throw new TypeError("Invalid argument"); } if (fn) { criteria = new Query(); fn(criteria); criteria = criteria._conditions; } const conds = this._conditions[path] || (this._conditions[path] = {}); conds.$elemMatch = criteria; return this; }; Query.prototype.within = function within() { this._ensurePath("within"); this._geoComparison = $withinCmd; if (0 === arguments.length) { return this; } if (2 === arguments.length) { return this.box.apply(this, arguments); } else if (2 < arguments.length) { return this.polygon.apply(this, arguments); } const area = arguments[0]; if (!area) throw new TypeError("Invalid argument"); if (area.center) return this.circle(area); if (area.box) return this.box.apply(this, area.box); if (area.polygon) return this.polygon.apply(this, area.polygon); if (area.type && area.coordinates) return this.geometry(area); throw new TypeError("Invalid argument"); }; Query.prototype.box = function() { let path, box; if (3 === arguments.length) { path = arguments[0]; box = [arguments[1], arguments[2]]; } else if (2 === arguments.length) { this._ensurePath("box"); path = this._path; box = [arguments[0], arguments[1]]; } else { throw new TypeError("Invalid argument"); } const conds = this._conditions[path] || (this._conditions[path] = {}); conds[this._geoComparison || $withinCmd] = { $box: box }; return this; }; Query.prototype.polygon = function() { let val, path; if ("string" == typeof arguments[0]) { val = Array.from(arguments); path = val.shift(); } else { this._ensurePath("polygon"); path = this._path; val = Array.from(arguments); } const conds = this._conditions[path] || (this._conditions[path] = {}); conds[this._geoComparison || $withinCmd] = { $polygon: val }; return this; }; Query.prototype.circle = function() { let path, val; if (1 === arguments.length) { this._ensurePath("circle"); path = this._path; val = arguments[0]; } else if (2 === arguments.length) { path = arguments[0]; val = arguments[1]; } else { throw new TypeError("Invalid argument"); } if (!("radius" in val && val.center)) throw new Error("center and radius are required"); const conds = this._conditions[path] || (this._conditions[path] = {}); const type = val.spherical ? "$centerSphere" : "$center"; const wKey = this._geoComparison || $withinCmd; conds[wKey] = {}; conds[wKey][type] = [val.center, val.radius]; if ("unique" in val) conds[wKey].$uniqueDocs = !!val.unique; return this; }; Query.prototype.near = function near() { let path, val; this._geoComparison = "$near"; if (0 === arguments.length) { return this; } else if (1 === arguments.length) { this._ensurePath("near"); path = this._path; val = arguments[0]; } else if (2 === arguments.length) { path = arguments[0]; val = arguments[1]; } else { throw new TypeError("Invalid argument"); } if (!val.center) { throw new Error("center is required"); } const conds = this._conditions[path] || (this._conditions[path] = {}); const type = val.spherical ? "$nearSphere" : "$near"; if (Array.isArray(val.center)) { conds[type] = val.center; const radius = "maxDistance" in val ? val.maxDistance : null; if (null != radius) { conds.$maxDistance = radius; } if (null != val.minDistance) { conds.$minDistance = val.minDistance; } } else { if (val.center.type != "Point" || !Array.isArray(val.center.coordinates)) { throw new Error(util.format("Invalid GeoJSON specified for %s", type)); } conds[type] = { $geometry: val.center }; if ("maxDistance" in val) { conds[type]["$maxDistance"] = val.maxDistance; } if ("minDistance" in val) { conds[type]["$minDistance"] = val.minDistance; } } return this; }; Query.prototype.intersects = function intersects() { this._ensurePath("intersects"); this._geoComparison = "$geoIntersects"; if (0 === arguments.length) { return this; } const area = arguments[0]; if (null != area && area.type && area.coordinates) return this.geometry(area); throw new TypeError("Invalid argument"); }; Query.prototype.geometry = function geometry() { if (!("$within" == this._geoComparison || "$geoWithin" == this._geoComparison || "$near" == this._geoComparison || "$geoIntersects" == this._geoComparison)) { throw new Error("geometry() must come after `within()`, `intersects()`, or `near()"); } let val, path; if (1 === arguments.length) { this._ensurePath("geometry"); path = this._path; val = arguments[0]; } else { throw new TypeError("Invalid argument"); } if (!(val.type && Array.isArray(val.coordinates))) { throw new TypeError("Invalid argument"); } const conds = this._conditions[path] || (this._conditions[path] = {}); conds[this._geoComparison] = { $geometry: val }; return this; }; Query.prototype.select = function select() { let arg = arguments[0]; if (!arg) return this; if (arguments.length !== 1) { throw new Error("Invalid select: select only takes 1 argument"); } this._validate("select"); const fields = this._fields || (this._fields = {}); const type = typeof arg; let i, len; if (("string" == type || utils.isArgumentsObject(arg)) && "number" == typeof arg.length || Array.isArray(arg)) { if ("string" == type) arg = arg.split(/\s+/); for (i = 0, len = arg.length; i < len; ++i) { let field = arg[i]; if (!field) continue; const include = "-" == field[0] ? 0 : 1; if (include === 0) field = field.substring(1); fields[field] = include; } return this; } if (utils.isObject(arg)) { const keys = utils.keys(arg); for (i = 0; i < keys.length; ++i) { fields[keys[i]] = arg[keys[i]]; } return this; } throw new TypeError("Invalid select() argument. Must be string or object."); }; Query.prototype.slice = function() { if (0 === arguments.length) return this; this._validate("slice"); let path, val; if (1 === arguments.length) { const arg = arguments[0]; if (typeof arg === "object" && !Array.isArray(arg)) { const keys = Object.keys(arg); const numKeys = keys.length; for (let i = 0; i < numKeys; ++i) { this.slice(keys[i], arg[keys[i]]); } return this; } this._ensurePath("slice"); path = this._path; val = arguments[0]; } else if (2 === arguments.length) { if ("number" === typeof arguments[0]) { this._ensurePath("slice"); path = this._path; val = [arguments[0], arguments[1]]; } else { path = arguments[0]; val = arguments[1]; } } else if (3 === arguments.length) { path = arguments[0]; val = [arguments[1], arguments[2]]; } const myFields = this._fields || (this._fields = {}); myFields[path] = { $slice: val }; return this; }; Query.prototype.sort = function(arg) { if (!arg) return this; let i, len, field; this._validate("sort"); const type = typeof arg; if (Array.isArray(arg)) { len = arg.length; for (i = 0; i < arg.length; ++i) { if (!Array.isArray(arg[i])) { throw new Error("Invalid sort() argument, must be array of arrays"); } _pushArr(this.options, arg[i][0], arg[i][1]); } return this; } if (1 === arguments.length && "string" == type) { arg = arg.split(/\s+/); len = arg.length; for (i = 0; i < len; ++i) { field = arg[i]; if (!field) continue; const ascend = "-" == field[0] ? -1 : 1; if (ascend === -1) field = field.substring(1); push(this.options, field, ascend); } return this; } if (utils.isObject(arg)) { const keys = utils.keys(arg); for (i = 0; i < keys.length; ++i) { field = keys[i]; push(this.options, field, arg[field]); } return this; } if (typeof Map !== "undefined" && arg instanceof Map) { _pushMap(this.options, arg); return this; } throw new TypeError("Invalid sort() argument. Must be a string, object, or array."); }; var _validSortValue = { 1: 1, "-1": -1, asc: 1, ascending: 1, desc: -1, descending: -1 }; function push(opts, field, value) { if (Array.isArray(opts.sort)) { throw new TypeError("Can't mix sort syntaxes. Use either array or object:\n- `.sort([['field', 1], ['test', -1]])`\n- `.sort({ field: 1, test: -1 })`"); } let s; if (value && value.$meta) { s = opts.sort || (opts.sort = {}); s[field] = { $meta: value.$meta }; return; } s = opts.sort || (opts.sort = {}); let val = String(value || 1).toLowerCase(); val = _validSortValue[val]; if (!val) throw new TypeError("Invalid sort value: { " + field + ": " + value + " }"); s[field] = val; } function _pushArr(opts, field, value) { opts.sort = opts.sort || []; if (!Array.isArray(opts.sort)) { throw new TypeError("Can't mix sort syntaxes. Use either array or object:\n- `.sort([['field', 1], ['test', -1]])`\n- `.sort({ field: 1, test: -1 })`"); } let val = String(value || 1).toLowerCase(); val = _validSortValue[val]; if (!val) throw new TypeError("Invalid sort value: [ " + field + ", " + value + " ]"); opts.sort.push([field, val]); } function _pushMap(opts, map) { opts.sort = opts.sort || /* @__PURE__ */ new Map(); if (!(opts.sort instanceof Map)) { throw new TypeError("Can't mix sort syntaxes. Use either array or object or map consistently"); } map.forEach(function(value, key) { let val = String(value || 1).toLowerCase(); val = _validSortValue[val]; if (!val) throw new TypeError("Invalid sort value: < " + key + ": " + value + " >"); opts.sort.set(key, val); }); } ["limit", "skip", "batchSize", "comment"].forEach(function(method) { Query.prototype[method] = function(v) { this._validate(method); this.options[method] = v; return this; }; }); Query.prototype.maxTime = Query.prototype.maxTimeMS = function(ms) { this._validate("maxTime"); this.options.maxTimeMS = ms; return this; }; Query.prototype.hint = function() { if (0 === arguments.length) return this; this._validate("hint"); const arg = arguments[0]; if (utils.isObject(arg)) { const hint = this.options.hint || (this.options.hint = {}); for (const k in arg) { hint[k] = arg[k]; } return this; } if (typeof arg === "string") { this.options.hint = arg; return this; } throw new TypeError("Invalid hint. " + arg); }; Query.prototype.j = function j(val) { this.options.j = val; return this; }; Query.prototype.slaveOk = function(v) { this.options.slaveOk = arguments.length ? !!v : true; return this; }; Query.prototype.read = Query.prototype.setReadPreference = function(pref) { if (arguments.length > 1 && !Query.prototype.read.deprecationWarningIssued) { console.error("Deprecation warning: 'tags' argument is not supported anymore in Query.read() method. Please use mongodb.ReadPreference object instead."); Query.prototype.read.deprecationWarningIssued = true; } this.options.readPreference = utils.readPref(pref); return this; }; Query.prototype.readConcern = Query.prototype.r = function(level) { this.options.readConcern = utils.readConcern(level); return this; }; Query.prototype.tailable = function() { this._validate("tailable"); this.options.tailable = arguments.length ? !!arguments[0] : true; return this; }; Query.prototype.writeConcern = Query.prototype.w = function writeConcern(concern) { if ("object" === typeof concern) { if ("undefined" !== typeof concern.j) this.options.j = concern.j; if ("undefined" !== typeof concern.w) this.options.w = concern.w; if ("undefined" !== typeof concern.wtimeout) this.options.wtimeout = concern.wtimeout; } else { this.options.w = "m" === concern ? "majority" : concern; } return this; }; Query.prototype.wtimeout = Query.prototype.wTimeout = function wtimeout(ms) { this.options.wtimeout = ms; return this; }; Query.prototype.merge = function(source) { if (!source) return this; if (!Query.canMerge(source)) throw new TypeError("Invalid argument. Expected instanceof mquery or plain object"); if (source instanceof Query) { if (source._conditions) { utils.merge(this._conditions, source._conditions); } if (source._fields) { this._fields || (this._fields = {}); utils.merge(this._fields, source._fields); } if (source.options) { this.options || (this.options = {}); utils.merge(this.options, source.options); } if (source._updateDoc) { this._updateDoc || (this._updateDoc = {}); utils.mergeClone(this._updateDoc, source._updateDoc); } if (source._distinctDoc) { this._distinctDoc = source._distinctDoc; } return this; } utils.merge(this._conditions, source); return this; }; Query.prototype.find = function(criteria) { this.op = "find"; if (Query.canMerge(criteria)) { this.merge(criteria); } return this; }; Query.prototype._find = async function _find() { const conds = this._conditions; const options = this._optionsForExec(); if (this.$useProjection) { options.projection = this._fieldsForExec(); } else { options.fields = this._fieldsForExec(); } debug("_find", this._collection.collectionName, conds, options); return this._collection.find(conds, options); }; Query.prototype.cursor = function cursor(criteria) { if (this.op) { if (this.op !== "find") { throw new TypeError(".cursor only support .find method"); } } else { this.find(criteria); } const conds = this._conditions; const options = this._optionsForExec(); if (this.$useProjection) { options.projection = this._fieldsForExec(); } else { options.fields = this._fieldsForExec(); } debug("findCursor", this._collection.collectionName, conds, options); return this._collection.findCursor(conds, options); }; Query.prototype.findOne = function(criteria) { this.op = "findOne"; if (Query.canMerge(criteria)) { this.merge(criteria); } return this; }; Query.prototype._findOne = async function _findOne() { const conds = this._conditions; const options = this._optionsForExec(); if (this.$useProjection) { options.projection = this._fieldsForExec(); } else { options.fields = this._fieldsForExec(); } debug("findOne", this._collection.collectionName, conds, options); return this._collection.findOne(conds, options); }; Query.prototype.count = function(criteria) { this.op = "count"; this._validate(); if (Query.canMerge(criteria)) { this.merge(criteria); } return this; }; Query.prototype._count = async function _count() { const conds = this._conditions, options = this._optionsForExec(); debug("count", this._collection.collectionName, conds, options); return this._collection.count(conds, options); }; Query.prototype.distinct = function(criteria, field) { this.op = "distinct"; this._validate(); if (!field && typeof criteria === "string") { field = criteria; criteria = void 0; } if ("string" == typeof field) { this._distinctDoc = field; } if (Query.canMerge(criteria)) { this.merge(criteria); } return this; }; Query.prototype._distinct = async function _distinct() { if (!this._distinctDoc) { throw new Error("No value for `distinct` has been declared"); } const conds = this._conditions, options = this._optionsForExec(); debug("distinct", this._collection.collectionName, conds, options); return this._collection.distinct(this._distinctDoc, conds, options); }; Query.prototype.updateMany = function updateMany(criteria, doc, options) { if (arguments.length === 1) { doc = criteria; criteria = options = void 0; } return _update(this, "updateMany", criteria, doc, options); }; Query.prototype._updateMany = async function() { return _updateExec(this, "updateMany"); }; Query.prototype.updateOne = function updateOne(criteria, doc, options) { if (arguments.length === 1) { doc = criteria; criteria = options = void 0; } return _update(this, "updateOne", criteria, doc, options); }; Query.prototype._updateOne = async function() { return _updateExec(this, "updateOne"); }; Query.prototype.replaceOne = function replaceOne(criteria, doc, options) { if (arguments.length === 1) { doc = criteria; criteria = options = void 0; } this.setOptions({ overwrite: true }); return _update(this, "replaceOne", criteria, doc, options); }; Query.prototype._replaceOne = async function() { return _updateExec(this, "replaceOne"); }; function _update(query, op, criteria, doc, options) { query.op = op; if (Query.canMerge(criteria)) { query.merge(criteria); } if (doc) { query._mergeUpdate(doc); } if (utils.isObject(options)) { query.setOptions(options); } return query; } async function _updateExec(query, op) { const options = query._optionsForExec(); const criteria = query._conditions; const doc = query._updateForExec(); debug("update", query._collection.collectionName, criteria, doc, options); return query._collection[op](criteria, doc, options); } Query.prototype.deleteOne = function(criteria) { this.op = "deleteOne"; if (Query.canMerge(criteria)) { this.merge(criteria); } return this; }; Query.prototype._deleteOne = async function() { const options = this._optionsForExec(); delete options.justOne; const conds = this._conditions; debug("deleteOne", this._collection.collectionName, conds, options); return this._collection.deleteOne(conds, options); }; Query.prototype.deleteMany = function(criteria) { this.op = "deleteMany"; if (Query.canMerge(criteria)) { this.merge(criteria); } return this; }; Query.prototype._deleteMany = async function() { const options = this._optionsForExec(); delete options.justOne; const conds = this._conditions; debug("deleteOne", this._collection.collectionName, conds, options); return this._collection.deleteMany(conds, options); }; Query.prototype.findOneAndUpdate = function(criteria, doc, options) { this.op = "findOneAndUpdate"; this._validate(); if (arguments.length === 1) { doc = criteria; criteria = options = void 0; } if (Query.canMerge(criteria)) { this.merge(criteria); } if (doc) { this._mergeUpdate(doc); } options && this.setOptions(options); return this; }; Query.prototype._findOneAndUpdate = async function() { const conds = this._conditions; const update = this._updateForExec(); const options = this._optionsForExec(); return this._collection.findOneAndUpdate(conds, update, options); }; Query.prototype.findOneAndRemove = Query.prototype.findOneAndDelete = function(conditions, options) { this.op = "findOneAndRemove"; this._validate(); if (Query.canMerge(conditions)) { this.merge(conditions); } options && this.setOptions(options); return this; }; Query.prototype._findOneAndRemove = async function() { const options = this._optionsForExec(); const conds = this._conditions; return this._collection.findOneAndDelete(conds, options); }; Query.prototype.setTraceFunction = function(traceFunction) { this._traceFunction = traceFunction; return this; }; Query.prototype.exec = async function exec(op) { if (typeof op === "string") { this.op = op; } assert.ok(this.op, "Missing query type: (find, etc)"); const fnName = "_" + this.op; if (typeof this[fnName] !== "function") { throw new TypeError(`this[${fnName}] is not a function`); } return this[fnName](); }; Query.prototype.then = async function(res, rej) { return this.exec().then(res, rej); }; Query.prototype.cursor = function() { if ("find" != this.op) throw new Error("cursor() is only available for find"); const conds = this._conditions; const options = this._optionsForExec(); if (this.$useProjection) { options.projection = this._fieldsForExec(); } else { options.fields = this._fieldsForExec(); } debug("cursor", this._collection.collectionName, conds, options); return this._collection.findCursor(conds, options); }; Query.prototype.selected = function selected() { return !!(this._fields && Object.keys(this._fields).length > 0); }; Query.prototype.selectedInclusively = function selectedInclusively() { if (!this._fields) return false; const keys = Object.keys(this._fields); if (0 === keys.length) return false; for (let i = 0; i < keys.length; ++i) { const key = keys[i]; if (0 === this._fields[key]) return false; if (this._fields[key] && typeof this._fields[key] === "object" && this._fields[key].$meta) { return false; } } return true; }; Query.prototype.selectedExclusively = function selectedExclusively() { if (!this._fields) return false; const keys = Object.keys(this._fields); if (0 === keys.length) return false; for (let i = 0; i < keys.length; ++i) { const key = keys[i]; if (0 === this._fields[key]) return true; } return false; }; Query.prototype._mergeUpdate = function(doc) { if (!this._updateDoc) this._updateDoc = {}; if (doc instanceof Query) { if (doc._updateDoc) { utils.mergeClone(this._updateDoc, doc._updateDoc); } } else { utils.mergeClone(this._updateDoc, doc); } }; Query.prototype._optionsForExec = function() { const options = utils.clone(this.options); return options; }; Query.prototype._fieldsForExec = function() { return utils.clone(this._fields); }; Query.prototype._updateForExec = function() { const update = utils.clone(this._updateDoc); const ops = utils.keys(update); const ret = {}; for (const op of ops) { if (this.options.overwrite) { ret[op] = update[op]; continue; } if ("$" !== op[0]) { if (!ret.$set) { if (update.$set) { ret.$set = update.$set; } else { ret.$set = {}; } } ret.$set[op] = update[op]; if (!~ops.indexOf("$set")) ops.push("$set"); } else if ("$set" === op) { if (!ret.$set) { ret[op] = update[op]; } } else { ret[op] = update[op]; } } this._compiledUpdate = ret; return ret; }; Query.prototype._ensurePath = function(method) { if (!this._path) { const msg = method + "() must be used after where() when called with these arguments"; throw new Error(msg); } }; Query.permissions = require_permissions(); Query._isPermitted = function(a, b) { const denied = Query.permissions[b]; if (!denied) return true; return true !== denied[a]; }; Query.prototype._validate = function(action) { let fail; let validator; if (void 0 === action) { validator = Query.permissions[this.op]; if ("function" != typeof validator) return true; fail = validator(this); } else if (!Query._isPermitted(action, this.op)) { fail = action; } if (fail) { throw new Error(fail + " cannot be used with " + this.op); } }; Query.canMerge = function(conds) { return conds instanceof Query || utils.isObject(conds); }; Query.setGlobalTraceFunction = function(traceFunction) { Query.traceFunction = traceFunction; }; Query.utils = utils; Query.env = require_env(); Query.Collection = require_collection5(); Query.BaseCollection = require_collection4(); module2.exports = exports2 = Query; } }); // netlify/functions/node_modules/mongoose/lib/helpers/projection/parseProjection.js var require_parseProjection = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/projection/parseProjection.js"(exports2, module2) { "use strict"; module2.exports = function parseProjection(v, retainMinusPaths) { const type = typeof v; if (type === "string") { v = v.split(/\s+/); } if (!Array.isArray(v) && Object.prototype.toString.call(v) !== "[object Arguments]") { return v; } const len = v.length; const ret = {}; for (let i = 0; i < len; ++i) { let field = v[i]; if (!field) { continue; } const include = "-" == field[0] ? 0 : 1; if (!retainMinusPaths && include === 0) { field = field.substring(1); } ret[field] = include; } return ret; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/update/removeUnusedArrayFilters.js var require_removeUnusedArrayFilters = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/update/removeUnusedArrayFilters.js"(exports2, module2) { "use strict"; module2.exports = function removeUnusedArrayFilters(update, arrayFilters) { const updateKeys = Object.keys(update).map((key) => Object.keys(update[key])).reduce((cur, arr) => cur.concat(arr), []); return arrayFilters.filter((obj) => { return _checkSingleFilterKey(obj, updateKeys); }); }; function _checkSingleFilterKey(arrayFilter, updateKeys) { const firstKey = Object.keys(arrayFilter)[0]; if (firstKey === "$and" || firstKey === "$or") { if (!Array.isArray(arrayFilter[firstKey])) { return false; } return arrayFilter[firstKey].find((filter) => _checkSingleFilterKey(filter, updateKeys)) != null; } const firstDot = firstKey.indexOf("."); const arrayFilterKey = firstDot === -1 ? firstKey : firstKey.slice(0, firstDot); return updateKeys.find((key) => key.includes("$[" + arrayFilterKey + "]")) != null; } } }); // netlify/functions/node_modules/mongoose/lib/helpers/query/hasDollarKeys.js var require_hasDollarKeys = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/query/hasDollarKeys.js"(exports2, module2) { "use strict"; module2.exports = function hasDollarKeys(obj) { if (typeof obj !== "object" || obj === null) { return false; } const keys = Object.keys(obj); const len = keys.length; for (let i = 0; i < len; ++i) { if (keys[i][0] === "$") { return true; } } return false; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/query/sanitizeFilter.js var require_sanitizeFilter = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/query/sanitizeFilter.js"(exports2, module2) { "use strict"; var hasDollarKeys = require_hasDollarKeys(); var { trustedSymbol } = require_trusted(); module2.exports = function sanitizeFilter(filter) { if (filter == null || typeof filter !== "object") { return filter; } if (Array.isArray(filter)) { for (const subfilter of filter) { sanitizeFilter(subfilter); } return filter; } const filterKeys = Object.keys(filter); for (const key of filterKeys) { const value = filter[key]; if (value != null && value[trustedSymbol]) { continue; } if (key === "$and" || key === "$or") { sanitizeFilter(value); continue; } if (hasDollarKeys(value)) { const keys = Object.keys(value); if (keys.length === 1 && keys[0] === "$eq") { continue; } filter[key] = { $eq: filter[key] }; } } return filter; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/query/sanitizeProjection.js var require_sanitizeProjection = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/query/sanitizeProjection.js"(exports2, module2) { "use strict"; module2.exports = function sanitizeProjection(projection) { if (projection == null) { return; } const keys = Object.keys(projection); for (let i = 0; i < keys.length; ++i) { if (typeof projection[keys[i]] === "string") { projection[keys[i]] = 1; } } }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/query/selectPopulatedFields.js var require_selectPopulatedFields = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/query/selectPopulatedFields.js"(exports2, module2) { "use strict"; var isExclusive = require_isExclusive(); var isInclusive = require_isInclusive(); module2.exports = function selectPopulatedFields(fields, userProvidedFields, populateOptions) { if (populateOptions == null) { return; } const paths = Object.keys(populateOptions); userProvidedFields = userProvidedFields || {}; if (isInclusive(fields)) { for (const path of paths) { if (!isPathInFields(userProvidedFields, path)) { fields[path] = 1; } else if (userProvidedFields[path] === 0) { delete fields[path]; } const refPath = populateOptions[path]?.refPath; if (typeof refPath === "string") { if (!isPathInFields(userProvidedFields, refPath)) { fields[refPath] = 1; } else if (userProvidedFields[refPath] === 0) { delete fields[refPath]; } } } } else if (isExclusive(fields)) { for (const path of paths) { if (userProvidedFields[path] == null) { delete fields[path]; } const refPath = populateOptions[path]?.refPath; if (typeof refPath === "string" && userProvidedFields[refPath] == null) { delete fields[refPath]; } } } }; function isPathInFields(userProvidedFields, path) { const pieces = path.split("."); const len = pieces.length; let cur = pieces[0]; for (let i = 1; i < len; ++i) { if (userProvidedFields[cur] != null || userProvidedFields[cur + ".$"] != null) { return true; } cur += "." + pieces[i]; } return userProvidedFields[cur] != null || userProvidedFields[cur + ".$"] != null; } } }); // netlify/functions/node_modules/mongoose/lib/helpers/updateValidators.js var require_updateValidators = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/updateValidators.js"(exports2, module2) { "use strict"; var ValidationError = require_validation(); var cleanPositionalOperators = require_cleanPositionalOperators(); var flatten = require_common3().flatten; var modifiedPaths = require_common3().modifiedPaths; module2.exports = function(query, schema, castedDoc, options, callback) { const keys = Object.keys(castedDoc || {}); let updatedKeys = {}; let updatedValues = {}; const isPull = {}; const arrayAtomicUpdates = {}; const numKeys = keys.length; let hasDollarUpdate = false; const modified = {}; let currentUpdate; let key; let i; for (i = 0; i < numKeys; ++i) { if (keys[i].startsWith("$")) { hasDollarUpdate = true; if (keys[i] === "$push" || keys[i] === "$addToSet") { const _keys = Object.keys(castedDoc[keys[i]]); for (let ii = 0; ii < _keys.length; ++ii) { currentUpdate = castedDoc[keys[i]][_keys[ii]]; if (currentUpdate && currentUpdate.$each) { arrayAtomicUpdates[_keys[ii]] = (arrayAtomicUpdates[_keys[ii]] || []).concat(currentUpdate.$each); } else { arrayAtomicUpdates[_keys[ii]] = (arrayAtomicUpdates[_keys[ii]] || []).concat([currentUpdate]); } } continue; } modifiedPaths(castedDoc[keys[i]], "", modified); const flat = flatten(castedDoc[keys[i]], null, null, schema); const paths = Object.keys(flat); const numPaths = paths.length; for (let j = 0; j < numPaths; ++j) { const updatedPath = cleanPositionalOperators(paths[j]); key = keys[i]; if (updatedPath.includes("$")) { continue; } if (key === "$set" || key === "$setOnInsert" || key === "$pull" || key === "$pullAll") { updatedValues[updatedPath] = flat[paths[j]]; isPull[updatedPath] = key === "$pull" || key === "$pullAll"; } else if (key === "$unset") { updatedValues[updatedPath] = void 0; } updatedKeys[updatedPath] = true; } } } if (!hasDollarUpdate) { modifiedPaths(castedDoc, "", modified); updatedValues = flatten(castedDoc, null, null, schema); updatedKeys = Object.keys(updatedValues); } const updates = Object.keys(updatedValues); const numUpdates = updates.length; const validatorsToExecute = []; const validationErrors = []; const alreadyValidated = []; const context = query; function iter(i2, v) { const schemaPath = schema._getSchema(updates[i2]); if (schemaPath == null) { return; } if (schemaPath.instance === "Mixed" && schemaPath.path !== updates[i2]) { return; } if (v && Array.isArray(v.$in)) { v.$in.forEach((v2, i3) => { validatorsToExecute.push(function(callback2) { schemaPath.doValidate( v2, function(err) { if (err) { err.path = updates[i3] + ".$in." + i3; validationErrors.push(err); } callback2(null); }, context, { updateValidator: true } ); }); }); } else { if (isPull[updates[i2]] && schemaPath.$isMongooseArray) { return; } if (schemaPath.$isMongooseDocumentArrayElement && v != null && v.$__ != null) { alreadyValidated.push(updates[i2]); validatorsToExecute.push(function(callback2) { schemaPath.doValidate(v, function(err) { if (err) { if (err.errors) { for (const key2 of Object.keys(err.errors)) { const _err = err.errors[key2]; _err.path = updates[i2] + "." + key2; validationErrors.push(_err); } } else { err.path = updates[i2]; validationErrors.push(err); } } return callback2(null); }, context, { updateValidator: true }); }); } else { validatorsToExecute.push(function(callback2) { for (const path of alreadyValidated) { if (updates[i2].startsWith(path + ".")) { return callback2(null); } } if (schemaPath.$isSingleNested) { alreadyValidated.push(updates[i2]); } schemaPath.doValidate(v, function(err) { if (schemaPath.schema != null && schemaPath.schema.options.storeSubdocValidationError === false && err instanceof ValidationError) { return callback2(null); } if (err) { err.path = updates[i2]; validationErrors.push(err); } callback2(null); }, context, { updateValidator: true }); }); } } } for (i = 0; i < numUpdates; ++i) { iter(i, updatedValues[updates[i]]); } const arrayUpdates = Object.keys(arrayAtomicUpdates); for (const arrayUpdate of arrayUpdates) { let schemaPath = schema._getSchema(arrayUpdate); if (schemaPath && schemaPath.$isMongooseDocumentArray) { validatorsToExecute.push(function(callback2) { schemaPath.doValidate( arrayAtomicUpdates[arrayUpdate], getValidationCallback(arrayUpdate, validationErrors, callback2), options && options.context === "query" ? query : null ); }); } else { schemaPath = schema._getSchema(arrayUpdate + ".0"); for (const atomicUpdate of arrayAtomicUpdates[arrayUpdate]) { validatorsToExecute.push(function(callback2) { schemaPath.doValidate( atomicUpdate, getValidationCallback(arrayUpdate, validationErrors, callback2), options && options.context === "query" ? query : null, { updateValidator: true } ); }); } } } if (callback != null) { let numValidators = validatorsToExecute.length; if (numValidators === 0) { return _done(callback); } for (const validator of validatorsToExecute) { validator(function() { if (--numValidators <= 0) { _done(callback); } }); } return; } return function(callback2) { let numValidators = validatorsToExecute.length; if (numValidators === 0) { return _done(callback2); } for (const validator of validatorsToExecute) { validator(function() { if (--numValidators <= 0) { _done(callback2); } }); } }; function _done(callback2) { if (validationErrors.length) { const err = new ValidationError(null); for (const validationError of validationErrors) { err.addError(validationError.path, validationError); } return callback2(err); } callback2(null); } function getValidationCallback(arrayUpdate, validationErrors2, callback2) { return function(err) { if (err) { err.path = arrayUpdate; validationErrors2.push(err); } callback2(null); }; } }; } }); // netlify/functions/node_modules/mongoose/lib/query.js var require_query = __commonJS({ "netlify/functions/node_modules/mongoose/lib/query.js"(exports2, module2) { "use strict"; var CastError = require_cast(); var DocumentNotFoundError = require_notFound(); var Kareem = require_kareem(); var MongooseError = require_mongooseError(); var ObjectParameterError = require_objectParameter(); var QueryCursor = require_queryCursor(); var ValidationError = require_validation(); var { applyGlobalMaxTimeMS, applyGlobalDiskUse } = require_applyGlobalOption(); var handleReadPreferenceAliases = require_handleReadPreferenceAliases(); var applyReadConcern = require_applyReadConcern(); var applyWriteConcern = require_applyWriteConcern(); var cast = require_cast2(); var castArrayFilters = require_castArrayFilters(); var castNumber = require_number(); var castUpdate = require_castUpdate(); var clone = require_clone(); var getDiscriminatorByValue = require_getDiscriminatorByValue(); var helpers = require_queryHelpers(); var internalToObjectOptions = require_options().internalToObjectOptions; var isExclusive = require_isExclusive(); var isInclusive = require_isInclusive(); var isPathSelectedInclusive = require_isPathSelectedInclusive(); var isSubpath = require_isSubpath(); var mpath = require_mpath(); var mquery = require_mquery(); var parseProjection = require_parseProjection(); var removeUnusedArrayFilters = require_removeUnusedArrayFilters(); var sanitizeFilter = require_sanitizeFilter(); var sanitizeProjection = require_sanitizeProjection(); var selectPopulatedFields = require_selectPopulatedFields(); var setDefaultsOnInsert = require_setDefaultsOnInsert(); var specialProperties = require_specialProperties(); var updateValidators = require_updateValidators(); var util = require("util"); var utils = require_utils3(); var queryMiddlewareFunctions = require_constants3().queryMiddlewareFunctions; var queryOptionMethods = /* @__PURE__ */ new Set([ "allowDiskUse", "batchSize", "collation", "comment", "explain", "hint", "j", "lean", "limit", "maxTimeMS", "populate", "projection", "read", "select", "skip", "slice", "sort", "tailable", "w", "writeConcern", "wtimeout" ]); var opToThunk = /* @__PURE__ */ new Map([ ["countDocuments", "_countDocuments"], ["distinct", "__distinct"], ["estimatedDocumentCount", "_estimatedDocumentCount"], ["find", "_find"], ["findOne", "_findOne"], ["findOneAndReplace", "_findOneAndReplace"], ["findOneAndUpdate", "_findOneAndUpdate"], ["replaceOne", "_replaceOne"], ["updateMany", "_updateMany"], ["updateOne", "_updateOne"], ["deleteMany", "_deleteMany"], ["deleteOne", "_deleteOne"], ["findOneAndDelete", "_findOneAndDelete"] ]); function Query(conditions, options, model, collection) { if (!this._mongooseOptions) { this._mongooseOptions = {}; } options = options || {}; this._transforms = []; this._hooks = new Kareem(); this._executionStack = null; const keys = Object.keys(options); for (const key of keys) { this._mongooseOptions[key] = options[key]; } if (collection) { this.mongooseCollection = collection; } if (model) { this.model = model; this.schema = model.schema; } if (this.model && this.model._mapreduce) { this.lean(); } mquery.call(this, null, options); if (collection) { this.collection(collection); } if (conditions) { this.find(conditions); } this.options = this.options || {}; this.$useProjection = true; const collation = this && this.schema && this.schema.options && this.schema.options.collation || null; if (collation != null) { this.options.collation = collation; } } function isEmptyFilter(obj) { if (obj == null) return true; if (typeof obj !== "object") return true; if (Object.keys(obj).length === 0) return true; for (const key of ["$and", "$or", "$nor"]) { if (Array.isArray(obj[key])) { if (obj[key].length === 0 || obj[key].every((item) => isEmptyFilter(item))) { return true; } } } return false; } function checkRequireFilter(filter, options) { if (options && options.requireFilter && isEmptyFilter(filter)) { throw new Error("Empty or invalid filter not allowed with requireFilter enabled"); } } Query.prototype = new mquery(); Query.prototype.constructor = Query; Query.prototype.count = void 0; Query.prototype.findOneAndRemove = void 0; Query.base = mquery.prototype; Object.defineProperty(Query.prototype, "_distinct", { configurable: true, writable: true, enumerable: true, value: void 0 }); Query.use$geoWithin = mquery.use$geoWithin; Query.prototype.toConstructor = function toConstructor() { const model = this.model; const coll = this.mongooseCollection; const CustomQuery = function(criteria, options2) { if (!(this instanceof CustomQuery)) { return new CustomQuery(criteria, options2); } this._mongooseOptions = clone(p._mongooseOptions); Query.call(this, criteria, options2 || null, model, coll); }; util.inherits(CustomQuery, model.Query); const p = CustomQuery.prototype; p.options = {}; const options = Object.assign({}, this.options); if (options.sort != null) { p.sort(options.sort); delete options.sort; } p.setOptions(options); p.op = this.op; p._validateOp(); p._conditions = clone(this._conditions); p._fields = clone(this._fields); p._update = clone(this._update, { flattenDecimals: false }); p._path = this._path; p._distinct = this._distinct; p._collection = this._collection; p._mongooseOptions = this._mongooseOptions; return CustomQuery; }; Query.prototype.clone = function() { const model = this.model; const collection = this.mongooseCollection; const q = new this.model.Query({}, {}, model, collection); const options = Object.assign({}, this.options); if (options.sort != null) { q.sort(options.sort); delete options.sort; } q.setOptions(options); q.op = this.op; q._validateOp(); q._conditions = clone(this._conditions); q._fields = clone(this._fields); q._update = clone(this._update, { flattenDecimals: false }); q._path = this._path; q._distinct = this._distinct; q._collection = this._collection; q._mongooseOptions = this._mongooseOptions; return q; }; Query.prototype.slice = function() { if (arguments.length === 0) { return this; } this._validate("slice"); let path; let val; if (arguments.length === 1) { const arg = arguments[0]; if (typeof arg === "object" && !Array.isArray(arg)) { const keys = Object.keys(arg); const numKeys = keys.length; for (let i = 0; i < numKeys; ++i) { this.slice(keys[i], arg[keys[i]]); } return this; } this._ensurePath("slice"); path = this._path; val = arguments[0]; } else if (arguments.length === 2) { if ("number" === typeof arguments[0]) { this._ensurePath("slice"); path = this._path; val = [arguments[0], arguments[1]]; } else { path = arguments[0]; val = arguments[1]; } } else if (arguments.length === 3) { path = arguments[0]; val = [arguments[1], arguments[2]]; } const p = {}; p[path] = { $slice: val }; this.select(p); return this; }; var validOpsSet = new Set(queryMiddlewareFunctions); Query.prototype._validateOp = function() { if (this.op != null && !validOpsSet.has(this.op)) { this.error(new Error('Query has invalid `op`: "' + this.op + '"')); } }; Query.prototype.mod = function() { let val; let path; if (arguments.length === 1) { this._ensurePath("mod"); val = arguments[0]; path = this._path; } else if (arguments.length === 2 && !Array.isArray(arguments[1])) { this._ensurePath("mod"); val = [arguments[0], arguments[1]]; path = this._path; } else if (arguments.length === 3) { val = [arguments[1], arguments[2]]; path = arguments[0]; } else { val = arguments[1]; path = arguments[0]; } const conds = this._conditions[path] || (this._conditions[path] = {}); conds.$mod = val; return this; }; Query.prototype.limit = function limit(v) { this._validate("limit"); if (typeof v === "string") { try { v = castNumber(v); } catch (err) { throw new CastError("Number", v, "limit"); } } this.options.limit = v; return this; }; Query.prototype.skip = function skip(v) { this._validate("skip"); if (typeof v === "string") { try { v = castNumber(v); } catch (err) { throw new CastError("Number", v, "skip"); } } this.options.skip = v; return this; }; Query.prototype.projection = function(arg) { if (arguments.length === 0) { return this._fields; } this._fields = {}; this._userProvidedFields = {}; this.select(arg); return this._fields; }; Query.prototype.select = function select() { let arg = arguments[0]; if (!arg) return this; if (arguments.length !== 1) { throw new Error("Invalid select: select only takes 1 argument"); } this._validate("select"); const fields = this._fields || (this._fields = {}); const userProvidedFields = this._userProvidedFields || (this._userProvidedFields = {}); let sanitizeProjection2 = void 0; if (this.model != null && utils.hasUserDefinedProperty(this.model.db.options, "sanitizeProjection")) { sanitizeProjection2 = this.model.db.options.sanitizeProjection; } else if (this.model != null && utils.hasUserDefinedProperty(this.model.base.options, "sanitizeProjection")) { sanitizeProjection2 = this.model.base.options.sanitizeProjection; } else { sanitizeProjection2 = this._mongooseOptions.sanitizeProjection; } function sanitizeValue(value) { return typeof value === "string" && sanitizeProjection2 ? value = 1 : value; } arg = parseProjection(arg, true); if (utils.isObject(arg)) { if (this.selectedInclusively()) { Object.entries(arg).forEach(([key, value]) => { if (value) { if (fields["-" + key] != null) { delete fields["-" + key]; } fields[key] = userProvidedFields[key] = sanitizeValue(value); } else { Object.keys(userProvidedFields).forEach((field) => { if (isSubpath(key, field)) { delete fields[field]; delete userProvidedFields[field]; } }); } }); } else if (this.selectedExclusively()) { Object.entries(arg).forEach(([key, value]) => { if (!value) { if (fields["+" + key] != null) { delete fields["+" + key]; } fields[key] = userProvidedFields[key] = sanitizeValue(value); } else { Object.keys(userProvidedFields).forEach((field) => { if (isSubpath(key, field)) { delete fields[field]; delete userProvidedFields[field]; } }); } }); } else { const keys = Object.keys(arg); for (let i = 0; i < keys.length; ++i) { const value = arg[keys[i]]; const key = keys[i]; fields[key] = sanitizeValue(value); userProvidedFields[key] = sanitizeValue(value); } } return this; } throw new TypeError("Invalid select() argument. Must be string or object."); }; Query.prototype.schemaLevelProjections = function schemaLevelProjections(value) { this._mongooseOptions.schemaLevelProjections = value; return this; }; Query.prototype.sanitizeProjection = function sanitizeProjection2(value) { this._mongooseOptions.sanitizeProjection = value; return this; }; Query.prototype.read = function read(mode, tags) { if (typeof mode === "string") { mode = handleReadPreferenceAliases(mode); this.options.readPreference = { mode, tags }; } else { this.options.readPreference = mode; } return this; }; Query.prototype.toString = function toString() { if (this.op === "count" || this.op === "countDocuments" || this.op === "find" || this.op === "findOne" || this.op === "deleteMany" || this.op === "deleteOne" || this.op === "findOneAndDelete" || this.op === "remove") { return `${this.model.modelName}.${this.op}(${util.inspect(this._conditions)})`; } if (this.op === "distinct") { return `${this.model.modelName}.distinct('${this._distinct}', ${util.inspect(this._conditions)})`; } if (this.op === "findOneAndReplace" || this.op === "findOneAndUpdate" || this.op === "replaceOne" || this.op === "update" || this.op === "updateMany" || this.op === "updateOne") { return `${this.model.modelName}.${this.op}(${util.inspect(this._conditions)}, ${util.inspect(this._update)})`; } return `${this.model.modelName}.${this.op}()`; }; Query.prototype.session = function session(v) { if (v == null) { delete this.options.session; } this.options.session = v; return this; }; Query.prototype.writeConcern = function writeConcern(val) { if (val == null) { delete this.options.writeConcern; return this; } this.options.writeConcern = val; return this; }; Query.prototype.w = function w(val) { if (val == null) { delete this.options.w; } if (this.options.writeConcern != null) { this.options.writeConcern.w = val; } else { this.options.w = val; } return this; }; Query.prototype.j = function j(val) { if (val == null) { delete this.options.j; } if (this.options.writeConcern != null) { this.options.writeConcern.j = val; } else { this.options.j = val; } return this; }; Query.prototype.wtimeout = function wtimeout(ms) { if (ms == null) { delete this.options.wtimeout; } if (this.options.writeConcern != null) { this.options.writeConcern.wtimeout = ms; } else { this.options.wtimeout = ms; } return this; }; Query.prototype.getOptions = function() { return this.options; }; Query.prototype.setOptions = function(options, overwrite) { if (overwrite) { this._mongooseOptions = options && clone(options) || {}; this.options = options || {}; if ("populate" in options) { this.populate(this._mongooseOptions); } return this; } if (options == null) { return this; } if (typeof options !== "object") { throw new Error('Options must be an object, got "' + options + '"'); } options = Object.assign({}, options); if (Array.isArray(options.populate)) { const populate = options.populate; delete options.populate; const _numPopulate = populate.length; for (let i = 0; i < _numPopulate; ++i) { this.populate(populate[i]); } } if ("setDefaultsOnInsert" in options) { this._mongooseOptions.setDefaultsOnInsert = options.setDefaultsOnInsert; delete options.setDefaultsOnInsert; } if ("overwriteDiscriminatorKey" in options) { this._mongooseOptions.overwriteDiscriminatorKey = options.overwriteDiscriminatorKey; delete options.overwriteDiscriminatorKey; } if ("overwriteImmutable" in options) { this._mongooseOptions.overwriteImmutable = options.overwriteImmutable; delete options.overwriteImmutable; } if ("sanitizeProjection" in options) { if (options.sanitizeProjection && !this._mongooseOptions.sanitizeProjection) { sanitizeProjection(this._fields); } this._mongooseOptions.sanitizeProjection = options.sanitizeProjection; delete options.sanitizeProjection; } if ("sanitizeFilter" in options) { this._mongooseOptions.sanitizeFilter = options.sanitizeFilter; delete options.sanitizeFilter; } if ("timestamps" in options) { this._mongooseOptions.timestamps = options.timestamps; delete options.timestamps; } if ("defaults" in options) { this._mongooseOptions.defaults = options.defaults; } if ("translateAliases" in options) { this._mongooseOptions.translateAliases = options.translateAliases; delete options.translateAliases; } if ("schemaLevelProjections" in options) { this._mongooseOptions.schemaLevelProjections = options.schemaLevelProjections; delete options.schemaLevelProjections; } if (options.lean == null && this.schema && "lean" in this.schema.options) { this._mongooseOptions.lean = this.schema.options.lean; } if (typeof options.limit === "string") { try { options.limit = castNumber(options.limit); } catch (err) { throw new CastError("Number", options.limit, "limit"); } } if (typeof options.skip === "string") { try { options.skip = castNumber(options.skip); } catch (err) { throw new CastError("Number", options.skip, "skip"); } } for (const key of Object.keys(options)) { if (queryOptionMethods.has(key)) { const args = Array.isArray(options[key]) ? options[key] : [options[key]]; this[key].apply(this, args); } else { this.options[key] = options[key]; } } return this; }; Query.prototype.explain = function explain(verbose) { if (arguments.length === 0) { this.options.explain = true; } else if (verbose === false) { delete this.options.explain; } else { this.options.explain = verbose; } return this; }; Query.prototype.allowDiskUse = function(v) { if (arguments.length === 0) { this.options.allowDiskUse = true; } else if (v === false) { delete this.options.allowDiskUse; } else { this.options.allowDiskUse = v; } return this; }; Query.prototype.maxTimeMS = function(ms) { this.options.maxTimeMS = ms; return this; }; Query.prototype.getFilter = function() { return this._conditions; }; Query.prototype.getQuery = function() { return this._conditions; }; Query.prototype.setQuery = function(val) { this._conditions = val; }; Query.prototype.getUpdate = function() { return this._update; }; Query.prototype.setUpdate = function(val) { this._update = val; }; Query.prototype._fieldsForExec = function() { if (this._fields == null) { return null; } if (Object.keys(this._fields).length === 0) { return null; } return clone(this._fields); }; Query.prototype._updateForExec = function() { const update = clone(this._update, { transform: false, depopulate: true }); const ops = Object.keys(update); let i = ops.length; const ret = {}; while (i--) { const op = ops[i]; if ("$" !== op[0]) { if (!ret.$set) { if (update.$set) { ret.$set = update.$set; } else { ret.$set = {}; } } ret.$set[op] = update[op]; ops.splice(i, 1); if (!~ops.indexOf("$set")) ops.push("$set"); } else if ("$set" === op) { if (!ret.$set) { ret[op] = update[op]; } } else { ret[op] = update[op]; } } return ret; }; Query.prototype._optionsForExec = function(model) { const options = clone(this.options); delete options.populate; model = model || this.model; if (!model) { return options; } applyReadConcern(model.schema, options); applyWriteConcern(model.schema, options); const asyncLocalStorage = this.model?.db?.base.transactionAsyncLocalStorage?.getStore(); if (!this.options.hasOwnProperty("session") && asyncLocalStorage?.session != null) { options.session = asyncLocalStorage.session; } const readPreference = model && model.schema && model.schema.options && model.schema.options.read; if (!("readPreference" in options) && readPreference) { options.readPreference = readPreference; } if (options.upsert !== void 0) { options.upsert = !!options.upsert; } if (options.writeConcern) { if (options.j) { options.writeConcern.j = options.j; delete options.j; } if (options.w) { options.writeConcern.w = options.w; delete options.w; } if (options.wtimeout) { options.writeConcern.wtimeout = options.wtimeout; delete options.wtimeout; } } this._applyPaths(); if (this._fields != null) { this._fields = this._castFields(this._fields); const projection = this._fieldsForExec(); if (projection != null) { options.projection = projection; } } if (this._mongooseOptions.populate) { if (options.readPreference) { for (const pop of Object.values(this._mongooseOptions.populate)) { if (pop.options?.readPreference === void 0) { if (!pop.options) { pop.options = {}; } pop.options.readPreference = options.readPreference; } } } if (options.readConcern) { for (const pop of Object.values(this._mongooseOptions.populate)) { if (pop.options?.readConcern === void 0) { if (!pop.options) { pop.options = {}; } pop.options.readConcern = options.readConcern; } } } } return options; }; Query.prototype.lean = function(v) { this._mongooseOptions.lean = arguments.length ? v : true; return this; }; Query.prototype.set = function(path, val) { if (typeof path === "object") { const keys = Object.keys(path); for (const key of keys) { this.set(key, path[key]); } return this; } this._update = this._update || {}; if (path in this._update) { delete this._update[path]; } this._update.$set = this._update.$set || {}; this._update.$set[path] = val; return this; }; Query.prototype.get = function get(path) { const update = this._update; if (update == null) { return void 0; } const $set = update.$set; if ($set == null) { return update[path]; } if (utils.hasUserDefinedProperty(update, path)) { return update[path]; } if (utils.hasUserDefinedProperty($set, path)) { return $set[path]; } return void 0; }; Query.prototype.error = function error(err) { if (arguments.length === 0) { return this._error; } this._error = err; return this; }; Query.prototype._unsetCastError = function _unsetCastError() { if (this._error == null || !(this._error instanceof CastError)) { return; } return this.error(null); }; Query.prototype.mongooseOptions = function(v) { if (arguments.length > 0) { this._mongooseOptions = v; } return this._mongooseOptions; }; Query.prototype._castConditions = function() { let sanitizeFilterOpt = void 0; if (this.model?.db.options?.sanitizeFilter != null) { sanitizeFilterOpt = this.model.db.options.sanitizeFilter; } else if (this.model?.base.options?.sanitizeFilter != null) { sanitizeFilterOpt = this.model.base.options.sanitizeFilter; } else { sanitizeFilterOpt = this._mongooseOptions.sanitizeFilter; } if (sanitizeFilterOpt) { sanitizeFilter(this._conditions); } try { this.cast(this.model); this._unsetCastError(); } catch (err) { this.error(err); } }; function _castArrayFilters(query) { try { castArrayFilters(query); } catch (err) { query.error(err); } } Query.prototype._find = async function _find() { this._applyTranslateAliases(); this._castConditions(); if (this.error() != null) { throw this.error(); } const mongooseOptions = this._mongooseOptions; const userProvidedFields = this._userProvidedFields || {}; applyGlobalMaxTimeMS(this.options, this.model.db.options, this.model.base.options); applyGlobalDiskUse(this.options, this.model.db.options, this.model.base.options); const completeManyOptions = { session: this && this.options && this.options.session || null, lean: mongooseOptions.lean || null }; const options = this._optionsForExec(); const filter = this._conditions; const fields = options.projection; const cursor = await this.mongooseCollection.find(filter, options); if (options.explain) { return cursor.explain(); } let docs = await cursor.toArray(); if (docs.length === 0) { return docs; } if (!mongooseOptions.populate) { const versionKey = this.schema.options.versionKey; if (mongooseOptions.lean && mongooseOptions.lean.versionKey === false && versionKey) { docs.forEach((doc) => { if (versionKey in doc) { delete doc[versionKey]; } }); } return mongooseOptions.lean ? _completeManyLean(this.model.schema, docs, null, completeManyOptions) : this._completeMany(docs, fields, userProvidedFields, completeManyOptions); } const pop = helpers.preparePopulationOptionsMQ(this, mongooseOptions); if (mongooseOptions.lean) { return this.model.populate(docs, pop); } docs = await this._completeMany(docs, fields, userProvidedFields, completeManyOptions); await this.model.populate(docs, pop); return docs; }; Query.prototype.find = function(conditions) { if (typeof conditions === "function" || typeof arguments[1] === "function") { throw new MongooseError("Query.prototype.find() no longer accepts a callback"); } this.op = "find"; if (mquery.canMerge(conditions)) { this.merge(conditions); prepareDiscriminatorCriteria(this); } else if (conditions != null) { this.error(new ObjectParameterError(conditions, "filter", "find")); } return this; }; Query.prototype.merge = function(source) { if (!source) { return this; } const opts = { overwrite: true }; if (source instanceof Query) { if (source._conditions) { opts.omit = {}; if (this._conditions && this._conditions.$and && source._conditions.$and) { opts.omit["$and"] = true; this._conditions.$and = this._conditions.$and.concat(source._conditions.$and); } if (this._conditions && this._conditions.$or && source._conditions.$or) { opts.omit["$or"] = true; this._conditions.$or = this._conditions.$or.concat(source._conditions.$or); } utils.merge(this._conditions, source._conditions, opts); } if (source._fields) { this._fields || (this._fields = {}); utils.merge(this._fields, source._fields, opts); } if (source.options) { this.options || (this.options = {}); utils.merge(this.options, source.options, opts); } if (source._update) { this._update || (this._update = {}); utils.mergeClone(this._update, source._update); } if (source._distinct) { this._distinct = source._distinct; } utils.merge(this._mongooseOptions, source._mongooseOptions); return this; } else if (this.model != null && source instanceof this.model.base.Types.ObjectId) { utils.merge(this._conditions, { _id: source }, opts); return this; } else if (source && source.$__) { source = source.toObject(internalToObjectOptions); } opts.omit = {}; if (Array.isArray(source.$and)) { opts.omit["$and"] = true; if (!this._conditions) { this._conditions = {}; } this._conditions.$and = (this._conditions.$and || []).concat( source.$and.map((el) => utils.isPOJO(el) ? utils.merge({}, el) : el) ); } if (Array.isArray(source.$or)) { opts.omit["$or"] = true; if (!this._conditions) { this._conditions = {}; } this._conditions.$or = (this._conditions.$or || []).concat( source.$or.map((el) => utils.isPOJO(el) ? utils.merge({}, el) : el) ); } utils.merge(this._conditions, source, opts); return this; }; Query.prototype.collation = function(value) { if (this.options == null) { this.options = {}; } this.options.collation = value; return this; }; Query.prototype._completeOne = function(doc, res, projection, callback) { if (!doc && !this.options.includeResultMetadata) { return callback(null, null); } const model = this.model; const userProvidedFields = this._userProvidedFields || {}; const mongooseOptions = this._mongooseOptions; const options = this.options; if (!options.lean && mongooseOptions.lean) { options.lean = mongooseOptions.lean; } if (options.explain) { return callback(null, doc); } if (!mongooseOptions.populate) { const versionKey = this.schema.options.versionKey; if (mongooseOptions.lean && mongooseOptions.lean.versionKey === false && versionKey) { if (versionKey in doc) { delete doc[versionKey]; } } return mongooseOptions.lean ? _completeOneLean(model.schema, doc, null, res, options, callback) : completeOne( model, doc, res, options, projection, userProvidedFields, null, callback ); } const pop = helpers.preparePopulationOptionsMQ(this, this._mongooseOptions); if (mongooseOptions.lean) { return model.populate(doc, pop).then( (doc2) => { _completeOneLean(model.schema, doc2, null, res, options, callback); }, (error) => { callback(error); } ); } completeOne(model, doc, res, options, projection, userProvidedFields, [], (err, doc2) => { if (err != null) { return callback(err); } model.populate(doc2, pop).then((res2) => { callback(null, res2); }, (err2) => { callback(err2); }); }); }; Query.prototype._completeMany = async function _completeMany(docs, fields, userProvidedFields, opts) { const model = this.model; return Promise.all(docs.map((doc) => new Promise((resolve, reject) => { const rawDoc = doc; doc = helpers.createModel(model, doc, fields, userProvidedFields); if (opts.session != null) { doc.$session(opts.session); } doc.$init(rawDoc, opts, (err) => { if (err != null) { return reject(err); } resolve(doc); }); }))); }; Query.prototype._findOne = async function _findOne() { this._applyTranslateAliases(); this._castConditions(); if (this.error()) { const err = this.error(); throw err; } applyGlobalMaxTimeMS(this.options, this.model.db.options, this.model.base.options); applyGlobalDiskUse(this.options, this.model.db.options, this.model.base.options); const options = this._optionsForExec(); const doc = await this.mongooseCollection.findOne(this._conditions, options); return new Promise((resolve, reject) => { this._completeOne(doc, null, options.projection, (err, res) => { if (err) { return reject(err); } resolve(res); }); }); }; Query.prototype.findOne = function(conditions, projection, options) { if (typeof conditions === "function" || typeof projection === "function" || typeof options === "function" || typeof arguments[3] === "function") { throw new MongooseError("Query.prototype.findOne() no longer accepts a callback"); } this.op = "findOne"; this._validateOp(); if (options) { this.setOptions(options); } if (projection) { this.select(projection); } if (mquery.canMerge(conditions)) { this.merge(conditions); prepareDiscriminatorCriteria(this); } else if (conditions != null) { this.error(new ObjectParameterError(conditions, "filter", "findOne")); } return this; }; Query.prototype._countDocuments = async function _countDocuments() { this._applyTranslateAliases(); try { this.cast(this.model); } catch (err) { this.error(err); } if (this.error()) { throw this.error(); } applyGlobalMaxTimeMS(this.options, this.model.db.options, this.model.base.options); applyGlobalDiskUse(this.options, this.model.db.options, this.model.base.options); const options = this._optionsForExec(); const conds = this._conditions; return this.mongooseCollection.countDocuments(conds, options); }; Query.prototype._applyTranslateAliases = function _applyTranslateAliases() { let applyTranslateAliases = false; if ("translateAliases" in this._mongooseOptions) { applyTranslateAliases = this._mongooseOptions.translateAliases; } else if (this.model?.schema?._userProvidedOptions?.translateAliases != null) { applyTranslateAliases = this.model.schema._userProvidedOptions.translateAliases; } else if (this.model?.base?.options?.translateAliases != null) { applyTranslateAliases = this.model.base.options.translateAliases; } if (!applyTranslateAliases) { return; } if (this.model?.schema?.aliases && Object.keys(this.model.schema.aliases).length > 0) { this.model.translateAliases(this._conditions, true); this.model.translateAliases(this._fields, true); this.model.translateAliases(this._update, true); if (this._distinct != null && this.model.schema.aliases[this._distinct] != null) { this._distinct = this.model.schema.aliases[this._distinct]; } } }; Query.prototype._estimatedDocumentCount = async function _estimatedDocumentCount() { if (this.error()) { throw this.error(); } const options = this._optionsForExec(); return this.mongooseCollection.estimatedDocumentCount(options); }; Query.prototype.estimatedDocumentCount = function(options) { if (typeof options === "function" || typeof arguments[1] === "function") { throw new MongooseError("Query.prototype.estimatedDocumentCount() no longer accepts a callback"); } this.op = "estimatedDocumentCount"; this._validateOp(); if (options != null) { this.setOptions(options); } return this; }; Query.prototype.countDocuments = function(conditions, options) { if (typeof conditions === "function" || typeof options === "function" || typeof arguments[2] === "function") { throw new MongooseError("Query.prototype.countDocuments() no longer accepts a callback"); } this.op = "countDocuments"; this._validateOp(); if (mquery.canMerge(conditions)) { this.merge(conditions); } if (options != null) { this.setOptions(options); } return this; }; Query.prototype.__distinct = async function __distinct() { this._applyTranslateAliases(); this._castConditions(); if (this.error()) { throw this.error(); } applyGlobalMaxTimeMS(this.options, this.model.db.options, this.model.base.options); applyGlobalDiskUse(this.options, this.model.db.options, this.model.base.options); const options = this._optionsForExec(); return this.mongooseCollection.distinct(this._distinct, this._conditions, options); }; Query.prototype.distinct = function(field, conditions, options) { if (typeof field === "function" || typeof conditions === "function" || typeof options === "function" || typeof arguments[3] === "function") { throw new MongooseError("Query.prototype.distinct() no longer accepts a callback"); } this.op = "distinct"; this._validateOp(); if (mquery.canMerge(conditions)) { this.merge(conditions); prepareDiscriminatorCriteria(this); } else if (conditions != null) { this.error(new ObjectParameterError(conditions, "filter", "distinct")); } if (field != null) { this._distinct = field; } if (options != null) { this.setOptions(options); } return this; }; Query.prototype.sort = function(arg, options) { if (arguments.length > 2) { throw new Error("sort() takes at most 2 arguments"); } if (options != null && typeof options !== "object") { throw new Error("sort() options argument must be an object or nullish"); } if (this.options.sort == null) { this.options.sort = {}; } if (options && options.override) { this.options.sort = {}; } const sort = this.options.sort; if (typeof arg === "string") { const properties = arg.indexOf(" ") === -1 ? [arg] : arg.split(" "); for (let property of properties) { const ascend = "-" == property[0] ? -1 : 1; if (ascend === -1) { property = property.slice(1); } if (specialProperties.has(property)) { continue; } sort[property] = ascend; } } else if (Array.isArray(arg)) { for (const pair of arg) { if (!Array.isArray(pair)) { throw new TypeError("Invalid sort() argument, must be array of arrays"); } const key = "" + pair[0]; if (specialProperties.has(key)) { continue; } sort[key] = _handleSortValue(pair[1], key); } } else if (typeof arg === "object" && arg != null && !(arg instanceof Map)) { for (const key of Object.keys(arg)) { if (specialProperties.has(key)) { continue; } sort[key] = _handleSortValue(arg[key], key); } } else if (arg instanceof Map) { for (let key of arg.keys()) { key = "" + key; if (specialProperties.has(key)) { continue; } sort[key] = _handleSortValue(arg.get(key), key); } } else if (arg != null) { throw new TypeError("Invalid sort() argument. Must be a string, object, array, or map."); } return this; }; function _handleSortValue(val, key) { if (val === 1 || val === "asc" || val === "ascending") { return 1; } if (val === -1 || val === "desc" || val === "descending") { return -1; } if (val?.$meta != null) { return { $meta: val.$meta }; } throw new TypeError("Invalid sort value: { " + key + ": " + val + " }"); } Query.prototype.deleteOne = function deleteOne(filter, options) { if (typeof filter === "function" || typeof options === "function" || typeof arguments[2] === "function") { throw new MongooseError("Query.prototype.deleteOne() no longer accepts a callback"); } this.op = "deleteOne"; this.setOptions(options); if (mquery.canMerge(filter)) { this.merge(filter); prepareDiscriminatorCriteria(this); } else if (filter != null) { this.error(new ObjectParameterError(filter, "filter", "deleteOne")); } return this; }; Query.prototype._deleteOne = async function _deleteOne() { this._applyTranslateAliases(); this._castConditions(); checkRequireFilter(this._conditions, this.options); if (this.error() != null) { throw this.error(); } const options = this._optionsForExec(); return this.mongooseCollection.deleteOne(this._conditions, options); }; Query.prototype.deleteMany = function(filter, options) { if (typeof filter === "function" || typeof options === "function" || typeof arguments[2] === "function") { throw new MongooseError("Query.prototype.deleteMany() no longer accepts a callback"); } this.setOptions(options); this.op = "deleteMany"; if (mquery.canMerge(filter)) { this.merge(filter); prepareDiscriminatorCriteria(this); } else if (filter != null) { this.error(new ObjectParameterError(filter, "filter", "deleteMany")); } return this; }; Query.prototype._deleteMany = async function _deleteMany() { this._applyTranslateAliases(); this._castConditions(); checkRequireFilter(this._conditions, this.options); if (this.error() != null) { throw this.error(); } const options = this._optionsForExec(); return this.mongooseCollection.deleteMany(this._conditions, options); }; function completeOne(model, doc, res, options, fields, userProvidedFields, pop, callback) { if (options.includeResultMetadata && doc == null) { _init(null); return null; } helpers.createModelAndInit(model, doc, fields, userProvidedFields, options, pop, _init); function _init(err, casted) { if (err) { return callback(err); } if (options.includeResultMetadata) { if (doc && casted) { if (options.session != null) { casted.$session(options.session); } res.value = casted; } else { res.value = null; } return callback(null, res); } if (options.session != null) { casted.$session(options.session); } callback(null, casted); } } function prepareDiscriminatorCriteria(query) { if (!query || !query.model || !query.model.schema) { return; } const schema = query.model.schema; if (schema && schema.discriminatorMapping && !schema.discriminatorMapping.isRoot) { query._conditions[schema.discriminatorMapping.key] = schema.discriminatorMapping.value; } } Query.prototype.findOneAndUpdate = function(filter, doc, options) { if (typeof filter === "function" || typeof doc === "function" || typeof options === "function" || typeof arguments[3] === "function") { throw new MongooseError("Query.prototype.findOneAndUpdate() no longer accepts a callback"); } this.op = "findOneAndUpdate"; this._validateOp(); this._validate(); switch (arguments.length) { case 2: options = void 0; break; case 1: doc = filter; filter = options = void 0; break; } if (mquery.canMerge(filter)) { this.merge(filter); } else if (filter != null) { this.error( new ObjectParameterError(filter, "filter", "findOneAndUpdate") ); } if (doc) { this._mergeUpdate(doc); } options = options ? clone(options) : {}; if (options.projection) { this.select(options.projection); delete options.projection; } if (options.fields) { this.select(options.fields); delete options.fields; } const returnOriginal = this && this.model && this.model.base && this.model.base.options && this.model.base.options.returnOriginal; if (options.new == null && options.returnDocument == null && options.returnOriginal == null && returnOriginal != null) { options.returnOriginal = returnOriginal; } this.setOptions(options); return this; }; Query.prototype._findOneAndUpdate = async function _findOneAndUpdate() { this._applyTranslateAliases(); this._castConditions(); checkRequireFilter(this._conditions, this.options); _castArrayFilters(this); if (this.error()) { throw this.error(); } applyGlobalMaxTimeMS(this.options, this.model.db.options, this.model.base.options); applyGlobalDiskUse(this.options, this.model.db.options, this.model.base.options); if ("strict" in this.options) { this._mongooseOptions.strict = this.options.strict; } const options = this._optionsForExec(this.model); convertNewToReturnDocument(options); this._update = this._castUpdate(this._update); const _opts = Object.assign({}, options, { setDefaultsOnInsert: this._mongooseOptions.setDefaultsOnInsert }); this._update = setDefaultsOnInsert( this._conditions, this.model.schema, this._update, _opts ); if (!this._update || Object.keys(this._update).length === 0) { if (options.upsert) { const $set = clone(this._update); delete $set._id; this._update = { $set }; } else { this._executionStack = null; const res2 = await this._findOne(); return res2; } } else if (this._update instanceof Error) { throw this._update; } else { if (this._update.$set && Object.keys(this._update.$set).length === 0) { delete this._update.$set; } } const runValidators = _getOption(this, "runValidators", false); if (runValidators) { await this.validate(this._update, options, false); } if (this._update.toBSON) { this._update = this._update.toBSON(); } let res = await this.mongooseCollection.findOneAndUpdate(this._conditions, this._update, options); for (const fn of this._transforms) { res = fn(res); } const doc = !options.includeResultMetadata ? res : res.value; return new Promise((resolve, reject) => { this._completeOne(doc, res, options.projection, (err, res2) => { if (err) { return reject(err); } resolve(res2); }); }); }; Query.prototype.findOneAndDelete = function(filter, options) { if (typeof filter === "function" || typeof options === "function" || typeof arguments[2] === "function") { throw new MongooseError("Query.prototype.findOneAndDelete() no longer accepts a callback"); } this.op = "findOneAndDelete"; this._validateOp(); this._validate(); if (mquery.canMerge(filter)) { this.merge(filter); } options && this.setOptions(options); return this; }; Query.prototype._findOneAndDelete = async function _findOneAndDelete() { this._applyTranslateAliases(); this._castConditions(); checkRequireFilter(this._conditions, this.options); if (this.error() != null) { throw this.error(); } const includeResultMetadata = this.options.includeResultMetadata; const filter = this._conditions; const options = this._optionsForExec(this.model); let res = await this.mongooseCollection.findOneAndDelete(filter, options); for (const fn of this._transforms) { res = fn(res); } const doc = !includeResultMetadata ? res : res.value; return new Promise((resolve, reject) => { this._completeOne(doc, res, options.projection, (err, res2) => { if (err) { return reject(err); } resolve(res2); }); }); }; Query.prototype.findOneAndReplace = function(filter, replacement, options) { if (typeof filter === "function" || typeof replacement === "function" || typeof options === "function" || typeof arguments[4] === "function") { throw new MongooseError("Query.prototype.findOneAndReplace() no longer accepts a callback"); } this.op = "findOneAndReplace"; this._validateOp(); this._validate(); if (mquery.canMerge(filter)) { this.merge(filter); } else if (filter != null) { this.error( new ObjectParameterError(filter, "filter", "findOneAndReplace") ); } if (replacement != null) { this._mergeUpdate(replacement); } options = options || {}; const returnOriginal = this && this.model && this.model.base && this.model.base.options && this.model.base.options.returnOriginal; if (options.new == null && options.returnDocument == null && options.returnOriginal == null && returnOriginal != null) { options.returnOriginal = returnOriginal; } this.setOptions(options); return this; }; Query.prototype._findOneAndReplace = async function _findOneAndReplace() { this._applyTranslateAliases(); this._castConditions(); checkRequireFilter(this._conditions, this.options); if (this.error() != null) { throw this.error(); } if ("strict" in this.options) { this._mongooseOptions.strict = this.options.strict; delete this.options.strict; } const filter = this._conditions; const options = this._optionsForExec(); convertNewToReturnDocument(options); const includeResultMetadata = this.options.includeResultMetadata; const modelOpts = { skipId: true }; if ("strict" in this._mongooseOptions) { modelOpts.strict = this._mongooseOptions.strict; } const runValidators = _getOption(this, "runValidators", false); try { const update = new this.model(this._update, null, modelOpts); if (runValidators) { await update.validate(); } else if (update.$__.validationError) { throw update.$__.validationError; } this._update = update.toBSON(); } catch (err) { if (err instanceof ValidationError) { throw err; } const validationError = new ValidationError(); validationError.errors[err.path] = err; throw validationError; } let res = await this.mongooseCollection.findOneAndReplace(filter, this._update, options); for (const fn of this._transforms) { res = fn(res); } const doc = !includeResultMetadata ? res : res.value; return new Promise((resolve, reject) => { this._completeOne(doc, res, options.projection, (err, res2) => { if (err) { return reject(err); } resolve(res2); }); }); }; Query.prototype.findById = function(id, projection, options) { return this.findOne({ _id: id }, projection, options); }; Query.prototype.findByIdAndUpdate = function(id, update, options) { return this.findOneAndUpdate({ _id: id }, update, options); }; Query.prototype.findByIdAndDelete = function(id, options) { return this.findOneAndDelete({ _id: id }, options); }; function convertNewToReturnDocument(options) { if ("new" in options) { options.returnDocument = options["new"] ? "after" : "before"; delete options["new"]; } if ("returnOriginal" in options) { options.returnDocument = options["returnOriginal"] ? "before" : "after"; delete options["returnOriginal"]; } if (typeof options.returnDocument === "string") { options.returnOriginal = options.returnDocument === "before"; } } function _getOption(query, option, def) { const opts = query._optionsForExec(query.model); if (option in opts) { return opts[option]; } if (option in query.model.base.options) { return query.model.base.options[option]; } return def; } function _completeOneLean(schema, doc, path, res, opts, callback) { if (opts.lean && typeof opts.lean.transform === "function") { opts.lean.transform(doc); for (let i = 0; i < schema.childSchemas.length; i++) { const childPath = path ? path + "." + schema.childSchemas[i].model.path : schema.childSchemas[i].model.path; const _schema = schema.childSchemas[i].schema; const obj = mpath.get(childPath, doc); if (obj == null) { continue; } if (Array.isArray(obj)) { for (let i2 = 0; i2 < obj.length; i2++) { opts.lean.transform(obj[i2]); } } else { opts.lean.transform(obj); } _completeOneLean(_schema, obj, childPath, res, opts); } if (callback) { return callback(null, doc); } else { return; } } if (opts.includeResultMetadata) { return callback(null, res); } return callback(null, doc); } function _completeManyLean(schema, docs, path, opts) { if (opts.lean && typeof opts.lean.transform === "function") { for (const doc of docs) { opts.lean.transform(doc); } for (let i = 0; i < schema.childSchemas.length; i++) { const childPath = path ? path + "." + schema.childSchemas[i].model.path : schema.childSchemas[i].model.path; const _schema = schema.childSchemas[i].schema; let doc = mpath.get(childPath, docs); if (doc == null) { continue; } doc = doc.flat(); for (let i2 = 0; i2 < doc.length; i2++) { opts.lean.transform(doc[i2]); } _completeManyLean(_schema, doc, childPath, opts); } } return docs; } Query.prototype._mergeUpdate = function(doc) { if (!this._update) { this._update = Array.isArray(doc) ? [] : {}; } if (doc == null || typeof doc === "object" && Object.keys(doc).length === 0) { return; } if (doc instanceof Query) { if (Array.isArray(this._update)) { throw new Error("Cannot mix array and object updates"); } if (doc._update) { utils.mergeClone(this._update, doc._update); } } else if (Array.isArray(doc)) { if (!Array.isArray(this._update)) { throw new Error("Cannot mix array and object updates"); } this._update = this._update.concat(doc); } else { if (Array.isArray(this._update)) { throw new Error("Cannot mix array and object updates"); } utils.mergeClone(this._update, doc); } }; async function _updateThunk(op) { this._applyTranslateAliases(); this._castConditions(); checkRequireFilter(this._conditions, this.options); _castArrayFilters(this); if (this.error() != null) { throw this.error(); } const castedQuery = this._conditions; const options = this._optionsForExec(this.model); this._update = clone(this._update, options); const isOverwriting = op === "replaceOne"; if (isOverwriting) { this._update = new this.model(this._update, null, true); } else { this._update = this._castUpdate(this._update); if (this._update == null || Object.keys(this._update).length === 0) { return { acknowledged: false }; } const _opts = Object.assign({}, options, { setDefaultsOnInsert: this._mongooseOptions.setDefaultsOnInsert }); this._update = setDefaultsOnInsert( this._conditions, this.model.schema, this._update, _opts ); } if (Array.isArray(options.arrayFilters)) { options.arrayFilters = removeUnusedArrayFilters(this._update, options.arrayFilters); } const runValidators = _getOption(this, "runValidators", false); if (runValidators) { await this.validate(this._update, options, isOverwriting); } if (this._update.toBSON) { this._update = this._update.toBSON(); } return this.mongooseCollection[op](castedQuery, this._update, options); } Query.prototype.validate = async function validate(castedDoc, options, isOverwriting) { if (typeof arguments[3] === "function") { throw new MongooseError("Query.prototype.validate() no longer accepts a callback"); } await _executePreHooks(this, "validate"); if (isOverwriting) { await castedDoc.$validate(); } else { await new Promise((resolve, reject) => { updateValidators(this, this.model.schema, castedDoc, options, (err) => { if (err != null) { return reject(err); } resolve(); }); }); } await _executePostHooks(this, null, null, "validate"); }; Query.prototype._updateMany = async function _updateMany() { return _updateThunk.call(this, "updateMany"); }; Query.prototype._updateOne = async function _updateOne() { return _updateThunk.call(this, "updateOne"); }; Query.prototype._replaceOne = async function _replaceOne() { return _updateThunk.call(this, "replaceOne"); }; Query.prototype.updateMany = function(conditions, doc, options, callback) { if (typeof options === "function") { callback = options; options = null; } else if (typeof doc === "function") { callback = doc; doc = conditions; conditions = {}; options = null; } else if (typeof conditions === "function") { callback = conditions; conditions = void 0; doc = void 0; options = void 0; } else if (typeof conditions === "object" && !doc && !options && !callback) { doc = conditions; conditions = void 0; options = void 0; callback = void 0; } return _update(this, "updateMany", conditions, doc, options, callback); }; Query.prototype.updateOne = function(conditions, doc, options, callback) { if (typeof options === "function") { callback = options; options = null; } else if (typeof doc === "function") { callback = doc; doc = conditions; conditions = {}; options = null; } else if (typeof conditions === "function") { callback = conditions; conditions = void 0; doc = void 0; options = void 0; } else if (typeof conditions === "object" && !doc && !options && !callback) { doc = conditions; conditions = void 0; options = void 0; callback = void 0; } return _update(this, "updateOne", conditions, doc, options, callback); }; Query.prototype.replaceOne = function(conditions, doc, options, callback) { if (typeof options === "function") { callback = options; options = null; } else if (typeof doc === "function") { callback = doc; doc = conditions; conditions = {}; options = null; } else if (typeof conditions === "function") { callback = conditions; conditions = void 0; doc = void 0; options = void 0; } else if (typeof conditions === "object" && !doc && !options && !callback) { doc = conditions; conditions = void 0; options = void 0; callback = void 0; } return _update(this, "replaceOne", conditions, doc, options, callback); }; function _update(query, op, filter, doc, options, callback) { query.op = op; query._validateOp(); doc = doc || {}; if (options != null) { if ("strict" in options) { query._mongooseOptions.strict = options.strict; } } if (!(filter instanceof Query) && filter != null && filter.toString() !== "[object Object]") { query.error(new ObjectParameterError(filter, "filter", op)); } else { query.merge(filter); } if (utils.isObject(options)) { query.setOptions(options); } query._mergeUpdate(doc); if (callback) { query.exec(callback); return query; } return query; } Query.prototype.transform = function(fn) { this._transforms.push(fn); return this; }; Query.prototype.orFail = function(err) { this.transform((res) => { switch (this.op) { case "find": if (res.length === 0) { throw _orFailError(err, this); } break; case "findOne": if (res == null) { throw _orFailError(err, this); } break; case "replaceOne": case "updateMany": case "updateOne": if (res && res.matchedCount === 0) { throw _orFailError(err, this); } break; case "findOneAndDelete": case "findOneAndUpdate": case "findOneAndReplace": if (this.options.includeResultMetadata && res != null && res.value == null) { throw _orFailError(err, this); } if (!this.options.includeResultMetadata && res == null) { throw _orFailError(err, this); } break; case "deleteMany": case "deleteOne": if (res.deletedCount === 0) { throw _orFailError(err, this); } break; default: break; } return res; }); return this; }; function _orFailError(err, query) { if (typeof err === "function") { err = err.call(query); } if (err == null) { err = new DocumentNotFoundError(query.getQuery(), query.model.modelName); } return err; } Query.prototype.isPathSelectedInclusive = function(path) { return isPathSelectedInclusive(this._fields, path); }; Query.prototype.exec = async function exec(op) { if (typeof op === "function" || arguments.length >= 2 && typeof arguments[1] === "function") { throw new MongooseError("Query.prototype.exec() no longer accepts a callback"); } if (typeof op === "string") { this.op = op; } if (this.op == null) { throw new MongooseError("Query must have `op` before executing"); } if (this.model == null) { throw new MongooseError("Query must have an associated model before executing"); } const thunk = opToThunk.get(this.op); if (!thunk) { throw new MongooseError('Query has invalid `op`: "' + this.op + '"'); } if (this.options && this.options.sort && typeof this.options.sort === "object" && this.options.sort.hasOwnProperty("")) { throw new Error('Invalid field "" passed to sort()'); } if (this._executionStack != null) { let str = this.toString(); if (str.length > 60) { str = str.slice(0, 60) + "..."; } const err = new MongooseError("Query was already executed: " + str); if (!this.model.base.options.skipOriginalStackTraces) { err.originalStack = this._executionStack; } throw err; } else { this._executionStack = this.model.base.options.skipOriginalStackTraces ? true : new Error().stack; } let skipWrappedFunction = null; try { await _executePreExecHooks(this); } catch (err) { if (err instanceof Kareem.skipWrappedFunction) { skipWrappedFunction = err; } else { throw err; } } let res; let error = null; try { await _executePreHooks(this); res = skipWrappedFunction ? skipWrappedFunction.args[0] : await this[thunk](); for (const fn of this._transforms) { res = fn(res); } } catch (err) { if (err instanceof Kareem.skipWrappedFunction) { res = err.args[0]; } else { error = err; } error = this.model.schema._transformDuplicateKeyError(error); } res = await _executePostHooks(this, res, error); await _executePostExecHooks(this); return res; }; function _executePostExecHooks(query) { return new Promise((resolve, reject) => { query._hooks.execPost("exec", query, [], {}, (error) => { if (error) { return reject(error); } resolve(); }); }); } function _executePostHooks(query, res, error, op) { if (query._queryMiddleware == null) { if (error != null) { throw error; } return res; } return new Promise((resolve, reject) => { const opts = error ? { error } : {}; query._queryMiddleware.execPost(op || query.op, query, [res], opts, (error2, res2) => { if (error2) { return reject(error2); } resolve(res2); }); }); } function _executePreExecHooks(query) { return new Promise((resolve, reject) => { query._hooks.execPre("exec", query, [], (error) => { if (error != null) { return reject(error); } resolve(); }); }); } function _executePreHooks(query, op) { if (query._queryMiddleware == null) { return; } return new Promise((resolve, reject) => { query._queryMiddleware.execPre(op || query.op, query, [], (error) => { if (error != null) { return reject(error); } resolve(); }); }); } Query.prototype.then = function(resolve, reject) { return this.exec().then(resolve, reject); }; Query.prototype.catch = function(reject) { return this.exec().then(null, reject); }; Query.prototype.finally = function(onFinally) { return this.exec().finally(onFinally); }; Query.prototype[Symbol.toStringTag] = function toString() { return `Query { ${this.op} }`; }; Query.prototype.pre = function(fn) { this._hooks.pre("exec", fn); return this; }; Query.prototype.post = function(fn) { this._hooks.post("exec", fn); return this; }; Query.prototype._castUpdate = function _castUpdate(obj) { let schema = this.schema; const discriminatorKey = schema.options.discriminatorKey; const baseSchema = schema._baseSchema ? schema._baseSchema : schema; if (this._mongooseOptions.overwriteDiscriminatorKey && obj[discriminatorKey] != null && baseSchema.discriminators) { const _schema = Object.values(baseSchema.discriminators).find( (discriminator) => discriminator.discriminatorMapping.value === obj[discriminatorKey] ); if (_schema != null) { schema = _schema; } } let upsert; if ("upsert" in this.options) { upsert = this.options.upsert; } return castUpdate(schema, obj, { strict: this._mongooseOptions.strict, upsert, arrayFilters: this.options.arrayFilters, overwriteDiscriminatorKey: this._mongooseOptions.overwriteDiscriminatorKey, overwriteImmutable: this._mongooseOptions.overwriteImmutable }, this, this._conditions); }; Query.prototype.populate = function() { const args = Array.from(arguments); if (!args.some(Boolean)) { return this; } const res = utils.populate.apply(null, args); const opts = this._mongooseOptions; if (opts.lean != null) { const lean = opts.lean; for (const populateOptions of res) { if ((populateOptions && populateOptions.options && populateOptions.options.lean) == null) { populateOptions.options = populateOptions.options || {}; populateOptions.options.lean = lean; } } } if (!utils.isObject(opts.populate)) { opts.populate = {}; } const pop = opts.populate; for (const populateOptions of res) { const path = populateOptions.path; if (pop[path] && pop[path].populate && populateOptions.populate) { populateOptions.populate = pop[path].populate.concat(populateOptions.populate); } pop[populateOptions.path] = populateOptions; } return this; }; Query.prototype.getPopulatedPaths = function getPopulatedPaths() { const obj = this._mongooseOptions.populate || {}; const ret = Object.keys(obj); for (const path of Object.keys(obj)) { const pop = obj[path]; if (!Array.isArray(pop.populate)) { continue; } _getPopulatedPaths(ret, pop.populate, path + "."); } return ret; }; function _getPopulatedPaths(list, arr, prefix) { for (const pop of arr) { list.push(prefix + pop.path); if (!Array.isArray(pop.populate)) { continue; } _getPopulatedPaths(list, pop.populate, prefix + pop.path + "."); } } Query.prototype.cast = function(model, obj) { obj || (obj = this._conditions); model = model || this.model; const discriminatorKey = model.schema.options.discriminatorKey; if (obj != null && obj.hasOwnProperty(discriminatorKey)) { model = getDiscriminatorByValue(model.discriminators, obj[discriminatorKey]) || model; } const opts = { upsert: this.options && this.options.upsert }; if (this.options) { if ("strict" in this.options) { opts.strict = this.options.strict; } if ("strictQuery" in this.options) { opts.strictQuery = this.options.strictQuery; } } if ("sanitizeFilter" in this._mongooseOptions) { opts.sanitizeFilter = this._mongooseOptions.sanitizeFilter; } try { return cast(model.schema, obj, opts, this); } catch (err) { if (typeof err.setModel === "function") { err.setModel(model); } throw err; } }; Query.prototype._castFields = function _castFields(fields) { let selected, elemMatchKeys, keys, key, out; if (fields) { keys = Object.keys(fields); elemMatchKeys = []; for (let i = 0; i < keys.length; ++i) { key = keys[i]; if (fields[key].$elemMatch) { selected || (selected = {}); selected[key] = fields[key]; elemMatchKeys.push(key); } } } if (selected) { try { out = this.cast(this.model, selected); } catch (err) { return err; } for (let i = 0; i < elemMatchKeys.length; ++i) { key = elemMatchKeys[i]; fields[key] = out[key]; } } return fields; }; Query.prototype._applyPaths = function applyPaths() { if (!this.model) { return; } this._fields = this._fields || {}; let sanitizeProjection2 = void 0; if (this.model != null && utils.hasUserDefinedProperty(this.model.db.options, "sanitizeProjection")) { sanitizeProjection2 = this.model.db.options.sanitizeProjection; } else if (this.model != null && utils.hasUserDefinedProperty(this.model.base.options, "sanitizeProjection")) { sanitizeProjection2 = this.model.base.options.sanitizeProjection; } else { sanitizeProjection2 = this._mongooseOptions.sanitizeProjection; } const schemaLevelProjections = this._mongooseOptions.schemaLevelProjections ?? true; if (schemaLevelProjections) { helpers.applyPaths(this._fields, this.model.schema, sanitizeProjection2); } let _selectPopulatedPaths = true; if ("selectPopulatedPaths" in this.model.base.options) { _selectPopulatedPaths = this.model.base.options.selectPopulatedPaths; } if ("selectPopulatedPaths" in this.model.schema.options) { _selectPopulatedPaths = this.model.schema.options.selectPopulatedPaths; } if (_selectPopulatedPaths) { selectPopulatedFields(this._fields, this._userProvidedFields, this._mongooseOptions.populate); } }; Query.prototype.cursor = function cursor(opts) { if (opts) { this.setOptions(opts); } try { this.cast(this.model); } catch (err) { return new QueryCursor(this)._markError(err); } return new QueryCursor(this); }; Query.prototype.tailable = function(val, opts) { if (val != null && typeof val.constructor === "function" && val.constructor.name === "Object") { opts = val; val = true; } if (val === void 0) { val = true; } if (opts && typeof opts === "object") { for (const key of Object.keys(opts)) { if (key === "awaitData" || key === "awaitdata") { this.options["awaitData"] = !!opts[key]; } else { this.options[key] = opts[key]; } } } this.options.tailable = arguments.length ? !!val : true; return this; }; Query.prototype.near = function() { const params = []; const sphere = this._mongooseOptions.nearSphere; if (arguments.length === 1) { if (Array.isArray(arguments[0])) { params.push({ center: arguments[0], spherical: sphere }); } else if (typeof arguments[0] === "string") { params.push(arguments[0]); } else if (utils.isObject(arguments[0])) { if (typeof arguments[0].spherical !== "boolean") { arguments[0].spherical = sphere; } params.push(arguments[0]); } else { throw new TypeError("invalid argument"); } } else if (arguments.length === 2) { if (typeof arguments[0] === "number" && typeof arguments[1] === "number") { params.push({ center: [arguments[0], arguments[1]], spherical: sphere }); } else if (typeof arguments[0] === "string" && Array.isArray(arguments[1])) { params.push(arguments[0]); params.push({ center: arguments[1], spherical: sphere }); } else if (typeof arguments[0] === "string" && utils.isObject(arguments[1])) { params.push(arguments[0]); if (typeof arguments[1].spherical !== "boolean") { arguments[1].spherical = sphere; } params.push(arguments[1]); } else { throw new TypeError("invalid argument"); } } else if (arguments.length === 3) { if (typeof arguments[0] === "string" && typeof arguments[1] === "number" && typeof arguments[2] === "number") { params.push(arguments[0]); params.push({ center: [arguments[1], arguments[2]], spherical: sphere }); } else { throw new TypeError("invalid argument"); } } else { throw new TypeError("invalid argument"); } return Query.base.near.apply(this, params); }; Query.prototype.nearSphere = function() { this._mongooseOptions.nearSphere = true; this.near.apply(this, arguments); return this; }; if (Symbol.asyncIterator != null) { Query.prototype[Symbol.asyncIterator] = function queryAsyncIterator() { this._mongooseOptions._asyncIterator = true; return this.cursor(); }; } Query.prototype.box = function(ll, ur) { if (!Array.isArray(ll) && utils.isObject(ll)) { ur = ll.ur; ll = ll.ll; } return Query.base.box.call(this, ll, ur); }; Query.prototype.center = Query.base.circle; Query.prototype.centerSphere = function() { if (arguments[0] != null && typeof arguments[0].constructor === "function" && arguments[0].constructor.name === "Object") { arguments[0].spherical = true; } if (arguments[1] != null && typeof arguments[1].constructor === "function" && arguments[1].constructor.name === "Object") { arguments[1].spherical = true; } Query.base.circle.apply(this, arguments); }; Query.prototype.selectedInclusively = function selectedInclusively() { return isInclusive(this._fields); }; Query.prototype.selectedExclusively = function selectedExclusively() { return isExclusive(this._fields); }; Query.prototype.model; module2.exports = Query; } }); // netlify/functions/node_modules/mongoose/lib/cursor/aggregationCursor.js var require_aggregationCursor = __commonJS({ "netlify/functions/node_modules/mongoose/lib/cursor/aggregationCursor.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var Readable = require("stream").Readable; var eachAsync = require_eachAsync(); var immediate = require_immediate(); var kareem = require_kareem(); var util = require("util"); function AggregationCursor(agg) { Readable.call(this, { autoDestroy: true, objectMode: true }); this.cursor = null; this.agg = agg; this._transforms = []; const connection = agg._connection; const model = agg._model; delete agg.options.cursor.useMongooseAggCursor; this._mongooseOptions = {}; if (connection) { this.cursor = connection.db.aggregate(agg._pipeline, agg.options || {}); setImmediate(() => this.emit("cursor", this.cursor)); } else { _init(model, this, agg); } } util.inherits(AggregationCursor, Readable); function _init(model, c, agg) { if (!model.collection.buffer) { model.hooks.execPre("aggregate", agg, function(err) { if (err != null) { _handlePreHookError(c, err); return; } if (typeof agg.options?.cursor?.transform === "function") { c._transforms.push(agg.options.cursor.transform); } c.cursor = model.collection.aggregate(agg._pipeline, agg.options || {}); c.emit("cursor", c.cursor); }); } else { model.collection.emitter.once("queue", function() { model.hooks.execPre("aggregate", agg, function(err) { if (err != null) { _handlePreHookError(c, err); return; } if (typeof agg.options?.cursor?.transform === "function") { c._transforms.push(agg.options.cursor.transform); } c.cursor = model.collection.aggregate(agg._pipeline, agg.options || {}); c.emit("cursor", c.cursor); }); }); } } function _handlePreHookError(queryCursor, err) { if (err instanceof kareem.skipWrappedFunction) { const resultValue = err.args[0]; if (resultValue != null && (!Array.isArray(resultValue) || resultValue.length)) { const err2 = new MongooseError( 'Cannot `skipMiddlewareFunction()` with a value when using `.aggregate().cursor()`, value must be nullish or empty array, got "' + util.inspect(resultValue) + '".' ); queryCursor._markError(err2); queryCursor.listeners("error").length > 0 && queryCursor.emit("error", err2); return; } queryCursor.emit("cursor", null); return; } queryCursor._markError(err); queryCursor.listeners("error").length > 0 && queryCursor.emit("error", err); } AggregationCursor.prototype._read = function() { const _this = this; _next(this, function(error, doc) { if (error) { return _this.emit("error", error); } if (!doc) { _this.push(null); _this.cursor.close(function(error2) { if (error2) { return _this.emit("error", error2); } }); return; } _this.push(doc); }); }; if (Symbol.asyncIterator != null) { const msg = "Mongoose does not support using async iterators with an existing aggregation cursor. See https://bit.ly/mongoose-async-iterate-aggregation"; AggregationCursor.prototype[Symbol.asyncIterator] = function() { throw new MongooseError(msg); }; } Object.defineProperty(AggregationCursor.prototype, "map", { value: function(fn) { this._transforms.push(fn); return this; }, enumerable: true, configurable: true, writable: true }); AggregationCursor.prototype._markError = function(error) { this._error = error; return this; }; AggregationCursor.prototype.close = async function close() { if (typeof arguments[0] === "function") { throw new MongooseError("AggregationCursor.prototype.close() no longer accepts a callback"); } try { await this.cursor.close(); } catch (error) { this.listeners("error").length > 0 && this.emit("error", error); throw error; } this.emit("close"); }; AggregationCursor.prototype._destroy = function _destroy(_err, callback) { let waitForCursor = null; if (!this.cursor) { waitForCursor = new Promise((resolve) => { this.once("cursor", resolve); }); } else { waitForCursor = Promise.resolve(); } waitForCursor.then(() => this.cursor.close()).then(() => { this._closed = true; callback(); }).catch((error) => { callback(error); }); return this; }; AggregationCursor.prototype.next = async function next() { if (typeof arguments[0] === "function") { throw new MongooseError("AggregationCursor.prototype.next() no longer accepts a callback"); } return new Promise((resolve, reject) => { _next(this, (err, res) => { if (err != null) { return reject(err); } resolve(res); }); }); }; AggregationCursor.prototype.eachAsync = function(fn, opts) { if (typeof arguments[2] === "function") { throw new MongooseError("AggregationCursor.prototype.eachAsync() no longer accepts a callback"); } const _this = this; if (typeof opts === "function") { opts = {}; } opts = opts || {}; return eachAsync(function(cb) { return _next(_this, cb); }, fn, opts); }; if (Symbol.asyncIterator != null) { AggregationCursor.prototype[Symbol.asyncIterator] = function() { return this.transformNull()._transformForAsyncIterator(); }; } AggregationCursor.prototype._transformForAsyncIterator = function() { if (this._transforms.indexOf(_transformForAsyncIterator) === -1) { this.map(_transformForAsyncIterator); } return this; }; AggregationCursor.prototype.transformNull = function(val) { if (arguments.length === 0) { val = true; } this._mongooseOptions.transformNull = val; return this; }; function _transformForAsyncIterator(doc) { return doc == null ? { done: true } : { value: doc, done: false }; } AggregationCursor.prototype.addCursorFlag = function(flag, value) { const _this = this; _waitForCursor(this, function() { _this.cursor.addCursorFlag(flag, value); }); return this; }; function _waitForCursor(ctx, cb) { if (ctx.cursor) { return cb(); } ctx.once("cursor", function() { cb(); }); } function _next(ctx, cb) { let callback = cb; if (ctx._transforms.length) { callback = function(err, doc) { if (err || doc === null && !ctx._mongooseOptions.transformNull) { return cb(err, doc); } cb(err, ctx._transforms.reduce(function(doc2, fn) { return fn(doc2); }, doc)); }; } if (ctx._error) { return immediate(function() { callback(ctx._error); }); } if (ctx.cursor) { return ctx.cursor.next().then( (doc) => { if (!doc) { return callback(null, null); } callback(null, doc); }, (err) => callback(err) ); } else { ctx.once("error", cb); ctx.once("cursor", function() { _next(ctx, cb); }); } } module2.exports = AggregationCursor; } }); // netlify/functions/node_modules/mongoose/lib/helpers/aggregate/prepareDiscriminatorPipeline.js var require_prepareDiscriminatorPipeline = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/aggregate/prepareDiscriminatorPipeline.js"(exports2, module2) { "use strict"; module2.exports = function prepareDiscriminatorPipeline(pipeline, schema, prefix) { const discriminatorMapping = schema && schema.discriminatorMapping; prefix = prefix || ""; if (discriminatorMapping && !discriminatorMapping.isRoot) { const originalPipeline = pipeline; const filterKey = (prefix.length > 0 ? prefix + "." : prefix) + discriminatorMapping.key; const discriminatorValue = discriminatorMapping.value; if (originalPipeline[0] != null && originalPipeline[0].$match && (originalPipeline[0].$match[filterKey] === void 0 || originalPipeline[0].$match[filterKey] === discriminatorValue)) { originalPipeline[0].$match[filterKey] = discriminatorValue; } else if (originalPipeline[0] != null && originalPipeline[0].$geoNear) { originalPipeline[0].$geoNear.query = originalPipeline[0].$geoNear.query || {}; originalPipeline[0].$geoNear.query[filterKey] = discriminatorValue; } else if (originalPipeline[0] != null && originalPipeline[0].$search) { if (originalPipeline[1] && originalPipeline[1].$match != null) { originalPipeline[1].$match[filterKey] = originalPipeline[1].$match[filterKey] || discriminatorValue; } else { const match = {}; match[filterKey] = discriminatorValue; originalPipeline.splice(1, 0, { $match: match }); } } else { const match = {}; match[filterKey] = discriminatorValue; originalPipeline.unshift({ $match: match }); } } }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/aggregate/stringifyFunctionOperators.js var require_stringifyFunctionOperators = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/aggregate/stringifyFunctionOperators.js"(exports2, module2) { "use strict"; module2.exports = function stringifyFunctionOperators(pipeline) { if (!Array.isArray(pipeline)) { return; } for (const stage of pipeline) { if (stage == null) { continue; } const canHaveAccumulator = stage.$group || stage.$bucket || stage.$bucketAuto; if (canHaveAccumulator != null) { for (const key of Object.keys(canHaveAccumulator)) { handleAccumulator(canHaveAccumulator[key]); } } const stageType = Object.keys(stage)[0]; if (stageType && typeof stage[stageType] === "object") { const stageOptions = stage[stageType]; for (const key of Object.keys(stageOptions)) { if (stageOptions[key] != null && stageOptions[key].$function != null && typeof stageOptions[key].$function.body === "function") { stageOptions[key].$function.body = stageOptions[key].$function.body.toString(); } } } if (stage.$facet != null) { for (const key of Object.keys(stage.$facet)) { stringifyFunctionOperators(stage.$facet[key]); } } } }; function handleAccumulator(operator) { if (operator == null || operator.$accumulator == null) { return; } for (const key of ["init", "accumulate", "merge", "finalize"]) { if (typeof operator.$accumulator[key] === "function") { operator.$accumulator[key] = String(operator.$accumulator[key]); } } } } }); // netlify/functions/node_modules/mongoose/lib/aggregate.js var require_aggregate2 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/aggregate.js"(exports2, module2) { "use strict"; var AggregationCursor = require_aggregationCursor(); var MongooseError = require_mongooseError(); var Query = require_query(); var { applyGlobalMaxTimeMS, applyGlobalDiskUse } = require_applyGlobalOption(); var clone = require_clone(); var getConstructorName = require_getConstructorName(); var prepareDiscriminatorPipeline = require_prepareDiscriminatorPipeline(); var stringifyFunctionOperators = require_stringifyFunctionOperators(); var utils = require_utils3(); var { modelSymbol } = require_symbols(); var read = Query.prototype.read; var readConcern = Query.prototype.readConcern; var validRedactStringValues = /* @__PURE__ */ new Set(["$$DESCEND", "$$PRUNE", "$$KEEP"]); function Aggregate(pipeline, modelOrConn) { this._pipeline = []; if (modelOrConn == null || modelOrConn[modelSymbol]) { this._model = modelOrConn; } else { this._connection = modelOrConn; } this.options = {}; if (arguments.length === 1 && Array.isArray(pipeline)) { this.append.apply(this, pipeline); } } Aggregate.prototype.options; Aggregate.prototype._optionsForExec = function() { const options = this.options || {}; const asyncLocalStorage = this.model()?.db?.base.transactionAsyncLocalStorage?.getStore(); if (!options.hasOwnProperty("session") && asyncLocalStorage?.session != null) { options.session = asyncLocalStorage.session; } return options; }; Aggregate.prototype.model = function(model) { if (arguments.length === 0) { return this._model; } this._model = model; if (model.schema != null) { if (this.options.readPreference == null && model.schema.options.read != null) { this.options.readPreference = model.schema.options.read; } if (this.options.collation == null && model.schema.options.collation != null) { this.options.collation = model.schema.options.collation; } } return model; }; Aggregate.prototype.append = function() { const args = arguments.length === 1 && Array.isArray(arguments[0]) ? arguments[0] : [...arguments]; if (!args.every(isOperator)) { throw new Error("Arguments must be aggregate pipeline operators"); } this._pipeline = this._pipeline.concat(args); return this; }; Aggregate.prototype.addFields = function(arg) { if (typeof arg !== "object" || arg === null || Array.isArray(arg)) { throw new Error("Invalid addFields() argument. Must be an object"); } return this.append({ $addFields: Object.assign({}, arg) }); }; Aggregate.prototype.project = function(arg) { const fields = {}; if (typeof arg === "object" && !Array.isArray(arg)) { Object.keys(arg).forEach(function(field) { fields[field] = arg[field]; }); } else if (arguments.length === 1 && typeof arg === "string") { arg.split(/\s+/).forEach(function(field) { if (!field) { return; } const include = field[0] === "-" ? 0 : 1; if (include === 0) { field = field.substring(1); } fields[field] = include; }); } else { throw new Error("Invalid project() argument. Must be string or object"); } return this.append({ $project: fields }); }; Aggregate.prototype.near = function(arg) { if (arg == null) { throw new MongooseError("Aggregate `near()` must be called with non-nullish argument"); } if (arg.near == null) { throw new MongooseError("Aggregate `near()` argument must have a `near` property"); } const coordinates = Array.isArray(arg.near) ? arg.near : arg.near.coordinates; if (typeof arg.near === "object" && (!Array.isArray(coordinates) || coordinates.length < 2 || coordinates.find((c) => typeof c !== "number"))) { throw new MongooseError(`Aggregate \`near()\` argument has invalid coordinates, got "${coordinates}"`); } const op = {}; op.$geoNear = arg; return this.append(op); }; "group match skip limit out densify fill".split(" ").forEach(function($operator) { Aggregate.prototype[$operator] = function(arg) { const op = {}; op["$" + $operator] = arg; return this.append(op); }; }); Aggregate.prototype.unwind = function() { const args = [...arguments]; const res = []; for (const arg of args) { if (arg && typeof arg === "object") { res.push({ $unwind: arg }); } else if (typeof arg === "string") { res.push({ $unwind: arg[0] === "$" ? arg : "$" + arg }); } else { throw new Error('Invalid arg "' + arg + '" to unwind(), must be string or object'); } } return this.append.apply(this, res); }; Aggregate.prototype.replaceRoot = function(newRoot) { let ret; if (typeof newRoot === "string") { ret = newRoot.startsWith("$") ? newRoot : "$" + newRoot; } else { ret = newRoot; } return this.append({ $replaceRoot: { newRoot: ret } }); }; Aggregate.prototype.count = function(fieldName) { return this.append({ $count: fieldName }); }; Aggregate.prototype.sortByCount = function(arg) { if (arg && typeof arg === "object") { return this.append({ $sortByCount: arg }); } else if (typeof arg === "string") { return this.append({ $sortByCount: arg[0] === "$" ? arg : "$" + arg }); } else { throw new TypeError('Invalid arg "' + arg + '" to sortByCount(), must be string or object'); } }; Aggregate.prototype.lookup = function(options) { return this.append({ $lookup: options }); }; Aggregate.prototype.graphLookup = function(options) { const cloneOptions = {}; if (options) { if (!utils.isObject(options)) { throw new TypeError("Invalid graphLookup() argument. Must be an object."); } utils.mergeClone(cloneOptions, options); const startWith = cloneOptions.startWith; if (startWith && typeof startWith === "string") { cloneOptions.startWith = cloneOptions.startWith.startsWith("$") ? cloneOptions.startWith : "$" + cloneOptions.startWith; } } return this.append({ $graphLookup: cloneOptions }); }; Aggregate.prototype.sample = function(size) { return this.append({ $sample: { size } }); }; Aggregate.prototype.sort = function(arg) { const sort = {}; if (getConstructorName(arg) === "Object") { const desc = ["desc", "descending", -1]; Object.keys(arg).forEach(function(field) { if (arg[field] instanceof Object && arg[field].$meta) { sort[field] = arg[field]; return; } sort[field] = desc.indexOf(arg[field]) === -1 ? 1 : -1; }); } else if (arguments.length === 1 && typeof arg === "string") { arg.split(/\s+/).forEach(function(field) { if (!field) { return; } const ascend = field[0] === "-" ? -1 : 1; if (ascend === -1) { field = field.substring(1); } sort[field] = ascend; }); } else { throw new TypeError("Invalid sort() argument. Must be a string or object."); } return this.append({ $sort: sort }); }; Aggregate.prototype.unionWith = function(options) { return this.append({ $unionWith: options }); }; Aggregate.prototype.read = function(pref, tags) { read.call(this, pref, tags); return this; }; Aggregate.prototype.readConcern = function(level) { readConcern.call(this, level); return this; }; Aggregate.prototype.redact = function(expression, thenExpr, elseExpr) { if (arguments.length === 3) { if (typeof thenExpr === "string" && !validRedactStringValues.has(thenExpr) || typeof elseExpr === "string" && !validRedactStringValues.has(elseExpr)) { throw new Error("If thenExpr or elseExpr is string, it must be either $$DESCEND, $$PRUNE or $$KEEP"); } expression = { $cond: { if: expression, then: thenExpr, else: elseExpr } }; } else if (arguments.length !== 1) { throw new TypeError("Invalid arguments"); } return this.append({ $redact: expression }); }; Aggregate.prototype.explain = async function explain(verbosity) { if (typeof verbosity === "function" || typeof arguments[1] === "function") { throw new MongooseError("Aggregate.prototype.explain() no longer accepts a callback"); } const model = this._model; if (!this._pipeline.length) { throw new Error("Aggregate has empty pipeline"); } prepareDiscriminatorPipeline(this._pipeline, this._model.schema); await new Promise((resolve, reject) => { model.hooks.execPre("aggregate", this, (error) => { if (error) { const _opts2 = { error }; return model.hooks.execPost("aggregate", this, [null], _opts2, (error2) => { reject(error2); }); } else { resolve(); } }); }); const cursor = model.collection.aggregate(this._pipeline, this.options); if (verbosity == null) { verbosity = true; } let result = null; try { result = await cursor.explain(verbosity); } catch (error) { await new Promise((resolve, reject) => { const _opts2 = { error }; model.hooks.execPost("aggregate", this, [null], _opts2, (error2) => { if (error2) { return reject(error2); } return resolve(); }); }); } const _opts = { error: null }; await new Promise((resolve, reject) => { model.hooks.execPost("aggregate", this, [result], _opts, (error) => { if (error) { return reject(error); } return resolve(); }); }); return result; }; Aggregate.prototype.allowDiskUse = function(value) { this.options.allowDiskUse = value; return this; }; Aggregate.prototype.hint = function(value) { this.options.hint = value; return this; }; Aggregate.prototype.session = function(session) { if (session == null) { delete this.options.session; } else { this.options.session = session; } return this; }; Aggregate.prototype.option = function(value) { for (const key in value) { this.options[key] = value[key]; } return this; }; Aggregate.prototype.cursor = function(options) { this._optionsForExec(); this.options.cursor = options || {}; return new AggregationCursor(this); }; Aggregate.prototype.collation = function(collation) { this.options.collation = collation; return this; }; Aggregate.prototype.facet = function(options) { return this.append({ $facet: options }); }; Aggregate.prototype.search = function(options) { return this.append({ $search: options }); }; Aggregate.prototype.pipeline = function() { return this._pipeline; }; Aggregate.prototype.exec = async function exec() { if (!this._model && !this._connection) { throw new Error("Aggregate not bound to any Model"); } if (typeof arguments[0] === "function") { throw new MongooseError("Aggregate.prototype.exec() no longer accepts a callback"); } if (this._connection) { if (!this._pipeline.length) { throw new MongooseError("Aggregate has empty pipeline"); } this._optionsForExec(); const cursor = await this._connection.client.db().aggregate(this._pipeline, this.options); return await cursor.toArray(); } const model = this._model; const collection = this._model.collection; applyGlobalMaxTimeMS(this.options, model.db.options, model.base.options); applyGlobalDiskUse(this.options, model.db.options, model.base.options); this._optionsForExec(); if (this.options && this.options.cursor) { return new AggregationCursor(this); } prepareDiscriminatorPipeline(this._pipeline, this._model.schema); stringifyFunctionOperators(this._pipeline); await new Promise((resolve, reject) => { model.hooks.execPre("aggregate", this, (error) => { if (error) { const _opts2 = { error }; return model.hooks.execPost("aggregate", this, [null], _opts2, (error2) => { reject(error2); }); } else { resolve(); } }); }); if (!this._pipeline.length) { throw new MongooseError("Aggregate has empty pipeline"); } const options = clone(this.options || {}); let result; try { const cursor = await collection.aggregate(this._pipeline, options); result = await cursor.toArray(); } catch (error) { await new Promise((resolve, reject) => { const _opts2 = { error }; model.hooks.execPost("aggregate", this, [null], _opts2, (error2) => { if (error2) { return reject(error2); } resolve(); }); }); } const _opts = { error: null }; await new Promise((resolve, reject) => { model.hooks.execPost("aggregate", this, [result], _opts, (error) => { if (error) { return reject(error); } return resolve(); }); }); return result; }; Aggregate.prototype.then = function(resolve, reject) { return this.exec().then(resolve, reject); }; Aggregate.prototype.catch = function(reject) { return this.exec().then(null, reject); }; Aggregate.prototype.finally = function(onFinally) { return this.exec().finally(onFinally); }; if (Symbol.asyncIterator != null) { Aggregate.prototype[Symbol.asyncIterator] = function() { return this.cursor({ useMongooseAggCursor: true }).transformNull()._transformForAsyncIterator(); }; } function isOperator(obj) { if (typeof obj !== "object" || obj === null) { return false; } const k = Object.keys(obj); return k.length === 1 && k[0][0] === "$"; } Aggregate._prepareDiscriminatorPipeline = prepareDiscriminatorPipeline; module2.exports = Aggregate; } }); // netlify/functions/node_modules/mongoose/lib/options/saveOptions.js var require_saveOptions = __commonJS({ "netlify/functions/node_modules/mongoose/lib/options/saveOptions.js"(exports2, module2) { "use strict"; var clone = require_clone(); var SaveOptions = class { constructor(obj) { if (obj == null) { return; } Object.assign(this, clone(obj)); } }; SaveOptions.prototype.__subdocs = null; module2.exports = SaveOptions; } }); // netlify/functions/node_modules/mongoose/lib/helpers/model/applyDefaultsToPOJO.js var require_applyDefaultsToPOJO = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/model/applyDefaultsToPOJO.js"(exports2, module2) { "use strict"; module2.exports = function applyDefaultsToPOJO(doc, schema) { const paths = Object.keys(schema.paths); const plen = paths.length; for (let i = 0; i < plen; ++i) { let curPath = ""; const p = paths[i]; const type = schema.paths[p]; const path = type.splitPath(); const len = path.length; let doc_ = doc; for (let j = 0; j < len; ++j) { if (doc_ == null) { break; } const piece = path[j]; curPath += (!curPath.length ? "" : ".") + piece; if (j === len - 1) { if (typeof doc_[piece] !== "undefined") { if (type.$isSingleNested) { applyDefaultsToPOJO(doc_[piece], type.caster.schema); } else if (type.$isMongooseDocumentArray && Array.isArray(doc_[piece])) { doc_[piece].forEach((el) => applyDefaultsToPOJO(el, type.schema)); } break; } const def = type.getDefault(doc, false, { skipCast: true }); if (typeof def !== "undefined") { doc_[piece] = def; if (type.$isSingleNested) { applyDefaultsToPOJO(def, type.caster.schema); } else if (type.$isMongooseDocumentArray && Array.isArray(def)) { def.forEach((el) => applyDefaultsToPOJO(el, type.schema)); } } } else { if (doc_[piece] == null) { doc_[piece] = {}; } doc_ = doc_[piece]; } } } }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/discriminator/applyEmbeddedDiscriminators.js var require_applyEmbeddedDiscriminators = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/discriminator/applyEmbeddedDiscriminators.js"(exports2, module2) { "use strict"; module2.exports = applyEmbeddedDiscriminators; function applyEmbeddedDiscriminators(schema, seen = /* @__PURE__ */ new WeakSet(), overwriteExisting = false) { if (seen.has(schema)) { return; } seen.add(schema); for (const path of Object.keys(schema.paths)) { const schemaType = schema.paths[path]; if (!schemaType.schema) { continue; } applyEmbeddedDiscriminators(schemaType.schema, seen); if (!schemaType.schema._applyDiscriminators) { continue; } if (schemaType._appliedDiscriminators && !overwriteExisting) { continue; } for (const discriminatorKey of schemaType.schema._applyDiscriminators.keys()) { const { schema: discriminatorSchema, options } = schemaType.schema._applyDiscriminators.get(discriminatorKey); applyEmbeddedDiscriminators(discriminatorSchema, seen); schemaType.discriminator( discriminatorKey, discriminatorSchema, overwriteExisting ? { ...options, overwriteExisting: true } : options ); } schemaType._appliedDiscriminators = true; } } } }); // netlify/functions/node_modules/mongoose/lib/helpers/model/applyMethods.js var require_applyMethods = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/model/applyMethods.js"(exports2, module2) { "use strict"; var get = require_get(); var utils = require_utils3(); module2.exports = function applyMethods(model, schema) { const Model = require_model(); function apply(method, schema2) { Object.defineProperty(model.prototype, method, { get: function() { const h = {}; for (const k in schema2.methods[method]) { h[k] = schema2.methods[method][k].bind(this); } return h; }, configurable: true }); } for (const method of Object.keys(schema.methods)) { const fn = schema.methods[method]; if (schema.tree.hasOwnProperty(method)) { throw new Error('You have a method and a property in your schema both named "' + method + '"'); } if (typeof fn === "function" && Model.prototype[method] === fn) { delete schema.methods[method]; continue; } if (schema.reserved[method] && !get(schema, `methodOptions.${method}.suppressWarning`, false)) { utils.warn(`mongoose: the method name "${method}" is used by mongoose internally, overwriting it may cause bugs. If you're sure you know what you're doing, you can suppress this error by using \`schema.method('${method}', fn, { suppressWarning: true })\`.`); } if (typeof fn === "function") { model.prototype[method] = fn; } else { apply(method, schema); } } model.$appliedMethods = true; for (const key of Object.keys(schema.paths)) { const type = schema.paths[key]; if (type.$isSingleNested && !type.caster.$appliedMethods) { applyMethods(type.caster, type.schema); } if (type.$isMongooseDocumentArray && !type.Constructor.$appliedMethods) { applyMethods(type.Constructor, type.schema); } } }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/projection/applyProjection.js var require_applyProjection = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/projection/applyProjection.js"(exports2, module2) { "use strict"; var hasIncludedChildren = require_hasIncludedChildren(); var isExclusive = require_isExclusive(); var isInclusive = require_isInclusive(); var isPOJO = require_utils3().isPOJO; module2.exports = function applyProjection(doc, projection, _hasIncludedChildren) { if (projection == null) { return doc; } if (doc == null) { return doc; } let exclude = null; if (isInclusive(projection)) { exclude = false; } else if (isExclusive(projection)) { exclude = true; } if (exclude == null) { return doc; } else if (exclude) { _hasIncludedChildren = _hasIncludedChildren || hasIncludedChildren(projection); return applyExclusiveProjection(doc, projection, _hasIncludedChildren); } else { _hasIncludedChildren = _hasIncludedChildren || hasIncludedChildren(projection); return applyInclusiveProjection(doc, projection, _hasIncludedChildren); } }; function applyExclusiveProjection(doc, projection, hasIncludedChildren2, projectionLimb, prefix) { if (doc == null || typeof doc !== "object") { return doc; } if (Array.isArray(doc)) { return doc.map((el) => applyExclusiveProjection(el, projection, hasIncludedChildren2, projectionLimb, prefix)); } const ret = { ...doc }; projectionLimb = prefix ? projectionLimb || {} : projection; for (const key of Object.keys(ret)) { const fullPath = prefix ? prefix + "." + key : key; if (projection.hasOwnProperty(fullPath) || projectionLimb.hasOwnProperty(key)) { if (isPOJO(projection[fullPath]) || isPOJO(projectionLimb[key])) { ret[key] = applyExclusiveProjection(ret[key], projection, hasIncludedChildren2, projectionLimb[key], fullPath); } else { delete ret[key]; } } else if (hasIncludedChildren2[fullPath]) { ret[key] = applyExclusiveProjection(ret[key], projection, hasIncludedChildren2, projectionLimb[key], fullPath); } } return ret; } function applyInclusiveProjection(doc, projection, hasIncludedChildren2, projectionLimb, prefix) { if (doc == null || typeof doc !== "object") { return doc; } if (Array.isArray(doc)) { return doc.map((el) => applyInclusiveProjection(el, projection, hasIncludedChildren2, projectionLimb, prefix)); } const ret = { ...doc }; projectionLimb = prefix ? projectionLimb || {} : projection; for (const key of Object.keys(ret)) { const fullPath = prefix ? prefix + "." + key : key; if (projection.hasOwnProperty(fullPath) || projectionLimb.hasOwnProperty(key)) { if (isPOJO(projection[fullPath]) || isPOJO(projectionLimb[key])) { ret[key] = applyInclusiveProjection(ret[key], projection, hasIncludedChildren2, projectionLimb[key], fullPath); } continue; } else if (hasIncludedChildren2[fullPath]) { ret[key] = applyInclusiveProjection(ret[key], projection, hasIncludedChildren2, projectionLimb[key], fullPath); } else { delete ret[key]; } } return ret; } } }); // netlify/functions/node_modules/mongoose/lib/helpers/indexes/isTextIndex.js var require_isTextIndex = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/indexes/isTextIndex.js"(exports2, module2) { "use strict"; module2.exports = function isTextIndex(indexKeys) { let isTextIndex2 = false; for (const key of Object.keys(indexKeys)) { if (indexKeys[key] === "text") { isTextIndex2 = true; } } return isTextIndex2; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/indexes/applySchemaCollation.js var require_applySchemaCollation = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/indexes/applySchemaCollation.js"(exports2, module2) { "use strict"; var isTextIndex = require_isTextIndex(); module2.exports = function applySchemaCollation(indexKeys, indexOptions, schemaOptions) { if (isTextIndex(indexKeys)) { return; } if (schemaOptions.hasOwnProperty("collation") && !indexOptions.hasOwnProperty("collation")) { indexOptions.collation = schemaOptions.collation; } }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/model/applyStaticHooks.js var require_applyStaticHooks = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/model/applyStaticHooks.js"(exports2, module2) { "use strict"; var promiseOrCallback = require_promiseOrCallback(); var { queryMiddlewareFunctions, aggregateMiddlewareFunctions, modelMiddlewareFunctions, documentMiddlewareFunctions } = require_constants3(); var middlewareFunctions = Array.from( /* @__PURE__ */ new Set([ ...queryMiddlewareFunctions, ...aggregateMiddlewareFunctions, ...modelMiddlewareFunctions, ...documentMiddlewareFunctions ]) ); module2.exports = function applyStaticHooks(model, hooks, statics) { const kareemOptions = { useErrorHandlers: true, numCallbackParams: 1 }; model.$__insertMany = hooks.createWrapper( "insertMany", model.$__insertMany, model, kareemOptions ); hooks = hooks.filter((hook) => { if (middlewareFunctions.indexOf(hook.name) !== -1) { return !!hook.model; } return hook.model !== false; }); for (const key of Object.keys(statics)) { if (hooks.hasHooks(key)) { const original = model[key]; model[key] = function() { const numArgs = arguments.length; const lastArg = numArgs > 0 ? arguments[numArgs - 1] : null; const cb = typeof lastArg === "function" ? lastArg : null; const args = Array.prototype.slice.call(arguments, 0, cb == null ? numArgs : numArgs - 1); return promiseOrCallback(cb, (callback) => { hooks.execPre(key, model, args, function(err) { if (err != null) { return callback(err); } let postCalled = 0; const ret = original.apply(model, args.concat(post)); if (ret != null && typeof ret.then === "function") { ret.then((res) => post(null, res), (err2) => post(err2)); } function post(error, res) { if (postCalled++ > 0) { return; } if (error != null) { return callback(error); } hooks.execPost(key, model, [res], function(error2) { if (error2 != null) { return callback(error2); } callback(null, res); }); } }); }, model.events); }; } } }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/model/applyStatics.js var require_applyStatics = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/model/applyStatics.js"(exports2, module2) { "use strict"; module2.exports = function applyStatics(model, schema) { for (const i in schema.statics) { model[i] = schema.statics[i]; } }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/document/applyTimestamps.js var require_applyTimestamps = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/document/applyTimestamps.js"(exports2, module2) { "use strict"; var handleTimestampOption = require_handleTimestampOption(); var mpath = require_mpath(); module2.exports = applyTimestamps; function applyTimestamps(schema, obj, options) { if (obj == null) { return obj; } applyTimestampsToChildren(schema, obj, options); return applyTimestampsToDoc(schema, obj, options); } function applyTimestampsToChildren(schema, res, options) { for (const childSchema of schema.childSchemas) { const _path = childSchema.model.path; const _schema = childSchema.schema; if (!_path) { continue; } const _obj = mpath.get(_path, res); if (_obj == null || Array.isArray(_obj) && _obj.flat(Infinity).length === 0) { continue; } applyTimestamps(_schema, _obj, options); } } function applyTimestampsToDoc(schema, obj, options) { if (obj == null || typeof obj !== "object") { return; } if (Array.isArray(obj)) { for (const el of obj) { applyTimestampsToDoc(schema, el, options); } return; } if (schema.discriminators && Object.keys(schema.discriminators).length > 0) { for (const discriminatorKey of Object.keys(schema.discriminators)) { const discriminator = schema.discriminators[discriminatorKey]; const key = discriminator.discriminatorMapping.key; const value = discriminator.discriminatorMapping.value; if (obj[key] == value) { schema = discriminator; break; } } } const createdAt = handleTimestampOption(schema.options.timestamps, "createdAt"); const updatedAt = handleTimestampOption(schema.options.timestamps, "updatedAt"); const currentTime = options?.currentTime; let ts = null; if (currentTime != null) { ts = currentTime(); } else if (schema.base?.now) { ts = schema.base.now(); } else { ts = /* @__PURE__ */ new Date(); } if (createdAt && obj[createdAt] == null && !options?.isUpdate) { obj[createdAt] = ts; } if (updatedAt) { obj[updatedAt] = ts; } } } }); // netlify/functions/node_modules/mongoose/lib/helpers/document/applyVirtuals.js var require_applyVirtuals = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/document/applyVirtuals.js"(exports2, module2) { "use strict"; var mpath = require_mpath(); module2.exports = applyVirtuals; function applyVirtuals(schema, obj, virtuals) { if (obj == null) { return obj; } let virtualsForChildren = virtuals; let toApply = null; if (Array.isArray(virtuals)) { virtualsForChildren = []; toApply = []; for (const virtual of virtuals) { if (virtual.length === 1) { toApply.push(virtual[0]); } else { virtualsForChildren.push(virtual); } } } applyVirtualsToChildren(schema, obj, virtualsForChildren); return applyVirtualsToDoc(schema, obj, toApply); } function applyVirtualsToChildren(schema, res, virtuals) { let attachedVirtuals = false; for (const childSchema of schema.childSchemas) { const _path = childSchema.model.path; const _schema = childSchema.schema; if (!_path) { continue; } const _obj = mpath.get(_path, res); if (_obj == null || Array.isArray(_obj) && _obj.flat(Infinity).length === 0) { continue; } let virtualsForChild = null; if (Array.isArray(virtuals)) { virtualsForChild = []; for (const virtual of virtuals) { if (virtual[0] == _path) { virtualsForChild.push(virtual.slice(1)); } } if (virtualsForChild.length === 0) { continue; } } applyVirtuals(_schema, _obj, virtualsForChild); attachedVirtuals = true; } if (virtuals && virtuals.length && !attachedVirtuals) { applyVirtualsToDoc(schema, res, virtuals); } } function applyVirtualsToDoc(schema, obj, virtuals) { if (obj == null || typeof obj !== "object") { return; } if (Array.isArray(obj)) { for (const el of obj) { applyVirtualsToDoc(schema, el, virtuals); } return; } if (schema.discriminators && Object.keys(schema.discriminators).length > 0) { for (const discriminatorKey of Object.keys(schema.discriminators)) { const discriminator = schema.discriminators[discriminatorKey]; const key = discriminator.discriminatorMapping.key; const value = discriminator.discriminatorMapping.value; if (obj[key] == value) { schema = discriminator; break; } } } if (virtuals == null) { virtuals = Object.keys(schema.virtuals); } for (const virtual of virtuals) { if (schema.virtuals[virtual] == null) { continue; } const virtualType = schema.virtuals[virtual]; const sp = Array.isArray(virtual) ? virtual : virtual.indexOf(".") === -1 ? [virtual] : virtual.split("."); let cur = obj; for (let i = 0; i < sp.length - 1; ++i) { cur[sp[i]] = sp[i] in cur ? cur[sp[i]] : {}; cur = cur[sp[i]]; } let val = virtualType.applyGetters(cur[sp[sp.length - 1]], obj); const isPopulateVirtual = virtualType.options && (virtualType.options.ref || virtualType.options.refPath); if (isPopulateVirtual && val === void 0) { if (virtualType.options.justOne) { val = null; } else { val = []; } } cur[sp[sp.length - 1]] = val; } } } }); // netlify/functions/node_modules/mongoose/lib/helpers/populate/skipPopulateValue.js var require_skipPopulateValue = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/populate/skipPopulateValue.js"(exports2, module2) { "use strict"; module2.exports = function SkipPopulateValue(val) { if (!(this instanceof SkipPopulateValue)) { return new SkipPopulateValue(val); } this.val = val; return this; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/populate/leanPopulateMap.js var require_leanPopulateMap = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/populate/leanPopulateMap.js"(exports2, module2) { "use strict"; module2.exports = /* @__PURE__ */ new WeakMap(); } }); // netlify/functions/node_modules/mongoose/lib/helpers/populate/assignRawDocsToIdStructure.js var require_assignRawDocsToIdStructure = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/populate/assignRawDocsToIdStructure.js"(exports2, module2) { "use strict"; var clone = require_clone(); var leanPopulateMap = require_leanPopulateMap(); var modelSymbol = require_symbols().modelSymbol; var utils = require_utils3(); module2.exports = assignRawDocsToIdStructure; var kHasArray = Symbol("mongoose#assignRawDocsToIdStructure#hasArray"); function assignRawDocsToIdStructure(rawIds, resultDocs, resultOrder, options, recursed) { const newOrder = []; const sorting = options.isVirtual && options.justOne && rawIds.length > 1 ? false : options.sort && rawIds.length > 1; const nullIfNotFound = options.$nullIfNotFound; let doc; let sid; let id; if (utils.isMongooseArray(rawIds)) { rawIds = rawIds.__array; } let i = 0; const len = rawIds.length; if (sorting && recursed && options[kHasArray] === void 0) { options[kHasArray] = false; for (const key in resultOrder) { if (Array.isArray(resultOrder[key])) { options[kHasArray] = true; break; } } } for (i = 0; i < len; ++i) { id = rawIds[i]; if (Array.isArray(id)) { assignRawDocsToIdStructure(id, resultDocs, resultOrder, options, true); newOrder.push(id); continue; } if (id === null && sorting === false) { newOrder.push(id); continue; } if (id?.constructor?.name === "Binary" && id.sub_type === 4 && typeof id.toUUID === "function") { sid = String(id.toUUID()); } else if (id?.constructor?.name === "Buffer" && id._subtype === 4 && typeof id.toUUID === "function") { sid = String(id.toUUID()); } else { sid = String(id); } doc = resultDocs[sid]; if (options.clone && doc != null) { if (options.lean) { const _model = leanPopulateMap.get(doc); doc = clone(doc); leanPopulateMap.set(doc, _model); } else { doc = doc.constructor.hydrate(doc._doc); } } if (recursed) { if (doc) { if (sorting) { const _resultOrder = resultOrder[sid]; if (options[kHasArray]) { newOrder.push(doc); } else { newOrder[_resultOrder] = doc; } } else { newOrder.push(doc); } } else if (id != null && id[modelSymbol] != null) { newOrder.push(id); } else { newOrder.push(options.retainNullValues || nullIfNotFound ? null : id); } } else { newOrder[i] = doc || null; } } rawIds.length = 0; if (newOrder.length) { newOrder.forEach(function(doc2, i2) { rawIds[i2] = doc2; }); } } } }); // netlify/functions/node_modules/mongoose/lib/helpers/populate/getVirtual.js var require_getVirtual = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/populate/getVirtual.js"(exports2, module2) { "use strict"; module2.exports = getVirtual; function getVirtual(schema, name) { if (schema.virtuals[name]) { return { virtual: schema.virtuals[name], path: void 0 }; } const parts = name.split("."); let cur = ""; let nestedSchemaPath = ""; for (let i = 0; i < parts.length; ++i) { cur += (cur.length > 0 ? "." : "") + parts[i]; if (schema.virtuals[cur]) { if (i === parts.length - 1) { return { virtual: schema.virtuals[cur], path: nestedSchemaPath }; } continue; } if (schema.nested[cur]) { continue; } if (schema.paths[cur] && schema.paths[cur].schema) { schema = schema.paths[cur].schema; const rest = parts.slice(i + 1).join("."); if (schema.virtuals[rest]) { if (i === parts.length - 2) { return { virtual: schema.virtuals[rest], nestedSchemaPath: [nestedSchemaPath, cur].filter((v) => !!v).join(".") }; } continue; } if (i + 1 < parts.length && schema.discriminators) { for (const key of Object.keys(schema.discriminators)) { const res = getVirtual(schema.discriminators[key], rest); if (res != null) { const _path = [nestedSchemaPath, cur, res.nestedSchemaPath].filter((v) => !!v).join("."); return { virtual: res.virtual, nestedSchemaPath: _path }; } } } nestedSchemaPath += (nestedSchemaPath.length > 0 ? "." : "") + cur; cur = ""; continue; } else if (schema.paths[cur]?.$isSchemaMap && schema.paths[cur].$__schemaType?.schema) { schema = schema.paths[cur].$__schemaType.schema; ++i; const rest = parts.slice(i + 1).join("."); if (schema.virtuals[rest]) { if (i === parts.length - 2) { return { virtual: schema.virtuals[rest], nestedSchemaPath: [nestedSchemaPath, cur, "$*"].filter((v) => !!v).join(".") }; } continue; } if (i + 1 < parts.length && schema.discriminators) { for (const key of Object.keys(schema.discriminators)) { const res = getVirtual(schema.discriminators[key], rest); if (res != null) { const _path = [nestedSchemaPath, cur, res.nestedSchemaPath, "$*"].filter((v) => !!v).join("."); return { virtual: res.virtual, nestedSchemaPath: _path }; } } } nestedSchemaPath += (nestedSchemaPath.length > 0 ? "." : "") + "$*" + cur; cur = ""; } if (schema.discriminators) { for (const discriminatorKey of Object.keys(schema.discriminators)) { const virtualFromDiscriminator = getVirtual(schema.discriminators[discriminatorKey], name); if (virtualFromDiscriminator) return virtualFromDiscriminator; } } return null; } } } }); // netlify/functions/node_modules/sift/lib/index.js var require_lib5 = __commonJS({ "netlify/functions/node_modules/sift/lib/index.js"(exports2, module2) { (function(global2, factory) { typeof exports2 === "object" && typeof module2 !== "undefined" ? factory(exports2) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.sift = {})); })(exports2, (function(exports3) { "use strict"; var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { d2.__proto__ = b2; } || function(d2, b2) { for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; }; return extendStatics(d, b); }; function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; var typeChecker = function(type) { var typeString = "[object " + type + "]"; return function(value) { return getClassName(value) === typeString; }; }; var getClassName = function(value) { return Object.prototype.toString.call(value); }; var comparable = function(value) { if (value instanceof Date) { return value.getTime(); } else if (isArray(value)) { return value.map(comparable); } else if (value && typeof value.toJSON === "function") { return value.toJSON(); } return value; }; var coercePotentiallyNull = function(value) { return value == null ? null : value; }; var isArray = typeChecker("Array"); var isObject = typeChecker("Object"); var isFunction = typeChecker("Function"); var isProperty = function(item, key) { return item.hasOwnProperty(key) && !isFunction(item[key]); }; var isVanillaObject = function(value) { return value && (value.constructor === Object || value.constructor === Array || value.constructor.toString() === "function Object() { [native code] }" || value.constructor.toString() === "function Array() { [native code] }") && !value.toJSON; }; var equals = function(a, b) { if (a == null && a == b) { return true; } if (a === b) { return true; } if (Object.prototype.toString.call(a) !== Object.prototype.toString.call(b)) { return false; } if (isArray(a)) { if (a.length !== b.length) { return false; } for (var i = 0, length_1 = a.length; i < length_1; i++) { if (!equals(a[i], b[i])) return false; } return true; } else if (isObject(a)) { if (Object.keys(a).length !== Object.keys(b).length) { return false; } for (var key in a) { if (!equals(a[key], b[key])) return false; } return true; } return false; }; var walkKeyPathValues = function(item, keyPath, next, depth, key, owner) { var currentKey = keyPath[depth]; if (isArray(item) && isNaN(Number(currentKey)) && !isProperty(item, currentKey)) { for (var i = 0, length_1 = item.length; i < length_1; i++) { if (!walkKeyPathValues(item[i], keyPath, next, depth, i, item)) { return false; } } } if (depth === keyPath.length || item == null) { return next(item, key, owner, depth === 0, depth === keyPath.length); } return walkKeyPathValues(item[currentKey], keyPath, next, depth + 1, currentKey, item); }; var BaseOperation = ( /** @class */ (function() { function BaseOperation2(params, owneryQuery, options, name) { this.params = params; this.owneryQuery = owneryQuery; this.options = options; this.name = name; this.init(); } BaseOperation2.prototype.init = function() { }; BaseOperation2.prototype.reset = function() { this.done = false; this.keep = false; }; return BaseOperation2; })() ); var GroupOperation = ( /** @class */ (function(_super) { __extends(GroupOperation2, _super); function GroupOperation2(params, owneryQuery, options, children) { var _this = _super.call(this, params, owneryQuery, options) || this; _this.children = children; return _this; } GroupOperation2.prototype.reset = function() { this.keep = false; this.done = false; for (var i = 0, length_2 = this.children.length; i < length_2; i++) { this.children[i].reset(); } }; GroupOperation2.prototype.childrenNext = function(item, key, owner, root, leaf) { var done = true; var keep = true; for (var i = 0, length_3 = this.children.length; i < length_3; i++) { var childOperation = this.children[i]; if (!childOperation.done) { childOperation.next(item, key, owner, root, leaf); } if (!childOperation.keep) { keep = false; } if (childOperation.done) { if (!childOperation.keep) { break; } } else { done = false; } } this.done = done; this.keep = keep; }; return GroupOperation2; })(BaseOperation) ); var NamedGroupOperation = ( /** @class */ (function(_super) { __extends(NamedGroupOperation2, _super); function NamedGroupOperation2(params, owneryQuery, options, children, name) { var _this = _super.call(this, params, owneryQuery, options, children) || this; _this.name = name; return _this; } return NamedGroupOperation2; })(GroupOperation) ); var QueryOperation = ( /** @class */ (function(_super) { __extends(QueryOperation2, _super); function QueryOperation2() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.propop = true; return _this; } QueryOperation2.prototype.next = function(item, key, parent, root) { this.childrenNext(item, key, parent, root); }; return QueryOperation2; })(GroupOperation) ); var NestedOperation = ( /** @class */ (function(_super) { __extends(NestedOperation2, _super); function NestedOperation2(keyPath, params, owneryQuery, options, children) { var _this = _super.call(this, params, owneryQuery, options, children) || this; _this.keyPath = keyPath; _this.propop = true; _this._nextNestedValue = function(value, key, owner, root, leaf) { _this.childrenNext(value, key, owner, root, leaf); return !_this.done; }; return _this; } NestedOperation2.prototype.next = function(item, key, parent) { walkKeyPathValues(item, this.keyPath, this._nextNestedValue, 0, key, parent); }; return NestedOperation2; })(GroupOperation) ); var createTester = function(a, compare) { if (a instanceof Function) { return a; } if (a instanceof RegExp) { return function(b) { var result = typeof b === "string" && a.test(b); a.lastIndex = 0; return result; }; } var comparableA = comparable(a); return function(b) { return compare(comparableA, comparable(b)); }; }; var EqualsOperation = ( /** @class */ (function(_super) { __extends(EqualsOperation2, _super); function EqualsOperation2() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.propop = true; return _this; } EqualsOperation2.prototype.init = function() { this._test = createTester(this.params, this.options.compare); }; EqualsOperation2.prototype.next = function(item, key, parent) { if (!Array.isArray(parent) || parent.hasOwnProperty(key)) { if (this._test(item, key, parent)) { this.done = true; this.keep = true; } } }; return EqualsOperation2; })(BaseOperation) ); var createEqualsOperation = function(params, owneryQuery, options) { return new EqualsOperation(params, owneryQuery, options); }; var numericalOperationCreator = function(createNumericalOperation) { return function(params, owneryQuery, options, name) { return createNumericalOperation(params, owneryQuery, options, name); }; }; var numericalOperation = function(createTester2) { return numericalOperationCreator(function(params, owneryQuery, options, name) { var typeofParams = typeof comparable(params); var test = createTester2(params); return new EqualsOperation(function(b) { var actualValue = coercePotentiallyNull(b); return typeof comparable(actualValue) === typeofParams && test(actualValue); }, owneryQuery, options, name); }); }; var createNamedOperation = function(name, params, parentQuery, options) { var operationCreator = options.operations[name]; if (!operationCreator) { throwUnsupportedOperation(name); } return operationCreator(params, parentQuery, options, name); }; var throwUnsupportedOperation = function(name) { throw new Error("Unsupported operation: ".concat(name)); }; var containsOperation = function(query, options) { for (var key in query) { if (options.operations.hasOwnProperty(key) || key.charAt(0) === "$") return true; } return false; }; var createNestedOperation = function(keyPath, nestedQuery, parentKey, owneryQuery, options) { if (containsOperation(nestedQuery, options)) { var _a = createQueryOperations(nestedQuery, parentKey, options), selfOperations = _a[0], nestedOperations = _a[1]; if (nestedOperations.length) { throw new Error("Property queries must contain only operations, or exact objects."); } return new NestedOperation(keyPath, nestedQuery, owneryQuery, options, selfOperations); } return new NestedOperation(keyPath, nestedQuery, owneryQuery, options, [ new EqualsOperation(nestedQuery, owneryQuery, options) ]); }; var createQueryOperation = function(query, owneryQuery, _a) { if (owneryQuery === void 0) { owneryQuery = null; } var _b = _a === void 0 ? {} : _a, compare = _b.compare, operations = _b.operations; var options = { compare: compare || equals, operations: Object.assign({}, operations || {}) }; var _c = createQueryOperations(query, null, options), selfOperations = _c[0], nestedOperations = _c[1]; var ops = []; if (selfOperations.length) { ops.push(new NestedOperation([], query, owneryQuery, options, selfOperations)); } ops.push.apply(ops, nestedOperations); if (ops.length === 1) { return ops[0]; } return new QueryOperation(query, owneryQuery, options, ops); }; var createQueryOperations = function(query, parentKey, options) { var selfOperations = []; var nestedOperations = []; if (!isVanillaObject(query)) { selfOperations.push(new EqualsOperation(query, query, options)); return [selfOperations, nestedOperations]; } for (var key in query) { if (options.operations.hasOwnProperty(key)) { var op = createNamedOperation(key, query[key], query, options); if (op) { if (!op.propop && parentKey && !options.operations[parentKey]) { throw new Error("Malformed query. ".concat(key, " cannot be matched against property.")); } } if (op != null) { selfOperations.push(op); } } else if (key.charAt(0) === "$") { throwUnsupportedOperation(key); } else { nestedOperations.push(createNestedOperation(key.split("."), query[key], key, query, options)); } } return [selfOperations, nestedOperations]; }; var createOperationTester = function(operation) { return function(item, key, owner) { operation.reset(); operation.next(item, key, owner); return operation.keep; }; }; var createQueryTester = function(query, options) { if (options === void 0) { options = {}; } return createOperationTester(createQueryOperation(query, null, options)); }; var $Ne = ( /** @class */ (function(_super) { __extends($Ne2, _super); function $Ne2() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.propop = true; return _this; } $Ne2.prototype.init = function() { this._test = createTester(this.params, this.options.compare); }; $Ne2.prototype.reset = function() { _super.prototype.reset.call(this); this.keep = true; }; $Ne2.prototype.next = function(item) { if (this._test(item)) { this.done = true; this.keep = false; } }; return $Ne2; })(BaseOperation) ); var $ElemMatch = ( /** @class */ (function(_super) { __extends($ElemMatch2, _super); function $ElemMatch2() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.propop = true; return _this; } $ElemMatch2.prototype.init = function() { if (!this.params || typeof this.params !== "object") { throw new Error("Malformed query. $elemMatch must by an object."); } this._queryOperation = createQueryOperation(this.params, this.owneryQuery, this.options); }; $ElemMatch2.prototype.reset = function() { _super.prototype.reset.call(this); this._queryOperation.reset(); }; $ElemMatch2.prototype.next = function(item) { if (isArray(item)) { for (var i = 0, length_1 = item.length; i < length_1; i++) { this._queryOperation.reset(); var child = item[i]; this._queryOperation.next(child, i, item, false); this.keep = this.keep || this._queryOperation.keep; } this.done = true; } else { this.done = false; this.keep = false; } }; return $ElemMatch2; })(BaseOperation) ); var $Not = ( /** @class */ (function(_super) { __extends($Not2, _super); function $Not2() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.propop = true; return _this; } $Not2.prototype.init = function() { this._queryOperation = createQueryOperation(this.params, this.owneryQuery, this.options); }; $Not2.prototype.reset = function() { _super.prototype.reset.call(this); this._queryOperation.reset(); }; $Not2.prototype.next = function(item, key, owner, root) { this._queryOperation.next(item, key, owner, root); this.done = this._queryOperation.done; this.keep = !this._queryOperation.keep; }; return $Not2; })(BaseOperation) ); var $Size = ( /** @class */ (function(_super) { __extends($Size2, _super); function $Size2() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.propop = true; return _this; } $Size2.prototype.init = function() { }; $Size2.prototype.next = function(item) { if (isArray(item) && item.length === this.params) { this.done = true; this.keep = true; } }; return $Size2; })(BaseOperation) ); var assertGroupNotEmpty = function(values) { if (values.length === 0) { throw new Error("$and/$or/$nor must be a nonempty array"); } }; var $Or = ( /** @class */ (function(_super) { __extends($Or2, _super); function $Or2() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.propop = false; return _this; } $Or2.prototype.init = function() { var _this = this; assertGroupNotEmpty(this.params); this._ops = this.params.map(function(op) { return createQueryOperation(op, null, _this.options); }); }; $Or2.prototype.reset = function() { this.done = false; this.keep = false; for (var i = 0, length_2 = this._ops.length; i < length_2; i++) { this._ops[i].reset(); } }; $Or2.prototype.next = function(item, key, owner) { var done = false; var success = false; for (var i = 0, length_3 = this._ops.length; i < length_3; i++) { var op = this._ops[i]; op.next(item, key, owner); if (op.keep) { done = true; success = op.keep; break; } } this.keep = success; this.done = done; }; return $Or2; })(BaseOperation) ); var $Nor = ( /** @class */ (function(_super) { __extends($Nor2, _super); function $Nor2() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.propop = false; return _this; } $Nor2.prototype.next = function(item, key, owner) { _super.prototype.next.call(this, item, key, owner); this.keep = !this.keep; }; return $Nor2; })($Or) ); var $In = ( /** @class */ (function(_super) { __extends($In2, _super); function $In2() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.propop = true; return _this; } $In2.prototype.init = function() { var _this = this; var params = Array.isArray(this.params) ? this.params : [this.params]; this._testers = params.map(function(value) { if (containsOperation(value, _this.options)) { throw new Error("cannot nest $ under ".concat(_this.name.toLowerCase())); } return createTester(value, _this.options.compare); }); }; $In2.prototype.next = function(item, key, owner) { var done = false; var success = false; for (var i = 0, length_4 = this._testers.length; i < length_4; i++) { var test = this._testers[i]; if (test(item)) { done = true; success = true; break; } } this.keep = success; this.done = done; }; return $In2; })(BaseOperation) ); var $Nin = ( /** @class */ (function(_super) { __extends($Nin2, _super); function $Nin2(params, ownerQuery, options, name) { var _this = _super.call(this, params, ownerQuery, options, name) || this; _this.propop = true; _this._in = new $In(params, ownerQuery, options, name); return _this; } $Nin2.prototype.next = function(item, key, owner, root) { this._in.next(item, key, owner); if (isArray(owner) && !root) { if (this._in.keep) { this.keep = false; this.done = true; } else if (key == owner.length - 1) { this.keep = true; this.done = true; } } else { this.keep = !this._in.keep; this.done = true; } }; $Nin2.prototype.reset = function() { _super.prototype.reset.call(this); this._in.reset(); }; return $Nin2; })(BaseOperation) ); var $Exists = ( /** @class */ (function(_super) { __extends($Exists2, _super); function $Exists2() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.propop = true; return _this; } $Exists2.prototype.next = function(item, key, owner, root, leaf) { if (!leaf) { this.done = true; this.keep = !this.params; } else if (owner.hasOwnProperty(key) === this.params) { this.done = true; this.keep = true; } }; return $Exists2; })(BaseOperation) ); var $And = ( /** @class */ (function(_super) { __extends($And2, _super); function $And2(params, owneryQuery, options, name) { var _this = _super.call(this, params, owneryQuery, options, params.map(function(query) { return createQueryOperation(query, owneryQuery, options); }), name) || this; _this.propop = false; assertGroupNotEmpty(params); return _this; } $And2.prototype.next = function(item, key, owner, root) { this.childrenNext(item, key, owner, root); }; return $And2; })(NamedGroupOperation) ); var $All = ( /** @class */ (function(_super) { __extends($All2, _super); function $All2(params, owneryQuery, options, name) { var _this = _super.call(this, params, owneryQuery, options, params.map(function(query) { return createQueryOperation(query, owneryQuery, options); }), name) || this; _this.propop = true; return _this; } $All2.prototype.next = function(item, key, owner, root) { this.childrenNext(item, key, owner, root); }; return $All2; })(NamedGroupOperation) ); var $eq = function(params, owneryQuery, options) { return new EqualsOperation(params, owneryQuery, options); }; var $ne = function(params, owneryQuery, options, name) { return new $Ne(params, owneryQuery, options, name); }; var $or = function(params, owneryQuery, options, name) { return new $Or(params, owneryQuery, options, name); }; var $nor = function(params, owneryQuery, options, name) { return new $Nor(params, owneryQuery, options, name); }; var $elemMatch = function(params, owneryQuery, options, name) { return new $ElemMatch(params, owneryQuery, options, name); }; var $nin = function(params, owneryQuery, options, name) { return new $Nin(params, owneryQuery, options, name); }; var $in = function(params, owneryQuery, options, name) { return new $In(params, owneryQuery, options, name); }; var $lt = numericalOperation(function(params) { return function(b) { return b != null && b < params; }; }); var $lte = numericalOperation(function(params) { return function(b) { return b === params || b <= params; }; }); var $gt = numericalOperation(function(params) { return function(b) { return b != null && b > params; }; }); var $gte = numericalOperation(function(params) { return function(b) { return b === params || b >= params; }; }); var $mod = function(_a, owneryQuery, options) { var mod = _a[0], equalsValue = _a[1]; return new EqualsOperation(function(b) { return comparable(b) % mod === equalsValue; }, owneryQuery, options); }; var $exists = function(params, owneryQuery, options, name) { return new $Exists(params, owneryQuery, options, name); }; var $regex = function(pattern, owneryQuery, options) { return new EqualsOperation(new RegExp(pattern, owneryQuery.$options), owneryQuery, options); }; var $not = function(params, owneryQuery, options, name) { return new $Not(params, owneryQuery, options, name); }; var typeAliases = { number: function(v) { return typeof v === "number"; }, string: function(v) { return typeof v === "string"; }, bool: function(v) { return typeof v === "boolean"; }, array: function(v) { return Array.isArray(v); }, null: function(v) { return v === null; }, timestamp: function(v) { return v instanceof Date; } }; var $type = function(clazz, owneryQuery, options) { return new EqualsOperation(function(b) { if (typeof clazz === "string") { if (!typeAliases[clazz]) { throw new Error("Type alias does not exist"); } return typeAliases[clazz](b); } return b != null ? b instanceof clazz || b.constructor === clazz : false; }, owneryQuery, options); }; var $and = function(params, ownerQuery, options, name) { return new $And(params, ownerQuery, options, name); }; var $all = function(params, ownerQuery, options, name) { return new $All(params, ownerQuery, options, name); }; var $size = function(params, ownerQuery, options) { return new $Size(params, ownerQuery, options, "$size"); }; var $options = function() { return null; }; var $where = function(params, ownerQuery, options) { var test; if (isFunction(params)) { test = params; } else if (!process.env.CSP_ENABLED) { test = new Function("obj", "return " + params); } else { throw new Error('In CSP mode, sift does not support strings in "$where" condition'); } return new EqualsOperation(function(b) { return test.bind(b)(b); }, ownerQuery, options); }; var defaultOperations = /* @__PURE__ */ Object.freeze({ __proto__: null, $Size, $all, $and, $elemMatch, $eq, $exists, $gt, $gte, $in, $lt, $lte, $mod, $ne, $nin, $nor, $not, $options, $or, $regex, $size, $type, $where }); var createDefaultQueryOperation = function(query, ownerQuery, _a) { var _b = _a === void 0 ? {} : _a, compare = _b.compare, operations = _b.operations; return createQueryOperation(query, ownerQuery, { compare, operations: Object.assign({}, defaultOperations, operations || {}) }); }; var createDefaultQueryTester = function(query, options) { if (options === void 0) { options = {}; } var op = createDefaultQueryOperation(query, null, options); return createOperationTester(op); }; exports3.$Size = $Size; exports3.$all = $all; exports3.$and = $and; exports3.$elemMatch = $elemMatch; exports3.$eq = $eq; exports3.$exists = $exists; exports3.$gt = $gt; exports3.$gte = $gte; exports3.$in = $in; exports3.$lt = $lt; exports3.$lte = $lte; exports3.$mod = $mod; exports3.$ne = $ne; exports3.$nin = $nin; exports3.$nor = $nor; exports3.$not = $not; exports3.$options = $options; exports3.$or = $or; exports3.$regex = $regex; exports3.$size = $size; exports3.$type = $type; exports3.$where = $where; exports3.EqualsOperation = EqualsOperation; exports3.createDefaultQueryOperation = createDefaultQueryOperation; exports3.createEqualsOperation = createEqualsOperation; exports3.createOperationTester = createOperationTester; exports3.createQueryOperation = createQueryOperation; exports3.createQueryTester = createQueryTester; exports3.default = createDefaultQueryTester; Object.defineProperty(exports3, "__esModule", { value: true }); })); } }); // netlify/functions/node_modules/sift/index.js var require_sift = __commonJS({ "netlify/functions/node_modules/sift/index.js"(exports2, module2) { var lib = require_lib5(); module2.exports = lib.default; Object.assign(module2.exports, lib); } }); // netlify/functions/node_modules/mongoose/lib/helpers/populate/assignVals.js var require_assignVals = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/populate/assignVals.js"(exports2, module2) { "use strict"; var MongooseMap = require_map(); var SkipPopulateValue = require_skipPopulateValue(); var assignRawDocsToIdStructure = require_assignRawDocsToIdStructure(); var get = require_get(); var getVirtual = require_getVirtual(); var leanPopulateMap = require_leanPopulateMap(); var lookupLocalFields = require_lookupLocalFields(); var markArraySubdocsPopulated = require_markArraySubdocsPopulated(); var mpath = require_mpath(); var sift = require_sift().default; var utils = require_utils3(); var { populateModelSymbol } = require_symbols(); module2.exports = function assignVals(o) { const userOptions = Object.assign({}, get(o, "allOptions.options.options"), get(o, "allOptions.options")); const populateOptions = Object.assign({}, o.options, userOptions, { justOne: o.justOne, isVirtual: o.isVirtual }); populateOptions.$nullIfNotFound = o.isVirtual; const populatedModel = o.populatedModel; const originalIds = [].concat(o.rawIds); o.allIds = [].concat(o.allIds); assignRawDocsToIdStructure(o.rawIds, o.rawDocs, o.rawOrder, populateOptions); const docs = o.docs; const rawIds = o.rawIds; const options = o.options; const count = o.count && o.isVirtual; let i; let setValueIndex = 0; function setValue(val) { ++setValueIndex; if (count) { return val; } if (val instanceof SkipPopulateValue) { return val.val; } if (val === void 0) { return val; } const _allIds = o.allIds[i]; if (o.path.endsWith(".$*")) { return valueFilter(val, options, populateOptions, _allIds); } if (o.justOne === true && Array.isArray(val)) { const ret = []; for (const doc of val) { const _docPopulatedModel = leanPopulateMap.get(doc); if (_docPopulatedModel == null || _docPopulatedModel === populatedModel) { ret.push(doc); } } while (val.length > ret.length) { Array.prototype.pop.apply(val, []); } for (let i2 = 0; i2 < ret.length; ++i2) { val[i2] = ret[i2]; } return valueFilter(val[0], options, populateOptions, _allIds); } else if (o.justOne === false && !Array.isArray(val)) { return valueFilter([val], options, populateOptions, _allIds); } else if (o.justOne === true && !Array.isArray(val) && Array.isArray(_allIds)) { return valueFilter(val, options, populateOptions, val == null ? val : _allIds[setValueIndex - 1]); } return valueFilter(val, options, populateOptions, _allIds); } for (i = 0; i < docs.length; ++i) { setValueIndex = 0; const _path = o.path.endsWith(".$*") ? o.path.slice(0, -3) : o.path; const existingVal = mpath.get(_path, docs[i], lookupLocalFields); if (existingVal == null && !getVirtual(o.originalModel.schema, _path)) { continue; } let valueToSet; if (count) { valueToSet = numDocs(rawIds[i]); } else if (Array.isArray(o.match)) { valueToSet = Array.isArray(rawIds[i]) ? rawIds[i].filter((v) => v == null || sift(o.match[i])(v)) : [rawIds[i]].filter((v) => v == null || sift(o.match[i])(v))[0]; } else { valueToSet = rawIds[i]; } const originalSchema = o.originalModel.schema; const isDoc = get(docs[i], "$__", null) != null; let isMap = isDoc ? existingVal instanceof Map : utils.isPOJO(existingVal); isMap = isMap && get(originalSchema._getSchema(_path), "$isSchemaMap"); if (!o.isVirtual && isMap) { const _keys = existingVal instanceof Map ? Array.from(existingVal.keys()) : Object.keys(existingVal); valueToSet = valueToSet.reduce((cur2, v, i2) => { cur2.set(_keys[i2], v); return cur2; }, /* @__PURE__ */ new Map()); } if (isDoc && Array.isArray(valueToSet)) { for (const val of valueToSet) { if (val != null && val.$__ != null) { val.$__.parent = docs[i]; } } } else if (isDoc && valueToSet != null && valueToSet.$__ != null) { valueToSet.$__.parent = docs[i]; } if (o.isVirtual && isDoc) { docs[i].$populated(_path, o.justOne ? originalIds[0] : originalIds, o.allOptions); if (Array.isArray(valueToSet)) { valueToSet = valueToSet.map((v) => v == null ? void 0 : v); } mpath.set( _path, valueToSet, docs[i], // Handle setting paths underneath maps using $* by converting arrays into maps of values function lookup(obj, part, val) { if (arguments.length >= 3) { obj[part] = val; return obj[part]; } if (obj instanceof Map && part === "$*") { return [...obj.values()]; } return obj[part]; }, setValue, false ); continue; } const parts = _path.split("."); let cur = docs[i]; for (let j = 0; j < parts.length - 1; ++j) { if (Array.isArray(cur) && !utils.isArrayIndex(parts[j])) { break; } if (parts[j] === "$*") { break; } if (cur[parts[j]] == null) { const curPath = parts.slice(0, j + 1).join("."); const schematype = originalSchema._getSchema(curPath); if (valueToSet == null && schematype != null && schematype.$isMongooseArray) { break; } cur[parts[j]] = {}; } cur = cur[parts[j]]; if (typeof cur !== "object") { break; } } if (docs[i].$__) { o.allOptions.options[populateModelSymbol] = o.allOptions.model; docs[i].$populated(_path, o.unpopulatedValues[i], o.allOptions.options); if (valueToSet != null && valueToSet.$__ != null) { valueToSet.$__.wasPopulated = { value: o.unpopulatedValues[i] }; } if (valueToSet instanceof Map && !valueToSet.$isMongooseMap) { valueToSet = new MongooseMap(valueToSet, _path, docs[i], docs[i].schema.path(_path).$__schemaType); } } mpath.set(_path, valueToSet, docs[i], lookupLocalFields, setValue, false); if (docs[i].$__) { markArraySubdocsPopulated(docs[i], [o.allOptions.options]); } } }; function numDocs(v) { if (Array.isArray(v)) { if (v.some((el) => Array.isArray(el) || el === null)) { return v.map((el) => { if (el == null) { return 0; } if (Array.isArray(el)) { return el.filter((el2) => el2 != null).length; } return 1; }); } return v.filter((el) => el != null).length; } return v == null ? 0 : 1; } function valueFilter(val, assignmentOpts, populateOptions, allIds) { const userSpecifiedTransform = typeof populateOptions.transform === "function"; const transform = userSpecifiedTransform ? populateOptions.transform : (v) => v; if (Array.isArray(val)) { const ret = []; const numValues = val.length; for (let i2 = 0; i2 < numValues; ++i2) { let subdoc = val[i2]; const _allIds = Array.isArray(allIds) ? allIds[i2] : allIds; if (!isPopulatedObject(subdoc) && (!populateOptions.retainNullValues || subdoc != null) && !userSpecifiedTransform) { continue; } else if (!populateOptions.retainNullValues && subdoc == null) { continue; } else if (userSpecifiedTransform) { subdoc = transform(isPopulatedObject(subdoc) ? subdoc : null, _allIds); } maybeRemoveId(subdoc, assignmentOpts); ret.push(subdoc); if (assignmentOpts.originalLimit && ret.length >= assignmentOpts.originalLimit) { break; } } const rLen = ret.length; while (val.length > rLen) { Array.prototype.pop.apply(val, []); } let i = 0; if (utils.isMongooseArray(val)) { for (i = 0; i < rLen; ++i) { val.set(i, ret[i], true); } } else { for (i = 0; i < rLen; ++i) { val[i] = ret[i]; } } return val; } if (isPopulatedObject(val) || utils.isPOJO(val)) { maybeRemoveId(val, assignmentOpts); return transform(val, allIds); } if (val instanceof Map) { return val; } if (populateOptions.justOne === false) { return []; } return val == null ? transform(val, allIds) : transform(null, allIds); } function maybeRemoveId(subdoc, assignmentOpts) { if (subdoc != null && assignmentOpts.excludeId) { if (typeof subdoc.$__setValue === "function") { delete subdoc._doc._id; } else { delete subdoc._id; } } } function isPopulatedObject(obj) { if (obj == null) { return false; } return Array.isArray(obj) || obj.$isMongooseMap || obj.$__ != null || leanPopulateMap.has(obj); } } }); // netlify/functions/node_modules/mongoose/lib/helpers/populate/createPopulateQueryFilter.js var require_createPopulateQueryFilter = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/populate/createPopulateQueryFilter.js"(exports2, module2) { "use strict"; var SkipPopulateValue = require_skipPopulateValue(); var parentPaths = require_parentPaths(); var { trusted } = require_trusted(); var hasDollarKeys = require_hasDollarKeys(); module2.exports = function createPopulateQueryFilter(ids, _match, _foreignField, model, skipInvalidIds) { const match = _formatMatch(_match); if (_foreignField.size === 1) { const foreignField = Array.from(_foreignField)[0]; const foreignSchemaType = model.schema.path(foreignField); if (foreignField !== "_id" || !match["_id"]) { ids = _filterInvalidIds(ids, foreignSchemaType, skipInvalidIds); match[foreignField] = trusted({ $in: ids }); } else if (foreignField === "_id" && match["_id"]) { const userSpecifiedMatch = hasDollarKeys(match[foreignField]) ? match[foreignField] : { $eq: match[foreignField] }; match[foreignField] = { ...trusted({ $in: ids }), ...userSpecifiedMatch }; } const _parentPaths = parentPaths(foreignField); for (let i = 0; i < _parentPaths.length - 1; ++i) { const cur = _parentPaths[i]; if (match[cur] != null && match[cur].$elemMatch != null) { match[cur].$elemMatch[foreignField.slice(cur.length + 1)] = trusted({ $in: ids }); delete match[foreignField]; break; } } } else { const $or = []; if (Array.isArray(match.$or)) { match.$and = [{ $or: match.$or }, { $or }]; delete match.$or; } else { match.$or = $or; } for (const foreignField of _foreignField) { if (foreignField !== "_id" || !match["_id"]) { const foreignSchemaType = model.schema.path(foreignField); ids = _filterInvalidIds(ids, foreignSchemaType, skipInvalidIds); $or.push({ [foreignField]: { $in: ids } }); } else if (foreignField === "_id" && match["_id"]) { const userSpecifiedMatch = hasDollarKeys(match[foreignField]) ? match[foreignField] : { $eq: match[foreignField] }; match[foreignField] = { ...trusted({ $in: ids }), ...userSpecifiedMatch }; } } } return match; }; function _filterInvalidIds(ids, foreignSchemaType, skipInvalidIds) { ids = ids.filter((v) => !(v instanceof SkipPopulateValue)); if (!skipInvalidIds) { return ids; } return ids.filter((id) => { try { foreignSchemaType.cast(id); return true; } catch (err) { return false; } }); } function _formatMatch(match) { if (Array.isArray(match)) { if (match.length > 1) { return { $or: [].concat(match.map((m) => Object.assign({}, m))) }; } return Object.assign({}, match[0]); } return Object.assign({}, match); } } }); // netlify/functions/node_modules/mongoose/lib/helpers/populate/getSchemaTypes.js var require_getSchemaTypes = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/populate/getSchemaTypes.js"(exports2, module2) { "use strict"; var Mixed = require_mixed(); var get = require_get(); var getDiscriminatorByValue = require_getDiscriminatorByValue(); var leanPopulateMap = require_leanPopulateMap(); var mpath = require_mpath(); var populateModelSymbol = require_symbols().populateModelSymbol; module2.exports = function getSchemaTypes(model, schema, doc, path) { const pathschema = schema.path(path); const topLevelDoc = doc; if (pathschema) { return pathschema; } const discriminatorKey = schema.discriminatorMapping && schema.discriminatorMapping.key; if (discriminatorKey && model != null) { if (doc != null && doc[discriminatorKey] != null) { const discriminator = getDiscriminatorByValue(model.discriminators, doc[discriminatorKey]); schema = discriminator ? discriminator.schema : schema; } else if (model.discriminators != null) { return Object.keys(model.discriminators).reduce((arr, name) => { const disc = model.discriminators[name]; return arr.concat(getSchemaTypes(disc, disc.schema, null, path)); }, []); } } function search(parts2, schema2, subdoc, nestedPath) { let p = parts2.length + 1; let foundschema; let trypath; while (p--) { trypath = parts2.slice(0, p).join("."); foundschema = schema2.path(trypath); if (foundschema == null) { continue; } if (foundschema.caster) { if (foundschema.caster instanceof Mixed) { return foundschema.caster; } let schemas = null; if (foundschema.schema != null && foundschema.schema.discriminators != null) { const discriminators = foundschema.schema.discriminators; const discriminatorKeyPath = trypath + "." + foundschema.schema.options.discriminatorKey; const keys = subdoc ? mpath.get(discriminatorKeyPath, subdoc) || [] : []; schemas = Object.keys(discriminators).reduce(function(cur, discriminator) { const tiedValue = discriminators[discriminator].discriminatorMapping.value; if (doc == null || keys.indexOf(discriminator) !== -1 || keys.indexOf(tiedValue) !== -1) { cur.push(discriminators[discriminator]); } return cur; }, []); } if (p !== parts2.length && foundschema.schema) { let ret; if (parts2[p] === "$") { if (p + 1 === parts2.length) { return foundschema; } ret = search( parts2.slice(p + 1), schema2, subdoc ? mpath.get(trypath, subdoc) : null, nestedPath.concat(parts2.slice(0, p)) ); if (ret) { ret.$parentSchemaDocArray = ret.$parentSchemaDocArray || (foundschema.schema.$isSingleNested ? null : foundschema); } return ret; } if (schemas != null && schemas.length > 0) { ret = []; for (const schema3 of schemas) { const _ret = search( parts2.slice(p), schema3, subdoc ? mpath.get(trypath, subdoc) : null, nestedPath.concat(parts2.slice(0, p)) ); if (_ret != null) { _ret.$parentSchemaDocArray = _ret.$parentSchemaDocArray || (foundschema.schema.$isSingleNested ? null : foundschema); if (_ret.$parentSchemaDocArray) { ret.$parentSchemaDocArray = _ret.$parentSchemaDocArray; } ret.push(_ret); } } return ret; } else { ret = search( parts2.slice(p), foundschema.schema, subdoc ? mpath.get(trypath, subdoc) : null, nestedPath.concat(parts2.slice(0, p)) ); if (ret) { ret.$parentSchemaDocArray = ret.$parentSchemaDocArray || (foundschema.schema.$isSingleNested ? null : foundschema); } return ret; } } else if (p !== parts2.length && foundschema.$isMongooseArray && foundschema.casterConstructor.$isMongooseArray) { let type = foundschema; while (type.$isMongooseArray && !type.$isMongooseDocumentArray) { type = type.casterConstructor; } const ret = search( parts2.slice(p), type.schema, null, nestedPath.concat(parts2.slice(0, p)) ); if (ret != null) { return ret; } if (type.schema.discriminators) { const discriminatorPaths = []; for (const discriminatorName of Object.keys(type.schema.discriminators)) { const _schema = type.schema.discriminators[discriminatorName] || type.schema; const ret2 = search(parts2.slice(p), _schema, null, nestedPath.concat(parts2.slice(0, p))); if (ret2 != null) { discriminatorPaths.push(ret2); } } if (discriminatorPaths.length > 0) { return discriminatorPaths; } } } } else if (foundschema.$isSchemaMap && foundschema.$__schemaType instanceof Mixed) { return foundschema.$__schemaType; } const fullPath = nestedPath.concat([trypath]).join("."); if (topLevelDoc != null && topLevelDoc.$__ && topLevelDoc.$populated(fullPath, true) && p < parts2.length) { const model2 = topLevelDoc.$populated(fullPath, true).options[populateModelSymbol]; if (model2 != null) { const ret = search( parts2.slice(p), model2.schema, subdoc ? mpath.get(trypath, subdoc) : null, nestedPath.concat(parts2.slice(0, p)) ); return ret; } } const _val = get(topLevelDoc, trypath); if (_val != null) { const model2 = Array.isArray(_val) && _val.length > 0 ? leanPopulateMap.get(_val[0]) : leanPopulateMap.get(_val); const schema3 = model2 != null ? model2.schema : null; if (schema3 != null) { const ret = search( parts2.slice(p), schema3, subdoc ? mpath.get(trypath, subdoc) : null, nestedPath.concat(parts2.slice(0, p)) ); if (ret != null) { ret.$parentSchemaDocArray = ret.$parentSchemaDocArray || (schema3.$isSingleNested ? null : schema3); return ret; } } } return foundschema; } } const parts = path.split("."); for (let i = 0; i < parts.length; ++i) { if (parts[i] === "$") { parts[i] = "0"; } } return search(parts, schema, doc, []); }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/populate/getModelsMapForPopulate.js var require_getModelsMapForPopulate = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/populate/getModelsMapForPopulate.js"(exports2, module2) { "use strict"; var MongooseError = require_error2(); var SkipPopulateValue = require_skipPopulateValue(); var clone = require_clone(); var get = require_get(); var getDiscriminatorByValue = require_getDiscriminatorByValue(); var getConstructorName = require_getConstructorName(); var getSchemaTypes = require_getSchemaTypes(); var getVirtual = require_getVirtual(); var lookupLocalFields = require_lookupLocalFields(); var mpath = require_mpath(); var modelNamesFromRefPath = require_modelNamesFromRefPath(); var utils = require_utils3(); var modelSymbol = require_symbols().modelSymbol; var populateModelSymbol = require_symbols().populateModelSymbol; var schemaMixedSymbol = require_symbols2().schemaMixedSymbol; var StrictPopulate = require_strictPopulate(); module2.exports = function getModelsMapForPopulate(model, docs, options) { let doc; const len = docs.length; const map = []; const modelNameFromQuery = options.model && options.model.modelName || options.model; let schema; let refPath; let modelNames; const available = {}; const modelSchema = model.schema; if (options._localModel != null && options._localModel.schema.nested[options.path]) { return []; } const _virtualRes = getVirtual(model.schema, options.path); const virtual = _virtualRes == null ? null : _virtualRes.virtual; if (virtual != null) { return _virtualPopulate(model, docs, options, _virtualRes); } let allSchemaTypes = getSchemaTypes(model, modelSchema, null, options.path); allSchemaTypes = Array.isArray(allSchemaTypes) ? allSchemaTypes : [allSchemaTypes].filter((v) => v != null); const isStrictPopulateDisabled = options.strictPopulate === false || options.options?.strictPopulate === false; if (!isStrictPopulateDisabled && allSchemaTypes.length === 0 && options._localModel != null) { return new StrictPopulate(options._fullPath || options.path); } for (let i = 0; i < len; i++) { doc = docs[i]; let justOne = null; if (doc.$__ != null && doc.populated(options.path)) { const forceRepopulate = options.forceRepopulate != null ? options.forceRepopulate : doc.constructor.base.options.forceRepopulate; if (forceRepopulate === false) { continue; } } const docSchema = doc != null && doc.$__ != null ? doc.$__schema : modelSchema; schema = getSchemaTypes(model, docSchema, doc, options.path); if (schema != null && schema.$isMongooseDocumentArray && schema.options.ref == null && schema.options.refPath == null) { continue; } const isUnderneathDocArray = schema && schema.$parentSchemaDocArray; if (isUnderneathDocArray && get(options, "options.sort") != null) { return new MongooseError("Cannot populate with `sort` on path " + options.path + " because it is a subproperty of a document array"); } modelNames = null; let isRefPath = false; let normalizedRefPath = null; let schemaOptions = null; let modelNamesInOrder = null; if (schema != null && schema.instance === "Embedded") { if (schema.options.ref) { const data2 = { localField: options.path + "._id", foreignField: "_id", justOne: true }; const res = _getModelNames(doc, schema, modelNameFromQuery, model); const unpopulatedValue = mpath.get(options.path, doc); const id2 = mpath.get("_id", unpopulatedValue); addModelNamesToMap(model, map, available, res.modelNames, options, data2, id2, doc, schemaOptions, unpopulatedValue); } continue; } if (Array.isArray(schema)) { const schemasArray = schema; for (const _schema of schemasArray) { let _modelNames; let res; try { res = _getModelNames(doc, _schema, modelNameFromQuery, model); _modelNames = res.modelNames; isRefPath = isRefPath || res.isRefPath; normalizedRefPath = normalizedRefPath || res.refPath; justOne = res.justOne; } catch (error) { return error; } if (isRefPath && !res.isRefPath) { continue; } if (!_modelNames) { continue; } modelNames = modelNames || []; for (const modelName of _modelNames) { if (modelNames.indexOf(modelName) === -1) { modelNames.push(modelName); } } } } else { try { const res = _getModelNames(doc, schema, modelNameFromQuery, model); modelNames = res.modelNames; isRefPath = res.isRefPath; normalizedRefPath = normalizedRefPath || res.refPath; justOne = res.justOne; schemaOptions = get(schema, "options.populate", null); if (isRefPath) { modelNamesInOrder = modelNames; modelNames = Array.from(new Set(modelNames)); } } catch (error) { return error; } if (!modelNames) { continue; } } const data = {}; const localField = options.path; const foreignField = "_id"; if ("justOne" in options && options.justOne !== void 0) { justOne = options.justOne; } else if (schema && !schema[schemaMixedSymbol]) { if (options.path.endsWith("." + schema.path) || options.path === schema.path) { justOne = Array.isArray(schema) ? schema.every((schema2) => !schema2.$isMongooseArray) : !schema.$isMongooseArray; } } if (!modelNames) { continue; } data.isVirtual = false; data.justOne = justOne; data.localField = localField; data.foreignField = foreignField; const ret = _getLocalFieldValues(doc, localField, model, options, null, schema); const id = String(utils.getValue(foreignField, doc)); options._docs[id] = Array.isArray(ret) ? ret.slice() : ret; let match = get(options, "match", null); const hasMatchFunction = typeof match === "function"; if (hasMatchFunction) { match = match.call(doc, doc); } throwOn$where(match); data.match = match; data.hasMatchFunction = hasMatchFunction; data.isRefPath = isRefPath; data.modelNamesInOrder = modelNamesInOrder; if (isRefPath) { const embeddedDiscriminatorModelNames = _findRefPathForDiscriminators( doc, modelSchema, data, options, normalizedRefPath, ret ); modelNames = embeddedDiscriminatorModelNames || modelNames; } try { addModelNamesToMap(model, map, available, modelNames, options, data, ret, doc, schemaOptions); } catch (err) { return err; } } return map; function _getModelNames(doc2, schema2, modelNameFromQuery2, model2) { let modelNames2; let isRefPath = false; let justOne = null; const originalSchema = schema2; if (schema2 && schema2.instance === "Array") { schema2 = schema2.caster; } if (schema2 && schema2.$isSchemaMap) { schema2 = schema2.$__schemaType; } const ref = schema2 && schema2.options && schema2.options.ref; refPath = schema2 && schema2.options && schema2.options.refPath; if (schema2 != null && schema2[schemaMixedSymbol] && !ref && !refPath && !modelNameFromQuery2) { return { modelNames: null }; } if (modelNameFromQuery2) { modelNames2 = [modelNameFromQuery2]; } else if (refPath != null) { if (typeof refPath === "function") { const subdocPath = options.path.slice(0, options.path.length - schema2.path.length - 1); const vals = mpath.get(subdocPath, doc2, lookupLocalFields); const subdocsBeingPopulated = Array.isArray(vals) ? utils.array.flatten(vals) : vals ? [vals] : []; modelNames2 = /* @__PURE__ */ new Set(); for (const subdoc of subdocsBeingPopulated) { refPath = refPath.call(subdoc, subdoc, options.path); modelNamesFromRefPath(refPath, doc2, options.path, modelSchema, options._queryProjection).forEach((name) => modelNames2.add(name)); } modelNames2 = Array.from(modelNames2); } else { modelNames2 = modelNamesFromRefPath(refPath, doc2, options.path, modelSchema, options._queryProjection); } isRefPath = true; } else { let ref2; let refPath2; let schemaForCurrentDoc; let discriminatorValue; let modelForCurrentDoc = model2; const discriminatorKey = model2.schema.options.discriminatorKey; if (!schema2 && discriminatorKey && (discriminatorValue = utils.getValue(discriminatorKey, doc2))) { const discriminatorModel = getDiscriminatorByValue(model2.discriminators, discriminatorValue) || model2; if (discriminatorModel != null) { modelForCurrentDoc = discriminatorModel; } else { try { modelForCurrentDoc = _getModelFromConn(model2.db, discriminatorValue); } catch (error) { return error; } } schemaForCurrentDoc = modelForCurrentDoc.schema._getSchema(options.path); if (schemaForCurrentDoc && schemaForCurrentDoc.caster) { schemaForCurrentDoc = schemaForCurrentDoc.caster; } } else { schemaForCurrentDoc = schema2; } if (originalSchema && originalSchema.path.endsWith(".$*")) { justOne = !originalSchema.$isMongooseArray && !originalSchema._arrayPath; } else if (schemaForCurrentDoc != null) { justOne = !schemaForCurrentDoc.$isMongooseArray && !schemaForCurrentDoc._arrayPath; } if ((ref2 = get(schemaForCurrentDoc, "options.ref")) != null) { if (schemaForCurrentDoc != null && typeof ref2 === "function" && options.path.endsWith("." + schemaForCurrentDoc.path)) { modelNames2 = /* @__PURE__ */ new Set(); const subdocPath = options.path.slice(0, options.path.length - schemaForCurrentDoc.path.length - 1); const vals = mpath.get(subdocPath, doc2, lookupLocalFields); const subdocsBeingPopulated = Array.isArray(vals) ? utils.array.flatten(vals) : vals ? [vals] : []; for (const subdoc of subdocsBeingPopulated) { modelNames2.add(handleRefFunction(ref2, subdoc)); } if (subdocsBeingPopulated.length === 0) { modelNames2 = [handleRefFunction(ref2, doc2)]; } else { modelNames2 = Array.from(modelNames2); } } else { ref2 = handleRefFunction(ref2, doc2); modelNames2 = [ref2]; } } else if ((schemaForCurrentDoc = get(schema2, "options.refPath")) != null) { isRefPath = true; if (typeof refPath2 === "function") { const subdocPath = options.path.slice(0, options.path.length - schemaForCurrentDoc.path.length - 1); const vals = mpath.get(subdocPath, doc2, lookupLocalFields); const subdocsBeingPopulated = Array.isArray(vals) ? utils.array.flatten(vals) : vals ? [vals] : []; modelNames2 = /* @__PURE__ */ new Set(); for (const subdoc of subdocsBeingPopulated) { refPath2 = refPath2.call(subdoc, subdoc, options.path); modelNamesFromRefPath(refPath2, doc2, options.path, modelSchema, options._queryProjection).forEach((name) => modelNames2.add(name)); } modelNames2 = Array.from(modelNames2); } else { modelNames2 = modelNamesFromRefPath(refPath2, doc2, options.path, modelSchema, options._queryProjection); } } } if (!modelNames2) { if (options._localModel == null) { modelNames2 = [model2.modelName]; } else { return { modelNames: modelNames2, justOne, isRefPath, refPath }; } } if (!Array.isArray(modelNames2)) { modelNames2 = [modelNames2]; } return { modelNames: modelNames2, justOne, isRefPath, refPath }; } }; function _virtualPopulate(model, docs, options, _virtualRes) { const map = []; const available = {}; const virtual = _virtualRes.virtual; for (const doc of docs) { let modelNames = null; const data = {}; let localField; const virtualPrefix = _virtualRes.nestedSchemaPath ? _virtualRes.nestedSchemaPath + "." : ""; if (typeof options.localField === "string") { localField = options.localField; } else if (typeof virtual.options.localField === "function") { localField = virtualPrefix + virtual.options.localField.call(doc, doc); } else if (Array.isArray(virtual.options.localField)) { localField = virtual.options.localField.map((field) => virtualPrefix + field); } else { localField = virtualPrefix + virtual.options.localField; } data.count = virtual.options.count; if (virtual.options.skip != null && !options.hasOwnProperty("skip")) { options.skip = virtual.options.skip; } if (virtual.options.limit != null && !options.hasOwnProperty("limit")) { options.limit = virtual.options.limit; } if (virtual.options.perDocumentLimit != null && !options.hasOwnProperty("perDocumentLimit")) { options.perDocumentLimit = virtual.options.perDocumentLimit; } let foreignField = virtual.options.foreignField; if (!localField || !foreignField) { return new MongooseError(`Cannot populate virtual \`${options.path}\` on model \`${model.modelName}\`, because options \`localField\` and / or \`foreignField\` are missing`); } if (typeof localField === "function") { localField = localField.call(doc, doc); } if (typeof foreignField === "function") { foreignField = foreignField.call(doc, doc); } data.isRefPath = false; let justOne = null; if ("justOne" in options && options.justOne !== void 0) { justOne = options.justOne; } modelNames = virtual._getModelNamesForPopulate(doc); if (virtual.options.refPath) { justOne = !!virtual.options.justOne; data.isRefPath = true; } else if (virtual.options.ref) { justOne = !!virtual.options.justOne; } data.isVirtual = true; data.virtual = virtual; data.justOne = justOne; const baseMatch = get(data, "virtual.options.match", null) || get(data, "virtual.options.options.match", null); let match = get(options, "match", null) || baseMatch; let hasMatchFunction = typeof match === "function"; if (hasMatchFunction) { match = match.call(doc, doc, data.virtual); } if (Array.isArray(localField) && Array.isArray(foreignField) && localField.length === foreignField.length) { match = Object.assign({}, match); for (let i = 1; i < localField.length; ++i) { match[foreignField[i]] = convertTo_id(mpath.get(localField[i], doc, lookupLocalFields), model.schema); hasMatchFunction = true; } localField = localField[0]; foreignField = foreignField[0]; } data.localField = localField; data.foreignField = foreignField; data.match = match; data.hasMatchFunction = hasMatchFunction; throwOn$where(match); const ret = _getLocalFieldValues(doc, localField, model, options, virtual); try { addModelNamesToMap(model, map, available, modelNames, options, data, ret, doc); } catch (err) { return err; } } return map; } function addModelNamesToMap(model, map, available, modelNames, options, data, ret, doc, schemaOptions, unpopulatedValue) { const connection = options.connection != null ? options.connection : model.db; unpopulatedValue = unpopulatedValue === void 0 ? ret : unpopulatedValue; if (Array.isArray(unpopulatedValue)) { unpopulatedValue = utils.cloneArrays(unpopulatedValue); } if (modelNames == null) { return; } const flatModelNames = utils.array.flatten(modelNames); let k = flatModelNames.length; while (k--) { let modelName = flatModelNames[k]; if (modelName == null) { continue; } let Model; if (options.model && options.model[modelSymbol]) { Model = options.model; } else if (modelName[modelSymbol]) { Model = modelName; modelName = Model.modelName; } else { try { Model = _getModelFromConn(connection, modelName); } catch (err) { if (ret !== void 0) { throw err; } Model = null; } } let ids = ret; const modelNamesForRefPath = data.modelNamesInOrder ? data.modelNamesInOrder : modelNames; if (data.isRefPath && Array.isArray(ret) && ret.length === modelNamesForRefPath.length) { ids = matchIdsToRefPaths(ret, modelNamesForRefPath, modelName); } const perDocumentLimit = options.perDocumentLimit == null ? get(options, "options.perDocumentLimit", null) : options.perDocumentLimit; if (!available[modelName] || perDocumentLimit != null) { const currentOptions = { model: Model }; if (data.isVirtual && get(data.virtual, "options.options")) { currentOptions.options = clone(data.virtual.options.options); } else if (schemaOptions != null) { currentOptions.options = Object.assign({}, schemaOptions); } utils.merge(currentOptions, options); options[populateModelSymbol] = Model; currentOptions[populateModelSymbol] = Model; available[modelName] = { model: Model, options: currentOptions, match: data.hasMatchFunction ? [data.match] : data.match, docs: [doc], ids: [ids], allIds: [ret], unpopulatedValues: [unpopulatedValue], localField: /* @__PURE__ */ new Set([data.localField]), foreignField: /* @__PURE__ */ new Set([data.foreignField]), justOne: data.justOne, isVirtual: data.isVirtual, virtual: data.virtual, count: data.count, [populateModelSymbol]: Model }; map.push(available[modelName]); } else { available[modelName].localField.add(data.localField); available[modelName].foreignField.add(data.foreignField); available[modelName].docs.push(doc); available[modelName].ids.push(ids); available[modelName].allIds.push(ret); available[modelName].unpopulatedValues.push(unpopulatedValue); if (data.hasMatchFunction) { available[modelName].match.push(data.match); } } } } function _getModelFromConn(conn, modelName) { if (conn.models[modelName] == null && conn._parent != null) { return _getModelFromConn(conn._parent, modelName); } return conn.model(modelName); } function matchIdsToRefPaths(ids, refPaths, refPathToFind) { if (!Array.isArray(refPaths)) { return refPaths === refPathToFind ? Array.isArray(ids) ? utils.array.flatten(ids) : [ids] : []; } if (Array.isArray(ids) && Array.isArray(refPaths)) { return ids.flatMap((id, index) => matchIdsToRefPaths(id, refPaths[index], refPathToFind)); } return []; } function handleRefFunction(ref, doc) { if (typeof ref === "function" && !ref[modelSymbol]) { return ref.call(doc, doc); } return ref; } function _getLocalFieldValues(doc, localField, model, options, virtual, schema) { const localFieldPathType = model.schema._getPathType(localField); const localFieldPath = localFieldPathType === "real" ? model.schema.path(localField) : localFieldPathType.schema; const localFieldGetters = localFieldPath && localFieldPath.getters ? localFieldPath.getters : []; localField = localFieldPath != null && localFieldPath.instance === "Embedded" ? localField + "._id" : localField; const _populateOptions = get(options, "options", {}); const getters = "getters" in _populateOptions ? _populateOptions.getters : get(virtual, "options.getters", false); if (localFieldGetters.length !== 0 && getters) { const hydratedDoc = doc.$__ != null ? doc : model.hydrate(doc); const localFieldValue = utils.getValue(localField, doc); if (Array.isArray(localFieldValue)) { const localFieldHydratedValue = utils.getValue(localField.split(".").slice(0, -1), hydratedDoc); return localFieldValue.map((localFieldArrVal, localFieldArrIndex) => localFieldPath.applyGetters(localFieldArrVal, localFieldHydratedValue[localFieldArrIndex])); } else { return localFieldPath.applyGetters(localFieldValue, hydratedDoc); } } else { return convertTo_id(mpath.get(localField, doc, lookupLocalFields), schema); } } function convertTo_id(val, schema) { if (val != null && val.$__ != null) { return val._doc._id; } if (val != null && val._id != null && (schema == null || !schema.$isSchemaMap)) { return val._id; } if (Array.isArray(val)) { const rawVal = val.__array != null ? val.__array : val; for (let i = 0; i < rawVal.length; ++i) { if (rawVal[i] != null && rawVal[i].$__ != null) { rawVal[i] = rawVal[i]._doc._id; } } if (utils.isMongooseArray(val) && val.$schema()) { return val.$schema()._castForPopulate(val, val.$parent()); } return [].concat(val); } if (getConstructorName(val) === "Object" && // The intent here is we should only flatten the object if we expect // to get a Map in the end. Avoid doing this for mixed types. (schema == null || schema[schemaMixedSymbol] == null)) { const ret = []; for (const key of Object.keys(val)) { ret.push(val[key]); } return ret; } if (val instanceof Map) { return Array.from(val.values()); } return val; } function _findRefPathForDiscriminators(doc, modelSchema, data, options, normalizedRefPath, ret) { if (!data.isRefPath || normalizedRefPath == null) { return; } const pieces = normalizedRefPath.split("."); let cur = ""; let modelNames = void 0; for (let i = 0; i < pieces.length; ++i) { const piece = pieces[i]; cur = cur + (cur.length === 0 ? "" : ".") + piece; const schematype = modelSchema.path(cur); if (schematype != null && schematype.$isMongooseArray && schematype.caster.discriminators != null && Object.keys(schematype.caster.discriminators).length !== 0) { const subdocs = utils.getValue(cur, doc); const remnant = options.path.substring(cur.length + 1); const discriminatorKey = schematype.caster.schema.options.discriminatorKey; modelNames = []; for (const subdoc of subdocs) { const discriminatorName = utils.getValue(discriminatorKey, subdoc); const discriminator = schematype.caster.discriminators[discriminatorName]; const discriminatorSchema = discriminator && discriminator.schema; if (discriminatorSchema == null) { continue; } const _path = discriminatorSchema.path(remnant); if (_path == null || _path.options.refPath == null) { const docValue = utils.getValue(data.localField.substring(cur.length + 1), subdoc); ret.forEach((v, i2) => { if (v === docValue) { ret[i2] = SkipPopulateValue(v); } }); continue; } const modelName = utils.getValue(pieces.slice(i + 1).join("."), subdoc); modelNames.push(modelName); } } } return modelNames; } function throwOn$where(match) { if (match == null) { return; } if (typeof match !== "object") { return; } for (const key of Object.keys(match)) { if (key === "$where") { throw new MongooseError("Cannot use $where filter with populate() match"); } if (match[key] != null && typeof match[key] === "object") { throwOn$where(match[key]); } } } } }); // netlify/functions/node_modules/mongoose/lib/helpers/indexes/isDefaultIdIndex.js var require_isDefaultIdIndex = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/indexes/isDefaultIdIndex.js"(exports2, module2) { "use strict"; var get = require_get(); module2.exports = function isDefaultIdIndex(index) { if (Array.isArray(index)) { const keys = Object.keys(index[0]); return keys.length === 1 && keys[0] === "_id" && index[0]._id !== "hashed"; } if (typeof index !== "object") { return false; } const key = get(index, "key", {}); return Object.keys(key).length === 1 && key.hasOwnProperty("_id"); }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/indexes/isIndexEqual.js var require_isIndexEqual = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/indexes/isIndexEqual.js"(exports2, module2) { "use strict"; var get = require_get(); var utils = require_utils3(); module2.exports = function isIndexEqual(schemaIndexKeysObject, options, dbIndex) { if (dbIndex.textIndexVersion != null) { delete dbIndex.key._fts; delete dbIndex.key._ftsx; const weights = { ...dbIndex.weights, ...dbIndex.key }; if (Object.keys(weights).length !== Object.keys(schemaIndexKeysObject).length) { return false; } for (const prop of Object.keys(weights)) { if (!(prop in schemaIndexKeysObject)) { return false; } const weight = weights[prop]; if (weight !== get(options, "weights." + prop) && !(weight === 1 && get(options, "weights." + prop) == null)) { return false; } } if (options["default_language"] !== dbIndex["default_language"]) { return dbIndex["default_language"] === "english" && options["default_language"] == null; } return true; } const optionKeys = [ "unique", "partialFilterExpression", "sparse", "expireAfterSeconds", "collation" ]; for (const key of optionKeys) { if (!(key in options) && !(key in dbIndex)) { continue; } if (key === "collation") { if (options[key] == null || dbIndex[key] == null) { return options[key] == null && dbIndex[key] == null; } const definedKeys = Object.keys(options.collation); const schemaCollation = options.collation; const dbCollation = dbIndex.collation; for (const opt of definedKeys) { if (get(schemaCollation, opt) !== get(dbCollation, opt)) { return false; } } } else if (!utils.deepEqual(options[key], dbIndex[key])) { return false; } } const schemaIndexKeys = Object.keys(schemaIndexKeysObject); const dbIndexKeys = Object.keys(dbIndex.key); if (schemaIndexKeys.length !== dbIndexKeys.length) { return false; } for (let i = 0; i < schemaIndexKeys.length; ++i) { if (schemaIndexKeys[i] !== dbIndexKeys[i]) { return false; } if (!utils.deepEqual(schemaIndexKeysObject[schemaIndexKeys[i]], dbIndex.key[dbIndexKeys[i]])) { return false; } } return true; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/indexes/isTimeseriesIndex.js var require_isTimeseriesIndex = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/indexes/isTimeseriesIndex.js"(exports2, module2) { "use strict"; module2.exports = function isTimeseriesIndex(dbIndex, schemaOptions) { if (schemaOptions.timeseries == null) { return false; } const { timeField, metaField } = schemaOptions.timeseries; if (typeof timeField !== "string" || typeof metaField !== "string") { return false; } return Object.keys(dbIndex.key).length === 2 && dbIndex.key[timeField] === 1 && dbIndex.key[metaField] === 1; }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/indexes/getRelatedIndexes.js var require_getRelatedIndexes = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/indexes/getRelatedIndexes.js"(exports2, module2) { "use strict"; var hasDollarKeys = require_hasDollarKeys(); function getRelatedSchemaIndexes(model, schemaIndexes) { return getRelatedIndexes({ baseModelName: model.baseModelName, discriminatorMapping: model.schema.discriminatorMapping, indexes: schemaIndexes, indexesType: "schema" }); } function getRelatedDBIndexes(model, dbIndexes) { return getRelatedIndexes({ baseModelName: model.baseModelName, discriminatorMapping: model.schema.discriminatorMapping, indexes: dbIndexes, indexesType: "db" }); } module2.exports = { getRelatedSchemaIndexes, getRelatedDBIndexes }; function getRelatedIndexes({ baseModelName, discriminatorMapping, indexes, indexesType }) { const discriminatorKey = discriminatorMapping && discriminatorMapping.key; const discriminatorValue = discriminatorMapping && discriminatorMapping.value; if (!discriminatorKey) { return indexes; } const isChildDiscriminatorModel = Boolean(baseModelName); if (isChildDiscriminatorModel) { return indexes.filter((index) => { const partialFilterExpression = getPartialFilterExpression(index, indexesType); return partialFilterExpression && partialFilterExpression[discriminatorKey] === discriminatorValue; }); } return indexes.filter((index) => { const partialFilterExpression = getPartialFilterExpression(index, indexesType); return !partialFilterExpression || !partialFilterExpression[discriminatorKey] || hasDollarKeys(partialFilterExpression[discriminatorKey]) && !("$eq" in partialFilterExpression[discriminatorKey]); }); } function getPartialFilterExpression(index, indexesType) { if (indexesType === "schema") { const options = index[1]; return options && options.partialFilterExpression; } return index.partialFilterExpression; } } }); // netlify/functions/node_modules/mongoose/lib/helpers/parallelLimit.js var require_parallelLimit = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/parallelLimit.js"(exports2, module2) { "use strict"; module2.exports = parallelLimit; function parallelLimit(fns, limit, callback) { let numInProgress = 0; let numFinished = 0; let error = null; if (limit <= 0) { throw new Error("Limit must be positive"); } if (fns.length === 0) { return callback(null, []); } for (let i = 0; i < fns.length && i < limit; ++i) { _start(); } function _start() { fns[numFinished + numInProgress](_done(numFinished + numInProgress)); ++numInProgress; } const results = []; function _done(index) { return (err, res) => { --numInProgress; ++numFinished; if (error != null) { return; } if (err != null) { error = err; return callback(error); } results[index] = res; if (numFinished === fns.length) { return callback(null, results); } else if (numFinished + numInProgress < fns.length) { _start(); } }; } } } }); // netlify/functions/node_modules/mongoose/lib/helpers/model/pushNestedArrayPaths.js var require_pushNestedArrayPaths = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/model/pushNestedArrayPaths.js"(exports2, module2) { "use strict"; module2.exports = function pushNestedArrayPaths(paths, nestedArray, path) { if (nestedArray == null) { return; } for (let i = 0; i < nestedArray.length; ++i) { if (Array.isArray(nestedArray[i])) { pushNestedArrayPaths(paths, nestedArray[i], path + "." + i); } else { paths.push(path + "." + i); } } }; } }); // netlify/functions/node_modules/mongoose/lib/helpers/populate/removeDeselectedForeignField.js var require_removeDeselectedForeignField = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/populate/removeDeselectedForeignField.js"(exports2, module2) { "use strict"; var get = require_get(); var mpath = require_mpath(); var parseProjection = require_parseProjection(); module2.exports = function removeDeselectedForeignField(foreignFields, options, docs) { const projection = parseProjection(get(options, "select", null), true) || parseProjection(get(options, "options.select", null), true); if (projection == null) { return; } for (const foreignField of foreignFields) { if (!projection.hasOwnProperty("-" + foreignField)) { continue; } for (const val of docs) { if (val.$__ != null) { mpath.unset(foreignField, val._doc); } else { mpath.unset(foreignField, val); } } } }; } }); // netlify/functions/node_modules/mongoose/lib/model.js var require_model = __commonJS({ "netlify/functions/node_modules/mongoose/lib/model.js"(exports2, module2) { "use strict"; var Aggregate = require_aggregate2(); var ChangeStream = require_changeStream(); var Document = require_document2(); var DocumentNotFoundError = require_notFound(); var EventEmitter = require("events").EventEmitter; var Kareem = require_kareem(); var MongooseBulkWriteError = require_bulkWriteError(); var MongooseError = require_error2(); var ObjectParameterError = require_objectParameter(); var OverwriteModelError = require_overwriteModel(); var Query = require_query(); var SaveOptions = require_saveOptions(); var Schema = require_schema2(); var ValidationError = require_validation(); var VersionError = require_version(); var ParallelSaveError = require_parallelSave(); var applyDefaultsHelper = require_applyDefaults(); var applyDefaultsToPOJO = require_applyDefaultsToPOJO(); var applyEmbeddedDiscriminators = require_applyEmbeddedDiscriminators(); var applyHooks = require_applyHooks(); var applyMethods = require_applyMethods(); var applyProjection = require_applyProjection(); var applyReadConcern = require_applyReadConcern(); var applySchemaCollation = require_applySchemaCollation(); var applyStaticHooks = require_applyStaticHooks(); var applyStatics = require_applyStatics(); var applyTimestampsHelper = require_applyTimestamps(); var applyWriteConcern = require_applyWriteConcern(); var applyVirtualsHelper = require_applyVirtuals(); var assignVals = require_assignVals(); var castBulkWrite = require_castBulkWrite(); var clone = require_clone(); var createPopulateQueryFilter = require_createPopulateQueryFilter(); var decorateUpdateWithVersionKey = require_decorateUpdateWithVersionKey(); var getDefaultBulkwriteResult = require_getDefaultBulkwriteResult(); var getSchemaDiscriminatorByValue = require_getSchemaDiscriminatorByValue(); var discriminator = require_discriminator(); var each = require_each(); var get = require_get(); var getConstructorName = require_getConstructorName(); var getDiscriminatorByValue = require_getDiscriminatorByValue(); var getModelsMapForPopulate = require_getModelsMapForPopulate(); var immediate = require_immediate(); var internalToObjectOptions = require_options().internalToObjectOptions; var isDefaultIdIndex = require_isDefaultIdIndex(); var isIndexEqual = require_isIndexEqual(); var isTimeseriesIndex = require_isTimeseriesIndex(); var { getRelatedDBIndexes, getRelatedSchemaIndexes } = require_getRelatedIndexes(); var decorateDiscriminatorIndexOptions = require_decorateDiscriminatorIndexOptions(); var isPathSelectedInclusive = require_isPathSelectedInclusive(); var leanPopulateMap = require_leanPopulateMap(); var parallelLimit = require_parallelLimit(); var prepareDiscriminatorPipeline = require_prepareDiscriminatorPipeline(); var pushNestedArrayPaths = require_pushNestedArrayPaths(); var removeDeselectedForeignField = require_removeDeselectedForeignField(); var setDottedPath = require_setDottedPath(); var util = require("util"); var utils = require_utils3(); var minimize = require_minimize(); var MongooseBulkSaveIncompleteError = require_bulkSaveIncompleteError(); var ObjectExpectedError = require_objectExpected(); var decorateBulkWriteResult = require_decorateBulkWriteResult(); var modelCollectionSymbol = Symbol("mongoose#Model#collection"); var modelDbSymbol = Symbol("mongoose#Model#db"); var modelSymbol = require_symbols().modelSymbol; var subclassedSymbol = Symbol("mongoose#Model#subclassed"); var { VERSION_INC, VERSION_WHERE, VERSION_ALL } = Document; var saveToObjectOptions = Object.assign({}, internalToObjectOptions, { bson: true }); function Model(doc, fields, skipId) { if (fields instanceof Schema) { throw new TypeError("2nd argument to `Model` constructor must be a POJO or string, **not** a schema. Make sure you're calling `mongoose.model()`, not `mongoose.Model()`."); } if (typeof doc === "string") { throw new TypeError("First argument to `Model` constructor must be an object, **not** a string. Make sure you're calling `mongoose.model()`, not `mongoose.Model()`."); } Document.call(this, doc, fields, skipId); } Object.setPrototypeOf(Model.prototype, Document.prototype); Model.prototype.$isMongooseModelPrototype = true; Model.prototype.db; Model.useConnection = function useConnection(connection) { if (!connection) { throw new Error("Please provide a connection."); } if (this.db) { delete this.db.models[this.modelName]; delete this.prototype.db; delete this.prototype[modelDbSymbol]; delete this.prototype.collection; delete this.prototype.$collection; delete this.prototype[modelCollectionSymbol]; } this.db = connection; const collection = connection.collection(this.collection.collectionName, connection.options); this.prototype.collection = collection; this.prototype.$collection = collection; this.prototype[modelCollectionSymbol] = collection; this.prototype.db = connection; this.prototype[modelDbSymbol] = connection; this.collection = collection; this.$__collection = collection; connection.models[this.modelName] = this; return this; }; Model.prototype.collection; Model.prototype.$__collection; Model.prototype.modelName; Model.prototype.$where; Model.prototype.baseModelName; Model.events; Model._middleware; function _applyCustomWhere(doc, where) { if (doc.$where == null) { return; } for (const key of Object.keys(doc.$where)) { where[key] = doc.$where[key]; } } Model.prototype.$__handleSave = function(options, callback) { const saveOptions = {}; applyWriteConcern(this.$__schema, options); if (typeof options.writeConcern !== "undefined") { saveOptions.writeConcern = {}; if ("w" in options.writeConcern) { saveOptions.writeConcern.w = options.writeConcern.w; } if ("j" in options.writeConcern) { saveOptions.writeConcern.j = options.writeConcern.j; } if ("wtimeout" in options.writeConcern) { saveOptions.writeConcern.wtimeout = options.writeConcern.wtimeout; } } else { if ("w" in options) { saveOptions.w = options.w; } if ("j" in options) { saveOptions.j = options.j; } if ("wtimeout" in options) { saveOptions.wtimeout = options.wtimeout; } } if ("checkKeys" in options) { saveOptions.checkKeys = options.checkKeys; } const session = this.$session(); const asyncLocalStorage = this[modelDbSymbol].base.transactionAsyncLocalStorage?.getStore(); if (session != null) { saveOptions.session = session; } else if (!options.hasOwnProperty("session") && asyncLocalStorage?.session != null) { saveOptions.session = asyncLocalStorage.session; } if (this.$isNew) { const obj = this.toObject(saveToObjectOptions); if ((obj || {})._id === void 0) { immediate(function() { callback(new MongooseError("document must have an _id before saving")); }); return; } this.$__version(true, obj); this[modelCollectionSymbol].insertOne(obj, saveOptions).then( (ret) => callback(null, ret), (err) => { _setIsNew(this, true); callback(err, null); } ); this.$__reset(); _setIsNew(this, false); this.$__.inserting = true; return; } this.$__.inserting = false; const delta = this.$__delta(); if (options.pathsToSave) { for (const key in delta[1]["$set"]) { if (options.pathsToSave.includes(key)) { continue; } else if (options.pathsToSave.some((pathToSave) => key.slice(0, pathToSave.length) === pathToSave && key.charAt(pathToSave.length) === ".")) { continue; } else { delete delta[1]["$set"][key]; } } } if (delta) { if (delta instanceof MongooseError) { callback(delta); return; } const where = this.$__where(delta[0]); if (where instanceof MongooseError) { callback(where); return; } _applyCustomWhere(this, where); const update = delta[1]; if (this.$__schema.options.minimize) { for (const updateOp of Object.values(update)) { if (updateOp == null) { continue; } for (const key of Object.keys(updateOp)) { if (updateOp[key] == null || typeof updateOp[key] !== "object") { continue; } if (!utils.isPOJO(updateOp[key])) { continue; } minimize(updateOp[key]); if (Object.keys(updateOp[key]).length === 0) { delete updateOp[key]; update.$unset = update.$unset || {}; update.$unset[key] = 1; } } } } this[modelCollectionSymbol].updateOne(where, update, saveOptions).then( (ret) => { if (ret == null) { ret = { $where: where }; } else { ret.$where = where; } callback(null, ret); }, (err) => { this.$__undoReset(); callback(err); } ); } else { handleEmptyUpdate.call(this); return; } this.$__.modifiedPaths = this.modifiedPaths().concat(Object.keys(this.$__.activePaths.getStatePaths("default"))); this.$__reset(); _setIsNew(this, false); function handleEmptyUpdate() { const optionsWithCustomValues = Object.assign({}, options, saveOptions); const where = this.$__where(); const optimisticConcurrency = this.$__schema.options.optimisticConcurrency; if (optimisticConcurrency && !Array.isArray(optimisticConcurrency)) { const key = this.$__schema.options.versionKey; const val = this.$__getValue(key); if (val != null) { where[key] = val; } } applyReadConcern(this.$__schema, optionsWithCustomValues); this.constructor.collection.findOne(where, optionsWithCustomValues).then((documentExists) => { const matchedCount = !documentExists ? 0 : 1; callback(null, { $where: where, matchedCount }); }).catch(callback); } }; Model.prototype.$__save = function(options, callback) { this.$__handleSave(options, (error, result) => { if (error) { error = this.$__schema._transformDuplicateKeyError(error); const hooks = this.$__schema.s.hooks; return hooks.execPost("save:error", this, [this], { error }, (error2) => { callback(error2, this); }); } let numAffected = 0; const writeConcern = options != null ? options.writeConcern != null ? options.writeConcern.w : options.w : 0; if (writeConcern !== 0) { if (result != null) { if (Array.isArray(result)) { numAffected = result.length; } else if (result.matchedCount != null) { numAffected = result.matchedCount; } else { numAffected = result; } } const versionBump = this.$__.version; if (versionBump && !this.$__.inserting) { const doIncrement = VERSION_INC === (VERSION_INC & this.$__.version); this.$__.version = void 0; const key = this.$__schema.options.versionKey; const version = this.$__getValue(key) || 0; if (numAffected <= 0) { this.$__undoReset(); const err = this.$__.$versionError || new VersionError(this, version, this.$__.modifiedPaths); return callback(err, this); } if (doIncrement) { this.$__setValue(key, version + 1); } } if (result != null && numAffected <= 0) { this.$__undoReset(); error = new DocumentNotFoundError( result.$where, this.constructor.modelName, numAffected, result ); const hooks = this.$__schema.s.hooks; return hooks.execPost("save:error", this, [this], { error }, (error2) => { callback(error2, this); }); } } this.$__.saving = void 0; this.$__.savedState = {}; this.$emit("save", this, numAffected); this.constructor.emit("save", this, numAffected); callback(null, this); }); }; function generateVersionError(doc, modifiedPaths, defaultPaths) { const key = doc.$__schema.options.versionKey; if (!key) { return null; } const version = doc.$__getValue(key) || 0; return new VersionError(doc, version, modifiedPaths.concat(defaultPaths)); } Model.prototype.save = async function save(options) { if (typeof options === "function" || typeof arguments[1] === "function") { throw new MongooseError("Model.prototype.save() no longer accepts a callback"); } let parallelSave; this.$op = "save"; if (this.$__.saving) { parallelSave = new ParallelSaveError(this); } else { this.$__.saving = new ParallelSaveError(this); } options = new SaveOptions(options); if (options.hasOwnProperty("session")) { this.$session(options.session); } if (this.$__.timestamps != null) { options.timestamps = this.$__.timestamps; } this.$__.$versionError = generateVersionError( this, this.modifiedPaths(), Object.keys(this.$__.activePaths.getStatePaths("default")) ); if (parallelSave) { this.$__handleReject(parallelSave); throw parallelSave; } this.$__.saveOptions = options; await new Promise((resolve, reject) => { this.$__save(options, (error) => { this.$__.saving = null; this.$__.saveOptions = null; this.$__.$versionError = null; this.$op = null; if (error != null) { this.$__handleReject(error); return reject(error); } resolve(); }); }); return this; }; Model.prototype.$save = Model.prototype.save; Model.prototype.$__version = function(where, delta) { const key = this.$__schema.options.versionKey; if (where === true) { if (key) { setDottedPath(delta, key, 0); this.$__setValue(key, 0); } return; } if (key === false) { return; } if (!this.$__isSelected(key)) { return; } if (VERSION_WHERE === (VERSION_WHERE & this.$__.version)) { const value = this.$__getValue(key); if (value != null) where[key] = value; } if (VERSION_INC === (VERSION_INC & this.$__.version)) { if (get(delta.$set, key, null) != null) { ++delta.$set[key]; } else { delta.$inc = delta.$inc || {}; delta.$inc[key] = 1; } } }; Model.prototype.increment = function increment() { this.$__.version = VERSION_ALL; return this; }; Model.prototype.$__where = function _where(where) { where || (where = {}); if (!where._id) { where._id = this._doc._id; } if (this._doc._id === void 0) { return new MongooseError("No _id found on document!"); } return where; }; Model.prototype.deleteOne = function deleteOne(options) { if (typeof options === "function" || typeof arguments[1] === "function") { throw new MongooseError("Model.prototype.deleteOne() no longer accepts a callback"); } if (!options) { options = {}; } if (options.hasOwnProperty("session")) { this.$session(options.session); } const self2 = this; const where = this.$__where(); if (where instanceof Error) { throw where; } const query = self2.constructor.deleteOne(where, options); if (this.$session() != null) { if (!("session" in query.options)) { query.options.session = this.$session(); } } query.pre(function queryPreDeleteOne(cb) { self2.constructor._middleware.execPre("deleteOne", self2, [self2], cb); }); query.pre(function callSubdocPreHooks(cb) { each(self2.$getAllSubdocs(), (subdoc, cb2) => { subdoc.constructor._middleware.execPre("deleteOne", subdoc, [subdoc], cb2); }, cb); }); query.pre(function skipIfAlreadyDeleted(cb) { if (self2.$__.isDeleted) { return cb(Kareem.skipWrappedFunction()); } return cb(); }); query.post(function callSubdocPostHooks(cb) { each(self2.$getAllSubdocs(), (subdoc, cb2) => { subdoc.constructor._middleware.execPost("deleteOne", subdoc, [subdoc], {}, cb2); }, cb); }); query.post(function queryPostDeleteOne(cb) { self2.constructor._middleware.execPost("deleteOne", self2, [self2], {}, cb); }); return query; }; Model.prototype.$model = function $model(name) { if (arguments.length === 0) { return this.constructor; } return this[modelDbSymbol].model(name); }; Model.prototype.model = Model.prototype.$model; Model.exists = function exists(filter, options) { _checkContext(this, "exists"); if (typeof arguments[2] === "function") { throw new MongooseError("Model.exists() no longer accepts a callback"); } const query = this.findOne(filter).select({ _id: 1 }).lean().setOptions(options); return query; }; Model.discriminator = function(name, schema, options) { let model; if (typeof name === "function") { model = name; name = utils.getFunctionName(model); if (!(model.prototype instanceof Model)) { throw new MongooseError("The provided class " + name + " must extend Model"); } } options = options || {}; const value = utils.isPOJO(options) ? options.value : options; const clone2 = typeof options.clone === "boolean" ? options.clone : true; const mergePlugins = typeof options.mergePlugins === "boolean" ? options.mergePlugins : true; const overwriteModels = typeof options.overwriteModels === "boolean" ? options.overwriteModels : false; _checkContext(this, "discriminator"); if (utils.isObject(schema) && !schema.instanceOfSchema) { schema = new Schema(schema); } if (schema instanceof Schema && clone2) { schema = schema.clone(); } schema = discriminator(this, name, schema, value, mergePlugins, options.mergeHooks, overwriteModels); if (this.db.models[name] && !schema.options.overwriteModels && !overwriteModels) { throw new OverwriteModelError(name); } schema.$isRootDiscriminator = true; schema.$globalPluginsApplied = true; model = this.db.model(model || name, schema, this.$__collection.name); this.discriminators[name] = model; const d = this.discriminators[name]; Object.setPrototypeOf(d.prototype, this.prototype); Object.defineProperty(d, "baseModelName", { value: this.modelName, configurable: true, writable: false }); applyMethods(d, schema); applyStatics(d, schema); if (this[subclassedSymbol] != null) { for (const submodel of this[subclassedSymbol]) { submodel.discriminators = submodel.discriminators || {}; submodel.discriminators[name] = model.__subclass(model.db, schema, submodel.collection.name); } } return d; }; function _checkContext(ctx, fnName) { if (ctx == null || ctx === global) { throw new MongooseError("`Model." + fnName + "()` cannot run without a model as `this`. Make sure you are calling `MyModel." + fnName + "()` where `MyModel` is a Mongoose model."); } else if (ctx[modelSymbol] == null) { throw new MongooseError("`Model." + fnName + "()` cannot run without a model as `this`. Make sure you are not calling `new Model." + fnName + "()`"); } } for (const i in EventEmitter.prototype) { Model[i] = EventEmitter.prototype[i]; } Model.init = function init() { _checkContext(this, "init"); if (typeof arguments[0] === "function") { throw new MongooseError("Model.init() no longer accepts a callback"); } this.schema.emit("init", this); if (this.$init != null) { return this.$init; } const conn = this.db; const _ensureIndexes2 = async () => { const autoIndex = utils.getOption( "autoIndex", this.schema.options, conn.config, conn.base.options ); if (!autoIndex) { return; } return await this.ensureIndexes({ _automatic: true }); }; const _createSearchIndexes = async () => { const autoSearchIndex = utils.getOption( "autoSearchIndex", this.schema.options, conn.config, conn.base.options ); if (!autoSearchIndex) { return; } return await this.createSearchIndexes(); }; const _createCollection = async () => { let autoCreate = utils.getOption( "autoCreate", this.schema.options, conn.config // No base.options here because we don't want to take the base value if the connection hasn't // set it yet ); if (autoCreate == null) { await conn._waitForConnect(true); autoCreate = utils.getOption( "autoCreate", this.schema.options, conn.config, conn.base.options ); } if (!autoCreate) { return; } return await this.createCollection(); }; this.$init = _createCollection().then(() => _ensureIndexes2()).then(() => _createSearchIndexes()); const _catch = this.$init.catch; const _this = this; this.$init.catch = function() { _this.$caught = true; return _catch.apply(_this.$init, arguments); }; return this.$init; }; Model.createCollection = async function createCollection(options) { _checkContext(this, "createCollection"); if (typeof arguments[0] === "function" || typeof arguments[1] === "function") { throw new MongooseError("Model.createCollection() no longer accepts a callback"); } const shouldSkip = await new Promise((resolve, reject) => { this.hooks.execPre("createCollection", this, [options], (err) => { if (err != null) { if (err instanceof Kareem.skipWrappedFunction) { return resolve(true); } return reject(err); } resolve(); }); }); const collectionOptions = this && this.schema && this.schema.options && this.schema.options.collectionOptions; if (collectionOptions != null) { options = Object.assign({}, collectionOptions, options); } const schemaCollation = this && this.schema && this.schema.options && this.schema.options.collation; if (schemaCollation != null) { options = Object.assign({ collation: schemaCollation }, options); } const capped = this && this.schema && this.schema.options && this.schema.options.capped; if (capped != null) { if (typeof capped === "number") { options = Object.assign({ capped: true, size: capped }, options); } else if (typeof capped === "object") { options = Object.assign({ capped: true }, capped, options); } } const timeseries = this && this.schema && this.schema.options && this.schema.options.timeseries; if (timeseries != null) { options = Object.assign({ timeseries }, options); if (options.expireAfterSeconds != null) { } else if (options.expires != null) { utils.expires(options); } else if (this.schema.options.expireAfterSeconds != null) { options.expireAfterSeconds = this.schema.options.expireAfterSeconds; } else if (this.schema.options.expires != null) { options.expires = this.schema.options.expires; utils.expires(options); } } const clusteredIndex = this && this.schema && this.schema.options && this.schema.options.clusteredIndex; if (clusteredIndex != null) { options = Object.assign({ clusteredIndex: { ...clusteredIndex, unique: true } }, options); } try { if (!shouldSkip) { await this.db.createCollection(this.$__collection.collectionName, options); } } catch (err) { if (err != null && (err.name !== "MongoServerError" || err.code !== 48)) { await new Promise((resolve, reject) => { const _opts = { error: err }; this.hooks.execPost("createCollection", this, [null], _opts, (err2) => { if (err2 != null) { return reject(err2); } resolve(); }); }); } } await new Promise((resolve, reject) => { this.hooks.execPost("createCollection", this, [this.$__collection], (err) => { if (err != null) { return reject(err); } resolve(); }); }); return this.$__collection; }; Model.syncIndexes = async function syncIndexes(options) { _checkContext(this, "syncIndexes"); if (typeof arguments[0] === "function" || typeof arguments[1] === "function") { throw new MongooseError("Model.syncIndexes() no longer accepts a callback"); } const autoCreate = options?.autoCreate ?? this.schema.options?.autoCreate ?? this.db.config.autoCreate ?? true; if (autoCreate) { try { await this.createCollection(); } catch (err) { if (err != null && (err.name !== "MongoServerError" || err.code !== 48)) { throw err; } } } const diffIndexesResult = await this.diffIndexes({ indexOptionsToCreate: true }); const dropped = await this.cleanIndexes({ ...options, toDrop: diffIndexesResult.toDrop }); await this.createIndexes({ ...options, toCreate: diffIndexesResult.toCreate }); return dropped; }; Model.createSearchIndex = async function createSearchIndex(description) { _checkContext(this, "createSearchIndex"); return await this.$__collection.createSearchIndex(description); }; Model.updateSearchIndex = async function updateSearchIndex(name, definition) { _checkContext(this, "updateSearchIndex"); return await this.$__collection.updateSearchIndex(name, definition); }; Model.dropSearchIndex = async function dropSearchIndex(name) { _checkContext(this, "dropSearchIndex"); return await this.$__collection.dropSearchIndex(name); }; Model.listSearchIndexes = async function listSearchIndexes(options) { _checkContext(this, "listSearchIndexes"); const cursor = await this.$__collection.listSearchIndexes(options); return await cursor.toArray(); }; Model.diffIndexes = async function diffIndexes(options) { if (typeof arguments[0] === "function" || typeof arguments[1] === "function") { throw new MongooseError("Model.syncIndexes() no longer accepts a callback"); } const model = this; let dbIndexes = await model.listIndexes().catch((err) => { if (err.codeName == "NamespaceNotFound") { return void 0; } throw err; }); if (dbIndexes === void 0) { dbIndexes = []; } dbIndexes = getRelatedDBIndexes(model, dbIndexes); const schema = model.schema; const schemaIndexes = getRelatedSchemaIndexes(model, schema.indexes()); const toDrop = getIndexesToDrop(schema, schemaIndexes, dbIndexes); const toCreate = getIndexesToCreate(schema, schemaIndexes, dbIndexes, toDrop, options); return { toDrop, toCreate }; }; function getIndexesToCreate(schema, schemaIndexes, dbIndexes, toDrop, options) { const toCreate = []; const indexOptionsToCreate = options?.indexOptionsToCreate ?? false; for (const [schemaIndexKeysObject, schemaIndexOptions] of schemaIndexes) { let found = false; const options2 = decorateDiscriminatorIndexOptions(schema, clone(schemaIndexOptions)); for (const index of dbIndexes) { if (isDefaultIdIndex(index)) { continue; } if (isIndexEqual(schemaIndexKeysObject, options2, index) && !toDrop.includes(index.name)) { found = true; break; } } if (!found) { if (indexOptionsToCreate) { toCreate.push([schemaIndexKeysObject, schemaIndexOptions]); } else { toCreate.push(schemaIndexKeysObject); } } } return toCreate; } function getIndexesToDrop(schema, schemaIndexes, dbIndexes) { const toDrop = []; for (const dbIndex of dbIndexes) { let found = false; if (isDefaultIdIndex(dbIndex)) { continue; } if (isTimeseriesIndex(dbIndex, schema.options)) { continue; } for (const [schemaIndexKeysObject, schemaIndexOptions] of schemaIndexes) { const options = decorateDiscriminatorIndexOptions(schema, clone(schemaIndexOptions)); applySchemaCollation(schemaIndexKeysObject, options, schema.options); if (isIndexEqual(schemaIndexKeysObject, options, dbIndex)) { found = true; break; } } if (found) { continue; } toDrop.push(dbIndex.name); } return toDrop; } Model.cleanIndexes = async function cleanIndexes(options) { _checkContext(this, "cleanIndexes"); if (typeof arguments[0] === "function" || typeof arguments[1] === "function") { throw new MongooseError("Model.cleanIndexes() no longer accepts a callback"); } const model = this; if (Array.isArray(options && options.toDrop)) { const res2 = await _dropIndexes(options.toDrop, model, options); return res2; } const res = await model.diffIndexes(); return await _dropIndexes(res.toDrop, model, options); }; async function _dropIndexes(toDrop, model, options) { if (toDrop.length === 0) { return []; } const collection = model.$__collection; if (options && options.hideIndexes) { await Promise.all(toDrop.map((indexName) => { return model.db.db.command({ collMod: collection.collectionName, index: { name: indexName, hidden: true } }); })); } else { await Promise.all(toDrop.map((indexName) => collection.dropIndex(indexName))); } return toDrop; } Model.listIndexes = async function listIndexes() { _checkContext(this, "listIndexes"); if (typeof arguments[0] === "function") { throw new MongooseError("Model.listIndexes() no longer accepts a callback"); } if (this.$__collection.buffer) { await new Promise((resolve) => { this.$__collection.addQueue(resolve); }); } return this.$__collection.listIndexes().toArray(); }; Model.ensureIndexes = async function ensureIndexes(options) { _checkContext(this, "ensureIndexes"); if (typeof arguments[0] === "function" || typeof arguments[1] === "function") { throw new MongooseError("Model.ensureIndexes() no longer accepts a callback"); } await new Promise((resolve, reject) => { _ensureIndexes(this, options, (err) => { if (err != null) { return reject(err); } resolve(); }); }); }; Model.createIndexes = async function createIndexes(options) { _checkContext(this, "createIndexes"); if (typeof arguments[0] === "function" || typeof arguments[1] === "function") { throw new MongooseError("Model.createIndexes() no longer accepts a callback"); } return this.ensureIndexes(options); }; function _ensureIndexes(model, options, callback) { const indexes = Array.isArray(options?.toCreate) ? options.toCreate : model.schema.indexes(); let indexError; options = options || {}; const done = function(err) { if (err && !model.$caught) { model.emit("error", err); } model.emit("index", err || indexError); callback && callback(err || indexError); }; for (const index of indexes) { if (isDefaultIdIndex(index)) { utils.warn('mongoose: Cannot specify a custom index on `_id` for model name "' + model.modelName + '", MongoDB does not allow overwriting the default `_id` index. See https://bit.ly/mongodb-id-index'); } } if (!indexes.length) { immediate(function() { done(); }); return; } const indexSingleDone = function(err, fields, options2, name) { model.emit("index-single-done", err, fields, options2, name); }; const indexSingleStart = function(fields, options2) { model.emit("index-single-start", fields, options2); }; const baseSchema = model.schema._baseSchema; const baseSchemaIndexes = baseSchema ? baseSchema.indexes() : []; immediate(function() { if (options._automatic && !model.collection.collection) { model.collection.addQueue(create, []); } else { create(); } }); function create() { if (options._automatic) { if (model.schema.options.autoIndex === false || model.schema.options.autoIndex == null && model.db.config.autoIndex === false) { return done(); } } const index = indexes.shift(); if (!index) { return done(); } if (options._automatic && index[1]._autoIndex === false) { return create(); } if (baseSchemaIndexes.find((i) => utils.deepEqual(i, index))) { return create(); } const indexFields = clone(index[0]); const indexOptions = clone(index[1]); delete indexOptions._autoIndex; decorateDiscriminatorIndexOptions(model.schema, indexOptions); applyWriteConcern(model.schema, indexOptions); applySchemaCollation(indexFields, indexOptions, model.schema.options); indexSingleStart(indexFields, options); if ("background" in options) { indexOptions.background = options.background; } let promise = null; try { promise = model.collection.createIndex(indexFields, indexOptions); } catch (err) { if (!indexError) { indexError = err; } if (!model.$caught) { model.emit("error", err); } indexSingleDone(err, indexFields, indexOptions); create(); return; } promise.then( (name) => { indexSingleDone(null, indexFields, indexOptions, name); create(); }, (err) => { if (!indexError) { indexError = err; } if (!model.$caught) { model.emit("error", err); } indexSingleDone(err, indexFields, indexOptions); create(); } ); } } Model.createSearchIndexes = async function createSearchIndexes() { _checkContext(this, "createSearchIndexes"); const results = []; for (const searchIndex of this.schema._searchIndexes) { results.push(await this.createSearchIndex(searchIndex)); } return results; }; Model.schema; Model.db; Model.collection; Model.$__collection; Model.base; Model.discriminators; Model.translateAliases = function translateAliases(fields, errorOnDuplicates) { _checkContext(this, "translateAliases"); const translate = (key, value) => { let alias; const translated = []; const fieldKeys = key.split("."); let currentSchema = this.schema; for (const i in fieldKeys) { const name = fieldKeys[i]; if (currentSchema && currentSchema.aliases[name]) { alias = currentSchema.aliases[name]; if (errorOnDuplicates && alias in fields) { throw new MongooseError(`Provided object has both field "${name}" and its alias "${alias}"`); } translated.push(alias); } else { alias = name; translated.push(name); } if (currentSchema && currentSchema.paths[alias]) { currentSchema = currentSchema.paths[alias].schema; } else currentSchema = null; } const translatedKey = translated.join("."); if (fields instanceof Map) fields.set(translatedKey, value); else fields[translatedKey] = value; if (translatedKey !== key) { if (fields instanceof Map) { fields.delete(key); } else { delete fields[key]; } } return fields; }; if (typeof fields === "object") { if (fields instanceof Map) { for (const field of new Map(fields)) { fields = translate(field[0], field[1]); } } else { for (const key of Object.keys(fields)) { fields = translate(key, fields[key]); if (key[0] === "$") { if (Array.isArray(fields[key])) { for (const i in fields[key]) { fields[key][i] = this.translateAliases(fields[key][i]); } } else { this.translateAliases(fields[key]); } } } } return fields; } else { return fields; } }; Model.deleteOne = function deleteOne(conditions, options) { _checkContext(this, "deleteOne"); if (typeof arguments[0] === "function" || typeof arguments[1] === "function" || typeof arguments[2] === "function") { throw new MongooseError("Model.prototype.deleteOne() no longer accepts a callback"); } const mq = new this.Query({}, {}, this, this.$__collection); mq.setOptions(options); return mq.deleteOne(conditions); }; Model.deleteMany = function deleteMany(conditions, options) { _checkContext(this, "deleteMany"); if (typeof arguments[0] === "function" || typeof arguments[1] === "function" || typeof arguments[2] === "function") { throw new MongooseError("Model.deleteMany() no longer accepts a callback"); } const mq = new this.Query({}, {}, this, this.$__collection); mq.setOptions(options); return mq.deleteMany(conditions); }; Model.find = function find(conditions, projection, options) { _checkContext(this, "find"); if (typeof arguments[0] === "function" || typeof arguments[1] === "function" || typeof arguments[2] === "function" || typeof arguments[3] === "function") { throw new MongooseError("Model.find() no longer accepts a callback"); } const mq = new this.Query({}, {}, this, this.$__collection); mq.select(projection); mq.setOptions(options); return mq.find(conditions); }; Model.findById = function findById(id, projection, options) { _checkContext(this, "findById"); if (typeof arguments[0] === "function" || typeof arguments[1] === "function" || typeof arguments[2] === "function") { throw new MongooseError("Model.findById() no longer accepts a callback"); } return this.findOne({ _id: id }, projection, options); }; Model.findOne = function findOne(conditions, projection, options) { _checkContext(this, "findOne"); if (typeof arguments[0] === "function" || typeof arguments[1] === "function" || typeof arguments[2] === "function") { throw new MongooseError("Model.findOne() no longer accepts a callback"); } const mq = new this.Query({}, {}, this, this.$__collection); mq.select(projection); mq.setOptions(options); return mq.findOne(conditions); }; Model.estimatedDocumentCount = function estimatedDocumentCount(options) { _checkContext(this, "estimatedDocumentCount"); const mq = new this.Query({}, {}, this, this.$__collection); return mq.estimatedDocumentCount(options); }; Model.countDocuments = function countDocuments(conditions, options) { _checkContext(this, "countDocuments"); if (typeof arguments[0] === "function" || typeof arguments[1] === "function" || typeof arguments[2] === "function") { throw new MongooseError("Model.countDocuments() no longer accepts a callback"); } const mq = new this.Query({}, {}, this, this.$__collection); if (options != null) { mq.setOptions(options); } return mq.countDocuments(conditions); }; Model.distinct = function distinct(field, conditions, options) { _checkContext(this, "distinct"); if (typeof arguments[0] === "function" || typeof arguments[1] === "function" || typeof arguments[2] === "function") { throw new MongooseError("Model.distinct() no longer accepts a callback"); } const mq = new this.Query({}, {}, this, this.$__collection); if (options != null) { mq.setOptions(options); } return mq.distinct(field, conditions); }; Model.where = function where(path, val) { _checkContext(this, "where"); void val; const mq = new this.Query({}, {}, this, this.$__collection).find({}); return mq.where.apply(mq, arguments); }; Model.$where = function $where() { _checkContext(this, "$where"); const mq = new this.Query({}, {}, this, this.$__collection).find({}); return mq.$where.apply(mq, arguments); }; Model.findOneAndUpdate = function(conditions, update, options) { _checkContext(this, "findOneAndUpdate"); if (typeof arguments[0] === "function" || typeof arguments[1] === "function" || typeof arguments[2] === "function" || typeof arguments[3] === "function") { throw new MongooseError("Model.findOneAndUpdate() no longer accepts a callback"); } let fields; if (options) { fields = options.fields || options.projection; } update = clone(update, { depopulate: true, _isNested: true }); decorateUpdateWithVersionKey(update, options, this.schema.options.versionKey); const mq = new this.Query({}, {}, this, this.$__collection); mq.select(fields); return mq.findOneAndUpdate(conditions, update, options); }; Model.findByIdAndUpdate = function(id, update, options) { _checkContext(this, "findByIdAndUpdate"); if (typeof arguments[0] === "function" || typeof arguments[1] === "function" || typeof arguments[2] === "function" || typeof arguments[3] === "function") { throw new MongooseError("Model.findByIdAndUpdate() no longer accepts a callback"); } if (id instanceof Document) { id = id._doc._id; } return this.findOneAndUpdate.call(this, { _id: id }, update, options); }; Model.findOneAndDelete = function(conditions, options) { _checkContext(this, "findOneAndDelete"); if (typeof arguments[0] === "function" || typeof arguments[1] === "function" || typeof arguments[2] === "function") { throw new MongooseError("Model.findOneAndDelete() no longer accepts a callback"); } let fields; if (options) { fields = options.select; options.select = void 0; } const mq = new this.Query({}, {}, this, this.$__collection); mq.select(fields); return mq.findOneAndDelete(conditions, options); }; Model.findByIdAndDelete = function(id, options) { _checkContext(this, "findByIdAndDelete"); if (typeof arguments[0] === "function" || typeof arguments[1] === "function" || typeof arguments[2] === "function") { throw new MongooseError("Model.findByIdAndDelete() no longer accepts a callback"); } return this.findOneAndDelete({ _id: id }, options); }; Model.findOneAndReplace = function(filter, replacement, options) { _checkContext(this, "findOneAndReplace"); if (typeof arguments[0] === "function" || typeof arguments[1] === "function" || typeof arguments[2] === "function" || typeof arguments[3] === "function") { throw new MongooseError("Model.findOneAndReplace() no longer accepts a callback"); } let fields; if (options) { fields = options.select; options.select = void 0; } const mq = new this.Query({}, {}, this, this.$__collection); mq.select(fields); return mq.findOneAndReplace(filter, replacement, options); }; Model.create = async function create(doc, options) { if (typeof options === "function" || typeof arguments[2] === "function") { throw new MongooseError("Model.create() no longer accepts a callback"); } _checkContext(this, "create"); let args; const discriminatorKey = this.schema.options.discriminatorKey; if (Array.isArray(doc)) { args = doc; options = options != null && typeof options === "object" ? options : {}; } else { const last = arguments[arguments.length - 1]; options = {}; const hasCallback = typeof last === "function" || typeof options === "function" || typeof arguments[2] === "function"; if (hasCallback) { throw new MongooseError("Model.create() no longer accepts a callback"); } else { args = [...arguments]; if (args.length > 1 && !last) { args.pop(); } } if (args.length === 2 && args[0] != null && args[1] != null && args[0].session == null && last && getConstructorName(last.session) === "ClientSession" && !this.schema.path("session")) { utils.warn("WARNING: to pass a `session` to `Model.create()` in Mongoose, you **must** pass an array as the first argument. See: https://mongoosejs.com/docs/api/model.html#Model.create()"); } } if (args.length === 0) { return Array.isArray(doc) ? [] : null; } let res = []; const immediateError = typeof options.aggregateErrors === "boolean" ? !options.aggregateErrors : true; delete options.aggregateErrors; if (options.session && !options.ordered && args.length > 1) { throw new MongooseError("Cannot call `create()` with a session and multiple documents unless `ordered: true` is set"); } if (options.ordered) { for (let i = 0; i < args.length; i++) { try { const doc2 = args[i]; const Model2 = this.discriminators && doc2[discriminatorKey] != null ? this.discriminators[doc2[discriminatorKey]] || getDiscriminatorByValue(this.discriminators, doc2[discriminatorKey]) : this; if (Model2 == null) { throw new MongooseError(`Discriminator "${doc2[discriminatorKey]}" not found for model "${this.modelName}"`); } let toSave = doc2; if (!(toSave instanceof Model2)) { toSave = new Model2(toSave); } await toSave.$save(options); res.push(toSave); } catch (err) { if (!immediateError) { res.push(err); } else { throw err; } } } return res; } else if (!immediateError) { res = await Promise.allSettled(args.map(async (doc2) => { const Model2 = this.discriminators && doc2[discriminatorKey] != null ? this.discriminators[doc2[discriminatorKey]] || getDiscriminatorByValue(this.discriminators, doc2[discriminatorKey]) : this; if (Model2 == null) { throw new MongooseError(`Discriminator "${doc2[discriminatorKey]}" not found for model "${this.modelName}"`); } let toSave = doc2; if (!(toSave instanceof Model2)) { toSave = new Model2(toSave); } await toSave.$save(options); return toSave; })); res = res.map((result) => result.status === "fulfilled" ? result.value : result.reason); } else { let firstError = null; res = await Promise.all(args.map(async (doc2) => { const Model2 = this.discriminators && doc2[discriminatorKey] != null ? this.discriminators[doc2[discriminatorKey]] || getDiscriminatorByValue(this.discriminators, doc2[discriminatorKey]) : this; if (Model2 == null) { throw new MongooseError(`Discriminator "${doc2[discriminatorKey]}" not found for model "${this.modelName}"`); } try { let toSave = doc2; if (!(toSave instanceof Model2)) { toSave = new Model2(toSave); } await toSave.$save(options); return toSave; } catch (err) { if (!firstError) { firstError = err; } } })); if (firstError) { throw firstError; } } if (!Array.isArray(doc) && args.length === 1) { return res[0]; } return res; }; Model.insertOne = async function insertOne(doc, options) { _checkContext(this, "insertOne"); const discriminatorKey = this.schema.options.discriminatorKey; const Model2 = this.discriminators && doc[discriminatorKey] != null ? this.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) : this; if (Model2 == null) { throw new MongooseError( `Discriminator "${doc[discriminatorKey]}" not found for model "${this.modelName}"` ); } if (!(doc instanceof Model2)) { doc = new Model2(doc); } return await doc.$save(options); }; Model.watch = function(pipeline, options) { _checkContext(this, "watch"); const changeStreamThunk = (cb) => { pipeline = pipeline || []; prepareDiscriminatorPipeline(pipeline, this.schema, "fullDocument"); if (this.$__collection.buffer) { this.$__collection.addQueue(() => { if (this.closed) { return; } const driverChangeStream = this.$__collection.watch(pipeline, options); cb(null, driverChangeStream); }); } else { const driverChangeStream = this.$__collection.watch(pipeline, options); cb(null, driverChangeStream); } }; options = options || {}; options.model = this; return new ChangeStream(changeStreamThunk, pipeline, options); }; Model.startSession = function() { _checkContext(this, "startSession"); return this.db.startSession.apply(this.db, arguments); }; Model.insertMany = async function insertMany(arr, options) { _checkContext(this, "insertMany"); if (typeof options === "function" || typeof arguments[2] === "function") { throw new MongooseError("Model.insertMany() no longer accepts a callback"); } return new Promise((resolve, reject) => { this.$__insertMany(arr, options, (err, res) => { if (err != null) { return reject(err); } resolve(res); }); }); }; Model.$__insertMany = function(arr, options, callback) { const _this = this; if (typeof options === "function") { callback = options; options = null; } callback = callback || utils.noop; options = options || {}; const limit = options.limit || 1e3; const rawResult = !!options.rawResult; const ordered = typeof options.ordered === "boolean" ? options.ordered : true; const throwOnValidationError = typeof options.throwOnValidationError === "boolean" ? options.throwOnValidationError : false; const lean = !!options.lean; const asyncLocalStorage = this.db.base.transactionAsyncLocalStorage?.getStore(); if ((!options || !options.hasOwnProperty("session")) && asyncLocalStorage?.session != null) { options = { ...options, session: asyncLocalStorage.session }; } if (!Array.isArray(arr)) { arr = [arr]; } const validationErrors = []; const validationErrorsToOriginalOrder = /* @__PURE__ */ new Map(); const results = ordered ? null : new Array(arr.length); const toExecute = arr.map((doc, index) => (callback2) => { if (lean) { return immediate(() => callback2(null, doc)); } let createdNewDoc = false; if (!(doc instanceof _this)) { if (doc != null && typeof doc !== "object") { return callback2(new ObjectParameterError(doc, "arr." + index, "insertMany")); } try { doc = new _this(doc); createdNewDoc = true; } catch (err) { return callback2(err); } } if (options.session != null) { doc.$session(options.session); } if (lean) { return immediate(() => callback2(null, doc)); } doc.$validate(createdNewDoc ? { _skipParallelValidateCheck: true } : null).then( () => { callback2(null, doc); }, (error) => { if (ordered === false) { validationErrors.push(error); validationErrorsToOriginalOrder.set(error, index); results[index] = error; return callback2(null, null); } callback2(error); } ); }); parallelLimit(toExecute, limit, function(error, docs) { if (error) { callback(error, null); return; } const originalDocIndex = /* @__PURE__ */ new Map(); const validDocIndexToOriginalIndex = /* @__PURE__ */ new Map(); for (let i = 0; i < docs.length; ++i) { originalDocIndex.set(docs[i], i); } const docAttributes = docs.filter(function(doc) { return doc != null; }); for (let i = 0; i < docAttributes.length; ++i) { validDocIndexToOriginalIndex.set(i, originalDocIndex.get(docAttributes[i])); } if (validationErrors.length > 0) { validationErrors.sort((err1, err2) => { return validationErrorsToOriginalOrder.get(err1) - validationErrorsToOriginalOrder.get(err2); }); } if (docAttributes.length === 0) { if (throwOnValidationError) { return callback(new MongooseBulkWriteError( validationErrors, results, null, "insertMany" )); } if (rawResult) { const res = { acknowledged: true, insertedCount: 0, insertedIds: {} }; decorateBulkWriteResult(res, validationErrors, validationErrors); return callback(null, res); } callback(null, []); return; } const docObjects = lean ? docAttributes : docAttributes.map(function(doc) { if (doc.$__schema.options.versionKey) { doc[doc.$__schema.options.versionKey] = 0; } const shouldSetTimestamps = (!options || options.timestamps !== false) && doc.initializeTimestamps && (!doc.$__ || doc.$__.timestamps !== false); if (shouldSetTimestamps) { doc.initializeTimestamps(); } if (doc.$__hasOnlyPrimitiveValues()) { return doc.$__toObjectShallow(); } return doc.toObject(internalToObjectOptions); }); _this.$__collection.insertMany(docObjects, options).then( (res) => { if (!lean) { for (const attribute of docAttributes) { attribute.$__reset(); _setIsNew(attribute, false); } } if (ordered === false && throwOnValidationError && validationErrors.length > 0) { for (let i = 0; i < results.length; ++i) { if (results[i] === void 0) { results[i] = docs[i]; } } return callback(new MongooseBulkWriteError( validationErrors, results, res, "insertMany" )); } if (rawResult) { if (ordered === false) { for (let i = 0; i < results.length; ++i) { if (results[i] === void 0) { results[i] = docs[i]; } } decorateBulkWriteResult(res, validationErrors, results); } return callback(null, res); } if (options.populate != null) { return _this.populate(docAttributes, options.populate).then( (docs2) => { callback(null, docs2); }, (err) => { if (err != null) { err.insertedDocs = docAttributes; } throw err; } ); } callback(null, docAttributes); }, (error2) => { if (error2.writeErrors == null && (error2.result && error2.result.result && error2.result.result.writeErrors) != null) { error2.writeErrors = error2.result.result.writeErrors; } const hasWriteErrors = error2 && error2.writeErrors; const erroredIndexes = new Set((error2 && error2.writeErrors || []).map((err) => err.index)); if (error2.writeErrors != null) { for (let i = 0; i < error2.writeErrors.length; ++i) { const originalIndex = validDocIndexToOriginalIndex.get(error2.writeErrors[i].index); error2.writeErrors[i] = { ...error2.writeErrors[i], index: originalIndex }; if (!ordered) { results[originalIndex] = error2.writeErrors[i]; } } } if (!ordered) { for (let i = 0; i < results.length; ++i) { if (results[i] === void 0) { results[i] = docs[i]; } } error2.results = results; } let firstErroredIndex = -1; error2.insertedDocs = docAttributes.filter((doc, i) => { const isErrored = !hasWriteErrors || erroredIndexes.has(i); if (ordered) { if (firstErroredIndex > -1) { return i < firstErroredIndex; } if (isErrored) { firstErroredIndex = i; } } return !isErrored; }).map(function setIsNewForInsertedDoc(doc) { if (lean) { return doc; } doc.$__reset(); _setIsNew(doc, false); return doc; }); if (rawResult && ordered === false) { decorateBulkWriteResult(error2, validationErrors, results); } callback(error2, null); } ); }); }; function _setIsNew(doc, val) { doc.$isNew = val; doc.$emit("isNew", val); doc.constructor.emit("isNew", val); const subdocs = doc.$getAllSubdocs({ useCache: true }); for (const subdoc of subdocs) { subdoc.$isNew = val; subdoc.$emit("isNew", val); } } Model.bulkWrite = async function bulkWrite(ops, options) { _checkContext(this, "bulkWrite"); if (typeof options === "function" || typeof arguments[2] === "function") { throw new MongooseError("Model.bulkWrite() no longer accepts a callback"); } options = options || {}; const shouldSkip = await new Promise((resolve, reject) => { this.hooks.execPre("bulkWrite", this, [ops, options], (err) => { if (err != null) { if (err instanceof Kareem.skipWrappedFunction) { return resolve(err); } return reject(err); } resolve(); }); }); if (shouldSkip) { return shouldSkip.args[0]; } const ordered = options.ordered == null ? true : options.ordered; if (ops.length === 0) { const BulkWriteResult = this.base.driver.get().BulkWriteResult; const bulkWriteResult = new BulkWriteResult(getDefaultBulkwriteResult(), false); bulkWriteResult.n = 0; decorateBulkWriteResult(bulkWriteResult, [], []); return bulkWriteResult; } const validations = options?._skipCastBulkWrite ? [] : ops.map((op) => castBulkWrite(this, op, options)); const asyncLocalStorage = this.db.base.transactionAsyncLocalStorage?.getStore(); if ((!options || !options.hasOwnProperty("session")) && asyncLocalStorage?.session != null) { options = { ...options, session: asyncLocalStorage.session }; } let res = null; if (ordered) { await new Promise((resolve, reject) => { each(validations, (fn, cb) => fn(cb), (error) => { if (error) { return reject(error); } resolve(); }); }); try { res = await this.$__collection.bulkWrite(ops, options); } catch (error) { await new Promise((resolve, reject) => { const _opts = { error }; this.hooks.execPost("bulkWrite", this, [null], _opts, (err) => { if (err != null) { return reject(err); } resolve(); }); }); } } else { let validOpIndexes = []; let validationErrors = []; const results = []; if (validations.length > 0) { validOpIndexes = await Promise.all(ops.map((op, i) => { if (i >= validations.length) { return i; } return new Promise((resolve) => { validations[i]((err) => { if (err == null) { resolve(i); } else { validationErrors.push({ index: i, error: err }); results[i] = err; } resolve(); }); }); })); validOpIndexes = validOpIndexes.filter((index) => index != null); } else { validOpIndexes = ops.map((op, i) => i); } validationErrors = validationErrors.sort((v1, v2) => v1.index - v2.index).map((v) => v.error); const validOps = validOpIndexes.sort().map((index) => ops[index]); if (validOps.length === 0) { if (options.throwOnValidationError && validationErrors.length) { throw new MongooseBulkWriteError( validationErrors, results, res, "bulkWrite" ); } const BulkWriteResult = this.base.driver.get().BulkWriteResult; const bulkWriteResult = new BulkWriteResult(getDefaultBulkwriteResult(), false); bulkWriteResult.result = getDefaultBulkwriteResult(); decorateBulkWriteResult(bulkWriteResult, validationErrors, results); return bulkWriteResult; } let error; [res, error] = await this.$__collection.bulkWrite(validOps, options).then((res2) => [res2, null]).catch((error2) => [null, error2]); const writeErrorsByIndex = {}; if (error?.writeErrors) { for (const writeError of error.writeErrors) { writeErrorsByIndex[writeError.err.index] = writeError; } } for (let i = 0; i < validOpIndexes.length; ++i) { results[validOpIndexes[i]] = writeErrorsByIndex[i] ?? null; } if (error) { if (validationErrors.length > 0) { decorateBulkWriteResult(error, validationErrors, results); } await new Promise((resolve, reject) => { const _opts = { error }; this.hooks.execPost("bulkWrite", this, [null], _opts, (err) => { if (err != null) { return reject(err); } resolve(); }); }); } if (validationErrors.length > 0) { if (options.throwOnValidationError) { throw new MongooseBulkWriteError( validationErrors, results, res, "bulkWrite" ); } else { decorateBulkWriteResult(res, validationErrors, results); } } } await new Promise((resolve, reject) => { this.hooks.execPost("bulkWrite", this, [res], (err) => { if (err != null) { return reject(err); } resolve(); }); }); return res; }; Model.bulkSave = async function bulkSave(documents, options) { options = options || {}; if (options.timestamps != null) { for (const document2 of documents) { document2.$__.saveOptions = document2.$__.saveOptions || {}; document2.$__.saveOptions.timestamps = options.timestamps; } } else { for (const document2 of documents) { if (document2.$__.timestamps != null) { document2.$__.saveOptions = document2.$__.saveOptions || {}; document2.$__.saveOptions.timestamps = document2.$__.timestamps; } } } await Promise.all(documents.map((doc) => buildPreSavePromise(doc, options))); const writeOperations = this.buildBulkWriteOperations(documents, options); const opts = { skipValidation: true, _skipCastBulkWrite: true, ...options }; const { bulkWriteResult, bulkWriteError } = await this.bulkWrite(writeOperations, opts).then( (res) => ({ bulkWriteResult: res, bulkWriteError: null }), (err) => ({ bulkWriteResult: null, bulkWriteError: err }) ); if (bulkWriteError != null && bulkWriteError.name !== "MongoBulkWriteError") { throw bulkWriteError; } const matchedCount = bulkWriteResult?.matchedCount ?? 0; const insertedCount = bulkWriteResult?.insertedCount ?? 0; if (writeOperations.length > 0 && matchedCount + insertedCount < writeOperations.length && !bulkWriteError) { throw new MongooseBulkSaveIncompleteError( this.modelName, documents, bulkWriteResult ); } const successfulDocuments = []; for (let i = 0; i < documents.length; i++) { const document2 = documents[i]; const documentError = bulkWriteError && bulkWriteError.writeErrors.find((writeError) => { const writeErrorDocumentId = writeError.err.op._id || writeError.err.op.q._id; return writeErrorDocumentId.toString() === document2._doc._id.toString(); }); if (documentError == null) { successfulDocuments.push(document2); } } await Promise.all(successfulDocuments.map((document2) => handleSuccessfulWrite(document2))); if (bulkWriteError != null) { throw bulkWriteError; } return bulkWriteResult; }; function buildPreSavePromise(document2, options) { return new Promise((resolve, reject) => { document2.schema.s.hooks.execPre("save", document2, [options], (err) => { if (err) { reject(err); return; } resolve(); }); }); } function handleSuccessfulWrite(document2) { return new Promise((resolve, reject) => { if (document2.$isNew) { _setIsNew(document2, false); } document2.$__reset(); document2.schema.s.hooks.execPost("save", document2, [document2], {}, (err) => { if (err) { reject(err); return; } resolve(); }); }); } Model.applyDefaults = function applyDefaults(doc) { if (doc == null) { return doc; } if (doc.$__ != null) { applyDefaultsHelper(doc, doc.$__.fields, doc.$__.exclude); for (const subdoc of doc.$getAllSubdocs()) { applyDefaults(subdoc, subdoc.$__.fields, subdoc.$__.exclude); } return doc; } applyDefaultsToPOJO(doc, this.schema); return doc; }; Model.applyVirtuals = function applyVirtuals(obj, virtualsToApply) { if (obj == null) { return obj; } if (obj.$__ != null) { return obj; } applyVirtualsHelper(this.schema, obj, virtualsToApply); return obj; }; Model.applyTimestamps = function applyTimestamps(obj, options) { if (obj == null) { return obj; } if (obj.$__ != null) { return obj; } applyTimestampsHelper(this.schema, obj, options); return obj; }; Model.castObject = function castObject(obj, options) { options = options || {}; const ret = {}; let schema = this.schema; const discriminatorKey = schema.options.discriminatorKey; if (schema.discriminators != null && obj != null && obj[discriminatorKey] != null) { schema = getSchemaDiscriminatorByValue(schema, obj[discriminatorKey]) || schema; } const paths = Object.keys(schema.paths); for (const path of paths) { const schemaType = schema.path(path); if (!schemaType || !schemaType.$isMongooseArray) { continue; } const val = get(obj, path); pushNestedArrayPaths(paths, val, path); } let error = null; for (const path of paths) { const schemaType = schema.path(path); if (schemaType == null) { continue; } let val = get(obj, path, void 0); if (val == null) { continue; } const pieces = path.indexOf(".") === -1 ? [path] : path.split("."); let cur = ret; for (let i = 0; i < pieces.length - 1; ++i) { if (cur[pieces[i]] == null) { cur[pieces[i]] = isNaN(pieces[i + 1]) ? {} : []; } cur = cur[pieces[i]]; } if (schemaType.$isMongooseDocumentArray) { const castNonArraysOption = schemaType.options?.castNonArrays ?? schemaType.constructor.options.castNonArrays; if (!Array.isArray(val)) { if (!castNonArraysOption) { if (!options.ignoreCastErrors) { error = error || new ValidationError(); error.addError(path, new ObjectExpectedError(path, val)); } } else { cur[pieces[pieces.length - 1]] = [ Model.castObject.call(schemaType.caster, val) ]; } continue; } } if (schemaType.$isSingleNested || schemaType.$isMongooseDocumentArrayElement) { try { val = Model.castObject.call(schemaType.caster, val); } catch (err) { if (!options.ignoreCastErrors) { error = error || new ValidationError(); error.addError(path, err); } continue; } cur[pieces[pieces.length - 1]] = val; continue; } try { val = schemaType.cast(val); cur[pieces[pieces.length - 1]] = val; } catch (err) { if (!options.ignoreCastErrors) { error = error || new ValidationError(); error.addError(path, err); } continue; } } if (error != null) { throw error; } return ret; }; Model.buildBulkWriteOperations = function buildBulkWriteOperations(documents, options) { if (!Array.isArray(documents)) { throw new Error(`bulkSave expects an array of documents to be passed, received \`${documents}\` instead`); } setDefaultOptions(); const writeOperations = documents.map((document2, i) => { if (!options.skipValidation) { if (!(document2 instanceof Document)) { throw new Error(`documents.${i} was not a mongoose document, documents must be an array of mongoose documents (instanceof mongoose.Document).`); } if (options.validateBeforeSave == null || options.validateBeforeSave) { const err = document2.validateSync(); if (err != null) { throw err; } } } const isANewDocument = document2.isNew; if (isANewDocument) { const writeOperation = { insertOne: { document: document2 } }; utils.injectTimestampsOption(writeOperation.insertOne, options.timestamps); return writeOperation; } const delta = document2.$__delta(); const isDocumentWithChanges = delta != null && !utils.isEmptyObject(delta[0]); if (isDocumentWithChanges) { const where = document2.$__where(delta[0]); const changes = delta[1]; _applyCustomWhere(document2, where); const shardKey = this.schema.options.shardKey; if (shardKey) { const paths = Object.keys(shardKey); const len = paths.length; for (let i2 = 0; i2 < len; ++i2) { where[paths[i2]] = document2[paths[i2]]; } } document2.$__version(where, delta); const writeOperation = { updateOne: { filter: where, update: changes } }; utils.injectTimestampsOption(writeOperation.updateOne, options.timestamps); return writeOperation; } return null; }).filter((op) => op !== null); return writeOperations; function setDefaultOptions() { options = options || {}; if (options.skipValidation == null) { options.skipValidation = false; } } }; Model.hydrate = function(obj, projection, options) { _checkContext(this, "hydrate"); if (projection != null) { if (obj != null && obj.$__ != null) { obj = obj.toObject(internalToObjectOptions); } obj = applyProjection(obj, projection); } const document2 = require_queryHelpers().createModel(this, obj, projection); document2.$init(obj, options); return document2; }; Model.updateMany = function updateMany(conditions, update, options) { _checkContext(this, "updateMany"); if (update == null) { throw new MongooseError("updateMany `update` parameter cannot be nullish"); } return _update(this, "updateMany", conditions, update, options); }; Model.updateOne = function updateOne(conditions, doc, options) { _checkContext(this, "updateOne"); return _update(this, "updateOne", conditions, doc, options); }; Model.replaceOne = function replaceOne(conditions, doc, options) { _checkContext(this, "replaceOne"); const versionKey = this && this.schema && this.schema.options && this.schema.options.versionKey || null; if (versionKey && !doc[versionKey]) { doc[versionKey] = 0; } return _update(this, "replaceOne", conditions, doc, options); }; function _update(model, op, conditions, doc, options) { const mq = new model.Query({}, {}, model, model.collection); if (conditions instanceof Document) { conditions = conditions.toObject(); } else { conditions = clone(conditions); } options = typeof options === "function" ? options : clone(options); const versionKey = model && model.schema && model.schema.options && model.schema.options.versionKey || null; decorateUpdateWithVersionKey(doc, options, versionKey); return mq[op](conditions, doc, options); } Model.aggregate = function aggregate(pipeline, options) { _checkContext(this, "aggregate"); if (typeof options === "function" || typeof arguments[2] === "function") { throw new MongooseError("Model.aggregate() no longer accepts a callback"); } const aggregate2 = new Aggregate(pipeline || []); aggregate2.model(this); if (options != null) { aggregate2.option(options); } return aggregate2; }; Model.validate = async function validate(obj, pathsOrOptions, context) { if (arguments.length < 3 || arguments.length === 3 && typeof arguments[2] === "function") { context = obj; } if (typeof context === "function" || typeof arguments[3] === "function") { throw new MongooseError("Model.validate() no longer accepts a callback"); } let schema = this.schema; const discriminatorKey = schema.options.discriminatorKey; if (schema.discriminators != null && obj != null && obj[discriminatorKey] != null) { schema = getSchemaDiscriminatorByValue(schema, obj[discriminatorKey]) || schema; } let paths = Object.keys(schema.paths); if (pathsOrOptions != null) { const _pathsToValidate = typeof pathsOrOptions === "string" ? new Set(pathsOrOptions.split(" ")) : Array.isArray(pathsOrOptions) ? new Set(pathsOrOptions) : new Set(paths); paths = paths.filter((p) => { if (pathsOrOptions.pathsToSkip) { if (Array.isArray(pathsOrOptions.pathsToSkip)) { if (pathsOrOptions.pathsToSkip.find((x) => x == p)) { return false; } } else if (typeof pathsOrOptions.pathsToSkip == "string") { if (pathsOrOptions.pathsToSkip.includes(p)) { return false; } } } const pieces = p.split("."); let cur = pieces[0]; for (const piece of pieces) { if (_pathsToValidate.has(cur)) { return true; } cur += "." + piece; } return _pathsToValidate.has(p); }); } for (const path of paths) { const schemaType = schema.path(path); if (!schemaType || !schemaType.$isMongooseArray || schemaType.$isMongooseDocumentArray) { continue; } const val = get(obj, path); pushNestedArrayPaths(paths, val, path); } let error = null; paths = new Set(paths); try { obj = this.castObject(obj); } catch (err) { error = err; for (const key of Object.keys(error.errors || {})) { paths.delete(key); } } let remaining = paths.size; return new Promise((resolve, reject) => { if (remaining === 0) { return settle(); } for (const path of paths) { const schemaType = schema.path(path); if (schemaType == null) { _checkDone(); continue; } const pieces = path.indexOf(".") === -1 ? [path] : path.split("."); let cur = obj; for (let i = 0; i < pieces.length - 1; ++i) { cur = cur[pieces[i]]; } const val = get(obj, path, void 0); schemaType.doValidate(val, (err) => { if (err) { error = error || new ValidationError(); error.addError(path, err); } _checkDone(); }, context, { path }); } function settle() { if (error) { reject(error); } else { resolve(obj); } } function _checkDone() { if (--remaining <= 0) { return settle(); } } }); }; Model.populate = async function populate(docs, paths) { _checkContext(this, "populate"); if (typeof paths === "function" || typeof arguments[2] === "function") { throw new MongooseError("Model.populate() no longer accepts a callback"); } paths = utils.populate(paths); if (paths.length === 0) { return docs; } if (paths.find((p) => p.ordered)) { for (const path of paths) { await _populatePath(this, docs, path); } } else { const promises = []; for (const path of paths) { promises.push(_populatePath(this, docs, path)); } await Promise.all(promises); } return docs; }; var excludeIdReg = /\s?-_id\s?/; var excludeIdRegGlobal = /\s?-_id\s?/g; async function _populatePath(model, docs, populateOptions) { if (populateOptions.strictPopulate == null) { if (populateOptions._localModel != null && populateOptions._localModel.schema._userProvidedOptions.strictPopulate != null) { populateOptions.strictPopulate = populateOptions._localModel.schema._userProvidedOptions.strictPopulate; } else if (populateOptions._localModel != null && model.base.options.strictPopulate != null) { populateOptions.strictPopulate = model.base.options.strictPopulate; } else if (model.base.options.strictPopulate != null) { populateOptions.strictPopulate = model.base.options.strictPopulate; } } if (!Array.isArray(docs)) { docs = [docs]; } if (docs.length === 0 || docs.every(utils.isNullOrUndefined)) { return; } const modelsMap = getModelsMapForPopulate(model, docs, populateOptions); if (modelsMap instanceof MongooseError) { throw modelsMap; } const len = modelsMap.length; let vals = []; function flatten(item) { return void 0 !== item; } let hasOne = false; const params = []; for (let i = 0; i < len; ++i) { const mod = modelsMap[i]; let select = mod.options.select; let ids = utils.array.flatten(mod.ids, flatten); ids = utils.array.unique(ids); const assignmentOpts = {}; assignmentOpts.sort = mod && mod.options && mod.options.options && mod.options.options.sort || void 0; assignmentOpts.excludeId = excludeIdReg.test(select) || select && select._id === 0; if (mod.options && mod.options.options && mod.options.options.lean && mod.options.options.lean.transform) { mod.options.options._leanTransform = mod.options.options.lean.transform; mod.options.options.lean = true; } if (ids.length === 0 || ids.every(utils.isNullOrUndefined)) { _assign(model, [], mod, assignmentOpts); continue; } hasOne = true; if (typeof populateOptions.foreignField === "string") { mod.foreignField.clear(); mod.foreignField.add(populateOptions.foreignField); } const match = createPopulateQueryFilter(ids, mod.match, mod.foreignField, mod.model, mod.options.skipInvalidIds); if (assignmentOpts.excludeId) { if (typeof select === "string") { select = select.replace(excludeIdRegGlobal, " "); } else if (Array.isArray(select)) { select = select.filter((field) => field !== "-_id"); } else { select = { ...select }; delete select._id; } } if (mod.options.options && mod.options.options.limit != null) { assignmentOpts.originalLimit = mod.options.options.limit; } else if (mod.options.limit != null) { assignmentOpts.originalLimit = mod.options.limit; } params.push([mod, match, select, assignmentOpts]); } if (!hasOne) { if (modelsMap.length !== 0) { return; } if (populateOptions.populate != null) { const opts = utils.populate(populateOptions.populate).map((pop) => Object.assign({}, pop, { path: populateOptions.path + "." + pop.path })); return model.populate(docs, opts); } return; } if (populateOptions.ordered) { for (const arr of params) { await _execPopulateQuery.apply(null, arr).then((valsFromDb) => { vals = vals.concat(valsFromDb); }); } } else { const promises = []; for (const arr of params) { promises.push(_execPopulateQuery.apply(null, arr).then((valsFromDb) => { vals = vals.concat(valsFromDb); })); } await Promise.all(promises); } for (const arr of params) { const mod = arr[0]; const assignmentOpts = arr[3]; for (const val of vals) { mod.options._childDocs.push(val); } _assign(model, vals, mod, assignmentOpts); } for (const arr of params) { removeDeselectedForeignField(arr[0].foreignField, arr[0].options, vals); } for (const arr of params) { const mod = arr[0]; if (mod.options && mod.options.options && mod.options.options._leanTransform) { for (const doc of vals) { mod.options.options._leanTransform(doc); } } } } function _execPopulateQuery(mod, match, select) { let subPopulate = clone(mod.options.populate); const queryOptions = Object.assign({ skip: mod.options.skip, limit: mod.options.limit, perDocumentLimit: mod.options.perDocumentLimit }, mod.options.options); if (mod.count) { delete queryOptions.skip; } if (queryOptions.perDocumentLimit != null) { queryOptions.limit = queryOptions.perDocumentLimit; delete queryOptions.perDocumentLimit; } else if (queryOptions.limit != null) { queryOptions.limit = queryOptions.limit * mod.ids.length; } const query = mod.model.find(match, select, queryOptions); for (const foreignField of mod.foreignField) { if (foreignField !== "_id" && query.selectedInclusively() && !isPathSelectedInclusive(query._fields, foreignField)) { query.select(foreignField); } } if (mod.count) { for (const foreignField of mod.foreignField) { query.select(foreignField); } } if (subPopulate) { if (mod.model.baseModelName != null) { if (Array.isArray(subPopulate)) { subPopulate.forEach((pop) => { pop.strictPopulate = false; }); } else if (typeof subPopulate === "string") { subPopulate = { path: subPopulate, strictPopulate: false }; } else { subPopulate.strictPopulate = false; } } const basePath = mod.options._fullPath || mod.options.path; if (Array.isArray(subPopulate)) { for (const pop of subPopulate) { pop._fullPath = basePath + "." + pop.path; } } else if (typeof subPopulate === "object") { subPopulate._fullPath = basePath + "." + subPopulate.path; } query.populate(subPopulate); } return query.exec().then( (docs) => { for (const val of docs) { leanPopulateMap.set(val, mod.model); } return docs; } ); } function _assign(model, vals, mod, assignmentOpts) { const options = mod.options; const isVirtual = mod.isVirtual; const justOne = mod.justOne; let _val; const lean = options && options.options && options.options.lean || false; const len = vals.length; const rawOrder = {}; const rawDocs = {}; let key; let val; const allIds = clone(mod.allIds); for (let i = 0; i < len; i++) { val = vals[i]; if (val == null) { continue; } for (const foreignField of mod.foreignField) { _val = utils.getValue(foreignField, val); if (Array.isArray(_val)) { _val = utils.array.unique(utils.array.flatten(_val)); for (let __val of _val) { if (__val instanceof Document) { __val = __val._doc._id; } if (__val?.constructor?.name === "Binary" && __val.sub_type === 4 && typeof __val.toUUID === "function") { key = String(__val.toUUID()); } else if (__val?.constructor?.name === "Buffer" && __val._subtype === 4 && typeof __val.toUUID === "function") { key = String(__val.toUUID()); } else { key = String(__val); } if (rawDocs[key]) { if (Array.isArray(rawDocs[key])) { rawDocs[key].push(val); rawOrder[key].push(i); } else { rawDocs[key] = [rawDocs[key], val]; rawOrder[key] = [rawOrder[key], i]; } } else { if (isVirtual && !justOne) { rawDocs[key] = [val]; rawOrder[key] = [i]; } else { rawDocs[key] = val; rawOrder[key] = i; } } } } else { if (_val instanceof Document) { _val = _val._doc._id; } if (_val?.constructor?.name === "Binary" && _val.sub_type === 4 && typeof _val.toUUID === "function") { key = String(_val.toUUID()); } else if (_val?.constructor?.name === "Buffer" && _val._subtype === 4 && typeof _val.toUUID === "function") { key = String(_val.toUUID()); } else { key = String(_val); } if (rawDocs[key]) { if (Array.isArray(rawDocs[key])) { rawDocs[key].push(val); rawOrder[key].push(i); } else if (isVirtual || rawDocs[key].constructor !== val.constructor || (rawDocs[key] instanceof Document ? String(rawDocs[key]._doc._id) : String(rawDocs[key]._id)) !== (val instanceof Document ? String(val._doc._id) : String(val._id))) { rawDocs[key] = [rawDocs[key], val]; rawOrder[key] = [rawOrder[key], i]; } } else { rawDocs[key] = val; rawOrder[key] = i; } } if (!lean) { val.$__.wasPopulated = val.$__.wasPopulated || { value: _val }; } } } assignVals({ originalModel: model, // If virtual, make sure to not mutate original field rawIds: mod.isVirtual ? allIds : mod.allIds, allIds, unpopulatedValues: mod.unpopulatedValues, foreignField: mod.foreignField, rawDocs, rawOrder, docs: mod.docs, path: options.path, options: assignmentOpts, justOne: mod.justOne, isVirtual: mod.isVirtual, allOptions: mod, populatedModel: mod.model, lean, virtual: mod.virtual, count: mod.count, match: mod.match }); } Model.compile = function compile(name, schema, collectionName, connection, base) { const versioningEnabled = schema.options.versionKey !== false; if (versioningEnabled && !schema.paths[schema.options.versionKey]) { const o = {}; o[schema.options.versionKey] = Number; schema.add(o); } let model; if (typeof name === "function" && name.prototype instanceof Model) { model = name; name = model.name; schema.loadClass(model, false); model.prototype.$isMongooseModelPrototype = true; } else { model = function model2(doc, fields, skipId) { model2.hooks.execPreSync("createModel", doc); if (!(this instanceof model2)) { return new model2(doc, fields, skipId); } const discriminatorKey = model2.schema.options.discriminatorKey; if (model2.discriminators == null || doc == null || doc[discriminatorKey] == null) { Model.call(this, doc, fields, skipId); return; } const Discriminator = model2.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(model2.discriminators, doc[discriminatorKey]); if (Discriminator != null) { return new Discriminator(doc, fields, skipId); } Model.call(this, doc, fields, skipId); }; } model.hooks = schema.s.hooks.clone(); model.base = base; model.modelName = name; if (!(model.prototype instanceof Model)) { Object.setPrototypeOf(model, Model); Object.setPrototypeOf(model.prototype, Model.prototype); } model.model = function model2(name2) { return this.db.model(name2); }; model.db = connection; model.prototype.db = connection; model.prototype[modelDbSymbol] = connection; model.discriminators = model.prototype.discriminators = void 0; model[modelSymbol] = true; model.events = new EventEmitter(); schema._preCompile(); const _userProvidedOptions = schema._userProvidedOptions || {}; const collectionOptions = { schemaUserProvidedOptions: _userProvidedOptions, capped: schema.options.capped, Promise: model.base.Promise, modelName: name }; if (schema.options.autoCreate !== void 0) { collectionOptions.autoCreate = schema.options.autoCreate; } const collection = connection.collection( collectionName, collectionOptions ); model.prototype.collection = collection; model.prototype.$collection = collection; model.prototype[modelCollectionSymbol] = collection; model.prototype.$__setSchema(schema); applyMethods(model, schema); applyStatics(model, schema); applyHooks(model, schema); applyStaticHooks(model, schema.s.hooks, schema.statics); model.schema = model.prototype.$__schema; model.collection = collection; model.$__collection = collection; model.Query = function() { Query.apply(this, arguments); }; Object.setPrototypeOf(model.Query.prototype, Query.prototype); model.Query.base = Query.base; model.Query.prototype.constructor = Query; model._applyQueryMiddleware(); applyQueryMethods(model, schema.query); return model; }; Model.clientEncryption = function clientEncryption() { const ClientEncryption = this.base.driver.get().ClientEncryption; if (!ClientEncryption) { throw new Error("The mongodb driver must be used to obtain a ClientEncryption object."); } const client = this.collection?.conn?.client; if (!client) return null; const autoEncryptionOptions = client.options.autoEncryption; if (!autoEncryptionOptions) return null; const { keyVaultNamespace, keyVaultClient, kmsProviders, credentialProviders, proxyOptions, tlsOptions } = autoEncryptionOptions; return new ClientEncryption( keyVaultClient ?? client, { keyVaultNamespace, kmsProviders, credentialProviders, proxyOptions, tlsOptions } ); }; Model.$__updateConnection = function $__updateConnection(newConnection) { this.db = newConnection; this.prototype.db = newConnection; this.prototype[modelDbSymbol] = newConnection; const collection = newConnection.collection( this.collection.collectionName, this.collection.opts ); this.prototype.collection = collection; this.prototype.$collection = collection; this.prototype[modelCollectionSymbol] = collection; this.collection = collection; this.$__collection = collection; }; function applyQueryMethods(model, methods) { for (const i in methods) { model.Query.prototype[i] = methods[i]; } } Model.__subclass = function subclass(conn, schema, collection) { const _this = this; const Model2 = function Model3(doc, fields, skipId) { if (!(this instanceof Model3)) { return new Model3(doc, fields, skipId); } _this.call(this, doc, fields, skipId); }; Object.setPrototypeOf(Model2, _this); Object.setPrototypeOf(Model2.prototype, _this.prototype); Model2.db = conn; Model2.prototype.db = conn; Model2.prototype[modelDbSymbol] = conn; _this[subclassedSymbol] = _this[subclassedSymbol] || []; _this[subclassedSymbol].push(Model2); if (_this.discriminators != null) { Model2.discriminators = {}; for (const key of Object.keys(_this.discriminators)) { Model2.discriminators[key] = _this.discriminators[key].__subclass(_this.db, _this.discriminators[key].schema, collection); } } const s = schema && typeof schema !== "string" ? schema : _this.prototype.$__schema; const options = s.options || {}; const _userProvidedOptions = s._userProvidedOptions || {}; if (!collection) { collection = _this.prototype.$__schema.get("collection") || utils.toCollectionName(_this.modelName, this.base.pluralize()); } const collectionOptions = { schemaUserProvidedOptions: _userProvidedOptions, capped: s && options.capped }; Model2.prototype.collection = conn.collection(collection, collectionOptions); Model2.prototype.$collection = Model2.prototype.collection; Model2.prototype[modelCollectionSymbol] = Model2.prototype.collection; Model2.collection = Model2.prototype.collection; Model2.$__collection = Model2.collection; Model2.init().catch(() => { }); return Model2; }; Model.recompileSchema = function recompileSchema() { this.prototype.$__setSchema(this.schema); if (this.schema._applyDiscriminators != null) { for (const disc of this.schema._applyDiscriminators.keys()) { this.discriminator(disc, this.schema._applyDiscriminators.get(disc)); } } delete this.schema._defaultToObjectOptionsMap; applyEmbeddedDiscriminators(this.schema, /* @__PURE__ */ new WeakSet(), true); }; Model.inspect = function() { return `Model { ${this.modelName} }`; }; Model.namespace = function namespace() { return this.db.name + "." + this.collection.collectionName; }; if (util.inspect.custom) { Model[util.inspect.custom] = Model.inspect; } Model._applyQueryMiddleware = function _applyQueryMiddleware() { const Query2 = this.Query; const queryMiddleware = this.schema.s.hooks.filter((hook) => { const contexts = _getContexts(hook); if (hook.name === "validate") { return !!contexts.query; } if (hook.name === "deleteOne" || hook.name === "updateOne") { return !!contexts.query || Object.keys(contexts).length === 0; } if (hook.query != null || hook.document != null) { return !!hook.query; } return true; }); Query2.prototype._queryMiddleware = queryMiddleware; }; function _getContexts(hook) { const ret = {}; if (hook.hasOwnProperty("query")) { ret.query = hook.query; } if (hook.hasOwnProperty("document")) { ret.document = hook.document; } return ret; } module2.exports = exports2 = Model; } }); // netlify/functions/node_modules/mongoose/lib/helpers/pluralize.js var require_pluralize = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/pluralize.js"(exports2, module2) { "use strict"; module2.exports = pluralize; exports2.pluralization = [ [/human$/gi, "humans"], [/(m)an$/gi, "$1en"], [/(pe)rson$/gi, "$1ople"], [/(child)$/gi, "$1ren"], [/^(ox)$/gi, "$1en"], [/(ax|test)is$/gi, "$1es"], [/(octop|vir)us$/gi, "$1i"], [/(alias|status)$/gi, "$1es"], [/(bu)s$/gi, "$1ses"], [/(buffal|tomat|potat)o$/gi, "$1oes"], [/([ti])um$/gi, "$1a"], [/sis$/gi, "ses"], [/(?:([^f])fe|([lr])f)$/gi, "$1$2ves"], [/(hive)$/gi, "$1s"], [/([^aeiouy]|qu)y$/gi, "$1ies"], [/(x|ch|ss|sh)$/gi, "$1es"], [/(matr|vert|ind)ix|ex$/gi, "$1ices"], [/([m|l])ouse$/gi, "$1ice"], [/(kn|w|l)ife$/gi, "$1ives"], [/(quiz)$/gi, "$1zes"], [/^goose$/i, "geese"], [/s$/gi, "s"], [/([^a-z])$/, "$1"], [/$/gi, "s"] ]; var rules = exports2.pluralization; exports2.uncountables = [ "advice", "energy", "excretion", "digestion", "cooperation", "health", "justice", "labour", "machinery", "equipment", "information", "pollution", "sewage", "paper", "money", "species", "series", "rain", "rice", "fish", "sheep", "moose", "deer", "news", "expertise", "status", "media" ]; var uncountables = exports2.uncountables; function pluralize(str) { let found; str = str.toLowerCase(); if (!~uncountables.indexOf(str)) { found = rules.filter(function(rule) { return str.match(rule[0]); }); if (found[0]) { return str.replace(found[0][0], found[0][1]); } } return str; } } }); // netlify/functions/node_modules/mongoose/lib/error/setOptionError.js var require_setOptionError = __commonJS({ "netlify/functions/node_modules/mongoose/lib/error/setOptionError.js"(exports2, module2) { "use strict"; var MongooseError = require_mongooseError(); var util = require("util"); var combinePathErrors = require_combinePathErrors(); var SetOptionError = class _SetOptionError extends MongooseError { constructor() { super(""); this.errors = {}; } /** * Console.log helper */ toString() { return combinePathErrors(this); } /** * inspect helper * @api private */ inspect() { return Object.assign(new Error(this.message), this); } /** * add message * @param {String} key * @param {String|Error} error * @api private */ addError(key, error) { if (error instanceof _SetOptionError) { const { errors } = error; for (const optionKey of Object.keys(errors)) { this.addError(optionKey, errors[optionKey]); } return; } this.errors[key] = error; this.message = combinePathErrors(this); } }; if (util.inspect.custom) { SetOptionError.prototype[util.inspect.custom] = SetOptionError.prototype.inspect; } Object.defineProperty(SetOptionError.prototype, "toJSON", { enumerable: false, writable: false, configurable: true, value: function() { return Object.assign({}, this, { name: this.name, message: this.message }); } }); Object.defineProperty(SetOptionError.prototype, "name", { value: "SetOptionError" }); var SetOptionInnerError = class extends MongooseError { /** * Error for the "errors" array in "SetOptionError" with consistent message * @param {String} key */ constructor(key) { super(`"${key}" is not a valid option to set`); } }; SetOptionError.SetOptionInnerError = SetOptionInnerError; module2.exports = SetOptionError; } }); // netlify/functions/node_modules/mongoose/lib/helpers/printJestWarning.js var require_printJestWarning = __commonJS({ "netlify/functions/node_modules/mongoose/lib/helpers/printJestWarning.js"() { "use strict"; var utils = require_utils3(); if (typeof jest !== "undefined" && !process.env.SUPPRESS_JEST_WARNINGS) { if (typeof window !== "undefined") { utils.warn("Mongoose: looks like you're trying to test a Mongoose app with Jest's default jsdom test environment. Please make sure you read Mongoose's docs on configuring Jest to test Node.js apps: https://mongoosejs.com/docs/jest.html. Set the SUPPRESS_JEST_WARNINGS to true to hide this warning."); } if (setTimeout.clock != null && typeof setTimeout.clock.Date === "function") { utils.warn("Mongoose: looks like you're trying to test a Mongoose app with Jest's mock timers enabled. Please make sure you read Mongoose's docs on configuring Jest to test Node.js apps: https://mongoosejs.com/docs/jest.html. Set the SUPPRESS_JEST_WARNINGS to true to hide this warning."); } } } }); // netlify/functions/node_modules/mongoose/lib/browserDocument.js var require_browserDocument = __commonJS({ "netlify/functions/node_modules/mongoose/lib/browserDocument.js"(exports2, module2) { "use strict"; var NodeJSDocument = require_document2(); var EventEmitter = require("events").EventEmitter; var MongooseError = require_error2(); var Schema = require_schema2(); var ObjectId2 = require_objectid(); var ValidationError = MongooseError.ValidationError; var applyHooks = require_applyHooks(); var isObject = require_isObject(); function Document(obj, schema, fields, skipId, skipInit) { if (!(this instanceof Document)) { return new Document(obj, schema, fields, skipId, skipInit); } if (isObject(schema) && !schema.instanceOfSchema) { schema = new Schema(schema); } schema = this.schema || schema; if (!this.schema && schema.options._id) { obj = obj || {}; if (obj._id === void 0) { obj._id = new ObjectId2(); } } if (!schema) { throw new MongooseError.MissingSchemaError(); } this.$__setSchema(schema); NodeJSDocument.call(this, obj, fields, skipId, skipInit); applyHooks(this, schema, { decorateDoc: true }); for (const m in schema.methods) { this[m] = schema.methods[m]; } for (const s in schema.statics) { this[s] = schema.statics[s]; } } Document.prototype = Object.create(NodeJSDocument.prototype); Document.prototype.constructor = Document; Document.events = new EventEmitter(); Document.$emitter = new EventEmitter(); [ "on", "once", "emit", "listeners", "removeListener", "setMaxListeners", "removeAllListeners", "addListener" ].forEach(function(emitterFn) { Document[emitterFn] = function() { return Document.$emitter[emitterFn].apply(Document.$emitter, arguments); }; }); Document.ValidationError = ValidationError; module2.exports = exports2 = Document; } }); // netlify/functions/node_modules/mongoose/lib/documentProvider.js var require_documentProvider = __commonJS({ "netlify/functions/node_modules/mongoose/lib/documentProvider.js"(exports2, module2) { "use strict"; var Document = require_document2(); var BrowserDocument = require_browserDocument(); var isBrowser = false; module2.exports = function documentProvider() { if (isBrowser) { return BrowserDocument; } return Document; }; module2.exports.setBrowser = function(flag) { isBrowser = flag; }; } }); // netlify/functions/node_modules/mongoose/lib/mongoose.js var require_mongoose = __commonJS({ "netlify/functions/node_modules/mongoose/lib/mongoose.js"(exports2, module2) { "use strict"; var Document = require_document2(); var EventEmitter = require("events").EventEmitter; var Kareem = require_kareem(); var Schema = require_schema2(); var SchemaType = require_schemaType(); var SchemaTypes = require_schema(); var VirtualType = require_virtualType(); var STATES = require_connectionState(); var VALID_OPTIONS = require_validOptions(); var Types = require_types(); var Query = require_query(); var Model = require_model(); var applyPlugins = require_applyPlugins(); var builtinPlugins = require_plugins(); var driver = require_driver(); var legacyPluralize = require_pluralize(); var utils = require_utils3(); var pkg = require_package2(); var cast = require_cast2(); var Aggregate = require_aggregate2(); var trusted = require_trusted().trusted; var sanitizeFilter = require_sanitizeFilter(); var isBsonType = require_isBsonType(); var MongooseError = require_mongooseError(); var SetOptionError = require_setOptionError(); var applyEmbeddedDiscriminators = require_applyEmbeddedDiscriminators(); var defaultMongooseSymbol = Symbol.for("mongoose:default"); var defaultConnectionSymbol = Symbol("mongoose:defaultConnection"); require_printJestWarning(); var objectIdHexRegexp = /^[0-9A-Fa-f]{24}$/; var { AsyncLocalStorage } = require("async_hooks"); function Mongoose(options) { this.connections = []; this.nextConnectionId = 0; this.models = {}; this.events = new EventEmitter(); this.__driver = driver.get(); this.options = Object.assign({ pluralization: true, autoIndex: true, autoCreate: true, autoSearchIndex: false }, options); const createInitialConnection = utils.getOption("createInitialConnection", this.options) ?? true; if (createInitialConnection && this.__driver != null) { _createDefaultConnection(this); } if (this.options.pluralization) { this._pluralize = legacyPluralize; } if (!options || !options[defaultMongooseSymbol]) { const _this = this; this.Schema = function() { this.base = _this; return Schema.apply(this, arguments); }; this.Schema.prototype = Object.create(Schema.prototype); Object.assign(this.Schema, Schema); this.Schema.base = this; this.Schema.Types = Object.assign({}, Schema.Types); } else { for (const key of ["Schema", "model"]) { this[key] = Mongoose.prototype[key]; } } this.Schema.prototype.base = this; if (options?.transactionAsyncLocalStorage) { this.transactionAsyncLocalStorage = new AsyncLocalStorage(); } Object.defineProperty(this, "plugins", { configurable: false, enumerable: true, writable: false, value: Object.values(builtinPlugins).map((plugin) => [plugin, { deduplicate: true }]) }); } Mongoose.prototype.cast = cast; Mongoose.prototype.STATES = STATES; Mongoose.prototype.ConnectionStates = STATES; Mongoose.prototype.driver = driver; Mongoose.prototype.setDriver = function setDriver(driver2) { const _mongoose = this instanceof Mongoose ? this : mongoose; if (_mongoose.__driver === driver2) { return _mongoose; } const openConnection = _mongoose.connections && _mongoose.connections.find((conn) => conn.readyState !== STATES.disconnected); if (openConnection) { const msg = "Cannot modify Mongoose driver if a connection is already open. Call `mongoose.disconnect()` before modifying the driver"; throw new MongooseError(msg); } _mongoose.__driver = driver2; if (Array.isArray(driver2.plugins)) { for (const plugin of driver2.plugins) { if (typeof plugin === "function") { _mongoose.plugin(plugin); } } } if (driver2.SchemaTypes != null) { Object.assign(mongoose.Schema.Types, driver2.SchemaTypes); } const Connection = driver2.Connection; const oldDefaultConnection = _mongoose.connections[0]; _mongoose.connections = [new Connection(_mongoose)]; _mongoose.connections[0].models = _mongoose.models; if (oldDefaultConnection == null) { return _mongoose; } for (const model of Object.values(_mongoose.models)) { if (model.db !== oldDefaultConnection) { continue; } model.$__updateConnection(_mongoose.connections[0]); } return _mongoose; }; Mongoose.prototype.set = function getsetOptions(key, value) { const _mongoose = this instanceof Mongoose ? this : mongoose; if (arguments.length === 1 && typeof key !== "object") { if (VALID_OPTIONS.indexOf(key) === -1) { const error2 = new SetOptionError(); error2.addError(key, new SetOptionError.SetOptionInnerError(key)); throw error2; } return _mongoose.options[key]; } let options = {}; if (arguments.length === 2) { options = { [key]: value }; } if (arguments.length === 1 && typeof key === "object") { options = key; } let error = void 0; for (const [optionKey, optionValue] of Object.entries(options)) { if (VALID_OPTIONS.indexOf(optionKey) === -1) { if (!error) { error = new SetOptionError(); } error.addError(optionKey, new SetOptionError.SetOptionInnerError(optionKey)); continue; } _mongoose.options[optionKey] = optionValue; if (optionKey === "objectIdGetter") { if (optionValue) { Object.defineProperty(_mongoose.Types.ObjectId.prototype, "_id", { enumerable: false, configurable: true, get: function() { return this; } }); } else { delete _mongoose.Types.ObjectId.prototype._id; } } else if (optionKey === "transactionAsyncLocalStorage") { if (optionValue && !_mongoose.transactionAsyncLocalStorage) { _mongoose.transactionAsyncLocalStorage = new AsyncLocalStorage(); } else if (!optionValue && _mongoose.transactionAsyncLocalStorage) { delete _mongoose.transactionAsyncLocalStorage; } } else if (optionKey === "createInitialConnection") { if (optionValue && !_mongoose.connection) { _createDefaultConnection(_mongoose); } else if (optionValue === false && _mongoose.connection && _mongoose.connection[defaultConnectionSymbol]) { if (_mongoose.connection.readyState === STATES.disconnected && Object.keys(_mongoose.connection.models).length === 0) { _mongoose.connections.shift(); } } } } if (error) { throw error; } return _mongoose; }; Mongoose.prototype.get = Mongoose.prototype.set; Mongoose.prototype.createConnection = function createConnection(uri, options) { const _mongoose = this instanceof Mongoose ? this : mongoose; const Connection = _mongoose.__driver.Connection; const conn = new Connection(_mongoose); _mongoose.connections.push(conn); _mongoose.nextConnectionId++; _mongoose.events.emit("createConnection", conn); if (arguments.length > 0) { conn.openUri(uri, { ...options, _fireAndForget: true }); } return conn; }; Mongoose.prototype.connect = async function connect(uri, options) { if (typeof options === "function" || arguments.length >= 3 && typeof arguments[2] === "function") { throw new MongooseError("Mongoose.prototype.connect() no longer accepts a callback"); } const _mongoose = this instanceof Mongoose ? this : mongoose; if (_mongoose.connection == null) { _createDefaultConnection(_mongoose); } const conn = _mongoose.connection; return conn.openUri(uri, options).then(() => _mongoose); }; Mongoose.prototype.disconnect = async function disconnect() { if (arguments.length >= 1 && typeof arguments[0] === "function") { throw new MongooseError("Mongoose.prototype.disconnect() no longer accepts a callback"); } const _mongoose = this instanceof Mongoose ? this : mongoose; const remaining = _mongoose.connections.length; if (remaining <= 0) { return; } await Promise.all(_mongoose.connections.map((conn) => conn.close())); }; Mongoose.prototype.startSession = function startSession() { const _mongoose = this instanceof Mongoose ? this : mongoose; return _mongoose.connection.startSession.apply(_mongoose.connection, arguments); }; Mongoose.prototype.pluralize = function pluralize(fn) { const _mongoose = this instanceof Mongoose ? this : mongoose; if (arguments.length > 0) { _mongoose._pluralize = fn; } return _mongoose._pluralize; }; Mongoose.prototype.model = function model(name, schema, collection, options) { const _mongoose = this instanceof Mongoose ? this : mongoose; if (typeof schema === "string") { collection = schema; schema = false; } if (arguments.length === 1) { const model3 = _mongoose.models[name]; if (!model3) { throw new _mongoose.Error.MissingSchemaError(name); } return model3; } if (utils.isObject(schema) && !(schema instanceof Schema)) { schema = new Schema(schema); } if (schema && !(schema instanceof Schema)) { throw new _mongoose.Error("The 2nd parameter to `mongoose.model()` should be a schema or a POJO"); } options = options || {}; const originalSchema = schema; if (schema) { if (_mongoose.get("cloneSchemas")) { schema = schema.clone(); } _mongoose._applyPlugins(schema); } const overwriteModels = _mongoose.options.hasOwnProperty("overwriteModels") ? _mongoose.options.overwriteModels : options.overwriteModels; if (_mongoose.models.hasOwnProperty(name) && options.cache !== false && overwriteModels !== true) { if (originalSchema && originalSchema.instanceOfSchema && originalSchema !== _mongoose.models[name].schema) { throw new _mongoose.Error.OverwriteModelError(name); } if (collection && collection !== _mongoose.models[name].collection.name) { const model3 = _mongoose.models[name]; schema = model3.prototype.schema; const sub = model3.__subclass(_mongoose.connection, schema, collection); return sub; } return _mongoose.models[name]; } if (schema == null) { throw new _mongoose.Error.MissingSchemaError(name); } const model2 = _mongoose._model(name, schema, collection, options); _mongoose.connection.models[name] = model2; _mongoose.models[name] = model2; return model2; }; Mongoose.prototype._model = function _model(name, schema, collection, options) { const _mongoose = this instanceof Mongoose ? this : mongoose; let model; if (typeof name === "function") { model = name; name = model.name; if (!(model.prototype instanceof Model)) { throw new _mongoose.Error("The provided class " + name + " must extend Model"); } } if (schema) { if (_mongoose.get("cloneSchemas")) { schema = schema.clone(); } _mongoose._applyPlugins(schema); } if (schema == null || !("pluralization" in schema.options)) { schema.options.pluralization = _mongoose.options.pluralization; } if (!collection) { collection = schema.get("collection") || utils.toCollectionName(name, _mongoose.pluralize()); } applyEmbeddedDiscriminators(schema); const connection = options.connection || _mongoose.connection; model = _mongoose.Model.compile(model || name, schema, collection, connection, _mongoose); model.init().catch(function $modelInitNoop() { }); connection.emit("model", model); if (schema._applyDiscriminators != null) { for (const disc of schema._applyDiscriminators.keys()) { const { schema: discriminatorSchema, options: options2 } = schema._applyDiscriminators.get(disc); model.discriminator(disc, discriminatorSchema, options2); } } return model; }; Mongoose.prototype.deleteModel = function deleteModel(name) { const _mongoose = this instanceof Mongoose ? this : mongoose; _mongoose.connection.deleteModel(name); delete _mongoose.models[name]; return _mongoose; }; Mongoose.prototype.modelNames = function modelNames() { const _mongoose = this instanceof Mongoose ? this : mongoose; const names = Object.keys(_mongoose.models); return names; }; Mongoose.prototype._applyPlugins = function _applyPlugins(schema, options) { const _mongoose = this instanceof Mongoose ? this : mongoose; options = options || {}; options.applyPluginsToDiscriminators = _mongoose.options && _mongoose.options.applyPluginsToDiscriminators || false; options.applyPluginsToChildSchemas = typeof (_mongoose.options && _mongoose.options.applyPluginsToChildSchemas) === "boolean" ? _mongoose.options.applyPluginsToChildSchemas : true; applyPlugins(schema, _mongoose.plugins, options, "$globalPluginsApplied"); }; Mongoose.prototype.plugin = function plugin(fn, opts) { const _mongoose = this instanceof Mongoose ? this : mongoose; _mongoose.plugins.push([fn, opts]); return _mongoose; }; Mongoose.prototype.__defineGetter__("connection", function() { return this.connections[0]; }); Mongoose.prototype.__defineSetter__("connection", function(v) { if (v instanceof this.__driver.Connection) { this.connections[0] = v; this.models = v.models; } }); Mongoose.prototype.connections; Mongoose.prototype.nextConnectionId; Mongoose.prototype.Aggregate = Aggregate; Mongoose.prototype.BaseCollection = require_collection2(); Object.defineProperty(Mongoose.prototype, "Collection", { get: function() { return this.__driver.Collection; }, set: function(Collection) { this.__driver.Collection = Collection; } }); Object.defineProperty(Mongoose.prototype, "Connection", { get: function() { return this.__driver.Connection; }, set: function(Connection) { if (Connection === this.__driver.Connection) { return; } this.__driver.Connection = Connection; } }); Mongoose.prototype.BaseConnection = require_connection2(); Mongoose.prototype.version = pkg.version; Mongoose.prototype.Mongoose = Mongoose; Mongoose.prototype.Schema = Schema; Mongoose.prototype.SchemaType = SchemaType; Mongoose.prototype.SchemaTypes = Schema.Types; Mongoose.prototype.VirtualType = VirtualType; Mongoose.prototype.Types = Types; Mongoose.prototype.Query = Query; Mongoose.prototype.Model = Model; Mongoose.prototype.Document = Document; Mongoose.prototype.DocumentProvider = require_documentProvider(); Mongoose.prototype.ObjectId = SchemaTypes.ObjectId; Mongoose.prototype.isValidObjectId = function isValidObjectId(v) { const _mongoose = this instanceof Mongoose ? this : mongoose; return _mongoose.Types.ObjectId.isValid(v); }; Mongoose.prototype.isObjectIdOrHexString = function isObjectIdOrHexString(v) { return isBsonType(v, "ObjectId") || typeof v === "string" && objectIdHexRegexp.test(v); }; Mongoose.prototype.syncIndexes = function syncIndexes(options) { const _mongoose = this instanceof Mongoose ? this : mongoose; return _mongoose.connection.syncIndexes(options); }; Mongoose.prototype.Decimal128 = SchemaTypes.Decimal128; Mongoose.prototype.Mixed = SchemaTypes.Mixed; Mongoose.prototype.Date = SchemaTypes.Date; Mongoose.prototype.Number = SchemaTypes.Number; Mongoose.prototype.Error = MongooseError; Mongoose.prototype.MongooseError = MongooseError; Mongoose.prototype.now = function now() { return /* @__PURE__ */ new Date(); }; Mongoose.prototype.CastError = MongooseError.CastError; Mongoose.prototype.SchemaTypeOptions = require_schemaTypeOptions(); Mongoose.prototype.mquery = require_mquery(); Mongoose.prototype.sanitizeFilter = sanitizeFilter; Mongoose.prototype.trusted = trusted; Mongoose.prototype.skipMiddlewareFunction = Kareem.skipWrappedFunction; Mongoose.prototype.overwriteMiddlewareResult = Kareem.overwriteResult; Mongoose.prototype.omitUndefined = require_omitUndefined(); function _createDefaultConnection(mongoose2) { if (mongoose2.connection) { return; } const conn = mongoose2.createConnection(); conn[defaultConnectionSymbol] = true; conn.models = mongoose2.models; } var mongoose = module2.exports = exports2 = new Mongoose({ [defaultMongooseSymbol]: true }); } }); // netlify/functions/node_modules/mongoose/lib/index.js var require_lib6 = __commonJS({ "netlify/functions/node_modules/mongoose/lib/index.js"(exports2, module2) { "use strict"; var mongodbDriver = require_node_mongodb_native(); require_driver().set(mongodbDriver); var mongoose = require_mongoose(); mongoose.setDriver(mongodbDriver); mongoose.Mongoose.prototype.mongo = require_lib3(); module2.exports = mongoose; } }); // netlify/functions/node_modules/mongoose/index.js var require_mongoose2 = __commonJS({ "netlify/functions/node_modules/mongoose/index.js"(exports2, module2) { "use strict"; var mongoose = require_lib6(); module2.exports = mongoose; module2.exports.default = mongoose; module2.exports.mongoose = mongoose; module2.exports.cast = mongoose.cast; module2.exports.STATES = mongoose.STATES; module2.exports.setDriver = mongoose.setDriver; module2.exports.set = mongoose.set; module2.exports.get = mongoose.get; module2.exports.createConnection = mongoose.createConnection; module2.exports.connect = mongoose.connect; module2.exports.disconnect = mongoose.disconnect; module2.exports.startSession = mongoose.startSession; module2.exports.pluralize = mongoose.pluralize; module2.exports.model = mongoose.model; module2.exports.deleteModel = mongoose.deleteModel; module2.exports.modelNames = mongoose.modelNames; module2.exports.plugin = mongoose.plugin; module2.exports.connections = mongoose.connections; module2.exports.version = mongoose.version; module2.exports.Aggregate = mongoose.Aggregate; module2.exports.Mongoose = mongoose.Mongoose; module2.exports.Schema = mongoose.Schema; module2.exports.SchemaType = mongoose.SchemaType; module2.exports.SchemaTypes = mongoose.SchemaTypes; module2.exports.VirtualType = mongoose.VirtualType; module2.exports.Types = mongoose.Types; module2.exports.Query = mongoose.Query; module2.exports.Model = mongoose.Model; module2.exports.Document = mongoose.Document; module2.exports.ObjectId = mongoose.ObjectId; module2.exports.isValidObjectId = mongoose.isValidObjectId; module2.exports.isObjectIdOrHexString = mongoose.isObjectIdOrHexString; module2.exports.syncIndexes = mongoose.syncIndexes; module2.exports.Decimal128 = mongoose.Decimal128; module2.exports.Mixed = mongoose.Mixed; module2.exports.Date = mongoose.Date; module2.exports.Number = mongoose.Number; module2.exports.Error = mongoose.Error; module2.exports.MongooseError = mongoose.MongooseError; module2.exports.now = mongoose.now; module2.exports.CastError = mongoose.CastError; module2.exports.SchemaTypeOptions = mongoose.SchemaTypeOptions; module2.exports.mongo = mongoose.mongo; module2.exports.mquery = mongoose.mquery; module2.exports.sanitizeFilter = mongoose.sanitizeFilter; module2.exports.trusted = mongoose.trusted; module2.exports.skipMiddlewareFunction = mongoose.skipMiddlewareFunction; module2.exports.overwriteMiddlewareResult = mongoose.overwriteMiddlewareResult; } }); // netlify/functions/utils/database.js var require_database = __commonJS({ "netlify/functions/utils/database.js"(exports2, module2) { var mongoose = require_mongoose2(); var cached = global.mongoose; if (!cached) { cached = global.mongoose = { conn: null, promise: null }; } async function connectToDatabase2() { if (cached.conn) { return cached.conn; } if (!cached.promise) { const MONGODB_URI = process.env.MONGODB_URI; if (!MONGODB_URI) { throw new Error("MONGODB_URI n\xE3o definida nas vari\xE1veis de ambiente"); } cached.promise = mongoose.connect(MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true }); } try { cached.conn = await cached.promise; } catch (e) { cached.promise = null; throw e; } return cached.conn; } var corsHeaders2 = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "Content-Type, Authorization", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS", "Access-Control-Allow-Credentials": "true" }; function createResponse2(statusCode, body) { return { statusCode, headers: corsHeaders2, body: JSON.stringify(body) }; } module2.exports = { connectToDatabase: connectToDatabase2, corsHeaders: corsHeaders2, createResponse: createResponse2 }; } }); // netlify/functions/node_modules/bcryptjs/dist/bcrypt.js var require_bcrypt = __commonJS({ "netlify/functions/node_modules/bcryptjs/dist/bcrypt.js"(exports2, module2) { (function(global2, factory) { if (typeof define === "function" && define["amd"]) define([], factory); else if (typeof require === "function" && typeof module2 === "object" && module2 && module2["exports"]) module2["exports"] = factory(); else (global2["dcodeIO"] = global2["dcodeIO"] || {})["bcrypt"] = factory(); })(exports2, function() { "use strict"; var bcrypt = {}; var randomFallback = null; function random(len) { if (typeof module2 !== "undefined" && module2 && module2["exports"]) try { return require("crypto")["randomBytes"](len); } catch (e) { } try { var a; (self["crypto"] || self["msCrypto"])["getRandomValues"](a = new Uint32Array(len)); return Array.prototype.slice.call(a); } catch (e) { } if (!randomFallback) throw Error("Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative"); return randomFallback(len); } var randomAvailable = false; try { random(1); randomAvailable = true; } catch (e) { } randomFallback = null; bcrypt.setRandomFallback = function(random2) { randomFallback = random2; }; bcrypt.genSaltSync = function(rounds, seed_length) { rounds = rounds || GENSALT_DEFAULT_LOG2_ROUNDS; if (typeof rounds !== "number") throw Error("Illegal arguments: " + typeof rounds + ", " + typeof seed_length); if (rounds < 4) rounds = 4; else if (rounds > 31) rounds = 31; var salt = []; salt.push("$2a$"); if (rounds < 10) salt.push("0"); salt.push(rounds.toString()); salt.push("$"); salt.push(base64_encode(random(BCRYPT_SALT_LEN), BCRYPT_SALT_LEN)); return salt.join(""); }; bcrypt.genSalt = function(rounds, seed_length, callback) { if (typeof seed_length === "function") callback = seed_length, seed_length = void 0; if (typeof rounds === "function") callback = rounds, rounds = void 0; if (typeof rounds === "undefined") rounds = GENSALT_DEFAULT_LOG2_ROUNDS; else if (typeof rounds !== "number") throw Error("illegal arguments: " + typeof rounds); function _async(callback2) { nextTick(function() { try { callback2(null, bcrypt.genSaltSync(rounds)); } catch (err) { callback2(err); } }); } if (callback) { if (typeof callback !== "function") throw Error("Illegal callback: " + typeof callback); _async(callback); } else return new Promise(function(resolve, reject) { _async(function(err, res) { if (err) { reject(err); return; } resolve(res); }); }); }; bcrypt.hashSync = function(s, salt) { if (typeof salt === "undefined") salt = GENSALT_DEFAULT_LOG2_ROUNDS; if (typeof salt === "number") salt = bcrypt.genSaltSync(salt); if (typeof s !== "string" || typeof salt !== "string") throw Error("Illegal arguments: " + typeof s + ", " + typeof salt); return _hash(s, salt); }; bcrypt.hash = function(s, salt, callback, progressCallback) { function _async(callback2) { if (typeof s === "string" && typeof salt === "number") bcrypt.genSalt(salt, function(err, salt2) { _hash(s, salt2, callback2, progressCallback); }); else if (typeof s === "string" && typeof salt === "string") _hash(s, salt, callback2, progressCallback); else nextTick(callback2.bind(this, Error("Illegal arguments: " + typeof s + ", " + typeof salt))); } if (callback) { if (typeof callback !== "function") throw Error("Illegal callback: " + typeof callback); _async(callback); } else return new Promise(function(resolve, reject) { _async(function(err, res) { if (err) { reject(err); return; } resolve(res); }); }); }; function safeStringCompare(known, unknown) { var right = 0, wrong = 0; for (var i = 0, k = known.length; i < k; ++i) { if (known.charCodeAt(i) === unknown.charCodeAt(i)) ++right; else ++wrong; } if (right < 0) return false; return wrong === 0; } bcrypt.compareSync = function(s, hash) { if (typeof s !== "string" || typeof hash !== "string") throw Error("Illegal arguments: " + typeof s + ", " + typeof hash); if (hash.length !== 60) return false; return safeStringCompare(bcrypt.hashSync(s, hash.substr(0, hash.length - 31)), hash); }; bcrypt.compare = function(s, hash, callback, progressCallback) { function _async(callback2) { if (typeof s !== "string" || typeof hash !== "string") { nextTick(callback2.bind(this, Error("Illegal arguments: " + typeof s + ", " + typeof hash))); return; } if (hash.length !== 60) { nextTick(callback2.bind(this, null, false)); return; } bcrypt.hash(s, hash.substr(0, 29), function(err, comp) { if (err) callback2(err); else callback2(null, safeStringCompare(comp, hash)); }, progressCallback); } if (callback) { if (typeof callback !== "function") throw Error("Illegal callback: " + typeof callback); _async(callback); } else return new Promise(function(resolve, reject) { _async(function(err, res) { if (err) { reject(err); return; } resolve(res); }); }); }; bcrypt.getRounds = function(hash) { if (typeof hash !== "string") throw Error("Illegal arguments: " + typeof hash); return parseInt(hash.split("$")[2], 10); }; bcrypt.getSalt = function(hash) { if (typeof hash !== "string") throw Error("Illegal arguments: " + typeof hash); if (hash.length !== 60) throw Error("Illegal hash length: " + hash.length + " != 60"); return hash.substring(0, 29); }; var nextTick = typeof process !== "undefined" && process && typeof process.nextTick === "function" ? typeof setImmediate === "function" ? setImmediate : process.nextTick : setTimeout; function stringToBytes(str) { var out = [], i = 0; utfx.encodeUTF16toUTF8(function() { if (i >= str.length) return null; return str.charCodeAt(i++); }, function(b) { out.push(b); }); return out; } var BASE64_CODE = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""); var BASE64_INDEX = [ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, -1, -1, -1, -1, -1, -1, -1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, -1, -1, -1, -1, -1, -1, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, -1, -1, -1, -1, -1 ]; var stringFromCharCode = String.fromCharCode; function base64_encode(b, len) { var off = 0, rs2 = [], c1, c2; if (len <= 0 || len > b.length) throw Error("Illegal len: " + len); while (off < len) { c1 = b[off++] & 255; rs2.push(BASE64_CODE[c1 >> 2 & 63]); c1 = (c1 & 3) << 4; if (off >= len) { rs2.push(BASE64_CODE[c1 & 63]); break; } c2 = b[off++] & 255; c1 |= c2 >> 4 & 15; rs2.push(BASE64_CODE[c1 & 63]); c1 = (c2 & 15) << 2; if (off >= len) { rs2.push(BASE64_CODE[c1 & 63]); break; } c2 = b[off++] & 255; c1 |= c2 >> 6 & 3; rs2.push(BASE64_CODE[c1 & 63]); rs2.push(BASE64_CODE[c2 & 63]); } return rs2.join(""); } function base64_decode(s, len) { var off = 0, slen = s.length, olen = 0, rs2 = [], c1, c2, c3, c4, o, code; if (len <= 0) throw Error("Illegal len: " + len); while (off < slen - 1 && olen < len) { code = s.charCodeAt(off++); c1 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1; code = s.charCodeAt(off++); c2 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1; if (c1 == -1 || c2 == -1) break; o = c1 << 2 >>> 0; o |= (c2 & 48) >> 4; rs2.push(stringFromCharCode(o)); if (++olen >= len || off >= slen) break; code = s.charCodeAt(off++); c3 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1; if (c3 == -1) break; o = (c2 & 15) << 4 >>> 0; o |= (c3 & 60) >> 2; rs2.push(stringFromCharCode(o)); if (++olen >= len || off >= slen) break; code = s.charCodeAt(off++); c4 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1; o = (c3 & 3) << 6 >>> 0; o |= c4; rs2.push(stringFromCharCode(o)); ++olen; } var res = []; for (off = 0; off < olen; off++) res.push(rs2[off].charCodeAt(0)); return res; } var utfx = (function() { "use strict"; var utfx2 = {}; utfx2.MAX_CODEPOINT = 1114111; utfx2.encodeUTF8 = function(src, dst) { var cp = null; if (typeof src === "number") cp = src, src = function() { return null; }; while (cp !== null || (cp = src()) !== null) { if (cp < 128) dst(cp & 127); else if (cp < 2048) dst(cp >> 6 & 31 | 192), dst(cp & 63 | 128); else if (cp < 65536) dst(cp >> 12 & 15 | 224), dst(cp >> 6 & 63 | 128), dst(cp & 63 | 128); else dst(cp >> 18 & 7 | 240), dst(cp >> 12 & 63 | 128), dst(cp >> 6 & 63 | 128), dst(cp & 63 | 128); cp = null; } }; utfx2.decodeUTF8 = function(src, dst) { var a, b, c, d, fail = function(b2) { b2 = b2.slice(0, b2.indexOf(null)); var err = Error(b2.toString()); err.name = "TruncatedError"; err["bytes"] = b2; throw err; }; while ((a = src()) !== null) { if ((a & 128) === 0) dst(a); else if ((a & 224) === 192) (b = src()) === null && fail([a, b]), dst((a & 31) << 6 | b & 63); else if ((a & 240) === 224) ((b = src()) === null || (c = src()) === null) && fail([a, b, c]), dst((a & 15) << 12 | (b & 63) << 6 | c & 63); else if ((a & 248) === 240) ((b = src()) === null || (c = src()) === null || (d = src()) === null) && fail([a, b, c, d]), dst((a & 7) << 18 | (b & 63) << 12 | (c & 63) << 6 | d & 63); else throw RangeError("Illegal starting byte: " + a); } }; utfx2.UTF16toUTF8 = function(src, dst) { var c1, c2 = null; while (true) { if ((c1 = c2 !== null ? c2 : src()) === null) break; if (c1 >= 55296 && c1 <= 57343) { if ((c2 = src()) !== null) { if (c2 >= 56320 && c2 <= 57343) { dst((c1 - 55296) * 1024 + c2 - 56320 + 65536); c2 = null; continue; } } } dst(c1); } if (c2 !== null) dst(c2); }; utfx2.UTF8toUTF16 = function(src, dst) { var cp = null; if (typeof src === "number") cp = src, src = function() { return null; }; while (cp !== null || (cp = src()) !== null) { if (cp <= 65535) dst(cp); else cp -= 65536, dst((cp >> 10) + 55296), dst(cp % 1024 + 56320); cp = null; } }; utfx2.encodeUTF16toUTF8 = function(src, dst) { utfx2.UTF16toUTF8(src, function(cp) { utfx2.encodeUTF8(cp, dst); }); }; utfx2.decodeUTF8toUTF16 = function(src, dst) { utfx2.decodeUTF8(src, function(cp) { utfx2.UTF8toUTF16(cp, dst); }); }; utfx2.calculateCodePoint = function(cp) { return cp < 128 ? 1 : cp < 2048 ? 2 : cp < 65536 ? 3 : 4; }; utfx2.calculateUTF8 = function(src) { var cp, l = 0; while ((cp = src()) !== null) l += utfx2.calculateCodePoint(cp); return l; }; utfx2.calculateUTF16asUTF8 = function(src) { var n = 0, l = 0; utfx2.UTF16toUTF8(src, function(cp) { ++n; l += utfx2.calculateCodePoint(cp); }); return [n, l]; }; return utfx2; })(); Date.now = Date.now || function() { return +/* @__PURE__ */ new Date(); }; var BCRYPT_SALT_LEN = 16; var GENSALT_DEFAULT_LOG2_ROUNDS = 10; var BLOWFISH_NUM_ROUNDS = 16; var MAX_EXECUTION_TIME = 100; var P_ORIG = [ 608135816, 2242054355, 320440878, 57701188, 2752067618, 698298832, 137296536, 3964562569, 1160258022, 953160567, 3193202383, 887688300, 3232508343, 3380367581, 1065670069, 3041331479, 2450970073, 2306472731 ]; var S_ORIG = [ 3509652390, 2564797868, 805139163, 3491422135, 3101798381, 1780907670, 3128725573, 4046225305, 614570311, 3012652279, 134345442, 2240740374, 1667834072, 1901547113, 2757295779, 4103290238, 227898511, 1921955416, 1904987480, 2182433518, 2069144605, 3260701109, 2620446009, 720527379, 3318853667, 677414384, 3393288472, 3101374703, 2390351024, 1614419982, 1822297739, 2954791486, 3608508353, 3174124327, 2024746970, 1432378464, 3864339955, 2857741204, 1464375394, 1676153920, 1439316330, 715854006, 3033291828, 289532110, 2706671279, 2087905683, 3018724369, 1668267050, 732546397, 1947742710, 3462151702, 2609353502, 2950085171, 1814351708, 2050118529, 680887927, 999245976, 1800124847, 3300911131, 1713906067, 1641548236, 4213287313, 1216130144, 1575780402, 4018429277, 3917837745, 3693486850, 3949271944, 596196993, 3549867205, 258830323, 2213823033, 772490370, 2760122372, 1774776394, 2652871518, 566650946, 4142492826, 1728879713, 2882767088, 1783734482, 3629395816, 2517608232, 2874225571, 1861159788, 326777828, 3124490320, 2130389656, 2716951837, 967770486, 1724537150, 2185432712, 2364442137, 1164943284, 2105845187, 998989502, 3765401048, 2244026483, 1075463327, 1455516326, 1322494562, 910128902, 469688178, 1117454909, 936433444, 3490320968, 3675253459, 1240580251, 122909385, 2157517691, 634681816, 4142456567, 3825094682, 3061402683, 2540495037, 79693498, 3249098678, 1084186820, 1583128258, 426386531, 1761308591, 1047286709, 322548459, 995290223, 1845252383, 2603652396, 3431023940, 2942221577, 3202600964, 3727903485, 1712269319, 422464435, 3234572375, 1170764815, 3523960633, 3117677531, 1434042557, 442511882, 3600875718, 1076654713, 1738483198, 4213154764, 2393238008, 3677496056, 1014306527, 4251020053, 793779912, 2902807211, 842905082, 4246964064, 1395751752, 1040244610, 2656851899, 3396308128, 445077038, 3742853595, 3577915638, 679411651, 2892444358, 2354009459, 1767581616, 3150600392, 3791627101, 3102740896, 284835224, 4246832056, 1258075500, 768725851, 2589189241, 3069724005, 3532540348, 1274779536, 3789419226, 2764799539, 1660621633, 3471099624, 4011903706, 913787905, 3497959166, 737222580, 2514213453, 2928710040, 3937242737, 1804850592, 3499020752, 2949064160, 2386320175, 2390070455, 2415321851, 4061277028, 2290661394, 2416832540, 1336762016, 1754252060, 3520065937, 3014181293, 791618072, 3188594551, 3933548030, 2332172193, 3852520463, 3043980520, 413987798, 3465142937, 3030929376, 4245938359, 2093235073, 3534596313, 375366246, 2157278981, 2479649556, 555357303, 3870105701, 2008414854, 3344188149, 4221384143, 3956125452, 2067696032, 3594591187, 2921233993, 2428461, 544322398, 577241275, 1471733935, 610547355, 4027169054, 1432588573, 1507829418, 2025931657, 3646575487, 545086370, 48609733, 2200306550, 1653985193, 298326376, 1316178497, 3007786442, 2064951626, 458293330, 2589141269, 3591329599, 3164325604, 727753846, 2179363840, 146436021, 1461446943, 4069977195, 705550613, 3059967265, 3887724982, 4281599278, 3313849956, 1404054877, 2845806497, 146425753, 1854211946, 1266315497, 3048417604, 3681880366, 3289982499, 290971e4, 1235738493, 2632868024, 2414719590, 3970600049, 1771706367, 1449415276, 3266420449, 422970021, 1963543593, 2690192192, 3826793022, 1062508698, 1531092325, 1804592342, 2583117782, 2714934279, 4024971509, 1294809318, 4028980673, 1289560198, 2221992742, 1669523910, 35572830, 157838143, 1052438473, 1016535060, 1802137761, 1753167236, 1386275462, 3080475397, 2857371447, 1040679964, 2145300060, 2390574316, 1461121720, 2956646967, 4031777805, 4028374788, 33600511, 2920084762, 1018524850, 629373528, 3691585981, 3515945977, 2091462646, 2486323059, 586499841, 988145025, 935516892, 3367335476, 2599673255, 2839830854, 265290510, 3972581182, 2759138881, 3795373465, 1005194799, 847297441, 406762289, 1314163512, 1332590856, 1866599683, 4127851711, 750260880, 613907577, 1450815602, 3165620655, 3734664991, 3650291728, 3012275730, 3704569646, 1427272223, 778793252, 1343938022, 2676280711, 2052605720, 1946737175, 3164576444, 3914038668, 3967478842, 3682934266, 1661551462, 3294938066, 4011595847, 840292616, 3712170807, 616741398, 312560963, 711312465, 1351876610, 322626781, 1910503582, 271666773, 2175563734, 1594956187, 70604529, 3617834859, 1007753275, 1495573769, 4069517037, 2549218298, 2663038764, 504708206, 2263041392, 3941167025, 2249088522, 1514023603, 1998579484, 1312622330, 694541497, 2582060303, 2151582166, 1382467621, 776784248, 2618340202, 3323268794, 2497899128, 2784771155, 503983604, 4076293799, 907881277, 423175695, 432175456, 1378068232, 4145222326, 3954048622, 3938656102, 3820766613, 2793130115, 2977904593, 26017576, 3274890735, 3194772133, 1700274565, 1756076034, 4006520079, 3677328699, 720338349, 1533947780, 354530856, 688349552, 3973924725, 1637815568, 332179504, 3949051286, 53804574, 2852348879, 3044236432, 1282449977, 3583942155, 3416972820, 4006381244, 1617046695, 2628476075, 3002303598, 1686838959, 431878346, 2686675385, 1700445008, 1080580658, 1009431731, 832498133, 3223435511, 2605976345, 2271191193, 2516031870, 1648197032, 4164389018, 2548247927, 300782431, 375919233, 238389289, 3353747414, 2531188641, 2019080857, 1475708069, 455242339, 2609103871, 448939670, 3451063019, 1395535956, 2413381860, 1841049896, 1491858159, 885456874, 4264095073, 4001119347, 1565136089, 3898914787, 1108368660, 540939232, 1173283510, 2745871338, 3681308437, 4207628240, 3343053890, 4016749493, 1699691293, 1103962373, 3625875870, 2256883143, 3830138730, 1031889488, 3479347698, 1535977030, 4236805024, 3251091107, 2132092099, 1774941330, 1199868427, 1452454533, 157007616, 2904115357, 342012276, 595725824, 1480756522, 206960106, 497939518, 591360097, 863170706, 2375253569, 3596610801, 1814182875, 2094937945, 3421402208, 1082520231, 3463918190, 2785509508, 435703966, 3908032597, 1641649973, 2842273706, 3305899714, 1510255612, 2148256476, 2655287854, 3276092548, 4258621189, 236887753, 3681803219, 274041037, 1734335097, 3815195456, 3317970021, 1899903192, 1026095262, 4050517792, 356393447, 2410691914, 3873677099, 3682840055, 3913112168, 2491498743, 4132185628, 2489919796, 1091903735, 1979897079, 3170134830, 3567386728, 3557303409, 857797738, 1136121015, 1342202287, 507115054, 2535736646, 337727348, 3213592640, 1301675037, 2528481711, 1895095763, 1721773893, 3216771564, 62756741, 2142006736, 835421444, 2531993523, 1442658625, 3659876326, 2882144922, 676362277, 1392781812, 170690266, 3921047035, 1759253602, 3611846912, 1745797284, 664899054, 1329594018, 3901205900, 3045908486, 2062866102, 2865634940, 3543621612, 3464012697, 1080764994, 553557557, 3656615353, 3996768171, 991055499, 499776247, 1265440854, 648242737, 3940784050, 980351604, 3713745714, 1749149687, 3396870395, 4211799374, 3640570775, 1161844396, 3125318951, 1431517754, 545492359, 4268468663, 3499529547, 1437099964, 2702547544, 3433638243, 2581715763, 2787789398, 1060185593, 1593081372, 2418618748, 4260947970, 69676912, 2159744348, 86519011, 2512459080, 3838209314, 1220612927, 3339683548, 133810670, 1090789135, 1078426020, 1569222167, 845107691, 3583754449, 4072456591, 1091646820, 628848692, 1613405280, 3757631651, 526609435, 236106946, 48312990, 2942717905, 3402727701, 1797494240, 859738849, 992217954, 4005476642, 2243076622, 3870952857, 3732016268, 765654824, 3490871365, 2511836413, 1685915746, 3888969200, 1414112111, 2273134842, 3281911079, 4080962846, 172450625, 2569994100, 980381355, 4109958455, 2819808352, 2716589560, 2568741196, 3681446669, 3329971472, 1835478071, 660984891, 3704678404, 4045999559, 3422617507, 3040415634, 1762651403, 1719377915, 3470491036, 2693910283, 3642056355, 3138596744, 1364962596, 2073328063, 1983633131, 926494387, 3423689081, 2150032023, 4096667949, 1749200295, 3328846651, 309677260, 2016342300, 1779581495, 3079819751, 111262694, 1274766160, 443224088, 298511866, 1025883608, 3806446537, 1145181785, 168956806, 3641502830, 3584813610, 1689216846, 3666258015, 3200248200, 1692713982, 2646376535, 4042768518, 1618508792, 1610833997, 3523052358, 4130873264, 2001055236, 3610705100, 2202168115, 4028541809, 2961195399, 1006657119, 2006996926, 3186142756, 1430667929, 3210227297, 1314452623, 4074634658, 4101304120, 2273951170, 1399257539, 3367210612, 3027628629, 1190975929, 2062231137, 2333990788, 2221543033, 2438960610, 1181637006, 548689776, 2362791313, 3372408396, 3104550113, 3145860560, 296247880, 1970579870, 3078560182, 3769228297, 1714227617, 3291629107, 3898220290, 166772364, 1251581989, 493813264, 448347421, 195405023, 2709975567, 677966185, 3703036547, 1463355134, 2715995803, 1338867538, 1343315457, 2802222074, 2684532164, 233230375, 2599980071, 2000651841, 3277868038, 1638401717, 4028070440, 3237316320, 6314154, 819756386, 300326615, 590932579, 1405279636, 3267499572, 3150704214, 2428286686, 3959192993, 3461946742, 1862657033, 1266418056, 963775037, 2089974820, 2263052895, 1917689273, 448879540, 3550394620, 3981727096, 150775221, 3627908307, 1303187396, 508620638, 2975983352, 2726630617, 1817252668, 1876281319, 1457606340, 908771278, 3720792119, 3617206836, 2455994898, 1729034894, 1080033504, 976866871, 3556439503, 2881648439, 1522871579, 1555064734, 1336096578, 3548522304, 2579274686, 3574697629, 3205460757, 3593280638, 3338716283, 3079412587, 564236357, 2993598910, 1781952180, 1464380207, 3163844217, 3332601554, 1699332808, 1393555694, 1183702653, 3581086237, 1288719814, 691649499, 2847557200, 2895455976, 3193889540, 2717570544, 1781354906, 1676643554, 2592534050, 3230253752, 1126444790, 2770207658, 2633158820, 2210423226, 2615765581, 2414155088, 3127139286, 673620729, 2805611233, 1269405062, 4015350505, 3341807571, 4149409754, 1057255273, 2012875353, 2162469141, 2276492801, 2601117357, 993977747, 3918593370, 2654263191, 753973209, 36408145, 2530585658, 25011837, 3520020182, 2088578344, 530523599, 2918365339, 1524020338, 1518925132, 3760827505, 3759777254, 1202760957, 3985898139, 3906192525, 674977740, 4174734889, 2031300136, 2019492241, 3983892565, 4153806404, 3822280332, 352677332, 2297720250, 60907813, 90501309, 3286998549, 1016092578, 2535922412, 2839152426, 457141659, 509813237, 4120667899, 652014361, 1966332200, 2975202805, 55981186, 2327461051, 676427537, 3255491064, 2882294119, 3433927263, 1307055953, 942726286, 933058658, 2468411793, 3933900994, 4215176142, 1361170020, 2001714738, 2830558078, 3274259782, 1222529897, 1679025792, 2729314320, 3714953764, 1770335741, 151462246, 3013232138, 1682292957, 1483529935, 471910574, 1539241949, 458788160, 3436315007, 1807016891, 3718408830, 978976581, 1043663428, 3165965781, 1927990952, 4200891579, 2372276910, 3208408903, 3533431907, 1412390302, 2931980059, 4132332400, 1947078029, 3881505623, 4168226417, 2941484381, 1077988104, 1320477388, 886195818, 18198404, 3786409e3, 2509781533, 112762804, 3463356488, 1866414978, 891333506, 18488651, 661792760, 1628790961, 3885187036, 3141171499, 876946877, 2693282273, 1372485963, 791857591, 2686433993, 3759982718, 3167212022, 3472953795, 2716379847, 445679433, 3561995674, 3504004811, 3574258232, 54117162, 3331405415, 2381918588, 3769707343, 4154350007, 1140177722, 4074052095, 668550556, 3214352940, 367459370, 261225585, 2610173221, 4209349473, 3468074219, 3265815641, 314222801, 3066103646, 3808782860, 282218597, 3406013506, 3773591054, 379116347, 1285071038, 846784868, 2669647154, 3771962079, 3550491691, 2305946142, 453669953, 1268987020, 3317592352, 3279303384, 3744833421, 2610507566, 3859509063, 266596637, 3847019092, 517658769, 3462560207, 3443424879, 370717030, 4247526661, 2224018117, 4143653529, 4112773975, 2788324899, 2477274417, 1456262402, 2901442914, 1517677493, 1846949527, 2295493580, 3734397586, 2176403920, 1280348187, 1908823572, 3871786941, 846861322, 1172426758, 3287448474, 3383383037, 1655181056, 3139813346, 901632758, 1897031941, 2986607138, 3066810236, 3447102507, 1393639104, 373351379, 950779232, 625454576, 3124240540, 4148612726, 2007998917, 544563296, 2244738638, 2330496472, 2058025392, 1291430526, 424198748, 50039436, 29584100, 3605783033, 2429876329, 2791104160, 1057563949, 3255363231, 3075367218, 3463963227, 1469046755, 985887462 ]; var C_ORIG = [ 1332899944, 1700884034, 1701343084, 1684370003, 1668446532, 1869963892 ]; function _encipher(lr, off, P, S) { var n, l = lr[off], r = lr[off + 1]; l ^= P[0]; n = S[l >>> 24]; n += S[256 | l >> 16 & 255]; n ^= S[512 | l >> 8 & 255]; n += S[768 | l & 255]; r ^= n ^ P[1]; n = S[r >>> 24]; n += S[256 | r >> 16 & 255]; n ^= S[512 | r >> 8 & 255]; n += S[768 | r & 255]; l ^= n ^ P[2]; n = S[l >>> 24]; n += S[256 | l >> 16 & 255]; n ^= S[512 | l >> 8 & 255]; n += S[768 | l & 255]; r ^= n ^ P[3]; n = S[r >>> 24]; n += S[256 | r >> 16 & 255]; n ^= S[512 | r >> 8 & 255]; n += S[768 | r & 255]; l ^= n ^ P[4]; n = S[l >>> 24]; n += S[256 | l >> 16 & 255]; n ^= S[512 | l >> 8 & 255]; n += S[768 | l & 255]; r ^= n ^ P[5]; n = S[r >>> 24]; n += S[256 | r >> 16 & 255]; n ^= S[512 | r >> 8 & 255]; n += S[768 | r & 255]; l ^= n ^ P[6]; n = S[l >>> 24]; n += S[256 | l >> 16 & 255]; n ^= S[512 | l >> 8 & 255]; n += S[768 | l & 255]; r ^= n ^ P[7]; n = S[r >>> 24]; n += S[256 | r >> 16 & 255]; n ^= S[512 | r >> 8 & 255]; n += S[768 | r & 255]; l ^= n ^ P[8]; n = S[l >>> 24]; n += S[256 | l >> 16 & 255]; n ^= S[512 | l >> 8 & 255]; n += S[768 | l & 255]; r ^= n ^ P[9]; n = S[r >>> 24]; n += S[256 | r >> 16 & 255]; n ^= S[512 | r >> 8 & 255]; n += S[768 | r & 255]; l ^= n ^ P[10]; n = S[l >>> 24]; n += S[256 | l >> 16 & 255]; n ^= S[512 | l >> 8 & 255]; n += S[768 | l & 255]; r ^= n ^ P[11]; n = S[r >>> 24]; n += S[256 | r >> 16 & 255]; n ^= S[512 | r >> 8 & 255]; n += S[768 | r & 255]; l ^= n ^ P[12]; n = S[l >>> 24]; n += S[256 | l >> 16 & 255]; n ^= S[512 | l >> 8 & 255]; n += S[768 | l & 255]; r ^= n ^ P[13]; n = S[r >>> 24]; n += S[256 | r >> 16 & 255]; n ^= S[512 | r >> 8 & 255]; n += S[768 | r & 255]; l ^= n ^ P[14]; n = S[l >>> 24]; n += S[256 | l >> 16 & 255]; n ^= S[512 | l >> 8 & 255]; n += S[768 | l & 255]; r ^= n ^ P[15]; n = S[r >>> 24]; n += S[256 | r >> 16 & 255]; n ^= S[512 | r >> 8 & 255]; n += S[768 | r & 255]; l ^= n ^ P[16]; lr[off] = r ^ P[BLOWFISH_NUM_ROUNDS + 1]; lr[off + 1] = l; return lr; } function _streamtoword(data, offp) { for (var i = 0, word = 0; i < 4; ++i) word = word << 8 | data[offp] & 255, offp = (offp + 1) % data.length; return { key: word, offp }; } function _key(key, P, S) { var offset = 0, lr = [0, 0], plen = P.length, slen = S.length, sw; for (var i = 0; i < plen; i++) sw = _streamtoword(key, offset), offset = sw.offp, P[i] = P[i] ^ sw.key; for (i = 0; i < plen; i += 2) lr = _encipher(lr, 0, P, S), P[i] = lr[0], P[i + 1] = lr[1]; for (i = 0; i < slen; i += 2) lr = _encipher(lr, 0, P, S), S[i] = lr[0], S[i + 1] = lr[1]; } function _ekskey(data, key, P, S) { var offp = 0, lr = [0, 0], plen = P.length, slen = S.length, sw; for (var i = 0; i < plen; i++) sw = _streamtoword(key, offp), offp = sw.offp, P[i] = P[i] ^ sw.key; offp = 0; for (i = 0; i < plen; i += 2) sw = _streamtoword(data, offp), offp = sw.offp, lr[0] ^= sw.key, sw = _streamtoword(data, offp), offp = sw.offp, lr[1] ^= sw.key, lr = _encipher(lr, 0, P, S), P[i] = lr[0], P[i + 1] = lr[1]; for (i = 0; i < slen; i += 2) sw = _streamtoword(data, offp), offp = sw.offp, lr[0] ^= sw.key, sw = _streamtoword(data, offp), offp = sw.offp, lr[1] ^= sw.key, lr = _encipher(lr, 0, P, S), S[i] = lr[0], S[i + 1] = lr[1]; } function _crypt(b, salt, rounds, callback, progressCallback) { var cdata = C_ORIG.slice(), clen = cdata.length, err; if (rounds < 4 || rounds > 31) { err = Error("Illegal number of rounds (4-31): " + rounds); if (callback) { nextTick(callback.bind(this, err)); return; } else throw err; } if (salt.length !== BCRYPT_SALT_LEN) { err = Error("Illegal salt length: " + salt.length + " != " + BCRYPT_SALT_LEN); if (callback) { nextTick(callback.bind(this, err)); return; } else throw err; } rounds = 1 << rounds >>> 0; var P, S, i = 0, j; if (Int32Array) { P = new Int32Array(P_ORIG); S = new Int32Array(S_ORIG); } else { P = P_ORIG.slice(); S = S_ORIG.slice(); } _ekskey(salt, b, P, S); function next() { if (progressCallback) progressCallback(i / rounds); if (i < rounds) { var start = Date.now(); for (; i < rounds; ) { i = i + 1; _key(b, P, S); _key(salt, P, S); if (Date.now() - start > MAX_EXECUTION_TIME) break; } } else { for (i = 0; i < 64; i++) for (j = 0; j < clen >> 1; j++) _encipher(cdata, j << 1, P, S); var ret = []; for (i = 0; i < clen; i++) ret.push((cdata[i] >> 24 & 255) >>> 0), ret.push((cdata[i] >> 16 & 255) >>> 0), ret.push((cdata[i] >> 8 & 255) >>> 0), ret.push((cdata[i] & 255) >>> 0); if (callback) { callback(null, ret); return; } else return ret; } if (callback) nextTick(next); } if (typeof callback !== "undefined") { next(); } else { var res; while (true) if (typeof (res = next()) !== "undefined") return res || []; } } function _hash(s, salt, callback, progressCallback) { var err; if (typeof s !== "string" || typeof salt !== "string") { err = Error("Invalid string / salt: Not a string"); if (callback) { nextTick(callback.bind(this, err)); return; } else throw err; } var minor, offset; if (salt.charAt(0) !== "$" || salt.charAt(1) !== "2") { err = Error("Invalid salt version: " + salt.substring(0, 2)); if (callback) { nextTick(callback.bind(this, err)); return; } else throw err; } if (salt.charAt(2) === "$") minor = String.fromCharCode(0), offset = 3; else { minor = salt.charAt(2); if (minor !== "a" && minor !== "b" && minor !== "y" || salt.charAt(3) !== "$") { err = Error("Invalid salt revision: " + salt.substring(2, 4)); if (callback) { nextTick(callback.bind(this, err)); return; } else throw err; } offset = 4; } if (salt.charAt(offset + 2) > "$") { err = Error("Missing salt rounds"); if (callback) { nextTick(callback.bind(this, err)); return; } else throw err; } var r1 = parseInt(salt.substring(offset, offset + 1), 10) * 10, r2 = parseInt(salt.substring(offset + 1, offset + 2), 10), rounds = r1 + r2, real_salt = salt.substring(offset + 3, offset + 25); s += minor >= "a" ? "\0" : ""; var passwordb = stringToBytes(s), saltb = base64_decode(real_salt, BCRYPT_SALT_LEN); function finish(bytes) { var res = []; res.push("$2"); if (minor >= "a") res.push(minor); res.push("$"); if (rounds < 10) res.push("0"); res.push(rounds.toString()); res.push("$"); res.push(base64_encode(saltb, saltb.length)); res.push(base64_encode(bytes, C_ORIG.length * 4 - 1)); return res.join(""); } if (typeof callback == "undefined") return finish(_crypt(passwordb, saltb, rounds)); else { _crypt(passwordb, saltb, rounds, function(err2, bytes) { if (err2) callback(err2, null); else callback(null, finish(bytes)); }, progressCallback); } } bcrypt.encodeBase64 = base64_encode; bcrypt.decodeBase64 = base64_decode; return bcrypt; }); } }); // netlify/functions/node_modules/bcryptjs/index.js var require_bcryptjs = __commonJS({ "netlify/functions/node_modules/bcryptjs/index.js"(exports2, module2) { module2.exports = require_bcrypt(); } }); // netlify/functions/models/medico.js var require_medico = __commonJS({ "netlify/functions/models/medico.js"(exports2, module2) { var mongoose = require_mongoose2(); var bcrypt = require_bcryptjs(); var medicoSchema = new mongoose.Schema({ nome: { type: String, required: [true, "Nome \xE9 obrigat\xF3rio"], trim: true }, email: { type: String, required: [true, "Email \xE9 obrigat\xF3rio"], unique: true, lowercase: true }, senha: { type: String, required: [true, "Senha \xE9 obrigat\xF3ria"], minlength: 6 }, crm: { type: String, required: [true, "CRM \xE9 obrigat\xF3rio"], unique: true }, especialidade: { type: String, required: [true, "Especialidade \xE9 obrigat\xF3ria"] }, telefone: { type: String, required: [true, "Telefone \xE9 obrigat\xF3rio"] } }, { timestamps: true }); medicoSchema.pre("save", async function(next) { if (!this.isModified("senha")) return next(); const salt = await bcrypt.genSalt(10); this.senha = await bcrypt.hash(this.senha, salt); next(); }); medicoSchema.methods.compararSenha = async function(senha) { return await bcrypt.compare(senha, this.senha); }; var Medico2 = mongoose.models.Medico || mongoose.model("Medico", medicoSchema); module2.exports = Medico2; } }); // netlify/functions/medicos-login.js var { connectToDatabase, createResponse, corsHeaders } = require_database(); var Medico = require_medico(); exports.handler = async (event, context) => { if (event.httpMethod === "OPTIONS") { return { statusCode: 200, headers: corsHeaders, body: "" }; } try { await connectToDatabase(); const method = event.httpMethod; if (method === "POST") { const { email, senha } = JSON.parse(event.body); if (!email || !senha) { return createResponse(400, { message: "Email e senha s\xE3o obrigat\xF3rios" }); } const medico = await Medico.findOne({ email: email.toLowerCase().trim() }); if (!medico) { return createResponse(401, { message: "Email ou senha incorretos" }); } const senhaCorreta = await medico.compararSenha(senha); if (!senhaCorreta) { return createResponse(401, { message: "Email ou senha incorretos" }); } const medicoSemSenha = medico.toObject(); delete medicoSemSenha.senha; return createResponse(200, { message: "Login realizado com sucesso", medico: medicoSemSenha }); } return createResponse(405, { message: "M\xE9todo n\xE3o permitido" }); } catch (error) { console.error("Erro na function medicos-login:", error); return createResponse(500, { message: "Erro interno do servidor", error: error.message }); } }; /*! Bundled license information: mongoose/lib/connectionState.js: (*! * Connection states *) mongoose/lib/helpers/immediate.js: (*! * Centralize this so we can more easily work around issues with people * stubbing out `process.nextTick()` in tests using sinon: * https://github.com/sinonjs/lolex#automatically-incrementing-mocked-time * See gh-6074 *) mongoose/lib/collection.js: (*! * Module dependencies. *) (*! * ignore *) (*! * Module exports. *) mongoose/lib/error/mongooseError.js: mongoose/lib/options.js: mongoose/lib/helpers/clone.js: mongoose/lib/helpers/error/combinePathErrors.js: mongoose/lib/schema/operators/exists.js: mongoose/lib/schema/operators/type.js: mongoose/lib/helpers/schematype/handleImmutable.js: mongoose/lib/helpers/document/applyDefaults.js: mongoose/lib/helpers/document/cleanModifiedSubpaths.js: mongoose/lib/helpers/projection/isDefiningProjection.js: mongoose/lib/helpers/projection/isExclusive.js: mongoose/lib/helpers/projection/isPathSelectedInclusive.js: mongoose/lib/types/subdocument.js: mongoose/lib/helpers/schema/idGetter.js: mongoose/lib/helpers/schema/handleTimestampOption.js: mongoose/lib/helpers/update/applyTimestampsToChildren.js: mongoose/lib/helpers/update/applyTimestampsToUpdate.js: mongoose/lib/constants.js: mongoose/lib/helpers/model/applyHooks.js: mongoose/lib/types/map.js: mongoose/lib/options/schemaArrayOptions.js: mongoose/lib/options/schemaNumberOptions.js: mongoose/lib/options/schemaBufferOptions.js: mongoose/lib/options/schemaDateOptions.js: mongoose/lib/plugins/saveSubdocs.js: mongoose/lib/plugins/sharding.js: mongoose/lib/plugins/validateBeforeSave.js: mongoose/lib/helpers/model/discriminator.js: mongoose/lib/options/schemaDocumentArrayOptions.js: mongoose/lib/schema/map.js: mongoose/lib/options/schemaObjectIdOptions.js: mongoose/lib/options/schemaStringOptions.js: mongoose/lib/schema/union.js: mongoose/lib/driver.js: mongoose/lib/helpers/query/castUpdate.js: mongoose/lib/helpers/projection/isInclusive.js: mongoose/lib/helpers/query/hasDollarKeys.js: mongoose/lib/helpers/query/selectPopulatedFields.js: mongoose/lib/helpers/populate/leanPopulateMap.js: mongoose/lib/helpers/populate/getVirtual.js: mongoose/lib/helpers/populate/getSchemaTypes.js: mongoose/lib/helpers/populate/getModelsMapForPopulate.js: mongoose/lib/helpers/parallelLimit.js: mongoose/lib/helpers/populate/removeDeselectedForeignField.js: (*! * ignore *) mongoose/lib/types/objectid.js: (*! * Convenience `valueOf()` to allow comparing ObjectIds using double equals re: gh-7299 *) mongoose/lib/drivers/node-mongodb-native/collection.js: (*! * Module dependencies. *) (*! * Inherit from abstract Collection. *) (*! * ignore *) (*! * Module exports. *) mongoose/lib/cursor/changeStream.js: mongoose/lib/error/serverSelection.js: mongoose/lib/stateMachine.js: mongoose/lib/helpers/common.js: mongoose/lib/utils.js: mongoose/lib/schema/subdocument.js: mongoose/lib/cursor/queryCursor.js: mquery/lib/utils.js: mongoose/lib/cursor/aggregationCursor.js: mongoose/lib/documentProvider.js: (*! * Module dependencies. *) (*! * ignore *) mongoose/lib/error/cast.js: (*! * Module dependencies. *) (*! * ignore *) (*! * exports *) mongoose/lib/error/notFound.js: mongoose/lib/error/validator.js: mongoose/lib/error/version.js: mongoose/lib/error/parallelSave.js: mongoose/lib/error/overwriteModel.js: mongoose/lib/error/missingSchema.js: mongoose/lib/error/bulkSaveIncompleteError.js: mongoose/lib/error/divergentArray.js: mongoose/lib/error/parallelValidate.js: mongoose/lib/error/invalidSchemaOption.js: mongoose/lib/error/bulkWriteError.js: mongoose/lib/error/eachAsyncMultiError.js: (*! * Module dependencies. *) (*! * exports *) mongoose/lib/error/validation.js: mongoose/lib/error/setOptionError.js: (*! * Module requirements *) (*! * Module exports *) mongoose/lib/error/strict.js: mongoose/lib/error/strictPopulate.js: mongoose/lib/error/objectExpected.js: mongoose/lib/error/objectParameter.js: mongoose/lib/cast.js: mongoose/lib/error/syncIndexes.js: mongoose/lib/helpers/cursor/eachAsync.js: mongoose/lib/helpers/updateValidators.js: mongoose/lib/index.js: (*! * Module dependencies. *) mongoose/lib/error/index.js: mongoose/lib/types/index.js: mongoose/lib/schema/index.js: mongoose/lib/drivers/node-mongodb-native/index.js: (*! * Module exports. *) mpath/lib/index.js: (*! * Split a string path into components delimited by '.' or * '[\d+]' * * #### Example: * stringToParts('foo[0].bar.1'); // ['foo', '0', 'bar', '1'] *) (*! * Recursively set nested arrays *) (*! * Returns the value passed to it. *) mongoose/lib/internal.js: (*! * Dependencies *) mongoose/lib/types/buffer.js: (*! * Module dependencies. *) (*! * Inherit from Buffer. *) (*! * Compile other Buffer methods marking this buffer as modified. *) (*! * Module exports. *) mongoose/lib/schema/mixed.js: mongoose/lib/schema/documentArrayElement.js: (*! * Module dependencies. *) (*! * Inherits from SchemaType. *) (*! * Module exports. *) mongoose/lib/helpers/document/compile.js: (*! * exports *) mongoose/lib/queryHelpers.js: (*! * Module dependencies *) (*! * ignore *) mongoose/lib/types/arraySubdocument.js: (*! * Module dependencies. *) (*! * Inherit from Subdocument *) (*! * ignore *) (*! * Module exports. *) mongoose/lib/types/array/methods/index.js: (*! * ignore *) (*! * Minimize _just_ empty objects along the path chain specified * by `parts`, ignoring all other paths. Useful in cases where * you want to minimize after unsetting a path. * * #### Example: * * const obj = { foo: { bar: { baz: {} } }, a: {} }; * _minimizePath(obj, 'foo.bar.baz'); * obj; // { a: {} } *) (*! * If `docs` isn't all instances of the right model, depopulate `arr` *) mongoose/lib/types/array/index.js: mongoose/lib/types/documentArray/index.js: (*! * Module dependencies. *) (*! * Module exports. *) mongoose/lib/document.js: (*! * Module dependencies. *) (*! * ignore *) (*! * Document exposes the NodeJS event emitter API, so you can use * `on`, `once`, etc. *) (*! * Converts to POJO when you use the document for querying *) (*! * Runs queued functions *) (*! * Internal shallow clone alternative to `$toObject()`: much faster, no options processing *) (*! * Applies virtuals properties to `json`. *) (*! * Check if the given document only has primitive values *) (*! * Module exports. *) mongoose/lib/schemaType.js: (*! * Module dependencies. *) (*! * ignore *) (*! * If _duplicateKeyErrorMessage is a string, replace unique index errors "E11000 duplicate key error" with this string. * * @api private *) (*! * Module exports. *) mongoose/lib/virtualType.js: (*! * ignore *) (*! * exports *) mongoose/lib/schema/operators/bitwise.js: mongoose/lib/schema/operators/helpers.js: mongoose/lib/schema/operators/geospatial.js: (*! * Module requirements. *) (*! * ignore *) mongoose/lib/schema/number.js: (*! * Module requirements. *) (*! * ignore *) (*! * Inherits from SchemaType. *) (*! * Module exports. *) mongoose/lib/schema/array.js: (*! * Module dependencies. *) (*! * ignore *) (*! * Inherits from SchemaType. *) (*! * Virtuals defined on this array itself. *) (*! * Module exports. *) mongoose/lib/schema/bigint.js: mongoose/lib/schema/boolean.js: mongoose/lib/schema/buffer.js: mongoose/lib/schema/decimal128.js: mongoose/lib/schema/double.js: mongoose/lib/schema/int32.js: mongoose/lib/schema/objectId.js: mongoose/lib/schema/string.js: mongoose/lib/schema/uuid.js: (*! * Module dependencies. *) (*! * Inherits from SchemaType. *) (*! * ignore *) (*! * Module exports. *) mongoose/lib/schema/date.js: (*! * Module requirements. *) (*! * Inherits from SchemaType. *) (*! * ignore *) (*! * Module exports. *) mongoose/lib/schema/documentArray.js: (*! * Module dependencies. *) (*! * Inherits from SchemaArray. *) (*! * ignore *) (*! * Handle casting $elemMatch operators *) (*! * Module exports. *) mongoose/lib/schema.js: (*! * Module dependencies. *) (*! * Inherit from EventEmitter. *) (*! * ignore *) (*! * Get this schema's default toObject/toJSON options, including Mongoose global * options. *) (*! * Recursively set options on implicitly created schemas *) (*! * Module exports. *) mongoose/lib/connection.js: (*! * Module dependencies. *) (*! * Inherit from EventEmitter *) (*! * Reset document state in between transaction retries re: gh-13698 *) (*! * If transaction was aborted, we need to reset newly inserted documents' `isNew`. *) (*! * Get the default buffer timeout for this connection *) (*! * ignore *) (*! * Called internally by `openUri()` to create a MongoClient instance. *) (*! * Module exports. *) mongoose/lib/drivers/node-mongodb-native/connection.js: (*! * Module dependencies. *) (*! * Inherits from Connection. *) (*! * ignore *) (*! * Module exports. *) mongoose/lib/validOptions.js: (*! * Valid mongoose options *) mquery/lib/mquery.js: (*! * gt, gte, lt, lte, ne, in, nin, all, regex, size, maxDistance * * Thing.where('type').nin(array) *) (*! * @ignore *) (*! * limit, skip, batchSize, comment * * Sets these associated options. * * query.comment('feed query'); *) (*! * Internal helper for updateMany, updateOne *) (*! * Permissions *) (*! * Exports. *) mongoose/lib/query.js: (*! * Module dependencies. *) (*! * inherit mquery *) (*! * Overwrite mquery's `_distinct`, because Mongoose uses that name * to store the field to apply distinct on. *) (*! * ignore *) (*! * If `translateAliases` option is set, call `Model.translateAliases()` * on the following query properties: filter, projection, update, distinct. *) (*! * Convert sort values *) (*! * Export *) mongoose/lib/aggregate.js: (*! * Module dependencies *) (*! * define methods *) (*! * Helpers *) (*! * Exports *) mongoose/lib/model.js: (*! * Module dependencies. *) (*! * ignore *) (*! * Give the constructor the ability to emit events. *) (*! * Populates `docs` for a single `populateOptions` instance. *) (*! * Applies query middleware from this model's schema to this model's * Query constructor. *) (*! * Module exports. *) mongoose/lib/browserDocument.js: (*! * Module dependencies. *) (*! * Inherit from the NodeJS document *) (*! * ignore *) (*! * Browser doc exposes the event emitter API *) (*! * Module exports. *) mongoose/lib/mongoose.js: (*! * Module dependencies. *) (*! * ignore *) (*! * Create a new default connection (`mongoose.connection`) for a Mongoose instance. * No-op if there is already a default connection. *) bcryptjs/dist/bcrypt.js: (** * @license bcrypt.js (c) 2013 Daniel Wirtz * Released under the Apache License, Version 2.0 * see: https://github.com/dcodeIO/bcrypt.js for details *) */ //# sourceMappingURL=medicos-login.js.map