@adobe-commerce/aio-toolkit 1.2.1 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2259,8 +2259,8 @@ var _FileRepository = class _FileRepository {
2259
2259
  const existingFiles = await this.metadata();
2260
2260
  if (existingFiles.length) {
2261
2261
  for (const file of existingFiles) {
2262
- const buffer = await filesLib.read(`${file.name}`);
2263
- const data = JSON.parse(buffer.toString());
2262
+ const buffer2 = await filesLib.read(`${file.name}`);
2263
+ const data = JSON.parse(buffer2.toString());
2264
2264
  results.push({
2265
2265
  ...data,
2266
2266
  createdAt: file.creationTime.toISOString(),
@@ -2294,8 +2294,8 @@ var _FileRepository = class _FileRepository {
2294
2294
  const filesLib = await this.getFiles();
2295
2295
  const existingFile = await filesLib.list(filepath);
2296
2296
  if (existingFile.length) {
2297
- const buffer = await filesLib.read(filepath);
2298
- const data = JSON.parse(buffer.toString());
2297
+ const buffer2 = await filesLib.read(filepath);
2298
+ const data = JSON.parse(buffer2.toString());
2299
2299
  const fileProps = await filesLib.getProperties(filepath);
2300
2300
  return {
2301
2301
  ...data,
@@ -2335,8 +2335,8 @@ var _FileRepository = class _FileRepository {
2335
2335
  ...payload
2336
2336
  };
2337
2337
  } else {
2338
- const buffer = await filesLib.read(filepath);
2339
- const existingData = JSON.parse(buffer.toString());
2338
+ const buffer2 = await filesLib.read(filepath);
2339
+ const existingData = JSON.parse(buffer2.toString());
2340
2340
  payload = { ...existingData, ...payload };
2341
2341
  }
2342
2342
  } else {
@@ -2395,6 +2395,3177 @@ __name(_FileRepository, "FileRepository");
2395
2395
  var FileRepository = _FileRepository;
2396
2396
  var file_repository_default = FileRepository;
2397
2397
 
2398
+ // node_modules/bson/lib/bson.node.mjs
2399
+ var import_crypto = require("crypto");
2400
+ var TypedArrayPrototypeGetSymbolToStringTag = (() => {
2401
+ const g = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
2402
+ return (value) => g.call(value);
2403
+ })();
2404
+ function isUint8Array(value) {
2405
+ return TypedArrayPrototypeGetSymbolToStringTag(value) === "Uint8Array";
2406
+ }
2407
+ __name(isUint8Array, "isUint8Array");
2408
+ function isAnyArrayBuffer(value) {
2409
+ return typeof value === "object" && value != null && Symbol.toStringTag in value && (value[Symbol.toStringTag] === "ArrayBuffer" || value[Symbol.toStringTag] === "SharedArrayBuffer");
2410
+ }
2411
+ __name(isAnyArrayBuffer, "isAnyArrayBuffer");
2412
+ function isRegExp(regexp) {
2413
+ return regexp instanceof RegExp || Object.prototype.toString.call(regexp) === "[object RegExp]";
2414
+ }
2415
+ __name(isRegExp, "isRegExp");
2416
+ function isMap(value) {
2417
+ return typeof value === "object" && value != null && Symbol.toStringTag in value && value[Symbol.toStringTag] === "Map";
2418
+ }
2419
+ __name(isMap, "isMap");
2420
+ function isDate(date) {
2421
+ return date instanceof Date || Object.prototype.toString.call(date) === "[object Date]";
2422
+ }
2423
+ __name(isDate, "isDate");
2424
+ function defaultInspect(x, _options) {
2425
+ return JSON.stringify(x, (k, v) => {
2426
+ if (typeof v === "bigint") {
2427
+ return { $numberLong: `${v}` };
2428
+ } else if (isMap(v)) {
2429
+ return Object.fromEntries(v);
2430
+ }
2431
+ return v;
2432
+ });
2433
+ }
2434
+ __name(defaultInspect, "defaultInspect");
2435
+ function getStylizeFunction(options) {
2436
+ const stylizeExists = options != null && typeof options === "object" && "stylize" in options && typeof options.stylize === "function";
2437
+ if (stylizeExists) {
2438
+ return options.stylize;
2439
+ }
2440
+ }
2441
+ __name(getStylizeFunction, "getStylizeFunction");
2442
+ var BSON_MAJOR_VERSION = 6;
2443
+ var BSON_VERSION_SYMBOL = /* @__PURE__ */ Symbol.for("@@mdb.bson.version");
2444
+ var BSON_INT32_MAX = 2147483647;
2445
+ var BSON_INT32_MIN = -2147483648;
2446
+ var BSON_INT64_MAX = Math.pow(2, 63) - 1;
2447
+ var BSON_INT64_MIN = -Math.pow(2, 63);
2448
+ var JS_INT_MAX = Math.pow(2, 53);
2449
+ var JS_INT_MIN = -Math.pow(2, 53);
2450
+ var BSON_BINARY_SUBTYPE_UUID_NEW = 4;
2451
+ var BSONType = Object.freeze({
2452
+ double: 1,
2453
+ string: 2,
2454
+ object: 3,
2455
+ array: 4,
2456
+ binData: 5,
2457
+ undefined: 6,
2458
+ objectId: 7,
2459
+ bool: 8,
2460
+ date: 9,
2461
+ null: 10,
2462
+ regex: 11,
2463
+ dbPointer: 12,
2464
+ javascript: 13,
2465
+ symbol: 14,
2466
+ javascriptWithScope: 15,
2467
+ int: 16,
2468
+ timestamp: 17,
2469
+ long: 18,
2470
+ decimal: 19,
2471
+ minKey: -1,
2472
+ maxKey: 127
2473
+ });
2474
+ var _BSONError = class _BSONError extends Error {
2475
+ get bsonError() {
2476
+ return true;
2477
+ }
2478
+ get name() {
2479
+ return "BSONError";
2480
+ }
2481
+ constructor(message, options) {
2482
+ super(message, options);
2483
+ }
2484
+ static isBSONError(value) {
2485
+ return value != null && typeof value === "object" && "bsonError" in value && value.bsonError === true && "name" in value && "message" in value && "stack" in value;
2486
+ }
2487
+ };
2488
+ __name(_BSONError, "BSONError");
2489
+ var BSONError = _BSONError;
2490
+ var _BSONVersionError = class _BSONVersionError extends BSONError {
2491
+ get name() {
2492
+ return "BSONVersionError";
2493
+ }
2494
+ constructor() {
2495
+ super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`);
2496
+ }
2497
+ };
2498
+ __name(_BSONVersionError, "BSONVersionError");
2499
+ var BSONVersionError = _BSONVersionError;
2500
+ var _BSONRuntimeError = class _BSONRuntimeError extends BSONError {
2501
+ get name() {
2502
+ return "BSONRuntimeError";
2503
+ }
2504
+ constructor(message) {
2505
+ super(message);
2506
+ }
2507
+ };
2508
+ __name(_BSONRuntimeError, "BSONRuntimeError");
2509
+ var BSONRuntimeError = _BSONRuntimeError;
2510
+ var _BSONOffsetError = class _BSONOffsetError extends BSONError {
2511
+ get name() {
2512
+ return "BSONOffsetError";
2513
+ }
2514
+ constructor(message, offset, options) {
2515
+ super(`${message}. offset: ${offset}`, options);
2516
+ this.offset = offset;
2517
+ }
2518
+ };
2519
+ __name(_BSONOffsetError, "BSONOffsetError");
2520
+ var BSONOffsetError = _BSONOffsetError;
2521
+ var TextDecoderFatal;
2522
+ var TextDecoderNonFatal;
2523
+ function parseUtf8(buffer2, start, end, fatal) {
2524
+ if (fatal) {
2525
+ TextDecoderFatal ?? (TextDecoderFatal = new TextDecoder("utf8", { fatal: true }));
2526
+ try {
2527
+ return TextDecoderFatal.decode(buffer2.subarray(start, end));
2528
+ } catch (cause) {
2529
+ throw new BSONError("Invalid UTF-8 string in BSON document", { cause });
2530
+ }
2531
+ }
2532
+ TextDecoderNonFatal ?? (TextDecoderNonFatal = new TextDecoder("utf8", { fatal: false }));
2533
+ return TextDecoderNonFatal.decode(buffer2.subarray(start, end));
2534
+ }
2535
+ __name(parseUtf8, "parseUtf8");
2536
+ function tryReadBasicLatin(uint8array, start, end) {
2537
+ if (uint8array.length === 0) {
2538
+ return "";
2539
+ }
2540
+ const stringByteLength = end - start;
2541
+ if (stringByteLength === 0) {
2542
+ return "";
2543
+ }
2544
+ if (stringByteLength > 20) {
2545
+ return null;
2546
+ }
2547
+ if (stringByteLength === 1 && uint8array[start] < 128) {
2548
+ return String.fromCharCode(uint8array[start]);
2549
+ }
2550
+ if (stringByteLength === 2 && uint8array[start] < 128 && uint8array[start + 1] < 128) {
2551
+ return String.fromCharCode(uint8array[start]) + String.fromCharCode(uint8array[start + 1]);
2552
+ }
2553
+ if (stringByteLength === 3 && uint8array[start] < 128 && uint8array[start + 1] < 128 && uint8array[start + 2] < 128) {
2554
+ return String.fromCharCode(uint8array[start]) + String.fromCharCode(uint8array[start + 1]) + String.fromCharCode(uint8array[start + 2]);
2555
+ }
2556
+ const latinBytes = [];
2557
+ for (let i = start; i < end; i++) {
2558
+ const byte = uint8array[i];
2559
+ if (byte > 127) {
2560
+ return null;
2561
+ }
2562
+ latinBytes.push(byte);
2563
+ }
2564
+ return String.fromCharCode(...latinBytes);
2565
+ }
2566
+ __name(tryReadBasicLatin, "tryReadBasicLatin");
2567
+ function tryWriteBasicLatin(destination, source, offset) {
2568
+ if (source.length === 0)
2569
+ return 0;
2570
+ if (source.length > 25)
2571
+ return null;
2572
+ if (destination.length - offset < source.length)
2573
+ return null;
2574
+ for (let charOffset = 0, destinationOffset = offset; charOffset < source.length; charOffset++, destinationOffset++) {
2575
+ const char = source.charCodeAt(charOffset);
2576
+ if (char > 127)
2577
+ return null;
2578
+ destination[destinationOffset] = char;
2579
+ }
2580
+ return source.length;
2581
+ }
2582
+ __name(tryWriteBasicLatin, "tryWriteBasicLatin");
2583
+ var nodeJsByteUtils = {
2584
+ toLocalBufferType(potentialBuffer) {
2585
+ if (Buffer.isBuffer(potentialBuffer)) {
2586
+ return potentialBuffer;
2587
+ }
2588
+ if (ArrayBuffer.isView(potentialBuffer)) {
2589
+ return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength);
2590
+ }
2591
+ const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer);
2592
+ if (stringTag === "ArrayBuffer" || stringTag === "SharedArrayBuffer" || stringTag === "[object ArrayBuffer]" || stringTag === "[object SharedArrayBuffer]") {
2593
+ return Buffer.from(potentialBuffer);
2594
+ }
2595
+ throw new BSONError(`Cannot create Buffer from the passed potentialBuffer.`);
2596
+ },
2597
+ allocate(size) {
2598
+ return Buffer.alloc(size);
2599
+ },
2600
+ allocateUnsafe(size) {
2601
+ return Buffer.allocUnsafe(size);
2602
+ },
2603
+ equals(a, b) {
2604
+ return nodeJsByteUtils.toLocalBufferType(a).equals(b);
2605
+ },
2606
+ fromNumberArray(array) {
2607
+ return Buffer.from(array);
2608
+ },
2609
+ fromBase64(base64) {
2610
+ return Buffer.from(base64, "base64");
2611
+ },
2612
+ toBase64(buffer2) {
2613
+ return nodeJsByteUtils.toLocalBufferType(buffer2).toString("base64");
2614
+ },
2615
+ fromISO88591(codePoints) {
2616
+ return Buffer.from(codePoints, "binary");
2617
+ },
2618
+ toISO88591(buffer2) {
2619
+ return nodeJsByteUtils.toLocalBufferType(buffer2).toString("binary");
2620
+ },
2621
+ fromHex(hex) {
2622
+ return Buffer.from(hex, "hex");
2623
+ },
2624
+ toHex(buffer2) {
2625
+ return nodeJsByteUtils.toLocalBufferType(buffer2).toString("hex");
2626
+ },
2627
+ toUTF8(buffer2, start, end, fatal) {
2628
+ const basicLatin = end - start <= 20 ? tryReadBasicLatin(buffer2, start, end) : null;
2629
+ if (basicLatin != null) {
2630
+ return basicLatin;
2631
+ }
2632
+ const string = nodeJsByteUtils.toLocalBufferType(buffer2).toString("utf8", start, end);
2633
+ if (fatal) {
2634
+ for (let i = 0; i < string.length; i++) {
2635
+ if (string.charCodeAt(i) === 65533) {
2636
+ parseUtf8(buffer2, start, end, true);
2637
+ break;
2638
+ }
2639
+ }
2640
+ }
2641
+ return string;
2642
+ },
2643
+ utf8ByteLength(input) {
2644
+ return Buffer.byteLength(input, "utf8");
2645
+ },
2646
+ encodeUTF8Into(buffer2, source, byteOffset) {
2647
+ const latinBytesWritten = tryWriteBasicLatin(buffer2, source, byteOffset);
2648
+ if (latinBytesWritten != null) {
2649
+ return latinBytesWritten;
2650
+ }
2651
+ return nodeJsByteUtils.toLocalBufferType(buffer2).write(source, byteOffset, void 0, "utf8");
2652
+ },
2653
+ randomBytes: import_crypto.randomBytes,
2654
+ swap32(buffer2) {
2655
+ return nodeJsByteUtils.toLocalBufferType(buffer2).swap32();
2656
+ }
2657
+ };
2658
+ function isReactNative() {
2659
+ const { navigator } = globalThis;
2660
+ return typeof navigator === "object" && navigator.product === "ReactNative";
2661
+ }
2662
+ __name(isReactNative, "isReactNative");
2663
+ function webMathRandomBytes(byteLength) {
2664
+ if (byteLength < 0) {
2665
+ throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`);
2666
+ }
2667
+ return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
2668
+ }
2669
+ __name(webMathRandomBytes, "webMathRandomBytes");
2670
+ var webRandomBytes = (() => {
2671
+ const { crypto: crypto4 } = globalThis;
2672
+ if (crypto4 != null && typeof crypto4.getRandomValues === "function") {
2673
+ return (byteLength) => {
2674
+ return crypto4.getRandomValues(webByteUtils.allocate(byteLength));
2675
+ };
2676
+ } else {
2677
+ if (isReactNative()) {
2678
+ const { console: console2 } = globalThis;
2679
+ console2?.warn?.("BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.");
2680
+ }
2681
+ return webMathRandomBytes;
2682
+ }
2683
+ })();
2684
+ var HEX_DIGIT = /(\d|[a-f])/i;
2685
+ var webByteUtils = {
2686
+ toLocalBufferType(potentialUint8array) {
2687
+ const stringTag = potentialUint8array?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialUint8array);
2688
+ if (stringTag === "Uint8Array") {
2689
+ return potentialUint8array;
2690
+ }
2691
+ if (ArrayBuffer.isView(potentialUint8array)) {
2692
+ return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength));
2693
+ }
2694
+ if (stringTag === "ArrayBuffer" || stringTag === "SharedArrayBuffer" || stringTag === "[object ArrayBuffer]" || stringTag === "[object SharedArrayBuffer]") {
2695
+ return new Uint8Array(potentialUint8array);
2696
+ }
2697
+ throw new BSONError(`Cannot make a Uint8Array from passed potentialBuffer.`);
2698
+ },
2699
+ allocate(size) {
2700
+ if (typeof size !== "number") {
2701
+ throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`);
2702
+ }
2703
+ return new Uint8Array(size);
2704
+ },
2705
+ allocateUnsafe(size) {
2706
+ return webByteUtils.allocate(size);
2707
+ },
2708
+ equals(a, b) {
2709
+ if (a.byteLength !== b.byteLength) {
2710
+ return false;
2711
+ }
2712
+ for (let i = 0; i < a.byteLength; i++) {
2713
+ if (a[i] !== b[i]) {
2714
+ return false;
2715
+ }
2716
+ }
2717
+ return true;
2718
+ },
2719
+ fromNumberArray(array) {
2720
+ return Uint8Array.from(array);
2721
+ },
2722
+ fromBase64(base64) {
2723
+ return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
2724
+ },
2725
+ toBase64(uint8array) {
2726
+ return btoa(webByteUtils.toISO88591(uint8array));
2727
+ },
2728
+ fromISO88591(codePoints) {
2729
+ return Uint8Array.from(codePoints, (c) => c.charCodeAt(0) & 255);
2730
+ },
2731
+ toISO88591(uint8array) {
2732
+ return Array.from(Uint16Array.from(uint8array), (b) => String.fromCharCode(b)).join("");
2733
+ },
2734
+ fromHex(hex) {
2735
+ const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1);
2736
+ const buffer2 = [];
2737
+ for (let i = 0; i < evenLengthHex.length; i += 2) {
2738
+ const firstDigit = evenLengthHex[i];
2739
+ const secondDigit = evenLengthHex[i + 1];
2740
+ if (!HEX_DIGIT.test(firstDigit)) {
2741
+ break;
2742
+ }
2743
+ if (!HEX_DIGIT.test(secondDigit)) {
2744
+ break;
2745
+ }
2746
+ const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16);
2747
+ buffer2.push(hexDigit);
2748
+ }
2749
+ return Uint8Array.from(buffer2);
2750
+ },
2751
+ toHex(uint8array) {
2752
+ return Array.from(uint8array, (byte) => byte.toString(16).padStart(2, "0")).join("");
2753
+ },
2754
+ toUTF8(uint8array, start, end, fatal) {
2755
+ const basicLatin = end - start <= 20 ? tryReadBasicLatin(uint8array, start, end) : null;
2756
+ if (basicLatin != null) {
2757
+ return basicLatin;
2758
+ }
2759
+ return parseUtf8(uint8array, start, end, fatal);
2760
+ },
2761
+ utf8ByteLength(input) {
2762
+ return new TextEncoder().encode(input).byteLength;
2763
+ },
2764
+ encodeUTF8Into(uint8array, source, byteOffset) {
2765
+ const bytes = new TextEncoder().encode(source);
2766
+ uint8array.set(bytes, byteOffset);
2767
+ return bytes.byteLength;
2768
+ },
2769
+ randomBytes: webRandomBytes,
2770
+ swap32(buffer2) {
2771
+ if (buffer2.length % 4 !== 0) {
2772
+ throw new RangeError("Buffer size must be a multiple of 32-bits");
2773
+ }
2774
+ for (let i = 0; i < buffer2.length; i += 4) {
2775
+ const byte0 = buffer2[i];
2776
+ const byte1 = buffer2[i + 1];
2777
+ const byte2 = buffer2[i + 2];
2778
+ const byte3 = buffer2[i + 3];
2779
+ buffer2[i] = byte3;
2780
+ buffer2[i + 1] = byte2;
2781
+ buffer2[i + 2] = byte1;
2782
+ buffer2[i + 3] = byte0;
2783
+ }
2784
+ return buffer2;
2785
+ }
2786
+ };
2787
+ var hasGlobalBuffer = typeof Buffer === "function" && Buffer.prototype?._isBuffer !== true;
2788
+ var ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils;
2789
+ var _BSONValue = class _BSONValue {
2790
+ get [BSON_VERSION_SYMBOL]() {
2791
+ return BSON_MAJOR_VERSION;
2792
+ }
2793
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")](depth, options, inspect) {
2794
+ return this.inspect(depth, options, inspect);
2795
+ }
2796
+ };
2797
+ __name(_BSONValue, "BSONValue");
2798
+ var BSONValue = _BSONValue;
2799
+ var FLOAT = new Float64Array(1);
2800
+ var FLOAT_BYTES = new Uint8Array(FLOAT.buffer, 0, 8);
2801
+ FLOAT[0] = -1;
2802
+ var isBigEndian = FLOAT_BYTES[7] === 0;
2803
+ var NumberUtils = {
2804
+ isBigEndian,
2805
+ getNonnegativeInt32LE(source, offset) {
2806
+ if (source[offset + 3] > 127) {
2807
+ throw new RangeError(`Size cannot be negative at offset: ${offset}`);
2808
+ }
2809
+ return source[offset] | source[offset + 1] << 8 | source[offset + 2] << 16 | source[offset + 3] << 24;
2810
+ },
2811
+ getInt32LE(source, offset) {
2812
+ return source[offset] | source[offset + 1] << 8 | source[offset + 2] << 16 | source[offset + 3] << 24;
2813
+ },
2814
+ getUint32LE(source, offset) {
2815
+ return source[offset] + source[offset + 1] * 256 + source[offset + 2] * 65536 + source[offset + 3] * 16777216;
2816
+ },
2817
+ getUint32BE(source, offset) {
2818
+ return source[offset + 3] + source[offset + 2] * 256 + source[offset + 1] * 65536 + source[offset] * 16777216;
2819
+ },
2820
+ getBigInt64LE(source, offset) {
2821
+ const hi = BigInt(source[offset + 4] + source[offset + 5] * 256 + source[offset + 6] * 65536 + (source[offset + 7] << 24));
2822
+ const lo = BigInt(source[offset] + source[offset + 1] * 256 + source[offset + 2] * 65536 + source[offset + 3] * 16777216);
2823
+ return (hi << BigInt(32)) + lo;
2824
+ },
2825
+ getFloat64LE: isBigEndian ? (source, offset) => {
2826
+ FLOAT_BYTES[7] = source[offset];
2827
+ FLOAT_BYTES[6] = source[offset + 1];
2828
+ FLOAT_BYTES[5] = source[offset + 2];
2829
+ FLOAT_BYTES[4] = source[offset + 3];
2830
+ FLOAT_BYTES[3] = source[offset + 4];
2831
+ FLOAT_BYTES[2] = source[offset + 5];
2832
+ FLOAT_BYTES[1] = source[offset + 6];
2833
+ FLOAT_BYTES[0] = source[offset + 7];
2834
+ return FLOAT[0];
2835
+ } : (source, offset) => {
2836
+ FLOAT_BYTES[0] = source[offset];
2837
+ FLOAT_BYTES[1] = source[offset + 1];
2838
+ FLOAT_BYTES[2] = source[offset + 2];
2839
+ FLOAT_BYTES[3] = source[offset + 3];
2840
+ FLOAT_BYTES[4] = source[offset + 4];
2841
+ FLOAT_BYTES[5] = source[offset + 5];
2842
+ FLOAT_BYTES[6] = source[offset + 6];
2843
+ FLOAT_BYTES[7] = source[offset + 7];
2844
+ return FLOAT[0];
2845
+ },
2846
+ setInt32BE(destination, offset, value) {
2847
+ destination[offset + 3] = value;
2848
+ value >>>= 8;
2849
+ destination[offset + 2] = value;
2850
+ value >>>= 8;
2851
+ destination[offset + 1] = value;
2852
+ value >>>= 8;
2853
+ destination[offset] = value;
2854
+ return 4;
2855
+ },
2856
+ setInt32LE(destination, offset, value) {
2857
+ destination[offset] = value;
2858
+ value >>>= 8;
2859
+ destination[offset + 1] = value;
2860
+ value >>>= 8;
2861
+ destination[offset + 2] = value;
2862
+ value >>>= 8;
2863
+ destination[offset + 3] = value;
2864
+ return 4;
2865
+ },
2866
+ setBigInt64LE(destination, offset, value) {
2867
+ const mask32bits = BigInt(4294967295);
2868
+ let lo = Number(value & mask32bits);
2869
+ destination[offset] = lo;
2870
+ lo >>= 8;
2871
+ destination[offset + 1] = lo;
2872
+ lo >>= 8;
2873
+ destination[offset + 2] = lo;
2874
+ lo >>= 8;
2875
+ destination[offset + 3] = lo;
2876
+ let hi = Number(value >> BigInt(32) & mask32bits);
2877
+ destination[offset + 4] = hi;
2878
+ hi >>= 8;
2879
+ destination[offset + 5] = hi;
2880
+ hi >>= 8;
2881
+ destination[offset + 6] = hi;
2882
+ hi >>= 8;
2883
+ destination[offset + 7] = hi;
2884
+ return 8;
2885
+ },
2886
+ setFloat64LE: isBigEndian ? (destination, offset, value) => {
2887
+ FLOAT[0] = value;
2888
+ destination[offset] = FLOAT_BYTES[7];
2889
+ destination[offset + 1] = FLOAT_BYTES[6];
2890
+ destination[offset + 2] = FLOAT_BYTES[5];
2891
+ destination[offset + 3] = FLOAT_BYTES[4];
2892
+ destination[offset + 4] = FLOAT_BYTES[3];
2893
+ destination[offset + 5] = FLOAT_BYTES[2];
2894
+ destination[offset + 6] = FLOAT_BYTES[1];
2895
+ destination[offset + 7] = FLOAT_BYTES[0];
2896
+ return 8;
2897
+ } : (destination, offset, value) => {
2898
+ FLOAT[0] = value;
2899
+ destination[offset] = FLOAT_BYTES[0];
2900
+ destination[offset + 1] = FLOAT_BYTES[1];
2901
+ destination[offset + 2] = FLOAT_BYTES[2];
2902
+ destination[offset + 3] = FLOAT_BYTES[3];
2903
+ destination[offset + 4] = FLOAT_BYTES[4];
2904
+ destination[offset + 5] = FLOAT_BYTES[5];
2905
+ destination[offset + 6] = FLOAT_BYTES[6];
2906
+ destination[offset + 7] = FLOAT_BYTES[7];
2907
+ return 8;
2908
+ }
2909
+ };
2910
+ var _Binary = class _Binary extends BSONValue {
2911
+ get _bsontype() {
2912
+ return "Binary";
2913
+ }
2914
+ constructor(buffer2, subType) {
2915
+ super();
2916
+ if (!(buffer2 == null) && typeof buffer2 === "string" && !ArrayBuffer.isView(buffer2) && !isAnyArrayBuffer(buffer2) && !Array.isArray(buffer2)) {
2917
+ throw new BSONError("Binary can only be constructed from Uint8Array or number[]");
2918
+ }
2919
+ this.sub_type = subType ?? _Binary.BSON_BINARY_SUBTYPE_DEFAULT;
2920
+ if (buffer2 == null) {
2921
+ this.buffer = ByteUtils.allocate(_Binary.BUFFER_SIZE);
2922
+ this.position = 0;
2923
+ } else {
2924
+ this.buffer = Array.isArray(buffer2) ? ByteUtils.fromNumberArray(buffer2) : ByteUtils.toLocalBufferType(buffer2);
2925
+ this.position = this.buffer.byteLength;
2926
+ }
2927
+ }
2928
+ put(byteValue) {
2929
+ if (typeof byteValue === "string" && byteValue.length !== 1) {
2930
+ throw new BSONError("only accepts single character String");
2931
+ } else if (typeof byteValue !== "number" && byteValue.length !== 1)
2932
+ throw new BSONError("only accepts single character Uint8Array or Array");
2933
+ let decodedByte;
2934
+ if (typeof byteValue === "string") {
2935
+ decodedByte = byteValue.charCodeAt(0);
2936
+ } else if (typeof byteValue === "number") {
2937
+ decodedByte = byteValue;
2938
+ } else {
2939
+ decodedByte = byteValue[0];
2940
+ }
2941
+ if (decodedByte < 0 || decodedByte > 255) {
2942
+ throw new BSONError("only accepts number in a valid unsigned byte range 0-255");
2943
+ }
2944
+ if (this.buffer.byteLength > this.position) {
2945
+ this.buffer[this.position++] = decodedByte;
2946
+ } else {
2947
+ const newSpace = ByteUtils.allocate(_Binary.BUFFER_SIZE + this.buffer.length);
2948
+ newSpace.set(this.buffer, 0);
2949
+ this.buffer = newSpace;
2950
+ this.buffer[this.position++] = decodedByte;
2951
+ }
2952
+ }
2953
+ write(sequence, offset) {
2954
+ offset = typeof offset === "number" ? offset : this.position;
2955
+ if (this.buffer.byteLength < offset + sequence.length) {
2956
+ const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length);
2957
+ newSpace.set(this.buffer, 0);
2958
+ this.buffer = newSpace;
2959
+ }
2960
+ if (ArrayBuffer.isView(sequence)) {
2961
+ this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset);
2962
+ this.position = offset + sequence.byteLength > this.position ? offset + sequence.length : this.position;
2963
+ } else if (typeof sequence === "string") {
2964
+ throw new BSONError("input cannot be string");
2965
+ }
2966
+ }
2967
+ read(position, length) {
2968
+ length = length && length > 0 ? length : this.position;
2969
+ const end = position + length;
2970
+ return this.buffer.subarray(position, end > this.position ? this.position : end);
2971
+ }
2972
+ value() {
2973
+ return this.buffer.length === this.position ? this.buffer : this.buffer.subarray(0, this.position);
2974
+ }
2975
+ length() {
2976
+ return this.position;
2977
+ }
2978
+ toJSON() {
2979
+ return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
2980
+ }
2981
+ toString(encoding) {
2982
+ if (encoding === "hex")
2983
+ return ByteUtils.toHex(this.buffer.subarray(0, this.position));
2984
+ if (encoding === "base64")
2985
+ return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
2986
+ if (encoding === "utf8" || encoding === "utf-8")
2987
+ return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
2988
+ return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
2989
+ }
2990
+ toExtendedJSON(options) {
2991
+ options = options || {};
2992
+ if (this.sub_type === _Binary.SUBTYPE_VECTOR) {
2993
+ validateBinaryVector(this);
2994
+ }
2995
+ const base64String = ByteUtils.toBase64(this.buffer);
2996
+ const subType = Number(this.sub_type).toString(16);
2997
+ if (options.legacy) {
2998
+ return {
2999
+ $binary: base64String,
3000
+ $type: subType.length === 1 ? "0" + subType : subType
3001
+ };
3002
+ }
3003
+ return {
3004
+ $binary: {
3005
+ base64: base64String,
3006
+ subType: subType.length === 1 ? "0" + subType : subType
3007
+ }
3008
+ };
3009
+ }
3010
+ toUUID() {
3011
+ if (this.sub_type === _Binary.SUBTYPE_UUID) {
3012
+ return new UUID(this.buffer.subarray(0, this.position));
3013
+ }
3014
+ throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${_Binary.SUBTYPE_UUID}" is currently supported.`);
3015
+ }
3016
+ static createFromHexString(hex, subType) {
3017
+ return new _Binary(ByteUtils.fromHex(hex), subType);
3018
+ }
3019
+ static createFromBase64(base64, subType) {
3020
+ return new _Binary(ByteUtils.fromBase64(base64), subType);
3021
+ }
3022
+ static fromExtendedJSON(doc, options) {
3023
+ options = options || {};
3024
+ let data;
3025
+ let type;
3026
+ if ("$binary" in doc) {
3027
+ if (options.legacy && typeof doc.$binary === "string" && "$type" in doc) {
3028
+ type = doc.$type ? parseInt(doc.$type, 16) : 0;
3029
+ data = ByteUtils.fromBase64(doc.$binary);
3030
+ } else {
3031
+ if (typeof doc.$binary !== "string") {
3032
+ type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
3033
+ data = ByteUtils.fromBase64(doc.$binary.base64);
3034
+ }
3035
+ }
3036
+ } else if ("$uuid" in doc) {
3037
+ type = 4;
3038
+ data = UUID.bytesFromString(doc.$uuid);
3039
+ }
3040
+ if (!data) {
3041
+ throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`);
3042
+ }
3043
+ return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new _Binary(data, type);
3044
+ }
3045
+ inspect(depth, options, inspect) {
3046
+ inspect ?? (inspect = defaultInspect);
3047
+ const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position));
3048
+ const base64Arg = inspect(base64, options);
3049
+ const subTypeArg = inspect(this.sub_type, options);
3050
+ return `Binary.createFromBase64(${base64Arg}, ${subTypeArg})`;
3051
+ }
3052
+ toInt8Array() {
3053
+ if (this.sub_type !== _Binary.SUBTYPE_VECTOR) {
3054
+ throw new BSONError("Binary sub_type is not Vector");
3055
+ }
3056
+ if (this.buffer[0] !== _Binary.VECTOR_TYPE.Int8) {
3057
+ throw new BSONError("Binary datatype field is not Int8");
3058
+ }
3059
+ validateBinaryVector(this);
3060
+ return new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
3061
+ }
3062
+ toFloat32Array() {
3063
+ if (this.sub_type !== _Binary.SUBTYPE_VECTOR) {
3064
+ throw new BSONError("Binary sub_type is not Vector");
3065
+ }
3066
+ if (this.buffer[0] !== _Binary.VECTOR_TYPE.Float32) {
3067
+ throw new BSONError("Binary datatype field is not Float32");
3068
+ }
3069
+ validateBinaryVector(this);
3070
+ const floatBytes = new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
3071
+ if (NumberUtils.isBigEndian)
3072
+ ByteUtils.swap32(floatBytes);
3073
+ return new Float32Array(floatBytes.buffer);
3074
+ }
3075
+ toPackedBits() {
3076
+ if (this.sub_type !== _Binary.SUBTYPE_VECTOR) {
3077
+ throw new BSONError("Binary sub_type is not Vector");
3078
+ }
3079
+ if (this.buffer[0] !== _Binary.VECTOR_TYPE.PackedBit) {
3080
+ throw new BSONError("Binary datatype field is not packed bit");
3081
+ }
3082
+ validateBinaryVector(this);
3083
+ return new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
3084
+ }
3085
+ toBits() {
3086
+ if (this.sub_type !== _Binary.SUBTYPE_VECTOR) {
3087
+ throw new BSONError("Binary sub_type is not Vector");
3088
+ }
3089
+ if (this.buffer[0] !== _Binary.VECTOR_TYPE.PackedBit) {
3090
+ throw new BSONError("Binary datatype field is not packed bit");
3091
+ }
3092
+ validateBinaryVector(this);
3093
+ const byteCount = this.length() - 2;
3094
+ const bitCount = byteCount * 8 - this.buffer[1];
3095
+ const bits = new Int8Array(bitCount);
3096
+ for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {
3097
+ const byteOffset = bitOffset / 8 | 0;
3098
+ const byte = this.buffer[byteOffset + 2];
3099
+ const shift = 7 - bitOffset % 8;
3100
+ const bit = byte >> shift & 1;
3101
+ bits[bitOffset] = bit;
3102
+ }
3103
+ return bits;
3104
+ }
3105
+ static fromInt8Array(array) {
3106
+ const buffer2 = ByteUtils.allocate(array.byteLength + 2);
3107
+ buffer2[0] = _Binary.VECTOR_TYPE.Int8;
3108
+ buffer2[1] = 0;
3109
+ const intBytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
3110
+ buffer2.set(intBytes, 2);
3111
+ const bin = new this(buffer2, this.SUBTYPE_VECTOR);
3112
+ validateBinaryVector(bin);
3113
+ return bin;
3114
+ }
3115
+ static fromFloat32Array(array) {
3116
+ const binaryBytes = ByteUtils.allocate(array.byteLength + 2);
3117
+ binaryBytes[0] = _Binary.VECTOR_TYPE.Float32;
3118
+ binaryBytes[1] = 0;
3119
+ const floatBytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
3120
+ binaryBytes.set(floatBytes, 2);
3121
+ if (NumberUtils.isBigEndian)
3122
+ ByteUtils.swap32(new Uint8Array(binaryBytes.buffer, 2));
3123
+ const bin = new this(binaryBytes, this.SUBTYPE_VECTOR);
3124
+ validateBinaryVector(bin);
3125
+ return bin;
3126
+ }
3127
+ static fromPackedBits(array, padding = 0) {
3128
+ const buffer2 = ByteUtils.allocate(array.byteLength + 2);
3129
+ buffer2[0] = _Binary.VECTOR_TYPE.PackedBit;
3130
+ buffer2[1] = padding;
3131
+ buffer2.set(array, 2);
3132
+ const bin = new this(buffer2, this.SUBTYPE_VECTOR);
3133
+ validateBinaryVector(bin);
3134
+ return bin;
3135
+ }
3136
+ static fromBits(bits) {
3137
+ const byteLength = bits.length + 7 >>> 3;
3138
+ const bytes = new Uint8Array(byteLength + 2);
3139
+ bytes[0] = _Binary.VECTOR_TYPE.PackedBit;
3140
+ const remainder = bits.length % 8;
3141
+ bytes[1] = remainder === 0 ? 0 : 8 - remainder;
3142
+ for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {
3143
+ const byteOffset = bitOffset >>> 3;
3144
+ const bit = bits[bitOffset];
3145
+ if (bit !== 0 && bit !== 1) {
3146
+ throw new BSONError(`Invalid bit value at ${bitOffset}: must be 0 or 1, found ${bits[bitOffset]}`);
3147
+ }
3148
+ if (bit === 0)
3149
+ continue;
3150
+ const shift = 7 - bitOffset % 8;
3151
+ bytes[byteOffset + 2] |= bit << shift;
3152
+ }
3153
+ return new this(bytes, _Binary.SUBTYPE_VECTOR);
3154
+ }
3155
+ };
3156
+ __name(_Binary, "Binary");
3157
+ var Binary = _Binary;
3158
+ Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0;
3159
+ Binary.BUFFER_SIZE = 256;
3160
+ Binary.SUBTYPE_DEFAULT = 0;
3161
+ Binary.SUBTYPE_FUNCTION = 1;
3162
+ Binary.SUBTYPE_BYTE_ARRAY = 2;
3163
+ Binary.SUBTYPE_UUID_OLD = 3;
3164
+ Binary.SUBTYPE_UUID = 4;
3165
+ Binary.SUBTYPE_MD5 = 5;
3166
+ Binary.SUBTYPE_ENCRYPTED = 6;
3167
+ Binary.SUBTYPE_COLUMN = 7;
3168
+ Binary.SUBTYPE_SENSITIVE = 8;
3169
+ Binary.SUBTYPE_VECTOR = 9;
3170
+ Binary.SUBTYPE_USER_DEFINED = 128;
3171
+ Binary.VECTOR_TYPE = Object.freeze({
3172
+ Int8: 3,
3173
+ Float32: 39,
3174
+ PackedBit: 16
3175
+ });
3176
+ function validateBinaryVector(vector) {
3177
+ if (vector.sub_type !== Binary.SUBTYPE_VECTOR)
3178
+ return;
3179
+ const size = vector.position;
3180
+ const datatype = vector.buffer[0];
3181
+ const padding = vector.buffer[1];
3182
+ if ((datatype === Binary.VECTOR_TYPE.Float32 || datatype === Binary.VECTOR_TYPE.Int8) && padding !== 0) {
3183
+ throw new BSONError("Invalid Vector: padding must be zero for int8 and float32 vectors");
3184
+ }
3185
+ if (datatype === Binary.VECTOR_TYPE.Float32) {
3186
+ if (size !== 0 && size - 2 !== 0 && (size - 2) % 4 !== 0) {
3187
+ throw new BSONError("Invalid Vector: Float32 vector must contain a multiple of 4 bytes");
3188
+ }
3189
+ }
3190
+ if (datatype === Binary.VECTOR_TYPE.PackedBit && padding !== 0 && size === 2) {
3191
+ throw new BSONError("Invalid Vector: padding must be zero for packed bit vectors that are empty");
3192
+ }
3193
+ if (datatype === Binary.VECTOR_TYPE.PackedBit && padding > 7) {
3194
+ throw new BSONError(`Invalid Vector: padding must be a value between 0 and 7. found: ${padding}`);
3195
+ }
3196
+ }
3197
+ __name(validateBinaryVector, "validateBinaryVector");
3198
+ var UUID_BYTE_LENGTH = 16;
3199
+ var UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i;
3200
+ 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;
3201
+ var _UUID = class _UUID extends Binary {
3202
+ constructor(input) {
3203
+ let bytes;
3204
+ if (input == null) {
3205
+ bytes = _UUID.generate();
3206
+ } else if (input instanceof _UUID) {
3207
+ bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));
3208
+ } else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) {
3209
+ bytes = ByteUtils.toLocalBufferType(input);
3210
+ } else if (typeof input === "string") {
3211
+ bytes = _UUID.bytesFromString(input);
3212
+ } else {
3213
+ 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).");
3214
+ }
3215
+ super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW);
3216
+ }
3217
+ get id() {
3218
+ return this.buffer;
3219
+ }
3220
+ set id(value) {
3221
+ this.buffer = value;
3222
+ }
3223
+ toHexString(includeDashes = true) {
3224
+ if (includeDashes) {
3225
+ return [
3226
+ ByteUtils.toHex(this.buffer.subarray(0, 4)),
3227
+ ByteUtils.toHex(this.buffer.subarray(4, 6)),
3228
+ ByteUtils.toHex(this.buffer.subarray(6, 8)),
3229
+ ByteUtils.toHex(this.buffer.subarray(8, 10)),
3230
+ ByteUtils.toHex(this.buffer.subarray(10, 16))
3231
+ ].join("-");
3232
+ }
3233
+ return ByteUtils.toHex(this.buffer);
3234
+ }
3235
+ toString(encoding) {
3236
+ if (encoding === "hex")
3237
+ return ByteUtils.toHex(this.id);
3238
+ if (encoding === "base64")
3239
+ return ByteUtils.toBase64(this.id);
3240
+ return this.toHexString();
3241
+ }
3242
+ toJSON() {
3243
+ return this.toHexString();
3244
+ }
3245
+ equals(otherId) {
3246
+ if (!otherId) {
3247
+ return false;
3248
+ }
3249
+ if (otherId instanceof _UUID) {
3250
+ return ByteUtils.equals(otherId.id, this.id);
3251
+ }
3252
+ try {
3253
+ return ByteUtils.equals(new _UUID(otherId).id, this.id);
3254
+ } catch {
3255
+ return false;
3256
+ }
3257
+ }
3258
+ toBinary() {
3259
+ return new Binary(this.id, Binary.SUBTYPE_UUID);
3260
+ }
3261
+ static generate() {
3262
+ const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH);
3263
+ bytes[6] = bytes[6] & 15 | 64;
3264
+ bytes[8] = bytes[8] & 63 | 128;
3265
+ return bytes;
3266
+ }
3267
+ static isValid(input) {
3268
+ if (!input) {
3269
+ return false;
3270
+ }
3271
+ if (typeof input === "string") {
3272
+ return _UUID.isValidUUIDString(input);
3273
+ }
3274
+ if (isUint8Array(input)) {
3275
+ return input.byteLength === UUID_BYTE_LENGTH;
3276
+ }
3277
+ return input._bsontype === "Binary" && input.sub_type === this.SUBTYPE_UUID && input.buffer.byteLength === 16;
3278
+ }
3279
+ static createFromHexString(hexString) {
3280
+ const buffer2 = _UUID.bytesFromString(hexString);
3281
+ return new _UUID(buffer2);
3282
+ }
3283
+ static createFromBase64(base64) {
3284
+ return new _UUID(ByteUtils.fromBase64(base64));
3285
+ }
3286
+ static bytesFromString(representation) {
3287
+ if (!_UUID.isValidUUIDString(representation)) {
3288
+ throw new BSONError("UUID string representation must be 32 hex digits or canonical hyphenated representation");
3289
+ }
3290
+ return ByteUtils.fromHex(representation.replace(/-/g, ""));
3291
+ }
3292
+ static isValidUUIDString(representation) {
3293
+ return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation);
3294
+ }
3295
+ inspect(depth, options, inspect) {
3296
+ inspect ?? (inspect = defaultInspect);
3297
+ return `new UUID(${inspect(this.toHexString(), options)})`;
3298
+ }
3299
+ };
3300
+ __name(_UUID, "UUID");
3301
+ var UUID = _UUID;
3302
+ var _Code = class _Code extends BSONValue {
3303
+ get _bsontype() {
3304
+ return "Code";
3305
+ }
3306
+ constructor(code, scope) {
3307
+ super();
3308
+ this.code = code.toString();
3309
+ this.scope = scope ?? null;
3310
+ }
3311
+ toJSON() {
3312
+ if (this.scope != null) {
3313
+ return { code: this.code, scope: this.scope };
3314
+ }
3315
+ return { code: this.code };
3316
+ }
3317
+ toExtendedJSON() {
3318
+ if (this.scope) {
3319
+ return { $code: this.code, $scope: this.scope };
3320
+ }
3321
+ return { $code: this.code };
3322
+ }
3323
+ static fromExtendedJSON(doc) {
3324
+ return new _Code(doc.$code, doc.$scope);
3325
+ }
3326
+ inspect(depth, options, inspect) {
3327
+ inspect ?? (inspect = defaultInspect);
3328
+ let parametersString = inspect(this.code, options);
3329
+ const multiLineFn = parametersString.includes("\n");
3330
+ if (this.scope != null) {
3331
+ parametersString += `,${multiLineFn ? "\n" : " "}${inspect(this.scope, options)}`;
3332
+ }
3333
+ const endingNewline = multiLineFn && this.scope === null;
3334
+ return `new Code(${multiLineFn ? "\n" : ""}${parametersString}${endingNewline ? "\n" : ""})`;
3335
+ }
3336
+ };
3337
+ __name(_Code, "Code");
3338
+ var Code = _Code;
3339
+ function isDBRefLike(value) {
3340
+ 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");
3341
+ }
3342
+ __name(isDBRefLike, "isDBRefLike");
3343
+ var _DBRef = class _DBRef extends BSONValue {
3344
+ get _bsontype() {
3345
+ return "DBRef";
3346
+ }
3347
+ constructor(collection, oid, db, fields) {
3348
+ super();
3349
+ const parts = collection.split(".");
3350
+ if (parts.length === 2) {
3351
+ db = parts.shift();
3352
+ collection = parts.shift();
3353
+ }
3354
+ this.collection = collection;
3355
+ this.oid = oid;
3356
+ this.db = db;
3357
+ this.fields = fields || {};
3358
+ }
3359
+ get namespace() {
3360
+ return this.collection;
3361
+ }
3362
+ set namespace(value) {
3363
+ this.collection = value;
3364
+ }
3365
+ toJSON() {
3366
+ const o = Object.assign({
3367
+ $ref: this.collection,
3368
+ $id: this.oid
3369
+ }, this.fields);
3370
+ if (this.db != null)
3371
+ o.$db = this.db;
3372
+ return o;
3373
+ }
3374
+ toExtendedJSON(options) {
3375
+ options = options || {};
3376
+ let o = {
3377
+ $ref: this.collection,
3378
+ $id: this.oid
3379
+ };
3380
+ if (options.legacy) {
3381
+ return o;
3382
+ }
3383
+ if (this.db)
3384
+ o.$db = this.db;
3385
+ o = Object.assign(o, this.fields);
3386
+ return o;
3387
+ }
3388
+ static fromExtendedJSON(doc) {
3389
+ const copy = Object.assign({}, doc);
3390
+ delete copy.$ref;
3391
+ delete copy.$id;
3392
+ delete copy.$db;
3393
+ return new _DBRef(doc.$ref, doc.$id, doc.$db, copy);
3394
+ }
3395
+ inspect(depth, options, inspect) {
3396
+ inspect ?? (inspect = defaultInspect);
3397
+ const args = [
3398
+ inspect(this.namespace, options),
3399
+ inspect(this.oid, options),
3400
+ ...this.db ? [inspect(this.db, options)] : [],
3401
+ ...Object.keys(this.fields).length > 0 ? [inspect(this.fields, options)] : []
3402
+ ];
3403
+ args[1] = inspect === defaultInspect ? `new ObjectId(${args[1]})` : args[1];
3404
+ return `new DBRef(${args.join(", ")})`;
3405
+ }
3406
+ };
3407
+ __name(_DBRef, "DBRef");
3408
+ var DBRef = _DBRef;
3409
+ function removeLeadingZerosAndExplicitPlus(str) {
3410
+ if (str === "") {
3411
+ return str;
3412
+ }
3413
+ let startIndex = 0;
3414
+ const isNegative = str[startIndex] === "-";
3415
+ const isExplicitlyPositive = str[startIndex] === "+";
3416
+ if (isExplicitlyPositive || isNegative) {
3417
+ startIndex += 1;
3418
+ }
3419
+ let foundInsignificantZero = false;
3420
+ for (; startIndex < str.length && str[startIndex] === "0"; ++startIndex) {
3421
+ foundInsignificantZero = true;
3422
+ }
3423
+ if (!foundInsignificantZero) {
3424
+ return isExplicitlyPositive ? str.slice(1) : str;
3425
+ }
3426
+ return `${isNegative ? "-" : ""}${str.length === startIndex ? "0" : str.slice(startIndex)}`;
3427
+ }
3428
+ __name(removeLeadingZerosAndExplicitPlus, "removeLeadingZerosAndExplicitPlus");
3429
+ function validateStringCharacters(str, radix) {
3430
+ radix = radix ?? 10;
3431
+ const validCharacters = "0123456789abcdefghijklmnopqrstuvwxyz".slice(0, radix);
3432
+ const regex = new RegExp(`[^-+${validCharacters}]`, "i");
3433
+ return regex.test(str) ? false : str;
3434
+ }
3435
+ __name(validateStringCharacters, "validateStringCharacters");
3436
+ var wasm = void 0;
3437
+ try {
3438
+ 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;
3439
+ } catch {
3440
+ }
3441
+ var TWO_PWR_16_DBL = 1 << 16;
3442
+ var TWO_PWR_24_DBL = 1 << 24;
3443
+ var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
3444
+ var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
3445
+ var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
3446
+ var INT_CACHE = {};
3447
+ var UINT_CACHE = {};
3448
+ var MAX_INT64_STRING_LENGTH = 20;
3449
+ var DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/;
3450
+ var _Long = class _Long extends BSONValue {
3451
+ get _bsontype() {
3452
+ return "Long";
3453
+ }
3454
+ get __isLong__() {
3455
+ return true;
3456
+ }
3457
+ constructor(lowOrValue = 0, highOrUnsigned, unsigned) {
3458
+ super();
3459
+ const unsignedBool = typeof highOrUnsigned === "boolean" ? highOrUnsigned : Boolean(unsigned);
3460
+ const high = typeof highOrUnsigned === "number" ? highOrUnsigned : 0;
3461
+ const res = typeof lowOrValue === "string" ? _Long.fromString(lowOrValue, unsignedBool) : typeof lowOrValue === "bigint" ? _Long.fromBigInt(lowOrValue, unsignedBool) : { low: lowOrValue | 0, high: high | 0, unsigned: unsignedBool };
3462
+ this.low = res.low;
3463
+ this.high = res.high;
3464
+ this.unsigned = res.unsigned;
3465
+ }
3466
+ static fromBits(lowBits, highBits, unsigned) {
3467
+ return new _Long(lowBits, highBits, unsigned);
3468
+ }
3469
+ static fromInt(value, unsigned) {
3470
+ let obj, cachedObj, cache;
3471
+ if (unsigned) {
3472
+ value >>>= 0;
3473
+ if (cache = 0 <= value && value < 256) {
3474
+ cachedObj = UINT_CACHE[value];
3475
+ if (cachedObj)
3476
+ return cachedObj;
3477
+ }
3478
+ obj = _Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true);
3479
+ if (cache)
3480
+ UINT_CACHE[value] = obj;
3481
+ return obj;
3482
+ } else {
3483
+ value |= 0;
3484
+ if (cache = -128 <= value && value < 128) {
3485
+ cachedObj = INT_CACHE[value];
3486
+ if (cachedObj)
3487
+ return cachedObj;
3488
+ }
3489
+ obj = _Long.fromBits(value, value < 0 ? -1 : 0, false);
3490
+ if (cache)
3491
+ INT_CACHE[value] = obj;
3492
+ return obj;
3493
+ }
3494
+ }
3495
+ static fromNumber(value, unsigned) {
3496
+ if (isNaN(value))
3497
+ return unsigned ? _Long.UZERO : _Long.ZERO;
3498
+ if (unsigned) {
3499
+ if (value < 0)
3500
+ return _Long.UZERO;
3501
+ if (value >= TWO_PWR_64_DBL)
3502
+ return _Long.MAX_UNSIGNED_VALUE;
3503
+ } else {
3504
+ if (value <= -9223372036854776e3)
3505
+ return _Long.MIN_VALUE;
3506
+ if (value + 1 >= TWO_PWR_63_DBL)
3507
+ return _Long.MAX_VALUE;
3508
+ }
3509
+ if (value < 0)
3510
+ return _Long.fromNumber(-value, unsigned).neg();
3511
+ return _Long.fromBits(value % TWO_PWR_32_DBL | 0, value / TWO_PWR_32_DBL | 0, unsigned);
3512
+ }
3513
+ static fromBigInt(value, unsigned) {
3514
+ const FROM_BIGINT_BIT_MASK = BigInt(4294967295);
3515
+ const FROM_BIGINT_BIT_SHIFT = BigInt(32);
3516
+ return new _Long(Number(value & FROM_BIGINT_BIT_MASK), Number(value >> FROM_BIGINT_BIT_SHIFT & FROM_BIGINT_BIT_MASK), unsigned);
3517
+ }
3518
+ static _fromString(str, unsigned, radix) {
3519
+ if (str.length === 0)
3520
+ throw new BSONError("empty string");
3521
+ if (radix < 2 || 36 < radix)
3522
+ throw new BSONError("radix");
3523
+ let p;
3524
+ if ((p = str.indexOf("-")) > 0)
3525
+ throw new BSONError("interior hyphen");
3526
+ else if (p === 0) {
3527
+ return _Long._fromString(str.substring(1), unsigned, radix).neg();
3528
+ }
3529
+ const radixToPower = _Long.fromNumber(Math.pow(radix, 8));
3530
+ let result = _Long.ZERO;
3531
+ for (let i = 0; i < str.length; i += 8) {
3532
+ const size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix);
3533
+ if (size < 8) {
3534
+ const power = _Long.fromNumber(Math.pow(radix, size));
3535
+ result = result.mul(power).add(_Long.fromNumber(value));
3536
+ } else {
3537
+ result = result.mul(radixToPower);
3538
+ result = result.add(_Long.fromNumber(value));
3539
+ }
3540
+ }
3541
+ result.unsigned = unsigned;
3542
+ return result;
3543
+ }
3544
+ static fromStringStrict(str, unsignedOrRadix, radix) {
3545
+ let unsigned = false;
3546
+ if (typeof unsignedOrRadix === "number") {
3547
+ radix = unsignedOrRadix, unsignedOrRadix = false;
3548
+ } else {
3549
+ unsigned = !!unsignedOrRadix;
3550
+ }
3551
+ radix ?? (radix = 10);
3552
+ if (str.trim() !== str) {
3553
+ throw new BSONError(`Input: '${str}' contains leading and/or trailing whitespace`);
3554
+ }
3555
+ if (!validateStringCharacters(str, radix)) {
3556
+ throw new BSONError(`Input: '${str}' contains invalid characters for radix: ${radix}`);
3557
+ }
3558
+ const cleanedStr = removeLeadingZerosAndExplicitPlus(str);
3559
+ const result = _Long._fromString(cleanedStr, unsigned, radix);
3560
+ if (result.toString(radix).toLowerCase() !== cleanedStr.toLowerCase()) {
3561
+ throw new BSONError(`Input: ${str} is not representable as ${result.unsigned ? "an unsigned" : "a signed"} 64-bit Long ${radix != null ? `with radix: ${radix}` : ""}`);
3562
+ }
3563
+ return result;
3564
+ }
3565
+ static fromString(str, unsignedOrRadix, radix) {
3566
+ let unsigned = false;
3567
+ if (typeof unsignedOrRadix === "number") {
3568
+ radix = unsignedOrRadix, unsignedOrRadix = false;
3569
+ } else {
3570
+ unsigned = !!unsignedOrRadix;
3571
+ }
3572
+ radix ?? (radix = 10);
3573
+ if (str === "NaN" && radix < 24) {
3574
+ return _Long.ZERO;
3575
+ } else if ((str === "Infinity" || str === "+Infinity" || str === "-Infinity") && radix < 35) {
3576
+ return _Long.ZERO;
3577
+ }
3578
+ return _Long._fromString(str, unsigned, radix);
3579
+ }
3580
+ static fromBytes(bytes, unsigned, le) {
3581
+ return le ? _Long.fromBytesLE(bytes, unsigned) : _Long.fromBytesBE(bytes, unsigned);
3582
+ }
3583
+ static fromBytesLE(bytes, unsigned) {
3584
+ 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);
3585
+ }
3586
+ static fromBytesBE(bytes, unsigned) {
3587
+ 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);
3588
+ }
3589
+ static isLong(value) {
3590
+ return value != null && typeof value === "object" && "__isLong__" in value && value.__isLong__ === true;
3591
+ }
3592
+ static fromValue(val, unsigned) {
3593
+ if (typeof val === "number")
3594
+ return _Long.fromNumber(val, unsigned);
3595
+ if (typeof val === "string")
3596
+ return _Long.fromString(val, unsigned);
3597
+ return _Long.fromBits(val.low, val.high, typeof unsigned === "boolean" ? unsigned : val.unsigned);
3598
+ }
3599
+ add(addend) {
3600
+ if (!_Long.isLong(addend))
3601
+ addend = _Long.fromValue(addend);
3602
+ const a48 = this.high >>> 16;
3603
+ const a32 = this.high & 65535;
3604
+ const a16 = this.low >>> 16;
3605
+ const a00 = this.low & 65535;
3606
+ const b48 = addend.high >>> 16;
3607
+ const b32 = addend.high & 65535;
3608
+ const b16 = addend.low >>> 16;
3609
+ const b00 = addend.low & 65535;
3610
+ let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
3611
+ c00 += a00 + b00;
3612
+ c16 += c00 >>> 16;
3613
+ c00 &= 65535;
3614
+ c16 += a16 + b16;
3615
+ c32 += c16 >>> 16;
3616
+ c16 &= 65535;
3617
+ c32 += a32 + b32;
3618
+ c48 += c32 >>> 16;
3619
+ c32 &= 65535;
3620
+ c48 += a48 + b48;
3621
+ c48 &= 65535;
3622
+ return _Long.fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
3623
+ }
3624
+ and(other) {
3625
+ if (!_Long.isLong(other))
3626
+ other = _Long.fromValue(other);
3627
+ return _Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned);
3628
+ }
3629
+ compare(other) {
3630
+ if (!_Long.isLong(other))
3631
+ other = _Long.fromValue(other);
3632
+ if (this.eq(other))
3633
+ return 0;
3634
+ const thisNeg = this.isNegative(), otherNeg = other.isNegative();
3635
+ if (thisNeg && !otherNeg)
3636
+ return -1;
3637
+ if (!thisNeg && otherNeg)
3638
+ return 1;
3639
+ if (!this.unsigned)
3640
+ return this.sub(other).isNegative() ? -1 : 1;
3641
+ return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1;
3642
+ }
3643
+ comp(other) {
3644
+ return this.compare(other);
3645
+ }
3646
+ divide(divisor) {
3647
+ if (!_Long.isLong(divisor))
3648
+ divisor = _Long.fromValue(divisor);
3649
+ if (divisor.isZero())
3650
+ throw new BSONError("division by zero");
3651
+ if (wasm) {
3652
+ if (!this.unsigned && this.high === -2147483648 && divisor.low === -1 && divisor.high === -1) {
3653
+ return this;
3654
+ }
3655
+ const low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high);
3656
+ return _Long.fromBits(low, wasm.get_high(), this.unsigned);
3657
+ }
3658
+ if (this.isZero())
3659
+ return this.unsigned ? _Long.UZERO : _Long.ZERO;
3660
+ let approx, rem, res;
3661
+ if (!this.unsigned) {
3662
+ if (this.eq(_Long.MIN_VALUE)) {
3663
+ if (divisor.eq(_Long.ONE) || divisor.eq(_Long.NEG_ONE))
3664
+ return _Long.MIN_VALUE;
3665
+ else if (divisor.eq(_Long.MIN_VALUE))
3666
+ return _Long.ONE;
3667
+ else {
3668
+ const halfThis = this.shr(1);
3669
+ approx = halfThis.div(divisor).shl(1);
3670
+ if (approx.eq(_Long.ZERO)) {
3671
+ return divisor.isNegative() ? _Long.ONE : _Long.NEG_ONE;
3672
+ } else {
3673
+ rem = this.sub(divisor.mul(approx));
3674
+ res = approx.add(rem.div(divisor));
3675
+ return res;
3676
+ }
3677
+ }
3678
+ } else if (divisor.eq(_Long.MIN_VALUE))
3679
+ return this.unsigned ? _Long.UZERO : _Long.ZERO;
3680
+ if (this.isNegative()) {
3681
+ if (divisor.isNegative())
3682
+ return this.neg().div(divisor.neg());
3683
+ return this.neg().div(divisor).neg();
3684
+ } else if (divisor.isNegative())
3685
+ return this.div(divisor.neg()).neg();
3686
+ res = _Long.ZERO;
3687
+ } else {
3688
+ if (!divisor.unsigned)
3689
+ divisor = divisor.toUnsigned();
3690
+ if (divisor.gt(this))
3691
+ return _Long.UZERO;
3692
+ if (divisor.gt(this.shru(1)))
3693
+ return _Long.UONE;
3694
+ res = _Long.UZERO;
3695
+ }
3696
+ rem = this;
3697
+ while (rem.gte(divisor)) {
3698
+ approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
3699
+ const log2 = Math.ceil(Math.log(approx) / Math.LN2);
3700
+ const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);
3701
+ let approxRes = _Long.fromNumber(approx);
3702
+ let approxRem = approxRes.mul(divisor);
3703
+ while (approxRem.isNegative() || approxRem.gt(rem)) {
3704
+ approx -= delta;
3705
+ approxRes = _Long.fromNumber(approx, this.unsigned);
3706
+ approxRem = approxRes.mul(divisor);
3707
+ }
3708
+ if (approxRes.isZero())
3709
+ approxRes = _Long.ONE;
3710
+ res = res.add(approxRes);
3711
+ rem = rem.sub(approxRem);
3712
+ }
3713
+ return res;
3714
+ }
3715
+ div(divisor) {
3716
+ return this.divide(divisor);
3717
+ }
3718
+ equals(other) {
3719
+ if (!_Long.isLong(other))
3720
+ other = _Long.fromValue(other);
3721
+ if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
3722
+ return false;
3723
+ return this.high === other.high && this.low === other.low;
3724
+ }
3725
+ eq(other) {
3726
+ return this.equals(other);
3727
+ }
3728
+ getHighBits() {
3729
+ return this.high;
3730
+ }
3731
+ getHighBitsUnsigned() {
3732
+ return this.high >>> 0;
3733
+ }
3734
+ getLowBits() {
3735
+ return this.low;
3736
+ }
3737
+ getLowBitsUnsigned() {
3738
+ return this.low >>> 0;
3739
+ }
3740
+ getNumBitsAbs() {
3741
+ if (this.isNegative()) {
3742
+ return this.eq(_Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
3743
+ }
3744
+ const val = this.high !== 0 ? this.high : this.low;
3745
+ let bit;
3746
+ for (bit = 31; bit > 0; bit--)
3747
+ if ((val & 1 << bit) !== 0)
3748
+ break;
3749
+ return this.high !== 0 ? bit + 33 : bit + 1;
3750
+ }
3751
+ greaterThan(other) {
3752
+ return this.comp(other) > 0;
3753
+ }
3754
+ gt(other) {
3755
+ return this.greaterThan(other);
3756
+ }
3757
+ greaterThanOrEqual(other) {
3758
+ return this.comp(other) >= 0;
3759
+ }
3760
+ gte(other) {
3761
+ return this.greaterThanOrEqual(other);
3762
+ }
3763
+ ge(other) {
3764
+ return this.greaterThanOrEqual(other);
3765
+ }
3766
+ isEven() {
3767
+ return (this.low & 1) === 0;
3768
+ }
3769
+ isNegative() {
3770
+ return !this.unsigned && this.high < 0;
3771
+ }
3772
+ isOdd() {
3773
+ return (this.low & 1) === 1;
3774
+ }
3775
+ isPositive() {
3776
+ return this.unsigned || this.high >= 0;
3777
+ }
3778
+ isZero() {
3779
+ return this.high === 0 && this.low === 0;
3780
+ }
3781
+ lessThan(other) {
3782
+ return this.comp(other) < 0;
3783
+ }
3784
+ lt(other) {
3785
+ return this.lessThan(other);
3786
+ }
3787
+ lessThanOrEqual(other) {
3788
+ return this.comp(other) <= 0;
3789
+ }
3790
+ lte(other) {
3791
+ return this.lessThanOrEqual(other);
3792
+ }
3793
+ modulo(divisor) {
3794
+ if (!_Long.isLong(divisor))
3795
+ divisor = _Long.fromValue(divisor);
3796
+ if (wasm) {
3797
+ const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high);
3798
+ return _Long.fromBits(low, wasm.get_high(), this.unsigned);
3799
+ }
3800
+ return this.sub(this.div(divisor).mul(divisor));
3801
+ }
3802
+ mod(divisor) {
3803
+ return this.modulo(divisor);
3804
+ }
3805
+ rem(divisor) {
3806
+ return this.modulo(divisor);
3807
+ }
3808
+ multiply(multiplier) {
3809
+ if (this.isZero())
3810
+ return _Long.ZERO;
3811
+ if (!_Long.isLong(multiplier))
3812
+ multiplier = _Long.fromValue(multiplier);
3813
+ if (wasm) {
3814
+ const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
3815
+ return _Long.fromBits(low, wasm.get_high(), this.unsigned);
3816
+ }
3817
+ if (multiplier.isZero())
3818
+ return _Long.ZERO;
3819
+ if (this.eq(_Long.MIN_VALUE))
3820
+ return multiplier.isOdd() ? _Long.MIN_VALUE : _Long.ZERO;
3821
+ if (multiplier.eq(_Long.MIN_VALUE))
3822
+ return this.isOdd() ? _Long.MIN_VALUE : _Long.ZERO;
3823
+ if (this.isNegative()) {
3824
+ if (multiplier.isNegative())
3825
+ return this.neg().mul(multiplier.neg());
3826
+ else
3827
+ return this.neg().mul(multiplier).neg();
3828
+ } else if (multiplier.isNegative())
3829
+ return this.mul(multiplier.neg()).neg();
3830
+ if (this.lt(_Long.TWO_PWR_24) && multiplier.lt(_Long.TWO_PWR_24))
3831
+ return _Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
3832
+ const a48 = this.high >>> 16;
3833
+ const a32 = this.high & 65535;
3834
+ const a16 = this.low >>> 16;
3835
+ const a00 = this.low & 65535;
3836
+ const b48 = multiplier.high >>> 16;
3837
+ const b32 = multiplier.high & 65535;
3838
+ const b16 = multiplier.low >>> 16;
3839
+ const b00 = multiplier.low & 65535;
3840
+ let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
3841
+ c00 += a00 * b00;
3842
+ c16 += c00 >>> 16;
3843
+ c00 &= 65535;
3844
+ c16 += a16 * b00;
3845
+ c32 += c16 >>> 16;
3846
+ c16 &= 65535;
3847
+ c16 += a00 * b16;
3848
+ c32 += c16 >>> 16;
3849
+ c16 &= 65535;
3850
+ c32 += a32 * b00;
3851
+ c48 += c32 >>> 16;
3852
+ c32 &= 65535;
3853
+ c32 += a16 * b16;
3854
+ c48 += c32 >>> 16;
3855
+ c32 &= 65535;
3856
+ c32 += a00 * b32;
3857
+ c48 += c32 >>> 16;
3858
+ c32 &= 65535;
3859
+ c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
3860
+ c48 &= 65535;
3861
+ return _Long.fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
3862
+ }
3863
+ mul(multiplier) {
3864
+ return this.multiply(multiplier);
3865
+ }
3866
+ negate() {
3867
+ if (!this.unsigned && this.eq(_Long.MIN_VALUE))
3868
+ return _Long.MIN_VALUE;
3869
+ return this.not().add(_Long.ONE);
3870
+ }
3871
+ neg() {
3872
+ return this.negate();
3873
+ }
3874
+ not() {
3875
+ return _Long.fromBits(~this.low, ~this.high, this.unsigned);
3876
+ }
3877
+ notEquals(other) {
3878
+ return !this.equals(other);
3879
+ }
3880
+ neq(other) {
3881
+ return this.notEquals(other);
3882
+ }
3883
+ ne(other) {
3884
+ return this.notEquals(other);
3885
+ }
3886
+ or(other) {
3887
+ if (!_Long.isLong(other))
3888
+ other = _Long.fromValue(other);
3889
+ return _Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned);
3890
+ }
3891
+ shiftLeft(numBits) {
3892
+ if (_Long.isLong(numBits))
3893
+ numBits = numBits.toInt();
3894
+ if ((numBits &= 63) === 0)
3895
+ return this;
3896
+ else if (numBits < 32)
3897
+ return _Long.fromBits(this.low << numBits, this.high << numBits | this.low >>> 32 - numBits, this.unsigned);
3898
+ else
3899
+ return _Long.fromBits(0, this.low << numBits - 32, this.unsigned);
3900
+ }
3901
+ shl(numBits) {
3902
+ return this.shiftLeft(numBits);
3903
+ }
3904
+ shiftRight(numBits) {
3905
+ if (_Long.isLong(numBits))
3906
+ numBits = numBits.toInt();
3907
+ if ((numBits &= 63) === 0)
3908
+ return this;
3909
+ else if (numBits < 32)
3910
+ return _Long.fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >> numBits, this.unsigned);
3911
+ else
3912
+ return _Long.fromBits(this.high >> numBits - 32, this.high >= 0 ? 0 : -1, this.unsigned);
3913
+ }
3914
+ shr(numBits) {
3915
+ return this.shiftRight(numBits);
3916
+ }
3917
+ shiftRightUnsigned(numBits) {
3918
+ if (_Long.isLong(numBits))
3919
+ numBits = numBits.toInt();
3920
+ numBits &= 63;
3921
+ if (numBits === 0)
3922
+ return this;
3923
+ else {
3924
+ const high = this.high;
3925
+ if (numBits < 32) {
3926
+ const low = this.low;
3927
+ return _Long.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits, this.unsigned);
3928
+ } else if (numBits === 32)
3929
+ return _Long.fromBits(high, 0, this.unsigned);
3930
+ else
3931
+ return _Long.fromBits(high >>> numBits - 32, 0, this.unsigned);
3932
+ }
3933
+ }
3934
+ shr_u(numBits) {
3935
+ return this.shiftRightUnsigned(numBits);
3936
+ }
3937
+ shru(numBits) {
3938
+ return this.shiftRightUnsigned(numBits);
3939
+ }
3940
+ subtract(subtrahend) {
3941
+ if (!_Long.isLong(subtrahend))
3942
+ subtrahend = _Long.fromValue(subtrahend);
3943
+ return this.add(subtrahend.neg());
3944
+ }
3945
+ sub(subtrahend) {
3946
+ return this.subtract(subtrahend);
3947
+ }
3948
+ toInt() {
3949
+ return this.unsigned ? this.low >>> 0 : this.low;
3950
+ }
3951
+ toNumber() {
3952
+ if (this.unsigned)
3953
+ return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
3954
+ return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
3955
+ }
3956
+ toBigInt() {
3957
+ return BigInt(this.toString());
3958
+ }
3959
+ toBytes(le) {
3960
+ return le ? this.toBytesLE() : this.toBytesBE();
3961
+ }
3962
+ toBytesLE() {
3963
+ const hi = this.high, lo = this.low;
3964
+ return [
3965
+ lo & 255,
3966
+ lo >>> 8 & 255,
3967
+ lo >>> 16 & 255,
3968
+ lo >>> 24,
3969
+ hi & 255,
3970
+ hi >>> 8 & 255,
3971
+ hi >>> 16 & 255,
3972
+ hi >>> 24
3973
+ ];
3974
+ }
3975
+ toBytesBE() {
3976
+ const hi = this.high, lo = this.low;
3977
+ return [
3978
+ hi >>> 24,
3979
+ hi >>> 16 & 255,
3980
+ hi >>> 8 & 255,
3981
+ hi & 255,
3982
+ lo >>> 24,
3983
+ lo >>> 16 & 255,
3984
+ lo >>> 8 & 255,
3985
+ lo & 255
3986
+ ];
3987
+ }
3988
+ toSigned() {
3989
+ if (!this.unsigned)
3990
+ return this;
3991
+ return _Long.fromBits(this.low, this.high, false);
3992
+ }
3993
+ toString(radix) {
3994
+ radix = radix || 10;
3995
+ if (radix < 2 || 36 < radix)
3996
+ throw new BSONError("radix");
3997
+ if (this.isZero())
3998
+ return "0";
3999
+ if (this.isNegative()) {
4000
+ if (this.eq(_Long.MIN_VALUE)) {
4001
+ const radixLong = _Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this);
4002
+ return div.toString(radix) + rem1.toInt().toString(radix);
4003
+ } else
4004
+ return "-" + this.neg().toString(radix);
4005
+ }
4006
+ const radixToPower = _Long.fromNumber(Math.pow(radix, 6), this.unsigned);
4007
+ let rem = this;
4008
+ let result = "";
4009
+ while (true) {
4010
+ const remDiv = rem.div(radixToPower);
4011
+ const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0;
4012
+ let digits = intval.toString(radix);
4013
+ rem = remDiv;
4014
+ if (rem.isZero()) {
4015
+ return digits + result;
4016
+ } else {
4017
+ while (digits.length < 6)
4018
+ digits = "0" + digits;
4019
+ result = "" + digits + result;
4020
+ }
4021
+ }
4022
+ }
4023
+ toUnsigned() {
4024
+ if (this.unsigned)
4025
+ return this;
4026
+ return _Long.fromBits(this.low, this.high, true);
4027
+ }
4028
+ xor(other) {
4029
+ if (!_Long.isLong(other))
4030
+ other = _Long.fromValue(other);
4031
+ return _Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
4032
+ }
4033
+ eqz() {
4034
+ return this.isZero();
4035
+ }
4036
+ le(other) {
4037
+ return this.lessThanOrEqual(other);
4038
+ }
4039
+ toExtendedJSON(options) {
4040
+ if (options && options.relaxed)
4041
+ return this.toNumber();
4042
+ return { $numberLong: this.toString() };
4043
+ }
4044
+ static fromExtendedJSON(doc, options) {
4045
+ const { useBigInt64 = false, relaxed = true } = { ...options };
4046
+ if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) {
4047
+ throw new BSONError("$numberLong string is too long");
4048
+ }
4049
+ if (!DECIMAL_REG_EX.test(doc.$numberLong)) {
4050
+ throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`);
4051
+ }
4052
+ if (useBigInt64) {
4053
+ const bigIntResult = BigInt(doc.$numberLong);
4054
+ return BigInt.asIntN(64, bigIntResult);
4055
+ }
4056
+ const longResult = _Long.fromString(doc.$numberLong);
4057
+ if (relaxed) {
4058
+ return longResult.toNumber();
4059
+ }
4060
+ return longResult;
4061
+ }
4062
+ inspect(depth, options, inspect) {
4063
+ inspect ?? (inspect = defaultInspect);
4064
+ const longVal = inspect(this.toString(), options);
4065
+ const unsignedVal = this.unsigned ? `, ${inspect(this.unsigned, options)}` : "";
4066
+ return `new Long(${longVal}${unsignedVal})`;
4067
+ }
4068
+ };
4069
+ __name(_Long, "Long");
4070
+ var Long = _Long;
4071
+ Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL);
4072
+ Long.MAX_UNSIGNED_VALUE = Long.fromBits(4294967295 | 0, 4294967295 | 0, true);
4073
+ Long.ZERO = Long.fromInt(0);
4074
+ Long.UZERO = Long.fromInt(0, true);
4075
+ Long.ONE = Long.fromInt(1);
4076
+ Long.UONE = Long.fromInt(1, true);
4077
+ Long.NEG_ONE = Long.fromInt(-1);
4078
+ Long.MAX_VALUE = Long.fromBits(4294967295 | 0, 2147483647 | 0, false);
4079
+ Long.MIN_VALUE = Long.fromBits(0, 2147483648 | 0, false);
4080
+ var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
4081
+ var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
4082
+ var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
4083
+ var EXPONENT_MAX = 6111;
4084
+ var EXPONENT_MIN = -6176;
4085
+ var EXPONENT_BIAS = 6176;
4086
+ var MAX_DIGITS = 34;
4087
+ var NAN_BUFFER = ByteUtils.fromNumberArray([
4088
+ 124,
4089
+ 0,
4090
+ 0,
4091
+ 0,
4092
+ 0,
4093
+ 0,
4094
+ 0,
4095
+ 0,
4096
+ 0,
4097
+ 0,
4098
+ 0,
4099
+ 0,
4100
+ 0,
4101
+ 0,
4102
+ 0,
4103
+ 0
4104
+ ].reverse());
4105
+ var INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([
4106
+ 248,
4107
+ 0,
4108
+ 0,
4109
+ 0,
4110
+ 0,
4111
+ 0,
4112
+ 0,
4113
+ 0,
4114
+ 0,
4115
+ 0,
4116
+ 0,
4117
+ 0,
4118
+ 0,
4119
+ 0,
4120
+ 0,
4121
+ 0
4122
+ ].reverse());
4123
+ var INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([
4124
+ 120,
4125
+ 0,
4126
+ 0,
4127
+ 0,
4128
+ 0,
4129
+ 0,
4130
+ 0,
4131
+ 0,
4132
+ 0,
4133
+ 0,
4134
+ 0,
4135
+ 0,
4136
+ 0,
4137
+ 0,
4138
+ 0,
4139
+ 0
4140
+ ].reverse());
4141
+ var EXPONENT_REGEX = /^([-+])?(\d+)?$/;
4142
+ var COMBINATION_MASK = 31;
4143
+ var EXPONENT_MASK = 16383;
4144
+ var COMBINATION_INFINITY = 30;
4145
+ var COMBINATION_NAN = 31;
4146
+ function isDigit(value) {
4147
+ return !isNaN(parseInt(value, 10));
4148
+ }
4149
+ __name(isDigit, "isDigit");
4150
+ function divideu128(value) {
4151
+ const DIVISOR = Long.fromNumber(1e3 * 1e3 * 1e3);
4152
+ let _rem = Long.fromNumber(0);
4153
+ if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
4154
+ return { quotient: value, rem: _rem };
4155
+ }
4156
+ for (let i = 0; i <= 3; i++) {
4157
+ _rem = _rem.shiftLeft(32);
4158
+ _rem = _rem.add(new Long(value.parts[i], 0));
4159
+ value.parts[i] = _rem.div(DIVISOR).low;
4160
+ _rem = _rem.modulo(DIVISOR);
4161
+ }
4162
+ return { quotient: value, rem: _rem };
4163
+ }
4164
+ __name(divideu128, "divideu128");
4165
+ function multiply64x2(left, right) {
4166
+ if (!left && !right) {
4167
+ return { high: Long.fromNumber(0), low: Long.fromNumber(0) };
4168
+ }
4169
+ const leftHigh = left.shiftRightUnsigned(32);
4170
+ const leftLow = new Long(left.getLowBits(), 0);
4171
+ const rightHigh = right.shiftRightUnsigned(32);
4172
+ const rightLow = new Long(right.getLowBits(), 0);
4173
+ let productHigh = leftHigh.multiply(rightHigh);
4174
+ let productMid = leftHigh.multiply(rightLow);
4175
+ const productMid2 = leftLow.multiply(rightHigh);
4176
+ let productLow = leftLow.multiply(rightLow);
4177
+ productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
4178
+ productMid = new Long(productMid.getLowBits(), 0).add(productMid2).add(productLow.shiftRightUnsigned(32));
4179
+ productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
4180
+ productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0));
4181
+ return { high: productHigh, low: productLow };
4182
+ }
4183
+ __name(multiply64x2, "multiply64x2");
4184
+ function lessThan(left, right) {
4185
+ const uhleft = left.high >>> 0;
4186
+ const uhright = right.high >>> 0;
4187
+ if (uhleft < uhright) {
4188
+ return true;
4189
+ } else if (uhleft === uhright) {
4190
+ const ulleft = left.low >>> 0;
4191
+ const ulright = right.low >>> 0;
4192
+ if (ulleft < ulright)
4193
+ return true;
4194
+ }
4195
+ return false;
4196
+ }
4197
+ __name(lessThan, "lessThan");
4198
+ function invalidErr(string, message) {
4199
+ throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`);
4200
+ }
4201
+ __name(invalidErr, "invalidErr");
4202
+ var _Decimal128 = class _Decimal128 extends BSONValue {
4203
+ get _bsontype() {
4204
+ return "Decimal128";
4205
+ }
4206
+ constructor(bytes) {
4207
+ super();
4208
+ if (typeof bytes === "string") {
4209
+ this.bytes = _Decimal128.fromString(bytes).bytes;
4210
+ } else if (bytes instanceof Uint8Array || isUint8Array(bytes)) {
4211
+ if (bytes.byteLength !== 16) {
4212
+ throw new BSONError("Decimal128 must take a Buffer of 16 bytes");
4213
+ }
4214
+ this.bytes = bytes;
4215
+ } else {
4216
+ throw new BSONError("Decimal128 must take a Buffer or string");
4217
+ }
4218
+ }
4219
+ static fromString(representation) {
4220
+ return _Decimal128._fromString(representation, { allowRounding: false });
4221
+ }
4222
+ static fromStringWithRounding(representation) {
4223
+ return _Decimal128._fromString(representation, { allowRounding: true });
4224
+ }
4225
+ static _fromString(representation, options) {
4226
+ let isNegative = false;
4227
+ let sawSign = false;
4228
+ let sawRadix = false;
4229
+ let foundNonZero = false;
4230
+ let significantDigits = 0;
4231
+ let nDigitsRead = 0;
4232
+ let nDigits = 0;
4233
+ let radixPosition = 0;
4234
+ let firstNonZero = 0;
4235
+ const digits = [0];
4236
+ let nDigitsStored = 0;
4237
+ let digitsInsert = 0;
4238
+ let lastDigit = 0;
4239
+ let exponent = 0;
4240
+ let significandHigh = new Long(0, 0);
4241
+ let significandLow = new Long(0, 0);
4242
+ let biasedExponent = 0;
4243
+ let index = 0;
4244
+ if (representation.length >= 7e3) {
4245
+ throw new BSONError("" + representation + " not a valid Decimal128 string");
4246
+ }
4247
+ const stringMatch = representation.match(PARSE_STRING_REGEXP);
4248
+ const infMatch = representation.match(PARSE_INF_REGEXP);
4249
+ const nanMatch = representation.match(PARSE_NAN_REGEXP);
4250
+ if (!stringMatch && !infMatch && !nanMatch || representation.length === 0) {
4251
+ throw new BSONError("" + representation + " not a valid Decimal128 string");
4252
+ }
4253
+ if (stringMatch) {
4254
+ const unsignedNumber = stringMatch[2];
4255
+ const e = stringMatch[4];
4256
+ const expSign = stringMatch[5];
4257
+ const expNumber = stringMatch[6];
4258
+ if (e && expNumber === void 0)
4259
+ invalidErr(representation, "missing exponent power");
4260
+ if (e && unsignedNumber === void 0)
4261
+ invalidErr(representation, "missing exponent base");
4262
+ if (e === void 0 && (expSign || expNumber)) {
4263
+ invalidErr(representation, "missing e before exponent");
4264
+ }
4265
+ }
4266
+ if (representation[index] === "+" || representation[index] === "-") {
4267
+ sawSign = true;
4268
+ isNegative = representation[index++] === "-";
4269
+ }
4270
+ if (!isDigit(representation[index]) && representation[index] !== ".") {
4271
+ if (representation[index] === "i" || representation[index] === "I") {
4272
+ return new _Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
4273
+ } else if (representation[index] === "N") {
4274
+ return new _Decimal128(NAN_BUFFER);
4275
+ }
4276
+ }
4277
+ while (isDigit(representation[index]) || representation[index] === ".") {
4278
+ if (representation[index] === ".") {
4279
+ if (sawRadix)
4280
+ invalidErr(representation, "contains multiple periods");
4281
+ sawRadix = true;
4282
+ index = index + 1;
4283
+ continue;
4284
+ }
4285
+ if (nDigitsStored < MAX_DIGITS) {
4286
+ if (representation[index] !== "0" || foundNonZero) {
4287
+ if (!foundNonZero) {
4288
+ firstNonZero = nDigitsRead;
4289
+ }
4290
+ foundNonZero = true;
4291
+ digits[digitsInsert++] = parseInt(representation[index], 10);
4292
+ nDigitsStored = nDigitsStored + 1;
4293
+ }
4294
+ }
4295
+ if (foundNonZero)
4296
+ nDigits = nDigits + 1;
4297
+ if (sawRadix)
4298
+ radixPosition = radixPosition + 1;
4299
+ nDigitsRead = nDigitsRead + 1;
4300
+ index = index + 1;
4301
+ }
4302
+ if (sawRadix && !nDigitsRead)
4303
+ throw new BSONError("" + representation + " not a valid Decimal128 string");
4304
+ if (representation[index] === "e" || representation[index] === "E") {
4305
+ const match = representation.substr(++index).match(EXPONENT_REGEX);
4306
+ if (!match || !match[2])
4307
+ return new _Decimal128(NAN_BUFFER);
4308
+ exponent = parseInt(match[0], 10);
4309
+ index = index + match[0].length;
4310
+ }
4311
+ if (representation[index])
4312
+ return new _Decimal128(NAN_BUFFER);
4313
+ if (!nDigitsStored) {
4314
+ digits[0] = 0;
4315
+ nDigits = 1;
4316
+ nDigitsStored = 1;
4317
+ significantDigits = 0;
4318
+ } else {
4319
+ lastDigit = nDigitsStored - 1;
4320
+ significantDigits = nDigits;
4321
+ if (significantDigits !== 1) {
4322
+ while (representation[firstNonZero + significantDigits - 1 + Number(sawSign) + Number(sawRadix)] === "0") {
4323
+ significantDigits = significantDigits - 1;
4324
+ }
4325
+ }
4326
+ }
4327
+ if (exponent <= radixPosition && radixPosition > exponent + (1 << 14)) {
4328
+ exponent = EXPONENT_MIN;
4329
+ } else {
4330
+ exponent = exponent - radixPosition;
4331
+ }
4332
+ while (exponent > EXPONENT_MAX) {
4333
+ lastDigit = lastDigit + 1;
4334
+ if (lastDigit >= MAX_DIGITS) {
4335
+ if (significantDigits === 0) {
4336
+ exponent = EXPONENT_MAX;
4337
+ break;
4338
+ }
4339
+ invalidErr(representation, "overflow");
4340
+ }
4341
+ exponent = exponent - 1;
4342
+ }
4343
+ if (options.allowRounding) {
4344
+ while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
4345
+ if (lastDigit === 0 && significantDigits < nDigitsStored) {
4346
+ exponent = EXPONENT_MIN;
4347
+ significantDigits = 0;
4348
+ break;
4349
+ }
4350
+ if (nDigitsStored < nDigits) {
4351
+ nDigits = nDigits - 1;
4352
+ } else {
4353
+ lastDigit = lastDigit - 1;
4354
+ }
4355
+ if (exponent < EXPONENT_MAX) {
4356
+ exponent = exponent + 1;
4357
+ } else {
4358
+ const digitsString = digits.join("");
4359
+ if (digitsString.match(/^0+$/)) {
4360
+ exponent = EXPONENT_MAX;
4361
+ break;
4362
+ }
4363
+ invalidErr(representation, "overflow");
4364
+ }
4365
+ }
4366
+ if (lastDigit + 1 < significantDigits) {
4367
+ let endOfString = nDigitsRead;
4368
+ if (sawRadix) {
4369
+ firstNonZero = firstNonZero + 1;
4370
+ endOfString = endOfString + 1;
4371
+ }
4372
+ if (sawSign) {
4373
+ firstNonZero = firstNonZero + 1;
4374
+ endOfString = endOfString + 1;
4375
+ }
4376
+ const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
4377
+ let roundBit = 0;
4378
+ if (roundDigit >= 5) {
4379
+ roundBit = 1;
4380
+ if (roundDigit === 5) {
4381
+ roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0;
4382
+ for (let i = firstNonZero + lastDigit + 2; i < endOfString; i++) {
4383
+ if (parseInt(representation[i], 10)) {
4384
+ roundBit = 1;
4385
+ break;
4386
+ }
4387
+ }
4388
+ }
4389
+ }
4390
+ if (roundBit) {
4391
+ let dIdx = lastDigit;
4392
+ for (; dIdx >= 0; dIdx--) {
4393
+ if (++digits[dIdx] > 9) {
4394
+ digits[dIdx] = 0;
4395
+ if (dIdx === 0) {
4396
+ if (exponent < EXPONENT_MAX) {
4397
+ exponent = exponent + 1;
4398
+ digits[dIdx] = 1;
4399
+ } else {
4400
+ return new _Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
4401
+ }
4402
+ }
4403
+ } else {
4404
+ break;
4405
+ }
4406
+ }
4407
+ }
4408
+ }
4409
+ } else {
4410
+ while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
4411
+ if (lastDigit === 0) {
4412
+ if (significantDigits === 0) {
4413
+ exponent = EXPONENT_MIN;
4414
+ break;
4415
+ }
4416
+ invalidErr(representation, "exponent underflow");
4417
+ }
4418
+ if (nDigitsStored < nDigits) {
4419
+ if (representation[nDigits - 1 + Number(sawSign) + Number(sawRadix)] !== "0" && significantDigits !== 0) {
4420
+ invalidErr(representation, "inexact rounding");
4421
+ }
4422
+ nDigits = nDigits - 1;
4423
+ } else {
4424
+ if (digits[lastDigit] !== 0) {
4425
+ invalidErr(representation, "inexact rounding");
4426
+ }
4427
+ lastDigit = lastDigit - 1;
4428
+ }
4429
+ if (exponent < EXPONENT_MAX) {
4430
+ exponent = exponent + 1;
4431
+ } else {
4432
+ invalidErr(representation, "overflow");
4433
+ }
4434
+ }
4435
+ if (lastDigit + 1 < significantDigits) {
4436
+ if (sawRadix) {
4437
+ firstNonZero = firstNonZero + 1;
4438
+ }
4439
+ if (sawSign) {
4440
+ firstNonZero = firstNonZero + 1;
4441
+ }
4442
+ const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
4443
+ if (roundDigit !== 0) {
4444
+ invalidErr(representation, "inexact rounding");
4445
+ }
4446
+ }
4447
+ }
4448
+ significandHigh = Long.fromNumber(0);
4449
+ significandLow = Long.fromNumber(0);
4450
+ if (significantDigits === 0) {
4451
+ significandHigh = Long.fromNumber(0);
4452
+ significandLow = Long.fromNumber(0);
4453
+ } else if (lastDigit < 17) {
4454
+ let dIdx = 0;
4455
+ significandLow = Long.fromNumber(digits[dIdx++]);
4456
+ significandHigh = new Long(0, 0);
4457
+ for (; dIdx <= lastDigit; dIdx++) {
4458
+ significandLow = significandLow.multiply(Long.fromNumber(10));
4459
+ significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
4460
+ }
4461
+ } else {
4462
+ let dIdx = 0;
4463
+ significandHigh = Long.fromNumber(digits[dIdx++]);
4464
+ for (; dIdx <= lastDigit - 17; dIdx++) {
4465
+ significandHigh = significandHigh.multiply(Long.fromNumber(10));
4466
+ significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx]));
4467
+ }
4468
+ significandLow = Long.fromNumber(digits[dIdx++]);
4469
+ for (; dIdx <= lastDigit; dIdx++) {
4470
+ significandLow = significandLow.multiply(Long.fromNumber(10));
4471
+ significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
4472
+ }
4473
+ }
4474
+ const significand = multiply64x2(significandHigh, Long.fromString("100000000000000000"));
4475
+ significand.low = significand.low.add(significandLow);
4476
+ if (lessThan(significand.low, significandLow)) {
4477
+ significand.high = significand.high.add(Long.fromNumber(1));
4478
+ }
4479
+ biasedExponent = exponent + EXPONENT_BIAS;
4480
+ const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) };
4481
+ if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) {
4482
+ dec.high = dec.high.or(Long.fromNumber(3).shiftLeft(61));
4483
+ dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(16383).shiftLeft(47)));
4484
+ dec.high = dec.high.or(significand.high.and(Long.fromNumber(140737488355327)));
4485
+ } else {
4486
+ dec.high = dec.high.or(Long.fromNumber(biasedExponent & 16383).shiftLeft(49));
4487
+ dec.high = dec.high.or(significand.high.and(Long.fromNumber(562949953421311)));
4488
+ }
4489
+ dec.low = significand.low;
4490
+ if (isNegative) {
4491
+ dec.high = dec.high.or(Long.fromString("9223372036854775808"));
4492
+ }
4493
+ const buffer2 = ByteUtils.allocateUnsafe(16);
4494
+ index = 0;
4495
+ buffer2[index++] = dec.low.low & 255;
4496
+ buffer2[index++] = dec.low.low >> 8 & 255;
4497
+ buffer2[index++] = dec.low.low >> 16 & 255;
4498
+ buffer2[index++] = dec.low.low >> 24 & 255;
4499
+ buffer2[index++] = dec.low.high & 255;
4500
+ buffer2[index++] = dec.low.high >> 8 & 255;
4501
+ buffer2[index++] = dec.low.high >> 16 & 255;
4502
+ buffer2[index++] = dec.low.high >> 24 & 255;
4503
+ buffer2[index++] = dec.high.low & 255;
4504
+ buffer2[index++] = dec.high.low >> 8 & 255;
4505
+ buffer2[index++] = dec.high.low >> 16 & 255;
4506
+ buffer2[index++] = dec.high.low >> 24 & 255;
4507
+ buffer2[index++] = dec.high.high & 255;
4508
+ buffer2[index++] = dec.high.high >> 8 & 255;
4509
+ buffer2[index++] = dec.high.high >> 16 & 255;
4510
+ buffer2[index++] = dec.high.high >> 24 & 255;
4511
+ return new _Decimal128(buffer2);
4512
+ }
4513
+ toString() {
4514
+ let biased_exponent;
4515
+ let significand_digits = 0;
4516
+ const significand = new Array(36);
4517
+ for (let i = 0; i < significand.length; i++)
4518
+ significand[i] = 0;
4519
+ let index = 0;
4520
+ let is_zero = false;
4521
+ let significand_msb;
4522
+ let significand128 = { parts: [0, 0, 0, 0] };
4523
+ let j, k;
4524
+ const string = [];
4525
+ index = 0;
4526
+ const buffer2 = this.bytes;
4527
+ const low = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
4528
+ const midl = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
4529
+ const midh = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
4530
+ const high = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
4531
+ index = 0;
4532
+ const dec = {
4533
+ low: new Long(low, midl),
4534
+ high: new Long(midh, high)
4535
+ };
4536
+ if (dec.high.lessThan(Long.ZERO)) {
4537
+ string.push("-");
4538
+ }
4539
+ const combination = high >> 26 & COMBINATION_MASK;
4540
+ if (combination >> 3 === 3) {
4541
+ if (combination === COMBINATION_INFINITY) {
4542
+ return string.join("") + "Infinity";
4543
+ } else if (combination === COMBINATION_NAN) {
4544
+ return "NaN";
4545
+ } else {
4546
+ biased_exponent = high >> 15 & EXPONENT_MASK;
4547
+ significand_msb = 8 + (high >> 14 & 1);
4548
+ }
4549
+ } else {
4550
+ significand_msb = high >> 14 & 7;
4551
+ biased_exponent = high >> 17 & EXPONENT_MASK;
4552
+ }
4553
+ const exponent = biased_exponent - EXPONENT_BIAS;
4554
+ significand128.parts[0] = (high & 16383) + ((significand_msb & 15) << 14);
4555
+ significand128.parts[1] = midh;
4556
+ significand128.parts[2] = midl;
4557
+ significand128.parts[3] = low;
4558
+ if (significand128.parts[0] === 0 && significand128.parts[1] === 0 && significand128.parts[2] === 0 && significand128.parts[3] === 0) {
4559
+ is_zero = true;
4560
+ } else {
4561
+ for (k = 3; k >= 0; k--) {
4562
+ let least_digits = 0;
4563
+ const result = divideu128(significand128);
4564
+ significand128 = result.quotient;
4565
+ least_digits = result.rem.low;
4566
+ if (!least_digits)
4567
+ continue;
4568
+ for (j = 8; j >= 0; j--) {
4569
+ significand[k * 9 + j] = least_digits % 10;
4570
+ least_digits = Math.floor(least_digits / 10);
4571
+ }
4572
+ }
4573
+ }
4574
+ if (is_zero) {
4575
+ significand_digits = 1;
4576
+ significand[index] = 0;
4577
+ } else {
4578
+ significand_digits = 36;
4579
+ while (!significand[index]) {
4580
+ significand_digits = significand_digits - 1;
4581
+ index = index + 1;
4582
+ }
4583
+ }
4584
+ const scientific_exponent = significand_digits - 1 + exponent;
4585
+ if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
4586
+ if (significand_digits > 34) {
4587
+ string.push(`${0}`);
4588
+ if (exponent > 0)
4589
+ string.push(`E+${exponent}`);
4590
+ else if (exponent < 0)
4591
+ string.push(`E${exponent}`);
4592
+ return string.join("");
4593
+ }
4594
+ string.push(`${significand[index++]}`);
4595
+ significand_digits = significand_digits - 1;
4596
+ if (significand_digits) {
4597
+ string.push(".");
4598
+ }
4599
+ for (let i = 0; i < significand_digits; i++) {
4600
+ string.push(`${significand[index++]}`);
4601
+ }
4602
+ string.push("E");
4603
+ if (scientific_exponent > 0) {
4604
+ string.push(`+${scientific_exponent}`);
4605
+ } else {
4606
+ string.push(`${scientific_exponent}`);
4607
+ }
4608
+ } else {
4609
+ if (exponent >= 0) {
4610
+ for (let i = 0; i < significand_digits; i++) {
4611
+ string.push(`${significand[index++]}`);
4612
+ }
4613
+ } else {
4614
+ let radix_position = significand_digits + exponent;
4615
+ if (radix_position > 0) {
4616
+ for (let i = 0; i < radix_position; i++) {
4617
+ string.push(`${significand[index++]}`);
4618
+ }
4619
+ } else {
4620
+ string.push("0");
4621
+ }
4622
+ string.push(".");
4623
+ while (radix_position++ < 0) {
4624
+ string.push("0");
4625
+ }
4626
+ for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) {
4627
+ string.push(`${significand[index++]}`);
4628
+ }
4629
+ }
4630
+ }
4631
+ return string.join("");
4632
+ }
4633
+ toJSON() {
4634
+ return { $numberDecimal: this.toString() };
4635
+ }
4636
+ toExtendedJSON() {
4637
+ return { $numberDecimal: this.toString() };
4638
+ }
4639
+ static fromExtendedJSON(doc) {
4640
+ return _Decimal128.fromString(doc.$numberDecimal);
4641
+ }
4642
+ inspect(depth, options, inspect) {
4643
+ inspect ?? (inspect = defaultInspect);
4644
+ const d128string = inspect(this.toString(), options);
4645
+ return `new Decimal128(${d128string})`;
4646
+ }
4647
+ };
4648
+ __name(_Decimal128, "Decimal128");
4649
+ var Decimal128 = _Decimal128;
4650
+ var _Double = class _Double extends BSONValue {
4651
+ get _bsontype() {
4652
+ return "Double";
4653
+ }
4654
+ constructor(value) {
4655
+ super();
4656
+ if (value instanceof Number) {
4657
+ value = value.valueOf();
4658
+ }
4659
+ this.value = +value;
4660
+ }
4661
+ static fromString(value) {
4662
+ const coercedValue = Number(value);
4663
+ if (value === "NaN")
4664
+ return new _Double(NaN);
4665
+ if (value === "Infinity")
4666
+ return new _Double(Infinity);
4667
+ if (value === "-Infinity")
4668
+ return new _Double(-Infinity);
4669
+ if (!Number.isFinite(coercedValue)) {
4670
+ throw new BSONError(`Input: ${value} is not representable as a Double`);
4671
+ }
4672
+ if (value.trim() !== value) {
4673
+ throw new BSONError(`Input: '${value}' contains whitespace`);
4674
+ }
4675
+ if (value === "") {
4676
+ throw new BSONError(`Input is an empty string`);
4677
+ }
4678
+ if (/[^-0-9.+eE]/.test(value)) {
4679
+ throw new BSONError(`Input: '${value}' is not in decimal or exponential notation`);
4680
+ }
4681
+ return new _Double(coercedValue);
4682
+ }
4683
+ valueOf() {
4684
+ return this.value;
4685
+ }
4686
+ toJSON() {
4687
+ return this.value;
4688
+ }
4689
+ toString(radix) {
4690
+ return this.value.toString(radix);
4691
+ }
4692
+ toExtendedJSON(options) {
4693
+ if (options && (options.legacy || options.relaxed && isFinite(this.value))) {
4694
+ return this.value;
4695
+ }
4696
+ if (Object.is(Math.sign(this.value), -0)) {
4697
+ return { $numberDouble: "-0.0" };
4698
+ }
4699
+ return {
4700
+ $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString()
4701
+ };
4702
+ }
4703
+ static fromExtendedJSON(doc, options) {
4704
+ const doubleValue = parseFloat(doc.$numberDouble);
4705
+ return options && options.relaxed ? doubleValue : new _Double(doubleValue);
4706
+ }
4707
+ inspect(depth, options, inspect) {
4708
+ inspect ?? (inspect = defaultInspect);
4709
+ return `new Double(${inspect(this.value, options)})`;
4710
+ }
4711
+ };
4712
+ __name(_Double, "Double");
4713
+ var Double = _Double;
4714
+ var _Int32 = class _Int32 extends BSONValue {
4715
+ get _bsontype() {
4716
+ return "Int32";
4717
+ }
4718
+ constructor(value) {
4719
+ super();
4720
+ if (value instanceof Number) {
4721
+ value = value.valueOf();
4722
+ }
4723
+ this.value = +value | 0;
4724
+ }
4725
+ static fromString(value) {
4726
+ const cleanedValue = removeLeadingZerosAndExplicitPlus(value);
4727
+ const coercedValue = Number(value);
4728
+ if (BSON_INT32_MAX < coercedValue) {
4729
+ throw new BSONError(`Input: '${value}' is larger than the maximum value for Int32`);
4730
+ } else if (BSON_INT32_MIN > coercedValue) {
4731
+ throw new BSONError(`Input: '${value}' is smaller than the minimum value for Int32`);
4732
+ } else if (!Number.isSafeInteger(coercedValue)) {
4733
+ throw new BSONError(`Input: '${value}' is not a safe integer`);
4734
+ } else if (coercedValue.toString() !== cleanedValue) {
4735
+ throw new BSONError(`Input: '${value}' is not a valid Int32 string`);
4736
+ }
4737
+ return new _Int32(coercedValue);
4738
+ }
4739
+ valueOf() {
4740
+ return this.value;
4741
+ }
4742
+ toString(radix) {
4743
+ return this.value.toString(radix);
4744
+ }
4745
+ toJSON() {
4746
+ return this.value;
4747
+ }
4748
+ toExtendedJSON(options) {
4749
+ if (options && (options.relaxed || options.legacy))
4750
+ return this.value;
4751
+ return { $numberInt: this.value.toString() };
4752
+ }
4753
+ static fromExtendedJSON(doc, options) {
4754
+ return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new _Int32(doc.$numberInt);
4755
+ }
4756
+ inspect(depth, options, inspect) {
4757
+ inspect ?? (inspect = defaultInspect);
4758
+ return `new Int32(${inspect(this.value, options)})`;
4759
+ }
4760
+ };
4761
+ __name(_Int32, "Int32");
4762
+ var Int32 = _Int32;
4763
+ var _MaxKey = class _MaxKey extends BSONValue {
4764
+ get _bsontype() {
4765
+ return "MaxKey";
4766
+ }
4767
+ toExtendedJSON() {
4768
+ return { $maxKey: 1 };
4769
+ }
4770
+ static fromExtendedJSON() {
4771
+ return new _MaxKey();
4772
+ }
4773
+ inspect() {
4774
+ return "new MaxKey()";
4775
+ }
4776
+ };
4777
+ __name(_MaxKey, "MaxKey");
4778
+ var MaxKey = _MaxKey;
4779
+ var _MinKey = class _MinKey extends BSONValue {
4780
+ get _bsontype() {
4781
+ return "MinKey";
4782
+ }
4783
+ toExtendedJSON() {
4784
+ return { $minKey: 1 };
4785
+ }
4786
+ static fromExtendedJSON() {
4787
+ return new _MinKey();
4788
+ }
4789
+ inspect() {
4790
+ return "new MinKey()";
4791
+ }
4792
+ };
4793
+ __name(_MinKey, "MinKey");
4794
+ var MinKey = _MinKey;
4795
+ var PROCESS_UNIQUE = null;
4796
+ var __idCache = /* @__PURE__ */ new WeakMap();
4797
+ var _ObjectId = class _ObjectId extends BSONValue {
4798
+ get _bsontype() {
4799
+ return "ObjectId";
4800
+ }
4801
+ constructor(inputId) {
4802
+ super();
4803
+ let workingId;
4804
+ if (typeof inputId === "object" && inputId && "id" in inputId) {
4805
+ if (typeof inputId.id !== "string" && !ArrayBuffer.isView(inputId.id)) {
4806
+ throw new BSONError("Argument passed in must have an id that is of type string or Buffer");
4807
+ }
4808
+ if ("toHexString" in inputId && typeof inputId.toHexString === "function") {
4809
+ workingId = ByteUtils.fromHex(inputId.toHexString());
4810
+ } else {
4811
+ workingId = inputId.id;
4812
+ }
4813
+ } else {
4814
+ workingId = inputId;
4815
+ }
4816
+ if (workingId == null || typeof workingId === "number") {
4817
+ this.buffer = _ObjectId.generate(typeof workingId === "number" ? workingId : void 0);
4818
+ } else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) {
4819
+ this.buffer = ByteUtils.toLocalBufferType(workingId);
4820
+ } else if (typeof workingId === "string") {
4821
+ if (_ObjectId.validateHexString(workingId)) {
4822
+ this.buffer = ByteUtils.fromHex(workingId);
4823
+ if (_ObjectId.cacheHexString) {
4824
+ __idCache.set(this, workingId);
4825
+ }
4826
+ } else {
4827
+ throw new BSONError("input must be a 24 character hex string, 12 byte Uint8Array, or an integer");
4828
+ }
4829
+ } else {
4830
+ throw new BSONError("Argument passed in does not match the accepted types");
4831
+ }
4832
+ }
4833
+ get id() {
4834
+ return this.buffer;
4835
+ }
4836
+ set id(value) {
4837
+ this.buffer = value;
4838
+ if (_ObjectId.cacheHexString) {
4839
+ __idCache.set(this, ByteUtils.toHex(value));
4840
+ }
4841
+ }
4842
+ static validateHexString(string) {
4843
+ if (string?.length !== 24)
4844
+ return false;
4845
+ for (let i = 0; i < 24; i++) {
4846
+ const char = string.charCodeAt(i);
4847
+ if (char >= 48 && char <= 57 || char >= 97 && char <= 102 || char >= 65 && char <= 70) {
4848
+ continue;
4849
+ }
4850
+ return false;
4851
+ }
4852
+ return true;
4853
+ }
4854
+ toHexString() {
4855
+ if (_ObjectId.cacheHexString) {
4856
+ const __id = __idCache.get(this);
4857
+ if (__id)
4858
+ return __id;
4859
+ }
4860
+ const hexString = ByteUtils.toHex(this.id);
4861
+ if (_ObjectId.cacheHexString) {
4862
+ __idCache.set(this, hexString);
4863
+ }
4864
+ return hexString;
4865
+ }
4866
+ static getInc() {
4867
+ return _ObjectId.index = (_ObjectId.index + 1) % 16777215;
4868
+ }
4869
+ static generate(time) {
4870
+ if ("number" !== typeof time) {
4871
+ time = Math.floor(Date.now() / 1e3);
4872
+ }
4873
+ const inc = _ObjectId.getInc();
4874
+ const buffer2 = ByteUtils.allocateUnsafe(12);
4875
+ NumberUtils.setInt32BE(buffer2, 0, time);
4876
+ if (PROCESS_UNIQUE === null) {
4877
+ PROCESS_UNIQUE = ByteUtils.randomBytes(5);
4878
+ }
4879
+ buffer2[4] = PROCESS_UNIQUE[0];
4880
+ buffer2[5] = PROCESS_UNIQUE[1];
4881
+ buffer2[6] = PROCESS_UNIQUE[2];
4882
+ buffer2[7] = PROCESS_UNIQUE[3];
4883
+ buffer2[8] = PROCESS_UNIQUE[4];
4884
+ buffer2[11] = inc & 255;
4885
+ buffer2[10] = inc >> 8 & 255;
4886
+ buffer2[9] = inc >> 16 & 255;
4887
+ return buffer2;
4888
+ }
4889
+ toString(encoding) {
4890
+ if (encoding === "base64")
4891
+ return ByteUtils.toBase64(this.id);
4892
+ if (encoding === "hex")
4893
+ return this.toHexString();
4894
+ return this.toHexString();
4895
+ }
4896
+ toJSON() {
4897
+ return this.toHexString();
4898
+ }
4899
+ static is(variable) {
4900
+ return variable != null && typeof variable === "object" && "_bsontype" in variable && variable._bsontype === "ObjectId";
4901
+ }
4902
+ equals(otherId) {
4903
+ if (otherId === void 0 || otherId === null) {
4904
+ return false;
4905
+ }
4906
+ if (_ObjectId.is(otherId)) {
4907
+ return this.buffer[11] === otherId.buffer[11] && ByteUtils.equals(this.buffer, otherId.buffer);
4908
+ }
4909
+ if (typeof otherId === "string") {
4910
+ return otherId.toLowerCase() === this.toHexString();
4911
+ }
4912
+ if (typeof otherId === "object" && typeof otherId.toHexString === "function") {
4913
+ const otherIdString = otherId.toHexString();
4914
+ const thisIdString = this.toHexString();
4915
+ return typeof otherIdString === "string" && otherIdString.toLowerCase() === thisIdString;
4916
+ }
4917
+ return false;
4918
+ }
4919
+ getTimestamp() {
4920
+ const timestamp = /* @__PURE__ */ new Date();
4921
+ const time = NumberUtils.getUint32BE(this.buffer, 0);
4922
+ timestamp.setTime(Math.floor(time) * 1e3);
4923
+ return timestamp;
4924
+ }
4925
+ static createPk() {
4926
+ return new _ObjectId();
4927
+ }
4928
+ serializeInto(uint8array, index) {
4929
+ uint8array[index] = this.buffer[0];
4930
+ uint8array[index + 1] = this.buffer[1];
4931
+ uint8array[index + 2] = this.buffer[2];
4932
+ uint8array[index + 3] = this.buffer[3];
4933
+ uint8array[index + 4] = this.buffer[4];
4934
+ uint8array[index + 5] = this.buffer[5];
4935
+ uint8array[index + 6] = this.buffer[6];
4936
+ uint8array[index + 7] = this.buffer[7];
4937
+ uint8array[index + 8] = this.buffer[8];
4938
+ uint8array[index + 9] = this.buffer[9];
4939
+ uint8array[index + 10] = this.buffer[10];
4940
+ uint8array[index + 11] = this.buffer[11];
4941
+ return 12;
4942
+ }
4943
+ static createFromTime(time) {
4944
+ const buffer2 = ByteUtils.allocate(12);
4945
+ for (let i = 11; i >= 4; i--)
4946
+ buffer2[i] = 0;
4947
+ NumberUtils.setInt32BE(buffer2, 0, time);
4948
+ return new _ObjectId(buffer2);
4949
+ }
4950
+ static createFromHexString(hexString) {
4951
+ if (hexString?.length !== 24) {
4952
+ throw new BSONError("hex string must be 24 characters");
4953
+ }
4954
+ return new _ObjectId(ByteUtils.fromHex(hexString));
4955
+ }
4956
+ static createFromBase64(base64) {
4957
+ if (base64?.length !== 16) {
4958
+ throw new BSONError("base64 string must be 16 characters");
4959
+ }
4960
+ return new _ObjectId(ByteUtils.fromBase64(base64));
4961
+ }
4962
+ static isValid(id) {
4963
+ if (id == null)
4964
+ return false;
4965
+ if (typeof id === "string")
4966
+ return _ObjectId.validateHexString(id);
4967
+ try {
4968
+ new _ObjectId(id);
4969
+ return true;
4970
+ } catch {
4971
+ return false;
4972
+ }
4973
+ }
4974
+ toExtendedJSON() {
4975
+ if (this.toHexString)
4976
+ return { $oid: this.toHexString() };
4977
+ return { $oid: this.toString("hex") };
4978
+ }
4979
+ static fromExtendedJSON(doc) {
4980
+ return new _ObjectId(doc.$oid);
4981
+ }
4982
+ isCached() {
4983
+ return _ObjectId.cacheHexString && __idCache.has(this);
4984
+ }
4985
+ inspect(depth, options, inspect) {
4986
+ inspect ?? (inspect = defaultInspect);
4987
+ return `new ObjectId(${inspect(this.toHexString(), options)})`;
4988
+ }
4989
+ };
4990
+ __name(_ObjectId, "ObjectId");
4991
+ var ObjectId = _ObjectId;
4992
+ ObjectId.index = Math.floor(Math.random() * 16777215);
4993
+ function alphabetize(str) {
4994
+ return str.split("").sort().join("");
4995
+ }
4996
+ __name(alphabetize, "alphabetize");
4997
+ var _BSONRegExp = class _BSONRegExp extends BSONValue {
4998
+ get _bsontype() {
4999
+ return "BSONRegExp";
5000
+ }
5001
+ constructor(pattern, options) {
5002
+ super();
5003
+ this.pattern = pattern;
5004
+ this.options = alphabetize(options ?? "");
5005
+ if (this.pattern.indexOf("\0") !== -1) {
5006
+ throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`);
5007
+ }
5008
+ if (this.options.indexOf("\0") !== -1) {
5009
+ throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`);
5010
+ }
5011
+ for (let i = 0; i < this.options.length; i++) {
5012
+ 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")) {
5013
+ throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`);
5014
+ }
5015
+ }
5016
+ }
5017
+ static parseOptions(options) {
5018
+ return options ? options.split("").sort().join("") : "";
5019
+ }
5020
+ toExtendedJSON(options) {
5021
+ options = options || {};
5022
+ if (options.legacy) {
5023
+ return { $regex: this.pattern, $options: this.options };
5024
+ }
5025
+ return { $regularExpression: { pattern: this.pattern, options: this.options } };
5026
+ }
5027
+ static fromExtendedJSON(doc) {
5028
+ if ("$regex" in doc) {
5029
+ if (typeof doc.$regex !== "string") {
5030
+ if (doc.$regex._bsontype === "BSONRegExp") {
5031
+ return doc;
5032
+ }
5033
+ } else {
5034
+ return new _BSONRegExp(doc.$regex, _BSONRegExp.parseOptions(doc.$options));
5035
+ }
5036
+ }
5037
+ if ("$regularExpression" in doc) {
5038
+ return new _BSONRegExp(doc.$regularExpression.pattern, _BSONRegExp.parseOptions(doc.$regularExpression.options));
5039
+ }
5040
+ throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`);
5041
+ }
5042
+ inspect(depth, options, inspect) {
5043
+ const stylize = getStylizeFunction(options) ?? ((v) => v);
5044
+ inspect ?? (inspect = defaultInspect);
5045
+ const pattern = stylize(inspect(this.pattern), "regexp");
5046
+ const flags = stylize(inspect(this.options), "regexp");
5047
+ return `new BSONRegExp(${pattern}, ${flags})`;
5048
+ }
5049
+ };
5050
+ __name(_BSONRegExp, "BSONRegExp");
5051
+ var BSONRegExp = _BSONRegExp;
5052
+ var _BSONSymbol = class _BSONSymbol extends BSONValue {
5053
+ get _bsontype() {
5054
+ return "BSONSymbol";
5055
+ }
5056
+ constructor(value) {
5057
+ super();
5058
+ this.value = value;
5059
+ }
5060
+ valueOf() {
5061
+ return this.value;
5062
+ }
5063
+ toString() {
5064
+ return this.value;
5065
+ }
5066
+ toJSON() {
5067
+ return this.value;
5068
+ }
5069
+ toExtendedJSON() {
5070
+ return { $symbol: this.value };
5071
+ }
5072
+ static fromExtendedJSON(doc) {
5073
+ return new _BSONSymbol(doc.$symbol);
5074
+ }
5075
+ inspect(depth, options, inspect) {
5076
+ inspect ?? (inspect = defaultInspect);
5077
+ return `new BSONSymbol(${inspect(this.value, options)})`;
5078
+ }
5079
+ };
5080
+ __name(_BSONSymbol, "BSONSymbol");
5081
+ var BSONSymbol = _BSONSymbol;
5082
+ var LongWithoutOverridesClass = Long;
5083
+ var _Timestamp = class _Timestamp extends LongWithoutOverridesClass {
5084
+ get _bsontype() {
5085
+ return "Timestamp";
5086
+ }
5087
+ get i() {
5088
+ return this.low >>> 0;
5089
+ }
5090
+ get t() {
5091
+ return this.high >>> 0;
5092
+ }
5093
+ constructor(low) {
5094
+ if (low == null) {
5095
+ super(0, 0, true);
5096
+ } else if (typeof low === "bigint") {
5097
+ super(low, true);
5098
+ } else if (Long.isLong(low)) {
5099
+ super(low.low, low.high, true);
5100
+ } else if (typeof low === "object" && "t" in low && "i" in low) {
5101
+ if (typeof low.t !== "number" && (typeof low.t !== "object" || low.t._bsontype !== "Int32")) {
5102
+ throw new BSONError("Timestamp constructed from { t, i } must provide t as a number");
5103
+ }
5104
+ if (typeof low.i !== "number" && (typeof low.i !== "object" || low.i._bsontype !== "Int32")) {
5105
+ throw new BSONError("Timestamp constructed from { t, i } must provide i as a number");
5106
+ }
5107
+ const t = Number(low.t);
5108
+ const i = Number(low.i);
5109
+ if (t < 0 || Number.isNaN(t)) {
5110
+ throw new BSONError("Timestamp constructed from { t, i } must provide a positive t");
5111
+ }
5112
+ if (i < 0 || Number.isNaN(i)) {
5113
+ throw new BSONError("Timestamp constructed from { t, i } must provide a positive i");
5114
+ }
5115
+ if (t > 4294967295) {
5116
+ throw new BSONError("Timestamp constructed from { t, i } must provide t equal or less than uint32 max");
5117
+ }
5118
+ if (i > 4294967295) {
5119
+ throw new BSONError("Timestamp constructed from { t, i } must provide i equal or less than uint32 max");
5120
+ }
5121
+ super(i, t, true);
5122
+ } else {
5123
+ throw new BSONError("A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }");
5124
+ }
5125
+ }
5126
+ toJSON() {
5127
+ return {
5128
+ $timestamp: this.toString()
5129
+ };
5130
+ }
5131
+ static fromInt(value) {
5132
+ return new _Timestamp(Long.fromInt(value, true));
5133
+ }
5134
+ static fromNumber(value) {
5135
+ return new _Timestamp(Long.fromNumber(value, true));
5136
+ }
5137
+ static fromBits(lowBits, highBits) {
5138
+ return new _Timestamp({ i: lowBits, t: highBits });
5139
+ }
5140
+ static fromString(str, optRadix) {
5141
+ return new _Timestamp(Long.fromString(str, true, optRadix));
5142
+ }
5143
+ toExtendedJSON() {
5144
+ return { $timestamp: { t: this.t, i: this.i } };
5145
+ }
5146
+ static fromExtendedJSON(doc) {
5147
+ const i = Long.isLong(doc.$timestamp.i) ? doc.$timestamp.i.getLowBitsUnsigned() : doc.$timestamp.i;
5148
+ const t = Long.isLong(doc.$timestamp.t) ? doc.$timestamp.t.getLowBitsUnsigned() : doc.$timestamp.t;
5149
+ return new _Timestamp({ t, i });
5150
+ }
5151
+ inspect(depth, options, inspect) {
5152
+ inspect ?? (inspect = defaultInspect);
5153
+ const t = inspect(this.t, options);
5154
+ const i = inspect(this.i, options);
5155
+ return `new Timestamp({ t: ${t}, i: ${i} })`;
5156
+ }
5157
+ };
5158
+ __name(_Timestamp, "Timestamp");
5159
+ var Timestamp = _Timestamp;
5160
+ Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE;
5161
+ var JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX);
5162
+ var JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN);
5163
+ function isBSONType(value) {
5164
+ return value != null && typeof value === "object" && "_bsontype" in value && typeof value._bsontype === "string";
5165
+ }
5166
+ __name(isBSONType, "isBSONType");
5167
+ var keysToCodecs = {
5168
+ $oid: ObjectId,
5169
+ $binary: Binary,
5170
+ $uuid: Binary,
5171
+ $symbol: BSONSymbol,
5172
+ $numberInt: Int32,
5173
+ $numberDecimal: Decimal128,
5174
+ $numberDouble: Double,
5175
+ $numberLong: Long,
5176
+ $minKey: MinKey,
5177
+ $maxKey: MaxKey,
5178
+ $regex: BSONRegExp,
5179
+ $regularExpression: BSONRegExp,
5180
+ $timestamp: Timestamp
5181
+ };
5182
+ function deserializeValue(value, options = {}) {
5183
+ if (typeof value === "number") {
5184
+ const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN;
5185
+ const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN;
5186
+ if (options.relaxed || options.legacy) {
5187
+ return value;
5188
+ }
5189
+ if (Number.isInteger(value) && !Object.is(value, -0)) {
5190
+ if (in32BitRange) {
5191
+ return new Int32(value);
5192
+ }
5193
+ if (in64BitRange) {
5194
+ if (options.useBigInt64) {
5195
+ return BigInt(value);
5196
+ }
5197
+ return Long.fromNumber(value);
5198
+ }
5199
+ }
5200
+ return new Double(value);
5201
+ }
5202
+ if (value == null || typeof value !== "object")
5203
+ return value;
5204
+ if (value.$undefined)
5205
+ return null;
5206
+ const keys = Object.keys(value).filter((k) => k.startsWith("$") && value[k] != null);
5207
+ for (let i = 0; i < keys.length; i++) {
5208
+ const c = keysToCodecs[keys[i]];
5209
+ if (c)
5210
+ return c.fromExtendedJSON(value, options);
5211
+ }
5212
+ if (value.$date != null) {
5213
+ const d = value.$date;
5214
+ const date = /* @__PURE__ */ new Date();
5215
+ if (options.legacy) {
5216
+ if (typeof d === "number")
5217
+ date.setTime(d);
5218
+ else if (typeof d === "string")
5219
+ date.setTime(Date.parse(d));
5220
+ else if (typeof d === "bigint")
5221
+ date.setTime(Number(d));
5222
+ else
5223
+ throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
5224
+ } else {
5225
+ if (typeof d === "string")
5226
+ date.setTime(Date.parse(d));
5227
+ else if (Long.isLong(d))
5228
+ date.setTime(d.toNumber());
5229
+ else if (typeof d === "number" && options.relaxed)
5230
+ date.setTime(d);
5231
+ else if (typeof d === "bigint")
5232
+ date.setTime(Number(d));
5233
+ else
5234
+ throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
5235
+ }
5236
+ return date;
5237
+ }
5238
+ if (value.$code != null) {
5239
+ const copy = Object.assign({}, value);
5240
+ if (value.$scope) {
5241
+ copy.$scope = deserializeValue(value.$scope);
5242
+ }
5243
+ return Code.fromExtendedJSON(value);
5244
+ }
5245
+ if (isDBRefLike(value) || value.$dbPointer) {
5246
+ const v = value.$ref ? value : value.$dbPointer;
5247
+ if (v instanceof DBRef)
5248
+ return v;
5249
+ const dollarKeys = Object.keys(v).filter((k) => k.startsWith("$"));
5250
+ let valid = true;
5251
+ dollarKeys.forEach((k) => {
5252
+ if (["$ref", "$id", "$db"].indexOf(k) === -1)
5253
+ valid = false;
5254
+ });
5255
+ if (valid)
5256
+ return DBRef.fromExtendedJSON(v);
5257
+ }
5258
+ return value;
5259
+ }
5260
+ __name(deserializeValue, "deserializeValue");
5261
+ function serializeArray(array, options) {
5262
+ return array.map((v, index) => {
5263
+ options.seenObjects.push({ propertyName: `index ${index}`, obj: null });
5264
+ try {
5265
+ return serializeValue(v, options);
5266
+ } finally {
5267
+ options.seenObjects.pop();
5268
+ }
5269
+ });
5270
+ }
5271
+ __name(serializeArray, "serializeArray");
5272
+ function getISOString(date) {
5273
+ const isoStr = date.toISOString();
5274
+ return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + "Z";
5275
+ }
5276
+ __name(getISOString, "getISOString");
5277
+ function serializeValue(value, options) {
5278
+ if (value instanceof Map || isMap(value)) {
5279
+ const obj = /* @__PURE__ */ Object.create(null);
5280
+ for (const [k, v] of value) {
5281
+ if (typeof k !== "string") {
5282
+ throw new BSONError("Can only serialize maps with string keys");
5283
+ }
5284
+ obj[k] = v;
5285
+ }
5286
+ return serializeValue(obj, options);
5287
+ }
5288
+ if ((typeof value === "object" || typeof value === "function") && value !== null) {
5289
+ const index = options.seenObjects.findIndex((entry) => entry.obj === value);
5290
+ if (index !== -1) {
5291
+ const props = options.seenObjects.map((entry) => entry.propertyName);
5292
+ const leadingPart = props.slice(0, index).map((prop) => `${prop} -> `).join("");
5293
+ const alreadySeen = props[index];
5294
+ const circularPart = " -> " + props.slice(index + 1, props.length - 1).map((prop) => `${prop} -> `).join("");
5295
+ const current = props[props.length - 1];
5296
+ const leadingSpace = " ".repeat(leadingPart.length + alreadySeen.length / 2);
5297
+ const dashes = "-".repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1);
5298
+ throw new BSONError(`Converting circular structure to EJSON:
5299
+ ${leadingPart}${alreadySeen}${circularPart}${current}
5300
+ ${leadingSpace}\\${dashes}/`);
5301
+ }
5302
+ options.seenObjects[options.seenObjects.length - 1].obj = value;
5303
+ }
5304
+ if (Array.isArray(value))
5305
+ return serializeArray(value, options);
5306
+ if (value === void 0)
5307
+ return null;
5308
+ if (value instanceof Date || isDate(value)) {
5309
+ const dateNum = value.getTime(), inRange = dateNum > -1 && dateNum < 2534023188e5;
5310
+ if (options.legacy) {
5311
+ return options.relaxed && inRange ? { $date: value.getTime() } : { $date: getISOString(value) };
5312
+ }
5313
+ return options.relaxed && inRange ? { $date: getISOString(value) } : { $date: { $numberLong: value.getTime().toString() } };
5314
+ }
5315
+ if (typeof value === "number" && (!options.relaxed || !isFinite(value))) {
5316
+ if (Number.isInteger(value) && !Object.is(value, -0)) {
5317
+ if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
5318
+ return { $numberInt: value.toString() };
5319
+ }
5320
+ if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) {
5321
+ return { $numberLong: value.toString() };
5322
+ }
5323
+ }
5324
+ return { $numberDouble: Object.is(value, -0) ? "-0.0" : value.toString() };
5325
+ }
5326
+ if (typeof value === "bigint") {
5327
+ if (!options.relaxed) {
5328
+ return { $numberLong: BigInt.asIntN(64, value).toString() };
5329
+ }
5330
+ return Number(BigInt.asIntN(64, value));
5331
+ }
5332
+ if (value instanceof RegExp || isRegExp(value)) {
5333
+ let flags = value.flags;
5334
+ if (flags === void 0) {
5335
+ const match = value.toString().match(/[gimuy]*$/);
5336
+ if (match) {
5337
+ flags = match[0];
5338
+ }
5339
+ }
5340
+ const rx = new BSONRegExp(value.source, flags);
5341
+ return rx.toExtendedJSON(options);
5342
+ }
5343
+ if (value != null && typeof value === "object")
5344
+ return serializeDocument(value, options);
5345
+ return value;
5346
+ }
5347
+ __name(serializeValue, "serializeValue");
5348
+ var BSON_TYPE_MAPPINGS = {
5349
+ Binary: /* @__PURE__ */ __name((o) => new Binary(o.value(), o.sub_type), "Binary"),
5350
+ Code: /* @__PURE__ */ __name((o) => new Code(o.code, o.scope), "Code"),
5351
+ DBRef: /* @__PURE__ */ __name((o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields), "DBRef"),
5352
+ Decimal128: /* @__PURE__ */ __name((o) => new Decimal128(o.bytes), "Decimal128"),
5353
+ Double: /* @__PURE__ */ __name((o) => new Double(o.value), "Double"),
5354
+ Int32: /* @__PURE__ */ __name((o) => new Int32(o.value), "Int32"),
5355
+ Long: /* @__PURE__ */ __name((o) => Long.fromBits(o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_), "Long"),
5356
+ MaxKey: /* @__PURE__ */ __name(() => new MaxKey(), "MaxKey"),
5357
+ MinKey: /* @__PURE__ */ __name(() => new MinKey(), "MinKey"),
5358
+ ObjectId: /* @__PURE__ */ __name((o) => new ObjectId(o), "ObjectId"),
5359
+ BSONRegExp: /* @__PURE__ */ __name((o) => new BSONRegExp(o.pattern, o.options), "BSONRegExp"),
5360
+ BSONSymbol: /* @__PURE__ */ __name((o) => new BSONSymbol(o.value), "BSONSymbol"),
5361
+ Timestamp: /* @__PURE__ */ __name((o) => Timestamp.fromBits(o.low, o.high), "Timestamp")
5362
+ };
5363
+ function serializeDocument(doc, options) {
5364
+ if (doc == null || typeof doc !== "object")
5365
+ throw new BSONError("not an object instance");
5366
+ const bsontype = doc._bsontype;
5367
+ if (typeof bsontype === "undefined") {
5368
+ const _doc = {};
5369
+ for (const name of Object.keys(doc)) {
5370
+ options.seenObjects.push({ propertyName: name, obj: null });
5371
+ try {
5372
+ const value = serializeValue(doc[name], options);
5373
+ if (name === "__proto__") {
5374
+ Object.defineProperty(_doc, name, {
5375
+ value,
5376
+ writable: true,
5377
+ enumerable: true,
5378
+ configurable: true
5379
+ });
5380
+ } else {
5381
+ _doc[name] = value;
5382
+ }
5383
+ } finally {
5384
+ options.seenObjects.pop();
5385
+ }
5386
+ }
5387
+ return _doc;
5388
+ } else if (doc != null && typeof doc === "object" && typeof doc._bsontype === "string" && doc[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
5389
+ throw new BSONVersionError();
5390
+ } else if (isBSONType(doc)) {
5391
+ let outDoc = doc;
5392
+ if (typeof outDoc.toExtendedJSON !== "function") {
5393
+ const mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
5394
+ if (!mapper) {
5395
+ throw new BSONError("Unrecognized or invalid _bsontype: " + doc._bsontype);
5396
+ }
5397
+ outDoc = mapper(outDoc);
5398
+ }
5399
+ if (bsontype === "Code" && outDoc.scope) {
5400
+ outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options));
5401
+ } else if (bsontype === "DBRef" && outDoc.oid) {
5402
+ outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options));
5403
+ }
5404
+ return outDoc.toExtendedJSON(options);
5405
+ } else {
5406
+ throw new BSONError("_bsontype must be a string, but was: " + typeof bsontype);
5407
+ }
5408
+ }
5409
+ __name(serializeDocument, "serializeDocument");
5410
+ function parse2(text, options) {
5411
+ const ejsonOptions = {
5412
+ useBigInt64: options?.useBigInt64 ?? false,
5413
+ relaxed: options?.relaxed ?? true,
5414
+ legacy: options?.legacy ?? false
5415
+ };
5416
+ return JSON.parse(text, (key, value) => {
5417
+ if (key.indexOf("\0") !== -1) {
5418
+ throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`);
5419
+ }
5420
+ return deserializeValue(value, ejsonOptions);
5421
+ });
5422
+ }
5423
+ __name(parse2, "parse");
5424
+ function stringify(value, replacer, space, options) {
5425
+ if (space != null && typeof space === "object") {
5426
+ options = space;
5427
+ space = 0;
5428
+ }
5429
+ if (replacer != null && typeof replacer === "object" && !Array.isArray(replacer)) {
5430
+ options = replacer;
5431
+ replacer = void 0;
5432
+ space = 0;
5433
+ }
5434
+ const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, {
5435
+ seenObjects: [{ propertyName: "(root)", obj: null }]
5436
+ });
5437
+ const doc = serializeValue(value, serializeOptions);
5438
+ return JSON.stringify(doc, replacer, space);
5439
+ }
5440
+ __name(stringify, "stringify");
5441
+ function EJSONserialize(value, options) {
5442
+ options = options || {};
5443
+ return JSON.parse(stringify(value, options));
5444
+ }
5445
+ __name(EJSONserialize, "EJSONserialize");
5446
+ function EJSONdeserialize(ejson, options) {
5447
+ options = options || {};
5448
+ return parse2(JSON.stringify(ejson), options);
5449
+ }
5450
+ __name(EJSONdeserialize, "EJSONdeserialize");
5451
+ var EJSON = /* @__PURE__ */ Object.create(null);
5452
+ EJSON.parse = parse2;
5453
+ EJSON.stringify = stringify;
5454
+ EJSON.serialize = EJSONserialize;
5455
+ EJSON.deserialize = EJSONdeserialize;
5456
+ Object.freeze(EJSON);
5457
+ var BSONElementType = {
5458
+ double: 1,
5459
+ string: 2,
5460
+ object: 3,
5461
+ array: 4,
5462
+ binData: 5,
5463
+ undefined: 6,
5464
+ objectId: 7,
5465
+ bool: 8,
5466
+ date: 9,
5467
+ null: 10,
5468
+ regex: 11,
5469
+ dbPointer: 12,
5470
+ javascript: 13,
5471
+ symbol: 14,
5472
+ javascriptWithScope: 15,
5473
+ int: 16,
5474
+ timestamp: 17,
5475
+ long: 18,
5476
+ decimal: 19,
5477
+ minKey: 255,
5478
+ maxKey: 127
5479
+ };
5480
+ function getSize(source, offset) {
5481
+ try {
5482
+ return NumberUtils.getNonnegativeInt32LE(source, offset);
5483
+ } catch (cause) {
5484
+ throw new BSONOffsetError("BSON size cannot be negative", offset, { cause });
5485
+ }
5486
+ }
5487
+ __name(getSize, "getSize");
5488
+ function findNull(bytes, offset) {
5489
+ let nullTerminatorOffset = offset;
5490
+ for (; bytes[nullTerminatorOffset] !== 0; nullTerminatorOffset++)
5491
+ ;
5492
+ if (nullTerminatorOffset === bytes.length - 1) {
5493
+ throw new BSONOffsetError("Null terminator not found", offset);
5494
+ }
5495
+ return nullTerminatorOffset;
5496
+ }
5497
+ __name(findNull, "findNull");
5498
+ function parseToElements(bytes, startOffset = 0) {
5499
+ startOffset ?? (startOffset = 0);
5500
+ if (bytes.length < 5) {
5501
+ throw new BSONOffsetError(`Input must be at least 5 bytes, got ${bytes.length} bytes`, startOffset);
5502
+ }
5503
+ const documentSize = getSize(bytes, startOffset);
5504
+ if (documentSize > bytes.length - startOffset) {
5505
+ throw new BSONOffsetError(`Parsed documentSize (${documentSize} bytes) does not match input length (${bytes.length} bytes)`, startOffset);
5506
+ }
5507
+ if (bytes[startOffset + documentSize - 1] !== 0) {
5508
+ throw new BSONOffsetError("BSON documents must end in 0x00", startOffset + documentSize);
5509
+ }
5510
+ const elements = [];
5511
+ let offset = startOffset + 4;
5512
+ while (offset <= documentSize + startOffset) {
5513
+ const type = bytes[offset];
5514
+ offset += 1;
5515
+ if (type === 0) {
5516
+ if (offset - startOffset !== documentSize) {
5517
+ throw new BSONOffsetError(`Invalid 0x00 type byte`, offset);
5518
+ }
5519
+ break;
5520
+ }
5521
+ const nameOffset = offset;
5522
+ const nameLength = findNull(bytes, offset) - nameOffset;
5523
+ offset += nameLength + 1;
5524
+ let length;
5525
+ if (type === BSONElementType.double || type === BSONElementType.long || type === BSONElementType.date || type === BSONElementType.timestamp) {
5526
+ length = 8;
5527
+ } else if (type === BSONElementType.int) {
5528
+ length = 4;
5529
+ } else if (type === BSONElementType.objectId) {
5530
+ length = 12;
5531
+ } else if (type === BSONElementType.decimal) {
5532
+ length = 16;
5533
+ } else if (type === BSONElementType.bool) {
5534
+ length = 1;
5535
+ } else if (type === BSONElementType.null || type === BSONElementType.undefined || type === BSONElementType.maxKey || type === BSONElementType.minKey) {
5536
+ length = 0;
5537
+ } else if (type === BSONElementType.regex) {
5538
+ length = findNull(bytes, findNull(bytes, offset) + 1) + 1 - offset;
5539
+ } else if (type === BSONElementType.object || type === BSONElementType.array || type === BSONElementType.javascriptWithScope) {
5540
+ length = getSize(bytes, offset);
5541
+ } else if (type === BSONElementType.string || type === BSONElementType.binData || type === BSONElementType.dbPointer || type === BSONElementType.javascript || type === BSONElementType.symbol) {
5542
+ length = getSize(bytes, offset) + 4;
5543
+ if (type === BSONElementType.binData) {
5544
+ length += 1;
5545
+ }
5546
+ if (type === BSONElementType.dbPointer) {
5547
+ length += 12;
5548
+ }
5549
+ } else {
5550
+ throw new BSONOffsetError(`Invalid 0x${type.toString(16).padStart(2, "0")} type byte`, offset);
5551
+ }
5552
+ if (length > documentSize) {
5553
+ throw new BSONOffsetError("value reports length larger than document", offset);
5554
+ }
5555
+ elements.push([type, nameOffset, nameLength, offset, length]);
5556
+ offset += length;
5557
+ }
5558
+ return elements;
5559
+ }
5560
+ __name(parseToElements, "parseToElements");
5561
+ var onDemand = /* @__PURE__ */ Object.create(null);
5562
+ onDemand.parseToElements = parseToElements;
5563
+ onDemand.ByteUtils = ByteUtils;
5564
+ onDemand.NumberUtils = NumberUtils;
5565
+ Object.freeze(onDemand);
5566
+ var MAXSIZE = 1024 * 1024 * 17;
5567
+ var buffer = ByteUtils.allocate(MAXSIZE);
5568
+
2398
5569
  // src/framework/abdb/collection/index.ts
