UNPKG

314 kBJavaScriptView Raw
1var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
2
3function unwrapExports (x) {
4 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
5}
6
7function createCommonjsModule(fn, module) {
8 return module = { exports: {} }, fn(module, module.exports), module.exports;
9}
10
11var byteLength_1 = byteLength;
12var toByteArray_1 = toByteArray;
13var fromByteArray_1 = fromByteArray;
14var lookup = [];
15var revLookup = [];
16var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
17var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
18
19for (var i = 0, len = code.length; i < len; ++i) {
20 lookup[i] = code[i];
21 revLookup[code.charCodeAt(i)] = i;
22} // Support decoding URL-safe base64 strings, as Node.js does.
23// See: https://en.wikipedia.org/wiki/Base64#URL_applications
24
25
26revLookup['-'.charCodeAt(0)] = 62;
27revLookup['_'.charCodeAt(0)] = 63;
28
29function getLens(b64) {
30 var len = b64.length;
31
32 if (len % 4 > 0) {
33 throw new Error('Invalid string. Length must be a multiple of 4');
34 } // Trim off extra bytes after placeholder bytes are found
35 // See: https://github.com/beatgammit/base64-js/issues/42
36
37
38 var validLen = b64.indexOf('=');
39 if (validLen === -1) validLen = len;
40 var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4;
41 return [validLen, placeHoldersLen];
42} // base64 is 4/3 + up to two characters of the original data
43
44
45function byteLength(b64) {
46 var lens = getLens(b64);
47 var validLen = lens[0];
48 var placeHoldersLen = lens[1];
49 return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
50}
51
52function _byteLength(b64, validLen, placeHoldersLen) {
53 return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
54}
55
56function toByteArray(b64) {
57 var tmp;
58 var lens = getLens(b64);
59 var validLen = lens[0];
60 var placeHoldersLen = lens[1];
61 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
62 var curByte = 0; // if there are placeholders, only get up to the last complete 4 chars
63
64 var len = placeHoldersLen > 0 ? validLen - 4 : validLen;
65 var i;
66
67 for (i = 0; i < len; i += 4) {
68 tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
69 arr[curByte++] = tmp >> 16 & 0xFF;
70 arr[curByte++] = tmp >> 8 & 0xFF;
71 arr[curByte++] = tmp & 0xFF;
72 }
73
74 if (placeHoldersLen === 2) {
75 tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
76 arr[curByte++] = tmp & 0xFF;
77 }
78
79 if (placeHoldersLen === 1) {
80 tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
81 arr[curByte++] = tmp >> 8 & 0xFF;
82 arr[curByte++] = tmp & 0xFF;
83 }
84
85 return arr;
86}
87
88function tripletToBase64(num) {
89 return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F];
90}
91
92function encodeChunk(uint8, start, end) {
93 var tmp;
94 var output = [];
95
96 for (var i = start; i < end; i += 3) {
97 tmp = (uint8[i] << 16 & 0xFF0000) + (uint8[i + 1] << 8 & 0xFF00) + (uint8[i + 2] & 0xFF);
98 output.push(tripletToBase64(tmp));
99 }
100
101 return output.join('');
102}
103
104function fromByteArray(uint8) {
105 var tmp;
106 var len = uint8.length;
107 var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
108
109 var parts = [];
110 var maxChunkLength = 16383; // must be multiple of 3
111 // go through the array every three bytes, we'll deal with trailing stuff later
112
113 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
114 parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
115 } // pad the end with zeros, but make sure to not forget the extra bytes
116
117
118 if (extraBytes === 1) {
119 tmp = uint8[len - 1];
120 parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 0x3F] + '==');
121 } else if (extraBytes === 2) {
122 tmp = (uint8[len - 2] << 8) + uint8[len - 1];
123 parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 0x3F] + lookup[tmp << 2 & 0x3F] + '=');
124 }
125
126 return parts.join('');
127}
128
129var base64Js = {
130 byteLength: byteLength_1,
131 toByteArray: toByteArray_1,
132 fromByteArray: fromByteArray_1
133};
134
135var read = function read(buffer, offset, isLE, mLen, nBytes) {
136 var e, m;
137 var eLen = nBytes * 8 - mLen - 1;
138 var eMax = (1 << eLen) - 1;
139 var eBias = eMax >> 1;
140 var nBits = -7;
141 var i = isLE ? nBytes - 1 : 0;
142 var d = isLE ? -1 : 1;
143 var s = buffer[offset + i];
144 i += d;
145 e = s & (1 << -nBits) - 1;
146 s >>= -nBits;
147 nBits += eLen;
148
149 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
150
151 m = e & (1 << -nBits) - 1;
152 e >>= -nBits;
153 nBits += mLen;
154
155 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
156
157 if (e === 0) {
158 e = 1 - eBias;
159 } else if (e === eMax) {
160 return m ? NaN : (s ? -1 : 1) * Infinity;
161 } else {
162 m = m + Math.pow(2, mLen);
163 e = e - eBias;
164 }
165
166 return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
167};
168
169var write = function write(buffer, value, offset, isLE, mLen, nBytes) {
170 var e, m, c;
171 var eLen = nBytes * 8 - mLen - 1;
172 var eMax = (1 << eLen) - 1;
173 var eBias = eMax >> 1;
174 var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
175 var i = isLE ? 0 : nBytes - 1;
176 var d = isLE ? 1 : -1;
177 var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
178 value = Math.abs(value);
179
180 if (isNaN(value) || value === Infinity) {
181 m = isNaN(value) ? 1 : 0;
182 e = eMax;
183 } else {
184 e = Math.floor(Math.log(value) / Math.LN2);
185
186 if (value * (c = Math.pow(2, -e)) < 1) {
187 e--;
188 c *= 2;
189 }
190
191 if (e + eBias >= 1) {
192 value += rt / c;
193 } else {
194 value += rt * Math.pow(2, 1 - eBias);
195 }
196
197 if (value * c >= 2) {
198 e++;
199 c /= 2;
200 }
201
202 if (e + eBias >= eMax) {
203 m = 0;
204 e = eMax;
205 } else if (e + eBias >= 1) {
206 m = (value * c - 1) * Math.pow(2, mLen);
207 e = e + eBias;
208 } else {
209 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
210 e = 0;
211 }
212 }
213
214 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
215
216 e = e << mLen | m;
217 eLen += mLen;
218
219 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
220
221 buffer[offset + i - d] |= s * 128;
222};
223
224var ieee754 = {
225 read: read,
226 write: write
227};
228
229var buffer = createCommonjsModule(function (module, exports) {
230
231 var customInspectSymbol = typeof Symbol === 'function' && typeof Symbol["for"] === 'function' ? Symbol["for"]('nodejs.util.inspect.custom') : null;
232 exports.Buffer = Buffer;
233 exports.SlowBuffer = SlowBuffer;
234 exports.INSPECT_MAX_BYTES = 50;
235 var K_MAX_LENGTH = 0x7fffffff;
236 exports.kMaxLength = K_MAX_LENGTH;
237 /**
238 * If `Buffer.TYPED_ARRAY_SUPPORT`:
239 * === true Use Uint8Array implementation (fastest)
240 * === false Print warning and recommend using `buffer` v4.x which has an Object
241 * implementation (most compatible, even IE6)
242 *
243 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
244 * Opera 11.6+, iOS 4.2+.
245 *
246 * We report that the browser does not support typed arrays if the are not subclassable
247 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
248 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
249 * for __proto__ and has a buggy typed array implementation.
250 */
251
252 Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport();
253
254 if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && typeof console.error === 'function') {
255 console.error('This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.');
256 }
257
258 function typedArraySupport() {
259 // Can typed array instances can be augmented?
260 try {
261 var arr = new Uint8Array(1);
262 var proto = {
263 foo: function foo() {
264 return 42;
265 }
266 };
267 Object.setPrototypeOf(proto, Uint8Array.prototype);
268 Object.setPrototypeOf(arr, proto);
269 return arr.foo() === 42;
270 } catch (e) {
271 return false;
272 }
273 }
274
275 Object.defineProperty(Buffer.prototype, 'parent', {
276 enumerable: true,
277 get: function get() {
278 if (!Buffer.isBuffer(this)) return undefined;
279 return this.buffer;
280 }
281 });
282 Object.defineProperty(Buffer.prototype, 'offset', {
283 enumerable: true,
284 get: function get() {
285 if (!Buffer.isBuffer(this)) return undefined;
286 return this.byteOffset;
287 }
288 });
289
290 function createBuffer(length) {
291 if (length > K_MAX_LENGTH) {
292 throw new RangeError('The value "' + length + '" is invalid for option "size"');
293 } // Return an augmented `Uint8Array` instance
294
295
296 var buf = new Uint8Array(length);
297 Object.setPrototypeOf(buf, Buffer.prototype);
298 return buf;
299 }
300 /**
301 * The Buffer constructor returns instances of `Uint8Array` that have their
302 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
303 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
304 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
305 * returns a single octet.
306 *
307 * The `Uint8Array` prototype remains unmodified.
308 */
309
310
311 function Buffer(arg, encodingOrOffset, length) {
312 // Common case.
313 if (typeof arg === 'number') {
314 if (typeof encodingOrOffset === 'string') {
315 throw new TypeError('The "string" argument must be of type string. Received type number');
316 }
317
318 return allocUnsafe(arg);
319 }
320
321 return from(arg, encodingOrOffset, length);
322 }
323
324 Buffer.poolSize = 8192; // not used by this implementation
325
326 function from(value, encodingOrOffset, length) {
327 if (typeof value === 'string') {
328 return fromString(value, encodingOrOffset);
329 }
330
331 if (ArrayBuffer.isView(value)) {
332 return fromArrayLike(value);
333 }
334
335 if (value == null) {
336 throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + babelHelpers["typeof"](value));
337 }
338
339 if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) {
340 return fromArrayBuffer(value, encodingOrOffset, length);
341 }
342
343 if (typeof SharedArrayBuffer !== 'undefined' && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) {
344 return fromArrayBuffer(value, encodingOrOffset, length);
345 }
346
347 if (typeof value === 'number') {
348 throw new TypeError('The "value" argument must not be of type number. Received type number');
349 }
350
351 var valueOf = value.valueOf && value.valueOf();
352
353 if (valueOf != null && valueOf !== value) {
354 return Buffer.from(valueOf, encodingOrOffset, length);
355 }
356
357 var b = fromObject(value);
358 if (b) return b;
359
360 if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === 'function') {
361 return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length);
362 }
363
364 throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + babelHelpers["typeof"](value));
365 }
366 /**
367 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
368 * if value is a number.
369 * Buffer.from(str[, encoding])
370 * Buffer.from(array)
371 * Buffer.from(buffer)
372 * Buffer.from(arrayBuffer[, byteOffset[, length]])
373 **/
374
375
376 Buffer.from = function (value, encodingOrOffset, length) {
377 return from(value, encodingOrOffset, length);
378 }; // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
379 // https://github.com/feross/buffer/pull/148
380
381
382 Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype);
383 Object.setPrototypeOf(Buffer, Uint8Array);
384
385 function assertSize(size) {
386 if (typeof size !== 'number') {
387 throw new TypeError('"size" argument must be of type number');
388 } else if (size < 0) {
389 throw new RangeError('The value "' + size + '" is invalid for option "size"');
390 }
391 }
392
393 function alloc(size, fill, encoding) {
394 assertSize(size);
395
396 if (size <= 0) {
397 return createBuffer(size);
398 }
399
400 if (fill !== undefined) {
401 // Only pay attention to encoding if it's a string. This
402 // prevents accidentally sending in a number that would
403 // be interpretted as a start offset.
404 return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
405 }
406
407 return createBuffer(size);
408 }
409 /**
410 * Creates a new filled Buffer instance.
411 * alloc(size[, fill[, encoding]])
412 **/
413
414
415 Buffer.alloc = function (size, fill, encoding) {
416 return alloc(size, fill, encoding);
417 };
418
419 function allocUnsafe(size) {
420 assertSize(size);
421 return createBuffer(size < 0 ? 0 : checked(size) | 0);
422 }
423 /**
424 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
425 * */
426
427
428 Buffer.allocUnsafe = function (size) {
429 return allocUnsafe(size);
430 };
431 /**
432 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
433 */
434
435
436 Buffer.allocUnsafeSlow = function (size) {
437 return allocUnsafe(size);
438 };
439
440 function fromString(string, encoding) {
441 if (typeof encoding !== 'string' || encoding === '') {
442 encoding = 'utf8';
443 }
444
445 if (!Buffer.isEncoding(encoding)) {
446 throw new TypeError('Unknown encoding: ' + encoding);
447 }
448
449 var length = byteLength(string, encoding) | 0;
450 var buf = createBuffer(length);
451 var actual = buf.write(string, encoding);
452
453 if (actual !== length) {
454 // Writing a hex string, for example, that contains invalid characters will
455 // cause everything after the first invalid character to be ignored. (e.g.
456 // 'abxxcd' will be treated as 'ab')
457 buf = buf.slice(0, actual);
458 }
459
460 return buf;
461 }
462
463 function fromArrayLike(array) {
464 var length = array.length < 0 ? 0 : checked(array.length) | 0;
465 var buf = createBuffer(length);
466
467 for (var i = 0; i < length; i += 1) {
468 buf[i] = array[i] & 255;
469 }
470
471 return buf;
472 }
473
474 function fromArrayBuffer(array, byteOffset, length) {
475 if (byteOffset < 0 || array.byteLength < byteOffset) {
476 throw new RangeError('"offset" is outside of buffer bounds');
477 }
478
479 if (array.byteLength < byteOffset + (length || 0)) {
480 throw new RangeError('"length" is outside of buffer bounds');
481 }
482
483 var buf;
484
485 if (byteOffset === undefined && length === undefined) {
486 buf = new Uint8Array(array);
487 } else if (length === undefined) {
488 buf = new Uint8Array(array, byteOffset);
489 } else {
490 buf = new Uint8Array(array, byteOffset, length);
491 } // Return an augmented `Uint8Array` instance
492
493
494 Object.setPrototypeOf(buf, Buffer.prototype);
495 return buf;
496 }
497
498 function fromObject(obj) {
499 if (Buffer.isBuffer(obj)) {
500 var len = checked(obj.length) | 0;
501 var buf = createBuffer(len);
502
503 if (buf.length === 0) {
504 return buf;
505 }
506
507 obj.copy(buf, 0, 0, len);
508 return buf;
509 }
510
511 if (obj.length !== undefined) {
512 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
513 return createBuffer(0);
514 }
515
516 return fromArrayLike(obj);
517 }
518
519 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
520 return fromArrayLike(obj.data);
521 }
522 }
523
524 function checked(length) {
525 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
526 // length is NaN (which is otherwise coerced to zero.)
527 if (length >= K_MAX_LENGTH) {
528 throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes');
529 }
530
531 return length | 0;
532 }
533
534 function SlowBuffer(length) {
535 if (+length != length) {
536 // eslint-disable-line eqeqeq
537 length = 0;
538 }
539
540 return Buffer.alloc(+length);
541 }
542
543 Buffer.isBuffer = function isBuffer(b) {
544 return b != null && b._isBuffer === true && b !== Buffer.prototype; // so Buffer.isBuffer(Buffer.prototype) will be false
545 };
546
547 Buffer.compare = function compare(a, b) {
548 if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength);
549 if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength);
550
551 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
552 throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');
553 }
554
555 if (a === b) return 0;
556 var x = a.length;
557 var y = b.length;
558
559 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
560 if (a[i] !== b[i]) {
561 x = a[i];
562 y = b[i];
563 break;
564 }
565 }
566
567 if (x < y) return -1;
568 if (y < x) return 1;
569 return 0;
570 };
571
572 Buffer.isEncoding = function isEncoding(encoding) {
573 switch (String(encoding).toLowerCase()) {
574 case 'hex':
575 case 'utf8':
576 case 'utf-8':
577 case 'ascii':
578 case 'latin1':
579 case 'binary':
580 case 'base64':
581 case 'ucs2':
582 case 'ucs-2':
583 case 'utf16le':
584 case 'utf-16le':
585 return true;
586
587 default:
588 return false;
589 }
590 };
591
592 Buffer.concat = function concat(list, length) {
593 if (!Array.isArray(list)) {
594 throw new TypeError('"list" argument must be an Array of Buffers');
595 }
596
597 if (list.length === 0) {
598 return Buffer.alloc(0);
599 }
600
601 var i;
602
603 if (length === undefined) {
604 length = 0;
605
606 for (i = 0; i < list.length; ++i) {
607 length += list[i].length;
608 }
609 }
610
611 var buffer = Buffer.allocUnsafe(length);
612 var pos = 0;
613
614 for (i = 0; i < list.length; ++i) {
615 var buf = list[i];
616
617 if (isInstance(buf, Uint8Array)) {
618 buf = Buffer.from(buf);
619 }
620
621 if (!Buffer.isBuffer(buf)) {
622 throw new TypeError('"list" argument must be an Array of Buffers');
623 }
624
625 buf.copy(buffer, pos);
626 pos += buf.length;
627 }
628
629 return buffer;
630 };
631
632 function byteLength(string, encoding) {
633 if (Buffer.isBuffer(string)) {
634 return string.length;
635 }
636
637 if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
638 return string.byteLength;
639 }
640
641 if (typeof string !== 'string') {
642 throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + 'Received type ' + babelHelpers["typeof"](string));
643 }
644
645 var len = string.length;
646 var mustMatch = arguments.length > 2 && arguments[2] === true;
647 if (!mustMatch && len === 0) return 0; // Use a for loop to avoid recursion
648
649 var loweredCase = false;
650
651 for (;;) {
652 switch (encoding) {
653 case 'ascii':
654 case 'latin1':
655 case 'binary':
656 return len;
657
658 case 'utf8':
659 case 'utf-8':
660 return utf8ToBytes(string).length;
661
662 case 'ucs2':
663 case 'ucs-2':
664 case 'utf16le':
665 case 'utf-16le':
666 return len * 2;
667
668 case 'hex':
669 return len >>> 1;
670
671 case 'base64':
672 return base64ToBytes(string).length;
673
674 default:
675 if (loweredCase) {
676 return mustMatch ? -1 : utf8ToBytes(string).length; // assume utf8
677 }
678
679 encoding = ('' + encoding).toLowerCase();
680 loweredCase = true;
681 }
682 }
683 }
684
685 Buffer.byteLength = byteLength;
686
687 function slowToString(encoding, start, end) {
688 var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
689 // property of a typed array.
690 // This behaves neither like String nor Uint8Array in that we set start/end
691 // to their upper/lower bounds if the value passed is out of range.
692 // undefined is handled specially as per ECMA-262 6th Edition,
693 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
694
695 if (start === undefined || start < 0) {
696 start = 0;
697 } // Return early if start > this.length. Done here to prevent potential uint32
698 // coercion fail below.
699
700
701 if (start > this.length) {
702 return '';
703 }
704
705 if (end === undefined || end > this.length) {
706 end = this.length;
707 }
708
709 if (end <= 0) {
710 return '';
711 } // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
712
713
714 end >>>= 0;
715 start >>>= 0;
716
717 if (end <= start) {
718 return '';
719 }
720
721 if (!encoding) encoding = 'utf8';
722
723 while (true) {
724 switch (encoding) {
725 case 'hex':
726 return hexSlice(this, start, end);
727
728 case 'utf8':
729 case 'utf-8':
730 return utf8Slice(this, start, end);
731
732 case 'ascii':
733 return asciiSlice(this, start, end);
734
735 case 'latin1':
736 case 'binary':
737 return latin1Slice(this, start, end);
738
739 case 'base64':
740 return base64Slice(this, start, end);
741
742 case 'ucs2':
743 case 'ucs-2':
744 case 'utf16le':
745 case 'utf-16le':
746 return utf16leSlice(this, start, end);
747
748 default:
749 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
750 encoding = (encoding + '').toLowerCase();
751 loweredCase = true;
752 }
753 }
754 } // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
755 // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
756 // reliably in a browserify context because there could be multiple different
757 // copies of the 'buffer' package in use. This method works even for Buffer
758 // instances that were created from another copy of the `buffer` package.
759 // See: https://github.com/feross/buffer/issues/154
760
761
762 Buffer.prototype._isBuffer = true;
763
764 function swap(b, n, m) {
765 var i = b[n];
766 b[n] = b[m];
767 b[m] = i;
768 }
769
770 Buffer.prototype.swap16 = function swap16() {
771 var len = this.length;
772
773 if (len % 2 !== 0) {
774 throw new RangeError('Buffer size must be a multiple of 16-bits');
775 }
776
777 for (var i = 0; i < len; i += 2) {
778 swap(this, i, i + 1);
779 }
780
781 return this;
782 };
783
784 Buffer.prototype.swap32 = function swap32() {
785 var len = this.length;
786
787 if (len % 4 !== 0) {
788 throw new RangeError('Buffer size must be a multiple of 32-bits');
789 }
790
791 for (var i = 0; i < len; i += 4) {
792 swap(this, i, i + 3);
793 swap(this, i + 1, i + 2);
794 }
795
796 return this;
797 };
798
799 Buffer.prototype.swap64 = function swap64() {
800 var len = this.length;
801
802 if (len % 8 !== 0) {
803 throw new RangeError('Buffer size must be a multiple of 64-bits');
804 }
805
806 for (var i = 0; i < len; i += 8) {
807 swap(this, i, i + 7);
808 swap(this, i + 1, i + 6);
809 swap(this, i + 2, i + 5);
810 swap(this, i + 3, i + 4);
811 }
812
813 return this;
814 };
815
816 Buffer.prototype.toString = function toString() {
817 var length = this.length;
818 if (length === 0) return '';
819 if (arguments.length === 0) return utf8Slice(this, 0, length);
820 return slowToString.apply(this, arguments);
821 };
822
823 Buffer.prototype.toLocaleString = Buffer.prototype.toString;
824
825 Buffer.prototype.equals = function equals(b) {
826 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer');
827 if (this === b) return true;
828 return Buffer.compare(this, b) === 0;
829 };
830
831 Buffer.prototype.inspect = function inspect() {
832 var str = '';
833 var max = exports.INSPECT_MAX_BYTES;
834 str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim();
835 if (this.length > max) str += ' ... ';
836 return '<Buffer ' + str + '>';
837 };
838
839 if (customInspectSymbol) {
840 Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect;
841 }
842
843 Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
844 if (isInstance(target, Uint8Array)) {
845 target = Buffer.from(target, target.offset, target.byteLength);
846 }
847
848 if (!Buffer.isBuffer(target)) {
849 throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. ' + 'Received type ' + babelHelpers["typeof"](target));
850 }
851
852 if (start === undefined) {
853 start = 0;
854 }
855
856 if (end === undefined) {
857 end = target ? target.length : 0;
858 }
859
860 if (thisStart === undefined) {
861 thisStart = 0;
862 }
863
864 if (thisEnd === undefined) {
865 thisEnd = this.length;
866 }
867
868 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
869 throw new RangeError('out of range index');
870 }
871
872 if (thisStart >= thisEnd && start >= end) {
873 return 0;
874 }
875
876 if (thisStart >= thisEnd) {
877 return -1;
878 }
879
880 if (start >= end) {
881 return 1;
882 }
883
884 start >>>= 0;
885 end >>>= 0;
886 thisStart >>>= 0;
887 thisEnd >>>= 0;
888 if (this === target) return 0;
889 var x = thisEnd - thisStart;
890 var y = end - start;
891 var len = Math.min(x, y);
892 var thisCopy = this.slice(thisStart, thisEnd);
893 var targetCopy = target.slice(start, end);
894
895 for (var i = 0; i < len; ++i) {
896 if (thisCopy[i] !== targetCopy[i]) {
897 x = thisCopy[i];
898 y = targetCopy[i];
899 break;
900 }
901 }
902
903 if (x < y) return -1;
904 if (y < x) return 1;
905 return 0;
906 }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
907 // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
908 //
909 // Arguments:
910 // - buffer - a Buffer to search
911 // - val - a string, Buffer, or number
912 // - byteOffset - an index into `buffer`; will be clamped to an int32
913 // - encoding - an optional encoding, relevant is val is a string
914 // - dir - true for indexOf, false for lastIndexOf
915
916
917 function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
918 // Empty buffer means no match
919 if (buffer.length === 0) return -1; // Normalize byteOffset
920
921 if (typeof byteOffset === 'string') {
922 encoding = byteOffset;
923 byteOffset = 0;
924 } else if (byteOffset > 0x7fffffff) {
925 byteOffset = 0x7fffffff;
926 } else if (byteOffset < -0x80000000) {
927 byteOffset = -0x80000000;
928 }
929
930 byteOffset = +byteOffset; // Coerce to Number.
931
932 if (numberIsNaN(byteOffset)) {
933 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
934 byteOffset = dir ? 0 : buffer.length - 1;
935 } // Normalize byteOffset: negative offsets start from the end of the buffer
936
937
938 if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
939
940 if (byteOffset >= buffer.length) {
941 if (dir) return -1;else byteOffset = buffer.length - 1;
942 } else if (byteOffset < 0) {
943 if (dir) byteOffset = 0;else return -1;
944 } // Normalize val
945
946
947 if (typeof val === 'string') {
948 val = Buffer.from(val, encoding);
949 } // Finally, search either indexOf (if dir is true) or lastIndexOf
950
951
952 if (Buffer.isBuffer(val)) {
953 // Special case: looking for empty string/buffer always fails
954 if (val.length === 0) {
955 return -1;
956 }
957
958 return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
959 } else if (typeof val === 'number') {
960 val = val & 0xFF; // Search for a byte value [0-255]
961
962 if (typeof Uint8Array.prototype.indexOf === 'function') {
963 if (dir) {
964 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
965 } else {
966 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
967 }
968 }
969
970 return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
971 }
972
973 throw new TypeError('val must be string, number or Buffer');
974 }
975
976 function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
977 var indexSize = 1;
978 var arrLength = arr.length;
979 var valLength = val.length;
980
981 if (encoding !== undefined) {
982 encoding = String(encoding).toLowerCase();
983
984 if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') {
985 if (arr.length < 2 || val.length < 2) {
986 return -1;
987 }
988
989 indexSize = 2;
990 arrLength /= 2;
991 valLength /= 2;
992 byteOffset /= 2;
993 }
994 }
995
996 function read(buf, i) {
997 if (indexSize === 1) {
998 return buf[i];
999 } else {
1000 return buf.readUInt16BE(i * indexSize);
1001 }
1002 }
1003
1004 var i;
1005
1006 if (dir) {
1007 var foundIndex = -1;
1008
1009 for (i = byteOffset; i < arrLength; i++) {
1010 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
1011 if (foundIndex === -1) foundIndex = i;
1012 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
1013 } else {
1014 if (foundIndex !== -1) i -= i - foundIndex;
1015 foundIndex = -1;
1016 }
1017 }
1018 } else {
1019 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
1020
1021 for (i = byteOffset; i >= 0; i--) {
1022 var found = true;
1023
1024 for (var j = 0; j < valLength; j++) {
1025 if (read(arr, i + j) !== read(val, j)) {
1026 found = false;
1027 break;
1028 }
1029 }
1030
1031 if (found) return i;
1032 }
1033 }
1034
1035 return -1;
1036 }
1037
1038 Buffer.prototype.includes = function includes(val, byteOffset, encoding) {
1039 return this.indexOf(val, byteOffset, encoding) !== -1;
1040 };
1041
1042 Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
1043 return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
1044 };
1045
1046 Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
1047 return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
1048 };
1049
1050 function hexWrite(buf, string, offset, length) {
1051 offset = Number(offset) || 0;
1052 var remaining = buf.length - offset;
1053
1054 if (!length) {
1055 length = remaining;
1056 } else {
1057 length = Number(length);
1058
1059 if (length > remaining) {
1060 length = remaining;
1061 }
1062 }
1063
1064 var strLen = string.length;
1065
1066 if (length > strLen / 2) {
1067 length = strLen / 2;
1068 }
1069
1070 for (var i = 0; i < length; ++i) {
1071 var parsed = parseInt(string.substr(i * 2, 2), 16);
1072 if (numberIsNaN(parsed)) return i;
1073 buf[offset + i] = parsed;
1074 }
1075
1076 return i;
1077 }
1078
1079 function utf8Write(buf, string, offset, length) {
1080 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
1081 }
1082
1083 function asciiWrite(buf, string, offset, length) {
1084 return blitBuffer(asciiToBytes(string), buf, offset, length);
1085 }
1086
1087 function latin1Write(buf, string, offset, length) {
1088 return asciiWrite(buf, string, offset, length);
1089 }
1090
1091 function base64Write(buf, string, offset, length) {
1092 return blitBuffer(base64ToBytes(string), buf, offset, length);
1093 }
1094
1095 function ucs2Write(buf, string, offset, length) {
1096 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
1097 }
1098
1099 Buffer.prototype.write = function write(string, offset, length, encoding) {
1100 // Buffer#write(string)
1101 if (offset === undefined) {
1102 encoding = 'utf8';
1103 length = this.length;
1104 offset = 0; // Buffer#write(string, encoding)
1105 } else if (length === undefined && typeof offset === 'string') {
1106 encoding = offset;
1107 length = this.length;
1108 offset = 0; // Buffer#write(string, offset[, length][, encoding])
1109 } else if (isFinite(offset)) {
1110 offset = offset >>> 0;
1111
1112 if (isFinite(length)) {
1113 length = length >>> 0;
1114 if (encoding === undefined) encoding = 'utf8';
1115 } else {
1116 encoding = length;
1117 length = undefined;
1118 }
1119 } else {
1120 throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported');
1121 }
1122
1123 var remaining = this.length - offset;
1124 if (length === undefined || length > remaining) length = remaining;
1125
1126 if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
1127 throw new RangeError('Attempt to write outside buffer bounds');
1128 }
1129
1130 if (!encoding) encoding = 'utf8';
1131 var loweredCase = false;
1132
1133 for (;;) {
1134 switch (encoding) {
1135 case 'hex':
1136 return hexWrite(this, string, offset, length);
1137
1138 case 'utf8':
1139 case 'utf-8':
1140 return utf8Write(this, string, offset, length);
1141
1142 case 'ascii':
1143 return asciiWrite(this, string, offset, length);
1144
1145 case 'latin1':
1146 case 'binary':
1147 return latin1Write(this, string, offset, length);
1148
1149 case 'base64':
1150 // Warning: maxLength not taken into account in base64Write
1151 return base64Write(this, string, offset, length);
1152
1153 case 'ucs2':
1154 case 'ucs-2':
1155 case 'utf16le':
1156 case 'utf-16le':
1157 return ucs2Write(this, string, offset, length);
1158
1159 default:
1160 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
1161 encoding = ('' + encoding).toLowerCase();
1162 loweredCase = true;
1163 }
1164 }
1165 };
1166
1167 Buffer.prototype.toJSON = function toJSON() {
1168 return {
1169 type: 'Buffer',
1170 data: Array.prototype.slice.call(this._arr || this, 0)
1171 };
1172 };
1173
1174 function base64Slice(buf, start, end) {
1175 if (start === 0 && end === buf.length) {
1176 return base64Js.fromByteArray(buf);
1177 } else {
1178 return base64Js.fromByteArray(buf.slice(start, end));
1179 }
1180 }
1181
1182 function utf8Slice(buf, start, end) {
1183 end = Math.min(buf.length, end);
1184 var res = [];
1185 var i = start;
1186
1187 while (i < end) {
1188 var firstByte = buf[i];
1189 var codePoint = null;
1190 var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1;
1191
1192 if (i + bytesPerSequence <= end) {
1193 var secondByte, thirdByte, fourthByte, tempCodePoint;
1194
1195 switch (bytesPerSequence) {
1196 case 1:
1197 if (firstByte < 0x80) {
1198 codePoint = firstByte;
1199 }
1200
1201 break;
1202
1203 case 2:
1204 secondByte = buf[i + 1];
1205
1206 if ((secondByte & 0xC0) === 0x80) {
1207 tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F;
1208
1209 if (tempCodePoint > 0x7F) {
1210 codePoint = tempCodePoint;
1211 }
1212 }
1213
1214 break;
1215
1216 case 3:
1217 secondByte = buf[i + 1];
1218 thirdByte = buf[i + 2];
1219
1220 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
1221 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F;
1222
1223 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
1224 codePoint = tempCodePoint;
1225 }
1226 }
1227
1228 break;
1229
1230 case 4:
1231 secondByte = buf[i + 1];
1232 thirdByte = buf[i + 2];
1233 fourthByte = buf[i + 3];
1234
1235 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
1236 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F;
1237
1238 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
1239 codePoint = tempCodePoint;
1240 }
1241 }
1242
1243 }
1244 }
1245
1246 if (codePoint === null) {
1247 // we did not generate a valid codePoint so insert a
1248 // replacement char (U+FFFD) and advance only 1 byte
1249 codePoint = 0xFFFD;
1250 bytesPerSequence = 1;
1251 } else if (codePoint > 0xFFFF) {
1252 // encode to utf16 (surrogate pair dance)
1253 codePoint -= 0x10000;
1254 res.push(codePoint >>> 10 & 0x3FF | 0xD800);
1255 codePoint = 0xDC00 | codePoint & 0x3FF;
1256 }
1257
1258 res.push(codePoint);
1259 i += bytesPerSequence;
1260 }
1261
1262 return decodeCodePointsArray(res);
1263 } // Based on http://stackoverflow.com/a/22747272/680742, the browser with
1264 // the lowest limit is Chrome, with 0x10000 args.
1265 // We go 1 magnitude less, for safety
1266
1267
1268 var MAX_ARGUMENTS_LENGTH = 0x1000;
1269
1270 function decodeCodePointsArray(codePoints) {
1271 var len = codePoints.length;
1272
1273 if (len <= MAX_ARGUMENTS_LENGTH) {
1274 return String.fromCharCode.apply(String, codePoints); // avoid extra slice()
1275 } // Decode in chunks to avoid "call stack size exceeded".
1276
1277
1278 var res = '';
1279 var i = 0;
1280
1281 while (i < len) {
1282 res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));
1283 }
1284
1285 return res;
1286 }
1287
1288 function asciiSlice(buf, start, end) {
1289 var ret = '';
1290 end = Math.min(buf.length, end);
1291
1292 for (var i = start; i < end; ++i) {
1293 ret += String.fromCharCode(buf[i] & 0x7F);
1294 }
1295
1296 return ret;
1297 }
1298
1299 function latin1Slice(buf, start, end) {
1300 var ret = '';
1301 end = Math.min(buf.length, end);
1302
1303 for (var i = start; i < end; ++i) {
1304 ret += String.fromCharCode(buf[i]);
1305 }
1306
1307 return ret;
1308 }
1309
1310 function hexSlice(buf, start, end) {
1311 var len = buf.length;
1312 if (!start || start < 0) start = 0;
1313 if (!end || end < 0 || end > len) end = len;
1314 var out = '';
1315
1316 for (var i = start; i < end; ++i) {
1317 out += hexSliceLookupTable[buf[i]];
1318 }
1319
1320 return out;
1321 }
1322
1323 function utf16leSlice(buf, start, end) {
1324 var bytes = buf.slice(start, end);
1325 var res = '';
1326
1327 for (var i = 0; i < bytes.length; i += 2) {
1328 res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
1329 }
1330
1331 return res;
1332 }
1333
1334 Buffer.prototype.slice = function slice(start, end) {
1335 var len = this.length;
1336 start = ~~start;
1337 end = end === undefined ? len : ~~end;
1338
1339 if (start < 0) {
1340 start += len;
1341 if (start < 0) start = 0;
1342 } else if (start > len) {
1343 start = len;
1344 }
1345
1346 if (end < 0) {
1347 end += len;
1348 if (end < 0) end = 0;
1349 } else if (end > len) {
1350 end = len;
1351 }
1352
1353 if (end < start) end = start;
1354 var newBuf = this.subarray(start, end); // Return an augmented `Uint8Array` instance
1355
1356 Object.setPrototypeOf(newBuf, Buffer.prototype);
1357 return newBuf;
1358 };
1359 /*
1360 * Need to make sure that buffer isn't trying to write out of bounds.
1361 */
1362
1363
1364 function checkOffset(offset, ext, length) {
1365 if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint');
1366 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length');
1367 }
1368
1369 Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) {
1370 offset = offset >>> 0;
1371 byteLength = byteLength >>> 0;
1372 if (!noAssert) checkOffset(offset, byteLength, this.length);
1373 var val = this[offset];
1374 var mul = 1;
1375 var i = 0;
1376
1377 while (++i < byteLength && (mul *= 0x100)) {
1378 val += this[offset + i] * mul;
1379 }
1380
1381 return val;
1382 };
1383
1384 Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) {
1385 offset = offset >>> 0;
1386 byteLength = byteLength >>> 0;
1387
1388 if (!noAssert) {
1389 checkOffset(offset, byteLength, this.length);
1390 }
1391
1392 var val = this[offset + --byteLength];
1393 var mul = 1;
1394
1395 while (byteLength > 0 && (mul *= 0x100)) {
1396 val += this[offset + --byteLength] * mul;
1397 }
1398
1399 return val;
1400 };
1401
1402 Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) {
1403 offset = offset >>> 0;
1404 if (!noAssert) checkOffset(offset, 1, this.length);
1405 return this[offset];
1406 };
1407
1408 Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
1409 offset = offset >>> 0;
1410 if (!noAssert) checkOffset(offset, 2, this.length);
1411 return this[offset] | this[offset + 1] << 8;
1412 };
1413
1414 Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
1415 offset = offset >>> 0;
1416 if (!noAssert) checkOffset(offset, 2, this.length);
1417 return this[offset] << 8 | this[offset + 1];
1418 };
1419
1420 Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
1421 offset = offset >>> 0;
1422 if (!noAssert) checkOffset(offset, 4, this.length);
1423 return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000;
1424 };
1425
1426 Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
1427 offset = offset >>> 0;
1428 if (!noAssert) checkOffset(offset, 4, this.length);
1429 return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
1430 };
1431
1432 Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) {
1433 offset = offset >>> 0;
1434 byteLength = byteLength >>> 0;
1435 if (!noAssert) checkOffset(offset, byteLength, this.length);
1436 var val = this[offset];
1437 var mul = 1;
1438 var i = 0;
1439
1440 while (++i < byteLength && (mul *= 0x100)) {
1441 val += this[offset + i] * mul;
1442 }
1443
1444 mul *= 0x80;
1445 if (val >= mul) val -= Math.pow(2, 8 * byteLength);
1446 return val;
1447 };
1448
1449 Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) {
1450 offset = offset >>> 0;
1451 byteLength = byteLength >>> 0;
1452 if (!noAssert) checkOffset(offset, byteLength, this.length);
1453 var i = byteLength;
1454 var mul = 1;
1455 var val = this[offset + --i];
1456
1457 while (i > 0 && (mul *= 0x100)) {
1458 val += this[offset + --i] * mul;
1459 }
1460
1461 mul *= 0x80;
1462 if (val >= mul) val -= Math.pow(2, 8 * byteLength);
1463 return val;
1464 };
1465
1466 Buffer.prototype.readInt8 = function readInt8(offset, noAssert) {
1467 offset = offset >>> 0;
1468 if (!noAssert) checkOffset(offset, 1, this.length);
1469 if (!(this[offset] & 0x80)) return this[offset];
1470 return (0xff - this[offset] + 1) * -1;
1471 };
1472
1473 Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
1474 offset = offset >>> 0;
1475 if (!noAssert) checkOffset(offset, 2, this.length);
1476 var val = this[offset] | this[offset + 1] << 8;
1477 return val & 0x8000 ? val | 0xFFFF0000 : val;
1478 };
1479
1480 Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
1481 offset = offset >>> 0;
1482 if (!noAssert) checkOffset(offset, 2, this.length);
1483 var val = this[offset + 1] | this[offset] << 8;
1484 return val & 0x8000 ? val | 0xFFFF0000 : val;
1485 };
1486
1487 Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
1488 offset = offset >>> 0;
1489 if (!noAssert) checkOffset(offset, 4, this.length);
1490 return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
1491 };
1492
1493 Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
1494 offset = offset >>> 0;
1495 if (!noAssert) checkOffset(offset, 4, this.length);
1496 return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
1497 };
1498
1499 Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
1500 offset = offset >>> 0;
1501 if (!noAssert) checkOffset(offset, 4, this.length);
1502 return ieee754.read(this, offset, true, 23, 4);
1503 };
1504
1505 Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
1506 offset = offset >>> 0;
1507 if (!noAssert) checkOffset(offset, 4, this.length);
1508 return ieee754.read(this, offset, false, 23, 4);
1509 };
1510
1511 Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
1512 offset = offset >>> 0;
1513 if (!noAssert) checkOffset(offset, 8, this.length);
1514 return ieee754.read(this, offset, true, 52, 8);
1515 };
1516
1517 Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
1518 offset = offset >>> 0;
1519 if (!noAssert) checkOffset(offset, 8, this.length);
1520 return ieee754.read(this, offset, false, 52, 8);
1521 };
1522
1523 function checkInt(buf, value, offset, ext, max, min) {
1524 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
1525 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds');
1526 if (offset + ext > buf.length) throw new RangeError('Index out of range');
1527 }
1528
1529 Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) {
1530 value = +value;
1531 offset = offset >>> 0;
1532 byteLength = byteLength >>> 0;
1533
1534 if (!noAssert) {
1535 var maxBytes = Math.pow(2, 8 * byteLength) - 1;
1536 checkInt(this, value, offset, byteLength, maxBytes, 0);
1537 }
1538
1539 var mul = 1;
1540 var i = 0;
1541 this[offset] = value & 0xFF;
1542
1543 while (++i < byteLength && (mul *= 0x100)) {
1544 this[offset + i] = value / mul & 0xFF;
1545 }
1546
1547 return offset + byteLength;
1548 };
1549
1550 Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) {
1551 value = +value;
1552 offset = offset >>> 0;
1553 byteLength = byteLength >>> 0;
1554
1555 if (!noAssert) {
1556 var maxBytes = Math.pow(2, 8 * byteLength) - 1;
1557 checkInt(this, value, offset, byteLength, maxBytes, 0);
1558 }
1559
1560 var i = byteLength - 1;
1561 var mul = 1;
1562 this[offset + i] = value & 0xFF;
1563
1564 while (--i >= 0 && (mul *= 0x100)) {
1565 this[offset + i] = value / mul & 0xFF;
1566 }
1567
1568 return offset + byteLength;
1569 };
1570
1571 Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
1572 value = +value;
1573 offset = offset >>> 0;
1574 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
1575 this[offset] = value & 0xff;
1576 return offset + 1;
1577 };
1578
1579 Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
1580 value = +value;
1581 offset = offset >>> 0;
1582 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
1583 this[offset] = value & 0xff;
1584 this[offset + 1] = value >>> 8;
1585 return offset + 2;
1586 };
1587
1588 Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
1589 value = +value;
1590 offset = offset >>> 0;
1591 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
1592 this[offset] = value >>> 8;
1593 this[offset + 1] = value & 0xff;
1594 return offset + 2;
1595 };
1596
1597 Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
1598 value = +value;
1599 offset = offset >>> 0;
1600 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
1601 this[offset + 3] = value >>> 24;
1602 this[offset + 2] = value >>> 16;
1603 this[offset + 1] = value >>> 8;
1604 this[offset] = value & 0xff;
1605 return offset + 4;
1606 };
1607
1608 Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
1609 value = +value;
1610 offset = offset >>> 0;
1611 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
1612 this[offset] = value >>> 24;
1613 this[offset + 1] = value >>> 16;
1614 this[offset + 2] = value >>> 8;
1615 this[offset + 3] = value & 0xff;
1616 return offset + 4;
1617 };
1618
1619 Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) {
1620 value = +value;
1621 offset = offset >>> 0;
1622
1623 if (!noAssert) {
1624 var limit = Math.pow(2, 8 * byteLength - 1);
1625 checkInt(this, value, offset, byteLength, limit - 1, -limit);
1626 }
1627
1628 var i = 0;
1629 var mul = 1;
1630 var sub = 0;
1631 this[offset] = value & 0xFF;
1632
1633 while (++i < byteLength && (mul *= 0x100)) {
1634 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
1635 sub = 1;
1636 }
1637
1638 this[offset + i] = (value / mul >> 0) - sub & 0xFF;
1639 }
1640
1641 return offset + byteLength;
1642 };
1643
1644 Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) {
1645 value = +value;
1646 offset = offset >>> 0;
1647
1648 if (!noAssert) {
1649 var limit = Math.pow(2, 8 * byteLength - 1);
1650 checkInt(this, value, offset, byteLength, limit - 1, -limit);
1651 }
1652
1653 var i = byteLength - 1;
1654 var mul = 1;
1655 var sub = 0;
1656 this[offset + i] = value & 0xFF;
1657
1658 while (--i >= 0 && (mul *= 0x100)) {
1659 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
1660 sub = 1;
1661 }
1662
1663 this[offset + i] = (value / mul >> 0) - sub & 0xFF;
1664 }
1665
1666 return offset + byteLength;
1667 };
1668
1669 Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
1670 value = +value;
1671 offset = offset >>> 0;
1672 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
1673 if (value < 0) value = 0xff + value + 1;
1674 this[offset] = value & 0xff;
1675 return offset + 1;
1676 };
1677
1678 Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
1679 value = +value;
1680 offset = offset >>> 0;
1681 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
1682 this[offset] = value & 0xff;
1683 this[offset + 1] = value >>> 8;
1684 return offset + 2;
1685 };
1686
1687 Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
1688 value = +value;
1689 offset = offset >>> 0;
1690 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
1691 this[offset] = value >>> 8;
1692 this[offset + 1] = value & 0xff;
1693 return offset + 2;
1694 };
1695
1696 Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
1697 value = +value;
1698 offset = offset >>> 0;
1699 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
1700 this[offset] = value & 0xff;
1701 this[offset + 1] = value >>> 8;
1702 this[offset + 2] = value >>> 16;
1703 this[offset + 3] = value >>> 24;
1704 return offset + 4;
1705 };
1706
1707 Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
1708 value = +value;
1709 offset = offset >>> 0;
1710 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
1711 if (value < 0) value = 0xffffffff + value + 1;
1712 this[offset] = value >>> 24;
1713 this[offset + 1] = value >>> 16;
1714 this[offset + 2] = value >>> 8;
1715 this[offset + 3] = value & 0xff;
1716 return offset + 4;
1717 };
1718
1719 function checkIEEE754(buf, value, offset, ext, max, min) {
1720 if (offset + ext > buf.length) throw new RangeError('Index out of range');
1721 if (offset < 0) throw new RangeError('Index out of range');
1722 }
1723
1724 function writeFloat(buf, value, offset, littleEndian, noAssert) {
1725 value = +value;
1726 offset = offset >>> 0;
1727
1728 if (!noAssert) {
1729 checkIEEE754(buf, value, offset, 4);
1730 }
1731
1732 ieee754.write(buf, value, offset, littleEndian, 23, 4);
1733 return offset + 4;
1734 }
1735
1736 Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
1737 return writeFloat(this, value, offset, true, noAssert);
1738 };
1739
1740 Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
1741 return writeFloat(this, value, offset, false, noAssert);
1742 };
1743
1744 function writeDouble(buf, value, offset, littleEndian, noAssert) {
1745 value = +value;
1746 offset = offset >>> 0;
1747
1748 if (!noAssert) {
1749 checkIEEE754(buf, value, offset, 8);
1750 }
1751
1752 ieee754.write(buf, value, offset, littleEndian, 52, 8);
1753 return offset + 8;
1754 }
1755
1756 Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
1757 return writeDouble(this, value, offset, true, noAssert);
1758 };
1759
1760 Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
1761 return writeDouble(this, value, offset, false, noAssert);
1762 }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
1763
1764
1765 Buffer.prototype.copy = function copy(target, targetStart, start, end) {
1766 if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer');
1767 if (!start) start = 0;
1768 if (!end && end !== 0) end = this.length;
1769 if (targetStart >= target.length) targetStart = target.length;
1770 if (!targetStart) targetStart = 0;
1771 if (end > 0 && end < start) end = start; // Copy 0 bytes; we're done
1772
1773 if (end === start) return 0;
1774 if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions
1775
1776 if (targetStart < 0) {
1777 throw new RangeError('targetStart out of bounds');
1778 }
1779
1780 if (start < 0 || start >= this.length) throw new RangeError('Index out of range');
1781 if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob?
1782
1783 if (end > this.length) end = this.length;
1784
1785 if (target.length - targetStart < end - start) {
1786 end = target.length - targetStart + start;
1787 }
1788
1789 var len = end - start;
1790
1791 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
1792 // Use built-in when available, missing from IE11
1793 this.copyWithin(targetStart, start, end);
1794 } else if (this === target && start < targetStart && targetStart < end) {
1795 // descending copy from end
1796 for (var i = len - 1; i >= 0; --i) {
1797 target[i + targetStart] = this[i + start];
1798 }
1799 } else {
1800 Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart);
1801 }
1802
1803 return len;
1804 }; // Usage:
1805 // buffer.fill(number[, offset[, end]])
1806 // buffer.fill(buffer[, offset[, end]])
1807 // buffer.fill(string[, offset[, end]][, encoding])
1808
1809
1810 Buffer.prototype.fill = function fill(val, start, end, encoding) {
1811 // Handle string cases:
1812 if (typeof val === 'string') {
1813 if (typeof start === 'string') {
1814 encoding = start;
1815 start = 0;
1816 end = this.length;
1817 } else if (typeof end === 'string') {
1818 encoding = end;
1819 end = this.length;
1820 }
1821
1822 if (encoding !== undefined && typeof encoding !== 'string') {
1823 throw new TypeError('encoding must be a string');
1824 }
1825
1826 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
1827 throw new TypeError('Unknown encoding: ' + encoding);
1828 }
1829
1830 if (val.length === 1) {
1831 var code = val.charCodeAt(0);
1832
1833 if (encoding === 'utf8' && code < 128 || encoding === 'latin1') {
1834 // Fast path: If `val` fits into a single byte, use that numeric value.
1835 val = code;
1836 }
1837 }
1838 } else if (typeof val === 'number') {
1839 val = val & 255;
1840 } else if (typeof val === 'boolean') {
1841 val = Number(val);
1842 } // Invalid ranges are not set to a default, so can range check early.
1843
1844
1845 if (start < 0 || this.length < start || this.length < end) {
1846 throw new RangeError('Out of range index');
1847 }
1848
1849 if (end <= start) {
1850 return this;
1851 }
1852
1853 start = start >>> 0;
1854 end = end === undefined ? this.length : end >>> 0;
1855 if (!val) val = 0;
1856 var i;
1857
1858 if (typeof val === 'number') {
1859 for (i = start; i < end; ++i) {
1860 this[i] = val;
1861 }
1862 } else {
1863 var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding);
1864 var len = bytes.length;
1865
1866 if (len === 0) {
1867 throw new TypeError('The value "' + val + '" is invalid for argument "value"');
1868 }
1869
1870 for (i = 0; i < end - start; ++i) {
1871 this[i + start] = bytes[i % len];
1872 }
1873 }
1874
1875 return this;
1876 }; // HELPER FUNCTIONS
1877 // ================
1878
1879
1880 var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
1881
1882 function base64clean(str) {
1883 // Node takes equal signs as end of the Base64 encoding
1884 str = str.split('=')[0]; // Node strips out invalid characters like \n and \t from the string, base64-js does not
1885
1886 str = str.trim().replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to ''
1887
1888 if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
1889
1890 while (str.length % 4 !== 0) {
1891 str = str + '=';
1892 }
1893
1894 return str;
1895 }
1896
1897 function utf8ToBytes(string, units) {
1898 units = units || Infinity;
1899 var codePoint;
1900 var length = string.length;
1901 var leadSurrogate = null;
1902 var bytes = [];
1903
1904 for (var i = 0; i < length; ++i) {
1905 codePoint = string.charCodeAt(i); // is surrogate component
1906
1907 if (codePoint > 0xD7FF && codePoint < 0xE000) {
1908 // last char was a lead
1909 if (!leadSurrogate) {
1910 // no lead yet
1911 if (codePoint > 0xDBFF) {
1912 // unexpected trail
1913 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
1914 continue;
1915 } else if (i + 1 === length) {
1916 // unpaired lead
1917 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
1918 continue;
1919 } // valid lead
1920
1921
1922 leadSurrogate = codePoint;
1923 continue;
1924 } // 2 leads in a row
1925
1926
1927 if (codePoint < 0xDC00) {
1928 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
1929 leadSurrogate = codePoint;
1930 continue;
1931 } // valid surrogate pair
1932
1933
1934 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
1935 } else if (leadSurrogate) {
1936 // valid bmp char, but last char was a lead
1937 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
1938 }
1939
1940 leadSurrogate = null; // encode utf8
1941
1942 if (codePoint < 0x80) {
1943 if ((units -= 1) < 0) break;
1944 bytes.push(codePoint);
1945 } else if (codePoint < 0x800) {
1946 if ((units -= 2) < 0) break;
1947 bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80);
1948 } else if (codePoint < 0x10000) {
1949 if ((units -= 3) < 0) break;
1950 bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
1951 } else if (codePoint < 0x110000) {
1952 if ((units -= 4) < 0) break;
1953 bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
1954 } else {
1955 throw new Error('Invalid code point');
1956 }
1957 }
1958
1959 return bytes;
1960 }
1961
1962 function asciiToBytes(str) {
1963 var byteArray = [];
1964
1965 for (var i = 0; i < str.length; ++i) {
1966 // Node's code seems to be doing this and not & 0x7F..
1967 byteArray.push(str.charCodeAt(i) & 0xFF);
1968 }
1969
1970 return byteArray;
1971 }
1972
1973 function utf16leToBytes(str, units) {
1974 var c, hi, lo;
1975 var byteArray = [];
1976
1977 for (var i = 0; i < str.length; ++i) {
1978 if ((units -= 2) < 0) break;
1979 c = str.charCodeAt(i);
1980 hi = c >> 8;
1981 lo = c % 256;
1982 byteArray.push(lo);
1983 byteArray.push(hi);
1984 }
1985
1986 return byteArray;
1987 }
1988
1989 function base64ToBytes(str) {
1990 return base64Js.toByteArray(base64clean(str));
1991 }
1992
1993 function blitBuffer(src, dst, offset, length) {
1994 for (var i = 0; i < length; ++i) {
1995 if (i + offset >= dst.length || i >= src.length) break;
1996 dst[i + offset] = src[i];
1997 }
1998
1999 return i;
2000 } // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
2001 // the `instanceof` check but they should be treated as of that type.
2002 // See: https://github.com/feross/buffer/issues/166
2003
2004
2005 function isInstance(obj, type) {
2006 return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name;
2007 }
2008
2009 function numberIsNaN(obj) {
2010 // For IE11 support
2011 return obj !== obj; // eslint-disable-line no-self-compare
2012 } // Create lookup table for `toString('hex')`
2013 // See: https://github.com/feross/buffer/issues/219
2014
2015
2016 var hexSliceLookupTable = function () {
2017 var alphabet = '0123456789abcdef';
2018 var table = new Array(256);
2019
2020 for (var i = 0; i < 16; ++i) {
2021 var i16 = i * 16;
2022
2023 for (var j = 0; j < 16; ++j) {
2024 table[i16 + j] = alphabet[i] + alphabet[j];
2025 }
2026 }
2027
2028 return table;
2029 }();
2030});
2031var buffer_1 = buffer.Buffer;
2032var buffer_2 = buffer.SlowBuffer;
2033var buffer_3 = buffer.INSPECT_MAX_BYTES;
2034var buffer_4 = buffer.kMaxLength;
2035
2036/*! *****************************************************************************
2037Copyright (c) Microsoft Corporation.
2038
2039Permission to use, copy, modify, and/or distribute this software for any
2040purpose with or without fee is hereby granted.
2041
2042THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
2043REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
2044AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
2045INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
2046LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2047OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2048PERFORMANCE OF THIS SOFTWARE.
2049***************************************************************************** */
2050
2051/* global Reflect, Promise */
2052var _extendStatics = function extendStatics(d, b) {
2053 _extendStatics = Object.setPrototypeOf || {
2054 __proto__: []
2055 } instanceof Array && function (d, b) {
2056 d.__proto__ = b;
2057 } || function (d, b) {
2058 for (var p in b) {
2059 if (b.hasOwnProperty(p)) d[p] = b[p];
2060 }
2061 };
2062
2063 return _extendStatics(d, b);
2064};
2065
2066function __extends(d, b) {
2067 _extendStatics(d, b);
2068
2069 function __() {
2070 this.constructor = d;
2071 }
2072
2073 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
2074}
2075
2076var _assign = function __assign() {
2077 _assign = Object.assign || function __assign(t) {
2078 for (var s, i = 1, n = arguments.length; i < n; i++) {
2079 s = arguments[i];
2080
2081 for (var p in s) {
2082 if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
2083 }
2084 }
2085
2086 return t;
2087 };
2088
2089 return _assign.apply(this, arguments);
2090};
2091function __rest(s, e) {
2092 var t = {};
2093
2094 for (var p in s) {
2095 if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
2096 }
2097
2098 if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
2099 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
2100 }
2101 return t;
2102}
2103function __decorate(decorators, target, key, desc) {
2104 var c = arguments.length,
2105 r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
2106 d;
2107 if ((typeof Reflect === "undefined" ? "undefined" : babelHelpers["typeof"](Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) {
2108 if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2109 }
2110 return c > 3 && r && Object.defineProperty(target, key, r), r;
2111}
2112function __param(paramIndex, decorator) {
2113 return function (target, key) {
2114 decorator(target, key, paramIndex);
2115 };
2116}
2117function __metadata(metadataKey, metadataValue) {
2118 if ((typeof Reflect === "undefined" ? "undefined" : babelHelpers["typeof"](Reflect)) === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
2119}
2120function __awaiter(thisArg, _arguments, P, generator) {
2121 function adopt(value) {
2122 return value instanceof P ? value : new P(function (resolve) {
2123 resolve(value);
2124 });
2125 }
2126
2127 return new (P || (P = Promise))(function (resolve, reject) {
2128 function fulfilled(value) {
2129 try {
2130 step(generator.next(value));
2131 } catch (e) {
2132 reject(e);
2133 }
2134 }
2135
2136 function rejected(value) {
2137 try {
2138 step(generator["throw"](value));
2139 } catch (e) {
2140 reject(e);
2141 }
2142 }
2143
2144 function step(result) {
2145 result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
2146 }
2147
2148 step((generator = generator.apply(thisArg, _arguments || [])).next());
2149 });
2150}
2151function __generator(thisArg, body) {
2152 var _ = {
2153 label: 0,
2154 sent: function sent() {
2155 if (t[0] & 1) throw t[1];
2156 return t[1];
2157 },
2158 trys: [],
2159 ops: []
2160 },
2161 f,
2162 y,
2163 t,
2164 g;
2165 return g = {
2166 next: verb(0),
2167 "throw": verb(1),
2168 "return": verb(2)
2169 }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
2170 return this;
2171 }), g;
2172
2173 function verb(n) {
2174 return function (v) {
2175 return step([n, v]);
2176 };
2177 }
2178
2179 function step(op) {
2180 if (f) throw new TypeError("Generator is already executing.");
2181
2182 while (_) {
2183 try {
2184 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
2185 if (y = 0, t) op = [op[0] & 2, t.value];
2186
2187 switch (op[0]) {
2188 case 0:
2189 case 1:
2190 t = op;
2191 break;
2192
2193 case 4:
2194 _.label++;
2195 return {
2196 value: op[1],
2197 done: false
2198 };
2199
2200 case 5:
2201 _.label++;
2202 y = op[1];
2203 op = [0];
2204 continue;
2205
2206 case 7:
2207 op = _.ops.pop();
2208
2209 _.trys.pop();
2210
2211 continue;
2212
2213 default:
2214 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
2215 _ = 0;
2216 continue;
2217 }
2218
2219 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
2220 _.label = op[1];
2221 break;
2222 }
2223
2224 if (op[0] === 6 && _.label < t[1]) {
2225 _.label = t[1];
2226 t = op;
2227 break;
2228 }
2229
2230 if (t && _.label < t[2]) {
2231 _.label = t[2];
2232
2233 _.ops.push(op);
2234
2235 break;
2236 }
2237
2238 if (t[2]) _.ops.pop();
2239
2240 _.trys.pop();
2241
2242 continue;
2243 }
2244
2245 op = body.call(thisArg, _);
2246 } catch (e) {
2247 op = [6, e];
2248 y = 0;
2249 } finally {
2250 f = t = 0;
2251 }
2252 }
2253
2254 if (op[0] & 5) throw op[1];
2255 return {
2256 value: op[0] ? op[1] : void 0,
2257 done: true
2258 };
2259 }
2260}
2261function __createBinding(o, m, k, k2) {
2262 if (k2 === undefined) k2 = k;
2263 o[k2] = m[k];
2264}
2265function __exportStar(m, exports) {
2266 for (var p in m) {
2267 if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p];
2268 }
2269}
2270function __values(o) {
2271 var s = typeof Symbol === "function" && Symbol.iterator,
2272 m = s && o[s],
2273 i = 0;
2274 if (m) return m.call(o);
2275 if (o && typeof o.length === "number") return {
2276 next: function next() {
2277 if (o && i >= o.length) o = void 0;
2278 return {
2279 value: o && o[i++],
2280 done: !o
2281 };
2282 }
2283 };
2284 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
2285}
2286function __read(o, n) {
2287 var m = typeof Symbol === "function" && o[Symbol.iterator];
2288 if (!m) return o;
2289 var i = m.call(o),
2290 r,
2291 ar = [],
2292 e;
2293
2294 try {
2295 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) {
2296 ar.push(r.value);
2297 }
2298 } catch (error) {
2299 e = {
2300 error: error
2301 };
2302 } finally {
2303 try {
2304 if (r && !r.done && (m = i["return"])) m.call(i);
2305 } finally {
2306 if (e) throw e.error;
2307 }
2308 }
2309
2310 return ar;
2311}
2312function __spread() {
2313 for (var ar = [], i = 0; i < arguments.length; i++) {
2314 ar = ar.concat(__read(arguments[i]));
2315 }
2316
2317 return ar;
2318}
2319function __spreadArrays() {
2320 for (var s = 0, i = 0, il = arguments.length; i < il; i++) {
2321 s += arguments[i].length;
2322 }
2323
2324 for (var r = Array(s), k = 0, i = 0; i < il; i++) {
2325 for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) {
2326 r[k] = a[j];
2327 }
2328 }
2329
2330 return r;
2331}
2332function __await(v) {
2333 return this instanceof __await ? (this.v = v, this) : new __await(v);
2334}
2335function __asyncGenerator(thisArg, _arguments, generator) {
2336 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
2337 var g = generator.apply(thisArg, _arguments || []),
2338 i,
2339 q = [];
2340 return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () {
2341 return this;
2342 }, i;
2343
2344 function verb(n) {
2345 if (g[n]) i[n] = function (v) {
2346 return new Promise(function (a, b) {
2347 q.push([n, v, a, b]) > 1 || resume(n, v);
2348 });
2349 };
2350 }
2351
2352 function resume(n, v) {
2353 try {
2354 step(g[n](v));
2355 } catch (e) {
2356 settle(q[0][3], e);
2357 }
2358 }
2359
2360 function step(r) {
2361 r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
2362 }
2363
2364 function fulfill(value) {
2365 resume("next", value);
2366 }
2367
2368 function reject(value) {
2369 resume("throw", value);
2370 }
2371
2372 function settle(f, v) {
2373 if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
2374 }
2375}
2376function __asyncDelegator(o) {
2377 var i, p;
2378 return i = {}, verb("next"), verb("throw", function (e) {
2379 throw e;
2380 }), verb("return"), i[Symbol.iterator] = function () {
2381 return this;
2382 }, i;
2383
2384 function verb(n, f) {
2385 i[n] = o[n] ? function (v) {
2386 return (p = !p) ? {
2387 value: __await(o[n](v)),
2388 done: n === "return"
2389 } : f ? f(v) : v;
2390 } : f;
2391 }
2392}
2393function __asyncValues(o) {
2394 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
2395 var m = o[Symbol.asyncIterator],
2396 i;
2397 return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () {
2398 return this;
2399 }, i);
2400
2401 function verb(n) {
2402 i[n] = o[n] && function (v) {
2403 return new Promise(function (resolve, reject) {
2404 v = o[n](v), settle(resolve, reject, v.done, v.value);
2405 });
2406 };
2407 }
2408
2409 function settle(resolve, reject, d, v) {
2410 Promise.resolve(v).then(function (v) {
2411 resolve({
2412 value: v,
2413 done: d
2414 });
2415 }, reject);
2416 }
2417}
2418function __makeTemplateObject(cooked, raw) {
2419 if (Object.defineProperty) {
2420 Object.defineProperty(cooked, "raw", {
2421 value: raw
2422 });
2423 } else {
2424 cooked.raw = raw;
2425 }
2426
2427 return cooked;
2428}
2429function __importStar(mod) {
2430 if (mod && mod.__esModule) return mod;
2431 var result = {};
2432 if (mod != null) for (var k in mod) {
2433 if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
2434 }
2435 result["default"] = mod;
2436 return result;
2437}
2438function __importDefault(mod) {
2439 return mod && mod.__esModule ? mod : {
2440 "default": mod
2441 };
2442}
2443function __classPrivateFieldGet(receiver, privateMap) {
2444 if (!privateMap.has(receiver)) {
2445 throw new TypeError("attempted to get private field on non-instance");
2446 }
2447
2448 return privateMap.get(receiver);
2449}
2450function __classPrivateFieldSet(receiver, privateMap, value) {
2451 if (!privateMap.has(receiver)) {
2452 throw new TypeError("attempted to set private field on non-instance");
2453 }
2454
2455 privateMap.set(receiver, value);
2456 return value;
2457}
2458
2459var tslib_es6 = /*#__PURE__*/Object.freeze({
2460 __proto__: null,
2461 __extends: __extends,
2462 get __assign () { return _assign; },
2463 __rest: __rest,
2464 __decorate: __decorate,
2465 __param: __param,
2466 __metadata: __metadata,
2467 __awaiter: __awaiter,
2468 __generator: __generator,
2469 __createBinding: __createBinding,
2470 __exportStar: __exportStar,
2471 __values: __values,
2472 __read: __read,
2473 __spread: __spread,
2474 __spreadArrays: __spreadArrays,
2475 __await: __await,
2476 __asyncGenerator: __asyncGenerator,
2477 __asyncDelegator: __asyncDelegator,
2478 __asyncValues: __asyncValues,
2479 __makeTemplateObject: __makeTemplateObject,
2480 __importStar: __importStar,
2481 __importDefault: __importDefault,
2482 __classPrivateFieldGet: __classPrivateFieldGet,
2483 __classPrivateFieldSet: __classPrivateFieldSet
2484});
2485
2486var require$$0 = {};
2487
2488var inherits;
2489
2490if (typeof Object.create === 'function') {
2491 inherits = function inherits(ctor, superCtor) {
2492 // implementation from standard node.js 'util' module
2493 ctor.super_ = superCtor;
2494 ctor.prototype = Object.create(superCtor.prototype, {
2495 constructor: {
2496 value: ctor,
2497 enumerable: false,
2498 writable: true,
2499 configurable: true
2500 }
2501 });
2502 };
2503} else {
2504 inherits = function inherits(ctor, superCtor) {
2505 ctor.super_ = superCtor;
2506
2507 var TempCtor = function TempCtor() {};
2508
2509 TempCtor.prototype = superCtor.prototype;
2510 ctor.prototype = new TempCtor();
2511 ctor.prototype.constructor = ctor;
2512 };
2513}
2514
2515var inherits$1 = inherits;
2516
2517// Copyright Joyent, Inc. and other Node contributors.
2518var formatRegExp = /%[sdj%]/g;
2519function format(f) {
2520 if (!isString(f)) {
2521 var objects = [];
2522
2523 for (var i = 0; i < arguments.length; i++) {
2524 objects.push(inspect(arguments[i]));
2525 }
2526
2527 return objects.join(' ');
2528 }
2529
2530 var i = 1;
2531 var args = arguments;
2532 var len = args.length;
2533 var str = String(f).replace(formatRegExp, function (x) {
2534 if (x === '%%') return '%';
2535 if (i >= len) return x;
2536
2537 switch (x) {
2538 case '%s':
2539 return String(args[i++]);
2540
2541 case '%d':
2542 return Number(args[i++]);
2543
2544 case '%j':
2545 try {
2546 return JSON.stringify(args[i++]);
2547 } catch (_) {
2548 return '[Circular]';
2549 }
2550
2551 default:
2552 return x;
2553 }
2554 });
2555
2556 for (var x = args[i]; i < len; x = args[++i]) {
2557 if (isNull(x) || !isObject(x)) {
2558 str += ' ' + x;
2559 } else {
2560 str += ' ' + inspect(x);
2561 }
2562 }
2563
2564 return str;
2565}
2566// Returns a modified function which warns once by default.
2567// If --no-deprecation is set, then it is a no-op.
2568
2569function deprecate(fn, msg) {
2570 // Allow for deprecating things in the process of starting up.
2571 if (isUndefined(global.process)) {
2572 return function () {
2573 return deprecate(fn, msg).apply(this, arguments);
2574 };
2575 }
2576
2577 var warned = false;
2578
2579 function deprecated() {
2580 if (!warned) {
2581 {
2582 console.error(msg);
2583 }
2584
2585 warned = true;
2586 }
2587
2588 return fn.apply(this, arguments);
2589 }
2590
2591 return deprecated;
2592}
2593var debugs = {};
2594var debugEnviron;
2595function debuglog(set) {
2596 if (isUndefined(debugEnviron)) debugEnviron = '';
2597 set = set.toUpperCase();
2598
2599 if (!debugs[set]) {
2600 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
2601 var pid = 0;
2602
2603 debugs[set] = function () {
2604 var msg = format.apply(null, arguments);
2605 console.error('%s %d: %s', set, pid, msg);
2606 };
2607 } else {
2608 debugs[set] = function () {};
2609 }
2610 }
2611
2612 return debugs[set];
2613}
2614/**
2615 * Echos the value of a value. Trys to print the value out
2616 * in the best way possible given the different types.
2617 *
2618 * @param {Object} obj The object to print out.
2619 * @param {Object} opts Optional options object that alters the output.
2620 */
2621
2622/* legacy: obj, showHidden, depth, colors*/
2623
2624function inspect(obj, opts) {
2625 // default options
2626 var ctx = {
2627 seen: [],
2628 stylize: stylizeNoColor
2629 }; // legacy...
2630
2631 if (arguments.length >= 3) ctx.depth = arguments[2];
2632 if (arguments.length >= 4) ctx.colors = arguments[3];
2633
2634 if (isBoolean(opts)) {
2635 // legacy...
2636 ctx.showHidden = opts;
2637 } else if (opts) {
2638 // got an "options" object
2639 _extend(ctx, opts);
2640 } // set default options
2641
2642
2643 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
2644 if (isUndefined(ctx.depth)) ctx.depth = 2;
2645 if (isUndefined(ctx.colors)) ctx.colors = false;
2646 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
2647 if (ctx.colors) ctx.stylize = stylizeWithColor;
2648 return formatValue(ctx, obj, ctx.depth);
2649} // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
2650
2651inspect.colors = {
2652 'bold': [1, 22],
2653 'italic': [3, 23],
2654 'underline': [4, 24],
2655 'inverse': [7, 27],
2656 'white': [37, 39],
2657 'grey': [90, 39],
2658 'black': [30, 39],
2659 'blue': [34, 39],
2660 'cyan': [36, 39],
2661 'green': [32, 39],
2662 'magenta': [35, 39],
2663 'red': [31, 39],
2664 'yellow': [33, 39]
2665}; // Don't use 'blue' not visible on cmd.exe
2666
2667inspect.styles = {
2668 'special': 'cyan',
2669 'number': 'yellow',
2670 'boolean': 'yellow',
2671 'undefined': 'grey',
2672 'null': 'bold',
2673 'string': 'green',
2674 'date': 'magenta',
2675 // "name": intentionally not styling
2676 'regexp': 'red'
2677};
2678
2679function stylizeWithColor(str, styleType) {
2680 var style = inspect.styles[styleType];
2681
2682 if (style) {
2683 return "\x1B[" + inspect.colors[style][0] + 'm' + str + "\x1B[" + inspect.colors[style][1] + 'm';
2684 } else {
2685 return str;
2686 }
2687}
2688
2689function stylizeNoColor(str, styleType) {
2690 return str;
2691}
2692
2693function arrayToHash(array) {
2694 var hash = {};
2695 array.forEach(function (val, idx) {
2696 hash[val] = true;
2697 });
2698 return hash;
2699}
2700
2701function formatValue(ctx, value, recurseTimes) {
2702 // Provide a hook for user-specified inspect functions.
2703 // Check that value is an object with an inspect function on it
2704 if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special
2705 value.inspect !== inspect && // Also filter out any prototype objects using the circular check.
2706 !(value.constructor && value.constructor.prototype === value)) {
2707 var ret = value.inspect(recurseTimes, ctx);
2708
2709 if (!isString(ret)) {
2710 ret = formatValue(ctx, ret, recurseTimes);
2711 }
2712
2713 return ret;
2714 } // Primitive types cannot have properties
2715
2716
2717 var primitive = formatPrimitive(ctx, value);
2718
2719 if (primitive) {
2720 return primitive;
2721 } // Look up the keys of the object.
2722
2723
2724 var keys = Object.keys(value);
2725 var visibleKeys = arrayToHash(keys);
2726
2727 if (ctx.showHidden) {
2728 keys = Object.getOwnPropertyNames(value);
2729 } // IE doesn't make error fields non-enumerable
2730 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
2731
2732
2733 if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
2734 return formatError(value);
2735 } // Some type of object without properties can be shortcutted.
2736
2737
2738 if (keys.length === 0) {
2739 if (isFunction(value)) {
2740 var name = value.name ? ': ' + value.name : '';
2741 return ctx.stylize('[Function' + name + ']', 'special');
2742 }
2743
2744 if (isRegExp(value)) {
2745 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
2746 }
2747
2748 if (isDate(value)) {
2749 return ctx.stylize(Date.prototype.toString.call(value), 'date');
2750 }
2751
2752 if (isError(value)) {
2753 return formatError(value);
2754 }
2755 }
2756
2757 var base = '',
2758 array = false,
2759 braces = ['{', '}']; // Make Array say that they are Array
2760
2761 if (isArray(value)) {
2762 array = true;
2763 braces = ['[', ']'];
2764 } // Make functions say that they are functions
2765
2766
2767 if (isFunction(value)) {
2768 var n = value.name ? ': ' + value.name : '';
2769 base = ' [Function' + n + ']';
2770 } // Make RegExps say that they are RegExps
2771
2772
2773 if (isRegExp(value)) {
2774 base = ' ' + RegExp.prototype.toString.call(value);
2775 } // Make dates with properties first say the date
2776
2777
2778 if (isDate(value)) {
2779 base = ' ' + Date.prototype.toUTCString.call(value);
2780 } // Make error with message first say the error
2781
2782
2783 if (isError(value)) {
2784 base = ' ' + formatError(value);
2785 }
2786
2787 if (keys.length === 0 && (!array || value.length == 0)) {
2788 return braces[0] + base + braces[1];
2789 }
2790
2791 if (recurseTimes < 0) {
2792 if (isRegExp(value)) {
2793 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
2794 } else {
2795 return ctx.stylize('[Object]', 'special');
2796 }
2797 }
2798
2799 ctx.seen.push(value);
2800 var output;
2801
2802 if (array) {
2803 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
2804 } else {
2805 output = keys.map(function (key) {
2806 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
2807 });
2808 }
2809
2810 ctx.seen.pop();
2811 return reduceToSingleString(output, base, braces);
2812}
2813
2814function formatPrimitive(ctx, value) {
2815 if (isUndefined(value)) return ctx.stylize('undefined', 'undefined');
2816
2817 if (isString(value)) {
2818 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '').replace(/'/g, "\\'").replace(/\\"/g, '"') + '\'';
2819 return ctx.stylize(simple, 'string');
2820 }
2821
2822 if (isNumber(value)) return ctx.stylize('' + value, 'number');
2823 if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here.
2824
2825 if (isNull(value)) return ctx.stylize('null', 'null');
2826}
2827
2828function formatError(value) {
2829 return '[' + Error.prototype.toString.call(value) + ']';
2830}
2831
2832function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
2833 var output = [];
2834
2835 for (var i = 0, l = value.length; i < l; ++i) {
2836 if (hasOwnProperty(value, String(i))) {
2837 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true));
2838 } else {
2839 output.push('');
2840 }
2841 }
2842
2843 keys.forEach(function (key) {
2844 if (!key.match(/^\d+$/)) {
2845 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true));
2846 }
2847 });
2848 return output;
2849}
2850
2851function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
2852 var name, str, desc;
2853 desc = Object.getOwnPropertyDescriptor(value, key) || {
2854 value: value[key]
2855 };
2856
2857 if (desc.get) {
2858 if (desc.set) {
2859 str = ctx.stylize('[Getter/Setter]', 'special');
2860 } else {
2861 str = ctx.stylize('[Getter]', 'special');
2862 }
2863 } else {
2864 if (desc.set) {
2865 str = ctx.stylize('[Setter]', 'special');
2866 }
2867 }
2868
2869 if (!hasOwnProperty(visibleKeys, key)) {
2870 name = '[' + key + ']';
2871 }
2872
2873 if (!str) {
2874 if (ctx.seen.indexOf(desc.value) < 0) {
2875 if (isNull(recurseTimes)) {
2876 str = formatValue(ctx, desc.value, null);
2877 } else {
2878 str = formatValue(ctx, desc.value, recurseTimes - 1);
2879 }
2880
2881 if (str.indexOf('\n') > -1) {
2882 if (array) {
2883 str = str.split('\n').map(function (line) {
2884 return ' ' + line;
2885 }).join('\n').substr(2);
2886 } else {
2887 str = '\n' + str.split('\n').map(function (line) {
2888 return ' ' + line;
2889 }).join('\n');
2890 }
2891 }
2892 } else {
2893 str = ctx.stylize('[Circular]', 'special');
2894 }
2895 }
2896
2897 if (isUndefined(name)) {
2898 if (array && key.match(/^\d+$/)) {
2899 return str;
2900 }
2901
2902 name = JSON.stringify('' + key);
2903
2904 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
2905 name = name.substr(1, name.length - 2);
2906 name = ctx.stylize(name, 'name');
2907 } else {
2908 name = name.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'");
2909 name = ctx.stylize(name, 'string');
2910 }
2911 }
2912
2913 return name + ': ' + str;
2914}
2915
2916function reduceToSingleString(output, base, braces) {
2917 var length = output.reduce(function (prev, cur) {
2918 if (cur.indexOf('\n') >= 0) ;
2919 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
2920 }, 0);
2921
2922 if (length > 60) {
2923 return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1];
2924 }
2925
2926 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
2927} // NOTE: These type checking functions intentionally don't use `instanceof`
2928// because it is fragile and can be easily faked with `Object.create()`.
2929
2930
2931function isArray(ar) {
2932 return Array.isArray(ar);
2933}
2934function isBoolean(arg) {
2935 return typeof arg === 'boolean';
2936}
2937function isNull(arg) {
2938 return arg === null;
2939}
2940function isNullOrUndefined(arg) {
2941 return arg == null;
2942}
2943function isNumber(arg) {
2944 return typeof arg === 'number';
2945}
2946function isString(arg) {
2947 return typeof arg === 'string';
2948}
2949function isSymbol(arg) {
2950 return babelHelpers["typeof"](arg) === 'symbol';
2951}
2952function isUndefined(arg) {
2953 return arg === void 0;
2954}
2955function isRegExp(re) {
2956 return isObject(re) && objectToString(re) === '[object RegExp]';
2957}
2958function isObject(arg) {
2959 return babelHelpers["typeof"](arg) === 'object' && arg !== null;
2960}
2961function isDate(d) {
2962 return isObject(d) && objectToString(d) === '[object Date]';
2963}
2964function isError(e) {
2965 return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error);
2966}
2967function isFunction(arg) {
2968 return typeof arg === 'function';
2969}
2970function isPrimitive(arg) {
2971 return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || babelHelpers["typeof"](arg) === 'symbol' || // ES6 symbol
2972 typeof arg === 'undefined';
2973}
2974function isBuffer(maybeBuf) {
2975 return Buffer.isBuffer(maybeBuf);
2976}
2977
2978function objectToString(o) {
2979 return Object.prototype.toString.call(o);
2980}
2981
2982function pad(n) {
2983 return n < 10 ? '0' + n.toString(10) : n.toString(10);
2984}
2985
2986var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34
2987
2988function timestamp() {
2989 var d = new Date();
2990 var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':');
2991 return [d.getDate(), months[d.getMonth()], time].join(' ');
2992} // log is just a thin wrapper to console.log that prepends a timestamp
2993
2994
2995function log() {
2996 console.log('%s - %s', timestamp(), format.apply(null, arguments));
2997}
2998function _extend(origin, add) {
2999 // Don't do anything if add isn't an object
3000 if (!add || !isObject(add)) return origin;
3001 var keys = Object.keys(add);
3002 var i = keys.length;
3003
3004 while (i--) {
3005 origin[keys[i]] = add[keys[i]];
3006 }
3007
3008 return origin;
3009}
3010
3011function hasOwnProperty(obj, prop) {
3012 return Object.prototype.hasOwnProperty.call(obj, prop);
3013}
3014
3015var require$$1 = {
3016 inherits: inherits$1,
3017 _extend: _extend,
3018 log: log,
3019 isBuffer: isBuffer,
3020 isPrimitive: isPrimitive,
3021 isFunction: isFunction,
3022 isError: isError,
3023 isDate: isDate,
3024 isObject: isObject,
3025 isRegExp: isRegExp,
3026 isUndefined: isUndefined,
3027 isSymbol: isSymbol,
3028 isString: isString,
3029 isNumber: isNumber,
3030 isNullOrUndefined: isNullOrUndefined,
3031 isNull: isNull,
3032 isBoolean: isBoolean,
3033 isArray: isArray,
3034 inspect: inspect,
3035 deprecate: deprecate,
3036 format: format,
3037 debuglog: debuglog
3038};
3039
3040var utils = createCommonjsModule(function (module, exports) {
3041Object.defineProperty(exports, "__esModule", { value: true });
3042exports.deprecate = exports.isObjectLike = exports.isDate = exports.isBuffer = exports.haveBuffer = exports.isBigUInt64Array = exports.isBigInt64Array = exports.isUint8Array = exports.randomBytes = exports.normalizedFunctionString = void 0;
3043
3044
3045/**
3046 * Normalizes our expected stringified form of a function across versions of node
3047 * @param fn - The function to stringify
3048 */
3049function normalizedFunctionString(fn) {
3050 return fn.toString().replace('function(', 'function (');
3051}
3052exports.normalizedFunctionString = normalizedFunctionString;
3053function insecureRandomBytes(size) {
3054 var result = buffer.Buffer.alloc(size);
3055 for (var i = 0; i < size; ++i)
3056 result[i] = Math.floor(Math.random() * 256);
3057 return result;
3058}
3059exports.randomBytes = insecureRandomBytes;
3060if (typeof window !== 'undefined' && window.crypto && window.crypto.getRandomValues) {
3061 exports.randomBytes = function (size) { return window.crypto.getRandomValues(buffer.Buffer.alloc(size)); };
3062}
3063else {
3064 try {
3065 // eslint-disable-next-line @typescript-eslint/no-var-requires
3066 exports.randomBytes = require$$0.randomBytes;
3067 }
3068 catch (e) {
3069 // keep the fallback
3070 }
3071 // NOTE: in transpiled cases the above require might return null/undefined
3072 if (exports.randomBytes == null) {
3073 exports.randomBytes = insecureRandomBytes;
3074 }
3075}
3076function isUint8Array(value) {
3077 return Object.prototype.toString.call(value) === '[object Uint8Array]';
3078}
3079exports.isUint8Array = isUint8Array;
3080function isBigInt64Array(value) {
3081 return Object.prototype.toString.call(value) === '[object BigInt64Array]';
3082}
3083exports.isBigInt64Array = isBigInt64Array;
3084function isBigUInt64Array(value) {
3085 return Object.prototype.toString.call(value) === '[object BigUint64Array]';
3086}
3087exports.isBigUInt64Array = isBigUInt64Array;
3088/** Call to check if your environment has `Buffer` */
3089function haveBuffer() {
3090 return typeof commonjsGlobal !== 'undefined' && typeof commonjsGlobal.Buffer !== 'undefined';
3091}
3092exports.haveBuffer = haveBuffer;
3093/** Callable in any environment to check if value is a Buffer */
3094function isBuffer(value) {
3095 var _a;
3096 return typeof value === 'object' && ((_a = value === null || value === void 0 ? void 0 : value.constructor) === null || _a === void 0 ? void 0 : _a.name) === 'Buffer';
3097}
3098exports.isBuffer = isBuffer;
3099// To ensure that 0.4 of node works correctly
3100function isDate(d) {
3101 return isObjectLike(d) && Object.prototype.toString.call(d) === '[object Date]';
3102}
3103exports.isDate = isDate;
3104/**
3105 * @internal
3106 * this is to solve the `'someKey' in x` problem where x is unknown.
3107 * https://github.com/typescript-eslint/typescript-eslint/issues/1071#issuecomment-541955753
3108 */
3109function isObjectLike(candidate) {
3110 return typeof candidate === 'object' && candidate !== null;
3111}
3112exports.isObjectLike = isObjectLike;
3113function deprecate(fn, message) {
3114 if (typeof window === 'undefined' && typeof self === 'undefined') {
3115 // eslint-disable-next-line @typescript-eslint/no-var-requires
3116 return require$$1.deprecate(fn, message);
3117 }
3118 var warned = false;
3119 function deprecated() {
3120 var args = [];
3121 for (var _i = 0; _i < arguments.length; _i++) {
3122 args[_i] = arguments[_i];
3123 }
3124 if (!warned) {
3125 console.warn(message);
3126 warned = true;
3127 }
3128 return fn.apply.apply(fn, tslib_es6.__spreadArrays([this], args));
3129 }
3130 return deprecated;
3131}
3132exports.deprecate = deprecate;
3133
3134});
3135
3136unwrapExports(utils);
3137var utils_1 = utils.deprecate;
3138var utils_2 = utils.isObjectLike;
3139var utils_3 = utils.isDate;
3140var utils_4 = utils.isBuffer;
3141var utils_5 = utils.haveBuffer;
3142var utils_6 = utils.isBigUInt64Array;
3143var utils_7 = utils.isBigInt64Array;
3144var utils_8 = utils.isUint8Array;
3145var utils_9 = utils.randomBytes;
3146var utils_10 = utils.normalizedFunctionString;
3147
3148var ensure_buffer = createCommonjsModule(function (module, exports) {
3149Object.defineProperty(exports, "__esModule", { value: true });
3150exports.ensureBuffer = void 0;
3151
3152
3153/**
3154 * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer.
3155 *
3156 * @param potentialBuffer - The potential buffer
3157 * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that
3158 * wraps a passed in Uint8Array
3159 * @throws TypeError If anything other than a Buffer or Uint8Array is passed in
3160 */
3161function ensureBuffer(potentialBuffer) {
3162 if (utils.isBuffer(potentialBuffer)) {
3163 return potentialBuffer;
3164 }
3165 if (ArrayBuffer.isView(potentialBuffer)) {
3166 return buffer.Buffer.from(potentialBuffer.buffer);
3167 }
3168 if (potentialBuffer instanceof ArrayBuffer) {
3169 return buffer.Buffer.from(potentialBuffer);
3170 }
3171 throw new TypeError('Must use either Buffer or TypedArray');
3172}
3173exports.ensureBuffer = ensureBuffer;
3174
3175});
3176
3177unwrapExports(ensure_buffer);
3178var ensure_buffer_1 = ensure_buffer.ensureBuffer;
3179
3180var uuid = createCommonjsModule(function (module, exports) {
3181Object.defineProperty(exports, "__esModule", { value: true });
3182exports.parseUUID = void 0;
3183/**
3184 * UUID regular expression pattern copied from `uuid` npm module.
3185 * @see https://github.com/uuidjs/uuid/blob/master/src/regex.js
3186 */
3187var UUID_RX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
3188/**
3189 * Parser function copied from `uuid` npm module.
3190 * @see https://github.com/uuidjs/uuid/blob/master/src/parse.js
3191 * @internal
3192 */
3193function parseUUID(uuid) {
3194 if (typeof uuid !== 'string') {
3195 throw new TypeError('Invalid type for UUID, expected string but got ' + typeof uuid);
3196 }
3197 if (!UUID_RX.test(uuid)) {
3198 throw new TypeError('Invalid format for UUID: ' + uuid);
3199 }
3200 var v;
3201 var arr = new Uint8Array(16);
3202 // Parse ########-....-....-....-............
3203 arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
3204 arr[1] = (v >>> 16) & 0xff;
3205 arr[2] = (v >>> 8) & 0xff;
3206 arr[3] = v & 0xff;
3207 // Parse ........-####-....-....-............
3208 arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
3209 arr[5] = v & 0xff;
3210 // Parse ........-....-####-....-............
3211 arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
3212 arr[7] = v & 0xff;
3213 // Parse ........-....-....-####-............
3214 arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
3215 arr[9] = v & 0xff;
3216 // Parse ........-....-....-....-############
3217 // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
3218 arr[10] = ((v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000) & 0xff;
3219 arr[11] = (v / 0x100000000) & 0xff;
3220 arr[12] = (v >>> 24) & 0xff;
3221 arr[13] = (v >>> 16) & 0xff;
3222 arr[14] = (v >>> 8) & 0xff;
3223 arr[15] = v & 0xff;
3224 return arr;
3225}
3226exports.parseUUID = parseUUID;
3227
3228});
3229
3230unwrapExports(uuid);
3231var uuid_1 = uuid.parseUUID;
3232
3233var binary = createCommonjsModule(function (module, exports) {
3234Object.defineProperty(exports, "__esModule", { value: true });
3235exports.Binary = void 0;
3236
3237
3238
3239/**
3240 * A class representation of the BSON Binary type.
3241 * @public
3242 */
3243var Binary = /** @class */ (function () {
3244 /**
3245 * @param buffer - a buffer object containing the binary data.
3246 * @param subType - the option binary type.
3247 */
3248 function Binary(buffer$1, subType) {
3249 if (!(this instanceof Binary))
3250 return new Binary(buffer$1, subType);
3251 if (!(buffer$1 == null) &&
3252 !(typeof buffer$1 === 'string') &&
3253 !ArrayBuffer.isView(buffer$1) &&
3254 !(buffer$1 instanceof ArrayBuffer) &&
3255 !Array.isArray(buffer$1)) {
3256 throw new TypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array<number>');
3257 }
3258 this.sub_type = subType !== null && subType !== void 0 ? subType : Binary.BSON_BINARY_SUBTYPE_DEFAULT;
3259 if (buffer$1 == null) {
3260 // create an empty binary buffer
3261 this.buffer = buffer.Buffer.alloc(Binary.BUFFER_SIZE);
3262 this.position = 0;
3263 }
3264 else {
3265 if (typeof buffer$1 === 'string') {
3266 // string
3267 this.buffer = buffer.Buffer.from(buffer$1, 'binary');
3268 }
3269 else if (Array.isArray(buffer$1)) {
3270 // number[]
3271 this.buffer = buffer.Buffer.from(buffer$1);
3272 }
3273 else {
3274 // Buffer | TypedArray | ArrayBuffer
3275 this.buffer = ensure_buffer.ensureBuffer(buffer$1);
3276 }
3277 this.position = this.buffer.byteLength;
3278 }
3279 }
3280 /**
3281 * Updates this binary with byte_value.
3282 *
3283 * @param byteValue - a single byte we wish to write.
3284 */
3285 Binary.prototype.put = function (byteValue) {
3286 // If it's a string and a has more than one character throw an error
3287 if (typeof byteValue === 'string' && byteValue.length !== 1) {
3288 throw new TypeError('only accepts single character String');
3289 }
3290 else if (typeof byteValue !== 'number' && byteValue.length !== 1)
3291 throw new TypeError('only accepts single character Uint8Array or Array');
3292 // Decode the byte value once
3293 var decodedByte;
3294 if (typeof byteValue === 'string') {
3295 decodedByte = byteValue.charCodeAt(0);
3296 }
3297 else if (typeof byteValue === 'number') {
3298 decodedByte = byteValue;
3299 }
3300 else {
3301 decodedByte = byteValue[0];
3302 }
3303 if (decodedByte < 0 || decodedByte > 255) {
3304 throw new TypeError('only accepts number in a valid unsigned byte range 0-255');
3305 }
3306 if (this.buffer.length > this.position) {
3307 this.buffer[this.position++] = decodedByte;
3308 }
3309 else {
3310 var buffer$1 = buffer.Buffer.alloc(Binary.BUFFER_SIZE + this.buffer.length);
3311 // Combine the two buffers together
3312 this.buffer.copy(buffer$1, 0, 0, this.buffer.length);
3313 this.buffer = buffer$1;
3314 this.buffer[this.position++] = decodedByte;
3315 }
3316 };
3317 /**
3318 * Writes a buffer or string to the binary.
3319 *
3320 * @param sequence - a string or buffer to be written to the Binary BSON object.
3321 * @param offset - specify the binary of where to write the content.
3322 */
3323 Binary.prototype.write = function (sequence, offset) {
3324 offset = typeof offset === 'number' ? offset : this.position;
3325 // If the buffer is to small let's extend the buffer
3326 if (this.buffer.length < offset + sequence.length) {
3327 var buffer$1 = buffer.Buffer.alloc(this.buffer.length + sequence.length);
3328 this.buffer.copy(buffer$1, 0, 0, this.buffer.length);
3329 // Assign the new buffer
3330 this.buffer = buffer$1;
3331 }
3332 if (ArrayBuffer.isView(sequence)) {
3333 this.buffer.set(ensure_buffer.ensureBuffer(sequence), offset);
3334 this.position =
3335 offset + sequence.byteLength > this.position ? offset + sequence.length : this.position;
3336 }
3337 else if (typeof sequence === 'string') {
3338 this.buffer.write(sequence, offset, sequence.length, 'binary');
3339 this.position =
3340 offset + sequence.length > this.position ? offset + sequence.length : this.position;
3341 }
3342 };
3343 /**
3344 * Reads **length** bytes starting at **position**.
3345 *
3346 * @param position - read from the given position in the Binary.
3347 * @param length - the number of bytes to read.
3348 */
3349 Binary.prototype.read = function (position, length) {
3350 length = length && length > 0 ? length : this.position;
3351 // Let's return the data based on the type we have
3352 return this.buffer.slice(position, position + length);
3353 };
3354 /**
3355 * Returns the value of this binary as a string.
3356 * @param asRaw - Will skip converting to a string
3357 * @remarks
3358 * This is handy when calling this function conditionally for some key value pairs and not others
3359 */
3360 Binary.prototype.value = function (asRaw) {
3361 asRaw = !!asRaw;
3362 // Optimize to serialize for the situation where the data == size of buffer
3363 if (asRaw && this.buffer.length === this.position) {
3364 return this.buffer;
3365 }
3366 // If it's a node.js buffer object
3367 if (asRaw) {
3368 return this.buffer.slice(0, this.position);
3369 }
3370 return this.buffer.toString('binary', 0, this.position);
3371 };
3372 /** the length of the binary sequence */
3373 Binary.prototype.length = function () {
3374 return this.position;
3375 };
3376 /** @internal */
3377 Binary.prototype.toJSON = function () {
3378 return this.buffer.toString('base64');
3379 };
3380 /** @internal */
3381 Binary.prototype.toString = function (format) {
3382 return this.buffer.toString(format);
3383 };
3384 /** @internal */
3385 Binary.prototype.toExtendedJSON = function (options) {
3386 options = options || {};
3387 var base64String = this.buffer.toString('base64');
3388 var subType = Number(this.sub_type).toString(16);
3389 if (options.legacy) {
3390 return {
3391 $binary: base64String,
3392 $type: subType.length === 1 ? '0' + subType : subType
3393 };
3394 }
3395 return {
3396 $binary: {
3397 base64: base64String,
3398 subType: subType.length === 1 ? '0' + subType : subType
3399 }
3400 };
3401 };
3402 /** @internal */
3403 Binary.fromExtendedJSON = function (doc, options) {
3404 options = options || {};
3405 var data;
3406 var type;
3407 if ('$binary' in doc) {
3408 if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) {
3409 type = doc.$type ? parseInt(doc.$type, 16) : 0;
3410 data = buffer.Buffer.from(doc.$binary, 'base64');
3411 }
3412 else {
3413 if (typeof doc.$binary !== 'string') {
3414 type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
3415 data = buffer.Buffer.from(doc.$binary.base64, 'base64');
3416 }
3417 }
3418 }
3419 else if ('$uuid' in doc) {
3420 type = 4;
3421 data = buffer.Buffer.from(uuid.parseUUID(doc.$uuid));
3422 }
3423 if (!data) {
3424 throw new TypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc));
3425 }
3426 return new Binary(data, type);
3427 };
3428 /** @internal */
3429 Binary.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
3430 return this.inspect();
3431 };
3432 Binary.prototype.inspect = function () {
3433 var asBuffer = this.value(true);
3434 return "new Binary(Buffer.from(\"" + asBuffer.toString('hex') + "\", \"hex\"), " + this.sub_type + ")";
3435 };
3436 /**
3437 * Binary default subtype
3438 * @internal
3439 */
3440 Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0;
3441 /** Initial buffer default size */
3442 Binary.BUFFER_SIZE = 256;
3443 /** Default BSON type */
3444 Binary.SUBTYPE_DEFAULT = 0;
3445 /** Function BSON type */
3446 Binary.SUBTYPE_FUNCTION = 1;
3447 /** Byte Array BSON type */
3448 Binary.SUBTYPE_BYTE_ARRAY = 2;
3449 /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */
3450 Binary.SUBTYPE_UUID_OLD = 3;
3451 /** UUID BSON type */
3452 Binary.SUBTYPE_UUID = 4;
3453 /** MD5 BSON type */
3454 Binary.SUBTYPE_MD5 = 5;
3455 /** User BSON type */
3456 Binary.SUBTYPE_USER_DEFINED = 128;
3457 return Binary;
3458}());
3459exports.Binary = Binary;
3460Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' });
3461
3462});
3463
3464unwrapExports(binary);
3465var binary_1 = binary.Binary;
3466
3467var code$1 = createCommonjsModule(function (module, exports) {
3468Object.defineProperty(exports, "__esModule", { value: true });
3469exports.Code = void 0;
3470/**
3471 * A class representation of the BSON Code type.
3472 * @public
3473 */
3474var Code = /** @class */ (function () {
3475 /**
3476 * @param code - a string or function.
3477 * @param scope - an optional scope for the function.
3478 */
3479 function Code(code, scope) {
3480 if (!(this instanceof Code))
3481 return new Code(code, scope);
3482 this.code = code;
3483 this.scope = scope;
3484 }
3485 /** @internal */
3486 Code.prototype.toJSON = function () {
3487 return { code: this.code, scope: this.scope };
3488 };
3489 /** @internal */
3490 Code.prototype.toExtendedJSON = function () {
3491 if (this.scope) {
3492 return { $code: this.code, $scope: this.scope };
3493 }
3494 return { $code: this.code };
3495 };
3496 /** @internal */
3497 Code.fromExtendedJSON = function (doc) {
3498 return new Code(doc.$code, doc.$scope);
3499 };
3500 /** @internal */
3501 Code.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
3502 return this.inspect();
3503 };
3504 Code.prototype.inspect = function () {
3505 var codeJson = this.toJSON();
3506 return "new Code(\"" + codeJson.code + "\"" + (codeJson.scope ? ", " + JSON.stringify(codeJson.scope) : '') + ")";
3507 };
3508 return Code;
3509}());
3510exports.Code = Code;
3511Object.defineProperty(Code.prototype, '_bsontype', { value: 'Code' });
3512
3513});
3514
3515unwrapExports(code$1);
3516var code_1 = code$1.Code;
3517
3518var db_ref = createCommonjsModule(function (module, exports) {
3519Object.defineProperty(exports, "__esModule", { value: true });
3520exports.DBRef = exports.isDBRefLike = void 0;
3521
3522/** @internal */
3523function isDBRefLike(value) {
3524 return utils.isObjectLike(value) && value['$id'] != null && value['$ref'] != null;
3525}
3526exports.isDBRefLike = isDBRefLike;
3527/**
3528 * A class representation of the BSON DBRef type.
3529 * @public
3530 */
3531var DBRef = /** @class */ (function () {
3532 /**
3533 * @param collection - the collection name.
3534 * @param oid - the reference ObjectId.
3535 * @param db - optional db name, if omitted the reference is local to the current db.
3536 */
3537 function DBRef(collection, oid, db, fields) {
3538 if (!(this instanceof DBRef))
3539 return new DBRef(collection, oid, db, fields);
3540 // check if namespace has been provided
3541 var parts = collection.split('.');
3542 if (parts.length === 2) {
3543 db = parts.shift();
3544 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
3545 collection = parts.shift();
3546 }
3547 this.collection = collection;
3548 this.oid = oid;
3549 this.db = db;
3550 this.fields = fields || {};
3551 }
3552 Object.defineProperty(DBRef.prototype, "namespace", {
3553 // Property provided for compatibility with the 1.x parser
3554 // the 1.x parser used a "namespace" property, while 4.x uses "collection"
3555 /** @internal */
3556 get: function () {
3557 return this.collection;
3558 },
3559 set: function (value) {
3560 this.collection = value;
3561 },
3562 enumerable: false,
3563 configurable: true
3564 });
3565 /** @internal */
3566 DBRef.prototype.toJSON = function () {
3567 var o = Object.assign({
3568 $ref: this.collection,
3569 $id: this.oid
3570 }, this.fields);
3571 if (this.db != null)
3572 o.$db = this.db;
3573 return o;
3574 };
3575 /** @internal */
3576 DBRef.prototype.toExtendedJSON = function (options) {
3577 options = options || {};
3578 var o = {
3579 $ref: this.collection,
3580 $id: this.oid
3581 };
3582 if (options.legacy) {
3583 return o;
3584 }
3585 if (this.db)
3586 o.$db = this.db;
3587 o = Object.assign(o, this.fields);
3588 return o;
3589 };
3590 /** @internal */
3591 DBRef.fromExtendedJSON = function (doc) {
3592 var copy = Object.assign({}, doc);
3593 delete copy.$ref;
3594 delete copy.$id;
3595 delete copy.$db;
3596 return new DBRef(doc.$ref, doc.$id, doc.$db, copy);
3597 };
3598 /** @internal */
3599 DBRef.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
3600 return this.inspect();
3601 };
3602 DBRef.prototype.inspect = function () {
3603 // NOTE: if OID is an ObjectId class it will just print the oid string.
3604 var oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString();
3605 return "new DBRef(\"" + this.namespace + "\", new ObjectId(\"" + oid + "\")" + (this.db ? ", \"" + this.db + "\"" : '') + ")";
3606 };
3607 return DBRef;
3608}());
3609exports.DBRef = DBRef;
3610Object.defineProperty(DBRef.prototype, '_bsontype', { value: 'DBRef' });
3611
3612});
3613
3614unwrapExports(db_ref);
3615var db_ref_1 = db_ref.DBRef;
3616var db_ref_2 = db_ref.isDBRefLike;
3617
3618var long_1 = createCommonjsModule(function (module, exports) {
3619Object.defineProperty(exports, "__esModule", { value: true });
3620exports.Long = void 0;
3621
3622/**
3623 * wasm optimizations, to do native i64 multiplication and divide
3624 */
3625var wasm = undefined;
3626try {
3627 wasm = new WebAssembly.Instance(new WebAssembly.Module(
3628 // prettier-ignore
3629 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;
3630}
3631catch (_a) {
3632 // no wasm support
3633}
3634var TWO_PWR_16_DBL = 1 << 16;
3635var TWO_PWR_24_DBL = 1 << 24;
3636var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
3637var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
3638var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
3639/** A cache of the Long representations of small integer values. */
3640var INT_CACHE = {};
3641/** A cache of the Long representations of small unsigned integer values. */
3642var UINT_CACHE = {};
3643/**
3644 * A class representing a 64-bit integer
3645 * @public
3646 * @remarks
3647 * The internal representation of a long is the two given signed, 32-bit values.
3648 * We use 32-bit pieces because these are the size of integers on which
3649 * Javascript performs bit-operations. For operations like addition and
3650 * multiplication, we split each number into 16 bit pieces, which can easily be
3651 * multiplied within Javascript's floating-point representation without overflow
3652 * or change in sign.
3653 * In the algorithms below, we frequently reduce the negative case to the
3654 * positive case by negating the input(s) and then post-processing the result.
3655 * Note that we must ALWAYS check specially whether those values are MIN_VALUE
3656 * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
3657 * a positive number, it overflows back into a negative). Not handling this
3658 * case would often result in infinite recursion.
3659 * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class.
3660 */
3661var Long = /** @class */ (function () {
3662 /**
3663 * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
3664 * See the from* functions below for more convenient ways of constructing Longs.
3665 * @param low - The low (signed) 32 bits of the long
3666 * @param high - The high (signed) 32 bits of the long
3667 * @param unsigned - Whether unsigned or not, defaults to signed
3668 */
3669 function Long(low, high, unsigned) {
3670 if (low === void 0) { low = 0; }
3671 if (high === void 0) { high = 0; }
3672 if (!(this instanceof Long))
3673 return new Long(low, high, unsigned);
3674 this.low = low | 0;
3675 this.high = high | 0;
3676 this.unsigned = !!unsigned;
3677 Object.defineProperty(this, '__isLong__', {
3678 value: true,
3679 configurable: false,
3680 writable: false,
3681 enumerable: false
3682 });
3683 }
3684 /**
3685 * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits.
3686 * Each is assumed to use 32 bits.
3687 * @param lowBits - The low 32 bits
3688 * @param highBits - The high 32 bits
3689 * @param unsigned - Whether unsigned or not, defaults to signed
3690 * @returns The corresponding Long value
3691 */
3692 Long.fromBits = function (lowBits, highBits, unsigned) {
3693 return new Long(lowBits, highBits, unsigned);
3694 };
3695 /**
3696 * Returns a Long representing the given 32 bit integer value.
3697 * @param value - The 32 bit integer in question
3698 * @param unsigned - Whether unsigned or not, defaults to signed
3699 * @returns The corresponding Long value
3700 */
3701 Long.fromInt = function (value, unsigned) {
3702 var obj, cachedObj, cache;
3703 if (unsigned) {
3704 value >>>= 0;
3705 if ((cache = 0 <= value && value < 256)) {
3706 cachedObj = UINT_CACHE[value];
3707 if (cachedObj)
3708 return cachedObj;
3709 }
3710 obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true);
3711 if (cache)
3712 UINT_CACHE[value] = obj;
3713 return obj;
3714 }
3715 else {
3716 value |= 0;
3717 if ((cache = -128 <= value && value < 128)) {
3718 cachedObj = INT_CACHE[value];
3719 if (cachedObj)
3720 return cachedObj;
3721 }
3722 obj = Long.fromBits(value, value < 0 ? -1 : 0, false);
3723 if (cache)
3724 INT_CACHE[value] = obj;
3725 return obj;
3726 }
3727 };
3728 /**
3729 * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
3730 * @param value - The number in question
3731 * @param unsigned - Whether unsigned or not, defaults to signed
3732 * @returns The corresponding Long value
3733 */
3734 Long.fromNumber = function (value, unsigned) {
3735 if (isNaN(value))
3736 return unsigned ? Long.UZERO : Long.ZERO;
3737 if (unsigned) {
3738 if (value < 0)
3739 return Long.UZERO;
3740 if (value >= TWO_PWR_64_DBL)
3741 return Long.MAX_UNSIGNED_VALUE;
3742 }
3743 else {
3744 if (value <= -TWO_PWR_63_DBL)
3745 return Long.MIN_VALUE;
3746 if (value + 1 >= TWO_PWR_63_DBL)
3747 return Long.MAX_VALUE;
3748 }
3749 if (value < 0)
3750 return Long.fromNumber(-value, unsigned).neg();
3751 return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
3752 };
3753 /**
3754 * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
3755 * @param value - The number in question
3756 * @param unsigned - Whether unsigned or not, defaults to signed
3757 * @returns The corresponding Long value
3758 */
3759 Long.fromBigInt = function (value, unsigned) {
3760 return Long.fromString(value.toString(), unsigned);
3761 };
3762 /**
3763 * Returns a Long representation of the given string, written using the specified radix.
3764 * @param str - The textual representation of the Long
3765 * @param unsigned - Whether unsigned or not, defaults to signed
3766 * @param radix - The radix in which the text is written (2-36), defaults to 10
3767 * @returns The corresponding Long value
3768 */
3769 Long.fromString = function (str, unsigned, radix) {
3770 if (str.length === 0)
3771 throw Error('empty string');
3772 if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity')
3773 return Long.ZERO;
3774 if (typeof unsigned === 'number') {
3775 // For goog.math.long compatibility
3776 (radix = unsigned), (unsigned = false);
3777 }
3778 else {
3779 unsigned = !!unsigned;
3780 }
3781 radix = radix || 10;
3782 if (radix < 2 || 36 < radix)
3783 throw RangeError('radix');
3784 var p;
3785 if ((p = str.indexOf('-')) > 0)
3786 throw Error('interior hyphen');
3787 else if (p === 0) {
3788 return Long.fromString(str.substring(1), unsigned, radix).neg();
3789 }
3790 // Do several (8) digits each time through the loop, so as to
3791 // minimize the calls to the very expensive emulated div.
3792 var radixToPower = Long.fromNumber(Math.pow(radix, 8));
3793 var result = Long.ZERO;
3794 for (var i = 0; i < str.length; i += 8) {
3795 var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix);
3796 if (size < 8) {
3797 var power = Long.fromNumber(Math.pow(radix, size));
3798 result = result.mul(power).add(Long.fromNumber(value));
3799 }
3800 else {
3801 result = result.mul(radixToPower);
3802 result = result.add(Long.fromNumber(value));
3803 }
3804 }
3805 result.unsigned = unsigned;
3806 return result;
3807 };
3808 /**
3809 * Creates a Long from its byte representation.
3810 * @param bytes - Byte representation
3811 * @param unsigned - Whether unsigned or not, defaults to signed
3812 * @param le - Whether little or big endian, defaults to big endian
3813 * @returns The corresponding Long value
3814 */
3815 Long.fromBytes = function (bytes, unsigned, le) {
3816 return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
3817 };
3818 /**
3819 * Creates a Long from its little endian byte representation.
3820 * @param bytes - Little endian byte representation
3821 * @param unsigned - Whether unsigned or not, defaults to signed
3822 * @returns The corresponding Long value
3823 */
3824 Long.fromBytesLE = function (bytes, unsigned) {
3825 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);
3826 };
3827 /**
3828 * Creates a Long from its big endian byte representation.
3829 * @param bytes - Big endian byte representation
3830 * @param unsigned - Whether unsigned or not, defaults to signed
3831 * @returns The corresponding Long value
3832 */
3833 Long.fromBytesBE = function (bytes, unsigned) {
3834 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);
3835 };
3836 /**
3837 * Tests if the specified object is a Long.
3838 */
3839 // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
3840 Long.isLong = function (value) {
3841 return utils.isObjectLike(value) && value['__isLong__'] === true;
3842 };
3843 /**
3844 * Converts the specified value to a Long.
3845 * @param unsigned - Whether unsigned or not, defaults to signed
3846 */
3847 Long.fromValue = function (val, unsigned) {
3848 if (typeof val === 'number')
3849 return Long.fromNumber(val, unsigned);
3850 if (typeof val === 'string')
3851 return Long.fromString(val, unsigned);
3852 // Throws for non-objects, converts non-instanceof Long:
3853 return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);
3854 };
3855 /** Returns the sum of this and the specified Long. */
3856 Long.prototype.add = function (addend) {
3857 if (!Long.isLong(addend))
3858 addend = Long.fromValue(addend);
3859 // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
3860 var a48 = this.high >>> 16;
3861 var a32 = this.high & 0xffff;
3862 var a16 = this.low >>> 16;
3863 var a00 = this.low & 0xffff;
3864 var b48 = addend.high >>> 16;
3865 var b32 = addend.high & 0xffff;
3866 var b16 = addend.low >>> 16;
3867 var b00 = addend.low & 0xffff;
3868 var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
3869 c00 += a00 + b00;
3870 c16 += c00 >>> 16;
3871 c00 &= 0xffff;
3872 c16 += a16 + b16;
3873 c32 += c16 >>> 16;
3874 c16 &= 0xffff;
3875 c32 += a32 + b32;
3876 c48 += c32 >>> 16;
3877 c32 &= 0xffff;
3878 c48 += a48 + b48;
3879 c48 &= 0xffff;
3880 return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
3881 };
3882 /**
3883 * Returns the sum of this and the specified Long.
3884 * @returns Sum
3885 */
3886 Long.prototype.and = function (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 /**
3892 * Compares this Long's value with the specified's.
3893 * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater
3894 */
3895 Long.prototype.compare = function (other) {
3896 if (!Long.isLong(other))
3897 other = Long.fromValue(other);
3898 if (this.eq(other))
3899 return 0;
3900 var thisNeg = this.isNegative(), otherNeg = other.isNegative();
3901 if (thisNeg && !otherNeg)
3902 return -1;
3903 if (!thisNeg && otherNeg)
3904 return 1;
3905 // At this point the sign bits are the same
3906 if (!this.unsigned)
3907 return this.sub(other).isNegative() ? -1 : 1;
3908 // Both are positive if at least one is unsigned
3909 return other.high >>> 0 > this.high >>> 0 ||
3910 (other.high === this.high && other.low >>> 0 > this.low >>> 0)
3911 ? -1
3912 : 1;
3913 };
3914 /** This is an alias of {@link Long.compare} */
3915 Long.prototype.comp = function (other) {
3916 return this.compare(other);
3917 };
3918 /**
3919 * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned.
3920 * @returns Quotient
3921 */
3922 Long.prototype.divide = function (divisor) {
3923 if (!Long.isLong(divisor))
3924 divisor = Long.fromValue(divisor);
3925 if (divisor.isZero())
3926 throw Error('division by zero');
3927 // use wasm support if present
3928 if (wasm) {
3929 // guard against signed division overflow: the largest
3930 // negative number / -1 would be 1 larger than the largest
3931 // positive number, due to two's complement.
3932 if (!this.unsigned &&
3933 this.high === -0x80000000 &&
3934 divisor.low === -1 &&
3935 divisor.high === -1) {
3936 // be consistent with non-wasm code path
3937 return this;
3938 }
3939 var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high);
3940 return Long.fromBits(low, wasm.get_high(), this.unsigned);
3941 }
3942 if (this.isZero())
3943 return this.unsigned ? Long.UZERO : Long.ZERO;
3944 var approx, rem, res;
3945 if (!this.unsigned) {
3946 // This section is only relevant for signed longs and is derived from the
3947 // closure library as a whole.
3948 if (this.eq(Long.MIN_VALUE)) {
3949 if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE))
3950 return Long.MIN_VALUE;
3951 // recall that -MIN_VALUE == MIN_VALUE
3952 else if (divisor.eq(Long.MIN_VALUE))
3953 return Long.ONE;
3954 else {
3955 // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
3956 var halfThis = this.shr(1);
3957 approx = halfThis.div(divisor).shl(1);
3958 if (approx.eq(Long.ZERO)) {
3959 return divisor.isNegative() ? Long.ONE : Long.NEG_ONE;
3960 }
3961 else {
3962 rem = this.sub(divisor.mul(approx));
3963 res = approx.add(rem.div(divisor));
3964 return res;
3965 }
3966 }
3967 }
3968 else if (divisor.eq(Long.MIN_VALUE))
3969 return this.unsigned ? Long.UZERO : Long.ZERO;
3970 if (this.isNegative()) {
3971 if (divisor.isNegative())
3972 return this.neg().div(divisor.neg());
3973 return this.neg().div(divisor).neg();
3974 }
3975 else if (divisor.isNegative())
3976 return this.div(divisor.neg()).neg();
3977 res = Long.ZERO;
3978 }
3979 else {
3980 // The algorithm below has not been made for unsigned longs. It's therefore
3981 // required to take special care of the MSB prior to running it.
3982 if (!divisor.unsigned)
3983 divisor = divisor.toUnsigned();
3984 if (divisor.gt(this))
3985 return Long.UZERO;
3986 if (divisor.gt(this.shru(1)))
3987 // 15 >>> 1 = 7 ; with divisor = 8 ; true
3988 return Long.UONE;
3989 res = Long.UZERO;
3990 }
3991 // Repeat the following until the remainder is less than other: find a
3992 // floating-point that approximates remainder / other *from below*, add this
3993 // into the result, and subtract it from the remainder. It is critical that
3994 // the approximate value is less than or equal to the real value so that the
3995 // remainder never becomes negative.
3996 rem = this;
3997 while (rem.gte(divisor)) {
3998 // Approximate the result of division. This may be a little greater or
3999 // smaller than the actual value.
4000 approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
4001 // We will tweak the approximate result by changing it in the 48-th digit or
4002 // the smallest non-fractional digit, whichever is larger.
4003 var log2 = Math.ceil(Math.log(approx) / Math.LN2);
4004 var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);
4005 // Decrease the approximation until it is smaller than the remainder. Note
4006 // that if it is too large, the product overflows and is negative.
4007 var approxRes = Long.fromNumber(approx);
4008 var approxRem = approxRes.mul(divisor);
4009 while (approxRem.isNegative() || approxRem.gt(rem)) {
4010 approx -= delta;
4011 approxRes = Long.fromNumber(approx, this.unsigned);
4012 approxRem = approxRes.mul(divisor);
4013 }
4014 // We know the answer can't be zero... and actually, zero would cause
4015 // infinite recursion since we would make no progress.
4016 if (approxRes.isZero())
4017 approxRes = Long.ONE;
4018 res = res.add(approxRes);
4019 rem = rem.sub(approxRem);
4020 }
4021 return res;
4022 };
4023 /**This is an alias of {@link Long.divide} */
4024 Long.prototype.div = function (divisor) {
4025 return this.divide(divisor);
4026 };
4027 /**
4028 * Tests if this Long's value equals the specified's.
4029 * @param other - Other value
4030 */
4031 Long.prototype.equals = function (other) {
4032 if (!Long.isLong(other))
4033 other = Long.fromValue(other);
4034 if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
4035 return false;
4036 return this.high === other.high && this.low === other.low;
4037 };
4038 /** This is an alias of {@link Long.equals} */
4039 Long.prototype.eq = function (other) {
4040 return this.equals(other);
4041 };
4042 /** Gets the high 32 bits as a signed integer. */
4043 Long.prototype.getHighBits = function () {
4044 return this.high;
4045 };
4046 /** Gets the high 32 bits as an unsigned integer. */
4047 Long.prototype.getHighBitsUnsigned = function () {
4048 return this.high >>> 0;
4049 };
4050 /** Gets the low 32 bits as a signed integer. */
4051 Long.prototype.getLowBits = function () {
4052 return this.low;
4053 };
4054 /** Gets the low 32 bits as an unsigned integer. */
4055 Long.prototype.getLowBitsUnsigned = function () {
4056 return this.low >>> 0;
4057 };
4058 /** Gets the number of bits needed to represent the absolute value of this Long. */
4059 Long.prototype.getNumBitsAbs = function () {
4060 if (this.isNegative()) {
4061 // Unsigned Longs are never negative
4062 return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
4063 }
4064 var val = this.high !== 0 ? this.high : this.low;
4065 var bit;
4066 for (bit = 31; bit > 0; bit--)
4067 if ((val & (1 << bit)) !== 0)
4068 break;
4069 return this.high !== 0 ? bit + 33 : bit + 1;
4070 };
4071 /** Tests if this Long's value is greater than the specified's. */
4072 Long.prototype.greaterThan = function (other) {
4073 return this.comp(other) > 0;
4074 };
4075 /** This is an alias of {@link Long.greaterThan} */
4076 Long.prototype.gt = function (other) {
4077 return this.greaterThan(other);
4078 };
4079 /** Tests if this Long's value is greater than or equal the specified's. */
4080 Long.prototype.greaterThanOrEqual = function (other) {
4081 return this.comp(other) >= 0;
4082 };
4083 /** This is an alias of {@link Long.greaterThanOrEqual} */
4084 Long.prototype.gte = function (other) {
4085 return this.greaterThanOrEqual(other);
4086 };
4087 /** This is an alias of {@link Long.greaterThanOrEqual} */
4088 Long.prototype.ge = function (other) {
4089 return this.greaterThanOrEqual(other);
4090 };
4091 /** Tests if this Long's value is even. */
4092 Long.prototype.isEven = function () {
4093 return (this.low & 1) === 0;
4094 };
4095 /** Tests if this Long's value is negative. */
4096 Long.prototype.isNegative = function () {
4097 return !this.unsigned && this.high < 0;
4098 };
4099 /** Tests if this Long's value is odd. */
4100 Long.prototype.isOdd = function () {
4101 return (this.low & 1) === 1;
4102 };
4103 /** Tests if this Long's value is positive. */
4104 Long.prototype.isPositive = function () {
4105 return this.unsigned || this.high >= 0;
4106 };
4107 /** Tests if this Long's value equals zero. */
4108 Long.prototype.isZero = function () {
4109 return this.high === 0 && this.low === 0;
4110 };
4111 /** Tests if this Long's value is less than the specified's. */
4112 Long.prototype.lessThan = function (other) {
4113 return this.comp(other) < 0;
4114 };
4115 /** This is an alias of {@link Long#lessThan}. */
4116 Long.prototype.lt = function (other) {
4117 return this.lessThan(other);
4118 };
4119 /** Tests if this Long's value is less than or equal the specified's. */
4120 Long.prototype.lessThanOrEqual = function (other) {
4121 return this.comp(other) <= 0;
4122 };
4123 /** This is an alias of {@link Long.lessThanOrEqual} */
4124 Long.prototype.lte = function (other) {
4125 return this.lessThanOrEqual(other);
4126 };
4127 /** Returns this Long modulo the specified. */
4128 Long.prototype.modulo = function (divisor) {
4129 if (!Long.isLong(divisor))
4130 divisor = Long.fromValue(divisor);
4131 // use wasm support if present
4132 if (wasm) {
4133 var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high);
4134 return Long.fromBits(low, wasm.get_high(), this.unsigned);
4135 }
4136 return this.sub(this.div(divisor).mul(divisor));
4137 };
4138 /** This is an alias of {@link Long.modulo} */
4139 Long.prototype.mod = function (divisor) {
4140 return this.modulo(divisor);
4141 };
4142 /** This is an alias of {@link Long.modulo} */
4143 Long.prototype.rem = function (divisor) {
4144 return this.modulo(divisor);
4145 };
4146 /**
4147 * Returns the product of this and the specified Long.
4148 * @param multiplier - Multiplier
4149 * @returns Product
4150 */
4151 Long.prototype.multiply = function (multiplier) {
4152 if (this.isZero())
4153 return Long.ZERO;
4154 if (!Long.isLong(multiplier))
4155 multiplier = Long.fromValue(multiplier);
4156 // use wasm support if present
4157 if (wasm) {
4158 var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
4159 return Long.fromBits(low, wasm.get_high(), this.unsigned);
4160 }
4161 if (multiplier.isZero())
4162 return Long.ZERO;
4163 if (this.eq(Long.MIN_VALUE))
4164 return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO;
4165 if (multiplier.eq(Long.MIN_VALUE))
4166 return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;
4167 if (this.isNegative()) {
4168 if (multiplier.isNegative())
4169 return this.neg().mul(multiplier.neg());
4170 else
4171 return this.neg().mul(multiplier).neg();
4172 }
4173 else if (multiplier.isNegative())
4174 return this.mul(multiplier.neg()).neg();
4175 // If both longs are small, use float multiplication
4176 if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24))
4177 return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
4178 // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
4179 // We can skip products that would overflow.
4180 var a48 = this.high >>> 16;
4181 var a32 = this.high & 0xffff;
4182 var a16 = this.low >>> 16;
4183 var a00 = this.low & 0xffff;
4184 var b48 = multiplier.high >>> 16;
4185 var b32 = multiplier.high & 0xffff;
4186 var b16 = multiplier.low >>> 16;
4187 var b00 = multiplier.low & 0xffff;
4188 var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
4189 c00 += a00 * b00;
4190 c16 += c00 >>> 16;
4191 c00 &= 0xffff;
4192 c16 += a16 * b00;
4193 c32 += c16 >>> 16;
4194 c16 &= 0xffff;
4195 c16 += a00 * b16;
4196 c32 += c16 >>> 16;
4197 c16 &= 0xffff;
4198 c32 += a32 * b00;
4199 c48 += c32 >>> 16;
4200 c32 &= 0xffff;
4201 c32 += a16 * b16;
4202 c48 += c32 >>> 16;
4203 c32 &= 0xffff;
4204 c32 += a00 * b32;
4205 c48 += c32 >>> 16;
4206 c32 &= 0xffff;
4207 c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
4208 c48 &= 0xffff;
4209 return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
4210 };
4211 /** This is an alias of {@link Long.multiply} */
4212 Long.prototype.mul = function (multiplier) {
4213 return this.multiply(multiplier);
4214 };
4215 /** Returns the Negation of this Long's value. */
4216 Long.prototype.negate = function () {
4217 if (!this.unsigned && this.eq(Long.MIN_VALUE))
4218 return Long.MIN_VALUE;
4219 return this.not().add(Long.ONE);
4220 };
4221 /** This is an alias of {@link Long.negate} */
4222 Long.prototype.neg = function () {
4223 return this.negate();
4224 };
4225 /** Returns the bitwise NOT of this Long. */
4226 Long.prototype.not = function () {
4227 return Long.fromBits(~this.low, ~this.high, this.unsigned);
4228 };
4229 /** Tests if this Long's value differs from the specified's. */
4230 Long.prototype.notEquals = function (other) {
4231 return !this.equals(other);
4232 };
4233 /** This is an alias of {@link Long.notEquals} */
4234 Long.prototype.neq = function (other) {
4235 return this.notEquals(other);
4236 };
4237 /** This is an alias of {@link Long.notEquals} */
4238 Long.prototype.ne = function (other) {
4239 return this.notEquals(other);
4240 };
4241 /**
4242 * Returns the bitwise OR of this Long and the specified.
4243 */
4244 Long.prototype.or = function (other) {
4245 if (!Long.isLong(other))
4246 other = Long.fromValue(other);
4247 return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned);
4248 };
4249 /**
4250 * Returns this Long with bits shifted to the left by the given amount.
4251 * @param numBits - Number of bits
4252 * @returns Shifted Long
4253 */
4254 Long.prototype.shiftLeft = function (numBits) {
4255 if (Long.isLong(numBits))
4256 numBits = numBits.toInt();
4257 if ((numBits &= 63) === 0)
4258 return this;
4259 else if (numBits < 32)
4260 return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
4261 else
4262 return Long.fromBits(0, this.low << (numBits - 32), this.unsigned);
4263 };
4264 /** This is an alias of {@link Long.shiftLeft} */
4265 Long.prototype.shl = function (numBits) {
4266 return this.shiftLeft(numBits);
4267 };
4268 /**
4269 * Returns this Long with bits arithmetically shifted to the right by the given amount.
4270 * @param numBits - Number of bits
4271 * @returns Shifted Long
4272 */
4273 Long.prototype.shiftRight = function (numBits) {
4274 if (Long.isLong(numBits))
4275 numBits = numBits.toInt();
4276 if ((numBits &= 63) === 0)
4277 return this;
4278 else if (numBits < 32)
4279 return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
4280 else
4281 return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
4282 };
4283 /** This is an alias of {@link Long.shiftRight} */
4284 Long.prototype.shr = function (numBits) {
4285 return this.shiftRight(numBits);
4286 };
4287 /**
4288 * Returns this Long with bits logically shifted to the right by the given amount.
4289 * @param numBits - Number of bits
4290 * @returns Shifted Long
4291 */
4292 Long.prototype.shiftRightUnsigned = function (numBits) {
4293 if (Long.isLong(numBits))
4294 numBits = numBits.toInt();
4295 numBits &= 63;
4296 if (numBits === 0)
4297 return this;
4298 else {
4299 var high = this.high;
4300 if (numBits < 32) {
4301 var low = this.low;
4302 return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
4303 }
4304 else if (numBits === 32)
4305 return Long.fromBits(high, 0, this.unsigned);
4306 else
4307 return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned);
4308 }
4309 };
4310 /** This is an alias of {@link Long.shiftRightUnsigned} */
4311 Long.prototype.shr_u = function (numBits) {
4312 return this.shiftRightUnsigned(numBits);
4313 };
4314 /** This is an alias of {@link Long.shiftRightUnsigned} */
4315 Long.prototype.shru = function (numBits) {
4316 return this.shiftRightUnsigned(numBits);
4317 };
4318 /**
4319 * Returns the difference of this and the specified Long.
4320 * @param subtrahend - Subtrahend
4321 * @returns Difference
4322 */
4323 Long.prototype.subtract = function (subtrahend) {
4324 if (!Long.isLong(subtrahend))
4325 subtrahend = Long.fromValue(subtrahend);
4326 return this.add(subtrahend.neg());
4327 };
4328 /** This is an alias of {@link Long.subtract} */
4329 Long.prototype.sub = function (subtrahend) {
4330 return this.subtract(subtrahend);
4331 };
4332 /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */
4333 Long.prototype.toInt = function () {
4334 return this.unsigned ? this.low >>> 0 : this.low;
4335 };
4336 /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */
4337 Long.prototype.toNumber = function () {
4338 if (this.unsigned)
4339 return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
4340 return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
4341 };
4342 /** Converts the Long to a BigInt (arbitrary precision). */
4343 Long.prototype.toBigInt = function () {
4344 return BigInt(this.toString());
4345 };
4346 /**
4347 * Converts this Long to its byte representation.
4348 * @param le - Whether little or big endian, defaults to big endian
4349 * @returns Byte representation
4350 */
4351 Long.prototype.toBytes = function (le) {
4352 return le ? this.toBytesLE() : this.toBytesBE();
4353 };
4354 /**
4355 * Converts this Long to its little endian byte representation.
4356 * @returns Little endian byte representation
4357 */
4358 Long.prototype.toBytesLE = function () {
4359 var hi = this.high, lo = this.low;
4360 return [
4361 lo & 0xff,
4362 (lo >>> 8) & 0xff,
4363 (lo >>> 16) & 0xff,
4364 lo >>> 24,
4365 hi & 0xff,
4366 (hi >>> 8) & 0xff,
4367 (hi >>> 16) & 0xff,
4368 hi >>> 24
4369 ];
4370 };
4371 /**
4372 * Converts this Long to its big endian byte representation.
4373 * @returns Big endian byte representation
4374 */
4375 Long.prototype.toBytesBE = function () {
4376 var hi = this.high, lo = this.low;
4377 return [
4378 hi >>> 24,
4379 (hi >>> 16) & 0xff,
4380 (hi >>> 8) & 0xff,
4381 hi & 0xff,
4382 lo >>> 24,
4383 (lo >>> 16) & 0xff,
4384 (lo >>> 8) & 0xff,
4385 lo & 0xff
4386 ];
4387 };
4388 /**
4389 * Converts this Long to signed.
4390 */
4391 Long.prototype.toSigned = function () {
4392 if (!this.unsigned)
4393 return this;
4394 return Long.fromBits(this.low, this.high, false);
4395 };
4396 /**
4397 * Converts the Long to a string written in the specified radix.
4398 * @param radix - Radix (2-36), defaults to 10
4399 * @throws RangeError If `radix` is out of range
4400 */
4401 Long.prototype.toString = function (radix) {
4402 radix = radix || 10;
4403 if (radix < 2 || 36 < radix)
4404 throw RangeError('radix');
4405 if (this.isZero())
4406 return '0';
4407 if (this.isNegative()) {
4408 // Unsigned Longs are never negative
4409 if (this.eq(Long.MIN_VALUE)) {
4410 // We need to change the Long value before it can be negated, so we remove
4411 // the bottom-most digit in this base and then recurse to do the rest.
4412 var radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this);
4413 return div.toString(radix) + rem1.toInt().toString(radix);
4414 }
4415 else
4416 return '-' + this.neg().toString(radix);
4417 }
4418 // Do several (6) digits each time through the loop, so as to
4419 // minimize the calls to the very expensive emulated div.
4420 var radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned);
4421 // eslint-disable-next-line @typescript-eslint/no-this-alias
4422 var rem = this;
4423 var result = '';
4424 // eslint-disable-next-line no-constant-condition
4425 while (true) {
4426 var remDiv = rem.div(radixToPower);
4427 var intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0;
4428 var digits = intval.toString(radix);
4429 rem = remDiv;
4430 if (rem.isZero()) {
4431 return digits + result;
4432 }
4433 else {
4434 while (digits.length < 6)
4435 digits = '0' + digits;
4436 result = '' + digits + result;
4437 }
4438 }
4439 };
4440 /** Converts this Long to unsigned. */
4441 Long.prototype.toUnsigned = function () {
4442 if (this.unsigned)
4443 return this;
4444 return Long.fromBits(this.low, this.high, true);
4445 };
4446 /** Returns the bitwise XOR of this Long and the given one. */
4447 Long.prototype.xor = function (other) {
4448 if (!Long.isLong(other))
4449 other = Long.fromValue(other);
4450 return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
4451 };
4452 /** This is an alias of {@link Long.isZero} */
4453 Long.prototype.eqz = function () {
4454 return this.isZero();
4455 };
4456 /** This is an alias of {@link Long.lessThanOrEqual} */
4457 Long.prototype.le = function (other) {
4458 return this.lessThanOrEqual(other);
4459 };
4460 /*
4461 ****************************************************************
4462 * BSON SPECIFIC ADDITIONS *
4463 ****************************************************************
4464 */
4465 Long.prototype.toExtendedJSON = function (options) {
4466 if (options && options.relaxed)
4467 return this.toNumber();
4468 return { $numberLong: this.toString() };
4469 };
4470 Long.fromExtendedJSON = function (doc, options) {
4471 var result = Long.fromString(doc.$numberLong);
4472 return options && options.relaxed ? result.toNumber() : result;
4473 };
4474 /** @internal */
4475 Long.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
4476 return this.inspect();
4477 };
4478 Long.prototype.inspect = function () {
4479 return "new Long(\"" + this.toString() + "\")";
4480 };
4481 Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL);
4482 /** Maximum unsigned value. */
4483 Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true);
4484 /** Signed zero */
4485 Long.ZERO = Long.fromInt(0);
4486 /** Unsigned zero. */
4487 Long.UZERO = Long.fromInt(0, true);
4488 /** Signed one. */
4489 Long.ONE = Long.fromInt(1);
4490 /** Unsigned one. */
4491 Long.UONE = Long.fromInt(1, true);
4492 /** Signed negative one. */
4493 Long.NEG_ONE = Long.fromInt(-1);
4494 /** Maximum signed value. */
4495 Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false);
4496 /** Minimum signed value. */
4497 Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false);
4498 return Long;
4499}());
4500exports.Long = Long;
4501Object.defineProperty(Long.prototype, '__isLong__', { value: true });
4502Object.defineProperty(Long.prototype, '_bsontype', { value: 'Long' });
4503
4504});
4505
4506unwrapExports(long_1);
4507var long_2 = long_1.Long;
4508
4509var decimal128 = createCommonjsModule(function (module, exports) {
4510Object.defineProperty(exports, "__esModule", { value: true });
4511exports.Decimal128 = void 0;
4512
4513
4514var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
4515var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
4516var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
4517var EXPONENT_MAX = 6111;
4518var EXPONENT_MIN = -6176;
4519var EXPONENT_BIAS = 6176;
4520var MAX_DIGITS = 34;
4521// Nan value bits as 32 bit values (due to lack of longs)
4522var NAN_BUFFER = [
4523 0x7c,
4524 0x00,
4525 0x00,
4526 0x00,
4527 0x00,
4528 0x00,
4529 0x00,
4530 0x00,
4531 0x00,
4532 0x00,
4533 0x00,
4534 0x00,
4535 0x00,
4536 0x00,
4537 0x00,
4538 0x00
4539].reverse();
4540// Infinity value bits 32 bit values (due to lack of longs)
4541var INF_NEGATIVE_BUFFER = [
4542 0xf8,
4543 0x00,
4544 0x00,
4545 0x00,
4546 0x00,
4547 0x00,
4548 0x00,
4549 0x00,
4550 0x00,
4551 0x00,
4552 0x00,
4553 0x00,
4554 0x00,
4555 0x00,
4556 0x00,
4557 0x00
4558].reverse();
4559var INF_POSITIVE_BUFFER = [
4560 0x78,
4561 0x00,
4562 0x00,
4563 0x00,
4564 0x00,
4565 0x00,
4566 0x00,
4567 0x00,
4568 0x00,
4569 0x00,
4570 0x00,
4571 0x00,
4572 0x00,
4573 0x00,
4574 0x00,
4575 0x00
4576].reverse();
4577var EXPONENT_REGEX = /^([-+])?(\d+)?$/;
4578// Extract least significant 5 bits
4579var COMBINATION_MASK = 0x1f;
4580// Extract least significant 14 bits
4581var EXPONENT_MASK = 0x3fff;
4582// Value of combination field for Inf
4583var COMBINATION_INFINITY = 30;
4584// Value of combination field for NaN
4585var COMBINATION_NAN = 31;
4586// Detect if the value is a digit
4587function isDigit(value) {
4588 return !isNaN(parseInt(value, 10));
4589}
4590// Divide two uint128 values
4591function divideu128(value) {
4592 var DIVISOR = long_1.Long.fromNumber(1000 * 1000 * 1000);
4593 var _rem = long_1.Long.fromNumber(0);
4594 if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
4595 return { quotient: value, rem: _rem };
4596 }
4597 for (var i = 0; i <= 3; i++) {
4598 // Adjust remainder to match value of next dividend
4599 _rem = _rem.shiftLeft(32);
4600 // Add the divided to _rem
4601 _rem = _rem.add(new long_1.Long(value.parts[i], 0));
4602 value.parts[i] = _rem.div(DIVISOR).low;
4603 _rem = _rem.modulo(DIVISOR);
4604 }
4605 return { quotient: value, rem: _rem };
4606}
4607// Multiply two Long values and return the 128 bit value
4608function multiply64x2(left, right) {
4609 if (!left && !right) {
4610 return { high: long_1.Long.fromNumber(0), low: long_1.Long.fromNumber(0) };
4611 }
4612 var leftHigh = left.shiftRightUnsigned(32);
4613 var leftLow = new long_1.Long(left.getLowBits(), 0);
4614 var rightHigh = right.shiftRightUnsigned(32);
4615 var rightLow = new long_1.Long(right.getLowBits(), 0);
4616 var productHigh = leftHigh.multiply(rightHigh);
4617 var productMid = leftHigh.multiply(rightLow);
4618 var productMid2 = leftLow.multiply(rightHigh);
4619 var productLow = leftLow.multiply(rightLow);
4620 productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
4621 productMid = new long_1.Long(productMid.getLowBits(), 0)
4622 .add(productMid2)
4623 .add(productLow.shiftRightUnsigned(32));
4624 productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
4625 productLow = productMid.shiftLeft(32).add(new long_1.Long(productLow.getLowBits(), 0));
4626 // Return the 128 bit result
4627 return { high: productHigh, low: productLow };
4628}
4629function lessThan(left, right) {
4630 // Make values unsigned
4631 var uhleft = left.high >>> 0;
4632 var uhright = right.high >>> 0;
4633 // Compare high bits first
4634 if (uhleft < uhright) {
4635 return true;
4636 }
4637 else if (uhleft === uhright) {
4638 var ulleft = left.low >>> 0;
4639 var ulright = right.low >>> 0;
4640 if (ulleft < ulright)
4641 return true;
4642 }
4643 return false;
4644}
4645function invalidErr(string, message) {
4646 throw new TypeError("\"" + string + "\" is not a valid Decimal128 string - " + message);
4647}
4648/**
4649 * A class representation of the BSON Decimal128 type.
4650 * @public
4651 */
4652var Decimal128 = /** @class */ (function () {
4653 /** @param bytes - a buffer containing the raw Decimal128 bytes in little endian order */
4654 function Decimal128(bytes) {
4655 if (!(this instanceof Decimal128))
4656 return new Decimal128(bytes);
4657 this.bytes = bytes;
4658 }
4659 /**
4660 * Create a Decimal128 instance from a string representation
4661 *
4662 * @param representation - a numeric string representation.
4663 */
4664 Decimal128.fromString = function (representation) {
4665 // Parse state tracking
4666 var isNegative = false;
4667 var sawRadix = false;
4668 var foundNonZero = false;
4669 // Total number of significant digits (no leading or trailing zero)
4670 var significantDigits = 0;
4671 // Total number of significand digits read
4672 var nDigitsRead = 0;
4673 // Total number of digits (no leading zeros)
4674 var nDigits = 0;
4675 // The number of the digits after radix
4676 var radixPosition = 0;
4677 // The index of the first non-zero in *str*
4678 var firstNonZero = 0;
4679 // Digits Array
4680 var digits = [0];
4681 // The number of digits in digits
4682 var nDigitsStored = 0;
4683 // Insertion pointer for digits
4684 var digitsInsert = 0;
4685 // The index of the first non-zero digit
4686 var firstDigit = 0;
4687 // The index of the last digit
4688 var lastDigit = 0;
4689 // Exponent
4690 var exponent = 0;
4691 // loop index over array
4692 var i = 0;
4693 // The high 17 digits of the significand
4694 var significandHigh = new long_1.Long(0, 0);
4695 // The low 17 digits of the significand
4696 var significandLow = new long_1.Long(0, 0);
4697 // The biased exponent
4698 var biasedExponent = 0;
4699 // Read index
4700 var index = 0;
4701 // Naively prevent against REDOS attacks.
4702 // TODO: implementing a custom parsing for this, or refactoring the regex would yield
4703 // further gains.
4704 if (representation.length >= 7000) {
4705 throw new TypeError('' + representation + ' not a valid Decimal128 string');
4706 }
4707 // Results
4708 var stringMatch = representation.match(PARSE_STRING_REGEXP);
4709 var infMatch = representation.match(PARSE_INF_REGEXP);
4710 var nanMatch = representation.match(PARSE_NAN_REGEXP);
4711 // Validate the string
4712 if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) {
4713 throw new TypeError('' + representation + ' not a valid Decimal128 string');
4714 }
4715 if (stringMatch) {
4716 // full_match = stringMatch[0]
4717 // sign = stringMatch[1]
4718 var unsignedNumber = stringMatch[2];
4719 // stringMatch[3] is undefined if a whole number (ex "1", 12")
4720 // but defined if a number w/ decimal in it (ex "1.0, 12.2")
4721 var e = stringMatch[4];
4722 var expSign = stringMatch[5];
4723 var expNumber = stringMatch[6];
4724 // they provided e, but didn't give an exponent number. for ex "1e"
4725 if (e && expNumber === undefined)
4726 invalidErr(representation, 'missing exponent power');
4727 // they provided e, but didn't give a number before it. for ex "e1"
4728 if (e && unsignedNumber === undefined)
4729 invalidErr(representation, 'missing exponent base');
4730 if (e === undefined && (expSign || expNumber)) {
4731 invalidErr(representation, 'missing e before exponent');
4732 }
4733 }
4734 // Get the negative or positive sign
4735 if (representation[index] === '+' || representation[index] === '-') {
4736 isNegative = representation[index++] === '-';
4737 }
4738 // Check if user passed Infinity or NaN
4739 if (!isDigit(representation[index]) && representation[index] !== '.') {
4740 if (representation[index] === 'i' || representation[index] === 'I') {
4741 return new Decimal128(buffer.Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER));
4742 }
4743 else if (representation[index] === 'N') {
4744 return new Decimal128(buffer.Buffer.from(NAN_BUFFER));
4745 }
4746 }
4747 // Read all the digits
4748 while (isDigit(representation[index]) || representation[index] === '.') {
4749 if (representation[index] === '.') {
4750 if (sawRadix)
4751 invalidErr(representation, 'contains multiple periods');
4752 sawRadix = true;
4753 index = index + 1;
4754 continue;
4755 }
4756 if (nDigitsStored < 34) {
4757 if (representation[index] !== '0' || foundNonZero) {
4758 if (!foundNonZero) {
4759 firstNonZero = nDigitsRead;
4760 }
4761 foundNonZero = true;
4762 // Only store 34 digits
4763 digits[digitsInsert++] = parseInt(representation[index], 10);
4764 nDigitsStored = nDigitsStored + 1;
4765 }
4766 }
4767 if (foundNonZero)
4768 nDigits = nDigits + 1;
4769 if (sawRadix)
4770 radixPosition = radixPosition + 1;
4771 nDigitsRead = nDigitsRead + 1;
4772 index = index + 1;
4773 }
4774 if (sawRadix && !nDigitsRead)
4775 throw new TypeError('' + representation + ' not a valid Decimal128 string');
4776 // Read exponent if exists
4777 if (representation[index] === 'e' || representation[index] === 'E') {
4778 // Read exponent digits
4779 var match = representation.substr(++index).match(EXPONENT_REGEX);
4780 // No digits read
4781 if (!match || !match[2])
4782 return new Decimal128(buffer.Buffer.from(NAN_BUFFER));
4783 // Get exponent
4784 exponent = parseInt(match[0], 10);
4785 // Adjust the index
4786 index = index + match[0].length;
4787 }
4788 // Return not a number
4789 if (representation[index])
4790 return new Decimal128(buffer.Buffer.from(NAN_BUFFER));
4791 // Done reading input
4792 // Find first non-zero digit in digits
4793 firstDigit = 0;
4794 if (!nDigitsStored) {
4795 firstDigit = 0;
4796 lastDigit = 0;
4797 digits[0] = 0;
4798 nDigits = 1;
4799 nDigitsStored = 1;
4800 significantDigits = 0;
4801 }
4802 else {
4803 lastDigit = nDigitsStored - 1;
4804 significantDigits = nDigits;
4805 if (significantDigits !== 1) {
4806 while (representation[firstNonZero + significantDigits - 1] === '0') {
4807 significantDigits = significantDigits - 1;
4808 }
4809 }
4810 }
4811 // Normalization of exponent
4812 // Correct exponent based on radix position, and shift significand as needed
4813 // to represent user input
4814 // Overflow prevention
4815 if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) {
4816 exponent = EXPONENT_MIN;
4817 }
4818 else {
4819 exponent = exponent - radixPosition;
4820 }
4821 // Attempt to normalize the exponent
4822 while (exponent > EXPONENT_MAX) {
4823 // Shift exponent to significand and decrease
4824 lastDigit = lastDigit + 1;
4825 if (lastDigit - firstDigit > MAX_DIGITS) {
4826 // Check if we have a zero then just hard clamp, otherwise fail
4827 var digitsString = digits.join('');
4828 if (digitsString.match(/^0+$/)) {
4829 exponent = EXPONENT_MAX;
4830 break;
4831 }
4832 invalidErr(representation, 'overflow');
4833 }
4834 exponent = exponent - 1;
4835 }
4836 while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
4837 // Shift last digit. can only do this if < significant digits than # stored.
4838 if (lastDigit === 0 && significantDigits < nDigitsStored) {
4839 exponent = EXPONENT_MIN;
4840 significantDigits = 0;
4841 break;
4842 }
4843 if (nDigitsStored < nDigits) {
4844 // adjust to match digits not stored
4845 nDigits = nDigits - 1;
4846 }
4847 else {
4848 // adjust to round
4849 lastDigit = lastDigit - 1;
4850 }
4851 if (exponent < EXPONENT_MAX) {
4852 exponent = exponent + 1;
4853 }
4854 else {
4855 // Check if we have a zero then just hard clamp, otherwise fail
4856 var digitsString = digits.join('');
4857 if (digitsString.match(/^0+$/)) {
4858 exponent = EXPONENT_MAX;
4859 break;
4860 }
4861 invalidErr(representation, 'overflow');
4862 }
4863 }
4864 // Round
4865 // We've normalized the exponent, but might still need to round.
4866 if (lastDigit - firstDigit + 1 < significantDigits) {
4867 var endOfString = nDigitsRead;
4868 // If we have seen a radix point, 'string' is 1 longer than we have
4869 // documented with ndigits_read, so inc the position of the first nonzero
4870 // digit and the position that digits are read to.
4871 if (sawRadix) {
4872 firstNonZero = firstNonZero + 1;
4873 endOfString = endOfString + 1;
4874 }
4875 // if negative, we need to increment again to account for - sign at start.
4876 if (isNegative) {
4877 firstNonZero = firstNonZero + 1;
4878 endOfString = endOfString + 1;
4879 }
4880 var roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
4881 var roundBit = 0;
4882 if (roundDigit >= 5) {
4883 roundBit = 1;
4884 if (roundDigit === 5) {
4885 roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0;
4886 for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) {
4887 if (parseInt(representation[i], 10)) {
4888 roundBit = 1;
4889 break;
4890 }
4891 }
4892 }
4893 }
4894 if (roundBit) {
4895 var dIdx = lastDigit;
4896 for (; dIdx >= 0; dIdx--) {
4897 if (++digits[dIdx] > 9) {
4898 digits[dIdx] = 0;
4899 // overflowed most significant digit
4900 if (dIdx === 0) {
4901 if (exponent < EXPONENT_MAX) {
4902 exponent = exponent + 1;
4903 digits[dIdx] = 1;
4904 }
4905 else {
4906 return new Decimal128(buffer.Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER));
4907 }
4908 }
4909 }
4910 }
4911 }
4912 }
4913 // Encode significand
4914 // The high 17 digits of the significand
4915 significandHigh = long_1.Long.fromNumber(0);
4916 // The low 17 digits of the significand
4917 significandLow = long_1.Long.fromNumber(0);
4918 // read a zero
4919 if (significantDigits === 0) {
4920 significandHigh = long_1.Long.fromNumber(0);
4921 significandLow = long_1.Long.fromNumber(0);
4922 }
4923 else if (lastDigit - firstDigit < 17) {
4924 var dIdx = firstDigit;
4925 significandLow = long_1.Long.fromNumber(digits[dIdx++]);
4926 significandHigh = new long_1.Long(0, 0);
4927 for (; dIdx <= lastDigit; dIdx++) {
4928 significandLow = significandLow.multiply(long_1.Long.fromNumber(10));
4929 significandLow = significandLow.add(long_1.Long.fromNumber(digits[dIdx]));
4930 }
4931 }
4932 else {
4933 var dIdx = firstDigit;
4934 significandHigh = long_1.Long.fromNumber(digits[dIdx++]);
4935 for (; dIdx <= lastDigit - 17; dIdx++) {
4936 significandHigh = significandHigh.multiply(long_1.Long.fromNumber(10));
4937 significandHigh = significandHigh.add(long_1.Long.fromNumber(digits[dIdx]));
4938 }
4939 significandLow = long_1.Long.fromNumber(digits[dIdx++]);
4940 for (; dIdx <= lastDigit; dIdx++) {
4941 significandLow = significandLow.multiply(long_1.Long.fromNumber(10));
4942 significandLow = significandLow.add(long_1.Long.fromNumber(digits[dIdx]));
4943 }
4944 }
4945 var significand = multiply64x2(significandHigh, long_1.Long.fromString('100000000000000000'));
4946 significand.low = significand.low.add(significandLow);
4947 if (lessThan(significand.low, significandLow)) {
4948 significand.high = significand.high.add(long_1.Long.fromNumber(1));
4949 }
4950 // Biased exponent
4951 biasedExponent = exponent + EXPONENT_BIAS;
4952 var dec = { low: long_1.Long.fromNumber(0), high: long_1.Long.fromNumber(0) };
4953 // Encode combination, exponent, and significand.
4954 if (significand.high.shiftRightUnsigned(49).and(long_1.Long.fromNumber(1)).equals(long_1.Long.fromNumber(1))) {
4955 // Encode '11' into bits 1 to 3
4956 dec.high = dec.high.or(long_1.Long.fromNumber(0x3).shiftLeft(61));
4957 dec.high = dec.high.or(long_1.Long.fromNumber(biasedExponent).and(long_1.Long.fromNumber(0x3fff).shiftLeft(47)));
4958 dec.high = dec.high.or(significand.high.and(long_1.Long.fromNumber(0x7fffffffffff)));
4959 }
4960 else {
4961 dec.high = dec.high.or(long_1.Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49));
4962 dec.high = dec.high.or(significand.high.and(long_1.Long.fromNumber(0x1ffffffffffff)));
4963 }
4964 dec.low = significand.low;
4965 // Encode sign
4966 if (isNegative) {
4967 dec.high = dec.high.or(long_1.Long.fromString('9223372036854775808'));
4968 }
4969 // Encode into a buffer
4970 var buffer$1 = buffer.Buffer.alloc(16);
4971 index = 0;
4972 // Encode the low 64 bits of the decimal
4973 // Encode low bits
4974 buffer$1[index++] = dec.low.low & 0xff;
4975 buffer$1[index++] = (dec.low.low >> 8) & 0xff;
4976 buffer$1[index++] = (dec.low.low >> 16) & 0xff;
4977 buffer$1[index++] = (dec.low.low >> 24) & 0xff;
4978 // Encode high bits
4979 buffer$1[index++] = dec.low.high & 0xff;
4980 buffer$1[index++] = (dec.low.high >> 8) & 0xff;
4981 buffer$1[index++] = (dec.low.high >> 16) & 0xff;
4982 buffer$1[index++] = (dec.low.high >> 24) & 0xff;
4983 // Encode the high 64 bits of the decimal
4984 // Encode low bits
4985 buffer$1[index++] = dec.high.low & 0xff;
4986 buffer$1[index++] = (dec.high.low >> 8) & 0xff;
4987 buffer$1[index++] = (dec.high.low >> 16) & 0xff;
4988 buffer$1[index++] = (dec.high.low >> 24) & 0xff;
4989 // Encode high bits
4990 buffer$1[index++] = dec.high.high & 0xff;
4991 buffer$1[index++] = (dec.high.high >> 8) & 0xff;
4992 buffer$1[index++] = (dec.high.high >> 16) & 0xff;
4993 buffer$1[index++] = (dec.high.high >> 24) & 0xff;
4994 // Return the new Decimal128
4995 return new Decimal128(buffer$1);
4996 };
4997 /** Create a string representation of the raw Decimal128 value */
4998 Decimal128.prototype.toString = function () {
4999 // Note: bits in this routine are referred to starting at 0,
5000 // from the sign bit, towards the coefficient.
5001 // decoded biased exponent (14 bits)
5002 var biased_exponent;
5003 // the number of significand digits
5004 var significand_digits = 0;
5005 // the base-10 digits in the significand
5006 var significand = new Array(36);
5007 for (var i = 0; i < significand.length; i++)
5008 significand[i] = 0;
5009 // read pointer into significand
5010 var index = 0;
5011 // true if the number is zero
5012 var is_zero = false;
5013 // the most significant significand bits (50-46)
5014 var significand_msb;
5015 // temporary storage for significand decoding
5016 var significand128 = { parts: [0, 0, 0, 0] };
5017 // indexing variables
5018 var j, k;
5019 // Output string
5020 var string = [];
5021 // Unpack index
5022 index = 0;
5023 // Buffer reference
5024 var buffer = this.bytes;
5025 // Unpack the low 64bits into a long
5026 // bits 96 - 127
5027 var low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
5028 // bits 64 - 95
5029 var midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
5030 // Unpack the high 64bits into a long
5031 // bits 32 - 63
5032 var midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
5033 // bits 0 - 31
5034 var high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
5035 // Unpack index
5036 index = 0;
5037 // Create the state of the decimal
5038 var dec = {
5039 low: new long_1.Long(low, midl),
5040 high: new long_1.Long(midh, high)
5041 };
5042 if (dec.high.lessThan(long_1.Long.ZERO)) {
5043 string.push('-');
5044 }
5045 // Decode combination field and exponent
5046 // bits 1 - 5
5047 var combination = (high >> 26) & COMBINATION_MASK;
5048 if (combination >> 3 === 3) {
5049 // Check for 'special' values
5050 if (combination === COMBINATION_INFINITY) {
5051 return string.join('') + 'Infinity';
5052 }
5053 else if (combination === COMBINATION_NAN) {
5054 return 'NaN';
5055 }
5056 else {
5057 biased_exponent = (high >> 15) & EXPONENT_MASK;
5058 significand_msb = 0x08 + ((high >> 14) & 0x01);
5059 }
5060 }
5061 else {
5062 significand_msb = (high >> 14) & 0x07;
5063 biased_exponent = (high >> 17) & EXPONENT_MASK;
5064 }
5065 // unbiased exponent
5066 var exponent = biased_exponent - EXPONENT_BIAS;
5067 // Create string of significand digits
5068 // Convert the 114-bit binary number represented by
5069 // (significand_high, significand_low) to at most 34 decimal
5070 // digits through modulo and division.
5071 significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14);
5072 significand128.parts[1] = midh;
5073 significand128.parts[2] = midl;
5074 significand128.parts[3] = low;
5075 if (significand128.parts[0] === 0 &&
5076 significand128.parts[1] === 0 &&
5077 significand128.parts[2] === 0 &&
5078 significand128.parts[3] === 0) {
5079 is_zero = true;
5080 }
5081 else {
5082 for (k = 3; k >= 0; k--) {
5083 var least_digits = 0;
5084 // Perform the divide
5085 var result = divideu128(significand128);
5086 significand128 = result.quotient;
5087 least_digits = result.rem.low;
5088 // We now have the 9 least significant digits (in base 2).
5089 // Convert and output to string.
5090 if (!least_digits)
5091 continue;
5092 for (j = 8; j >= 0; j--) {
5093 // significand[k * 9 + j] = Math.round(least_digits % 10);
5094 significand[k * 9 + j] = least_digits % 10;
5095 // least_digits = Math.round(least_digits / 10);
5096 least_digits = Math.floor(least_digits / 10);
5097 }
5098 }
5099 }
5100 // Output format options:
5101 // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd
5102 // Regular - ddd.ddd
5103 if (is_zero) {
5104 significand_digits = 1;
5105 significand[index] = 0;
5106 }
5107 else {
5108 significand_digits = 36;
5109 while (!significand[index]) {
5110 significand_digits = significand_digits - 1;
5111 index = index + 1;
5112 }
5113 }
5114 // the exponent if scientific notation is used
5115 var scientific_exponent = significand_digits - 1 + exponent;
5116 // The scientific exponent checks are dictated by the string conversion
5117 // specification and are somewhat arbitrary cutoffs.
5118 //
5119 // We must check exponent > 0, because if this is the case, the number
5120 // has trailing zeros. However, we *cannot* output these trailing zeros,
5121 // because doing so would change the precision of the value, and would
5122 // change stored data if the string converted number is round tripped.
5123 if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
5124 // Scientific format
5125 // if there are too many significant digits, we should just be treating numbers
5126 // as + or - 0 and using the non-scientific exponent (this is for the "invalid
5127 // representation should be treated as 0/-0" spec cases in decimal128-1.json)
5128 if (significand_digits > 34) {
5129 string.push("" + 0);
5130 if (exponent > 0)
5131 string.push('E+' + exponent);
5132 else if (exponent < 0)
5133 string.push('E' + exponent);
5134 return string.join('');
5135 }
5136 string.push("" + significand[index++]);
5137 significand_digits = significand_digits - 1;
5138 if (significand_digits) {
5139 string.push('.');
5140 }
5141 for (var i = 0; i < significand_digits; i++) {
5142 string.push("" + significand[index++]);
5143 }
5144 // Exponent
5145 string.push('E');
5146 if (scientific_exponent > 0) {
5147 string.push('+' + scientific_exponent);
5148 }
5149 else {
5150 string.push("" + scientific_exponent);
5151 }
5152 }
5153 else {
5154 // Regular format with no decimal place
5155 if (exponent >= 0) {
5156 for (var i = 0; i < significand_digits; i++) {
5157 string.push("" + significand[index++]);
5158 }
5159 }
5160 else {
5161 var radix_position = significand_digits + exponent;
5162 // non-zero digits before radix
5163 if (radix_position > 0) {
5164 for (var i = 0; i < radix_position; i++) {
5165 string.push("" + significand[index++]);
5166 }
5167 }
5168 else {
5169 string.push('0');
5170 }
5171 string.push('.');
5172 // add leading zeros after radix
5173 while (radix_position++ < 0) {
5174 string.push('0');
5175 }
5176 for (var i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) {
5177 string.push("" + significand[index++]);
5178 }
5179 }
5180 }
5181 return string.join('');
5182 };
5183 Decimal128.prototype.toJSON = function () {
5184 return { $numberDecimal: this.toString() };
5185 };
5186 /** @internal */
5187 Decimal128.prototype.toExtendedJSON = function () {
5188 return { $numberDecimal: this.toString() };
5189 };
5190 /** @internal */
5191 Decimal128.fromExtendedJSON = function (doc) {
5192 return Decimal128.fromString(doc.$numberDecimal);
5193 };
5194 /** @internal */
5195 Decimal128.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
5196 return this.inspect();
5197 };
5198 Decimal128.prototype.inspect = function () {
5199 return "Decimal128.fromString(\"" + this.toString() + "\")";
5200 };
5201 return Decimal128;
5202}());
5203exports.Decimal128 = Decimal128;
5204Object.defineProperty(Decimal128.prototype, '_bsontype', { value: 'Decimal128' });
5205
5206});
5207
5208unwrapExports(decimal128);
5209var decimal128_1 = decimal128.Decimal128;
5210
5211var double_1 = createCommonjsModule(function (module, exports) {
5212Object.defineProperty(exports, "__esModule", { value: true });
5213exports.Double = void 0;
5214/**
5215 * A class representation of the BSON Double type.
5216 * @public
5217 */
5218var Double = /** @class */ (function () {
5219 /**
5220 * Create a Double type
5221 *
5222 * @param value - the number we want to represent as a double.
5223 */
5224 function Double(value) {
5225 if (!(this instanceof Double))
5226 return new Double(value);
5227 if (value instanceof Number) {
5228 value = value.valueOf();
5229 }
5230 this.value = +value;
5231 }
5232 /**
5233 * Access the number value.
5234 *
5235 * @returns returns the wrapped double number.
5236 */
5237 Double.prototype.valueOf = function () {
5238 return this.value;
5239 };
5240 /** @internal */
5241 Double.prototype.toJSON = function () {
5242 return this.value;
5243 };
5244 /** @internal */
5245 Double.prototype.toExtendedJSON = function (options) {
5246 if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) {
5247 return this.value;
5248 }
5249 // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user
5250 // explicitly provided `-0` then we need to ensure the sign makes it into the output
5251 if (Object.is(Math.sign(this.value), -0)) {
5252 return { $numberDouble: "-" + this.value.toFixed(1) };
5253 }
5254 var $numberDouble;
5255 if (Number.isInteger(this.value)) {
5256 $numberDouble = this.value.toFixed(1);
5257 if ($numberDouble.length >= 13) {
5258 $numberDouble = this.value.toExponential(13).toUpperCase();
5259 }
5260 }
5261 else {
5262 $numberDouble = this.value.toString();
5263 }
5264 return { $numberDouble: $numberDouble };
5265 };
5266 /** @internal */
5267 Double.fromExtendedJSON = function (doc, options) {
5268 var doubleValue = parseFloat(doc.$numberDouble);
5269 return options && options.relaxed ? doubleValue : new Double(doubleValue);
5270 };
5271 /** @internal */
5272 Double.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
5273 return this.inspect();
5274 };
5275 Double.prototype.inspect = function () {
5276 var eJSON = this.toExtendedJSON();
5277 return "new Double(" + eJSON.$numberDouble + ")";
5278 };
5279 return Double;
5280}());
5281exports.Double = Double;
5282Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' });
5283
5284});
5285
5286unwrapExports(double_1);
5287var double_2 = double_1.Double;
5288
5289var int_32 = createCommonjsModule(function (module, exports) {
5290Object.defineProperty(exports, "__esModule", { value: true });
5291exports.Int32 = void 0;
5292/**
5293 * A class representation of a BSON Int32 type.
5294 * @public
5295 */
5296var Int32 = /** @class */ (function () {
5297 /**
5298 * Create an Int32 type
5299 *
5300 * @param value - the number we want to represent as an int32.
5301 */
5302 function Int32(value) {
5303 if (!(this instanceof Int32))
5304 return new Int32(value);
5305 if (value instanceof Number) {
5306 value = value.valueOf();
5307 }
5308 this.value = +value;
5309 }
5310 /**
5311 * Access the number value.
5312 *
5313 * @returns returns the wrapped int32 number.
5314 */
5315 Int32.prototype.valueOf = function () {
5316 return this.value;
5317 };
5318 /** @internal */
5319 Int32.prototype.toJSON = function () {
5320 return this.value;
5321 };
5322 /** @internal */
5323 Int32.prototype.toExtendedJSON = function (options) {
5324 if (options && (options.relaxed || options.legacy))
5325 return this.value;
5326 return { $numberInt: this.value.toString() };
5327 };
5328 /** @internal */
5329 Int32.fromExtendedJSON = function (doc, options) {
5330 return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt);
5331 };
5332 /** @internal */
5333 Int32.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
5334 return this.inspect();
5335 };
5336 Int32.prototype.inspect = function () {
5337 return "new Int32(" + this.valueOf() + ")";
5338 };
5339 return Int32;
5340}());
5341exports.Int32 = Int32;
5342Object.defineProperty(Int32.prototype, '_bsontype', { value: 'Int32' });
5343
5344});
5345
5346unwrapExports(int_32);
5347var int_32_1 = int_32.Int32;
5348
5349var max_key = createCommonjsModule(function (module, exports) {
5350Object.defineProperty(exports, "__esModule", { value: true });
5351exports.MaxKey = void 0;
5352/**
5353 * A class representation of the BSON MaxKey type.
5354 * @public
5355 */
5356var MaxKey = /** @class */ (function () {
5357 function MaxKey() {
5358 if (!(this instanceof MaxKey))
5359 return new MaxKey();
5360 }
5361 /** @internal */
5362 MaxKey.prototype.toExtendedJSON = function () {
5363 return { $maxKey: 1 };
5364 };
5365 /** @internal */
5366 MaxKey.fromExtendedJSON = function () {
5367 return new MaxKey();
5368 };
5369 /** @internal */
5370 MaxKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
5371 return this.inspect();
5372 };
5373 MaxKey.prototype.inspect = function () {
5374 return 'new MaxKey()';
5375 };
5376 return MaxKey;
5377}());
5378exports.MaxKey = MaxKey;
5379Object.defineProperty(MaxKey.prototype, '_bsontype', { value: 'MaxKey' });
5380
5381});
5382
5383unwrapExports(max_key);
5384var max_key_1 = max_key.MaxKey;
5385
5386var min_key = createCommonjsModule(function (module, exports) {
5387Object.defineProperty(exports, "__esModule", { value: true });
5388exports.MinKey = void 0;
5389/**
5390 * A class representation of the BSON MinKey type.
5391 * @public
5392 */
5393var MinKey = /** @class */ (function () {
5394 function MinKey() {
5395 if (!(this instanceof MinKey))
5396 return new MinKey();
5397 }
5398 /** @internal */
5399 MinKey.prototype.toExtendedJSON = function () {
5400 return { $minKey: 1 };
5401 };
5402 /** @internal */
5403 MinKey.fromExtendedJSON = function () {
5404 return new MinKey();
5405 };
5406 /** @internal */
5407 MinKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
5408 return this.inspect();
5409 };
5410 MinKey.prototype.inspect = function () {
5411 return 'new MinKey()';
5412 };
5413 return MinKey;
5414}());
5415exports.MinKey = MinKey;
5416Object.defineProperty(MinKey.prototype, '_bsontype', { value: 'MinKey' });
5417
5418});
5419
5420unwrapExports(min_key);
5421var min_key_1 = min_key.MinKey;
5422
5423var objectid = createCommonjsModule(function (module, exports) {
5424Object.defineProperty(exports, "__esModule", { value: true });
5425exports.ObjectId = void 0;
5426
5427
5428
5429// constants
5430var PROCESS_UNIQUE = utils.randomBytes(5);
5431// Regular expression that checks for hex value
5432var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$');
5433// Precomputed hex table enables speedy hex string conversion
5434var hexTable = [];
5435for (var i_1 = 0; i_1 < 256; i_1++) {
5436 hexTable[i_1] = (i_1 <= 15 ? '0' : '') + i_1.toString(16);
5437}
5438// Lookup tables
5439var decodeLookup = [];
5440var i = 0;
5441while (i < 10)
5442 decodeLookup[0x30 + i] = i++;
5443while (i < 16)
5444 decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++;
5445var kId = Symbol('id');
5446/**
5447 * A class representation of the BSON ObjectId type.
5448 * @public
5449 */
5450var ObjectId = /** @class */ (function () {
5451 /**
5452 * Create an ObjectId type
5453 *
5454 * @param id - Can be a 24 character hex string, 12 byte binary Buffer, or a number.
5455 */
5456 function ObjectId(id) {
5457 if (!(this instanceof ObjectId))
5458 return new ObjectId(id);
5459 // Duck-typing to support ObjectId from different npm packages
5460 if (id instanceof ObjectId) {
5461 this[kId] = id.id;
5462 this.__id = id.__id;
5463 }
5464 if (typeof id === 'object' && id && 'id' in id) {
5465 if ('toHexString' in id && typeof id.toHexString === 'function') {
5466 this[kId] = buffer.Buffer.from(id.toHexString(), 'hex');
5467 }
5468 else {
5469 this[kId] = typeof id.id === 'string' ? buffer.Buffer.from(id.id) : id.id;
5470 }
5471 }
5472 // The most common use case (blank id, new objectId instance)
5473 if (id == null || typeof id === 'number') {
5474 // Generate a new id
5475 this[kId] = ObjectId.generate(typeof id === 'number' ? id : undefined);
5476 // If we are caching the hex string
5477 if (ObjectId.cacheHexString) {
5478 this.__id = this.id.toString('hex');
5479 }
5480 }
5481 if (ArrayBuffer.isView(id) && id.byteLength === 12) {
5482 this[kId] = ensure_buffer.ensureBuffer(id);
5483 }
5484 if (typeof id === 'string') {
5485 if (id.length === 12) {
5486 var bytes = buffer.Buffer.from(id);
5487 if (bytes.byteLength === 12) {
5488 this[kId] = bytes;
5489 }
5490 }
5491 else if (id.length === 24 && checkForHexRegExp.test(id)) {
5492 this[kId] = buffer.Buffer.from(id, 'hex');
5493 }
5494 else {
5495 throw new TypeError('Argument passed in must be a Buffer or string of 12 bytes or a string of 24 hex characters');
5496 }
5497 }
5498 if (ObjectId.cacheHexString) {
5499 this.__id = this.id.toString('hex');
5500 }
5501 }
5502 Object.defineProperty(ObjectId.prototype, "id", {
5503 /**
5504 * The ObjectId bytes
5505 * @readonly
5506 */
5507 get: function () {
5508 return this[kId];
5509 },
5510 set: function (value) {
5511 this[kId] = value;
5512 if (ObjectId.cacheHexString) {
5513 this.__id = value.toString('hex');
5514 }
5515 },
5516 enumerable: false,
5517 configurable: true
5518 });
5519 Object.defineProperty(ObjectId.prototype, "generationTime", {
5520 /**
5521 * The generation time of this ObjectId instance
5522 * @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch
5523 */
5524 get: function () {
5525 return this.id.readInt32BE(0);
5526 },
5527 set: function (value) {
5528 // Encode time into first 4 bytes
5529 this.id.writeUInt32BE(value, 0);
5530 },
5531 enumerable: false,
5532 configurable: true
5533 });
5534 /** Returns the ObjectId id as a 24 character hex string representation */
5535 ObjectId.prototype.toHexString = function () {
5536 if (ObjectId.cacheHexString && this.__id) {
5537 return this.__id;
5538 }
5539 var hexString = this.id.toString('hex');
5540 if (ObjectId.cacheHexString && !this.__id) {
5541 this.__id = hexString;
5542 }
5543 return hexString;
5544 };
5545 /**
5546 * Update the ObjectId index
5547 * @privateRemarks
5548 * Used in generating new ObjectId's on the driver
5549 * @internal
5550 */
5551 ObjectId.getInc = function () {
5552 return (ObjectId.index = (ObjectId.index + 1) % 0xffffff);
5553 };
5554 /**
5555 * Generate a 12 byte id buffer used in ObjectId's
5556 *
5557 * @param time - pass in a second based timestamp.
5558 */
5559 ObjectId.generate = function (time) {
5560 if ('number' !== typeof time) {
5561 time = ~~(Date.now() / 1000);
5562 }
5563 var inc = ObjectId.getInc();
5564 var buffer$1 = buffer.Buffer.alloc(12);
5565 // 4-byte timestamp
5566 buffer$1.writeUInt32BE(time, 0);
5567 // 5-byte process unique
5568 buffer$1[4] = PROCESS_UNIQUE[0];
5569 buffer$1[5] = PROCESS_UNIQUE[1];
5570 buffer$1[6] = PROCESS_UNIQUE[2];
5571 buffer$1[7] = PROCESS_UNIQUE[3];
5572 buffer$1[8] = PROCESS_UNIQUE[4];
5573 // 3-byte counter
5574 buffer$1[11] = inc & 0xff;
5575 buffer$1[10] = (inc >> 8) & 0xff;
5576 buffer$1[9] = (inc >> 16) & 0xff;
5577 return buffer$1;
5578 };
5579 /**
5580 * Converts the id into a 24 character hex string for printing
5581 *
5582 * @param format - The Buffer toString format parameter.
5583 * @internal
5584 */
5585 ObjectId.prototype.toString = function (format) {
5586 // Is the id a buffer then use the buffer toString method to return the format
5587 if (format)
5588 return this.id.toString(format);
5589 return this.toHexString();
5590 };
5591 /**
5592 * Converts to its JSON the 24 character hex string representation.
5593 * @internal
5594 */
5595 ObjectId.prototype.toJSON = function () {
5596 return this.toHexString();
5597 };
5598 /**
5599 * Compares the equality of this ObjectId with `otherID`.
5600 *
5601 * @param otherId - ObjectId instance to compare against.
5602 */
5603 ObjectId.prototype.equals = function (otherId) {
5604 if (otherId === undefined || otherId === null) {
5605 return false;
5606 }
5607 if (otherId instanceof ObjectId) {
5608 return this.toString() === otherId.toString();
5609 }
5610 if (typeof otherId === 'string' &&
5611 ObjectId.isValid(otherId) &&
5612 otherId.length === 12 &&
5613 this.id instanceof buffer.Buffer) {
5614 return otherId === this.id.toString('binary');
5615 }
5616 if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) {
5617 return otherId.toLowerCase() === this.toHexString();
5618 }
5619 if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) {
5620 return buffer.Buffer.from(otherId).equals(this.id);
5621 }
5622 if (typeof otherId === 'object' &&
5623 'toHexString' in otherId &&
5624 typeof otherId.toHexString === 'function') {
5625 return otherId.toHexString() === this.toHexString();
5626 }
5627 return false;
5628 };
5629 /** Returns the generation date (accurate up to the second) that this ID was generated. */
5630 ObjectId.prototype.getTimestamp = function () {
5631 var timestamp = new Date();
5632 var time = this.id.readUInt32BE(0);
5633 timestamp.setTime(Math.floor(time) * 1000);
5634 return timestamp;
5635 };
5636 /** @internal */
5637 ObjectId.createPk = function () {
5638 return new ObjectId();
5639 };
5640 /**
5641 * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId.
5642 *
5643 * @param time - an integer number representing a number of seconds.
5644 */
5645 ObjectId.createFromTime = function (time) {
5646 var buffer$1 = buffer.Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
5647 // Encode time into first 4 bytes
5648 buffer$1.writeUInt32BE(time, 0);
5649 // Return the new objectId
5650 return new ObjectId(buffer$1);
5651 };
5652 /**
5653 * Creates an ObjectId from a hex string representation of an ObjectId.
5654 *
5655 * @param hexString - create a ObjectId from a passed in 24 character hexstring.
5656 */
5657 ObjectId.createFromHexString = function (hexString) {
5658 // Throw an error if it's not a valid setup
5659 if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) {
5660 throw new TypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters');
5661 }
5662 return new ObjectId(buffer.Buffer.from(hexString, 'hex'));
5663 };
5664 /**
5665 * Checks if a value is a valid bson ObjectId
5666 *
5667 * @param id - ObjectId instance to validate.
5668 */
5669 ObjectId.isValid = function (id) {
5670 if (id == null)
5671 return false;
5672 if (typeof id === 'number') {
5673 return true;
5674 }
5675 if (typeof id === 'string') {
5676 return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id));
5677 }
5678 if (id instanceof ObjectId) {
5679 return true;
5680 }
5681 if (id instanceof buffer.Buffer && id.length === 12) {
5682 return true;
5683 }
5684 // Duck-Typing detection of ObjectId like objects
5685 if (typeof id === 'object' && 'toHexString' in id && typeof id.toHexString === 'function') {
5686 if (typeof id.id === 'string') {
5687 return id.id.length === 12;
5688 }
5689 return id.toHexString().length === 24 && checkForHexRegExp.test(id.id.toString('hex'));
5690 }
5691 return false;
5692 };
5693 /** @internal */
5694 ObjectId.prototype.toExtendedJSON = function () {
5695 if (this.toHexString)
5696 return { $oid: this.toHexString() };
5697 return { $oid: this.toString('hex') };
5698 };
5699 /** @internal */
5700 ObjectId.fromExtendedJSON = function (doc) {
5701 return new ObjectId(doc.$oid);
5702 };
5703 /**
5704 * Converts to a string representation of this Id.
5705 *
5706 * @returns return the 24 character hex string representation.
5707 * @internal
5708 */
5709 ObjectId.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
5710 return this.inspect();
5711 };
5712 ObjectId.prototype.inspect = function () {
5713 return "new ObjectId(\"" + this.toHexString() + "\")";
5714 };
5715 /** @internal */
5716 ObjectId.index = ~~(Math.random() * 0xffffff);
5717 return ObjectId;
5718}());
5719exports.ObjectId = ObjectId;
5720// Deprecated methods
5721Object.defineProperty(ObjectId.prototype, 'generate', {
5722 value: utils.deprecate(function (time) { return ObjectId.generate(time); }, 'Please use the static `ObjectId.generate(time)` instead')
5723});
5724Object.defineProperty(ObjectId.prototype, 'getInc', {
5725 value: utils.deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead')
5726});
5727Object.defineProperty(ObjectId.prototype, 'get_inc', {
5728 value: utils.deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead')
5729});
5730Object.defineProperty(ObjectId, 'get_inc', {
5731 value: utils.deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead')
5732});
5733Object.defineProperty(ObjectId.prototype, '_bsontype', { value: 'ObjectID' });
5734
5735});
5736
5737unwrapExports(objectid);
5738var objectid_1 = objectid.ObjectId;
5739
5740var regexp = createCommonjsModule(function (module, exports) {
5741Object.defineProperty(exports, "__esModule", { value: true });
5742exports.BSONRegExp = void 0;
5743function alphabetize(str) {
5744 return str.split('').sort().join('');
5745}
5746/**
5747 * A class representation of the BSON RegExp type.
5748 * @public
5749 */
5750var BSONRegExp = /** @class */ (function () {
5751 /**
5752 * @param pattern - The regular expression pattern to match
5753 * @param options - The regular expression options
5754 */
5755 function BSONRegExp(pattern, options) {
5756 if (!(this instanceof BSONRegExp))
5757 return new BSONRegExp(pattern, options);
5758 this.pattern = pattern;
5759 this.options = options !== null && options !== void 0 ? options : '';
5760 // Execute
5761 alphabetize(this.options);
5762 // Validate options
5763 for (var i = 0; i < this.options.length; i++) {
5764 if (!(this.options[i] === 'i' ||
5765 this.options[i] === 'm' ||
5766 this.options[i] === 'x' ||
5767 this.options[i] === 'l' ||
5768 this.options[i] === 's' ||
5769 this.options[i] === 'u')) {
5770 throw new Error("The regular expression option [" + this.options[i] + "] is not supported");
5771 }
5772 }
5773 }
5774 BSONRegExp.parseOptions = function (options) {
5775 return options ? options.split('').sort().join('') : '';
5776 };
5777 /** @internal */
5778 BSONRegExp.prototype.toExtendedJSON = function (options) {
5779 options = options || {};
5780 if (options.legacy) {
5781 return { $regex: this.pattern, $options: this.options };
5782 }
5783 return { $regularExpression: { pattern: this.pattern, options: this.options } };
5784 };
5785 /** @internal */
5786 BSONRegExp.fromExtendedJSON = function (doc) {
5787 if ('$regex' in doc) {
5788 if (typeof doc.$regex !== 'string') {
5789 // This is for $regex query operators that have extended json values.
5790 if (doc.$regex._bsontype === 'BSONRegExp') {
5791 return doc;
5792 }
5793 }
5794 else {
5795 return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options));
5796 }
5797 }
5798 if ('$regularExpression' in doc) {
5799 return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options));
5800 }
5801 throw new TypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc));
5802 };
5803 return BSONRegExp;
5804}());
5805exports.BSONRegExp = BSONRegExp;
5806Object.defineProperty(BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' });
5807
5808});
5809
5810unwrapExports(regexp);
5811var regexp_1 = regexp.BSONRegExp;
5812
5813var symbol = createCommonjsModule(function (module, exports) {
5814Object.defineProperty(exports, "__esModule", { value: true });
5815exports.BSONSymbol = void 0;
5816/**
5817 * A class representation of the BSON Symbol type.
5818 * @public
5819 */
5820var BSONSymbol = /** @class */ (function () {
5821 /**
5822 * @param value - the string representing the symbol.
5823 */
5824 function BSONSymbol(value) {
5825 if (!(this instanceof BSONSymbol))
5826 return new BSONSymbol(value);
5827 this.value = value;
5828 }
5829 /** Access the wrapped string value. */
5830 BSONSymbol.prototype.valueOf = function () {
5831 return this.value;
5832 };
5833 /** @internal */
5834 BSONSymbol.prototype.toString = function () {
5835 return this.value;
5836 };
5837 /** @internal */
5838 BSONSymbol.prototype.inspect = function () {
5839 return "new BSONSymbol(\"" + this.value + "\")";
5840 };
5841 /** @internal */
5842 BSONSymbol.prototype.toJSON = function () {
5843 return this.value;
5844 };
5845 /** @internal */
5846 BSONSymbol.prototype.toExtendedJSON = function () {
5847 return { $symbol: this.value };
5848 };
5849 /** @internal */
5850 BSONSymbol.fromExtendedJSON = function (doc) {
5851 return new BSONSymbol(doc.$symbol);
5852 };
5853 /** @internal */
5854 BSONSymbol.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
5855 return this.inspect();
5856 };
5857 return BSONSymbol;
5858}());
5859exports.BSONSymbol = BSONSymbol;
5860Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' });
5861
5862});
5863
5864unwrapExports(symbol);
5865var symbol_1 = symbol.BSONSymbol;
5866
5867var timestamp$1 = createCommonjsModule(function (module, exports) {
5868Object.defineProperty(exports, "__esModule", { value: true });
5869exports.Timestamp = exports.LongWithoutOverridesClass = void 0;
5870
5871
5872/** @public */
5873exports.LongWithoutOverridesClass = long_1.Long;
5874/** @public */
5875var Timestamp = /** @class */ (function (_super) {
5876 tslib_es6.__extends(Timestamp, _super);
5877 function Timestamp(low, high) {
5878 var _this = this;
5879 // eslint-disable-next-line @typescript-eslint/ban-ts-comment
5880 ///@ts-expect-error
5881 if (!(_this instanceof Timestamp))
5882 return new Timestamp(low, high);
5883 if (long_1.Long.isLong(low)) {
5884 _this = _super.call(this, low.low, low.high, true) || this;
5885 }
5886 else {
5887 _this = _super.call(this, low, high, true) || this;
5888 }
5889 Object.defineProperty(_this, '_bsontype', {
5890 value: 'Timestamp',
5891 writable: false,
5892 configurable: false,
5893 enumerable: false
5894 });
5895 return _this;
5896 }
5897 Timestamp.prototype.toJSON = function () {
5898 return {
5899 $timestamp: this.toString()
5900 };
5901 };
5902 /** Returns a Timestamp represented by the given (32-bit) integer value. */
5903 Timestamp.fromInt = function (value) {
5904 return new Timestamp(long_1.Long.fromInt(value, true));
5905 };
5906 /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */
5907 Timestamp.fromNumber = function (value) {
5908 return new Timestamp(long_1.Long.fromNumber(value, true));
5909 };
5910 /**
5911 * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits.
5912 *
5913 * @param lowBits - the low 32-bits.
5914 * @param highBits - the high 32-bits.
5915 */
5916 Timestamp.fromBits = function (lowBits, highBits) {
5917 return new Timestamp(lowBits, highBits);
5918 };
5919 /**
5920 * Returns a Timestamp from the given string, optionally using the given radix.
5921 *
5922 * @param str - the textual representation of the Timestamp.
5923 * @param optRadix - the radix in which the text is written.
5924 */
5925 Timestamp.fromString = function (str, optRadix) {
5926 return new Timestamp(long_1.Long.fromString(str, true, optRadix));
5927 };
5928 /** @internal */
5929 Timestamp.prototype.toExtendedJSON = function () {
5930 return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } };
5931 };
5932 /** @internal */
5933 Timestamp.fromExtendedJSON = function (doc) {
5934 return new Timestamp(doc.$timestamp.i, doc.$timestamp.t);
5935 };
5936 /** @internal */
5937 Timestamp.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
5938 return this.inspect();
5939 };
5940 Timestamp.prototype.inspect = function () {
5941 return "new Timestamp(" + this.getLowBits().toString() + ", " + this.getHighBits().toString() + ")";
5942 };
5943 Timestamp.MAX_VALUE = long_1.Long.MAX_UNSIGNED_VALUE;
5944 return Timestamp;
5945}(exports.LongWithoutOverridesClass));
5946exports.Timestamp = Timestamp;
5947
5948});
5949
5950unwrapExports(timestamp$1);
5951var timestamp_1 = timestamp$1.Timestamp;
5952var timestamp_2 = timestamp$1.LongWithoutOverridesClass;
5953
5954var extended_json = createCommonjsModule(function (module, exports) {
5955Object.defineProperty(exports, "__esModule", { value: true });
5956exports.EJSON = exports.isBSONType = void 0;
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971function isBSONType(value) {
5972 return (utils.isObjectLike(value) && Reflect.has(value, '_bsontype') && typeof value._bsontype === 'string');
5973}
5974exports.isBSONType = isBSONType;
5975// INT32 boundaries
5976var BSON_INT32_MAX = 0x7fffffff;
5977var BSON_INT32_MIN = -0x80000000;
5978// INT64 boundaries
5979var BSON_INT64_MAX = 0x7fffffffffffffff;
5980var BSON_INT64_MIN = -0x8000000000000000;
5981// all the types where we don't need to do any special processing and can just pass the EJSON
5982//straight to type.fromExtendedJSON
5983var keysToCodecs = {
5984 $oid: objectid.ObjectId,
5985 $binary: binary.Binary,
5986 $uuid: binary.Binary,
5987 $symbol: symbol.BSONSymbol,
5988 $numberInt: int_32.Int32,
5989 $numberDecimal: decimal128.Decimal128,
5990 $numberDouble: double_1.Double,
5991 $numberLong: long_1.Long,
5992 $minKey: min_key.MinKey,
5993 $maxKey: max_key.MaxKey,
5994 $regex: regexp.BSONRegExp,
5995 $regularExpression: regexp.BSONRegExp,
5996 $timestamp: timestamp$1.Timestamp
5997};
5998// eslint-disable-next-line @typescript-eslint/no-explicit-any
5999function deserializeValue(value, options) {
6000 if (options === void 0) { options = {}; }
6001 if (typeof value === 'number') {
6002 if (options.relaxed || options.legacy) {
6003 return value;
6004 }
6005 // if it's an integer, should interpret as smallest BSON integer
6006 // that can represent it exactly. (if out of range, interpret as double.)
6007 if (Math.floor(value) === value) {
6008 if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX)
6009 return new int_32.Int32(value);
6010 if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX)
6011 return long_1.Long.fromNumber(value);
6012 }
6013 // If the number is a non-integer or out of integer range, should interpret as BSON Double.
6014 return new double_1.Double(value);
6015 }
6016 // from here on out we're looking for bson types, so bail if its not an object
6017 if (value == null || typeof value !== 'object')
6018 return value;
6019 // upgrade deprecated undefined to null
6020 if (value.$undefined)
6021 return null;
6022 var keys = Object.keys(value).filter(function (k) { return k.startsWith('$') && value[k] != null; });
6023 for (var i = 0; i < keys.length; i++) {
6024 var c = keysToCodecs[keys[i]];
6025 if (c)
6026 return c.fromExtendedJSON(value, options);
6027 }
6028 if (value.$date != null) {
6029 var d = value.$date;
6030 var date = new Date();
6031 if (options.legacy) {
6032 if (typeof d === 'number')
6033 date.setTime(d);
6034 else if (typeof d === 'string')
6035 date.setTime(Date.parse(d));
6036 }
6037 else {
6038 if (typeof d === 'string')
6039 date.setTime(Date.parse(d));
6040 else if (long_1.Long.isLong(d))
6041 date.setTime(d.toNumber());
6042 else if (typeof d === 'number' && options.relaxed)
6043 date.setTime(d);
6044 }
6045 return date;
6046 }
6047 if (value.$code != null) {
6048 var copy = Object.assign({}, value);
6049 if (value.$scope) {
6050 copy.$scope = deserializeValue(value.$scope);
6051 }
6052 return code$1.Code.fromExtendedJSON(value);
6053 }
6054 if (value.$ref != null || value.$dbPointer != null) {
6055 var v = value.$ref ? value : value.$dbPointer;
6056 // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped)
6057 // because of the order JSON.parse goes through the document
6058 if (v instanceof db_ref.DBRef)
6059 return v;
6060 var dollarKeys = Object.keys(v).filter(function (k) { return k.startsWith('$'); });
6061 var valid_1 = true;
6062 dollarKeys.forEach(function (k) {
6063 if (['$ref', '$id', '$db'].indexOf(k) === -1)
6064 valid_1 = false;
6065 });
6066 // only make DBRef if $ keys are all valid
6067 if (valid_1)
6068 return db_ref.DBRef.fromExtendedJSON(v);
6069 }
6070 return value;
6071}
6072// eslint-disable-next-line @typescript-eslint/no-explicit-any
6073function serializeArray(array, options) {
6074 return array.map(function (v) { return serializeValue(v, options); });
6075}
6076function getISOString(date) {
6077 var isoStr = date.toISOString();
6078 // we should only show milliseconds in timestamp if they're non-zero
6079 return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z';
6080}
6081// eslint-disable-next-line @typescript-eslint/no-explicit-any
6082function serializeValue(value, options) {
6083 if (Array.isArray(value))
6084 return serializeArray(value, options);
6085 if (value === undefined)
6086 return null;
6087 if (value instanceof Date) {
6088 var dateNum = value.getTime(),
6089 // is it in year range 1970-9999?
6090 inRange = dateNum > -1 && dateNum < 253402318800000;
6091 if (options.legacy) {
6092 return options.relaxed && inRange
6093 ? { $date: value.getTime() }
6094 : { $date: getISOString(value) };
6095 }
6096 return options.relaxed && inRange
6097 ? { $date: getISOString(value) }
6098 : { $date: { $numberLong: value.getTime().toString() } };
6099 }
6100 if (typeof value === 'number' && !options.relaxed) {
6101 // it's an integer
6102 if (Math.floor(value) === value) {
6103 var int32Range = value >= BSON_INT32_MIN && value <= BSON_INT32_MAX, int64Range = value >= BSON_INT64_MIN && value <= BSON_INT64_MAX;
6104 // interpret as being of the smallest BSON integer type that can represent the number exactly
6105 if (int32Range)
6106 return { $numberInt: value.toString() };
6107 if (int64Range)
6108 return { $numberLong: value.toString() };
6109 }
6110 return { $numberDouble: value.toString() };
6111 }
6112 if (value instanceof RegExp) {
6113 var flags = value.flags;
6114 if (flags === undefined) {
6115 var match = value.toString().match(/[gimuy]*$/);
6116 if (match) {
6117 flags = match[0];
6118 }
6119 }
6120 var rx = new regexp.BSONRegExp(value.source, flags);
6121 return rx.toExtendedJSON(options);
6122 }
6123 if (value != null && typeof value === 'object')
6124 return serializeDocument(value, options);
6125 return value;
6126}
6127var BSON_TYPE_MAPPINGS = {
6128 Binary: function (o) { return new binary.Binary(o.value(), o.sub_type); },
6129 Code: function (o) { return new code$1.Code(o.code, o.scope); },
6130 DBRef: function (o) { return new db_ref.DBRef(o.collection || o.namespace, o.oid, o.db, o.fields); },
6131 Decimal128: function (o) { return new decimal128.Decimal128(o.bytes); },
6132 Double: function (o) { return new double_1.Double(o.value); },
6133 Int32: function (o) { return new int_32.Int32(o.value); },
6134 Long: function (o) {
6135 return long_1.Long.fromBits(
6136 // underscore variants for 1.x backwards compatibility
6137 o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_);
6138 },
6139 MaxKey: function () { return new max_key.MaxKey(); },
6140 MinKey: function () { return new min_key.MinKey(); },
6141 ObjectID: function (o) { return new objectid.ObjectId(o); },
6142 ObjectId: function (o) { return new objectid.ObjectId(o); },
6143 BSONRegExp: function (o) { return new regexp.BSONRegExp(o.pattern, o.options); },
6144 Symbol: function (o) { return new symbol.BSONSymbol(o.value); },
6145 Timestamp: function (o) { return timestamp$1.Timestamp.fromBits(o.low, o.high); }
6146};
6147// eslint-disable-next-line @typescript-eslint/no-explicit-any
6148function serializeDocument(doc, options) {
6149 if (doc == null || typeof doc !== 'object')
6150 throw new Error('not an object instance');
6151 var bsontype = doc._bsontype;
6152 if (typeof bsontype === 'undefined') {
6153 // It's a regular object. Recursively serialize its property values.
6154 var _doc = {};
6155 for (var name in doc) {
6156 _doc[name] = serializeValue(doc[name], options);
6157 }
6158 return _doc;
6159 }
6160 else if (isBSONType(doc)) {
6161 // the "document" is really just a BSON type object
6162 // eslint-disable-next-line @typescript-eslint/no-explicit-any
6163 var outDoc = doc;
6164 if (typeof outDoc.toExtendedJSON !== 'function') {
6165 // There's no EJSON serialization function on the object. It's probably an
6166 // object created by a previous version of this library (or another library)
6167 // that's duck-typing objects to look like they were generated by this library).
6168 // Copy the object into this library's version of that type.
6169 var mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
6170 if (!mapper) {
6171 throw new TypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
6172 }
6173 outDoc = mapper(outDoc);
6174 }
6175 // Two BSON types may have nested objects that may need to be serialized too
6176 if (bsontype === 'Code' && outDoc.scope) {
6177 outDoc = new code$1.Code(outDoc.code, serializeValue(outDoc.scope, options));
6178 }
6179 else if (bsontype === 'DBRef' && outDoc.oid) {
6180 outDoc = new db_ref.DBRef(outDoc.collection, serializeValue(outDoc.oid, options), outDoc.db, outDoc.fields);
6181 }
6182 return outDoc.toExtendedJSON(options);
6183 }
6184 else {
6185 throw new Error('_bsontype must be a string, but was: ' + typeof bsontype);
6186 }
6187}
6188/**
6189 * EJSON parse / stringify API
6190 * @public
6191 */
6192// the namespace here is used to emulate `export * as EJSON from '...'`
6193// which as of now (sept 2020) api-extractor does not support
6194// eslint-disable-next-line @typescript-eslint/no-namespace
6195var EJSON;
6196(function (EJSON) {
6197 /**
6198 * Parse an Extended JSON string, constructing the JavaScript value or object described by that
6199 * string.
6200 *
6201 * @example
6202 * ```js
6203 * const { EJSON } = require('bson');
6204 * const text = '{ "int32": { "$numberInt": "10" } }';
6205 *
6206 * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }
6207 * console.log(EJSON.parse(text, { relaxed: false }));
6208 *
6209 * // prints { int32: 10 }
6210 * console.log(EJSON.parse(text));
6211 * ```
6212 */
6213 function parse(text, options) {
6214 var finalOptions = Object.assign({}, { relaxed: true, legacy: false }, options);
6215 // relaxed implies not strict
6216 if (typeof finalOptions.relaxed === 'boolean')
6217 finalOptions.strict = !finalOptions.relaxed;
6218 if (typeof finalOptions.strict === 'boolean')
6219 finalOptions.relaxed = !finalOptions.strict;
6220 return JSON.parse(text, function (_key, value) { return deserializeValue(value, finalOptions); });
6221 }
6222 EJSON.parse = parse;
6223 /**
6224 * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer
6225 * function is specified or optionally including only the specified properties if a replacer array
6226 * is specified.
6227 *
6228 * @param value - The value to convert to extended JSON
6229 * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string
6230 * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes.
6231 * @param options - Optional settings
6232 *
6233 * @example
6234 * ```js
6235 * const { EJSON } = require('bson');
6236 * const Int32 = require('mongodb').Int32;
6237 * const doc = { int32: new Int32(10) };
6238 *
6239 * // prints '{"int32":{"$numberInt":"10"}}'
6240 * console.log(EJSON.stringify(doc, { relaxed: false }));
6241 *
6242 * // prints '{"int32":10}'
6243 * console.log(EJSON.stringify(doc));
6244 * ```
6245 */
6246 function stringify(value,
6247 // eslint-disable-next-line @typescript-eslint/no-explicit-any
6248 replacer, space, options) {
6249 if (space != null && typeof space === 'object') {
6250 options = space;
6251 space = 0;
6252 }
6253 if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) {
6254 options = replacer;
6255 replacer = undefined;
6256 space = 0;
6257 }
6258 options = Object.assign({}, { relaxed: true, legacy: false }, options);
6259 var doc = serializeValue(value, options);
6260 return JSON.stringify(doc, replacer, space);
6261 }
6262 EJSON.stringify = stringify;
6263 /**
6264 * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.
6265 *
6266 * @param value - The object to serialize
6267 * @param options - Optional settings passed to the `stringify` function
6268 */
6269 function serialize(value, options) {
6270 options = options || {};
6271 return JSON.parse(stringify(value, options));
6272 }
6273 EJSON.serialize = serialize;
6274 /**
6275 * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types
6276 *
6277 * @param ejson - The Extended JSON object to deserialize
6278 * @param options - Optional settings passed to the parse method
6279 */
6280 function deserialize(ejson, options) {
6281 options = options || {};
6282 return parse(JSON.stringify(ejson), options);
6283 }
6284 EJSON.deserialize = deserialize;
6285})(EJSON = exports.EJSON || (exports.EJSON = {}));
6286
6287});
6288
6289unwrapExports(extended_json);
6290var extended_json_1 = extended_json.EJSON;
6291var extended_json_2 = extended_json.isBSONType;
6292
6293var map = createCommonjsModule(function (module, exports) {
6294/* eslint-disable @typescript-eslint/no-explicit-any */
6295// We have an ES6 Map available, return the native instance
6296Object.defineProperty(exports, "__esModule", { value: true });
6297exports.Map = void 0;
6298/** @public */
6299var bsonMap;
6300exports.Map = bsonMap;
6301var check = function (potentialGlobal) {
6302 // eslint-disable-next-line eqeqeq
6303 return potentialGlobal && potentialGlobal.Math == Math && potentialGlobal;
6304};
6305// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
6306function getGlobal() {
6307 // eslint-disable-next-line no-undef
6308 return (check(typeof globalThis === 'object' && globalThis) ||
6309 check(typeof window === 'object' && window) ||
6310 check(typeof self === 'object' && self) ||
6311 check(typeof commonjsGlobal === 'object' && commonjsGlobal) ||
6312 Function('return this')());
6313}
6314var bsonGlobal = getGlobal();
6315if (Object.prototype.hasOwnProperty.call(bsonGlobal, 'Map')) {
6316 exports.Map = bsonMap = bsonGlobal.Map;
6317}
6318else {
6319 // We will return a polyfill
6320 exports.Map = bsonMap = /** @class */ (function () {
6321 function Map(array) {
6322 if (array === void 0) { array = []; }
6323 this._keys = [];
6324 this._values = {};
6325 for (var i = 0; i < array.length; i++) {
6326 if (array[i] == null)
6327 continue; // skip null and undefined
6328 var entry = array[i];
6329 var key = entry[0];
6330 var value = entry[1];
6331 // Add the key to the list of keys in order
6332 this._keys.push(key);
6333 // Add the key and value to the values dictionary with a point
6334 // to the location in the ordered keys list
6335 this._values[key] = { v: value, i: this._keys.length - 1 };
6336 }
6337 }
6338 Map.prototype.clear = function () {
6339 this._keys = [];
6340 this._values = {};
6341 };
6342 Map.prototype.delete = function (key) {
6343 var value = this._values[key];
6344 if (value == null)
6345 return false;
6346 // Delete entry
6347 delete this._values[key];
6348 // Remove the key from the ordered keys list
6349 this._keys.splice(value.i, 1);
6350 return true;
6351 };
6352 Map.prototype.entries = function () {
6353 var _this = this;
6354 var index = 0;
6355 return {
6356 next: function () {
6357 var key = _this._keys[index++];
6358 return {
6359 value: key !== undefined ? [key, _this._values[key].v] : undefined,
6360 done: key !== undefined ? false : true
6361 };
6362 }
6363 };
6364 };
6365 Map.prototype.forEach = function (callback, self) {
6366 self = self || this;
6367 for (var i = 0; i < this._keys.length; i++) {
6368 var key = this._keys[i];
6369 // Call the forEach callback
6370 callback.call(self, this._values[key].v, key, self);
6371 }
6372 };
6373 Map.prototype.get = function (key) {
6374 return this._values[key] ? this._values[key].v : undefined;
6375 };
6376 Map.prototype.has = function (key) {
6377 return this._values[key] != null;
6378 };
6379 Map.prototype.keys = function () {
6380 var _this = this;
6381 var index = 0;
6382 return {
6383 next: function () {
6384 var key = _this._keys[index++];
6385 return {
6386 value: key !== undefined ? key : undefined,
6387 done: key !== undefined ? false : true
6388 };
6389 }
6390 };
6391 };
6392 Map.prototype.set = function (key, value) {
6393 if (this._values[key]) {
6394 this._values[key].v = value;
6395 return this;
6396 }
6397 // Add the key to the list of keys in order
6398 this._keys.push(key);
6399 // Add the key and value to the values dictionary with a point
6400 // to the location in the ordered keys list
6401 this._values[key] = { v: value, i: this._keys.length - 1 };
6402 return this;
6403 };
6404 Map.prototype.values = function () {
6405 var _this = this;
6406 var index = 0;
6407 return {
6408 next: function () {
6409 var key = _this._keys[index++];
6410 return {
6411 value: key !== undefined ? _this._values[key].v : undefined,
6412 done: key !== undefined ? false : true
6413 };
6414 }
6415 };
6416 };
6417 Object.defineProperty(Map.prototype, "size", {
6418 get: function () {
6419 return this._keys.length;
6420 },
6421 enumerable: false,
6422 configurable: true
6423 });
6424 return Map;
6425 }());
6426}
6427
6428});
6429
6430unwrapExports(map);
6431var map_1 = map.Map;
6432
6433var constants = createCommonjsModule(function (module, exports) {
6434Object.defineProperty(exports, "__esModule", { value: true });
6435exports.BSON_BINARY_SUBTYPE_USER_DEFINED = exports.BSON_BINARY_SUBTYPE_MD5 = exports.BSON_BINARY_SUBTYPE_UUID_NEW = exports.BSON_BINARY_SUBTYPE_UUID = exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = exports.BSON_BINARY_SUBTYPE_FUNCTION = exports.BSON_BINARY_SUBTYPE_DEFAULT = exports.BSON_DATA_MAX_KEY = exports.BSON_DATA_MIN_KEY = exports.BSON_DATA_DECIMAL128 = exports.BSON_DATA_LONG = exports.BSON_DATA_TIMESTAMP = exports.BSON_DATA_INT = exports.BSON_DATA_CODE_W_SCOPE = exports.BSON_DATA_SYMBOL = exports.BSON_DATA_CODE = exports.BSON_DATA_DBPOINTER = exports.BSON_DATA_REGEXP = exports.BSON_DATA_NULL = exports.BSON_DATA_DATE = exports.BSON_DATA_BOOLEAN = exports.BSON_DATA_OID = exports.BSON_DATA_UNDEFINED = exports.BSON_DATA_BINARY = exports.BSON_DATA_ARRAY = exports.BSON_DATA_OBJECT = exports.BSON_DATA_STRING = exports.BSON_DATA_NUMBER = exports.JS_INT_MIN = exports.JS_INT_MAX = exports.BSON_INT64_MIN = exports.BSON_INT64_MAX = exports.BSON_INT32_MIN = exports.BSON_INT32_MAX = void 0;
6436/** @internal */
6437exports.BSON_INT32_MAX = 0x7fffffff;
6438/** @internal */
6439exports.BSON_INT32_MIN = -0x80000000;
6440/** @internal */
6441exports.BSON_INT64_MAX = Math.pow(2, 63) - 1;
6442/** @internal */
6443exports.BSON_INT64_MIN = -Math.pow(2, 63);
6444/**
6445 * Any integer up to 2^53 can be precisely represented by a double.
6446 * @internal
6447 */
6448exports.JS_INT_MAX = Math.pow(2, 53);
6449/**
6450 * Any integer down to -2^53 can be precisely represented by a double.
6451 * @internal
6452 */
6453exports.JS_INT_MIN = -Math.pow(2, 53);
6454/** Number BSON Type @internal */
6455exports.BSON_DATA_NUMBER = 1;
6456/** String BSON Type @internal */
6457exports.BSON_DATA_STRING = 2;
6458/** Object BSON Type @internal */
6459exports.BSON_DATA_OBJECT = 3;
6460/** Array BSON Type @internal */
6461exports.BSON_DATA_ARRAY = 4;
6462/** Binary BSON Type @internal */
6463exports.BSON_DATA_BINARY = 5;
6464/** Binary BSON Type @internal */
6465exports.BSON_DATA_UNDEFINED = 6;
6466/** ObjectId BSON Type @internal */
6467exports.BSON_DATA_OID = 7;
6468/** Boolean BSON Type @internal */
6469exports.BSON_DATA_BOOLEAN = 8;
6470/** Date BSON Type @internal */
6471exports.BSON_DATA_DATE = 9;
6472/** null BSON Type @internal */
6473exports.BSON_DATA_NULL = 10;
6474/** RegExp BSON Type @internal */
6475exports.BSON_DATA_REGEXP = 11;
6476/** Code BSON Type @internal */
6477exports.BSON_DATA_DBPOINTER = 12;
6478/** Code BSON Type @internal */
6479exports.BSON_DATA_CODE = 13;
6480/** Symbol BSON Type @internal */
6481exports.BSON_DATA_SYMBOL = 14;
6482/** Code with Scope BSON Type @internal */
6483exports.BSON_DATA_CODE_W_SCOPE = 15;
6484/** 32 bit Integer BSON Type @internal */
6485exports.BSON_DATA_INT = 16;
6486/** Timestamp BSON Type @internal */
6487exports.BSON_DATA_TIMESTAMP = 17;
6488/** Long BSON Type @internal */
6489exports.BSON_DATA_LONG = 18;
6490/** Decimal128 BSON Type @internal */
6491exports.BSON_DATA_DECIMAL128 = 19;
6492/** MinKey BSON Type @internal */
6493exports.BSON_DATA_MIN_KEY = 0xff;
6494/** MaxKey BSON Type @internal */
6495exports.BSON_DATA_MAX_KEY = 0x7f;
6496/** Binary Default Type @internal */
6497exports.BSON_BINARY_SUBTYPE_DEFAULT = 0;
6498/** Binary Function Type @internal */
6499exports.BSON_BINARY_SUBTYPE_FUNCTION = 1;
6500/** Binary Byte Array Type @internal */
6501exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
6502/** Binary Deprecated UUID Type @deprecated Please use BSON_BINARY_SUBTYPE_UUID_NEW @internal */
6503exports.BSON_BINARY_SUBTYPE_UUID = 3;
6504/** Binary UUID Type @internal */
6505exports.BSON_BINARY_SUBTYPE_UUID_NEW = 4;
6506/** Binary MD5 Type @internal */
6507exports.BSON_BINARY_SUBTYPE_MD5 = 5;
6508/** Binary User Defined Type @internal */
6509exports.BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
6510
6511});
6512
6513unwrapExports(constants);
6514var constants_1 = constants.BSON_BINARY_SUBTYPE_USER_DEFINED;
6515var constants_2 = constants.BSON_BINARY_SUBTYPE_MD5;
6516var constants_3 = constants.BSON_BINARY_SUBTYPE_UUID_NEW;
6517var constants_4 = constants.BSON_BINARY_SUBTYPE_UUID;
6518var constants_5 = constants.BSON_BINARY_SUBTYPE_BYTE_ARRAY;
6519var constants_6 = constants.BSON_BINARY_SUBTYPE_FUNCTION;
6520var constants_7 = constants.BSON_BINARY_SUBTYPE_DEFAULT;
6521var constants_8 = constants.BSON_DATA_MAX_KEY;
6522var constants_9 = constants.BSON_DATA_MIN_KEY;
6523var constants_10 = constants.BSON_DATA_DECIMAL128;
6524var constants_11 = constants.BSON_DATA_LONG;
6525var constants_12 = constants.BSON_DATA_TIMESTAMP;
6526var constants_13 = constants.BSON_DATA_INT;
6527var constants_14 = constants.BSON_DATA_CODE_W_SCOPE;
6528var constants_15 = constants.BSON_DATA_SYMBOL;
6529var constants_16 = constants.BSON_DATA_CODE;
6530var constants_17 = constants.BSON_DATA_DBPOINTER;
6531var constants_18 = constants.BSON_DATA_REGEXP;
6532var constants_19 = constants.BSON_DATA_NULL;
6533var constants_20 = constants.BSON_DATA_DATE;
6534var constants_21 = constants.BSON_DATA_BOOLEAN;
6535var constants_22 = constants.BSON_DATA_OID;
6536var constants_23 = constants.BSON_DATA_UNDEFINED;
6537var constants_24 = constants.BSON_DATA_BINARY;
6538var constants_25 = constants.BSON_DATA_ARRAY;
6539var constants_26 = constants.BSON_DATA_OBJECT;
6540var constants_27 = constants.BSON_DATA_STRING;
6541var constants_28 = constants.BSON_DATA_NUMBER;
6542var constants_29 = constants.JS_INT_MIN;
6543var constants_30 = constants.JS_INT_MAX;
6544var constants_31 = constants.BSON_INT64_MIN;
6545var constants_32 = constants.BSON_INT64_MAX;
6546var constants_33 = constants.BSON_INT32_MIN;
6547var constants_34 = constants.BSON_INT32_MAX;
6548
6549var calculate_size = createCommonjsModule(function (module, exports) {
6550Object.defineProperty(exports, "__esModule", { value: true });
6551exports.calculateObjectSize = void 0;
6552
6553
6554
6555
6556function calculateObjectSize(object, serializeFunctions, ignoreUndefined) {
6557 var totalLength = 4 + 1;
6558 if (Array.isArray(object)) {
6559 for (var i = 0; i < object.length; i++) {
6560 totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined);
6561 }
6562 }
6563 else {
6564 // If we have toBSON defined, override the current object
6565 if (object.toBSON) {
6566 object = object.toBSON();
6567 }
6568 // Calculate size
6569 for (var key in object) {
6570 totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined);
6571 }
6572 }
6573 return totalLength;
6574}
6575exports.calculateObjectSize = calculateObjectSize;
6576/** @internal */
6577function calculateElement(name,
6578// eslint-disable-next-line @typescript-eslint/no-explicit-any
6579value, serializeFunctions, isArray, ignoreUndefined) {
6580 if (serializeFunctions === void 0) { serializeFunctions = false; }
6581 if (isArray === void 0) { isArray = false; }
6582 if (ignoreUndefined === void 0) { ignoreUndefined = false; }
6583 // If we have toBSON defined, override the current object
6584 if (value && value.toBSON) {
6585 value = value.toBSON();
6586 }
6587 switch (typeof value) {
6588 case 'string':
6589 return 1 + buffer.Buffer.byteLength(name, 'utf8') + 1 + 4 + buffer.Buffer.byteLength(value, 'utf8') + 1;
6590 case 'number':
6591 if (Math.floor(value) === value &&
6592 value >= constants.JS_INT_MIN &&
6593 value <= constants.JS_INT_MAX) {
6594 if (value >= constants.BSON_INT32_MIN && value <= constants.BSON_INT32_MAX) {
6595 // 32 bit
6596 return (name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1);
6597 }
6598 else {
6599 return (name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
6600 }
6601 }
6602 else {
6603 // 64 bit
6604 return (name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
6605 }
6606 case 'undefined':
6607 if (isArray || !ignoreUndefined)
6608 return (name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + 1;
6609 return 0;
6610 case 'boolean':
6611 return (name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1);
6612 case 'object':
6613 if (value == null || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
6614 return (name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + 1;
6615 }
6616 else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') {
6617 return (name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1);
6618 }
6619 else if (value instanceof Date || utils.isDate(value)) {
6620 return (name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
6621 }
6622 else if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {
6623 return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.byteLength);
6624 }
6625 else if (value['_bsontype'] === 'Long' ||
6626 value['_bsontype'] === 'Double' ||
6627 value['_bsontype'] === 'Timestamp') {
6628 return (name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
6629 }
6630 else if (value['_bsontype'] === 'Decimal128') {
6631 return (name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1);
6632 }
6633 else if (value['_bsontype'] === 'Code') {
6634 // Calculate size depending on the availability of a scope
6635 if (value.scope != null && Object.keys(value.scope).length > 0) {
6636 return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) +
6637 1 +
6638 4 +
6639 4 +
6640 buffer.Buffer.byteLength(value.code.toString(), 'utf8') +
6641 1 +
6642 calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined));
6643 }
6644 else {
6645 return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) +
6646 1 +
6647 4 +
6648 buffer.Buffer.byteLength(value.code.toString(), 'utf8') +
6649 1);
6650 }
6651 }
6652 else if (value['_bsontype'] === 'Binary') {
6653 // Check what kind of subtype we have
6654 if (value.sub_type === binary.Binary.SUBTYPE_BYTE_ARRAY) {
6655 return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) +
6656 (value.position + 1 + 4 + 1 + 4));
6657 }
6658 else {
6659 return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1));
6660 }
6661 }
6662 else if (value['_bsontype'] === 'Symbol') {
6663 return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) +
6664 buffer.Buffer.byteLength(value.value, 'utf8') +
6665 4 +
6666 1 +
6667 1);
6668 }
6669 else if (value['_bsontype'] === 'DBRef') {
6670 // Set up correct object for serialization
6671 var ordered_values = Object.assign({
6672 $ref: value.collection,
6673 $id: value.oid
6674 }, value.fields);
6675 // Add db reference if it exists
6676 if (value.db != null) {
6677 ordered_values['$db'] = value.db;
6678 }
6679 return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) +
6680 1 +
6681 calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined));
6682 }
6683 else if (value instanceof RegExp ||
6684 Object.prototype.toString.call(value) === '[object RegExp]') {
6685 return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) +
6686 1 +
6687 buffer.Buffer.byteLength(value.source, 'utf8') +
6688 1 +
6689 (value.global ? 1 : 0) +
6690 (value.ignoreCase ? 1 : 0) +
6691 (value.multiline ? 1 : 0) +
6692 1);
6693 }
6694 else if (value['_bsontype'] === 'BSONRegExp') {
6695 return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) +
6696 1 +
6697 buffer.Buffer.byteLength(value.pattern, 'utf8') +
6698 1 +
6699 buffer.Buffer.byteLength(value.options, 'utf8') +
6700 1);
6701 }
6702 else {
6703 return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) +
6704 calculateObjectSize(value, serializeFunctions, ignoreUndefined) +
6705 1);
6706 }
6707 case 'function':
6708 // WTF for 0.4.X where typeof /someregexp/ === 'function'
6709 if (value instanceof RegExp ||
6710 Object.prototype.toString.call(value) === '[object RegExp]' ||
6711 String.call(value) === '[object RegExp]') {
6712 return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) +
6713 1 +
6714 buffer.Buffer.byteLength(value.source, 'utf8') +
6715 1 +
6716 (value.global ? 1 : 0) +
6717 (value.ignoreCase ? 1 : 0) +
6718 (value.multiline ? 1 : 0) +
6719 1);
6720 }
6721 else {
6722 if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) {
6723 return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) +
6724 1 +
6725 4 +
6726 4 +
6727 buffer.Buffer.byteLength(utils.normalizedFunctionString(value), 'utf8') +
6728 1 +
6729 calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined));
6730 }
6731 else if (serializeFunctions) {
6732 return ((name != null ? buffer.Buffer.byteLength(name, 'utf8') + 1 : 0) +
6733 1 +
6734 4 +
6735 buffer.Buffer.byteLength(utils.normalizedFunctionString(value), 'utf8') +
6736 1);
6737 }
6738 }
6739 }
6740 return 0;
6741}
6742
6743});
6744
6745unwrapExports(calculate_size);
6746var calculate_size_1 = calculate_size.calculateObjectSize;
6747
6748var validate_utf8 = createCommonjsModule(function (module, exports) {
6749Object.defineProperty(exports, "__esModule", { value: true });
6750exports.validateUtf8 = void 0;
6751var FIRST_BIT = 0x80;
6752var FIRST_TWO_BITS = 0xc0;
6753var FIRST_THREE_BITS = 0xe0;
6754var FIRST_FOUR_BITS = 0xf0;
6755var FIRST_FIVE_BITS = 0xf8;
6756var TWO_BIT_CHAR = 0xc0;
6757var THREE_BIT_CHAR = 0xe0;
6758var FOUR_BIT_CHAR = 0xf0;
6759var CONTINUING_CHAR = 0x80;
6760/**
6761 * Determines if the passed in bytes are valid utf8
6762 * @param bytes - An array of 8-bit bytes. Must be indexable and have length property
6763 * @param start - The index to start validating
6764 * @param end - The index to end validating
6765 */
6766function validateUtf8(bytes, start, end) {
6767 var continuation = 0;
6768 for (var i = start; i < end; i += 1) {
6769 var byte = bytes[i];
6770 if (continuation) {
6771 if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) {
6772 return false;
6773 }
6774 continuation -= 1;
6775 }
6776 else if (byte & FIRST_BIT) {
6777 if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) {
6778 continuation = 1;
6779 }
6780 else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) {
6781 continuation = 2;
6782 }
6783 else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) {
6784 continuation = 3;
6785 }
6786 else {
6787 return false;
6788 }
6789 }
6790 }
6791 return !continuation;
6792}
6793exports.validateUtf8 = validateUtf8;
6794
6795});
6796
6797unwrapExports(validate_utf8);
6798var validate_utf8_1 = validate_utf8.validateUtf8;
6799
6800var deserializer = createCommonjsModule(function (module, exports) {
6801Object.defineProperty(exports, "__esModule", { value: true });
6802exports.deserialize = void 0;
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819// Internal long versions
6820var JS_INT_MAX_LONG = long_1.Long.fromNumber(constants.JS_INT_MAX);
6821var JS_INT_MIN_LONG = long_1.Long.fromNumber(constants.JS_INT_MIN);
6822var functionCache = {};
6823function deserialize(buffer, options, isArray) {
6824 options = options == null ? {} : options;
6825 var index = options && options.index ? options.index : 0;
6826 // Read the document size
6827 var size = buffer[index] |
6828 (buffer[index + 1] << 8) |
6829 (buffer[index + 2] << 16) |
6830 (buffer[index + 3] << 24);
6831 if (size < 5) {
6832 throw new Error("bson size must be >= 5, is " + size);
6833 }
6834 if (options.allowObjectSmallerThanBufferSize && buffer.length < size) {
6835 throw new Error("buffer length " + buffer.length + " must be >= bson size " + size);
6836 }
6837 if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) {
6838 throw new Error("buffer length " + buffer.length + " must === bson size " + size);
6839 }
6840 if (size + index > buffer.byteLength) {
6841 throw new Error("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")");
6842 }
6843 // Illegal end value
6844 if (buffer[index + size - 1] !== 0) {
6845 throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
6846 }
6847 // Start deserializtion
6848 return deserializeObject(buffer, index, options, isArray);
6849}
6850exports.deserialize = deserialize;
6851function deserializeObject(buffer$1, index, options, isArray) {
6852 if (isArray === void 0) { isArray = false; }
6853 var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions'];
6854 var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions'];
6855 var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw'];
6856 // Return raw bson buffer instead of parsing it
6857 var raw = options['raw'] == null ? false : options['raw'];
6858 // Return BSONRegExp objects instead of native regular expressions
6859 var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false;
6860 // Controls the promotion of values vs wrapper classes
6861 var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers'];
6862 var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs'];
6863 var promoteValues = options['promoteValues'] == null ? true : options['promoteValues'];
6864 // Set the start index
6865 var startIndex = index;
6866 // Validate that we have at least 4 bytes of buffer
6867 if (buffer$1.length < 5)
6868 throw new Error('corrupt bson message < 5 bytes long');
6869 // Read the document size
6870 var size = buffer$1[index++] | (buffer$1[index++] << 8) | (buffer$1[index++] << 16) | (buffer$1[index++] << 24);
6871 // Ensure buffer is valid size
6872 if (size < 5 || size > buffer$1.length)
6873 throw new Error('corrupt bson message');
6874 // Create holding object
6875 var object = isArray ? [] : {};
6876 // Used for arrays to skip having to perform utf8 decoding
6877 var arrayIndex = 0;
6878 var done = false;
6879 // While we have more left data left keep parsing
6880 while (!done) {
6881 // Read the type
6882 var elementType = buffer$1[index++];
6883 // If we get a zero it's the last byte, exit
6884 if (elementType === 0)
6885 break;
6886 // Get the start search index
6887 var i = index;
6888 // Locate the end of the c string
6889 while (buffer$1[i] !== 0x00 && i < buffer$1.length) {
6890 i++;
6891 }
6892 // If are at the end of the buffer there is a problem with the document
6893 if (i >= buffer$1.byteLength)
6894 throw new Error('Bad BSON Document: illegal CString');
6895 var name = isArray ? arrayIndex++ : buffer$1.toString('utf8', index, i);
6896 index = i + 1;
6897 if (elementType === constants.BSON_DATA_STRING) {
6898 var stringSize = buffer$1[index++] |
6899 (buffer$1[index++] << 8) |
6900 (buffer$1[index++] << 16) |
6901 (buffer$1[index++] << 24);
6902 if (stringSize <= 0 ||
6903 stringSize > buffer$1.length - index ||
6904 buffer$1[index + stringSize - 1] !== 0)
6905 throw new Error('bad string length in bson');
6906 if (!validate_utf8.validateUtf8(buffer$1, index, index + stringSize - 1)) {
6907 throw new Error('Invalid UTF-8 string in BSON document');
6908 }
6909 var s = buffer$1.toString('utf8', index, index + stringSize - 1);
6910 object[name] = s;
6911 index = index + stringSize;
6912 }
6913 else if (elementType === constants.BSON_DATA_OID) {
6914 var oid = buffer.Buffer.alloc(12);
6915 buffer$1.copy(oid, 0, index, index + 12);
6916 object[name] = new objectid.ObjectId(oid);
6917 index = index + 12;
6918 }
6919 else if (elementType === constants.BSON_DATA_INT && promoteValues === false) {
6920 object[name] = new int_32.Int32(buffer$1[index++] | (buffer$1[index++] << 8) | (buffer$1[index++] << 16) | (buffer$1[index++] << 24));
6921 }
6922 else if (elementType === constants.BSON_DATA_INT) {
6923 object[name] =
6924 buffer$1[index++] |
6925 (buffer$1[index++] << 8) |
6926 (buffer$1[index++] << 16) |
6927 (buffer$1[index++] << 24);
6928 }
6929 else if (elementType === constants.BSON_DATA_NUMBER && promoteValues === false) {
6930 object[name] = new double_1.Double(buffer$1.readDoubleLE(index));
6931 index = index + 8;
6932 }
6933 else if (elementType === constants.BSON_DATA_NUMBER) {
6934 object[name] = buffer$1.readDoubleLE(index);
6935 index = index + 8;
6936 }
6937 else if (elementType === constants.BSON_DATA_DATE) {
6938 var lowBits = buffer$1[index++] |
6939 (buffer$1[index++] << 8) |
6940 (buffer$1[index++] << 16) |
6941 (buffer$1[index++] << 24);
6942 var highBits = buffer$1[index++] |
6943 (buffer$1[index++] << 8) |
6944 (buffer$1[index++] << 16) |
6945 (buffer$1[index++] << 24);
6946 object[name] = new Date(new long_1.Long(lowBits, highBits).toNumber());
6947 }
6948 else if (elementType === constants.BSON_DATA_BOOLEAN) {
6949 if (buffer$1[index] !== 0 && buffer$1[index] !== 1)
6950 throw new Error('illegal boolean type value');
6951 object[name] = buffer$1[index++] === 1;
6952 }
6953 else if (elementType === constants.BSON_DATA_OBJECT) {
6954 var _index = index;
6955 var objectSize = buffer$1[index] |
6956 (buffer$1[index + 1] << 8) |
6957 (buffer$1[index + 2] << 16) |
6958 (buffer$1[index + 3] << 24);
6959 if (objectSize <= 0 || objectSize > buffer$1.length - index)
6960 throw new Error('bad embedded document length in bson');
6961 // We have a raw value
6962 if (raw) {
6963 object[name] = buffer$1.slice(index, index + objectSize);
6964 }
6965 else {
6966 object[name] = deserializeObject(buffer$1, _index, options, false);
6967 }
6968 index = index + objectSize;
6969 }
6970 else if (elementType === constants.BSON_DATA_ARRAY) {
6971 var _index = index;
6972 var objectSize = buffer$1[index] |
6973 (buffer$1[index + 1] << 8) |
6974 (buffer$1[index + 2] << 16) |
6975 (buffer$1[index + 3] << 24);
6976 var arrayOptions = options;
6977 // Stop index
6978 var stopIndex = index + objectSize;
6979 // All elements of array to be returned as raw bson
6980 if (fieldsAsRaw && fieldsAsRaw[name]) {
6981 arrayOptions = {};
6982 for (var n in options) {
6983 arrayOptions[n] = options[n];
6984 }
6985 arrayOptions['raw'] = true;
6986 }
6987 object[name] = deserializeObject(buffer$1, _index, arrayOptions, true);
6988 index = index + objectSize;
6989 if (buffer$1[index - 1] !== 0)
6990 throw new Error('invalid array terminator byte');
6991 if (index !== stopIndex)
6992 throw new Error('corrupted array bson');
6993 }
6994 else if (elementType === constants.BSON_DATA_UNDEFINED) {
6995 object[name] = undefined;
6996 }
6997 else if (elementType === constants.BSON_DATA_NULL) {
6998 object[name] = null;
6999 }
7000 else if (elementType === constants.BSON_DATA_LONG) {
7001 // Unpack the low and high bits
7002 var lowBits = buffer$1[index++] |
7003 (buffer$1[index++] << 8) |
7004 (buffer$1[index++] << 16) |
7005 (buffer$1[index++] << 24);
7006 var highBits = buffer$1[index++] |
7007 (buffer$1[index++] << 8) |
7008 (buffer$1[index++] << 16) |
7009 (buffer$1[index++] << 24);
7010 var long = new long_1.Long(lowBits, highBits);
7011 // Promote the long if possible
7012 if (promoteLongs && promoteValues === true) {
7013 object[name] =
7014 long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG)
7015 ? long.toNumber()
7016 : long;
7017 }
7018 else {
7019 object[name] = long;
7020 }
7021 }
7022 else if (elementType === constants.BSON_DATA_DECIMAL128) {
7023 // Buffer to contain the decimal bytes
7024 var bytes = buffer.Buffer.alloc(16);
7025 // Copy the next 16 bytes into the bytes buffer
7026 buffer$1.copy(bytes, 0, index, index + 16);
7027 // Update index
7028 index = index + 16;
7029 // Assign the new Decimal128 value
7030 var decimal128$1 = new decimal128.Decimal128(bytes);
7031 // If we have an alternative mapper use that
7032 if ('toObject' in decimal128$1 && typeof decimal128$1.toObject === 'function') {
7033 object[name] = decimal128$1.toObject();
7034 }
7035 else {
7036 object[name] = decimal128$1;
7037 }
7038 }
7039 else if (elementType === constants.BSON_DATA_BINARY) {
7040 var binarySize = buffer$1[index++] |
7041 (buffer$1[index++] << 8) |
7042 (buffer$1[index++] << 16) |
7043 (buffer$1[index++] << 24);
7044 var totalBinarySize = binarySize;
7045 var subType = buffer$1[index++];
7046 // Did we have a negative binary size, throw
7047 if (binarySize < 0)
7048 throw new Error('Negative binary type element size found');
7049 // Is the length longer than the document
7050 if (binarySize > buffer$1.byteLength)
7051 throw new Error('Binary type size larger than document size');
7052 // Decode as raw Buffer object if options specifies it
7053 if (buffer$1['slice'] != null) {
7054 // If we have subtype 2 skip the 4 bytes for the size
7055 if (subType === binary.Binary.SUBTYPE_BYTE_ARRAY) {
7056 binarySize =
7057 buffer$1[index++] |
7058 (buffer$1[index++] << 8) |
7059 (buffer$1[index++] << 16) |
7060 (buffer$1[index++] << 24);
7061 if (binarySize < 0)
7062 throw new Error('Negative binary type element size found for subtype 0x02');
7063 if (binarySize > totalBinarySize - 4)
7064 throw new Error('Binary type with subtype 0x02 contains too long binary size');
7065 if (binarySize < totalBinarySize - 4)
7066 throw new Error('Binary type with subtype 0x02 contains too short binary size');
7067 }
7068 if (promoteBuffers && promoteValues) {
7069 object[name] = buffer$1.slice(index, index + binarySize);
7070 }
7071 else {
7072 object[name] = new binary.Binary(buffer$1.slice(index, index + binarySize), subType);
7073 }
7074 }
7075 else {
7076 var _buffer = buffer.Buffer.alloc(binarySize);
7077 // If we have subtype 2 skip the 4 bytes for the size
7078 if (subType === binary.Binary.SUBTYPE_BYTE_ARRAY) {
7079 binarySize =
7080 buffer$1[index++] |
7081 (buffer$1[index++] << 8) |
7082 (buffer$1[index++] << 16) |
7083 (buffer$1[index++] << 24);
7084 if (binarySize < 0)
7085 throw new Error('Negative binary type element size found for subtype 0x02');
7086 if (binarySize > totalBinarySize - 4)
7087 throw new Error('Binary type with subtype 0x02 contains too long binary size');
7088 if (binarySize < totalBinarySize - 4)
7089 throw new Error('Binary type with subtype 0x02 contains too short binary size');
7090 }
7091 // Copy the data
7092 for (i = 0; i < binarySize; i++) {
7093 _buffer[i] = buffer$1[index + i];
7094 }
7095 if (promoteBuffers && promoteValues) {
7096 object[name] = _buffer;
7097 }
7098 else {
7099 object[name] = new binary.Binary(_buffer, subType);
7100 }
7101 }
7102 // Update the index
7103 index = index + binarySize;
7104 }
7105 else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === false) {
7106 // Get the start search index
7107 i = index;
7108 // Locate the end of the c string
7109 while (buffer$1[i] !== 0x00 && i < buffer$1.length) {
7110 i++;
7111 }
7112 // If are at the end of the buffer there is a problem with the document
7113 if (i >= buffer$1.length)
7114 throw new Error('Bad BSON Document: illegal CString');
7115 // Return the C string
7116 var source = buffer$1.toString('utf8', index, i);
7117 // Create the regexp
7118 index = i + 1;
7119 // Get the start search index
7120 i = index;
7121 // Locate the end of the c string
7122 while (buffer$1[i] !== 0x00 && i < buffer$1.length) {
7123 i++;
7124 }
7125 // If are at the end of the buffer there is a problem with the document
7126 if (i >= buffer$1.length)
7127 throw new Error('Bad BSON Document: illegal CString');
7128 // Return the C string
7129 var regExpOptions = buffer$1.toString('utf8', index, i);
7130 index = i + 1;
7131 // For each option add the corresponding one for javascript
7132 var optionsArray = new Array(regExpOptions.length);
7133 // Parse options
7134 for (i = 0; i < regExpOptions.length; i++) {
7135 switch (regExpOptions[i]) {
7136 case 'm':
7137 optionsArray[i] = 'm';
7138 break;
7139 case 's':
7140 optionsArray[i] = 'g';
7141 break;
7142 case 'i':
7143 optionsArray[i] = 'i';
7144 break;
7145 }
7146 }
7147 object[name] = new RegExp(source, optionsArray.join(''));
7148 }
7149 else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === true) {
7150 // Get the start search index
7151 i = index;
7152 // Locate the end of the c string
7153 while (buffer$1[i] !== 0x00 && i < buffer$1.length) {
7154 i++;
7155 }
7156 // If are at the end of the buffer there is a problem with the document
7157 if (i >= buffer$1.length)
7158 throw new Error('Bad BSON Document: illegal CString');
7159 // Return the C string
7160 var source = buffer$1.toString('utf8', index, i);
7161 index = i + 1;
7162 // Get the start search index
7163 i = index;
7164 // Locate the end of the c string
7165 while (buffer$1[i] !== 0x00 && i < buffer$1.length) {
7166 i++;
7167 }
7168 // If are at the end of the buffer there is a problem with the document
7169 if (i >= buffer$1.length)
7170 throw new Error('Bad BSON Document: illegal CString');
7171 // Return the C string
7172 var regExpOptions = buffer$1.toString('utf8', index, i);
7173 index = i + 1;
7174 // Set the object
7175 object[name] = new regexp.BSONRegExp(source, regExpOptions);
7176 }
7177 else if (elementType === constants.BSON_DATA_SYMBOL) {
7178 var stringSize = buffer$1[index++] |
7179 (buffer$1[index++] << 8) |
7180 (buffer$1[index++] << 16) |
7181 (buffer$1[index++] << 24);
7182 if (stringSize <= 0 ||
7183 stringSize > buffer$1.length - index ||
7184 buffer$1[index + stringSize - 1] !== 0)
7185 throw new Error('bad string length in bson');
7186 var symbol$1 = buffer$1.toString('utf8', index, index + stringSize - 1);
7187 object[name] = promoteValues ? symbol$1 : new symbol.BSONSymbol(symbol$1);
7188 index = index + stringSize;
7189 }
7190 else if (elementType === constants.BSON_DATA_TIMESTAMP) {
7191 var lowBits = buffer$1[index++] |
7192 (buffer$1[index++] << 8) |
7193 (buffer$1[index++] << 16) |
7194 (buffer$1[index++] << 24);
7195 var highBits = buffer$1[index++] |
7196 (buffer$1[index++] << 8) |
7197 (buffer$1[index++] << 16) |
7198 (buffer$1[index++] << 24);
7199 object[name] = new timestamp$1.Timestamp(lowBits, highBits);
7200 }
7201 else if (elementType === constants.BSON_DATA_MIN_KEY) {
7202 object[name] = new min_key.MinKey();
7203 }
7204 else if (elementType === constants.BSON_DATA_MAX_KEY) {
7205 object[name] = new max_key.MaxKey();
7206 }
7207 else if (elementType === constants.BSON_DATA_CODE) {
7208 var stringSize = buffer$1[index++] |
7209 (buffer$1[index++] << 8) |
7210 (buffer$1[index++] << 16) |
7211 (buffer$1[index++] << 24);
7212 if (stringSize <= 0 ||
7213 stringSize > buffer$1.length - index ||
7214 buffer$1[index + stringSize - 1] !== 0)
7215 throw new Error('bad string length in bson');
7216 var functionString = buffer$1.toString('utf8', index, index + stringSize - 1);
7217 // If we are evaluating the functions
7218 if (evalFunctions) {
7219 // If we have cache enabled let's look for the md5 of the function in the cache
7220 if (cacheFunctions) {
7221 // Got to do this to avoid V8 deoptimizing the call due to finding eval
7222 object[name] = isolateEval(functionString, functionCache, object);
7223 }
7224 else {
7225 object[name] = isolateEval(functionString);
7226 }
7227 }
7228 else {
7229 object[name] = new code$1.Code(functionString);
7230 }
7231 // Update parse index position
7232 index = index + stringSize;
7233 }
7234 else if (elementType === constants.BSON_DATA_CODE_W_SCOPE) {
7235 var totalSize = buffer$1[index++] |
7236 (buffer$1[index++] << 8) |
7237 (buffer$1[index++] << 16) |
7238 (buffer$1[index++] << 24);
7239 // Element cannot be shorter than totalSize + stringSize + documentSize + terminator
7240 if (totalSize < 4 + 4 + 4 + 1) {
7241 throw new Error('code_w_scope total size shorter minimum expected length');
7242 }
7243 // Get the code string size
7244 var stringSize = buffer$1[index++] |
7245 (buffer$1[index++] << 8) |
7246 (buffer$1[index++] << 16) |
7247 (buffer$1[index++] << 24);
7248 // Check if we have a valid string
7249 if (stringSize <= 0 ||
7250 stringSize > buffer$1.length - index ||
7251 buffer$1[index + stringSize - 1] !== 0)
7252 throw new Error('bad string length in bson');
7253 // Javascript function
7254 var functionString = buffer$1.toString('utf8', index, index + stringSize - 1);
7255 // Update parse index position
7256 index = index + stringSize;
7257 // Parse the element
7258 var _index = index;
7259 // Decode the size of the object document
7260 var objectSize = buffer$1[index] |
7261 (buffer$1[index + 1] << 8) |
7262 (buffer$1[index + 2] << 16) |
7263 (buffer$1[index + 3] << 24);
7264 // Decode the scope object
7265 var scopeObject = deserializeObject(buffer$1, _index, options, false);
7266 // Adjust the index
7267 index = index + objectSize;
7268 // Check if field length is too short
7269 if (totalSize < 4 + 4 + objectSize + stringSize) {
7270 throw new Error('code_w_scope total size is too short, truncating scope');
7271 }
7272 // Check if totalSize field is too long
7273 if (totalSize > 4 + 4 + objectSize + stringSize) {
7274 throw new Error('code_w_scope total size is too long, clips outer document');
7275 }
7276 // If we are evaluating the functions
7277 if (evalFunctions) {
7278 // If we have cache enabled let's look for the md5 of the function in the cache
7279 if (cacheFunctions) {
7280 // Got to do this to avoid V8 deoptimizing the call due to finding eval
7281 object[name] = isolateEval(functionString, functionCache, object);
7282 }
7283 else {
7284 object[name] = isolateEval(functionString);
7285 }
7286 object[name].scope = scopeObject;
7287 }
7288 else {
7289 object[name] = new code$1.Code(functionString, scopeObject);
7290 }
7291 }
7292 else if (elementType === constants.BSON_DATA_DBPOINTER) {
7293 // Get the code string size
7294 var stringSize = buffer$1[index++] |
7295 (buffer$1[index++] << 8) |
7296 (buffer$1[index++] << 16) |
7297 (buffer$1[index++] << 24);
7298 // Check if we have a valid string
7299 if (stringSize <= 0 ||
7300 stringSize > buffer$1.length - index ||
7301 buffer$1[index + stringSize - 1] !== 0)
7302 throw new Error('bad string length in bson');
7303 // Namespace
7304 if (!validate_utf8.validateUtf8(buffer$1, index, index + stringSize - 1)) {
7305 throw new Error('Invalid UTF-8 string in BSON document');
7306 }
7307 var namespace = buffer$1.toString('utf8', index, index + stringSize - 1);
7308 // Update parse index position
7309 index = index + stringSize;
7310 // Read the oid
7311 var oidBuffer = buffer.Buffer.alloc(12);
7312 buffer$1.copy(oidBuffer, 0, index, index + 12);
7313 var oid = new objectid.ObjectId(oidBuffer);
7314 // Update the index
7315 index = index + 12;
7316 // Upgrade to DBRef type
7317 object[name] = new db_ref.DBRef(namespace, oid);
7318 }
7319 else {
7320 throw new Error('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"');
7321 }
7322 }
7323 // Check if the deserialization was against a valid array/object
7324 if (size !== index - startIndex) {
7325 if (isArray)
7326 throw new Error('corrupt array bson');
7327 throw new Error('corrupt object bson');
7328 }
7329 // check if object's $ keys are those of a DBRef
7330 var dollarKeys = Object.keys(object).filter(function (k) { return k.startsWith('$'); });
7331 var valid = true;
7332 dollarKeys.forEach(function (k) {
7333 if (['$ref', '$id', '$db'].indexOf(k) === -1)
7334 valid = false;
7335 });
7336 // if a $key not in "$ref", "$id", "$db", don't make a DBRef
7337 if (!valid)
7338 return object;
7339 if (db_ref.isDBRefLike(object)) {
7340 var copy = Object.assign({}, object);
7341 delete copy.$ref;
7342 delete copy.$id;
7343 delete copy.$db;
7344 return new db_ref.DBRef(object.$ref, object.$id, object.$db, copy);
7345 }
7346 return object;
7347}
7348/**
7349 * Ensure eval is isolated, store the result in functionCache.
7350 *
7351 * @internal
7352 */
7353function isolateEval(functionString, functionCache, object) {
7354 if (!functionCache)
7355 return new Function(functionString);
7356 // Check for cache hit, eval if missing and return cached function
7357 if (functionCache[functionString] == null) {
7358 functionCache[functionString] = new Function(functionString);
7359 }
7360 // Set the object
7361 return functionCache[functionString].bind(object);
7362}
7363
7364});
7365
7366unwrapExports(deserializer);
7367var deserializer_1 = deserializer.deserialize;
7368
7369var float_parser = createCommonjsModule(function (module, exports) {
7370// Copyright (c) 2008, Fair Oaks Labs, Inc.
7371// All rights reserved.
7372//
7373// Redistribution and use in source and binary forms, with or without
7374// modification, are permitted provided that the following conditions are met:
7375//
7376// * Redistributions of source code must retain the above copyright notice,
7377// this list of conditions and the following disclaimer.
7378//
7379// * Redistributions in binary form must reproduce the above copyright notice,
7380// this list of conditions and the following disclaimer in the documentation
7381// and/or other materials provided with the distribution.
7382//
7383// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors
7384// may be used to endorse or promote products derived from this software
7385// without specific prior written permission.
7386//
7387// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
7388// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
7389// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
7390// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
7391// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
7392// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
7393// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
7394// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
7395// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
7396// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
7397// POSSIBILITY OF SUCH DAMAGE.
7398//
7399//
7400// Modifications to writeIEEE754 to support negative zeroes made by Brian White
7401Object.defineProperty(exports, "__esModule", { value: true });
7402exports.writeIEEE754 = exports.readIEEE754 = void 0;
7403function readIEEE754(buffer, offset, endian, mLen, nBytes) {
7404 var e;
7405 var m;
7406 var bBE = endian === 'big';
7407 var eLen = nBytes * 8 - mLen - 1;
7408 var eMax = (1 << eLen) - 1;
7409 var eBias = eMax >> 1;
7410 var nBits = -7;
7411 var i = bBE ? 0 : nBytes - 1;
7412 var d = bBE ? 1 : -1;
7413 var s = buffer[offset + i];
7414 i += d;
7415 e = s & ((1 << -nBits) - 1);
7416 s >>= -nBits;
7417 nBits += eLen;
7418 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8)
7419 ;
7420 m = e & ((1 << -nBits) - 1);
7421 e >>= -nBits;
7422 nBits += mLen;
7423 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8)
7424 ;
7425 if (e === 0) {
7426 e = 1 - eBias;
7427 }
7428 else if (e === eMax) {
7429 return m ? NaN : (s ? -1 : 1) * Infinity;
7430 }
7431 else {
7432 m = m + Math.pow(2, mLen);
7433 e = e - eBias;
7434 }
7435 return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
7436}
7437exports.readIEEE754 = readIEEE754;
7438function writeIEEE754(buffer, value, offset, endian, mLen, nBytes) {
7439 var e;
7440 var m;
7441 var c;
7442 var bBE = endian === 'big';
7443 var eLen = nBytes * 8 - mLen - 1;
7444 var eMax = (1 << eLen) - 1;
7445 var eBias = eMax >> 1;
7446 var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
7447 var i = bBE ? nBytes - 1 : 0;
7448 var d = bBE ? -1 : 1;
7449 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
7450 value = Math.abs(value);
7451 if (isNaN(value) || value === Infinity) {
7452 m = isNaN(value) ? 1 : 0;
7453 e = eMax;
7454 }
7455 else {
7456 e = Math.floor(Math.log(value) / Math.LN2);
7457 if (value * (c = Math.pow(2, -e)) < 1) {
7458 e--;
7459 c *= 2;
7460 }
7461 if (e + eBias >= 1) {
7462 value += rt / c;
7463 }
7464 else {
7465 value += rt * Math.pow(2, 1 - eBias);
7466 }
7467 if (value * c >= 2) {
7468 e++;
7469 c /= 2;
7470 }
7471 if (e + eBias >= eMax) {
7472 m = 0;
7473 e = eMax;
7474 }
7475 else if (e + eBias >= 1) {
7476 m = (value * c - 1) * Math.pow(2, mLen);
7477 e = e + eBias;
7478 }
7479 else {
7480 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
7481 e = 0;
7482 }
7483 }
7484 if (isNaN(value))
7485 m = 0;
7486 while (mLen >= 8) {
7487 buffer[offset + i] = m & 0xff;
7488 i += d;
7489 m /= 256;
7490 mLen -= 8;
7491 }
7492 e = (e << mLen) | m;
7493 if (isNaN(value))
7494 e += 8;
7495 eLen += mLen;
7496 while (eLen > 0) {
7497 buffer[offset + i] = e & 0xff;
7498 i += d;
7499 e /= 256;
7500 eLen -= 8;
7501 }
7502 buffer[offset + i - d] |= s * 128;
7503}
7504exports.writeIEEE754 = writeIEEE754;
7505
7506});
7507
7508unwrapExports(float_parser);
7509var float_parser_1 = float_parser.writeIEEE754;
7510var float_parser_2 = float_parser.readIEEE754;
7511
7512var serializer = createCommonjsModule(function (module, exports) {
7513Object.defineProperty(exports, "__esModule", { value: true });
7514exports.serializeInto = void 0;
7515
7516
7517
7518
7519
7520
7521
7522
7523var regexp = /\x00/; // eslint-disable-line no-control-regex
7524var ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']);
7525function isRegExp(d) {
7526 return Object.prototype.toString.call(d) === '[object RegExp]';
7527}
7528/*
7529 * isArray indicates if we are writing to a BSON array (type 0x04)
7530 * which forces the "key" which really an array index as a string to be written as ascii
7531 * This will catch any errors in index as a string generation
7532 */
7533function serializeString(buffer, key, value, index, isArray) {
7534 // Encode String type
7535 buffer[index++] = constants.BSON_DATA_STRING;
7536 // Number of written bytes
7537 var numberOfWrittenBytes = !isArray
7538 ? buffer.write(key, index, undefined, 'utf8')
7539 : buffer.write(key, index, undefined, 'ascii');
7540 // Encode the name
7541 index = index + numberOfWrittenBytes + 1;
7542 buffer[index - 1] = 0;
7543 // Write the string
7544 var size = buffer.write(value, index + 4, undefined, 'utf8');
7545 // Write the size of the string to buffer
7546 buffer[index + 3] = ((size + 1) >> 24) & 0xff;
7547 buffer[index + 2] = ((size + 1) >> 16) & 0xff;
7548 buffer[index + 1] = ((size + 1) >> 8) & 0xff;
7549 buffer[index] = (size + 1) & 0xff;
7550 // Update index
7551 index = index + 4 + size;
7552 // Write zero
7553 buffer[index++] = 0;
7554 return index;
7555}
7556function serializeNumber(buffer, key, value, index, isArray) {
7557 // We have an integer value
7558 // TODO(NODE-2529): Add support for big int
7559 if (Number.isInteger(value) &&
7560 value >= constants.BSON_INT32_MIN &&
7561 value <= constants.BSON_INT32_MAX) {
7562 // If the value fits in 32 bits encode as int32
7563 // Set int type 32 bits or less
7564 buffer[index++] = constants.BSON_DATA_INT;
7565 // Number of written bytes
7566 var numberOfWrittenBytes = !isArray
7567 ? buffer.write(key, index, undefined, 'utf8')
7568 : buffer.write(key, index, undefined, 'ascii');
7569 // Encode the name
7570 index = index + numberOfWrittenBytes;
7571 buffer[index++] = 0;
7572 // Write the int value
7573 buffer[index++] = value & 0xff;
7574 buffer[index++] = (value >> 8) & 0xff;
7575 buffer[index++] = (value >> 16) & 0xff;
7576 buffer[index++] = (value >> 24) & 0xff;
7577 }
7578 else {
7579 // Encode as double
7580 buffer[index++] = constants.BSON_DATA_NUMBER;
7581 // Number of written bytes
7582 var numberOfWrittenBytes = !isArray
7583 ? buffer.write(key, index, undefined, 'utf8')
7584 : buffer.write(key, index, undefined, 'ascii');
7585 // Encode the name
7586 index = index + numberOfWrittenBytes;
7587 buffer[index++] = 0;
7588 // Write float
7589 float_parser.writeIEEE754(buffer, value, index, 'little', 52, 8);
7590 // Adjust index
7591 index = index + 8;
7592 }
7593 return index;
7594}
7595function serializeNull(buffer, key, _, index, isArray) {
7596 // Set long type
7597 buffer[index++] = constants.BSON_DATA_NULL;
7598 // Number of written bytes
7599 var numberOfWrittenBytes = !isArray
7600 ? buffer.write(key, index, undefined, 'utf8')
7601 : buffer.write(key, index, undefined, 'ascii');
7602 // Encode the name
7603 index = index + numberOfWrittenBytes;
7604 buffer[index++] = 0;
7605 return index;
7606}
7607function serializeBoolean(buffer, key, value, index, isArray) {
7608 // Write the type
7609 buffer[index++] = constants.BSON_DATA_BOOLEAN;
7610 // Number of written bytes
7611 var numberOfWrittenBytes = !isArray
7612 ? buffer.write(key, index, undefined, 'utf8')
7613 : buffer.write(key, index, undefined, 'ascii');
7614 // Encode the name
7615 index = index + numberOfWrittenBytes;
7616 buffer[index++] = 0;
7617 // Encode the boolean value
7618 buffer[index++] = value ? 1 : 0;
7619 return index;
7620}
7621function serializeDate(buffer, key, value, index, isArray) {
7622 // Write the type
7623 buffer[index++] = constants.BSON_DATA_DATE;
7624 // Number of written bytes
7625 var numberOfWrittenBytes = !isArray
7626 ? buffer.write(key, index, undefined, 'utf8')
7627 : buffer.write(key, index, undefined, 'ascii');
7628 // Encode the name
7629 index = index + numberOfWrittenBytes;
7630 buffer[index++] = 0;
7631 // Write the date
7632 var dateInMilis = long_1.Long.fromNumber(value.getTime());
7633 var lowBits = dateInMilis.getLowBits();
7634 var highBits = dateInMilis.getHighBits();
7635 // Encode low bits
7636 buffer[index++] = lowBits & 0xff;
7637 buffer[index++] = (lowBits >> 8) & 0xff;
7638 buffer[index++] = (lowBits >> 16) & 0xff;
7639 buffer[index++] = (lowBits >> 24) & 0xff;
7640 // Encode high bits
7641 buffer[index++] = highBits & 0xff;
7642 buffer[index++] = (highBits >> 8) & 0xff;
7643 buffer[index++] = (highBits >> 16) & 0xff;
7644 buffer[index++] = (highBits >> 24) & 0xff;
7645 return index;
7646}
7647function serializeRegExp(buffer, key, value, index, isArray) {
7648 // Write the type
7649 buffer[index++] = constants.BSON_DATA_REGEXP;
7650 // Number of written bytes
7651 var numberOfWrittenBytes = !isArray
7652 ? buffer.write(key, index, undefined, 'utf8')
7653 : buffer.write(key, index, undefined, 'ascii');
7654 // Encode the name
7655 index = index + numberOfWrittenBytes;
7656 buffer[index++] = 0;
7657 if (value.source && value.source.match(regexp) != null) {
7658 throw Error('value ' + value.source + ' must not contain null bytes');
7659 }
7660 // Adjust the index
7661 index = index + buffer.write(value.source, index, undefined, 'utf8');
7662 // Write zero
7663 buffer[index++] = 0x00;
7664 // Write the parameters
7665 if (value.ignoreCase)
7666 buffer[index++] = 0x69; // i
7667 if (value.global)
7668 buffer[index++] = 0x73; // s
7669 if (value.multiline)
7670 buffer[index++] = 0x6d; // m
7671 // Add ending zero
7672 buffer[index++] = 0x00;
7673 return index;
7674}
7675function serializeBSONRegExp(buffer, key, value, index, isArray) {
7676 // Write the type
7677 buffer[index++] = constants.BSON_DATA_REGEXP;
7678 // Number of written bytes
7679 var numberOfWrittenBytes = !isArray
7680 ? buffer.write(key, index, undefined, 'utf8')
7681 : buffer.write(key, index, undefined, 'ascii');
7682 // Encode the name
7683 index = index + numberOfWrittenBytes;
7684 buffer[index++] = 0;
7685 // Check the pattern for 0 bytes
7686 if (value.pattern.match(regexp) != null) {
7687 // The BSON spec doesn't allow keys with null bytes because keys are
7688 // null-terminated.
7689 throw Error('pattern ' + value.pattern + ' must not contain null bytes');
7690 }
7691 // Adjust the index
7692 index = index + buffer.write(value.pattern, index, undefined, 'utf8');
7693 // Write zero
7694 buffer[index++] = 0x00;
7695 // Write the options
7696 index = index + buffer.write(value.options.split('').sort().join(''), index, undefined, 'utf8');
7697 // Add ending zero
7698 buffer[index++] = 0x00;
7699 return index;
7700}
7701function serializeMinMax(buffer, key, value, index, isArray) {
7702 // Write the type of either min or max key
7703 if (value === null) {
7704 buffer[index++] = constants.BSON_DATA_NULL;
7705 }
7706 else if (value._bsontype === 'MinKey') {
7707 buffer[index++] = constants.BSON_DATA_MIN_KEY;
7708 }
7709 else {
7710 buffer[index++] = constants.BSON_DATA_MAX_KEY;
7711 }
7712 // Number of written bytes
7713 var numberOfWrittenBytes = !isArray
7714 ? buffer.write(key, index, undefined, 'utf8')
7715 : buffer.write(key, index, undefined, 'ascii');
7716 // Encode the name
7717 index = index + numberOfWrittenBytes;
7718 buffer[index++] = 0;
7719 return index;
7720}
7721function serializeObjectId(buffer, key, value, index, isArray) {
7722 // Write the type
7723 buffer[index++] = constants.BSON_DATA_OID;
7724 // Number of written bytes
7725 var numberOfWrittenBytes = !isArray
7726 ? buffer.write(key, index, undefined, 'utf8')
7727 : buffer.write(key, index, undefined, 'ascii');
7728 // Encode the name
7729 index = index + numberOfWrittenBytes;
7730 buffer[index++] = 0;
7731 // Write the objectId into the shared buffer
7732 if (typeof value.id === 'string') {
7733 buffer.write(value.id, index, undefined, 'binary');
7734 }
7735 else if (value.id && value.id.copy) {
7736 value.id.copy(buffer, index, 0, 12);
7737 }
7738 else {
7739 throw new TypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId');
7740 }
7741 // Adjust index
7742 return index + 12;
7743}
7744function serializeBuffer(buffer, key, value, index, isArray) {
7745 // Write the type
7746 buffer[index++] = constants.BSON_DATA_BINARY;
7747 // Number of written bytes
7748 var numberOfWrittenBytes = !isArray
7749 ? buffer.write(key, index, undefined, 'utf8')
7750 : buffer.write(key, index, undefined, 'ascii');
7751 // Encode the name
7752 index = index + numberOfWrittenBytes;
7753 buffer[index++] = 0;
7754 // Get size of the buffer (current write point)
7755 var size = value.length;
7756 // Write the size of the string to buffer
7757 buffer[index++] = size & 0xff;
7758 buffer[index++] = (size >> 8) & 0xff;
7759 buffer[index++] = (size >> 16) & 0xff;
7760 buffer[index++] = (size >> 24) & 0xff;
7761 // Write the default subtype
7762 buffer[index++] = constants.BSON_BINARY_SUBTYPE_DEFAULT;
7763 // Copy the content form the binary field to the buffer
7764 buffer.set(ensure_buffer.ensureBuffer(value), index);
7765 // Adjust the index
7766 index = index + size;
7767 return index;
7768}
7769function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) {
7770 if (checkKeys === void 0) { checkKeys = false; }
7771 if (depth === void 0) { depth = 0; }
7772 if (serializeFunctions === void 0) { serializeFunctions = false; }
7773 if (ignoreUndefined === void 0) { ignoreUndefined = true; }
7774 if (isArray === void 0) { isArray = false; }
7775 if (path === void 0) { path = []; }
7776 for (var i = 0; i < path.length; i++) {
7777 if (path[i] === value)
7778 throw new Error('cyclic dependency detected');
7779 }
7780 // Push value to stack
7781 path.push(value);
7782 // Write the type
7783 buffer[index++] = Array.isArray(value) ? constants.BSON_DATA_ARRAY : constants.BSON_DATA_OBJECT;
7784 // Number of written bytes
7785 var numberOfWrittenBytes = !isArray
7786 ? buffer.write(key, index, undefined, 'utf8')
7787 : buffer.write(key, index, undefined, 'ascii');
7788 // Encode the name
7789 index = index + numberOfWrittenBytes;
7790 buffer[index++] = 0;
7791 var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
7792 // Pop stack
7793 path.pop();
7794 return endIndex;
7795}
7796function serializeDecimal128(buffer, key, value, index, isArray) {
7797 buffer[index++] = constants.BSON_DATA_DECIMAL128;
7798 // Number of written bytes
7799 var numberOfWrittenBytes = !isArray
7800 ? buffer.write(key, index, undefined, 'utf8')
7801 : buffer.write(key, index, undefined, 'ascii');
7802 // Encode the name
7803 index = index + numberOfWrittenBytes;
7804 buffer[index++] = 0;
7805 // Write the data from the value
7806 value.bytes.copy(buffer, index, 0, 16);
7807 return index + 16;
7808}
7809function serializeLong(buffer, key, value, index, isArray) {
7810 // Write the type
7811 buffer[index++] =
7812 value._bsontype === 'Long' ? constants.BSON_DATA_LONG : constants.BSON_DATA_TIMESTAMP;
7813 // Number of written bytes
7814 var numberOfWrittenBytes = !isArray
7815 ? buffer.write(key, index, undefined, 'utf8')
7816 : buffer.write(key, index, undefined, 'ascii');
7817 // Encode the name
7818 index = index + numberOfWrittenBytes;
7819 buffer[index++] = 0;
7820 // Write the date
7821 var lowBits = value.getLowBits();
7822 var highBits = value.getHighBits();
7823 // Encode low bits
7824 buffer[index++] = lowBits & 0xff;
7825 buffer[index++] = (lowBits >> 8) & 0xff;
7826 buffer[index++] = (lowBits >> 16) & 0xff;
7827 buffer[index++] = (lowBits >> 24) & 0xff;
7828 // Encode high bits
7829 buffer[index++] = highBits & 0xff;
7830 buffer[index++] = (highBits >> 8) & 0xff;
7831 buffer[index++] = (highBits >> 16) & 0xff;
7832 buffer[index++] = (highBits >> 24) & 0xff;
7833 return index;
7834}
7835function serializeInt32(buffer, key, value, index, isArray) {
7836 value = value.valueOf();
7837 // Set int type 32 bits or less
7838 buffer[index++] = constants.BSON_DATA_INT;
7839 // Number of written bytes
7840 var numberOfWrittenBytes = !isArray
7841 ? buffer.write(key, index, undefined, 'utf8')
7842 : buffer.write(key, index, undefined, 'ascii');
7843 // Encode the name
7844 index = index + numberOfWrittenBytes;
7845 buffer[index++] = 0;
7846 // Write the int value
7847 buffer[index++] = value & 0xff;
7848 buffer[index++] = (value >> 8) & 0xff;
7849 buffer[index++] = (value >> 16) & 0xff;
7850 buffer[index++] = (value >> 24) & 0xff;
7851 return index;
7852}
7853function serializeDouble(buffer, key, value, index, isArray) {
7854 // Encode as double
7855 buffer[index++] = constants.BSON_DATA_NUMBER;
7856 // Number of written bytes
7857 var numberOfWrittenBytes = !isArray
7858 ? buffer.write(key, index, undefined, 'utf8')
7859 : buffer.write(key, index, undefined, 'ascii');
7860 // Encode the name
7861 index = index + numberOfWrittenBytes;
7862 buffer[index++] = 0;
7863 // Write float
7864 float_parser.writeIEEE754(buffer, value.value, index, 'little', 52, 8);
7865 // Adjust index
7866 index = index + 8;
7867 return index;
7868}
7869function serializeFunction(buffer, key, value, index, _checkKeys, _depth, isArray) {
7870 buffer[index++] = constants.BSON_DATA_CODE;
7871 // Number of written bytes
7872 var numberOfWrittenBytes = !isArray
7873 ? buffer.write(key, index, undefined, 'utf8')
7874 : buffer.write(key, index, undefined, 'ascii');
7875 // Encode the name
7876 index = index + numberOfWrittenBytes;
7877 buffer[index++] = 0;
7878 // Function string
7879 var functionString = utils.normalizedFunctionString(value);
7880 // Write the string
7881 var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1;
7882 // Write the size of the string to buffer
7883 buffer[index] = size & 0xff;
7884 buffer[index + 1] = (size >> 8) & 0xff;
7885 buffer[index + 2] = (size >> 16) & 0xff;
7886 buffer[index + 3] = (size >> 24) & 0xff;
7887 // Update index
7888 index = index + 4 + size - 1;
7889 // Write zero
7890 buffer[index++] = 0;
7891 return index;
7892}
7893function serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) {
7894 if (checkKeys === void 0) { checkKeys = false; }
7895 if (depth === void 0) { depth = 0; }
7896 if (serializeFunctions === void 0) { serializeFunctions = false; }
7897 if (ignoreUndefined === void 0) { ignoreUndefined = true; }
7898 if (isArray === void 0) { isArray = false; }
7899 if (value.scope && typeof value.scope === 'object') {
7900 // Write the type
7901 buffer[index++] = constants.BSON_DATA_CODE_W_SCOPE;
7902 // Number of written bytes
7903 var numberOfWrittenBytes = !isArray
7904 ? buffer.write(key, index, undefined, 'utf8')
7905 : buffer.write(key, index, undefined, 'ascii');
7906 // Encode the name
7907 index = index + numberOfWrittenBytes;
7908 buffer[index++] = 0;
7909 // Starting index
7910 var startIndex = index;
7911 // Serialize the function
7912 // Get the function string
7913 var functionString = typeof value.code === 'string' ? value.code : value.code.toString();
7914 // Index adjustment
7915 index = index + 4;
7916 // Write string into buffer
7917 var codeSize = buffer.write(functionString, index + 4, undefined, 'utf8') + 1;
7918 // Write the size of the string to buffer
7919 buffer[index] = codeSize & 0xff;
7920 buffer[index + 1] = (codeSize >> 8) & 0xff;
7921 buffer[index + 2] = (codeSize >> 16) & 0xff;
7922 buffer[index + 3] = (codeSize >> 24) & 0xff;
7923 // Write end 0
7924 buffer[index + 4 + codeSize - 1] = 0;
7925 // Write the
7926 index = index + codeSize + 4;
7927 //
7928 // Serialize the scope value
7929 var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined);
7930 index = endIndex - 1;
7931 // Writ the total
7932 var totalSize = endIndex - startIndex;
7933 // Write the total size of the object
7934 buffer[startIndex++] = totalSize & 0xff;
7935 buffer[startIndex++] = (totalSize >> 8) & 0xff;
7936 buffer[startIndex++] = (totalSize >> 16) & 0xff;
7937 buffer[startIndex++] = (totalSize >> 24) & 0xff;
7938 // Write trailing zero
7939 buffer[index++] = 0;
7940 }
7941 else {
7942 buffer[index++] = constants.BSON_DATA_CODE;
7943 // Number of written bytes
7944 var numberOfWrittenBytes = !isArray
7945 ? buffer.write(key, index, undefined, 'utf8')
7946 : buffer.write(key, index, undefined, 'ascii');
7947 // Encode the name
7948 index = index + numberOfWrittenBytes;
7949 buffer[index++] = 0;
7950 // Function string
7951 var functionString = value.code.toString();
7952 // Write the string
7953 var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1;
7954 // Write the size of the string to buffer
7955 buffer[index] = size & 0xff;
7956 buffer[index + 1] = (size >> 8) & 0xff;
7957 buffer[index + 2] = (size >> 16) & 0xff;
7958 buffer[index + 3] = (size >> 24) & 0xff;
7959 // Update index
7960 index = index + 4 + size - 1;
7961 // Write zero
7962 buffer[index++] = 0;
7963 }
7964 return index;
7965}
7966function serializeBinary(buffer, key, value, index, isArray) {
7967 // Write the type
7968 buffer[index++] = constants.BSON_DATA_BINARY;
7969 // Number of written bytes
7970 var numberOfWrittenBytes = !isArray
7971 ? buffer.write(key, index, undefined, 'utf8')
7972 : buffer.write(key, index, undefined, 'ascii');
7973 // Encode the name
7974 index = index + numberOfWrittenBytes;
7975 buffer[index++] = 0;
7976 // Extract the buffer
7977 var data = value.value(true);
7978 // Calculate size
7979 var size = value.position;
7980 // Add the deprecated 02 type 4 bytes of size to total
7981 if (value.sub_type === binary.Binary.SUBTYPE_BYTE_ARRAY)
7982 size = size + 4;
7983 // Write the size of the string to buffer
7984 buffer[index++] = size & 0xff;
7985 buffer[index++] = (size >> 8) & 0xff;
7986 buffer[index++] = (size >> 16) & 0xff;
7987 buffer[index++] = (size >> 24) & 0xff;
7988 // Write the subtype to the buffer
7989 buffer[index++] = value.sub_type;
7990 // If we have binary type 2 the 4 first bytes are the size
7991 if (value.sub_type === binary.Binary.SUBTYPE_BYTE_ARRAY) {
7992 size = size - 4;
7993 buffer[index++] = size & 0xff;
7994 buffer[index++] = (size >> 8) & 0xff;
7995 buffer[index++] = (size >> 16) & 0xff;
7996 buffer[index++] = (size >> 24) & 0xff;
7997 }
7998 // Write the data to the object
7999 buffer.set(data, index);
8000 // Adjust the index
8001 index = index + value.position;
8002 return index;
8003}
8004function serializeSymbol(buffer, key, value, index, isArray) {
8005 // Write the type
8006 buffer[index++] = constants.BSON_DATA_SYMBOL;
8007 // Number of written bytes
8008 var numberOfWrittenBytes = !isArray
8009 ? buffer.write(key, index, undefined, 'utf8')
8010 : buffer.write(key, index, undefined, 'ascii');
8011 // Encode the name
8012 index = index + numberOfWrittenBytes;
8013 buffer[index++] = 0;
8014 // Write the string
8015 var size = buffer.write(value.value, index + 4, undefined, 'utf8') + 1;
8016 // Write the size of the string to buffer
8017 buffer[index] = size & 0xff;
8018 buffer[index + 1] = (size >> 8) & 0xff;
8019 buffer[index + 2] = (size >> 16) & 0xff;
8020 buffer[index + 3] = (size >> 24) & 0xff;
8021 // Update index
8022 index = index + 4 + size - 1;
8023 // Write zero
8024 buffer[index++] = 0x00;
8025 return index;
8026}
8027function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, isArray) {
8028 // Write the type
8029 buffer[index++] = constants.BSON_DATA_OBJECT;
8030 // Number of written bytes
8031 var numberOfWrittenBytes = !isArray
8032 ? buffer.write(key, index, undefined, 'utf8')
8033 : buffer.write(key, index, undefined, 'ascii');
8034 // Encode the name
8035 index = index + numberOfWrittenBytes;
8036 buffer[index++] = 0;
8037 var startIndex = index;
8038 var output = {
8039 $ref: value.collection || value.namespace,
8040 $id: value.oid
8041 };
8042 if (value.db != null) {
8043 output.$db = value.db;
8044 }
8045 output = Object.assign(output, value.fields);
8046 var endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions);
8047 // Calculate object size
8048 var size = endIndex - startIndex;
8049 // Write the size
8050 buffer[startIndex++] = size & 0xff;
8051 buffer[startIndex++] = (size >> 8) & 0xff;
8052 buffer[startIndex++] = (size >> 16) & 0xff;
8053 buffer[startIndex++] = (size >> 24) & 0xff;
8054 // Set index
8055 return endIndex;
8056}
8057function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) {
8058 if (checkKeys === void 0) { checkKeys = false; }
8059 if (startingIndex === void 0) { startingIndex = 0; }
8060 if (depth === void 0) { depth = 0; }
8061 if (serializeFunctions === void 0) { serializeFunctions = false; }
8062 if (ignoreUndefined === void 0) { ignoreUndefined = true; }
8063 if (path === void 0) { path = []; }
8064 startingIndex = startingIndex || 0;
8065 path = path || [];
8066 // Push the object to the path
8067 path.push(object);
8068 // Start place to serialize into
8069 var index = startingIndex + 4;
8070 // Special case isArray
8071 if (Array.isArray(object)) {
8072 // Get object keys
8073 for (var i = 0; i < object.length; i++) {
8074 var key = '' + i;
8075 var value = object[i];
8076 // Is there an override value
8077 if (value && value.toBSON) {
8078 if (typeof value.toBSON !== 'function')
8079 throw new TypeError('toBSON is not a function');
8080 value = value.toBSON();
8081 }
8082 if (typeof value === 'string') {
8083 index = serializeString(buffer, key, value, index, true);
8084 }
8085 else if (typeof value === 'number') {
8086 index = serializeNumber(buffer, key, value, index, true);
8087 }
8088 else if (typeof value === 'bigint') {
8089 throw new TypeError('Unsupported type BigInt, please use Decimal128');
8090 }
8091 else if (typeof value === 'boolean') {
8092 index = serializeBoolean(buffer, key, value, index, true);
8093 }
8094 else if (value instanceof Date || utils.isDate(value)) {
8095 index = serializeDate(buffer, key, value, index, true);
8096 }
8097 else if (value === undefined) {
8098 index = serializeNull(buffer, key, value, index, true);
8099 }
8100 else if (value === null) {
8101 index = serializeNull(buffer, key, value, index, true);
8102 }
8103 else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') {
8104 index = serializeObjectId(buffer, key, value, index, true);
8105 }
8106 else if (utils.isBuffer(value) || utils.isUint8Array(value)) {
8107 index = serializeBuffer(buffer, key, value, index, true);
8108 }
8109 else if (value instanceof RegExp || isRegExp(value)) {
8110 index = serializeRegExp(buffer, key, value, index, true);
8111 }
8112 else if (typeof value === 'object' && value['_bsontype'] == null) {
8113 index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path);
8114 }
8115 else if (typeof value === 'object' &&
8116 extended_json.isBSONType(value) &&
8117 value._bsontype === 'Decimal128') {
8118 index = serializeDecimal128(buffer, key, value, index, true);
8119 }
8120 else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') {
8121 index = serializeLong(buffer, key, value, index, true);
8122 }
8123 else if (value['_bsontype'] === 'Double') {
8124 index = serializeDouble(buffer, key, value, index, true);
8125 }
8126 else if (typeof value === 'function' && serializeFunctions) {
8127 index = serializeFunction(buffer, key, value, index, checkKeys, depth, true);
8128 }
8129 else if (value['_bsontype'] === 'Code') {
8130 index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true);
8131 }
8132 else if (value['_bsontype'] === 'Binary') {
8133 index = serializeBinary(buffer, key, value, index, true);
8134 }
8135 else if (value['_bsontype'] === 'Symbol') {
8136 index = serializeSymbol(buffer, key, value, index, true);
8137 }
8138 else if (value['_bsontype'] === 'DBRef') {
8139 index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true);
8140 }
8141 else if (value['_bsontype'] === 'BSONRegExp') {
8142 index = serializeBSONRegExp(buffer, key, value, index, true);
8143 }
8144 else if (value['_bsontype'] === 'Int32') {
8145 index = serializeInt32(buffer, key, value, index, true);
8146 }
8147 else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
8148 index = serializeMinMax(buffer, key, value, index, true);
8149 }
8150 else if (typeof value['_bsontype'] !== 'undefined') {
8151 throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
8152 }
8153 }
8154 }
8155 else if (object instanceof map.Map) {
8156 var iterator = object.entries();
8157 var done = false;
8158 while (!done) {
8159 // Unpack the next entry
8160 var entry = iterator.next();
8161 done = !!entry.done;
8162 // Are we done, then skip and terminate
8163 if (done)
8164 continue;
8165 // Get the entry values
8166 var key = entry.value[0];
8167 var value = entry.value[1];
8168 // Check the type of the value
8169 var type = typeof value;
8170 // Check the key and throw error if it's illegal
8171 if (typeof key === 'string' && !ignoreKeys.has(key)) {
8172 if (key.match(regexp) != null) {
8173 // The BSON spec doesn't allow keys with null bytes because keys are
8174 // null-terminated.
8175 throw Error('key ' + key + ' must not contain null bytes');
8176 }
8177 if (checkKeys) {
8178 if ('$' === key[0]) {
8179 throw Error('key ' + key + " must not start with '$'");
8180 }
8181 else if (~key.indexOf('.')) {
8182 throw Error('key ' + key + " must not contain '.'");
8183 }
8184 }
8185 }
8186 if (type === 'string') {
8187 index = serializeString(buffer, key, value, index);
8188 }
8189 else if (type === 'number') {
8190 index = serializeNumber(buffer, key, value, index);
8191 }
8192 else if (type === 'bigint' || utils.isBigInt64Array(value) || utils.isBigUInt64Array(value)) {
8193 throw new TypeError('Unsupported type BigInt, please use Decimal128');
8194 }
8195 else if (type === 'boolean') {
8196 index = serializeBoolean(buffer, key, value, index);
8197 }
8198 else if (value instanceof Date || utils.isDate(value)) {
8199 index = serializeDate(buffer, key, value, index);
8200 }
8201 else if (value === null || (value === undefined && ignoreUndefined === false)) {
8202 index = serializeNull(buffer, key, value, index);
8203 }
8204 else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') {
8205 index = serializeObjectId(buffer, key, value, index);
8206 }
8207 else if (utils.isBuffer(value) || utils.isUint8Array(value)) {
8208 index = serializeBuffer(buffer, key, value, index);
8209 }
8210 else if (value instanceof RegExp || isRegExp(value)) {
8211 index = serializeRegExp(buffer, key, value, index);
8212 }
8213 else if (type === 'object' && value['_bsontype'] == null) {
8214 index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path);
8215 }
8216 else if (type === 'object' && value['_bsontype'] === 'Decimal128') {
8217 index = serializeDecimal128(buffer, key, value, index);
8218 }
8219 else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') {
8220 index = serializeLong(buffer, key, value, index);
8221 }
8222 else if (value['_bsontype'] === 'Double') {
8223 index = serializeDouble(buffer, key, value, index);
8224 }
8225 else if (value['_bsontype'] === 'Code') {
8226 index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined);
8227 }
8228 else if (typeof value === 'function' && serializeFunctions) {
8229 index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions);
8230 }
8231 else if (value['_bsontype'] === 'Binary') {
8232 index = serializeBinary(buffer, key, value, index);
8233 }
8234 else if (value['_bsontype'] === 'Symbol') {
8235 index = serializeSymbol(buffer, key, value, index);
8236 }
8237 else if (value['_bsontype'] === 'DBRef') {
8238 index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions);
8239 }
8240 else if (value['_bsontype'] === 'BSONRegExp') {
8241 index = serializeBSONRegExp(buffer, key, value, index);
8242 }
8243 else if (value['_bsontype'] === 'Int32') {
8244 index = serializeInt32(buffer, key, value, index);
8245 }
8246 else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
8247 index = serializeMinMax(buffer, key, value, index);
8248 }
8249 else if (typeof value['_bsontype'] !== 'undefined') {
8250 throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
8251 }
8252 }
8253 }
8254 else {
8255 // Did we provide a custom serialization method
8256 if (object.toBSON) {
8257 if (typeof object.toBSON !== 'function')
8258 throw new TypeError('toBSON is not a function');
8259 object = object.toBSON();
8260 if (object != null && typeof object !== 'object')
8261 throw new TypeError('toBSON function did not return an object');
8262 }
8263 // Iterate over all the keys
8264 for (var key in object) {
8265 var value = object[key];
8266 // Is there an override value
8267 if (value && value.toBSON) {
8268 if (typeof value.toBSON !== 'function')
8269 throw new TypeError('toBSON is not a function');
8270 value = value.toBSON();
8271 }
8272 // Check the type of the value
8273 var type = typeof value;
8274 // Check the key and throw error if it's illegal
8275 if (typeof key === 'string' && !ignoreKeys.has(key)) {
8276 if (key.match(regexp) != null) {
8277 // The BSON spec doesn't allow keys with null bytes because keys are
8278 // null-terminated.
8279 throw Error('key ' + key + ' must not contain null bytes');
8280 }
8281 if (checkKeys) {
8282 if ('$' === key[0]) {
8283 throw Error('key ' + key + " must not start with '$'");
8284 }
8285 else if (~key.indexOf('.')) {
8286 throw Error('key ' + key + " must not contain '.'");
8287 }
8288 }
8289 }
8290 if (type === 'string') {
8291 index = serializeString(buffer, key, value, index);
8292 }
8293 else if (type === 'number') {
8294 index = serializeNumber(buffer, key, value, index);
8295 }
8296 else if (type === 'bigint') {
8297 throw new TypeError('Unsupported type BigInt, please use Decimal128');
8298 }
8299 else if (type === 'boolean') {
8300 index = serializeBoolean(buffer, key, value, index);
8301 }
8302 else if (value instanceof Date || utils.isDate(value)) {
8303 index = serializeDate(buffer, key, value, index);
8304 }
8305 else if (value === undefined) {
8306 if (ignoreUndefined === false)
8307 index = serializeNull(buffer, key, value, index);
8308 }
8309 else if (value === null) {
8310 index = serializeNull(buffer, key, value, index);
8311 }
8312 else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') {
8313 index = serializeObjectId(buffer, key, value, index);
8314 }
8315 else if (utils.isBuffer(value) || utils.isUint8Array(value)) {
8316 index = serializeBuffer(buffer, key, value, index);
8317 }
8318 else if (value instanceof RegExp || isRegExp(value)) {
8319 index = serializeRegExp(buffer, key, value, index);
8320 }
8321 else if (type === 'object' && value['_bsontype'] == null) {
8322 index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path);
8323 }
8324 else if (type === 'object' && value['_bsontype'] === 'Decimal128') {
8325 index = serializeDecimal128(buffer, key, value, index);
8326 }
8327 else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') {
8328 index = serializeLong(buffer, key, value, index);
8329 }
8330 else if (value['_bsontype'] === 'Double') {
8331 index = serializeDouble(buffer, key, value, index);
8332 }
8333 else if (value['_bsontype'] === 'Code') {
8334 index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined);
8335 }
8336 else if (typeof value === 'function' && serializeFunctions) {
8337 index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions);
8338 }
8339 else if (value['_bsontype'] === 'Binary') {
8340 index = serializeBinary(buffer, key, value, index);
8341 }
8342 else if (value['_bsontype'] === 'Symbol') {
8343 index = serializeSymbol(buffer, key, value, index);
8344 }
8345 else if (value['_bsontype'] === 'DBRef') {
8346 index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions);
8347 }
8348 else if (value['_bsontype'] === 'BSONRegExp') {
8349 index = serializeBSONRegExp(buffer, key, value, index);
8350 }
8351 else if (value['_bsontype'] === 'Int32') {
8352 index = serializeInt32(buffer, key, value, index);
8353 }
8354 else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
8355 index = serializeMinMax(buffer, key, value, index);
8356 }
8357 else if (typeof value['_bsontype'] !== 'undefined') {
8358 throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
8359 }
8360 }
8361 }
8362 // Remove the path
8363 path.pop();
8364 // Final padding byte for object
8365 buffer[index++] = 0x00;
8366 // Final size
8367 var size = index - startingIndex;
8368 // Write the size of the object
8369 buffer[startingIndex++] = size & 0xff;
8370 buffer[startingIndex++] = (size >> 8) & 0xff;
8371 buffer[startingIndex++] = (size >> 16) & 0xff;
8372 buffer[startingIndex++] = (size >> 24) & 0xff;
8373 return index;
8374}
8375exports.serializeInto = serializeInto;
8376
8377});
8378
8379unwrapExports(serializer);
8380var serializer_1 = serializer.serializeInto;
8381
8382var bson = createCommonjsModule(function (module, exports) {
8383Object.defineProperty(exports, "__esModule", { value: true });
8384exports.deserializeStream = exports.calculateObjectSize = exports.deserialize = exports.serializeWithBufferAndIndex = exports.serialize = exports.setInternalBufferSize = exports.ObjectID = exports.Decimal128 = exports.BSONRegExp = exports.MaxKey = exports.MinKey = exports.Int32 = exports.Double = exports.Timestamp = exports.Long = exports.ObjectId = exports.Binary = exports.DBRef = exports.BSONSymbol = exports.Map = exports.Code = exports.LongWithoutOverridesClass = exports.EJSON = exports.BSON_INT64_MIN = exports.BSON_INT64_MAX = exports.BSON_INT32_MIN = exports.BSON_INT32_MAX = exports.BSON_DATA_UNDEFINED = exports.BSON_DATA_TIMESTAMP = exports.BSON_DATA_SYMBOL = exports.BSON_DATA_STRING = exports.BSON_DATA_REGEXP = exports.BSON_DATA_OID = exports.BSON_DATA_OBJECT = exports.BSON_DATA_NUMBER = exports.BSON_DATA_NULL = exports.BSON_DATA_MIN_KEY = exports.BSON_DATA_MAX_KEY = exports.BSON_DATA_LONG = exports.BSON_DATA_INT = exports.BSON_DATA_DECIMAL128 = exports.BSON_DATA_DBPOINTER = exports.BSON_DATA_DATE = exports.BSON_DATA_CODE_W_SCOPE = exports.BSON_DATA_CODE = exports.BSON_DATA_BOOLEAN = exports.BSON_DATA_BINARY = exports.BSON_DATA_ARRAY = exports.BSON_BINARY_SUBTYPE_UUID_NEW = exports.BSON_BINARY_SUBTYPE_UUID = exports.BSON_BINARY_SUBTYPE_USER_DEFINED = exports.BSON_BINARY_SUBTYPE_MD5 = exports.BSON_BINARY_SUBTYPE_FUNCTION = exports.BSON_BINARY_SUBTYPE_DEFAULT = exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = void 0;
8385
8386
8387Object.defineProperty(exports, "Binary", { enumerable: true, get: function () { return binary.Binary; } });
8388
8389Object.defineProperty(exports, "Code", { enumerable: true, get: function () { return code$1.Code; } });
8390
8391Object.defineProperty(exports, "DBRef", { enumerable: true, get: function () { return db_ref.DBRef; } });
8392
8393Object.defineProperty(exports, "Decimal128", { enumerable: true, get: function () { return decimal128.Decimal128; } });
8394
8395Object.defineProperty(exports, "Double", { enumerable: true, get: function () { return double_1.Double; } });
8396
8397
8398
8399Object.defineProperty(exports, "Int32", { enumerable: true, get: function () { return int_32.Int32; } });
8400
8401Object.defineProperty(exports, "Long", { enumerable: true, get: function () { return long_1.Long; } });
8402
8403Object.defineProperty(exports, "Map", { enumerable: true, get: function () { return map.Map; } });
8404
8405Object.defineProperty(exports, "MaxKey", { enumerable: true, get: function () { return max_key.MaxKey; } });
8406
8407Object.defineProperty(exports, "MinKey", { enumerable: true, get: function () { return min_key.MinKey; } });
8408
8409Object.defineProperty(exports, "ObjectId", { enumerable: true, get: function () { return objectid.ObjectId; } });
8410Object.defineProperty(exports, "ObjectID", { enumerable: true, get: function () { return objectid.ObjectId; } });
8411
8412// Parts of the parser
8413
8414
8415
8416Object.defineProperty(exports, "BSONRegExp", { enumerable: true, get: function () { return regexp.BSONRegExp; } });
8417
8418Object.defineProperty(exports, "BSONSymbol", { enumerable: true, get: function () { return symbol.BSONSymbol; } });
8419
8420Object.defineProperty(exports, "Timestamp", { enumerable: true, get: function () { return timestamp$1.Timestamp; } });
8421
8422Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_BYTE_ARRAY", { enumerable: true, get: function () { return constants.BSON_BINARY_SUBTYPE_BYTE_ARRAY; } });
8423Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_DEFAULT", { enumerable: true, get: function () { return constants.BSON_BINARY_SUBTYPE_DEFAULT; } });
8424Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_FUNCTION", { enumerable: true, get: function () { return constants.BSON_BINARY_SUBTYPE_FUNCTION; } });
8425Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_MD5", { enumerable: true, get: function () { return constants.BSON_BINARY_SUBTYPE_MD5; } });
8426Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_USER_DEFINED", { enumerable: true, get: function () { return constants.BSON_BINARY_SUBTYPE_USER_DEFINED; } });
8427Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_UUID", { enumerable: true, get: function () { return constants.BSON_BINARY_SUBTYPE_UUID; } });
8428Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_UUID_NEW", { enumerable: true, get: function () { return constants.BSON_BINARY_SUBTYPE_UUID_NEW; } });
8429Object.defineProperty(exports, "BSON_DATA_ARRAY", { enumerable: true, get: function () { return constants.BSON_DATA_ARRAY; } });
8430Object.defineProperty(exports, "BSON_DATA_BINARY", { enumerable: true, get: function () { return constants.BSON_DATA_BINARY; } });
8431Object.defineProperty(exports, "BSON_DATA_BOOLEAN", { enumerable: true, get: function () { return constants.BSON_DATA_BOOLEAN; } });
8432Object.defineProperty(exports, "BSON_DATA_CODE", { enumerable: true, get: function () { return constants.BSON_DATA_CODE; } });
8433Object.defineProperty(exports, "BSON_DATA_CODE_W_SCOPE", { enumerable: true, get: function () { return constants.BSON_DATA_CODE_W_SCOPE; } });
8434Object.defineProperty(exports, "BSON_DATA_DATE", { enumerable: true, get: function () { return constants.BSON_DATA_DATE; } });
8435Object.defineProperty(exports, "BSON_DATA_DBPOINTER", { enumerable: true, get: function () { return constants.BSON_DATA_DBPOINTER; } });
8436Object.defineProperty(exports, "BSON_DATA_DECIMAL128", { enumerable: true, get: function () { return constants.BSON_DATA_DECIMAL128; } });
8437Object.defineProperty(exports, "BSON_DATA_INT", { enumerable: true, get: function () { return constants.BSON_DATA_INT; } });
8438Object.defineProperty(exports, "BSON_DATA_LONG", { enumerable: true, get: function () { return constants.BSON_DATA_LONG; } });
8439Object.defineProperty(exports, "BSON_DATA_MAX_KEY", { enumerable: true, get: function () { return constants.BSON_DATA_MAX_KEY; } });
8440Object.defineProperty(exports, "BSON_DATA_MIN_KEY", { enumerable: true, get: function () { return constants.BSON_DATA_MIN_KEY; } });
8441Object.defineProperty(exports, "BSON_DATA_NULL", { enumerable: true, get: function () { return constants.BSON_DATA_NULL; } });
8442Object.defineProperty(exports, "BSON_DATA_NUMBER", { enumerable: true, get: function () { return constants.BSON_DATA_NUMBER; } });
8443Object.defineProperty(exports, "BSON_DATA_OBJECT", { enumerable: true, get: function () { return constants.BSON_DATA_OBJECT; } });
8444Object.defineProperty(exports, "BSON_DATA_OID", { enumerable: true, get: function () { return constants.BSON_DATA_OID; } });
8445Object.defineProperty(exports, "BSON_DATA_REGEXP", { enumerable: true, get: function () { return constants.BSON_DATA_REGEXP; } });
8446Object.defineProperty(exports, "BSON_DATA_STRING", { enumerable: true, get: function () { return constants.BSON_DATA_STRING; } });
8447Object.defineProperty(exports, "BSON_DATA_SYMBOL", { enumerable: true, get: function () { return constants.BSON_DATA_SYMBOL; } });
8448Object.defineProperty(exports, "BSON_DATA_TIMESTAMP", { enumerable: true, get: function () { return constants.BSON_DATA_TIMESTAMP; } });
8449Object.defineProperty(exports, "BSON_DATA_UNDEFINED", { enumerable: true, get: function () { return constants.BSON_DATA_UNDEFINED; } });
8450Object.defineProperty(exports, "BSON_INT32_MAX", { enumerable: true, get: function () { return constants.BSON_INT32_MAX; } });
8451Object.defineProperty(exports, "BSON_INT32_MIN", { enumerable: true, get: function () { return constants.BSON_INT32_MIN; } });
8452Object.defineProperty(exports, "BSON_INT64_MAX", { enumerable: true, get: function () { return constants.BSON_INT64_MAX; } });
8453Object.defineProperty(exports, "BSON_INT64_MIN", { enumerable: true, get: function () { return constants.BSON_INT64_MIN; } });
8454var extended_json_2 = extended_json;
8455Object.defineProperty(exports, "EJSON", { enumerable: true, get: function () { return extended_json_2.EJSON; } });
8456var timestamp_2 = timestamp$1;
8457Object.defineProperty(exports, "LongWithoutOverridesClass", { enumerable: true, get: function () { return timestamp_2.LongWithoutOverridesClass; } });
8458/** @internal */
8459// Default Max Size
8460var MAXSIZE = 1024 * 1024 * 17;
8461// Current Internal Temporary Serialization Buffer
8462var buffer$1 = buffer.Buffer.alloc(MAXSIZE);
8463/**
8464 * Sets the size of the internal serialization buffer.
8465 *
8466 * @param size - The desired size for the internal serialization buffer
8467 * @public
8468 */
8469function setInternalBufferSize(size) {
8470 // Resize the internal serialization buffer if needed
8471 if (buffer$1.length < size) {
8472 buffer$1 = buffer.Buffer.alloc(size);
8473 }
8474}
8475exports.setInternalBufferSize = setInternalBufferSize;
8476/**
8477 * Serialize a Javascript object.
8478 *
8479 * @param object - the Javascript object to serialize.
8480 * @returns Buffer object containing the serialized object.
8481 * @public
8482 */
8483function serialize(object, options) {
8484 if (options === void 0) { options = {}; }
8485 // Unpack the options
8486 var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
8487 var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
8488 var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
8489 var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE;
8490 // Resize the internal serialization buffer if needed
8491 if (buffer$1.length < minInternalBufferSize) {
8492 buffer$1 = buffer.Buffer.alloc(minInternalBufferSize);
8493 }
8494 // Attempt to serialize
8495 var serializationIndex = serializer.serializeInto(buffer$1, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []);
8496 // Create the final buffer
8497 var finishedBuffer = buffer.Buffer.alloc(serializationIndex);
8498 // Copy into the finished buffer
8499 buffer$1.copy(finishedBuffer, 0, 0, finishedBuffer.length);
8500 // Return the buffer
8501 return finishedBuffer;
8502}
8503exports.serialize = serialize;
8504/**
8505 * Serialize a Javascript object using a predefined Buffer and index into the buffer,
8506 * useful when pre-allocating the space for serialization.
8507 *
8508 * @param object - the Javascript object to serialize.
8509 * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object.
8510 * @returns the index pointing to the last written byte in the buffer.
8511 * @public
8512 */
8513function serializeWithBufferAndIndex(object, finalBuffer, options) {
8514 if (options === void 0) { options = {}; }
8515 // Unpack the options
8516 var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
8517 var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
8518 var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
8519 var startIndex = typeof options.index === 'number' ? options.index : 0;
8520 // Attempt to serialize
8521 var serializationIndex = serializer.serializeInto(buffer$1, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined);
8522 buffer$1.copy(finalBuffer, startIndex, 0, serializationIndex);
8523 // Return the index
8524 return startIndex + serializationIndex - 1;
8525}
8526exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex;
8527/**
8528 * Deserialize data as BSON.
8529 *
8530 * @param buffer - the buffer containing the serialized set of BSON documents.
8531 * @returns returns the deserialized Javascript Object.
8532 * @public
8533 */
8534function deserialize(buffer, options) {
8535 if (options === void 0) { options = {}; }
8536 return deserializer.deserialize(ensure_buffer.ensureBuffer(buffer), options);
8537}
8538exports.deserialize = deserialize;
8539/**
8540 * Calculate the bson size for a passed in Javascript object.
8541 *
8542 * @param object - the Javascript object to calculate the BSON byte size for
8543 * @returns size of BSON object in bytes
8544 * @public
8545 */
8546function calculateObjectSize(object, options) {
8547 if (options === void 0) { options = {}; }
8548 options = options || {};
8549 var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
8550 var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
8551 return calculate_size.calculateObjectSize(object, serializeFunctions, ignoreUndefined);
8552}
8553exports.calculateObjectSize = calculateObjectSize;
8554/**
8555 * Deserialize stream data as BSON documents.
8556 *
8557 * @param data - the buffer containing the serialized set of BSON documents.
8558 * @param startIndex - the start index in the data Buffer where the deserialization is to start.
8559 * @param numberOfDocuments - number of documents to deserialize.
8560 * @param documents - an array where to store the deserialized documents.
8561 * @param docStartIndex - the index in the documents array from where to start inserting documents.
8562 * @param options - additional options used for the deserialization.
8563 * @returns next index in the buffer after deserialization **x** numbers of documents.
8564 * @public
8565 */
8566function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) {
8567 var internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options);
8568 var bufferData = ensure_buffer.ensureBuffer(data);
8569 var index = startIndex;
8570 // Loop over all documents
8571 for (var i = 0; i < numberOfDocuments; i++) {
8572 // Find size of the document
8573 var size = bufferData[index] |
8574 (bufferData[index + 1] << 8) |
8575 (bufferData[index + 2] << 16) |
8576 (bufferData[index + 3] << 24);
8577 // Update options with index
8578 internalOptions.index = index;
8579 // Parse the document at this point
8580 documents[docStartIndex + i] = deserializer.deserialize(bufferData, internalOptions);
8581 // Adjust index by the document size
8582 index = index + size;
8583 }
8584 // Return object containing end index of parsing and list of documents
8585 return index;
8586}
8587exports.deserializeStream = deserializeStream;
8588/**
8589 * BSON default export
8590 * @deprecated Please use named exports
8591 * @privateRemarks
8592 * We want to someday deprecate the default export,
8593 * so none of the new TS types are being exported on the default
8594 * @public
8595 */
8596var BSON = {
8597 Binary: binary.Binary,
8598 Code: code$1.Code,
8599 DBRef: db_ref.DBRef,
8600 Decimal128: decimal128.Decimal128,
8601 Double: double_1.Double,
8602 Int32: int_32.Int32,
8603 Long: long_1.Long,
8604 Map: map.Map,
8605 MaxKey: max_key.MaxKey,
8606 MinKey: min_key.MinKey,
8607 ObjectId: objectid.ObjectId,
8608 ObjectID: objectid.ObjectId,
8609 BSONRegExp: regexp.BSONRegExp,
8610 BSONSymbol: symbol.BSONSymbol,
8611 Timestamp: timestamp$1.Timestamp,
8612 EJSON: extended_json.EJSON,
8613 setInternalBufferSize: setInternalBufferSize,
8614 serialize: serialize,
8615 serializeWithBufferAndIndex: serializeWithBufferAndIndex,
8616 deserialize: deserialize,
8617 calculateObjectSize: calculateObjectSize,
8618 deserializeStream: deserializeStream
8619};
8620exports.default = BSON;
8621
8622});
8623
8624var bson$1 = unwrapExports(bson);
8625var bson_1 = bson.deserializeStream;
8626var bson_2 = bson.calculateObjectSize;
8627var bson_3 = bson.deserialize;
8628var bson_4 = bson.serializeWithBufferAndIndex;
8629var bson_5 = bson.serialize;
8630var bson_6 = bson.setInternalBufferSize;
8631var bson_7 = bson.ObjectID;
8632var bson_8 = bson.Decimal128;
8633var bson_9 = bson.BSONRegExp;
8634var bson_10 = bson.MaxKey;
8635var bson_11 = bson.MinKey;
8636var bson_12 = bson.Int32;
8637var bson_13 = bson.Double;
8638var bson_14 = bson.Timestamp;
8639var bson_15 = bson.Long;
8640var bson_16 = bson.ObjectId;
8641var bson_17 = bson.Binary;
8642var bson_18 = bson.DBRef;
8643var bson_19 = bson.BSONSymbol;
8644var bson_20 = bson.Map;
8645var bson_21 = bson.Code;
8646var bson_22 = bson.LongWithoutOverridesClass;
8647var bson_23 = bson.EJSON;
8648var bson_24 = bson.BSON_INT64_MIN;
8649var bson_25 = bson.BSON_INT64_MAX;
8650var bson_26 = bson.BSON_INT32_MIN;
8651var bson_27 = bson.BSON_INT32_MAX;
8652var bson_28 = bson.BSON_DATA_UNDEFINED;
8653var bson_29 = bson.BSON_DATA_TIMESTAMP;
8654var bson_30 = bson.BSON_DATA_SYMBOL;
8655var bson_31 = bson.BSON_DATA_STRING;
8656var bson_32 = bson.BSON_DATA_REGEXP;
8657var bson_33 = bson.BSON_DATA_OID;
8658var bson_34 = bson.BSON_DATA_OBJECT;
8659var bson_35 = bson.BSON_DATA_NUMBER;
8660var bson_36 = bson.BSON_DATA_NULL;
8661var bson_37 = bson.BSON_DATA_MIN_KEY;
8662var bson_38 = bson.BSON_DATA_MAX_KEY;
8663var bson_39 = bson.BSON_DATA_LONG;
8664var bson_40 = bson.BSON_DATA_INT;
8665var bson_41 = bson.BSON_DATA_DECIMAL128;
8666var bson_42 = bson.BSON_DATA_DBPOINTER;
8667var bson_43 = bson.BSON_DATA_DATE;
8668var bson_44 = bson.BSON_DATA_CODE_W_SCOPE;
8669var bson_45 = bson.BSON_DATA_CODE;
8670var bson_46 = bson.BSON_DATA_BOOLEAN;
8671var bson_47 = bson.BSON_DATA_BINARY;
8672var bson_48 = bson.BSON_DATA_ARRAY;
8673var bson_49 = bson.BSON_BINARY_SUBTYPE_UUID_NEW;
8674var bson_50 = bson.BSON_BINARY_SUBTYPE_UUID;
8675var bson_51 = bson.BSON_BINARY_SUBTYPE_USER_DEFINED;
8676var bson_52 = bson.BSON_BINARY_SUBTYPE_MD5;
8677var bson_53 = bson.BSON_BINARY_SUBTYPE_FUNCTION;
8678var bson_54 = bson.BSON_BINARY_SUBTYPE_DEFAULT;
8679var bson_55 = bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY;
8680
8681export default bson$1;
8682export { bson_9 as BSONRegExp, bson_19 as BSONSymbol, bson_55 as BSON_BINARY_SUBTYPE_BYTE_ARRAY, bson_54 as BSON_BINARY_SUBTYPE_DEFAULT, bson_53 as BSON_BINARY_SUBTYPE_FUNCTION, bson_52 as BSON_BINARY_SUBTYPE_MD5, bson_51 as BSON_BINARY_SUBTYPE_USER_DEFINED, bson_50 as BSON_BINARY_SUBTYPE_UUID, bson_49 as BSON_BINARY_SUBTYPE_UUID_NEW, bson_48 as BSON_DATA_ARRAY, bson_47 as BSON_DATA_BINARY, bson_46 as BSON_DATA_BOOLEAN, bson_45 as BSON_DATA_CODE, bson_44 as BSON_DATA_CODE_W_SCOPE, bson_43 as BSON_DATA_DATE, bson_42 as BSON_DATA_DBPOINTER, bson_41 as BSON_DATA_DECIMAL128, bson_40 as BSON_DATA_INT, bson_39 as BSON_DATA_LONG, bson_38 as BSON_DATA_MAX_KEY, bson_37 as BSON_DATA_MIN_KEY, bson_36 as BSON_DATA_NULL, bson_35 as BSON_DATA_NUMBER, bson_34 as BSON_DATA_OBJECT, bson_33 as BSON_DATA_OID, bson_32 as BSON_DATA_REGEXP, bson_31 as BSON_DATA_STRING, bson_30 as BSON_DATA_SYMBOL, bson_29 as BSON_DATA_TIMESTAMP, bson_28 as BSON_DATA_UNDEFINED, bson_27 as BSON_INT32_MAX, bson_26 as BSON_INT32_MIN, bson_25 as BSON_INT64_MAX, bson_24 as BSON_INT64_MIN, bson_17 as Binary, bson_21 as Code, bson_18 as DBRef, bson_8 as Decimal128, bson_13 as Double, bson_23 as EJSON, bson_12 as Int32, bson_15 as Long, bson_22 as LongWithoutOverridesClass, bson_20 as Map, bson_10 as MaxKey, bson_11 as MinKey, bson_7 as ObjectID, bson_16 as ObjectId, bson_14 as Timestamp, bson_2 as calculateObjectSize, bson_3 as deserialize, bson_1 as deserializeStream, bson_5 as serialize, bson_4 as serializeWithBufferAndIndex, bson_6 as setInternalBufferSize };
8683//# sourceMappingURL=bson.browser.esm.js.map
8684
\No newline at end of file