2399
5570
  var import_aio_lib_db = require("@adobe/aio-lib-db");
2400
5571
 
@@ -2900,144 +6071,193 @@ var _AbdbRepository = class _AbdbRepository {
2900
6071
  );
2901
6072
  }
2902
6073
  /**
2903
- * Returns `true` when a document with the given `_id` exists in the collection.
2904
- * Uses `countDocuments` rather than fetching the full document for efficiency.
6074
+ * Returns the document with the given `_id`, or `null` if none found.
2905
6075
  *
2906
- * @param id - The `_id` to check
2907
- * @returns `true` if the document exists, `false` otherwise
6076
+ * @param id - The `_id` of the document to find (string or ObjectId)
6077
+ * @returns The matched document, or `null`
2908
6078
  */
2909
- async exists(id) {
2910
- if (!id) return false;
2911
- const n = await this._collection.run(
6079
+ async findById(id) {
6080
+ return await this.findOne({ _id: new ObjectId(String(id)) });
6081
+ }
6082
+ /**
6083
+ * Deletes all documents matching `filter` using a single `deleteMany` call.
6084
+ * Passing no filter (or an empty object) deletes every document in the collection.
6085
+ *
6086
+ * @param filter - Query filter (e.g. `{ _id: 'abc' }` or `{ email: 'a@b.com' }`)
6087
+ * @returns The raw `deleteMany` result document (e.g. `acknowledged`, `deletedCount`)
6088
+ */
6089
+ async delete(filter = {}) {
6090
+ return await this._collection.run(
2912
6091
  (collection) => {
2913
- return collection.countDocuments({ _id: id });
6092
+ return collection.deleteMany(filter);
2914
6093
  },
2915
6094
  this._token,
2916
6095
  this._region
2917
6096
  );
2918
- return n > 0;
2919
6097
  }
2920
6098
  /**
2921
- * Returns the number of documents in the collection matching `filter`.
2922
- * Passing no filter (or an empty object) counts every document.
6099
+ * Deletes the first document matching `filter` using a single `deleteOne` call.
2923
6100
  *
2924
- * @param filter - Optional query filter (default: `{}`)
2925
- * @returns Total number of matching documents
6101
+ * @param filter - Query filter (e.g. `{ _id: 'abc' }` or `{ email: 'a@b.com' }`)
6102
+ * @returns The raw `deleteOne` result document (e.g. `acknowledged`, `deletedCount`)
2926
6103
  */
2927
- async count(filter = {}) {
2928
- return this._collection.run(
6104
+ async deleteOne(filter = {}) {
6105
+ return await this._collection.run(
2929
6106
  (collection) => {
2930
- return collection.countDocuments(filter);
6107
+ return collection.deleteOne(filter);
2931
6108
  },
2932
6109
  this._token,
2933
6110
  this._region
2934
6111
  );
2935
6112
  }
2936
6113
  /**
2937
- * Inserts or updates a document.
6114
+ * Deletes the document with the given `_id` using a single `deleteOne` call.
2938
6115
  *
2939
- * - **Insert** (no `id`): stamps both `_created_at` and `_updated_at`, runs full schema
2940
- * validation, then calls `insertOne`. Returns the new document's `_id`.
2941
- * - **Update** (with `id`): stamps `_updated_at`, runs **partial** validation (only columns
2942
- * present in the payload are checked — required fields that are absent are not enforced
2943
- * because they already exist in the stored document), then calls `updateOne` with
2944
- * `upsert: true`. Returns the same `id` that was passed in.
6116
+ * @param id - The `_id` of the document to delete (string or ObjectId)
6117
+ * @returns The raw `deleteOne` result document (e.g. `acknowledged`, `deletedCount`)
6118
+ */
6119
+ async deleteById(id) {
6120
+ return await this.deleteOne({ _id: new ObjectId(String(id)) });
6121
+ }
6122
+ /**
6123
+ * Inserts multiple documents in a single `insertMany` call.
6124
+ * Each payload is stamped with `_created_at` / `_updated_at` and validated
6125
+ * against the full collection schema before the bulk write is sent to the DB.
2945
6126
  *
2946
- * @param payload - Document fields to write
2947
- * @param id - When provided, updates the document with this `_id`; otherwise inserts
2948
- * @returns The `_id` of the inserted or updated document
6127
+ * @param payloads - Array of document payloads to insert
6128
+ * @returns The raw `insertMany` result document (e.g. `acknowledged`, `insertedIds`)
2949
6129
  */
2950
- async save(payload = {}, id = "") {
6130
+ async insert(payloads) {
2951
6131
  const now = (/* @__PURE__ */ new Date()).toISOString();
2952
- if (id) {
2953
- const updatePayload = { ...payload, _updated_at: now };
2954
- this._validatePartial(updatePayload);
2955
- await this._collection.run(
2956
- async (collection) => {
2957
- await collection.updateOne({ _id: id }, updatePayload, { upsert: true });
2958
- },
2959
- this._token,
2960
- this._region
2961
- );
2962
- return id;
2963
- }
2964
- const insertPayload = { ...payload, _created_at: now, _updated_at: now };
2965
- this._collection.validate(insertPayload);
2966
- return this._collection.run(
2967
- async (collection) => {
2968
- return collection.insertOne(insertPayload);
6132
+ const insertPayloads = payloads.map((payload) => {
6133
+ const doc = { ...payload, _created_at: now, _updated_at: now };
6134
+ this._collection.validate(doc);
6135
+ return doc;
6136
+ });
6137
+ return await this._collection.run(
6138
+ (collection) => {
6139
+ return collection.insertMany(insertPayloads);
2969
6140
  },
2970
6141
  this._token,
2971
6142
  this._region
2972
6143
  );
2973
6144
  }
2974
6145
  /**
2975
- * Deletes the document with the given `_id`. No-ops silently when `id` is empty.
6146
+ * Inserts a single document in a single `insertOne` call.
6147
+ * The payload is stamped with `_created_at` / `_updated_at` and validated
6148
+ * against the full collection schema before the write is sent to the DB.
2976
6149
  *
2977
- * @param id - The `_id` of the document to delete
6150
+ * @param payload - Document payload to insert
6151
+ * @returns The raw `insertOne` result document (e.g. `acknowledged`, `insertedId`)
2978
6152
  */
2979
- async delete(id = "") {
2980
- if (!id) return;
2981
- await this._collection.run(
2982
- async (collection) => {
2983
- await collection.deleteOne({ _id: id });
6153
+ async insertOne(payload) {
6154
+ const now = (/* @__PURE__ */ new Date()).toISOString();
6155
+ const doc = { ...payload, _created_at: now, _updated_at: now };
6156
+ this._collection.validate(doc);
6157
+ return await this._collection.run(
6158
+ (collection) => {
6159
+ return collection.insertOne(doc);
2984
6160
  },
2985
6161
  this._token,
2986
6162
  this._region
2987
6163
  );
2988
6164
  }
2989
6165
  /**
2990
- * Inserts multiple documents in a single `insertMany` call.
2991
- * Each payload is stamped with `_created_at` / `_updated_at` and validated
6166
+ * Updates multiple documents in a single `updateMany` call.
6167
+ * Each payload is stamped with `_updated_at` and validated
2992
6168
  * against the full collection schema before the bulk write is sent to the DB.
2993
6169
  *
2994
- * @param payloads - Array of document payloads to insert
2995
- * @returns Array of inserted `_id` values in insertion order
6170
+ * @param payload - Document fields to apply to every matched document
6171
+ * @param filter - Query filter (e.g. `{ _id: 'abc' }` or `{ email: 'a@b.com' }`)
6172
+ * @param options - Optional `updateMany` options (e.g. `{ upsert: true }`)
6173
+ * @returns The raw `updateMany` result document (e.g. `acknowledged`, `modifiedCount`)
2996
6174
  */
2997
- async insertAll(payloads) {
2998
- const now = (/* @__PURE__ */ new Date()).toISOString();
2999
- const insertPayloads = payloads.map((payload) => {
3000
- const doc = { ...payload, _created_at: now, _updated_at: now };
3001
- this._collection.validate(doc);
3002
- return doc;
3003
- });
3004
- return this._collection.run(
3005
- async (collection) => {
3006
- return collection.insertMany(insertPayloads);
6175
+ async update(payload, filter = {}, options = {}) {
6176
+ const updatePayload = {
6177
+ ...payload,
6178
+ _updated_at: (/* @__PURE__ */ new Date()).toISOString()
6179
+ };
6180
+ this._validatePartial(updatePayload);
6181
+ return await this._collection.run(
6182
+ (collection) => {
6183
+ return collection.updateMany(filter, { $set: updatePayload }, options);
3007
6184
  },
3008
6185
  this._token,
3009
6186
  this._region
3010
6187
  );
3011
6188
  }
3012
6189
  /**
3013
- * Applies a partial update to all documents matching `filter` using a single `updateMany` call.
3014
- * Stamps `_updated_at` on every matched document and runs partial validation on the payload
3015
- * (only the columns present in the payload are checked).
6190
+ * Updates a single document in a single `updateOne` call.
6191
+ * The payload is stamped with `_updated_at` and validated
6192
+ * against the full collection schema before the write is sent to the DB.
3016
6193
  *
3017
- * @param payload - Fields to update on every matched document
3018
- * @param filter - Query condition selecting which documents to update (default: `{}` all documents)
6194
+ * @param payload - Document payload to update
6195
+ * @param filter - Query filter (e.g. `{ _id: 'abc' }` or `{ email: 'a@b.com' }`)
6196
+ * @param options - Optional `updateOne` options (e.g. `{ upsert: true }`)
6197
+ * @returns The raw `updateOne` result document (e.g. `acknowledged`, `modifiedCount`)
3019
6198
  */
3020
- async updateAll(payload, filter = {}) {
3021
- const updatePayload = { ...payload, _updated_at: (/* @__PURE__ */ new Date()).toISOString() };
6199
+ async updateOne(payload, filter = {}, options = {}) {
6200
+ const updatePayload = {
6201
+ ...payload,
6202
+ _updated_at: (/* @__PURE__ */ new Date()).toISOString()
6203
+ };
3022
6204
  this._validatePartial(updatePayload);
3023
- await this._collection.run(
3024
- async (collection) => {
3025
- await collection.updateMany(filter, updatePayload);
6205
+ return await this._collection.run(
6206
+ (collection) => {
6207
+ return collection.updateOne(filter, { $set: updatePayload }, options);
3026
6208
  },
3027
6209
  this._token,
3028
6210
  this._region
3029
6211
  );
3030
6212
  }
3031
6213
  /**
3032
- * Deletes all documents matching `filter` using a single `deleteMany` call.
3033
- * Passing no filter (or an empty object) deletes every document in the collection.
6214
+ * Inserts or updates a document.
3034
6215
  *
3035
- * @param filter - Optional query filter (default: `{}`)
6216
+ * @param payload - Document payload to insert or update
6217
+ * @param id - The `_id` of the document to update (string or ObjectId)
6218
+ * @returns The raw `insertOne` or `updateOne` result document (e.g. `acknowledged`, `insertedId`, `modifiedCount`)
3036
6219
  */
3037
- async deleteAll(filter = {}) {
3038
- await this._collection.run(
3039
- async (collection) => {
3040
- await collection.deleteMany(filter);
6220
+ async save(payload = {}, id = "") {
6221
+ if (id) {
6222
+ return await this.updateOne(payload, { _id: new ObjectId(String(id)) }, { upsert: true });
6223
+ }
6224
+ return await this.insertOne(payload);
6225
+ }
6226
+ /**
6227
+ * Returns `true` when a document with the given `_id` exists in the collection.
6228
+ * Uses `countDocuments` rather than fetching the full document for efficiency.
6229
+ *
6230
+ * @param id - The `_id` to check
6231
+ * @returns `true` if the document exists, `false` otherwise
6232
+ */
6233
+ async isIdExists(id) {
6234
+ if (!id) return false;
6235
+ return await this.exists({ _id: new ObjectId(String(id)) });
6236
+ }
6237
+ /**
6238
+ * Returns `true` when a document matching `filter` exists in the collection.
6239
+ * Uses `countDocuments` rather than fetching the full document for efficiency.
6240
+ *
6241
+ * @param filter - Query filter (e.g. `{ _id: 'abc' }` or `{ email: 'a@b.com' }`)
6242
+ * @param options - Optional `countDocuments` options (e.g. `{ limit: 10 }`)
6243
+ * @returns `true` if the document exists, `false` otherwise
6244
+ */
6245
+ async exists(filter = {}, options = {}) {
6246
+ const n = await this.count(filter, options);
6247
+ return n > 0;
6248
+ }
6249
+ /**
6250
+ * Returns the number of documents in the collection matching `filter`.
6251
+ * Passing no filter (or an empty object) counts every document.
6252
+ *
6253
+ * @param filter - Query filter (e.g. `{ _id: 'abc' }` or `{ email: 'a@b.com' }`)
6254
+ * @param options - Optional `countDocuments` options (e.g. `{ limit: 10 }`)
6255
+ * @returns The number of documents matching the filter
6256
+ */
6257
+ async count(filter = {}, options = {}) {
6258
+ return await this._collection.run(
6259
+ (collection) => {
6260
+ return collection.countDocuments(filter, options);
3041
6261
  },
3042
6262
  this._token,
3043
6263
  this._region
@@ -3048,7 +6268,7 @@ var _AbdbRepository = class _AbdbRepository {
3048
6268
  * Required columns that are absent from the payload are intentionally skipped —
3049
6269
  * they already exist in the stored document and are not being changed.
3050
6270
  *
3051
- * Used by the update path of {@link save} and {@link updateAll}.
6271
+ * Used by {@link update}, {@link updateOne}, and the update path of {@link save}.
3052
6272
  */
3053
6273
  _validatePartial(record) {
3054
6274
  for (const col of this._collection.getColumns()) {
@@ -3410,7 +6630,7 @@ var SignatureVerification = /* @__PURE__ */ ((SignatureVerification2) => {
3410
6630
  })(SignatureVerification || {});
3411
6631
 
3412
6632
  // src/framework/webhook-action/index.ts
3413
- var import_crypto = __toESM(require("crypto"));
6633
+ var import_crypto2 = __toESM(require("crypto"));
3414
6634
  var _WebhookAction = class _WebhookAction {
3415
6635
  /**
3416
6636
  * Execute a webhook action with validation and response handling.
@@ -3626,7 +6846,7 @@ var _WebhookAction = class _WebhookAction {
3626
6846
  return "Public key not found. Make sure the action is configured with the input `PUBLIC_KEY` or `PUBLIC_KEY_BASE64` and it is defined in .env file.";
3627
6847
  }
3628
6848
  try {
3629
- const verifier = import_crypto.default.createVerify("SHA256");
6849
+ const verifier = import_crypto2.default.createVerify("SHA256");
3630
6850
  verifier.update(body);
3631
6851
  const isSignatureValid = verifier.verify(publicKey, signature, "base64");
3632
6852
  if (!isSignatureValid) {
@@ -6915,7 +10135,7 @@ var RegistrationManager = _RegistrationManager;
6915
10135
  var registration_default = RegistrationManager;
6916
10136
 
6917
10137
  // src/integration/onboard-events/create-providers/index.ts
6918
- var import_crypto2 = require("crypto");
10138
+ var import_crypto3 = require("crypto");
6919
10139
  var _CreateProviders = class _CreateProviders {
6920
10140
  /**
6921
10141
  * Creates a new CreateProviders instance
@@ -7109,7 +10329,7 @@ var _CreateProviders = class _CreateProviders {
7109
10329
  }
7110
10330
  if (this.isCommerceProvider(providerData)) {
7111
10331
  input.provider_metadata = "dx_commerce_events";
7112
- input.instance_id = (0, import_crypto2.randomUUID)();
10332
+ input.instance_id = (0, import_crypto3.randomUUID)();
7113
10333
  }
7114
10334
  return input;
7115
10335
  }
@@ -7915,7 +11135,7 @@ var onboard_events_default = OnboardEvents;
7915
11135
 
7916
11136
  // src/integration/infinite-loop-breaker/index.ts
7917
11137
  var import_aio_sdk6 = require("@adobe/aio-sdk");
7918
- var import_crypto3 = __toESM(require("crypto"));
11138
+ var import_crypto4 = __toESM(require("crypto"));
7919
11139
  var _InfiniteLoopBreaker = class _InfiniteLoopBreaker {
7920
11140
  // seconds
7921
11141
  /**
@@ -7995,7 +11215,7 @@ var _InfiniteLoopBreaker = class _InfiniteLoopBreaker {
7995
11215
  * @returns The fingerprint
7996
11216
  */
7997
11217
  static fingerPrint(data) {
7998
- const hash = import_crypto3.default.createHash(_InfiniteLoopBreaker.FINGERPRINT_ALGORITHM);
11218
+ const hash = import_crypto4.default.createHash(_InfiniteLoopBreaker.FINGERPRINT_ALGORITHM);
7999
11219
  hash.update(JSON.stringify(data));
8000
11220
  return hash.digest(_InfiniteLoopBreaker.FINGERPRINT_ENCODING);
8001
11221
  }