Aryan commited on
Commit
4c452d5
·
1 Parent(s): 2be4436

Optimize full-stack VigilantRAG for Hugging Face Spaces deployment with MongoDB Atlas

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. Dockerfile +29 -11
  2. frontend/src/App.js +19 -17
  3. gateway/migrate.js +83 -0
  4. gateway/models/Chat.js +25 -0
  5. gateway/models/User.js +25 -0
  6. gateway/node_modules/.package-lock.json +211 -0
  7. gateway/node_modules/@mongodb-js/saslprep/LICENSE +22 -0
  8. gateway/node_modules/@mongodb-js/saslprep/package.json +87 -0
  9. gateway/node_modules/@mongodb-js/saslprep/readme.md +29 -0
  10. gateway/node_modules/@standard-schema/spec/LICENSE +21 -0
  11. gateway/node_modules/@standard-schema/spec/README.md +198 -0
  12. gateway/node_modules/@standard-schema/spec/package.json +52 -0
  13. gateway/node_modules/@types/webidl-conversions/LICENSE +21 -0
  14. gateway/node_modules/@types/webidl-conversions/README.md +15 -0
  15. gateway/node_modules/@types/webidl-conversions/index.d.ts +91 -0
  16. gateway/node_modules/@types/webidl-conversions/package.json +30 -0
  17. gateway/node_modules/@types/whatwg-url/LICENSE +21 -0
  18. gateway/node_modules/@types/whatwg-url/README.md +15 -0
  19. gateway/node_modules/@types/whatwg-url/index.d.ts +172 -0
  20. gateway/node_modules/@types/whatwg-url/package.json +38 -0
  21. gateway/node_modules/@types/whatwg-url/webidl2js-wrapper.d.ts +4 -0
  22. gateway/node_modules/bson/LICENSE.md +201 -0
  23. gateway/node_modules/bson/README.md +297 -0
  24. gateway/node_modules/bson/bson.d.ts +1901 -0
  25. gateway/node_modules/bson/etc/prepare.js +19 -0
  26. gateway/node_modules/bson/package.json +118 -0
  27. gateway/node_modules/bson/src/binary.ts +751 -0
  28. gateway/node_modules/bson/src/bson.ts +253 -0
  29. gateway/node_modules/bson/src/bson_value.ts +55 -0
  30. gateway/node_modules/bson/src/code.ts +69 -0
  31. gateway/node_modules/bson/src/constants.ts +147 -0
  32. gateway/node_modules/bson/src/db_ref.ts +128 -0
  33. gateway/node_modules/bson/src/decimal128.ts +855 -0
  34. gateway/node_modules/bson/src/double.ts +115 -0
  35. gateway/node_modules/bson/src/error.ts +105 -0
  36. gateway/node_modules/bson/src/extended_json.ts +557 -0
  37. gateway/node_modules/bson/src/index.ts +19 -0
  38. gateway/node_modules/bson/src/int_32.ts +101 -0
  39. gateway/node_modules/bson/src/long.ts +1240 -0
  40. gateway/node_modules/bson/src/max_key.ts +31 -0
  41. gateway/node_modules/bson/src/min_key.ts +31 -0
  42. gateway/node_modules/bson/src/objectid.ts +546 -0
  43. gateway/node_modules/bson/src/parse_utf8.ts +35 -0
  44. gateway/node_modules/bson/src/parser/calculate_size.ts +239 -0
  45. gateway/node_modules/bson/src/parser/deserializer.ts +793 -0
  46. gateway/node_modules/bson/src/parser/on_demand/index.ts +32 -0
  47. gateway/node_modules/bson/src/parser/on_demand/parse_to_elements.ts +190 -0
  48. gateway/node_modules/bson/src/parser/serializer.ts +748 -0
  49. gateway/node_modules/bson/src/parser/utils.ts +69 -0
  50. gateway/node_modules/bson/src/regexp.ts +114 -0
Dockerfile CHANGED
@@ -5,31 +5,49 @@ FROM python:3.11-slim
5
  ENV PYTHONUNBUFFERED=1 \
6
  PYTHONDONTWRITEBYTECODE=1 \
7
  HF_HOME=/code/.cache/huggingface \
8
- PORT=7860
 
9
 
10
  # Set the working directory
11
  WORKDIR /code
12
 
13
- # Install system dependencies (git is sometimes used by HF libraries)
14
  RUN apt-get update && apt-get install -y --no-install-recommends \
15
  git \
16
  build-essential \
 
 
 
17
  && rm -rf /var/lib/apt/lists/*
18
 
19
- # Copy requirements file first to leverage Docker layer caching
20
  COPY requirements.txt .
21
-
22
- # Install python dependencies
23
  RUN pip install --no-cache-dir --upgrade pip && \
24
  pip install --no-cache-dir -r requirements.txt
25
 
26
- # Create a writable cache directory for Hugging Face models
27
- # Hugging Face Spaces runs as user 1000, so we must make /code writable
28
- RUN mkdir -p /code/.cache/huggingface && chmod -R 777 /code
 
 
 
 
 
 
 
29
 
30
- # Copy the rest of the application files
 
 
 
31
  COPY . .
32
 
 
 
 
 
 
 
33
  # Pre-download and cache models in the container image during build time
34
  RUN python download_models.py
35
 
@@ -39,5 +57,5 @@ RUN python scratch/ingest_large_samples.py
39
  # Expose port 7860 for Hugging Face Space / external access
40
  EXPOSE 7860
41
 
42
- # Run the FastAPI application on host 0.0.0.0 and port 7860
43
- CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
 
5
  ENV PYTHONUNBUFFERED=1 \
6
  PYTHONDONTWRITEBYTECODE=1 \
7
  HF_HOME=/code/.cache/huggingface \
8
+ PORT=7860 \
9
+ NODE_ENV=production
10
 
11
  # Set the working directory
12
  WORKDIR /code
13
 
14
+ # Install system dependencies & Node.js (LTS v18)
15
  RUN apt-get update && apt-get install -y --no-install-recommends \
16
  git \
17
  build-essential \
18
+ curl \
19
+ && curl -fsSL https://deb.nodesource.com/setup_18.x | bash - \
20
+ && apt-get install -y nodejs \
21
  && rm -rf /var/lib/apt/lists/*
22
 
23
+ # 1. Install Python RAG Backend dependencies
24
  COPY requirements.txt .
 
 
25
  RUN pip install --no-cache-dir --upgrade pip && \
26
  pip install --no-cache-dir -r requirements.txt
27
 
28
+ # 2. Build React Frontend static files
29
+ COPY frontend/package*.json ./frontend/
30
+ RUN cd frontend && npm install
31
+
32
+ COPY frontend/ ./frontend/
33
+ RUN cd frontend && npm run build
34
+
35
+ # 3. Setup Node.js API Gateway
36
+ COPY gateway/package*.json ./gateway/
37
+ RUN cd gateway && npm install --production
38
 
39
+ # Copy build output from frontend to gateway's public directory
40
+ RUN mkdir -p gateway/public && cp -r frontend/build/* gateway/public/
41
+
42
+ # Copy the rest of the application files (including backends)
43
  COPY . .
44
 
45
+ # Ensure start.sh has execution permissions
46
+ RUN chmod +x start.sh
47
+
48
+ # Create a writable cache directory for Hugging Face models (user 1000 compatibility)
49
+ RUN mkdir -p /code/.cache/huggingface && chmod -R 777 /code
50
+
51
  # Pre-download and cache models in the container image during build time
52
  RUN python download_models.py
53
 
 
57
  # Expose port 7860 for Hugging Face Space / external access
58
  EXPOSE 7860
59
 
60
+ # Run the startup script to concurrently run FastAPI and Node.js
61
+ CMD ["bash", "start.sh"]
frontend/src/App.js CHANGED
@@ -6,6 +6,8 @@ import {
6
  } from 'lucide-react';
7
  import './App.css';
8
 
 
 
9
  function App() {
10
  const [token, setToken] = useState(localStorage.getItem('token') || '');
11
  const [email, setEmail] = useState('');
@@ -238,7 +240,7 @@ function App() {
238
  const targetEmail = devEmail || email;
239
  const targetPassword = devEmail ? 'password123' : password;
240
  try {
241
- const res = await fetch('http://localhost:5000/api/login', {
242
  method: 'POST',
243
  headers: { 'Content-Type': 'application/json' },
244
  body: JSON.stringify({ email: targetEmail, password: targetPassword })
@@ -283,7 +285,7 @@ function App() {
283
  }
284
 
285
  try {
286
- const res = await fetch('http://localhost:5000/api/register', {
287
  method: 'POST',
288
  headers: { 'Content-Type': 'application/json' },
289
  body: JSON.stringify({
@@ -322,7 +324,7 @@ function App() {
322
 
323
  const fetchUserStatus = async () => {
324
  try {
325
- const res = await fetch('http://localhost:5000/api/user-status', {
326
  headers: { 'Authorization': `Bearer ${token}` }
327
  });
328
  const data = await res.json();
@@ -333,7 +335,7 @@ function App() {
333
 
334
  const fetchDocuments = async () => {
335
  try {
336
- const res = await fetch('http://localhost:5000/api/documents', {
337
  headers: { 'Authorization': `Bearer ${token}` }
338
  });
339
  const data = await res.json();
@@ -351,7 +353,7 @@ function App() {
351
 
352
  const fetchChatThreads = async (projId) => {
353
  try {
354
- const res = await fetch(`http://localhost:5000/api/projects/${projId}/chats`, {
355
  headers: { 'Authorization': `Bearer ${token}` }
356
  });
357
  const data = await res.json();
@@ -363,7 +365,7 @@ function App() {
363
 
364
  const handleCreateChatThread = async (projId, threadTitle) => {
365
  try {
366
- const res = await fetch(`http://localhost:5000/api/projects/${projId}/chats`, {
367
  method: 'POST',
368
  headers: {
369
  'Content-Type': 'application/json',
@@ -380,7 +382,7 @@ function App() {
380
  const handleDeleteChatThread = async (e, threadId) => {
381
  e.stopPropagation();
382
  try {
383
- await fetch(`http://localhost:5000/api/projects/${selectedProjectId}/chats/${threadId}`, {
384
  method: 'DELETE',
385
  headers: { 'Authorization': `Bearer ${token}` }
386
  });
@@ -397,7 +399,7 @@ function App() {
397
  if (newTitle === currentTitle) return;
398
 
399
  try {
400
- const res = await fetch(`http://localhost:5000/api/projects/${selectedProjectId}/chats/${threadId}`, {
401
  method: 'PUT',
402
  headers: {
403
  'Content-Type': 'application/json',
@@ -419,7 +421,7 @@ function App() {
419
  if (!window.confirm("Are you sure you want to delete this document from the database? This will permanently wipe its text vectors and conversation history.")) return;
420
 
421
  try {
422
- const res = await fetch(`http://localhost:5000/api/documents/${docId}`, {
423
  method: 'DELETE',
424
  headers: { 'Authorization': `Bearer ${token}` }
425
  });
@@ -479,7 +481,7 @@ function App() {
479
  setQuery('');
480
  setLoading(true);
481
  try {
482
- const response = await fetch('http://localhost:5000/api/query', {
483
  method: 'POST',
484
  headers: {
485
  'Content-Type': 'application/json',
@@ -518,7 +520,7 @@ function App() {
518
  formData.append('doc_id', docId);
519
  formData.append('title', uploadTitle);
520
  try {
521
- const res = await fetch('http://localhost:5000/api/ingest-file', {
522
  method: 'POST',
523
  headers: { 'Authorization': `Bearer ${token}` },
524
  body: formData
@@ -543,7 +545,7 @@ function App() {
543
  setUploadStatus({ type: '', text: '' });
544
  const docId = `doc_${uploadTitle.toLowerCase().replace(/[^a-z0-9]/g, '_')}`;
545
  try {
546
- const res = await fetch('http://localhost:5000/api/ingest', {
547
  method: 'POST',
548
  headers: {
549
  'Content-Type': 'application/json',
@@ -568,7 +570,7 @@ function App() {
568
 
569
  const handleViewDocContent = async (docId) => {
570
  try {
571
- const res = await fetch(`http://localhost:5000/api/documents/${docId}`, {
572
  headers: { 'Authorization': `Bearer ${token}` }
573
  });
574
  const data = await res.json();
@@ -578,7 +580,7 @@ function App() {
578
 
579
  const handleUpgrade = async () => {
580
  try {
581
- const res = await fetch('http://localhost:5000/api/create-razorpay-order', {
582
  method: 'POST',
583
  headers: {
584
  'Content-Type': 'application/json',
@@ -600,7 +602,7 @@ function App() {
600
  order_id: order.id,
601
  handler: async function (response) {
602
  try {
603
- const verifyRes = await fetch("http://localhost:5000/api/verify-razorpay-payment", {
604
  method: "POST",
605
  headers: {
606
  "Content-Type": "application/json",
@@ -659,7 +661,7 @@ function App() {
659
  setProfileSaveStatus({ type: '', text: '' });
660
 
661
  try {
662
- const res = await fetch('http://localhost:5000/api/user-profile', {
663
  method: 'PUT',
664
  headers: {
665
  'Content-Type': 'application/json',
@@ -691,7 +693,7 @@ function App() {
691
  if (!confirmCancel) return;
692
 
693
  try {
694
- const res = await fetch('http://localhost:5000/api/cancel-subscription', {
695
  method: 'POST',
696
  headers: {
697
  'Authorization': `Bearer ${token}`
 
6
  } from 'lucide-react';
7
  import './App.css';
8
 
9
+ const API_URL = process.env.REACT_APP_API_URL || 'http://localhost:5000';
10
+
11
  function App() {
12
  const [token, setToken] = useState(localStorage.getItem('token') || '');
13
  const [email, setEmail] = useState('');
 
240
  const targetEmail = devEmail || email;
241
  const targetPassword = devEmail ? 'password123' : password;
242
  try {
243
+ const res = await fetch(`${API_URL}/api/login`, {
244
  method: 'POST',
245
  headers: { 'Content-Type': 'application/json' },
246
  body: JSON.stringify({ email: targetEmail, password: targetPassword })
 
285
  }
286
 
287
  try {
288
+ const res = await fetch(`${API_URL}/api/register`, {
289
  method: 'POST',
290
  headers: { 'Content-Type': 'application/json' },
291
  body: JSON.stringify({
 
324
 
325
  const fetchUserStatus = async () => {
326
  try {
327
+ const res = await fetch(`${API_URL}/api/user-status`, {
328
  headers: { 'Authorization': `Bearer ${token}` }
329
  });
330
  const data = await res.json();
 
335
 
336
  const fetchDocuments = async () => {
337
  try {
338
+ const res = await fetch(`${API_URL}/api/documents`, {
339
  headers: { 'Authorization': `Bearer ${token}` }
340
  });
341
  const data = await res.json();
 
353
 
354
  const fetchChatThreads = async (projId) => {
355
  try {
356
+ const res = await fetch(`${API_URL}/api/projects/${projId}/chats`, {
357
  headers: { 'Authorization': `Bearer ${token}` }
358
  });
359
  const data = await res.json();
 
365
 
366
  const handleCreateChatThread = async (projId, threadTitle) => {
367
  try {
368
+ const res = await fetch(`${API_URL}/api/projects/${projId}/chats`, {
369
  method: 'POST',
370
  headers: {
371
  'Content-Type': 'application/json',
 
382
  const handleDeleteChatThread = async (e, threadId) => {
383
  e.stopPropagation();
384
  try {
385
+ await fetch(`${API_URL}/api/projects/${selectedProjectId}/chats/${threadId}`, {
386
  method: 'DELETE',
387
  headers: { 'Authorization': `Bearer ${token}` }
388
  });
 
399
  if (newTitle === currentTitle) return;
400
 
401
  try {
402
+ const res = await fetch(`${API_URL}/api/projects/${selectedProjectId}/chats/${threadId}`, {
403
  method: 'PUT',
404
  headers: {
405
  'Content-Type': 'application/json',
 
421
  if (!window.confirm("Are you sure you want to delete this document from the database? This will permanently wipe its text vectors and conversation history.")) return;
422
 
423
  try {
424
+ const res = await fetch(`${API_URL}/api/documents/${docId}`, {
425
  method: 'DELETE',
426
  headers: { 'Authorization': `Bearer ${token}` }
427
  });
 
481
  setQuery('');
482
  setLoading(true);
483
  try {
484
+ const response = await fetch(`${API_URL}/api/query`, {
485
  method: 'POST',
486
  headers: {
487
  'Content-Type': 'application/json',
 
520
  formData.append('doc_id', docId);
521
  formData.append('title', uploadTitle);
522
  try {
523
+ const res = await fetch(`${API_URL}/api/ingest-file`, {
524
  method: 'POST',
525
  headers: { 'Authorization': `Bearer ${token}` },
526
  body: formData
 
545
  setUploadStatus({ type: '', text: '' });
546
  const docId = `doc_${uploadTitle.toLowerCase().replace(/[^a-z0-9]/g, '_')}`;
547
  try {
548
+ const res = await fetch(`${API_URL}/api/ingest`, {
549
  method: 'POST',
550
  headers: {
551
  'Content-Type': 'application/json',
 
570
 
571
  const handleViewDocContent = async (docId) => {
572
  try {
573
+ const res = await fetch(`${API_URL}/api/documents/${docId}`, {
574
  headers: { 'Authorization': `Bearer ${token}` }
575
  });
576
  const data = await res.json();
 
580
 
581
  const handleUpgrade = async () => {
582
  try {
583
+ const res = await fetch(`${API_URL}/api/create-razorpay-order`, {
584
  method: 'POST',
585
  headers: {
586
  'Content-Type': 'application/json',
 
602
  order_id: order.id,
603
  handler: async function (response) {
604
  try {
605
+ const verifyRes = await fetch(`${API_URL}/api/verify-razorpay-payment`, {
606
  method: "POST",
607
  headers: {
608
  "Content-Type": "application/json",
 
661
  setProfileSaveStatus({ type: '', text: '' });
662
 
663
  try {
664
+ const res = await fetch(`${API_URL}/api/user-profile`, {
665
  method: 'PUT',
666
  headers: {
667
  'Content-Type': 'application/json',
 
693
  if (!confirmCancel) return;
694
 
695
  try {
696
+ const res = await fetch(`${API_URL}/api/cancel-subscription`, {
697
  method: 'POST',
698
  headers: {
699
  'Authorization': `Bearer ${token}`
gateway/migrate.js ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const mongoose = require('mongoose');
4
+ const dotenv = require('dotenv');
5
+
6
+ // Load environment variables
7
+ dotenv.config();
8
+
9
+ const User = require('./models/User');
10
+ const ProjectChat = require('./models/Chat');
11
+
12
+ const USERS_FILE = path.join(__dirname, 'users.json');
13
+ const CHATS_FILE = path.join(__dirname, 'chats.json');
14
+
15
+ async function migrate() {
16
+ if (!process.env.MONGODB_URI) {
17
+ console.error("❌ MONGODB_URI not found in environment configurations.");
18
+ process.exit(1);
19
+ }
20
+
21
+ console.log("🌿 Connecting to MongoDB...");
22
+ await mongoose.connect(process.env.MONGODB_URI);
23
+ console.log("🌿 Connected successfully.");
24
+
25
+ // 1. Migrate Users
26
+ if (fs.existsSync(USERS_FILE)) {
27
+ try {
28
+ const rawUsers = JSON.parse(fs.readFileSync(USERS_FILE, 'utf8'));
29
+ console.log(`💼 Found ${rawUsers.length} users in users.json to migrate.`);
30
+
31
+ for (const user of rawUsers) {
32
+ const exists = await User.findOne({ userId: user.userId });
33
+ if (!exists) {
34
+ // Create new user model (preserving old plain-text passwords or bcrypt hashes as-is)
35
+ await User.create(user);
36
+ console.log(` ✅ Migrated user profile: ${user.name} (${user.email})`);
37
+ } else {
38
+ console.log(` ⏭️ User already exists in MongoDB: ${user.name} (${user.email})`);
39
+ }
40
+ }
41
+ } catch (err) {
42
+ console.error("❌ Failed migrating users:", err.message);
43
+ }
44
+ } else {
45
+ console.log("⏭️ No users.json file found to migrate.");
46
+ }
47
+
48
+ // 2. Migrate Chats
49
+ if (fs.existsSync(CHATS_FILE)) {
50
+ try {
51
+ const chatsDb = JSON.parse(fs.readFileSync(CHATS_FILE, 'utf8'));
52
+ let threadCount = 0;
53
+
54
+ for (const userId of Object.keys(chatsDb)) {
55
+ for (const projectId of Object.keys(chatsDb[userId])) {
56
+ const exists = await ProjectChat.findOne({ userId, projectId });
57
+ if (!exists) {
58
+ const projectData = chatsDb[userId][projectId];
59
+ await ProjectChat.create({
60
+ userId,
61
+ projectId,
62
+ chats: projectData.chats || []
63
+ });
64
+ threadCount += (projectData.chats || []).length;
65
+ console.log(` ✅ Migrated project workspace chats for User: ${userId}, Project: ${projectId}`);
66
+ } else {
67
+ console.log(` ⏭️ Project chat already exists in MongoDB for User: ${userId}, Project: ${projectId}`);
68
+ }
69
+ }
70
+ }
71
+ console.log(`💼 Migrated total of ${threadCount} chat threads to MongoDB.`);
72
+ } catch (err) {
73
+ console.error("❌ Failed migrating chats:", err.message);
74
+ }
75
+ } else {
76
+ console.log("⏭️ No chats.json file found to migrate.");
77
+ }
78
+
79
+ console.log("\n🎉 Migration completed successfully!");
80
+ mongoose.connection.close();
81
+ }
82
+
83
+ migrate();
gateway/models/Chat.js ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const mongoose = require('mongoose');
2
+
3
+ const messageSchema = new mongoose.Schema({
4
+ sender: { type: String, enum: ['user', 'ai'], required: true },
5
+ text: { type: String, required: true },
6
+ timestamp: { type: Date, default: Date.now },
7
+ telemetry: { type: mongoose.Schema.Types.Mixed } // Multi-source metadata storage
8
+ });
9
+
10
+ const threadSchema = new mongoose.Schema({
11
+ chatId: { type: String, required: true },
12
+ chatTitle: { type: String, required: true },
13
+ messages: [messageSchema]
14
+ });
15
+
16
+ const projectChatSchema = new mongoose.Schema({
17
+ userId: { type: String, required: true },
18
+ projectId: { type: String, required: true }, // active document workspace ID
19
+ chats: [threadSchema]
20
+ }, { timestamps: true });
21
+
22
+ // Dynamic indexes for fast lookups
23
+ projectChatSchema.index({ userId: 1, projectId: 1 }, { unique: true });
24
+
25
+ module.exports = mongoose.model('ProjectChat', projectChatSchema);
gateway/models/User.js ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const mongoose = require('mongoose');
2
+
3
+ const documentSchema = new mongoose.Schema({
4
+ id: { type: String, required: true },
5
+ name: { type: String, required: true },
6
+ sizeBytes: { type: Number, required: true },
7
+ uploadedAt: { type: Date, default: Date.now }
8
+ });
9
+
10
+ const userSchema = new mongoose.Schema({
11
+ userId: { type: String, required: true, unique: true },
12
+ name: { type: String, required: true },
13
+ email: { type: String, required: true, unique: true, lowercase: true, trim: true },
14
+ password: { type: String, required: true }, // bcrypt hashed passwords
15
+ isPremium: { type: Boolean, default: false },
16
+ queryCount: { type: Number, default: 0 },
17
+ totalStorageBytes: { type: Number, default: 0 },
18
+ uploadedDocuments: [documentSchema],
19
+ profilePhoto: { type: String, default: '👨‍💻' },
20
+ phoneNumber: { type: String, default: '' },
21
+ razorpayPaymentId: { type: String },
22
+ stripeCustomerId: { type: String }
23
+ }, { timestamps: true }); // Auto adds createdAt & updatedAt fields
24
+
25
+ module.exports = mongoose.model('User', userSchema);
gateway/node_modules/.package-lock.json CHANGED
@@ -4,6 +4,36 @@
4
  "lockfileVersion": 3,
5
  "requires": true,
6
  "packages": {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  "node_modules/accepts": {
8
  "version": "2.0.0",
9
  "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",
@@ -99,6 +129,15 @@
99
  "url": "https://opencollective.com/express"
100
  }
101
  },
 
 
 
 
 
 
 
 
 
102
  "node_modules/buffer-equal-constant-time": {
103
  "version": "1.0.1",
104
  "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
@@ -766,6 +805,15 @@
766
  "safe-buffer": "^5.0.1"
767
  }
768
  },
 
 
 
 
 
 
 
 
 
769
  "node_modules/lodash.includes": {
770
  "version": "4.3.0",
771
  "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
@@ -830,6 +878,12 @@
830
  "url": "https://opencollective.com/express"
831
  }
832
  },
 
 
 
 
 
 
833
  "node_modules/merge-descriptors": {
834
  "version": "2.0.0",
835
  "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",
@@ -867,6 +921,105 @@
867
  "url": "https://opencollective.com/express"
868
  }
869
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
870
  "node_modules/ms": {
871
  "version": "2.1.3",
872
  "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
@@ -1027,6 +1180,15 @@
1027
  "node": ">=10"
1028
  }
1029
  },
 
 
 
 
 
 
 
 
 
1030
  "node_modules/qs": {
1031
  "version": "6.15.3",
1032
  "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz",
@@ -1271,6 +1433,21 @@
1271
  "url": "https://github.com/sponsors/ljharb"
1272
  }
1273
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1274
  "node_modules/statuses": {
1275
  "version": "2.0.2",
1276
  "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
@@ -1323,6 +1500,18 @@
1323
  "node": ">=0.6"
1324
  }
1325
  },
 
 
 
 
 
 
 
 
 
 
 
 
1326
  "node_modules/type-is": {
1327
  "version": "2.1.0",
1328
  "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",
@@ -1384,6 +1573,28 @@
1384
  "node": ">= 0.8"
1385
  }
1386
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1387
  "node_modules/wrappy": {
1388
  "version": "1.0.2",
1389
  "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
 
4
  "lockfileVersion": 3,
5
  "requires": true,
6
  "packages": {
7
+ "node_modules/@mongodb-js/saslprep": {
8
+ "version": "1.4.13",
9
+ "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.4.13.tgz",
10
+ "integrity": "sha512-E3Sv4eCYAlKYUTx8S3ioQcDUscOif+8zZ5OnW1IzJ+Tt+EO+ke8mn+Y3FX6N1H79picwbdOavVOb1jPi2EOyrg==",
11
+ "license": "MIT",
12
+ "dependencies": {
13
+ "sparse-bitfield": "^3.0.3"
14
+ }
15
+ },
16
+ "node_modules/@standard-schema/spec": {
17
+ "version": "1.1.0",
18
+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
19
+ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
20
+ "license": "MIT"
21
+ },
22
+ "node_modules/@types/webidl-conversions": {
23
+ "version": "7.0.3",
24
+ "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz",
25
+ "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==",
26
+ "license": "MIT"
27
+ },
28
+ "node_modules/@types/whatwg-url": {
29
+ "version": "13.0.0",
30
+ "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-13.0.0.tgz",
31
+ "integrity": "sha512-N8WXpbE6Wgri7KUSvrmQcqrMllKZ9uxkYWMt+mCSGwNc0Hsw9VQTW7ApqI4XNrx6/SaM2QQJCzMPDEXE058s+Q==",
32
+ "license": "MIT",
33
+ "dependencies": {
34
+ "@types/webidl-conversions": "*"
35
+ }
36
+ },
37
  "node_modules/accepts": {
38
  "version": "2.0.0",
39
  "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",
 
129
  "url": "https://opencollective.com/express"
130
  }
131
  },
132
+ "node_modules/bson": {
133
+ "version": "7.3.2",
134
+ "resolved": "https://registry.npmjs.org/bson/-/bson-7.3.2.tgz",
135
+ "integrity": "sha512-1w0ra+ho1cuE+w8jzwgzTFIimFtCfZeCoOsvIPQg6uyFCsp8M29U7bNNf5GrFh88TXbYg1g3TyKUGpd6O7q6zA==",
136
+ "license": "Apache-2.0",
137
+ "engines": {
138
+ "node": ">=20.19.0"
139
+ }
140
+ },
141
  "node_modules/buffer-equal-constant-time": {
142
  "version": "1.0.1",
143
  "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
 
805
  "safe-buffer": "^5.0.1"
806
  }
807
  },
808
+ "node_modules/kareem": {
809
+ "version": "3.3.0",
810
+ "resolved": "https://registry.npmjs.org/kareem/-/kareem-3.3.0.tgz",
811
+ "integrity": "sha512-kpSuLD3/7RenBnjnJdOHXCKC8dTd1JzeOiJhN0necWWci6cC+qX+VuwPnMVgb+a4+KNJSfgqahpnfWaeDXCimw==",
812
+ "license": "Apache-2.0",
813
+ "engines": {
814
+ "node": ">=18.0.0"
815
+ }
816
+ },
817
  "node_modules/lodash.includes": {
818
  "version": "4.3.0",
819
  "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
 
878
  "url": "https://opencollective.com/express"
879
  }
880
  },
881
+ "node_modules/memory-pager": {
882
+ "version": "1.5.0",
883
+ "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz",
884
+ "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==",
885
+ "license": "MIT"
886
+ },
887
  "node_modules/merge-descriptors": {
888
  "version": "2.0.0",
889
  "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",
 
921
  "url": "https://opencollective.com/express"
922
  }
923
  },
924
+ "node_modules/mongodb": {
925
+ "version": "7.5.0",
926
+ "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-7.5.0.tgz",
927
+ "integrity": "sha512-5FnrEDLnvp6ycUOGLNLLU33BfCx2qmp2mJjGPDwKLruYsVzXVSK5fsGpoDXvsXJwBfBsD7ebMRdawbDxC2814g==",
928
+ "license": "Apache-2.0",
929
+ "dependencies": {
930
+ "@mongodb-js/saslprep": "^1.4.11",
931
+ "bson": "^7.2.0",
932
+ "mongodb-connection-string-url": "^7.0.1"
933
+ },
934
+ "engines": {
935
+ "node": ">=20.19.0"
936
+ },
937
+ "peerDependencies": {
938
+ "@aws-sdk/credential-providers": "^3.806.0",
939
+ "@mongodb-js/zstd": "^7.0.0",
940
+ "gcp-metadata": "^7.0.1",
941
+ "kerberos": "^7.0.0",
942
+ "mongodb-client-encryption": "^7.2.0",
943
+ "snappy": "^7.3.2",
944
+ "socks": "^2.8.6"
945
+ },
946
+ "peerDependenciesMeta": {
947
+ "@aws-sdk/credential-providers": {
948
+ "optional": true
949
+ },
950
+ "@mongodb-js/zstd": {
951
+ "optional": true
952
+ },
953
+ "gcp-metadata": {
954
+ "optional": true
955
+ },
956
+ "kerberos": {
957
+ "optional": true
958
+ },
959
+ "mongodb-client-encryption": {
960
+ "optional": true
961
+ },
962
+ "snappy": {
963
+ "optional": true
964
+ },
965
+ "socks": {
966
+ "optional": true
967
+ }
968
+ }
969
+ },
970
+ "node_modules/mongodb-connection-string-url": {
971
+ "version": "7.0.2",
972
+ "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-7.0.2.tgz",
973
+ "integrity": "sha512-ZoS07RoFqpKYQwAk59qmrx8+jJHNHU30UjlU96QktiGn1ltvDr+vCznLX5DiUBLEpMAHatHNWV1nM/74ul66kA==",
974
+ "license": "Apache-2.0",
975
+ "dependencies": {
976
+ "@types/whatwg-url": "^13.0.0",
977
+ "whatwg-url": "^14.1.0"
978
+ },
979
+ "engines": {
980
+ "node": ">=20.19.0"
981
+ }
982
+ },
983
+ "node_modules/mongoose": {
984
+ "version": "9.9.3",
985
+ "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-9.9.3.tgz",
986
+ "integrity": "sha512-9dQaKct05LNgVkunDzFPZsGGBhinobl3Qc5B5KYJkLNG5lBLgqESUEItl1EUIkVaCwZJGBgTuvJiFAjjIATCiw==",
987
+ "license": "MIT",
988
+ "dependencies": {
989
+ "@standard-schema/spec": "^1.1.0",
990
+ "kareem": "3.3.0",
991
+ "mongodb": "~7.5",
992
+ "mpath": "0.9.0",
993
+ "mquery": "6.0.0",
994
+ "ms": "2.1.3",
995
+ "sift": "17.1.3"
996
+ },
997
+ "engines": {
998
+ "node": ">=20.19.0"
999
+ },
1000
+ "funding": {
1001
+ "type": "opencollective",
1002
+ "url": "https://opencollective.com/mongoose"
1003
+ }
1004
+ },
1005
+ "node_modules/mpath": {
1006
+ "version": "0.9.0",
1007
+ "resolved": "https://registry.npmjs.org/mpath/-/mpath-0.9.0.tgz",
1008
+ "integrity": "sha512-ikJRQTk8hw5DEoFVxHG1Gn9T/xcjtdnOKIU1JTmGjZZlg9LST2mBLmcX3/ICIbgJydT2GOc15RnNy5mHmzfSew==",
1009
+ "license": "MIT",
1010
+ "engines": {
1011
+ "node": ">=4.0.0"
1012
+ }
1013
+ },
1014
+ "node_modules/mquery": {
1015
+ "version": "6.0.0",
1016
+ "resolved": "https://registry.npmjs.org/mquery/-/mquery-6.0.0.tgz",
1017
+ "integrity": "sha512-b2KQNsmgtkscfeDgkYMcWGn9vZI9YoXh802VDEwE6qc50zxBFQ0Oo8ROkawbPAsXCY1/Z1yp0MagqsZStPWJjw==",
1018
+ "license": "MIT",
1019
+ "engines": {
1020
+ "node": ">=20.19.0"
1021
+ }
1022
+ },
1023
  "node_modules/ms": {
1024
  "version": "2.1.3",
1025
  "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
 
1180
  "node": ">=10"
1181
  }
1182
  },
1183
+ "node_modules/punycode": {
1184
+ "version": "2.3.1",
1185
+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
1186
+ "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
1187
+ "license": "MIT",
1188
+ "engines": {
1189
+ "node": ">=6"
1190
+ }
1191
+ },
1192
  "node_modules/qs": {
1193
  "version": "6.15.3",
1194
  "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz",
 
1433
  "url": "https://github.com/sponsors/ljharb"
1434
  }
1435
  },
1436
+ "node_modules/sift": {
1437
+ "version": "17.1.3",
1438
+ "resolved": "https://registry.npmjs.org/sift/-/sift-17.1.3.tgz",
1439
+ "integrity": "sha512-Rtlj66/b0ICeFzYTuNvX/EF1igRbbnGSvEyT79McoZa/DeGhMyC5pWKOEsZKnpkqtSeovd5FL/bjHWC3CIIvCQ==",
1440
+ "license": "MIT"
1441
+ },
1442
+ "node_modules/sparse-bitfield": {
1443
+ "version": "3.0.3",
1444
+ "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz",
1445
+ "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==",
1446
+ "license": "MIT",
1447
+ "dependencies": {
1448
+ "memory-pager": "^1.0.2"
1449
+ }
1450
+ },
1451
  "node_modules/statuses": {
1452
  "version": "2.0.2",
1453
  "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
 
1500
  "node": ">=0.6"
1501
  }
1502
  },
1503
+ "node_modules/tr46": {
1504
+ "version": "5.1.1",
1505
+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz",
1506
+ "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==",
1507
+ "license": "MIT",
1508
+ "dependencies": {
1509
+ "punycode": "^2.3.1"
1510
+ },
1511
+ "engines": {
1512
+ "node": ">=18"
1513
+ }
1514
+ },
1515
  "node_modules/type-is": {
1516
  "version": "2.1.0",
1517
  "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",
 
1573
  "node": ">= 0.8"
1574
  }
1575
  },
1576
+ "node_modules/webidl-conversions": {
1577
+ "version": "7.0.0",
1578
+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",
1579
+ "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==",
1580
+ "license": "BSD-2-Clause",
1581
+ "engines": {
1582
+ "node": ">=12"
1583
+ }
1584
+ },
1585
+ "node_modules/whatwg-url": {
1586
+ "version": "14.2.0",
1587
+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz",
1588
+ "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==",
1589
+ "license": "MIT",
1590
+ "dependencies": {
1591
+ "tr46": "^5.1.0",
1592
+ "webidl-conversions": "^7.0.0"
1593
+ },
1594
+ "engines": {
1595
+ "node": ">=18"
1596
+ }
1597
+ },
1598
  "node_modules/wrappy": {
1599
  "version": "1.0.2",
1600
  "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
gateway/node_modules/@mongodb-js/saslprep/LICENSE ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2014 Dmitry Tsvettsikh
2
+
3
+ Permission is hereby granted, free of charge, to any person
4
+ obtaining a copy of this software and associated documentation
5
+ files (the "Software"), to deal in the Software without
6
+ restriction, including without limitation the rights to use,
7
+ copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ copies of the Software, and to permit persons to whom the
9
+ Software is furnished to do so, subject to the following
10
+ conditions:
11
+
12
+ The above copyright notice and this permission notice shall be
13
+ included in all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
17
+ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
gateway/node_modules/@mongodb-js/saslprep/package.json ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@mongodb-js/saslprep",
3
+ "description": "SASLprep: Stringprep Profile for User Names and Passwords, rfc4013",
4
+ "keywords": [
5
+ "sasl",
6
+ "saslprep",
7
+ "stringprep",
8
+ "rfc4013",
9
+ "4013"
10
+ ],
11
+ "author": "Dmitry Tsvettsikh <me@reklatsmasters.com>",
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
15
+ "main": "dist/node.js",
16
+ "bugs": {
17
+ "url": "https://jira.mongodb.org/projects/COMPASS/issues",
18
+ "email": "compass@mongodb.com"
19
+ },
20
+ "homepage": "https://github.com/mongodb-js/devtools-shared/tree/main/packages/saslprep",
21
+ "version": "1.4.13",
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/mongodb-js/devtools-shared.git"
25
+ },
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "license": "MIT",
30
+ "exports": {
31
+ "browser": {
32
+ "types": "./dist/browser.d.ts",
33
+ "default": "./dist/browser.js"
34
+ },
35
+ "import": {
36
+ "types": "./dist/node.d.ts",
37
+ "default": "./dist/.esm-wrapper.mjs"
38
+ },
39
+ "require": {
40
+ "types": "./dist/node.d.ts",
41
+ "default": "./dist/node.js"
42
+ }
43
+ },
44
+ "types": "./dist/node.d.ts",
45
+ "scripts": {
46
+ "gen-code-points": "ts-node src/generate-code-points.ts src/code-points-data.ts src/code-points-data-browser.ts",
47
+ "bootstrap": "npm run compile",
48
+ "prepublishOnly": "npm run compile",
49
+ "compile": "npm run gen-code-points && tsc -p tsconfig.json && gen-esm-wrapper . ./dist/.esm-wrapper.mjs",
50
+ "typecheck": "tsc --noEmit",
51
+ "eslint": "eslint",
52
+ "prettier": "prettier",
53
+ "lint": "npm run eslint . && npm run prettier -- --check .",
54
+ "depcheck": "depcheck",
55
+ "check": "npm run typecheck && npm run lint && npm run depcheck",
56
+ "check-ci": "npm run check",
57
+ "test": "mocha",
58
+ "test-cov": "nyc -x \"**/*.spec.*\" --reporter=lcov --reporter=text --reporter=html npm run test",
59
+ "test-watch": "npm run test -- --watch",
60
+ "test-ci": "npm run test-cov",
61
+ "reformat": "npm run prettier -- --write ."
62
+ },
63
+ "dependencies": {
64
+ "sparse-bitfield": "^3.0.3"
65
+ },
66
+ "devDependencies": {
67
+ "@mongodb-js/eslint-config-devtools": "^0.11.8",
68
+ "@mongodb-js/mocha-config-devtools": "^1.1.3",
69
+ "@mongodb-js/prettier-config-devtools": "^1.0.4",
70
+ "@mongodb-js/tsconfig-devtools": "^1.1.3",
71
+ "@types/chai": "^4.2.21",
72
+ "@types/mocha": "^9.1.1",
73
+ "@types/node": "^25.5.2",
74
+ "@types/sinon-chai": "^4.0.0",
75
+ "@types/sparse-bitfield": "^3.0.4",
76
+ "chai": "^4.5.0",
77
+ "depcheck": "^1.4.7",
78
+ "eslint": "^7.25.0 || ^8.0.0",
79
+ "gen-esm-wrapper": "^1.1.3",
80
+ "mocha": "^8.4.0",
81
+ "nyc": "^15.1.0",
82
+ "prettier": "^3.8.1",
83
+ "sinon": "^9.2.3",
84
+ "typescript": "^5.9.3"
85
+ },
86
+ "gitHead": "58acee6dbcadb316e3fd3d52bd97c2bd31d621cc"
87
+ }
gateway/node_modules/@mongodb-js/saslprep/readme.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # saslprep
2
+
3
+ _Note: This is a fork of the original [`saslprep`](https://www.npmjs.com/package/saslprep) npm package
4
+ and provides equivalent functionality._
5
+
6
+ Stringprep Profile for User Names and Passwords, [rfc4013](https://tools.ietf.org/html/rfc4013)
7
+
8
+ ### Usage
9
+
10
+ ```js
11
+ const saslprep = require('@mongodb-js/saslprep');
12
+
13
+ saslprep('password\u00AD'); // password
14
+ saslprep('password\u0007'); // Error: prohibited character
15
+ ```
16
+
17
+ ### API
18
+
19
+ ##### `saslprep(input: String, opts: Options): String`
20
+
21
+ Normalize user name or password.
22
+
23
+ ##### `Options.allowUnassigned: bool`
24
+
25
+ A special behavior for unassigned code points, see https://tools.ietf.org/html/rfc4013#section-2.5. Disabled by default.
26
+
27
+ ## License
28
+
29
+ MIT, 2017-2019 (c) Dmitriy Tsvettsikh
gateway/node_modules/@standard-schema/spec/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Colin McDonnell
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
gateway/node_modules/@standard-schema/spec/README.md ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <h1 align="center">
2
+ <img alt="Standard Schema fire logo" loading="lazy" width="50" height="50" decoding="async" data-nimg="1" style="color:transparent" src="https://standardschema.dev/favicon.svg">
3
+ </br>
4
+ Standard Schema</h1>
5
+ <p align="center">
6
+ A family of specs for interoperable TypeScript
7
+ <br/>
8
+ <a href="https://standardschema.dev">standardschema.dev</a>
9
+ </p>
10
+ <br/>
11
+
12
+ <!-- start -->
13
+
14
+ The Standard Schema project is a set of interfaces that standardize the provision and consumption of shared functionality in the TypeScript ecosystem.
15
+
16
+ Its goal is to allow tools to accept a single input that includes all the types and capabilities they need— no library-specific adapters, no extra dependencies. The result is an ecosystem that's fair for implementers, friendly for consumers, and open for end users.
17
+
18
+ ## The specifications
19
+
20
+ The specifications can be found below in their entirety. Libraries wishing to implement a spec can copy/paste the code block below into their codebase. They're also available at `@standard-schema/spec` on [npm](https://www.npmjs.com/package/@standard-schema/spec) and [JSR](https://jsr.io/@standard-schema/spec).
21
+
22
+ ```ts
23
+ // #########################
24
+ // ### Standard Typed ###
25
+ // #########################
26
+
27
+ /** The Standard Typed interface. This is a base type extended by other specs. */
28
+ export interface StandardTypedV1<Input = unknown, Output = Input> {
29
+ /** The Standard properties. */
30
+ readonly "~standard": StandardTypedV1.Props<Input, Output>;
31
+ }
32
+
33
+ export declare namespace StandardTypedV1 {
34
+ /** The Standard Typed properties interface. */
35
+ export interface Props<Input = unknown, Output = Input> {
36
+ /** The version number of the standard. */
37
+ readonly version: 1;
38
+ /** The vendor name of the schema library. */
39
+ readonly vendor: string;
40
+ /** Inferred types associated with the schema. */
41
+ readonly types?: Types<Input, Output> | undefined;
42
+ }
43
+
44
+ /** The Standard Typed types interface. */
45
+ export interface Types<Input = unknown, Output = Input> {
46
+ /** The input type of the schema. */
47
+ readonly input: Input;
48
+ /** The output type of the schema. */
49
+ readonly output: Output;
50
+ }
51
+
52
+ /** Infers the input type of a Standard Typed. */
53
+ export type InferInput<Schema extends StandardTypedV1> = NonNullable<
54
+ Schema["~standard"]["types"]
55
+ >["input"];
56
+
57
+ /** Infers the output type of a Standard Typed. */
58
+ export type InferOutput<Schema extends StandardTypedV1> = NonNullable<
59
+ Schema["~standard"]["types"]
60
+ >["output"];
61
+ }
62
+
63
+ // ##########################
64
+ // ### Standard Schema ###
65
+ // ##########################
66
+
67
+ /** The Standard Schema interface. */
68
+ export interface StandardSchemaV1<Input = unknown, Output = Input> {
69
+ /** The Standard Schema properties. */
70
+ readonly "~standard": StandardSchemaV1.Props<Input, Output>;
71
+ }
72
+
73
+ export declare namespace StandardSchemaV1 {
74
+ /** The Standard Schema properties interface. */
75
+ export interface Props<Input = unknown, Output = Input>
76
+ extends StandardTypedV1.Props<Input, Output> {
77
+ /** Validates unknown input values. */
78
+ readonly validate: (
79
+ value: unknown,
80
+ options?: StandardSchemaV1.Options | undefined
81
+ ) => Result<Output> | Promise<Result<Output>>;
82
+ }
83
+
84
+ /** The result interface of the validate function. */
85
+ export type Result<Output> = SuccessResult<Output> | FailureResult;
86
+
87
+ /** The result interface if validation succeeds. */
88
+ export interface SuccessResult<Output> {
89
+ /** The typed output value. */
90
+ readonly value: Output;
91
+ /** A falsy value for `issues` indicates success. */
92
+ readonly issues?: undefined;
93
+ }
94
+
95
+ export interface Options {
96
+ /** Explicit support for additional vendor-specific parameters, if needed. */
97
+ readonly libraryOptions?: Record<string, unknown> | undefined;
98
+ }
99
+
100
+ /** The result interface if validation fails. */
101
+ export interface FailureResult {
102
+ /** The issues of failed validation. */
103
+ readonly issues: ReadonlyArray<Issue>;
104
+ }
105
+
106
+ /** The issue interface of the failure output. */
107
+ export interface Issue {
108
+ /** The error message of the issue. */
109
+ readonly message: string;
110
+ /** The path of the issue, if any. */
111
+ readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
112
+ }
113
+
114
+ /** The path segment interface of the issue. */
115
+ export interface PathSegment {
116
+ /** The key representing a path segment. */
117
+ readonly key: PropertyKey;
118
+ }
119
+
120
+ /** The Standard types interface. */
121
+ export interface Types<Input = unknown, Output = Input>
122
+ extends StandardTypedV1.Types<Input, Output> {}
123
+
124
+ /** Infers the input type of a Standard. */
125
+ export type InferInput<Schema extends StandardTypedV1> =
126
+ StandardTypedV1.InferInput<Schema>;
127
+
128
+ /** Infers the output type of a Standard. */
129
+ export type InferOutput<Schema extends StandardTypedV1> =
130
+ StandardTypedV1.InferOutput<Schema>;
131
+ }
132
+
133
+ // ###############################
134
+ // ### Standard JSON Schema ###
135
+ // ###############################
136
+
137
+ /** The Standard JSON Schema interface. */
138
+ export interface StandardJSONSchemaV1<Input = unknown, Output = Input> {
139
+ /** The Standard JSON Schema properties. */
140
+ readonly "~standard": StandardJSONSchemaV1.Props<Input, Output>;
141
+ }
142
+
143
+ export declare namespace StandardJSONSchemaV1 {
144
+ /** The Standard JSON Schema properties interface. */
145
+ export interface Props<Input = unknown, Output = Input>
146
+ extends StandardTypedV1.Props<Input, Output> {
147
+ /** Methods for generating the input/output JSON Schema. */
148
+ readonly jsonSchema: StandardJSONSchemaV1.Converter;
149
+ }
150
+
151
+ /** The Standard JSON Schema converter interface. */
152
+ export interface Converter {
153
+ /** Converts the input type to JSON Schema. May throw if conversion is not supported. */
154
+ readonly input: (
155
+ options: StandardJSONSchemaV1.Options
156
+ ) => Record<string, unknown>;
157
+ /** Converts the output type to JSON Schema. May throw if conversion is not supported. */
158
+ readonly output: (
159
+ options: StandardJSONSchemaV1.Options
160
+ ) => Record<string, unknown>;
161
+ }
162
+
163
+ /**
164
+ * The target version of the generated JSON Schema.
165
+ *
166
+ * It is *strongly recommended* that implementers support `"draft-2020-12"` and `"draft-07"`, as they are both in wide use. All other targets can be implemented on a best-effort basis. Libraries should throw if they don't support a specified target.
167
+ *
168
+ * The `"openapi-3.0"` target is intended as a standardized specifier for OpenAPI 3.0 which is a superset of JSON Schema `"draft-04"`.
169
+ */
170
+ export type Target =
171
+ | "draft-2020-12"
172
+ | "draft-07"
173
+ | "openapi-3.0"
174
+ // Accepts any string for future targets while preserving autocomplete
175
+ | ({} & string);
176
+
177
+ /** The options for the input/output methods. */
178
+ export interface Options {
179
+ /** Specifies the target version of the generated JSON Schema. Support for all versions is on a best-effort basis. If a given version is not supported, the library should throw. */
180
+ readonly target: Target;
181
+
182
+ /** Explicit support for additional vendor-specific parameters, if needed. */
183
+ readonly libraryOptions?: Record<string, unknown> | undefined;
184
+ }
185
+
186
+ /** The Standard types interface. */
187
+ export interface Types<Input = unknown, Output = Input>
188
+ extends StandardTypedV1.Types<Input, Output> {}
189
+
190
+ /** Infers the input type of a Standard. */
191
+ export type InferInput<Schema extends StandardTypedV1> =
192
+ StandardTypedV1.InferInput<Schema>;
193
+
194
+ /** Infers the output type of a Standard. */
195
+ export type InferOutput<Schema extends StandardTypedV1> =
196
+ StandardTypedV1.InferOutput<Schema>;
197
+ }
198
+ ```
gateway/node_modules/@standard-schema/spec/package.json ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@standard-schema/spec",
3
+ "description": "A family of specs for interoperable TypeScript",
4
+ "version": "1.1.0",
5
+ "license": "MIT",
6
+ "author": "Colin McDonnell",
7
+ "homepage": "https://standardschema.dev",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/standard-schema/standard-schema"
11
+ },
12
+ "keywords": [
13
+ "typescript",
14
+ "schema",
15
+ "validation",
16
+ "standard",
17
+ "interface"
18
+ ],
19
+ "type": "module",
20
+ "main": "./dist/index.js",
21
+ "types": "./dist/index.d.ts",
22
+ "exports": {
23
+ ".": {
24
+ "standard-schema-spec": "./src/index.ts",
25
+ "import": {
26
+ "types": "./dist/index.d.ts",
27
+ "default": "./dist/index.js"
28
+ },
29
+ "require": {
30
+ "types": "./dist/index.d.cts",
31
+ "default": "./dist/index.cjs"
32
+ }
33
+ }
34
+ },
35
+ "sideEffects": false,
36
+ "files": [
37
+ "dist"
38
+ ],
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "devDependencies": {
43
+ "tsup": "^8.3.0",
44
+ "typescript": "^5.6.2"
45
+ },
46
+ "scripts": {
47
+ "lint": "pnpm biome lint ./src",
48
+ "format": "pnpm biome format --write ./src",
49
+ "check": "pnpm biome check ./src",
50
+ "build": "tsup"
51
+ }
52
+ }
gateway/node_modules/@types/webidl-conversions/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) Microsoft Corporation.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE
gateway/node_modules/@types/webidl-conversions/README.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Installation
2
+ > `npm install --save @types/webidl-conversions`
3
+
4
+ # Summary
5
+ This package contains type definitions for webidl-conversions (https://github.com/jsdom/webidl-conversions#readme).
6
+
7
+ # Details
8
+ Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/webidl-conversions.
9
+
10
+ ### Additional Details
11
+ * Last updated: Tue, 07 Nov 2023 15:11:36 GMT
12
+ * Dependencies: none
13
+
14
+ # Credits
15
+ These definitions were written by [ExE Boss](https://github.com/ExE-Boss), and [BendingBender](https://github.com/BendingBender).
gateway/node_modules/@types/webidl-conversions/index.d.ts ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ declare namespace WebIDLConversions {
2
+ interface Globals {
3
+ [key: string]: unknown;
4
+
5
+ Number: (value?: unknown) => number;
6
+ String: (value?: unknown) => string;
7
+ TypeError: new(message?: string) => TypeError;
8
+ }
9
+
10
+ interface Options {
11
+ context?: string | undefined;
12
+ globals?: Globals | undefined;
13
+ }
14
+
15
+ interface IntegerOptions extends Options {
16
+ enforceRange?: boolean | undefined;
17
+ clamp?: boolean | undefined;
18
+ }
19
+
20
+ interface StringOptions extends Options {
21
+ treatNullAsEmptyString?: boolean | undefined;
22
+ }
23
+
24
+ interface BufferSourceOptions extends Options {
25
+ allowShared?: boolean | undefined;
26
+ }
27
+
28
+ type IntegerConversion = (V: unknown, opts?: IntegerOptions) => number;
29
+ type StringConversion = (V: unknown, opts?: StringOptions) => string;
30
+ type NumberConversion = (V: unknown, opts?: Options) => number;
31
+ }
32
+
33
+ declare const WebIDLConversions: {
34
+ any<V>(V: V, opts?: WebIDLConversions.Options): V;
35
+ undefined(V?: unknown, opts?: WebIDLConversions.Options): void;
36
+ boolean(V: unknown, opts?: WebIDLConversions.Options): boolean;
37
+
38
+ byte(V: unknown, opts?: WebIDLConversions.IntegerOptions): number;
39
+ octet(V: unknown, opts?: WebIDLConversions.IntegerOptions): number;
40
+
41
+ short(V: unknown, opts?: WebIDLConversions.IntegerOptions): number;
42
+ ["unsigned short"](V: unknown, opts?: WebIDLConversions.IntegerOptions): number;
43
+
44
+ long(V: unknown, opts?: WebIDLConversions.IntegerOptions): number;
45
+ ["unsigned long"](V: unknown, opts?: WebIDLConversions.IntegerOptions): number;
46
+
47
+ ["long long"](V: unknown, opts?: WebIDLConversions.IntegerOptions): number;
48
+ ["unsigned long long"](V: unknown, opts?: WebIDLConversions.IntegerOptions): number;
49
+
50
+ double(V: unknown, opts?: WebIDLConversions.Options): number;
51
+ ["unrestricted double"](V: unknown, opts?: WebIDLConversions.Options): number;
52
+
53
+ float(V: unknown, opts?: WebIDLConversions.Options): number;
54
+ ["unrestricted float"](V: unknown, opts?: WebIDLConversions.Options): number;
55
+
56
+ DOMString(V: unknown, opts?: WebIDLConversions.StringOptions): string;
57
+ ByteString(V: unknown, opts?: WebIDLConversions.StringOptions): string;
58
+ USVString(V: unknown, opts?: WebIDLConversions.StringOptions): string;
59
+
60
+ object<V>(V: V, opts?: WebIDLConversions.Options): V extends object ? V : V & object;
61
+ ArrayBuffer(
62
+ V: unknown,
63
+ opts?: WebIDLConversions.BufferSourceOptions & { allowShared?: false | undefined },
64
+ ): ArrayBuffer;
65
+ ArrayBuffer(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): ArrayBufferLike;
66
+ DataView(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): DataView;
67
+
68
+ Int8Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Int8Array;
69
+ Int16Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Int16Array;
70
+ Int32Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Int32Array;
71
+
72
+ Uint8Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Uint8Array;
73
+ Uint16Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Uint16Array;
74
+ Uint32Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Uint32Array;
75
+ Uint8ClampedArray(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Uint8ClampedArray;
76
+
77
+ Float32Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Float32Array;
78
+ Float64Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Float64Array;
79
+
80
+ ArrayBufferView(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): ArrayBufferView;
81
+ BufferSource(
82
+ V: unknown,
83
+ opts?: WebIDLConversions.BufferSourceOptions & { allowShared?: false | undefined },
84
+ ): ArrayBuffer | ArrayBufferView;
85
+ BufferSource(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): ArrayBufferLike | ArrayBufferView;
86
+
87
+ DOMTimeStamp(V: unknown, opts?: WebIDLConversions.Options): number;
88
+ };
89
+
90
+ // This can't use ES6 style exports, as those can't have spaces in export names.
91
+ export = WebIDLConversions;
gateway/node_modules/@types/webidl-conversions/package.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@types/webidl-conversions",
3
+ "version": "7.0.3",
4
+ "description": "TypeScript definitions for webidl-conversions",
5
+ "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/webidl-conversions",
6
+ "license": "MIT",
7
+ "contributors": [
8
+ {
9
+ "name": "ExE Boss",
10
+ "githubUsername": "ExE-Boss",
11
+ "url": "https://github.com/ExE-Boss"
12
+ },
13
+ {
14
+ "name": "BendingBender",
15
+ "githubUsername": "BendingBender",
16
+ "url": "https://github.com/BendingBender"
17
+ }
18
+ ],
19
+ "main": "",
20
+ "types": "index.d.ts",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
24
+ "directory": "types/webidl-conversions"
25
+ },
26
+ "scripts": {},
27
+ "dependencies": {},
28
+ "typesPublisherContentHash": "ff1514e10869784e8b7cca9c4099a4213d3f14b48c198b1bf116300df94bf608",
29
+ "typeScriptVersion": "4.5"
30
+ }
gateway/node_modules/@types/whatwg-url/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) Microsoft Corporation.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE
gateway/node_modules/@types/whatwg-url/README.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Installation
2
+ > `npm install --save @types/whatwg-url`
3
+
4
+ # Summary
5
+ This package contains type definitions for whatwg-url (https://github.com/jsdom/whatwg-url#readme).
6
+
7
+ # Details
8
+ Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/whatwg-url.
9
+
10
+ ### Additional Details
11
+ * Last updated: Tue, 12 Nov 2024 00:46:36 GMT
12
+ * Dependencies: [@types/webidl-conversions](https://npmjs.com/package/@types/webidl-conversions)
13
+
14
+ # Credits
15
+ These definitions were written by [Alexander Marks](https://github.com/aomarks), [ExE Boss](https://github.com/ExE-Boss), and [BendingBender](https://github.com/BendingBender).
gateway/node_modules/@types/whatwg-url/index.d.ts ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /// <reference lib="es2020"/>
2
+ /** https://url.spec.whatwg.org/#url-representation */
3
+ export interface URLRecord {
4
+ scheme: string;
5
+ username: string;
6
+ password: string;
7
+ host: string | number | IPv6Address | null;
8
+ port: number | null;
9
+ path: string | string[];
10
+ query: string | null;
11
+ fragment: string | null;
12
+ }
13
+
14
+ /** https://url.spec.whatwg.org/#concept-ipv6 */
15
+ export type IPv6Address = [number, number, number, number, number, number, number, number];
16
+
17
+ /** https://url.spec.whatwg.org/#url-class */
18
+ export class URL {
19
+ constructor(url: string, base?: string | URL);
20
+
21
+ static canParse(url: string, base?: string): boolean;
22
+
23
+ get href(): string;
24
+ set href(V: string);
25
+
26
+ get origin(): string;
27
+
28
+ get protocol(): string;
29
+ set protocol(V: string);
30
+
31
+ get username(): string;
32
+ set username(V: string);
33
+
34
+ get password(): string;
35
+ set password(V: string);
36
+
37
+ get host(): string;
38
+ set host(V: string);
39
+
40
+ get hostname(): string;
41
+ set hostname(V: string);
42
+
43
+ get port(): string;
44
+ set port(V: string);
45
+
46
+ get pathname(): string;
47
+ set pathname(V: string);
48
+
49
+ get search(): string;
50
+ set search(V: string);
51
+
52
+ get searchParams(): URLSearchParams;
53
+
54
+ get hash(): string;
55
+ set hash(V: string);
56
+
57
+ toJSON(): string;
58
+
59
+ readonly [Symbol.toStringTag]: "URL";
60
+ }
61
+
62
+ /** https://url.spec.whatwg.org/#interface-urlsearchparams */
63
+ export class URLSearchParams {
64
+ constructor(
65
+ init?:
66
+ | ReadonlyArray<readonly [name: string, value: string]>
67
+ | Iterable<readonly [name: string, value: string]>
68
+ | { readonly [name: string]: string }
69
+ | string,
70
+ );
71
+
72
+ get size(): number;
73
+ append(name: string, value: string): void;
74
+ delete(name: string, value?: string): void;
75
+ get(name: string): string | null;
76
+ getAll(name: string): string[];
77
+ has(name: string, value?: string): boolean;
78
+ set(name: string, value: string): void;
79
+ sort(): void;
80
+
81
+ keys(): IterableIterator<string>;
82
+ values(): IterableIterator<string>;
83
+ entries(): IterableIterator<[name: string, value: string]>;
84
+ forEach<THIS_ARG = void>(
85
+ callback: (this: THIS_ARG, value: string, name: string, searchParams: this) => void,
86
+ thisArg?: THIS_ARG,
87
+ ): void;
88
+
89
+ readonly [Symbol.toStringTag]: "URLSearchParams";
90
+ [Symbol.iterator](): IterableIterator<[name: string, value: string]>;
91
+ }
92
+
93
+ /** https://url.spec.whatwg.org/#concept-url-parser */
94
+ export function parseURL(input: string, options?: { readonly baseURL?: URLRecord | undefined }): URLRecord | null;
95
+
96
+ /** https://url.spec.whatwg.org/#concept-basic-url-parser */
97
+ export function basicURLParse(
98
+ input: string,
99
+ options?: {
100
+ baseURL?: URLRecord | undefined;
101
+ url?: URLRecord | undefined;
102
+ stateOverride?: StateOverride | undefined;
103
+ },
104
+ ): URLRecord | null;
105
+
106
+ /** https://url.spec.whatwg.org/#scheme-start-state */
107
+ export type StateOverride =
108
+ | "scheme start"
109
+ | "scheme"
110
+ | "no scheme"
111
+ | "special relative or authority"
112
+ | "path or authority"
113
+ | "relative"
114
+ | "relative slash"
115
+ | "special authority slashes"
116
+ | "special authority ignore slashes"
117
+ | "authority"
118
+ | "host"
119
+ | "hostname"
120
+ | "port"
121
+ | "file"
122
+ | "file slash"
123
+ | "file host"
124
+ | "path start"
125
+ | "path"
126
+ | "opaque path"
127
+ | "query"
128
+ | "fragment";
129
+
130
+ /** https://url.spec.whatwg.org/#concept-url-serializer */
131
+ export function serializeURL(urlRecord: URLRecord, excludeFragment?: boolean): string;
132
+
133
+ /** https://url.spec.whatwg.org/#concept-host-serializer */
134
+ export function serializeHost(host: string | number | IPv6Address): string;
135
+
136
+ /** https://url.spec.whatwg.org/#url-path-serializer */
137
+ export function serializePath(urlRecord: URLRecord): string;
138
+
139
+ /** https://url.spec.whatwg.org/#serialize-an-integer */
140
+ export function serializeInteger(number: number): string;
141
+
142
+ /** https://html.spec.whatwg.org#ascii-serialisation-of-an-origin */
143
+ export function serializeURLOrigin(urlRecord: URLRecord): string;
144
+
145
+ /** https://url.spec.whatwg.org/#set-the-username */
146
+ export function setTheUsername(urlRecord: URLRecord, username: string): void;
147
+
148
+ /** https://url.spec.whatwg.org/#set-the-password */
149
+ export function setThePassword(urlRecord: URLRecord, password: string): void;
150
+
151
+ /** https://url.spec.whatwg.org/#url-opaque-path */
152
+ export function hasAnOpaquePath(urlRecord: URLRecord): boolean;
153
+
154
+ /** https://url.spec.whatwg.org/#cannot-have-a-username-password-port */
155
+ export function cannotHaveAUsernamePasswordPort(urlRecord: URLRecord): boolean;
156
+
157
+ /** https://url.spec.whatwg.org/#percent-decode */
158
+ export function percentDecodeBytes(buffer: TypedArray): Uint8Array;
159
+
160
+ /** https://url.spec.whatwg.org/#string-percent-decode */
161
+ export function percentDecodeString(string: string): Uint8Array;
162
+
163
+ export type TypedArray =
164
+ | Uint8Array
165
+ | Uint8ClampedArray
166
+ | Uint16Array
167
+ | Uint32Array
168
+ | Int8Array
169
+ | Int16Array
170
+ | Int32Array
171
+ | Float32Array
172
+ | Float64Array;
gateway/node_modules/@types/whatwg-url/package.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@types/whatwg-url",
3
+ "version": "13.0.0",
4
+ "description": "TypeScript definitions for whatwg-url",
5
+ "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/whatwg-url",
6
+ "license": "MIT",
7
+ "contributors": [
8
+ {
9
+ "name": "Alexander Marks",
10
+ "githubUsername": "aomarks",
11
+ "url": "https://github.com/aomarks"
12
+ },
13
+ {
14
+ "name": "ExE Boss",
15
+ "githubUsername": "ExE-Boss",
16
+ "url": "https://github.com/ExE-Boss"
17
+ },
18
+ {
19
+ "name": "BendingBender",
20
+ "githubUsername": "BendingBender",
21
+ "url": "https://github.com/BendingBender"
22
+ }
23
+ ],
24
+ "main": "",
25
+ "types": "index.d.ts",
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
29
+ "directory": "types/whatwg-url"
30
+ },
31
+ "scripts": {},
32
+ "dependencies": {
33
+ "@types/webidl-conversions": "*"
34
+ },
35
+ "peerDependencies": {},
36
+ "typesPublisherContentHash": "fd4818c1b74d8ef43c58e984d60d82658280822821b6ea5d4978f4007f29c39c",
37
+ "typeScriptVersion": "4.9"
38
+ }
gateway/node_modules/@types/whatwg-url/webidl2js-wrapper.d.ts ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ import * as URL from "./lib/URL";
2
+ import * as URLSearchParams from "./lib/URLSearchParams";
3
+
4
+ export { URL, URLSearchParams };
gateway/node_modules/bson/LICENSE.md ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
gateway/node_modules/bson/README.md ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # BSON parser
2
+
3
+ BSON is short for "Binary JSON," and is the binary-encoded serialization of JSON-like documents.
4
+ You can learn more about it in [the specification](http://bsonspec.org).
5
+
6
+ ### Table of Contents
7
+
8
+ - [Usage](#usage)
9
+ - [Bugs/Feature Requests](#bugs--feature-requests)
10
+ - [Installation](#installation)
11
+ - [Documentation](#documentation)
12
+ - [FAQ](#faq)
13
+
14
+
15
+ ### Release Integrity
16
+
17
+ Releases are created automatically and signed using the [Node team's GPG key](https://pgp.mongodb.com/node-driver.asc). All release packages provided as part of a GitHub release are signed. To verify the provided packages, download the key and import it using gpg:
18
+
19
+ ```shell
20
+ gpg --import node-driver.asc
21
+ ```
22
+
23
+ The GitHub release contains a detached signature file for the NPM package (named
24
+ `bson-X.Y.Z.tgz.sig`).
25
+
26
+ The following command returns the link npm package.
27
+ ```shell
28
+ npm view bson@vX.Y.Z dist.tarball
29
+ ```
30
+
31
+ Using the result of the above command, a `curl` command can return the official npm package for the release.
32
+
33
+ To verify the integrity of the downloaded package, run the following command:
34
+ ```shell
35
+ gpg --verify bson-X.Y.Z.tgz.sig bson-X.Y.Z.tgz
36
+ ```
37
+
38
+ >[!Note]
39
+ No GPG verification is done when using npm to install the package. The contents of the GitHub tarball and npm's tarball are identical.
40
+
41
+ Releases published to the npm registry also include a [provenance attestation](https://docs.npmjs.com/generating-provenance-statements), which cryptographically links the package to its source repository and build workflow. To verify provenance:
42
+
43
+ ```shell
44
+ npm audit signatures
45
+ ```
46
+
47
+ ## Bugs / Feature Requests
48
+
49
+ Think you've found a bug? Want to see a new feature in `bson`? Please open a case in our issue management tool, JIRA:
50
+
51
+ 1. Create an account and login: [jira.mongodb.org](https://jira.mongodb.org)
52
+ 2. Navigate to the NODE project: [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE)
53
+ 3. Click **Create Issue** - Please provide as much information as possible about the issue and how to reproduce it.
54
+
55
+ Bug reports in JIRA for the NODE driver project are **public**.
56
+
57
+ ## Usage
58
+
59
+ To build a new version perform the following operations:
60
+
61
+ ```
62
+ npm install
63
+ npm run build
64
+ ```
65
+
66
+ ### Node.js or Bundling Usage
67
+
68
+ When using a bundler or Node.js you can import bson using the package name:
69
+
70
+ ```js
71
+ import { BSON, EJSON, ObjectId } from 'bson';
72
+ // or:
73
+ // const { BSON, EJSON, ObjectId } = require('bson');
74
+
75
+ const bytes = BSON.serialize({ _id: new ObjectId() });
76
+ console.log(bytes);
77
+ const doc = BSON.deserialize(bytes);
78
+ console.log(EJSON.stringify(doc));
79
+ // {"_id":{"$oid":"..."}}
80
+ ```
81
+
82
+ ### Browser Usage
83
+
84
+ If you are working directly in the browser without a bundler please use the `.mjs` bundle like so:
85
+
86
+ ```html
87
+ <script type="module">
88
+ import { BSON, EJSON, ObjectId } from './lib/bson.mjs';
89
+
90
+ const bytes = BSON.serialize({ _id: new ObjectId() });
91
+ console.log(bytes);
92
+ const doc = BSON.deserialize(bytes);
93
+ console.log(EJSON.stringify(doc));
94
+ // {"_id":{"$oid":"..."}}
95
+ </script>
96
+ ```
97
+
98
+ ## Installation
99
+
100
+ ```sh
101
+ npm install bson
102
+ ```
103
+
104
+ ### MongoDB Node.js Driver Version Compatibility
105
+
106
+ Only the following version combinations with the [MongoDB Node.js Driver](https://github.com/mongodb/node-mongodb-native) are considered stable.
107
+
108
+ | | `bson@1.x` | `bson@4.x` | `bson@5.x` | `bson@6.x` | `bson@7.x` |
109
+ | ------------- | ---------- | ---------- | ---------- | ---------- | ---------- |
110
+ | `mongodb@7.x` | N/A | N/A | N/A | N/A | ✓ |
111
+ | `mongodb@6.x` | N/A | N/A | N/A | ✓ | N/A |
112
+ | `mongodb@5.x` | N/A | N/A | ✓ | N/A | N/A |
113
+ | `mongodb@4.x` | N/A | ✓ | N/A | N/A | N/A |
114
+ | `mongodb@3.x` | ✓ | N/A | N/A | N/A | N/A |
115
+
116
+ ## Documentation
117
+
118
+ ### BSON
119
+
120
+ [API documentation](https://mongodb.github.io/node-mongodb-native/Next/modules/BSON.html)
121
+
122
+ <a name="EJSON"></a>
123
+
124
+ ### EJSON
125
+
126
+ - [EJSON](#EJSON)
127
+
128
+ - [.parse(text, [options])](#EJSON.parse)
129
+
130
+ - [.stringify(value, [replacer], [space], [options])](#EJSON.stringify)
131
+
132
+ - [.serialize(bson, [options])](#EJSON.serialize)
133
+
134
+ - [.deserialize(ejson, [options])](#EJSON.deserialize)
135
+
136
+ <a name="EJSON.parse"></a>
137
+
138
+ #### _EJSON_.parse(text, [options])
139
+
140
+ | Param | Type | Default | Description |
141
+ | ----------------- | -------------------- | ----------------- | ---------------------------------------------------------------------------------- |
142
+ | text | <code>string</code> | | |
143
+ | [options] | <code>object</code> | | Optional settings |
144
+ | [options.relaxed] | <code>boolean</code> | <code>true</code> | Attempt to return native JS types where possible, rather than BSON types (if true) |
145
+
146
+ Parse an Extended JSON string, constructing the JavaScript value or object described by that
147
+ string.
148
+
149
+ **Example**
150
+
151
+ ```js
152
+ const { EJSON } = require('bson');
153
+ const text = '{ "int32": { "$numberInt": "10" } }';
154
+
155
+ // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }
156
+ console.log(EJSON.parse(text, { relaxed: false }));
157
+
158
+ // prints { int32: 10 }
159
+ console.log(EJSON.parse(text));
160
+ ```
161
+
162
+ <a name="EJSON.stringify"></a>
163
+
164
+ #### _EJSON_.stringify(value, [replacer], [space], [options])
165
+
166
+ | Param | Type | Default | Description |
167
+ | ----------------- | ------------------------------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
168
+ | value | <code>object</code> | | The value to convert to extended JSON |
169
+ | [replacer] | <code>function</code> \| <code>array</code> | | 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 |
170
+ | [space] | <code>string</code> \| <code>number</code> | | A String or Number object that's used to insert white space into the output JSON string for readability purposes. |
171
+ | [options] | <code>object</code> | | Optional settings |
172
+ | [options.relaxed] | <code>boolean</code> | <code>true</code> | Enabled Extended JSON's `relaxed` mode |
173
+ | [options.legacy] | <code>boolean</code> | <code>true</code> | Output in Extended JSON v1 |
174
+
175
+ Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer
176
+ function is specified or optionally including only the specified properties if a replacer array
177
+ is specified.
178
+
179
+ **Example**
180
+
181
+ ```js
182
+ const { EJSON } = require('bson');
183
+ const Int32 = require('mongodb').Int32;
184
+ const doc = { int32: new Int32(10) };
185
+
186
+ // prints '{"int32":{"$numberInt":"10"}}'
187
+ console.log(EJSON.stringify(doc, { relaxed: false }));
188
+
189
+ // prints '{"int32":10}'
190
+ console.log(EJSON.stringify(doc));
191
+ ```
192
+
193
+ <a name="EJSON.serialize"></a>
194
+
195
+ #### _EJSON_.serialize(bson, [options])
196
+
197
+ | Param | Type | Description |
198
+ | --------- | ------------------- | ---------------------------------------------------- |
199
+ | bson | <code>object</code> | The object to serialize |
200
+ | [options] | <code>object</code> | Optional settings passed to the `stringify` function |
201
+
202
+ Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.
203
+
204
+ <a name="EJSON.deserialize"></a>
205
+
206
+ #### _EJSON_.deserialize(ejson, [options])
207
+
208
+ | Param | Type | Description |
209
+ | --------- | ------------------- | -------------------------------------------- |
210
+ | ejson | <code>object</code> | The Extended JSON object to deserialize |
211
+ | [options] | <code>object</code> | Optional settings passed to the parse method |
212
+
213
+ Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types
214
+
215
+ ## Error Handling
216
+
217
+ It is our recommendation to use `BSONError.isBSONError()` checks on errors and to avoid relying on parsing `error.message` and `error.name` strings in your code. We guarantee `BSONError.isBSONError()` checks will pass according to semver guidelines, but errors may be sub-classed or their messages may change at any time, even patch releases, as we see fit to increase the helpfulness of the errors.
218
+
219
+ Any new errors we add to the driver will directly extend an existing error class and no existing error will be moved to a different parent class outside of a major release.
220
+ This means `BSONError.isBSONError()` will always be able to accurately capture the errors that our BSON library throws.
221
+
222
+ Hypothetical example: A collection in our Db has an issue with UTF-8 data:
223
+
224
+ ```ts
225
+ let documentCount = 0;
226
+ const cursor = collection.find({}, { utf8Validation: true });
227
+ try {
228
+ for await (const doc of cursor) documentCount += 1;
229
+ } catch (error) {
230
+ if (BSONError.isBSONError(error)) {
231
+ console.log(`Found the troublemaker UTF-8!: ${documentCount} ${error.message}`);
232
+ return documentCount;
233
+ }
234
+ throw error;
235
+ }
236
+ ```
237
+
238
+ ## React Native
239
+
240
+ js-bson requires the `atob`, `btoa` and `TextEncoder` globals. Older versions of React Native did not support these global objects, and so
241
+ [js-bson v5.4.0](https://github.com/mongodb/js-bson/releases/tag/v5.4.0) added support for bundled polyfills for these globals. Newer versions
242
+ of Hermes includes these globals, and so the polyfills for are no longer needed in the js-bson package.
243
+
244
+ If you find yourself on a version of React Native that does not have these globals, either:
245
+
246
+ 1. polyfill them yourself
247
+ 2. upgrade to a later version of hermes
248
+ 3. use a version of js-bson `>=5.4.0` and `<7.0.0`
249
+
250
+ One additional polyfill, `crypto.getRandomValues` is recommended and can be installed with the following command:
251
+
252
+ ```sh
253
+ npm install --save react-native-get-random-values
254
+ ```
255
+
256
+ The following snippet should be placed at the top of the entrypoint (by default this is the root `index.js` file) for React Native projects using the BSON library. These lines must be placed for any code that imports `BSON`.
257
+
258
+ ```typescript
259
+ // Required Polyfills For ReactNative
260
+ import 'react-native-get-random-values';
261
+ ```
262
+
263
+ Finally, import the `BSON` library like so:
264
+
265
+ ```typescript
266
+ import { BSON, EJSON } from 'bson';
267
+ ```
268
+
269
+ This will cause React Native to import the `node_modules/bson/lib/bson.rn.cjs` bundle (see the `"react-native"` setting we have in the `"exports"` section of our [package.json](./package.json).)
270
+
271
+ ### Technical Note about React Native module import
272
+
273
+ The `"exports"` definition in our `package.json` will result in BSON's CommonJS bundle being imported in a React Native project instead of the ES module bundle. Importing the CommonJS bundle is necessary because BSON's ES module bundle of BSON uses top-level await, which is not supported syntax in [React Native's runtime hermes](https://hermesengine.dev/).
274
+
275
+ ## FAQ
276
+
277
+ #### Why does `undefined` get converted to `null`?
278
+
279
+ The `undefined` BSON type has been [deprecated for many years](http://bsonspec.org/spec.html), so this library has dropped support for it. Use the `ignoreUndefined` option (for example, from the [driver](http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect) ) to instead remove `undefined` keys.
280
+
281
+ #### How do I add custom serialization logic?
282
+
283
+ This library looks for `toBSON()` functions on every path, and calls the `toBSON()` function to get the value to serialize.
284
+
285
+ ```javascript
286
+ const BSON = require('bson');
287
+
288
+ class CustomSerialize {
289
+ toBSON() {
290
+ return 42;
291
+ }
292
+ }
293
+
294
+ const obj = { answer: new CustomSerialize() };
295
+ // "{ answer: 42 }"
296
+ console.log(BSON.deserialize(BSON.serialize(obj)));
297
+ ```
gateway/node_modules/bson/bson.d.ts ADDED
@@ -0,0 +1,1901 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * A class representation of the BSON Binary type.
3
+ * @public
4
+ * @category BSONType
5
+ */
6
+ export declare class Binary extends BSONValue {
7
+ get _bsontype(): 'Binary';
8
+ /* Excluded from this release type: BSON_BINARY_SUBTYPE_DEFAULT */
9
+ /** Initial buffer default size */
10
+ static readonly BUFFER_SIZE = 256;
11
+ /** Default BSON type */
12
+ static readonly SUBTYPE_DEFAULT = 0;
13
+ /** Function BSON type */
14
+ static readonly SUBTYPE_FUNCTION = 1;
15
+ /**
16
+ * Legacy default BSON Binary type
17
+ * @deprecated BSON Binary subtype 2 is deprecated in the BSON specification
18
+ */
19
+ static readonly SUBTYPE_BYTE_ARRAY = 2;
20
+ /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */
21
+ static readonly SUBTYPE_UUID_OLD = 3;
22
+ /** UUID BSON type */
23
+ static readonly SUBTYPE_UUID = 4;
24
+ /** MD5 BSON type */
25
+ static readonly SUBTYPE_MD5 = 5;
26
+ /** Encrypted BSON type */
27
+ static readonly SUBTYPE_ENCRYPTED = 6;
28
+ /** Column BSON type */
29
+ static readonly SUBTYPE_COLUMN = 7;
30
+ /** Sensitive BSON type */
31
+ static readonly SUBTYPE_SENSITIVE = 8;
32
+ /** Vector BSON type */
33
+ static readonly SUBTYPE_VECTOR = 9;
34
+ /** User BSON type */
35
+ static readonly SUBTYPE_USER_DEFINED = 128;
36
+ /** datatype of a Binary Vector (subtype: 9) */
37
+ static readonly VECTOR_TYPE: Readonly<{
38
+ readonly Int8: 3;
39
+ readonly Float32: 39;
40
+ readonly PackedBit: 16;
41
+ }>;
42
+ /**
43
+ * The bytes of the Binary value.
44
+ *
45
+ * The format of a Binary value in BSON is defined as:
46
+ * ```txt
47
+ * binary ::= int32 subtype (byte*)
48
+ * ```
49
+ *
50
+ * This `buffer` is the "(byte*)" segment.
51
+ *
52
+ * Unless the value is subtype 2, then deserialize will read the first 4 bytes as an int32 and set this to the remaining bytes.
53
+ *
54
+ * ```txt
55
+ * binary ::= int32 unsigned_byte(2) int32 (byte*)
56
+ * ```
57
+ *
58
+ * @see https://bsonspec.org/spec.html
59
+ */
60
+ buffer: Uint8Array;
61
+ /**
62
+ * The binary subtype.
63
+ *
64
+ * Current defined values are:
65
+ *
66
+ * - `unsigned_byte(0)` Generic binary subtype
67
+ * - `unsigned_byte(1)` Function
68
+ * - `unsigned_byte(2)` Binary (Deprecated)
69
+ * - `unsigned_byte(3)` UUID (Deprecated)
70
+ * - `unsigned_byte(4)` UUID
71
+ * - `unsigned_byte(5)` MD5
72
+ * - `unsigned_byte(6)` Encrypted BSON value
73
+ * - `unsigned_byte(7)` Compressed BSON column
74
+ * - `unsigned_byte(8)` Sensitive
75
+ * - `unsigned_byte(9)` Vector
76
+ * - `unsigned_byte(128)` - `unsigned_byte(255)` User defined
77
+ */
78
+ sub_type: number;
79
+ /**
80
+ * The Binary's `buffer` can be larger than the Binary's content.
81
+ * This property is used to determine where the content ends in the buffer.
82
+ */
83
+ position: number;
84
+ /**
85
+ * Create a new Binary instance.
86
+ * @param buffer - a buffer object containing the binary data.
87
+ * @param subType - the option binary type.
88
+ */
89
+ constructor(buffer?: BinarySequence, subType?: number);
90
+ /**
91
+ * Updates this binary with byte_value.
92
+ *
93
+ * @param byteValue - a single byte we wish to write.
94
+ */
95
+ put(byteValue: string | number | Uint8Array | number[]): void;
96
+ /**
97
+ * Writes a buffer to the binary.
98
+ *
99
+ * @param sequence - a string or buffer to be written to the Binary BSON object.
100
+ * @param offset - specify the binary of where to write the content.
101
+ */
102
+ write(sequence: BinarySequence, offset: number): void;
103
+ /**
104
+ * Returns a view of **length** bytes starting at **position**.
105
+ *
106
+ * @param position - read from the given position in the Binary.
107
+ * @param length - the number of bytes to read.
108
+ */
109
+ read(position: number, length: number): Uint8Array;
110
+ /** returns a view of the binary value as a Uint8Array */
111
+ value(): Uint8Array;
112
+ /** the length of the binary sequence */
113
+ length(): number;
114
+ toJSON(): string;
115
+ toString(encoding?: 'hex' | 'base64' | 'utf8' | 'utf-8'): string;
116
+ /* Excluded from this release type: toExtendedJSON */
117
+ toUUID(): UUID;
118
+ /** Creates an Binary instance from a hex digit string */
119
+ static createFromHexString(hex: string, subType?: number): Binary;
120
+ /** Creates an Binary instance from a base64 string */
121
+ static createFromBase64(base64: string, subType?: number): Binary;
122
+ /* Excluded from this release type: fromExtendedJSON */
123
+ inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
124
+ /**
125
+ * If this Binary represents a Int8 Vector (`binary.buffer[0] === Binary.VECTOR_TYPE.Int8`),
126
+ * returns a copy of the bytes in a new Int8Array.
127
+ *
128
+ * If the Binary is not a Vector, or the datatype is not Int8, an error is thrown.
129
+ */
130
+ toInt8Array(): Int8Array;
131
+ /**
132
+ * If this Binary represents a Float32 Vector (`binary.buffer[0] === Binary.VECTOR_TYPE.Float32`),
133
+ * returns a copy of the bytes in a new Float32Array.
134
+ *
135
+ * If the Binary is not a Vector, or the datatype is not Float32, an error is thrown.
136
+ */
137
+ toFloat32Array(): Float32Array;
138
+ /**
139
+ * If this Binary represents packed bit Vector (`binary.buffer[0] === Binary.VECTOR_TYPE.PackedBit`),
140
+ * returns a copy of the bytes that are packed bits.
141
+ *
142
+ * Use `toBits` to get the unpacked bits.
143
+ *
144
+ * If the Binary is not a Vector, or the datatype is not PackedBit, an error is thrown.
145
+ */
146
+ toPackedBits(): Uint8Array;
147
+ /**
148
+ * If this Binary represents a Packed bit Vector (`binary.buffer[0] === Binary.VECTOR_TYPE.PackedBit`),
149
+ * returns a copy of the bit unpacked into a new Int8Array.
150
+ *
151
+ * Use `toPackedBits` to get the bits still in packed form.
152
+ *
153
+ * If the Binary is not a Vector, or the datatype is not PackedBit, an error is thrown.
154
+ */
155
+ toBits(): Int8Array;
156
+ /**
157
+ * Constructs a Binary representing an Int8 Vector.
158
+ * @param array - The array to store as a view on the Binary class
159
+ */
160
+ static fromInt8Array(array: Int8Array): Binary;
161
+ /** Constructs a Binary representing an Float32 Vector. */
162
+ static fromFloat32Array(array: Float32Array): Binary;
163
+ /**
164
+ * Constructs a Binary representing a packed bit Vector.
165
+ *
166
+ * Use `fromBits` to pack an array of 1s and 0s.
167
+ */
168
+ static fromPackedBits(array: Uint8Array, padding?: number): Binary;
169
+ /**
170
+ * Constructs a Binary representing an Packed Bit Vector.
171
+ * @param array - The array of 1s and 0s to pack into the Binary instance
172
+ */
173
+ static fromBits(bits: ArrayLike<number>): Binary;
174
+ }
175
+
176
+ /** @public */
177
+ export declare interface BinaryExtended {
178
+ $binary: {
179
+ subType: string;
180
+ base64: string;
181
+ };
182
+ }
183
+
184
+ /** @public */
185
+ export declare interface BinaryExtendedLegacy {
186
+ $type: string;
187
+ $binary: string;
188
+ }
189
+
190
+ /** @public */
191
+ export declare type BinarySequence = Uint8Array | number[];
192
+
193
+ declare namespace BSON {
194
+ export {
195
+ setInternalBufferSize,
196
+ serialize,
197
+ serializeWithBufferAndIndex,
198
+ deserialize,
199
+ calculateObjectSize,
200
+ deserializeStream,
201
+ UUIDExtended,
202
+ BinaryExtended,
203
+ BinaryExtendedLegacy,
204
+ BinarySequence,
205
+ CodeExtended,
206
+ DBRefLike,
207
+ Decimal128Extended,
208
+ DoubleExtended,
209
+ EJSONOptions,
210
+ EJSONOptionsBase,
211
+ EJSONSerializeOptions,
212
+ EJSONParseOptions,
213
+ Int32Extended,
214
+ LongExtended,
215
+ MaxKeyExtended,
216
+ MinKeyExtended,
217
+ ObjectIdExtended,
218
+ ObjectIdLike,
219
+ BSONRegExpExtended,
220
+ BSONRegExpExtendedLegacy,
221
+ BSONSymbolExtended,
222
+ LongWithoutOverrides,
223
+ TimestampExtended,
224
+ TimestampOverrides,
225
+ LongWithoutOverridesClass,
226
+ SerializeOptions,
227
+ DeserializeOptions,
228
+ Code,
229
+ BSONSymbol,
230
+ DBRef,
231
+ Binary,
232
+ ObjectId,
233
+ UUID,
234
+ Long,
235
+ Timestamp,
236
+ Double,
237
+ Int32,
238
+ MinKey,
239
+ MaxKey,
240
+ BSONRegExp,
241
+ Decimal128,
242
+ NumberUtils,
243
+ ByteUtils,
244
+ BSONValue,
245
+ bsonType,
246
+ BSONTypeTag,
247
+ BSONError,
248
+ BSONVersionError,
249
+ BSONRuntimeError,
250
+ BSONOffsetError,
251
+ BSONType,
252
+ EJSON,
253
+ onDemand,
254
+ OnDemand,
255
+ Document,
256
+ CalculateObjectSizeOptions
257
+ }
258
+ }
259
+ export { BSON }
260
+
261
+ /* Excluded from this release type: BSON_MAJOR_VERSION */
262
+
263
+ /* Excluded from this release type: BSON_VERSION_SYMBOL */
264
+
265
+ /**
266
+ * @public
267
+ * @experimental
268
+ */
269
+ declare type BSONElement = [
270
+ type: number,
271
+ nameOffset: number,
272
+ nameLength: number,
273
+ offset: number,
274
+ length: number
275
+ ];
276
+
277
+ /**
278
+ * @public
279
+ * @category Error
280
+ *
281
+ * `BSONError` objects are thrown when BSON encounters an error.
282
+ *
283
+ * This is the parent class for all the other errors thrown by this library.
284
+ */
285
+ export declare class BSONError extends Error {
286
+ /* Excluded from this release type: bsonError */
287
+ get name(): string;
288
+ constructor(message: string, options?: {
289
+ cause?: unknown;
290
+ });
291
+ /**
292
+ * @public
293
+ *
294
+ * All errors thrown from the BSON library inherit from `BSONError`.
295
+ * This method can assist with determining if an error originates from the BSON library
296
+ * even if it does not pass an `instanceof` check against this class' constructor.
297
+ *
298
+ * @param value - any javascript value that needs type checking
299
+ */
300
+ static isBSONError(value: unknown): value is BSONError;
301
+ }
302
+
303
+ /**
304
+ * @public
305
+ * @category Error
306
+ *
307
+ * @experimental
308
+ *
309
+ * An error generated when BSON bytes are invalid.
310
+ * Reports the offset the parser was able to reach before encountering the error.
311
+ */
312
+ export declare class BSONOffsetError extends BSONError {
313
+ get name(): 'BSONOffsetError';
314
+ offset: number;
315
+ constructor(message: string, offset: number, options?: {
316
+ cause?: unknown;
317
+ });
318
+ }
319
+
320
+ /**
321
+ * A class representation of the BSON RegExp type.
322
+ * @public
323
+ * @category BSONType
324
+ */
325
+ export declare class BSONRegExp extends BSONValue {
326
+ get _bsontype(): 'BSONRegExp';
327
+ pattern: string;
328
+ options: string;
329
+ /**
330
+ * @param pattern - The regular expression pattern to match
331
+ * @param options - The regular expression options
332
+ */
333
+ constructor(pattern: string, options?: string);
334
+ static parseOptions(options?: string): string;
335
+ /* Excluded from this release type: toExtendedJSON */
336
+ /* Excluded from this release type: fromExtendedJSON */
337
+ inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
338
+ }
339
+
340
+ /** @public */
341
+ export declare interface BSONRegExpExtended {
342
+ $regularExpression: {
343
+ pattern: string;
344
+ options: string;
345
+ };
346
+ }
347
+
348
+ /** @public */
349
+ export declare interface BSONRegExpExtendedLegacy {
350
+ $regex: string | BSONRegExp;
351
+ $options: string;
352
+ }
353
+
354
+ /**
355
+ * @public
356
+ * @category Error
357
+ *
358
+ * An error generated when BSON functions encounter an unexpected input
359
+ * or reaches an unexpected/invalid internal state
360
+ *
361
+ */
362
+ export declare class BSONRuntimeError extends BSONError {
363
+ get name(): 'BSONRuntimeError';
364
+ constructor(message: string);
365
+ }
366
+
367
+ /**
368
+ * A class representation of the BSON Symbol type.
369
+ * @public
370
+ * @category BSONType
371
+ */
372
+ export declare class BSONSymbol extends BSONValue {
373
+ get _bsontype(): 'BSONSymbol';
374
+ value: string;
375
+ /**
376
+ * @param value - the string representing the symbol.
377
+ */
378
+ constructor(value: string);
379
+ /** Access the wrapped string value. */
380
+ valueOf(): string;
381
+ toString(): string;
382
+ toJSON(): string;
383
+ /* Excluded from this release type: toExtendedJSON */
384
+ /* Excluded from this release type: fromExtendedJSON */
385
+ inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
386
+ }
387
+
388
+ /** @public */
389
+ export declare interface BSONSymbolExtended {
390
+ $symbol: string;
391
+ }
392
+
393
+ /** @public */
394
+ export declare const BSONType: Readonly<{
395
+ readonly double: 1;
396
+ readonly string: 2;
397
+ readonly object: 3;
398
+ readonly array: 4;
399
+ readonly binData: 5;
400
+ readonly undefined: 6;
401
+ readonly objectId: 7;
402
+ readonly bool: 8;
403
+ readonly date: 9;
404
+ readonly null: 10;
405
+ readonly regex: 11;
406
+ readonly dbPointer: 12;
407
+ readonly javascript: 13;
408
+ readonly symbol: 14;
409
+ readonly javascriptWithScope: 15;
410
+ readonly int: 16;
411
+ readonly timestamp: 17;
412
+ readonly long: 18;
413
+ readonly decimal: 19;
414
+ readonly minKey: -1;
415
+ readonly maxKey: 127;
416
+ }>;
417
+
418
+ /** @public */
419
+ export declare type BSONType = (typeof BSONType)[keyof typeof BSONType];
420
+
421
+ /** @public */
422
+ export declare const bsonType: unique symbol;
423
+
424
+ /** @public */
425
+ export declare type BSONTypeTag = 'BSONRegExp' | 'BSONSymbol' | 'ObjectId' | 'Binary' | 'Decimal128' | 'Double' | 'Int32' | 'Long' | 'MaxKey' | 'MinKey' | 'Timestamp' | 'Code' | 'DBRef';
426
+
427
+ /** @public */
428
+ export declare abstract class BSONValue {
429
+ /** @public */
430
+ abstract get _bsontype(): BSONTypeTag;
431
+ get [bsonType](): this['_bsontype'];
432
+ /* Excluded from this release type: [BSON_VERSION_SYMBOL] */
433
+ /**
434
+ * @public
435
+ * Prints a human-readable string of BSON value information
436
+ * If invoked manually without node.js.inspect function, this will default to a modified JSON.stringify
437
+ */
438
+ abstract inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
439
+ /* Excluded from this release type: toExtendedJSON */
440
+ }
441
+
442
+ /**
443
+ * @public
444
+ * @category Error
445
+ */
446
+ export declare class BSONVersionError extends BSONError {
447
+ get name(): 'BSONVersionError';
448
+ constructor();
449
+ }
450
+
451
+ /**
452
+ * @public
453
+ * @experimental
454
+ *
455
+ * A collection of functions that help work with data in a Uint8Array.
456
+ * ByteUtils is configured at load time to use Node.js or Web based APIs for the internal implementations.
457
+ */
458
+ export declare type ByteUtils = {
459
+ /** Checks if the given value is a Uint8Array. */
460
+ isUint8Array: (value: unknown) => value is Uint8Array;
461
+ /** Transforms the input to an instance of Buffer if running on node, otherwise Uint8Array */
462
+ toLocalBufferType: (buffer: Uint8Array | ArrayBufferView | ArrayBuffer) => Uint8Array;
463
+ /** Create empty space of size */
464
+ allocate: (size: number) => Uint8Array;
465
+ /** Create empty space of size, use pooled memory when available */
466
+ allocateUnsafe: (size: number) => Uint8Array;
467
+ /** Compare 2 Uint8Arrays lexicographically */
468
+ compare: (buffer1: Uint8Array, buffer2: Uint8Array) => -1 | 0 | 1;
469
+ /** Concatenating all the Uint8Arrays in new Uint8Array. */
470
+ concat: (list: Uint8Array[]) => Uint8Array;
471
+ /** Copy bytes from source Uint8Array to target Uint8Array */
472
+ copy: (source: Uint8Array, target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number) => number;
473
+ /** Check if two Uint8Arrays are deep equal */
474
+ equals: (a: Uint8Array, b: Uint8Array) => boolean;
475
+ /** Create a Uint8Array from an array of numbers */
476
+ fromNumberArray: (array: number[]) => Uint8Array;
477
+ /** Create a Uint8Array from a base64 string */
478
+ fromBase64: (base64: string) => Uint8Array;
479
+ /** Create a Uint8Array from a UTF8 string */
480
+ fromUTF8: (utf8: string) => Uint8Array;
481
+ /** Create a base64 string from bytes */
482
+ toBase64: (buffer: Uint8Array) => string;
483
+ /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */
484
+ fromISO88591: (codePoints: string) => Uint8Array;
485
+ /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */
486
+ toISO88591: (buffer: Uint8Array) => string;
487
+ /** Create a Uint8Array from a hex string */
488
+ fromHex: (hex: string) => Uint8Array;
489
+ /** Create a lowercase hex string from bytes */
490
+ toHex: (buffer: Uint8Array) => string;
491
+ /** Create a string from utf8 code units, fatal=true will throw an error if UTF-8 bytes are invalid, fatal=false will insert replacement characters */
492
+ toUTF8: (buffer: Uint8Array, start: number, end: number, fatal: boolean) => string;
493
+ /** Get the utf8 code unit count from a string if it were to be transformed to utf8 */
494
+ utf8ByteLength: (input: string) => number;
495
+ /** Encode UTF8 bytes generated from `source` string into `destination` at byteOffset. Returns the number of bytes encoded. */
496
+ encodeUTF8Into: (destination: Uint8Array, source: string, byteOffset: number) => number;
497
+ /** Generate a Uint8Array filled with random bytes with byteLength */
498
+ randomBytes: (byteLength: number) => Uint8Array;
499
+ /** Interprets `buffer` as an array of 32-bit values and swaps the byte order in-place. */
500
+ swap32: (buffer: Uint8Array) => Uint8Array;
501
+ };
502
+
503
+ /**
504
+ * This is the only ByteUtils that should be used across the rest of the BSON library.
505
+ *
506
+ * The type annotation is important here, it asserts that each of the platform specific
507
+ * utils implementations are compatible with the common one.
508
+ *
509
+ * @public
510
+ * @experimental
511
+ */
512
+ export declare const ByteUtils: ByteUtils;
513
+
514
+ /**
515
+ * Calculate the bson size for a passed in Javascript object.
516
+ *
517
+ * @param object - the Javascript object to calculate the BSON byte size for
518
+ * @returns size of BSON object in bytes
519
+ * @public
520
+ */
521
+ export declare function calculateObjectSize(object: Document, options?: CalculateObjectSizeOptions): number;
522
+
523
+ /** @public */
524
+ export declare type CalculateObjectSizeOptions = Pick<SerializeOptions, 'serializeFunctions' | 'ignoreUndefined'>;
525
+
526
+ /**
527
+ * A class representation of the BSON Code type.
528
+ * @public
529
+ * @category BSONType
530
+ */
531
+ export declare class Code extends BSONValue {
532
+ get _bsontype(): 'Code';
533
+ code: string;
534
+ scope: Document | null;
535
+ /**
536
+ * @param code - a string or function.
537
+ * @param scope - an optional scope for the function.
538
+ */
539
+ constructor(code: string | Function, scope?: Document | null);
540
+ toJSON(): {
541
+ code: string;
542
+ scope?: Document;
543
+ };
544
+ /* Excluded from this release type: toExtendedJSON */
545
+ /* Excluded from this release type: fromExtendedJSON */
546
+ inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
547
+ }
548
+
549
+ /** @public */
550
+ export declare interface CodeExtended {
551
+ $code: string;
552
+ $scope?: Document;
553
+ }
554
+
555
+ /**
556
+ * A class representation of the BSON DBRef type.
557
+ * @public
558
+ * @category BSONType
559
+ */
560
+ export declare class DBRef extends BSONValue {
561
+ get _bsontype(): 'DBRef';
562
+ collection: string;
563
+ oid: ObjectId;
564
+ db?: string;
565
+ fields: Document;
566
+ /**
567
+ * @param collection - the collection name.
568
+ * @param oid - the reference ObjectId.
569
+ * @param db - optional db name, if omitted the reference is local to the current db.
570
+ */
571
+ constructor(collection: string, oid: ObjectId, db?: string, fields?: Document);
572
+ /* Excluded from this release type: namespace */
573
+ /* Excluded from this release type: namespace */
574
+ toJSON(): DBRefLike & Document;
575
+ /* Excluded from this release type: toExtendedJSON */
576
+ /* Excluded from this release type: fromExtendedJSON */
577
+ inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
578
+ }
579
+
580
+ /** @public */
581
+ export declare interface DBRefLike {
582
+ $ref: string;
583
+ $id: ObjectId;
584
+ $db?: string;
585
+ }
586
+
587
+ /**
588
+ * A class representation of the BSON Decimal128 type.
589
+ * @public
590
+ * @category BSONType
591
+ */
592
+ export declare class Decimal128 extends BSONValue {
593
+ get _bsontype(): 'Decimal128';
594
+ readonly bytes: Uint8Array;
595
+ /**
596
+ * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order,
597
+ * or a string representation as returned by .toString()
598
+ */
599
+ constructor(bytes: Uint8Array | string);
600
+ /**
601
+ * Create a Decimal128 instance from a string representation
602
+ *
603
+ * @param representation - a numeric string representation.
604
+ */
605
+ static fromString(representation: string): Decimal128;
606
+ /**
607
+ * Create a Decimal128 instance from a string representation, allowing for rounding to 34
608
+ * significant digits
609
+ *
610
+ * @example Example of a number that will be rounded
611
+ * ```ts
612
+ * > let d = Decimal128.fromString('37.499999999999999196428571428571375')
613
+ * Uncaught:
614
+ * BSONError: "37.499999999999999196428571428571375" is not a valid Decimal128 string - inexact rounding
615
+ * at invalidErr (/home/wajames/js-bson/lib/bson.cjs:1402:11)
616
+ * at Decimal128.fromStringInternal (/home/wajames/js-bson/lib/bson.cjs:1633:25)
617
+ * at Decimal128.fromString (/home/wajames/js-bson/lib/bson.cjs:1424:27)
618
+ *
619
+ * > d = Decimal128.fromStringWithRounding('37.499999999999999196428571428571375')
620
+ * new Decimal128("37.49999999999999919642857142857138")
621
+ * ```
622
+ * @param representation - a numeric string representation.
623
+ */
624
+ static fromStringWithRounding(representation: string): Decimal128;
625
+ private static _fromString;
626
+ /** Create a string representation of the raw Decimal128 value */
627
+ toString(): string;
628
+ toJSON(): Decimal128Extended;
629
+ /* Excluded from this release type: toExtendedJSON */
630
+ /* Excluded from this release type: fromExtendedJSON */
631
+ inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
632
+ }
633
+
634
+ /** @public */
635
+ export declare interface Decimal128Extended {
636
+ $numberDecimal: string;
637
+ }
638
+
639
+ /**
640
+ * Deserialize data as BSON.
641
+ *
642
+ * @param buffer - the buffer containing the serialized set of BSON documents.
643
+ * @returns returns the deserialized Javascript Object.
644
+ * @public
645
+ */
646
+ export declare function deserialize(buffer: Uint8Array, options?: DeserializeOptions): Document;
647
+
648
+ /** @public */
649
+ export declare interface DeserializeOptions {
650
+ /**
651
+ * when deserializing a Long return as a BigInt.
652
+ * @defaultValue `false`
653
+ */
654
+ useBigInt64?: boolean;
655
+ /**
656
+ * when deserializing a Long will fit it into a Number if it's smaller than 53 bits.
657
+ * @defaultValue `true`
658
+ */
659
+ promoteLongs?: boolean;
660
+ /**
661
+ * when deserializing a Binary will return it as a node.js Buffer instance.
662
+ * @defaultValue `false`
663
+ */
664
+ promoteBuffers?: boolean;
665
+ /**
666
+ * when deserializing will promote BSON values to their Node.js closest equivalent types.
667
+ * @defaultValue `true`
668
+ */
669
+ promoteValues?: boolean;
670
+ /**
671
+ * allow to specify if there what fields we wish to return as unserialized raw buffer.
672
+ * @defaultValue `null`
673
+ */
674
+ fieldsAsRaw?: Document;
675
+ /**
676
+ * return BSON regular expressions as BSONRegExp instances.
677
+ * @defaultValue `false`
678
+ */
679
+ bsonRegExp?: boolean;
680
+ /**
681
+ * allows the buffer to be larger than the parsed BSON object.
682
+ * @defaultValue `false`
683
+ */
684
+ allowObjectSmallerThanBufferSize?: boolean;
685
+ /**
686
+ * Offset into buffer to begin reading document from
687
+ * @defaultValue `0`
688
+ */
689
+ index?: number;
690
+ raw?: boolean;
691
+ /** Allows for opt-out utf-8 validation for all keys or
692
+ * specified keys. Must be all true or all false.
693
+ *
694
+ * @example
695
+ * ```js
696
+ * // disables validation on all keys
697
+ * validation: { utf8: false }
698
+ *
699
+ * // enables validation only on specified keys a, b, and c
700
+ * validation: { utf8: { a: true, b: true, c: true } }
701
+ *
702
+ * // disables validation only on specified keys a, b
703
+ * validation: { utf8: { a: false, b: false } }
704
+ * ```
705
+ */
706
+ validation?: {
707
+ utf8: boolean | Record<string, true> | Record<string, false>;
708
+ };
709
+ }
710
+
711
+ /**
712
+ * Deserialize stream data as BSON documents.
713
+ *
714
+ * @param data - the buffer containing the serialized set of BSON documents.
715
+ * @param startIndex - the start index in the data Buffer where the deserialization is to start.
716
+ * @param numberOfDocuments - number of documents to deserialize.
717
+ * @param documents - an array where to store the deserialized documents.
718
+ * @param docStartIndex - the index in the documents array from where to start inserting documents.
719
+ * @param options - additional options used for the deserialization.
720
+ * @returns next index in the buffer after deserialization **x** numbers of documents.
721
+ * @public
722
+ */
723
+ export declare function deserializeStream(data: Uint8Array | ArrayBuffer, startIndex: number, numberOfDocuments: number, documents: Document[], docStartIndex: number, options: DeserializeOptions): number;
724
+
725
+ /** @public */
726
+ export declare interface Document {
727
+ [key: string]: any;
728
+ }
729
+
730
+ /**
731
+ * A class representation of the BSON Double type.
732
+ * @public
733
+ * @category BSONType
734
+ */
735
+ export declare class Double extends BSONValue {
736
+ get _bsontype(): 'Double';
737
+ value: number;
738
+ /**
739
+ * Create a Double type
740
+ *
741
+ * @param value - the number we want to represent as a double.
742
+ */
743
+ constructor(value: number);
744
+ /**
745
+ * Attempt to create an double type from string.
746
+ *
747
+ * This method will throw a BSONError on any string input that is not representable as a IEEE-754 64-bit double.
748
+ * Notably, this method will also throw on the following string formats:
749
+ * - Strings in non-decimal and non-exponential formats (binary, hex, or octal digits)
750
+ * - Strings with characters other than numeric, floating point, or leading sign characters (Note: 'Infinity', '-Infinity', and 'NaN' input strings are still allowed)
751
+ * - Strings with leading and/or trailing whitespace
752
+ *
753
+ * Strings with leading zeros, however, are also allowed
754
+ *
755
+ * @param value - the string we want to represent as a double.
756
+ */
757
+ static fromString(value: string): Double;
758
+ /**
759
+ * Access the number value.
760
+ *
761
+ * @returns returns the wrapped double number.
762
+ */
763
+ valueOf(): number;
764
+ toJSON(): number;
765
+ toString(radix?: number): string;
766
+ /* Excluded from this release type: toExtendedJSON */
767
+ /* Excluded from this release type: fromExtendedJSON */
768
+ inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
769
+ }
770
+
771
+ /** @public */
772
+ export declare interface DoubleExtended {
773
+ $numberDouble: string;
774
+ }
775
+
776
+ /** @public */
777
+ export declare const EJSON: {
778
+ parse: typeof parse;
779
+ stringify: typeof stringify;
780
+ serialize: typeof EJSONserialize;
781
+ deserialize: typeof EJSONdeserialize;
782
+ };
783
+
784
+ /**
785
+ * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types
786
+ *
787
+ * @param ejson - The Extended JSON object to deserialize
788
+ * @param options - Optional settings passed to the parse method
789
+ */
790
+ declare function EJSONdeserialize(ejson: Document, options?: EJSONParseOptions): any;
791
+
792
+ /** @public */
793
+ export declare type EJSONOptions = EJSONSerializeOptions & EJSONParseOptions;
794
+
795
+ /** @public */
796
+ export declare type EJSONOptionsBase = {
797
+ /**
798
+ * Output using the Extended JSON v1 spec
799
+ * @defaultValue `false`
800
+ */
801
+ legacy?: boolean;
802
+ /**
803
+ * Enable Extended JSON's `relaxed` mode, which attempts to return native JS types where possible, rather than BSON types
804
+ * @defaultValue `false`
805
+ */
806
+ relaxed?: boolean;
807
+ };
808
+
809
+ /** @public */
810
+ export declare type EJSONParseOptions = EJSONOptionsBase & {
811
+ /**
812
+ * Enable native bigint support
813
+ * @defaultValue `false`
814
+ */
815
+ useBigInt64?: boolean;
816
+ };
817
+
818
+ /**
819
+ * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.
820
+ *
821
+ * @param value - The object to serialize
822
+ * @param options - Optional settings passed to the `stringify` function
823
+ */
824
+ declare function EJSONserialize(value: any, options?: EJSONSerializeOptions): Document;
825
+
826
+ /** @public */
827
+ export declare type EJSONSerializeOptions = EJSONOptionsBase & {
828
+ /**
829
+ * Omits undefined values from the output instead of converting them to null
830
+ * @defaultValue `false`
831
+ */
832
+ ignoreUndefined?: boolean;
833
+ };
834
+
835
+ declare type InspectFn = (x: unknown, options?: unknown) => string;
836
+
837
+ /**
838
+ * A class representation of a BSON Int32 type.
839
+ * @public
840
+ * @category BSONType
841
+ */
842
+ export declare class Int32 extends BSONValue {
843
+ get _bsontype(): 'Int32';
844
+ value: number;
845
+ /**
846
+ * Create an Int32 type
847
+ *
848
+ * @param value - the number we want to represent as an int32.
849
+ */
850
+ constructor(value: number | string);
851
+ /**
852
+ * Attempt to create an Int32 type from string.
853
+ *
854
+ * This method will throw a BSONError on any string input that is not representable as an Int32.
855
+ * Notably, this method will also throw on the following string formats:
856
+ * - Strings in non-decimal formats (exponent notation, binary, hex, or octal digits)
857
+ * - Strings non-numeric and non-leading sign characters (ex: '2.0', '24,000')
858
+ * - Strings with leading and/or trailing whitespace
859
+ *
860
+ * Strings with leading zeros, however, are allowed.
861
+ *
862
+ * @param value - the string we want to represent as an int32.
863
+ */
864
+ static fromString(value: string): Int32;
865
+ /**
866
+ * Access the number value.
867
+ *
868
+ * @returns returns the wrapped int32 number.
869
+ */
870
+ valueOf(): number;
871
+ toString(radix?: number): string;
872
+ toJSON(): number;
873
+ /* Excluded from this release type: toExtendedJSON */
874
+ /* Excluded from this release type: fromExtendedJSON */
875
+ inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
876
+ }
877
+
878
+ /** @public */
879
+ export declare interface Int32Extended {
880
+ $numberInt: string;
881
+ }
882
+
883
+ /**
884
+ * A class representing a 64-bit integer
885
+ * @public
886
+ * @category BSONType
887
+ * @remarks
888
+ * The internal representation of a long is the two given signed, 32-bit values.
889
+ * We use 32-bit pieces because these are the size of integers on which
890
+ * Javascript performs bit-operations. For operations like addition and
891
+ * multiplication, we split each number into 16 bit pieces, which can easily be
892
+ * multiplied within Javascript's floating-point representation without overflow
893
+ * or change in sign.
894
+ * In the algorithms below, we frequently reduce the negative case to the
895
+ * positive case by negating the input(s) and then post-processing the result.
896
+ * Note that we must ALWAYS check specially whether those values are MIN_VALUE
897
+ * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
898
+ * a positive number, it overflows back into a negative). Not handling this
899
+ * case would often result in infinite recursion.
900
+ * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class.
901
+ */
902
+ export declare class Long extends BSONValue {
903
+ get _bsontype(): 'Long';
904
+ /** An indicator used to reliably determine if an object is a Long or not. */
905
+ get __isLong__(): boolean;
906
+ /**
907
+ * The high 32 bits as a signed value.
908
+ */
909
+ high: number;
910
+ /**
911
+ * The low 32 bits as a signed value.
912
+ */
913
+ low: number;
914
+ /**
915
+ * Whether unsigned or not.
916
+ */
917
+ unsigned: boolean;
918
+ /**
919
+ * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
920
+ *
921
+ * @param low - The low (signed) 32 bits of the long
922
+ * @param high - The high (signed) 32 bits of the long
923
+ * @param unsigned - Whether unsigned or not, defaults to signed
924
+ */
925
+ constructor(low: number, high?: number, unsigned?: boolean);
926
+ /**
927
+ * Constructs a 64 bit two's-complement integer, given a bigint representation.
928
+ *
929
+ * @param value - BigInt representation of the long value
930
+ * @param unsigned - Whether unsigned or not, defaults to signed
931
+ */
932
+ constructor(value: bigint, unsigned?: boolean);
933
+ /**
934
+ * Constructs a 64 bit two's-complement integer, given a string representation.
935
+ *
936
+ * @param value - String representation of the long value
937
+ * @param unsigned - Whether unsigned or not, defaults to signed
938
+ */
939
+ constructor(value: string, unsigned?: boolean);
940
+ static TWO_PWR_24: Long;
941
+ /** Maximum unsigned value. */
942
+ static MAX_UNSIGNED_VALUE: Long;
943
+ /** Signed zero */
944
+ static ZERO: Long;
945
+ /** Unsigned zero. */
946
+ static UZERO: Long;
947
+ /** Signed one. */
948
+ static ONE: Long;
949
+ /** Unsigned one. */
950
+ static UONE: Long;
951
+ /** Signed negative one. */
952
+ static NEG_ONE: Long;
953
+ /** Maximum signed value. */
954
+ static MAX_VALUE: Long;
955
+ /** Minimum signed value. */
956
+ static MIN_VALUE: Long;
957
+ /**
958
+ * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits.
959
+ * Each is assumed to use 32 bits.
960
+ * @param lowBits - The low 32 bits
961
+ * @param highBits - The high 32 bits
962
+ * @param unsigned - Whether unsigned or not, defaults to signed
963
+ * @returns The corresponding Long value
964
+ */
965
+ static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long;
966
+ /**
967
+ * Returns a Long representing the given 32 bit integer value.
968
+ * @param value - The 32 bit integer in question
969
+ * @param unsigned - Whether unsigned or not, defaults to signed
970
+ * @returns The corresponding Long value
971
+ */
972
+ static fromInt(value: number, unsigned?: boolean): Long;
973
+ /**
974
+ * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
975
+ * @param value - The number in question
976
+ * @param unsigned - Whether unsigned or not, defaults to signed
977
+ * @returns The corresponding Long value
978
+ */
979
+ static fromNumber(value: number, unsigned?: boolean): Long;
980
+ /**
981
+ * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
982
+ * @param value - The number in question
983
+ * @param unsigned - Whether unsigned or not, defaults to signed
984
+ * @returns The corresponding Long value
985
+ */
986
+ static fromBigInt(value: bigint, unsigned?: boolean): Long;
987
+ /* Excluded from this release type: _fromString */
988
+ /**
989
+ * Returns a signed Long representation of the given string, written using radix 10.
990
+ * Will throw an error if the given text is not exactly representable as a Long.
991
+ * Throws an error if any of the following conditions are true:
992
+ * - the string contains invalid characters for the radix 10
993
+ * - the string contains whitespace
994
+ * - the value the string represents is too large or too small to be a Long
995
+ * Unlike Long.fromString, this method does not coerce '+/-Infinity' and 'NaN' to Long.Zero
996
+ * @param str - The textual representation of the Long
997
+ * @returns The corresponding Long value
998
+ */
999
+ static fromStringStrict(str: string): Long;
1000
+ /**
1001
+ * Returns a Long representation of the given string, written using the radix 10.
1002
+ * Will throw an error if the given parameters are not exactly representable as a Long.
1003
+ * Throws an error if any of the following conditions are true:
1004
+ * - the string contains invalid characters for the given radix
1005
+ * - the string contains whitespace
1006
+ * - the value the string represents is too large or too small to be a Long
1007
+ * Unlike Long.fromString, this method does not coerce '+/-Infinity' and 'NaN' to Long.Zero
1008
+ * @param str - The textual representation of the Long
1009
+ * @param unsigned - Whether unsigned or not, defaults to signed
1010
+ * @returns The corresponding Long value
1011
+ */
1012
+ static fromStringStrict(str: string, unsigned?: boolean): Long;
1013
+ /**
1014
+ * Returns a signed Long representation of the given string, written using the specified radix.
1015
+ * Will throw an error if the given parameters are not exactly representable as a Long.
1016
+ * Throws an error if any of the following conditions are true:
1017
+ * - the string contains invalid characters for the given radix
1018
+ * - the string contains whitespace
1019
+ * - the value the string represents is too large or too small to be a Long
1020
+ * Unlike Long.fromString, this method does not coerce '+/-Infinity' and 'NaN' to Long.Zero
1021
+ * @param str - The textual representation of the Long
1022
+ * @param radix - The radix in which the text is written (2-36), defaults to 10
1023
+ * @returns The corresponding Long value
1024
+ */
1025
+ static fromStringStrict(str: string, radix?: boolean): Long;
1026
+ /**
1027
+ * Returns a Long representation of the given string, written using the specified radix.
1028
+ * Will throw an error if the given parameters are not exactly representable as a Long.
1029
+ * Throws an error if any of the following conditions are true:
1030
+ * - the string contains invalid characters for the given radix
1031
+ * - the string contains whitespace
1032
+ * - the value the string represents is too large or too small to be a Long
1033
+ * Unlike Long.fromString, this method does not coerce '+/-Infinity' and 'NaN' to Long.Zero
1034
+ * @param str - The textual representation of the Long
1035
+ * @param unsigned - Whether unsigned or not, defaults to signed
1036
+ * @param radix - The radix in which the text is written (2-36), defaults to 10
1037
+ * @returns The corresponding Long value
1038
+ */
1039
+ static fromStringStrict(str: string, unsigned?: boolean, radix?: number): Long;
1040
+ /**
1041
+ * Returns a signed Long representation of the given string, written using radix 10.
1042
+ *
1043
+ * If the input string is empty, this function will throw a BSONError.
1044
+ *
1045
+ * If input string does not have valid signed 64-bit Long representation, this method will return a coerced value:
1046
+ * - inputs that overflow 64-bit signed long will be coerced to Long.MAX_VALUE and Long.MIN_VALUE respectively
1047
+ * - 'NaN' or '+/-Infinity' are coerced to Long.ZERO
1048
+ * - other invalid characters sequences have variable behavior
1049
+ *
1050
+ * @param str - The textual representation of the Long
1051
+ * @returns The corresponding Long value
1052
+ */
1053
+ static fromString(str: string): Long;
1054
+ /**
1055
+ * Returns a signed Long representation of the given string, written using the provided radix.
1056
+ *
1057
+ * If the input string is empty or a provided radix is not within (2-36), this function will throw a BSONError.
1058
+ *
1059
+ * If input parameters do not have valid signed 64-bit Long representation, this method will return a coerced value:
1060
+ * - inputs that overflow 64-bit signed long will be coerced to Long.MAX_VALUE and Long.MIN_VALUE respectively
1061
+ * - if the radix is less than 24, 'NaN' is coerced to Long.ZERO
1062
+ * - if the radix is less than 35, '+/-Infinity' inputs are coerced to Long.ZERO
1063
+ * - other invalid characters sequences have variable behavior
1064
+ * @param str - The textual representation of the Long
1065
+ * @param radix - The radix in which the text is written (2-36), defaults to 10
1066
+ * @returns The corresponding Long value
1067
+ */
1068
+ static fromString(str: string, radix?: number): Long;
1069
+ /**
1070
+ * Returns a Long representation of the given string, written using radix 10.
1071
+ *
1072
+ * If the input string is empty, this function will throw a BSONError.
1073
+ *
1074
+ * If input parameters do not have a valid 64-bit Long representation, this method will return a coerced value:
1075
+ * - inputs that overflow 64-bit long will be coerced to max or min (if signed) values
1076
+ * - if the radix is less than 24, 'NaN' is coerced to Long.ZERO
1077
+ * - if the radix is less than 35, '+/-Infinity' inputs are coerced to Long.ZERO
1078
+ * - other invalid characters sequences have variable behavior
1079
+ * @param str - The textual representation of the Long
1080
+ * @param unsigned - Whether unsigned or not, defaults to signed
1081
+ * @returns The corresponding Long value
1082
+ */
1083
+ static fromString(str: string, unsigned?: boolean): Long;
1084
+ /**
1085
+ * Returns a Long representation of the given string, written using the specified radix.
1086
+ *
1087
+ * If the input string is empty or a provided radix is not within (2-36), this function will throw a BSONError.
1088
+ *
1089
+ * If input parameters do not have a valid 64-bit Long representation, this method will return a coerced value:
1090
+ * - inputs that overflow 64-bit long will be coerced to max or min (if signed) values
1091
+ * - if the radix is less than 24, 'NaN' is coerced to Long.ZERO
1092
+ * - if the radix is less than 35, '+/-Infinity' inputs are coerced to Long.ZERO
1093
+ * - other invalid characters sequences have variable behavior
1094
+ * @param str - The textual representation of the Long
1095
+ * @param unsigned - Whether unsigned or not, defaults to signed
1096
+ * @param radix - The radix in which the text is written (2-36), defaults to 10
1097
+ * @returns The corresponding Long value
1098
+ */
1099
+ static fromString(str: string, unsigned?: boolean, radix?: number): Long;
1100
+ /**
1101
+ * Creates a Long from its byte representation.
1102
+ * @param bytes - Byte representation
1103
+ * @param unsigned - Whether unsigned or not, defaults to signed
1104
+ * @param le - Whether little or big endian, defaults to big endian
1105
+ * @returns The corresponding Long value
1106
+ */
1107
+ static fromBytes(bytes: number[], unsigned?: boolean, le?: boolean): Long;
1108
+ /**
1109
+ * Creates a Long from its little endian byte representation.
1110
+ * @param bytes - Little endian byte representation
1111
+ * @param unsigned - Whether unsigned or not, defaults to signed
1112
+ * @returns The corresponding Long value
1113
+ */
1114
+ static fromBytesLE(bytes: number[], unsigned?: boolean): Long;
1115
+ /**
1116
+ * Creates a Long from its big endian byte representation.
1117
+ * @param bytes - Big endian byte representation
1118
+ * @param unsigned - Whether unsigned or not, defaults to signed
1119
+ * @returns The corresponding Long value
1120
+ */
1121
+ static fromBytesBE(bytes: number[], unsigned?: boolean): Long;
1122
+ /**
1123
+ * Tests if the specified object is a Long.
1124
+ */
1125
+ static isLong(value: unknown): value is Long;
1126
+ /**
1127
+ * Converts the specified value to a Long.
1128
+ * @param unsigned - Whether unsigned or not, defaults to signed
1129
+ */
1130
+ static fromValue(val: number | string | {
1131
+ low: number;
1132
+ high: number;
1133
+ unsigned?: boolean;
1134
+ }, unsigned?: boolean): Long;
1135
+ /** Returns the sum of this and the specified Long. */
1136
+ add(addend: string | number | Long | Timestamp): Long;
1137
+ /**
1138
+ * Returns the sum of this and the specified Long.
1139
+ * @returns Sum
1140
+ */
1141
+ and(other: string | number | Long | Timestamp): Long;
1142
+ /**
1143
+ * Compares this Long's value with the specified's.
1144
+ * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater
1145
+ */
1146
+ compare(other: string | number | Long | Timestamp): 0 | 1 | -1;
1147
+ /** This is an alias of {@link Long.compare} */
1148
+ comp(other: string | number | Long | Timestamp): 0 | 1 | -1;
1149
+ /**
1150
+ * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned.
1151
+ * @returns Quotient
1152
+ */
1153
+ divide(divisor: string | number | Long | Timestamp): Long;
1154
+ /**This is an alias of {@link Long.divide} */
1155
+ div(divisor: string | number | Long | Timestamp): Long;
1156
+ /**
1157
+ * Tests if this Long's value equals the specified's.
1158
+ * @param other - Other value
1159
+ */
1160
+ equals(other: string | number | Long | Timestamp): boolean;
1161
+ /** This is an alias of {@link Long.equals} */
1162
+ eq(other: string | number | Long | Timestamp): boolean;
1163
+ /** Gets the high 32 bits as a signed integer. */
1164
+ getHighBits(): number;
1165
+ /** Gets the high 32 bits as an unsigned integer. */
1166
+ getHighBitsUnsigned(): number;
1167
+ /** Gets the low 32 bits as a signed integer. */
1168
+ getLowBits(): number;
1169
+ /** Gets the low 32 bits as an unsigned integer. */
1170
+ getLowBitsUnsigned(): number;
1171
+ /** Gets the number of bits needed to represent the absolute value of this Long. */
1172
+ getNumBitsAbs(): number;
1173
+ /** Tests if this Long's value is greater than the specified's. */
1174
+ greaterThan(other: string | number | Long | Timestamp): boolean;
1175
+ /** This is an alias of {@link Long.greaterThan} */
1176
+ gt(other: string | number | Long | Timestamp): boolean;
1177
+ /** Tests if this Long's value is greater than or equal the specified's. */
1178
+ greaterThanOrEqual(other: string | number | Long | Timestamp): boolean;
1179
+ /** This is an alias of {@link Long.greaterThanOrEqual} */
1180
+ gte(other: string | number | Long | Timestamp): boolean;
1181
+ /** This is an alias of {@link Long.greaterThanOrEqual} */
1182
+ ge(other: string | number | Long | Timestamp): boolean;
1183
+ /** Tests if this Long's value is even. */
1184
+ isEven(): boolean;
1185
+ /** Tests if this Long's value is negative. */
1186
+ isNegative(): boolean;
1187
+ /** Tests if this Long's value is odd. */
1188
+ isOdd(): boolean;
1189
+ /** Tests if this Long's value is positive. */
1190
+ isPositive(): boolean;
1191
+ /** Tests if this Long's value equals zero. */
1192
+ isZero(): boolean;
1193
+ /** Tests if this Long's value is less than the specified's. */
1194
+ lessThan(other: string | number | Long | Timestamp): boolean;
1195
+ /** This is an alias of {@link Long#lessThan}. */
1196
+ lt(other: string | number | Long | Timestamp): boolean;
1197
+ /** Tests if this Long's value is less than or equal the specified's. */
1198
+ lessThanOrEqual(other: string | number | Long | Timestamp): boolean;
1199
+ /** This is an alias of {@link Long.lessThanOrEqual} */
1200
+ lte(other: string | number | Long | Timestamp): boolean;
1201
+ /** Returns this Long modulo the specified. */
1202
+ modulo(divisor: string | number | Long | Timestamp): Long;
1203
+ /** This is an alias of {@link Long.modulo} */
1204
+ mod(divisor: string | number | Long | Timestamp): Long;
1205
+ /** This is an alias of {@link Long.modulo} */
1206
+ rem(divisor: string | number | Long | Timestamp): Long;
1207
+ /**
1208
+ * Returns the product of this and the specified Long.
1209
+ * @param multiplier - Multiplier
1210
+ * @returns Product
1211
+ */
1212
+ multiply(multiplier: string | number | Long | Timestamp): Long;
1213
+ /** This is an alias of {@link Long.multiply} */
1214
+ mul(multiplier: string | number | Long | Timestamp): Long;
1215
+ /** Returns the Negation of this Long's value. */
1216
+ negate(): Long;
1217
+ /** This is an alias of {@link Long.negate} */
1218
+ neg(): Long;
1219
+ /** Returns the bitwise NOT of this Long. */
1220
+ not(): Long;
1221
+ /** Tests if this Long's value differs from the specified's. */
1222
+ notEquals(other: string | number | Long | Timestamp): boolean;
1223
+ /** This is an alias of {@link Long.notEquals} */
1224
+ neq(other: string | number | Long | Timestamp): boolean;
1225
+ /** This is an alias of {@link Long.notEquals} */
1226
+ ne(other: string | number | Long | Timestamp): boolean;
1227
+ /**
1228
+ * Returns the bitwise OR of this Long and the specified.
1229
+ */
1230
+ or(other: number | string | Long): Long;
1231
+ /**
1232
+ * Returns this Long with bits shifted to the left by the given amount.
1233
+ * @param numBits - Number of bits
1234
+ * @returns Shifted Long
1235
+ */
1236
+ shiftLeft(numBits: number | Long): Long;
1237
+ /** This is an alias of {@link Long.shiftLeft} */
1238
+ shl(numBits: number | Long): Long;
1239
+ /**
1240
+ * Returns this Long with bits arithmetically shifted to the right by the given amount.
1241
+ * @param numBits - Number of bits
1242
+ * @returns Shifted Long
1243
+ */
1244
+ shiftRight(numBits: number | Long): Long;
1245
+ /** This is an alias of {@link Long.shiftRight} */
1246
+ shr(numBits: number | Long): Long;
1247
+ /**
1248
+ * Returns this Long with bits logically shifted to the right by the given amount.
1249
+ * @param numBits - Number of bits
1250
+ * @returns Shifted Long
1251
+ */
1252
+ shiftRightUnsigned(numBits: Long | number): Long;
1253
+ /** This is an alias of {@link Long.shiftRightUnsigned} */
1254
+ shr_u(numBits: number | Long): Long;
1255
+ /** This is an alias of {@link Long.shiftRightUnsigned} */
1256
+ shru(numBits: number | Long): Long;
1257
+ /**
1258
+ * Returns the difference of this and the specified Long.
1259
+ * @param subtrahend - Subtrahend
1260
+ * @returns Difference
1261
+ */
1262
+ subtract(subtrahend: string | number | Long | Timestamp): Long;
1263
+ /** This is an alias of {@link Long.subtract} */
1264
+ sub(subtrahend: string | number | Long | Timestamp): Long;
1265
+ /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */
1266
+ toInt(): number;
1267
+ /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */
1268
+ toNumber(): number;
1269
+ /** Converts the Long to a BigInt (arbitrary precision). */
1270
+ toBigInt(): bigint;
1271
+ /**
1272
+ * Converts this Long to its byte representation.
1273
+ * @param le - Whether little or big endian, defaults to big endian
1274
+ * @returns Byte representation
1275
+ */
1276
+ toBytes(le?: boolean): number[];
1277
+ /**
1278
+ * Converts this Long to its little endian byte representation.
1279
+ * @returns Little endian byte representation
1280
+ */
1281
+ toBytesLE(): number[];
1282
+ /**
1283
+ * Converts this Long to its big endian byte representation.
1284
+ * @returns Big endian byte representation
1285
+ */
1286
+ toBytesBE(): number[];
1287
+ /**
1288
+ * Converts this Long to signed.
1289
+ */
1290
+ toSigned(): Long;
1291
+ /**
1292
+ * Converts the Long to a string written in the specified radix.
1293
+ * @param radix - Radix (2-36), defaults to 10
1294
+ * @throws RangeError If `radix` is out of range
1295
+ */
1296
+ toString(radix?: number): string;
1297
+ /** Converts this Long to unsigned. */
1298
+ toUnsigned(): Long;
1299
+ /** Returns the bitwise XOR of this Long and the given one. */
1300
+ xor(other: Long | number | string): Long;
1301
+ /** This is an alias of {@link Long.isZero} */
1302
+ eqz(): boolean;
1303
+ /** This is an alias of {@link Long.lessThanOrEqual} */
1304
+ le(other: string | number | Long | Timestamp): boolean;
1305
+ toExtendedJSON(options?: EJSONOptions): number | LongExtended;
1306
+ static fromExtendedJSON(doc: {
1307
+ $numberLong: string;
1308
+ }, options?: EJSONOptions): number | Long | bigint;
1309
+ inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
1310
+ }
1311
+
1312
+ /** @public */
1313
+ export declare interface LongExtended {
1314
+ $numberLong: string;
1315
+ }
1316
+
1317
+ /** @public */
1318
+ export declare type LongWithoutOverrides = new (low: unknown, high?: number | boolean, unsigned?: boolean) => {
1319
+ [P in TimestampKept]: Long[P];
1320
+ };
1321
+
1322
+ /** @public */
1323
+ export declare const LongWithoutOverridesClass: LongWithoutOverrides;
1324
+
1325
+ /**
1326
+ * A class representation of the BSON MaxKey type.
1327
+ * @public
1328
+ * @category BSONType
1329
+ */
1330
+ export declare class MaxKey extends BSONValue {
1331
+ get _bsontype(): 'MaxKey';
1332
+ /* Excluded from this release type: toExtendedJSON */
1333
+ /* Excluded from this release type: fromExtendedJSON */
1334
+ inspect(): string;
1335
+ }
1336
+
1337
+ /** @public */
1338
+ export declare interface MaxKeyExtended {
1339
+ $maxKey: 1;
1340
+ }
1341
+
1342
+ /**
1343
+ * A class representation of the BSON MinKey type.
1344
+ * @public
1345
+ * @category BSONType
1346
+ */
1347
+ export declare class MinKey extends BSONValue {
1348
+ get _bsontype(): 'MinKey';
1349
+ /* Excluded from this release type: toExtendedJSON */
1350
+ /* Excluded from this release type: fromExtendedJSON */
1351
+ inspect(): string;
1352
+ }
1353
+
1354
+ /** @public */
1355
+ export declare interface MinKeyExtended {
1356
+ $minKey: 1;
1357
+ }
1358
+
1359
+ /**
1360
+ * @experimental
1361
+ * @public
1362
+ *
1363
+ * A collection of functions that get or set various numeric types and bit widths from a Uint8Array.
1364
+ */
1365
+ export declare type NumberUtils = {
1366
+ /** Is true if the current system is big endian. */
1367
+ isBigEndian: boolean;
1368
+ /**
1369
+ * Parses a signed int32 at offset. Throws a `RangeError` if value is negative.
1370
+ */
1371
+ getNonnegativeInt32LE: (source: Uint8Array, offset: number) => number;
1372
+ getInt32LE: (source: Uint8Array, offset: number) => number;
1373
+ getUint32LE: (source: Uint8Array, offset: number) => number;
1374
+ getUint32BE: (source: Uint8Array, offset: number) => number;
1375
+ getBigInt64LE: (source: Uint8Array, offset: number) => bigint;
1376
+ getFloat64LE: (source: Uint8Array, offset: number) => number;
1377
+ setInt32BE: (destination: Uint8Array, offset: number, value: number) => 4;
1378
+ setInt32LE: (destination: Uint8Array, offset: number, value: number) => 4;
1379
+ setBigInt64LE: (destination: Uint8Array, offset: number, value: bigint) => 8;
1380
+ setFloat64LE: (destination: Uint8Array, offset: number, value: number) => 8;
1381
+ };
1382
+
1383
+ /**
1384
+ * Number parsing and serializing utilities.
1385
+ *
1386
+ * @experimental
1387
+ * @public
1388
+ */
1389
+ export declare const NumberUtils: NumberUtils;
1390
+
1391
+ /**
1392
+ * A class representation of the BSON ObjectId type.
1393
+ * @public
1394
+ * @category BSONType
1395
+ */
1396
+ export declare class ObjectId extends BSONValue {
1397
+ get _bsontype(): 'ObjectId';
1398
+ /* Excluded from this release type: index */
1399
+ /* Excluded from this release type: PROCESS_UNIQUE */
1400
+ /* Excluded from this release type: resetState */
1401
+ static cacheHexString: boolean;
1402
+ /* Excluded from this release type: i0 */
1403
+ /* Excluded from this release type: i1 */
1404
+ /* Excluded from this release type: i2 */
1405
+ /* Excluded from this release type: i3 */
1406
+ /* Excluded from this release type: setFromBytes */
1407
+ /* Excluded from this release type: setFromHex */
1408
+ /** To generate a new ObjectId, use ObjectId() with no argument. */
1409
+ constructor();
1410
+ /**
1411
+ * Create ObjectId from a 24 character hex string.
1412
+ *
1413
+ * @param inputId - A 24 character hex string.
1414
+ */
1415
+ constructor(inputId: string);
1416
+ /**
1417
+ * Create ObjectId from the BSON ObjectId type.
1418
+ *
1419
+ * @param inputId - The BSON ObjectId type.
1420
+ */
1421
+ constructor(inputId: ObjectId);
1422
+ /**
1423
+ * Create ObjectId from the object type that has the toHexString method.
1424
+ *
1425
+ * @param inputId - The ObjectIdLike type.
1426
+ */
1427
+ constructor(inputId: ObjectIdLike);
1428
+ /**
1429
+ * Create ObjectId from a 12 byte binary Buffer.
1430
+ *
1431
+ * @param inputId - A 12 byte binary Buffer.
1432
+ */
1433
+ constructor(inputId: Uint8Array);
1434
+ /**
1435
+ * Implementation overload.
1436
+ *
1437
+ * @param inputId - All input types that are used in the constructor implementation.
1438
+ */
1439
+ constructor(inputId?: string | ObjectId | ObjectIdLike | Uint8Array);
1440
+ /* Excluded from this release type: __constructor */
1441
+ /**
1442
+ * The ObjectId bytes, rebuilt from the packed integer fields on each access. Every read
1443
+ * returns a freshly allocated 12-byte buffer.
1444
+ * @readonly
1445
+ */
1446
+ get id(): Uint8Array;
1447
+ set id(value: Uint8Array);
1448
+ /* Excluded from this release type: validateHexString */
1449
+ /** Returns the ObjectId id as a 24 lowercase character hex string representation */
1450
+ toHexString(): string;
1451
+ /* Excluded from this release type: getInc */
1452
+ /**
1453
+ * Generate a 12 byte id buffer used in ObjectId's
1454
+ *
1455
+ * @param time - pass in a second based timestamp.
1456
+ */
1457
+ static generate(time?: number): Uint8Array;
1458
+ /**
1459
+ * Converts the id into a 24 character hex string for printing, unless encoding is provided.
1460
+ * @param encoding - hex or base64
1461
+ */
1462
+ toString(encoding?: 'hex' | 'base64'): string;
1463
+ /** Converts to its JSON the 24 character hex string representation. */
1464
+ toJSON(): string;
1465
+ /* Excluded from this release type: is */
1466
+ /**
1467
+ * Compares the equality of this ObjectId with `otherID`.
1468
+ *
1469
+ * @param otherId - ObjectId instance to compare against.
1470
+ */
1471
+ equals(otherId: string | ObjectId | ObjectIdLike | undefined | null): boolean;
1472
+ /** Returns the generation date (accurate up to the second) that this ID was generated. */
1473
+ getTimestamp(): Date;
1474
+ /* Excluded from this release type: createPk */
1475
+ /* Excluded from this release type: serializeInto */
1476
+ /**
1477
+ * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId.
1478
+ *
1479
+ * @param time - an integer number representing a number of seconds.
1480
+ */
1481
+ static createFromTime(time: number): ObjectId;
1482
+ /**
1483
+ * Creates an ObjectId from a hex string representation of an ObjectId.
1484
+ *
1485
+ * @param hexString - create a ObjectId from a passed in 24 character hexstring.
1486
+ */
1487
+ static createFromHexString(hexString: string): ObjectId;
1488
+ /** Creates an ObjectId instance from a base64 string */
1489
+ static createFromBase64(base64: string): ObjectId;
1490
+ /**
1491
+ * Checks if a value can be used to create a valid bson ObjectId
1492
+ * @param id - any JS value
1493
+ */
1494
+ static isValid(id: string | ObjectId | ObjectIdLike | Uint8Array): boolean;
1495
+ /* Excluded from this release type: toExtendedJSON */
1496
+ /* Excluded from this release type: fromExtendedJSON */
1497
+ /* Excluded from this release type: isCached */
1498
+ /**
1499
+ * Converts to a string representation of this Id.
1500
+ *
1501
+ * @returns return the 24 character hex string representation.
1502
+ */
1503
+ inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
1504
+ }
1505
+
1506
+ /** @public */
1507
+ export declare interface ObjectIdExtended {
1508
+ $oid: string;
1509
+ }
1510
+
1511
+ /** @public */
1512
+ export declare interface ObjectIdLike {
1513
+ id: string | Uint8Array;
1514
+ __id?: string;
1515
+ toHexString(): string;
1516
+ }
1517
+
1518
+ /**
1519
+ * @experimental
1520
+ * @public
1521
+ *
1522
+ * A new set of BSON APIs that are currently experimental and not intended for production use.
1523
+ */
1524
+ export declare type OnDemand = {
1525
+ parseToElements: (this: void, bytes: Uint8Array, startOffset?: number) => Iterable<BSONElement>;
1526
+ BSONElement: BSONElement;
1527
+ ByteUtils: ByteUtils;
1528
+ NumberUtils: NumberUtils;
1529
+ };
1530
+
1531
+ /**
1532
+ * @experimental
1533
+ * @public
1534
+ */
1535
+ export declare const onDemand: OnDemand;
1536
+
1537
+ /**
1538
+ * Parse an Extended JSON string, constructing the JavaScript value or object described by that
1539
+ * string.
1540
+ *
1541
+ * @example
1542
+ * ```js
1543
+ * const { EJSON } = require('bson');
1544
+ * const text = '{ "int32": { "$numberInt": "10" } }';
1545
+ *
1546
+ * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }
1547
+ * console.log(EJSON.parse(text, { relaxed: false }));
1548
+ *
1549
+ * // prints { int32: 10 }
1550
+ * console.log(EJSON.parse(text));
1551
+ * ```
1552
+ */
1553
+ declare function parse(text: string, options?: EJSONParseOptions): any;
1554
+
1555
+ /**
1556
+ * Serialize a Javascript object.
1557
+ *
1558
+ * @param object - the Javascript object to serialize.
1559
+ * @returns Buffer object containing the serialized object.
1560
+ * @public
1561
+ */
1562
+ export declare function serialize(object: Document, options?: SerializeOptions): Uint8Array;
1563
+
1564
+ /** @public */
1565
+ export declare interface SerializeOptions {
1566
+ /**
1567
+ * the serializer will check if keys are valid.
1568
+ * @defaultValue `false`
1569
+ */
1570
+ checkKeys?: boolean;
1571
+ /**
1572
+ * serialize the javascript functions
1573
+ * @defaultValue `false`
1574
+ */
1575
+ serializeFunctions?: boolean;
1576
+ /**
1577
+ * serialize will not emit undefined fields
1578
+ * note that the driver sets this to `false`
1579
+ * @defaultValue `true`
1580
+ */
1581
+ ignoreUndefined?: boolean;
1582
+ /* Excluded from this release type: minInternalBufferSize */
1583
+ /**
1584
+ * the index in the buffer where we wish to start serializing into
1585
+ * @defaultValue `0`
1586
+ */
1587
+ index?: number;
1588
+ }
1589
+
1590
+ /**
1591
+ * Serialize a Javascript object using a predefined Buffer and index into the buffer,
1592
+ * useful when pre-allocating the space for serialization.
1593
+ *
1594
+ * @param object - the Javascript object to serialize.
1595
+ * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object.
1596
+ * @returns the index pointing to the last written byte in the buffer.
1597
+ * @public
1598
+ */
1599
+ export declare function serializeWithBufferAndIndex(object: Document, finalBuffer: Uint8Array, options?: SerializeOptions): number;
1600
+
1601
+ /**
1602
+ * Sets the size of the internal serialization buffer.
1603
+ *
1604
+ * @param size - The desired size for the internal serialization buffer in bytes
1605
+ * @public
1606
+ */
1607
+ export declare function setInternalBufferSize(size: number): void;
1608
+
1609
+ /**
1610
+ * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer
1611
+ * function is specified or optionally including only the specified properties if a replacer array
1612
+ * is specified.
1613
+ *
1614
+ * @param value - The value to convert to extended JSON
1615
+ * @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
1616
+ * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes.
1617
+ * @param options - Optional settings
1618
+ *
1619
+ * @example
1620
+ * ```js
1621
+ * const { EJSON } = require('bson');
1622
+ * const Int32 = require('mongodb').Int32;
1623
+ * const doc = { int32: new Int32(10) };
1624
+ *
1625
+ * // prints '{"int32":{"$numberInt":"10"}}'
1626
+ * console.log(EJSON.stringify(doc, { relaxed: false }));
1627
+ *
1628
+ * // prints '{"int32":10}'
1629
+ * console.log(EJSON.stringify(doc));
1630
+ *
1631
+ * // prints '{"int32":{"$numberInt":"10"}}' with 2 space indentation
1632
+ * console.log(EJSON.stringify(doc, { relaxed: false }, 2));
1633
+ * ```
1634
+ */
1635
+ declare function stringify(value: any, replacer?: (number | string)[] | ((this: any, key: string, value: any) => any) | null, space?: string | number, options?: EJSONSerializeOptions): string;
1636
+
1637
+ declare function stringify(value: any, replacer?: (number | string)[] | ((this: any, key: string, value: any) => any) | null, options?: EJSONSerializeOptions): string;
1638
+
1639
+ declare function stringify(value: any, options?: EJSONSerializeOptions, space?: string | number): string;
1640
+
1641
+ /**
1642
+ * @public
1643
+ * @category BSONType
1644
+ *
1645
+ * A special type for _internal_ MongoDB use and is **not** associated with the regular Date type.
1646
+ */
1647
+ export declare class Timestamp extends LongWithoutOverridesClass {
1648
+ get _bsontype(): 'Timestamp';
1649
+ get [bsonType](): 'Timestamp';
1650
+ /**
1651
+ * @deprecated Use `Long.MAX_UNSIGNED_VALUE` instead.
1652
+ */
1653
+ static readonly MAX_VALUE: Long;
1654
+ /**
1655
+ * An incrementing ordinal for operations within a given second.
1656
+ */
1657
+ get i(): number;
1658
+ /**
1659
+ * A `time_t` value measuring seconds since the Unix epoch
1660
+ */
1661
+ get t(): number;
1662
+ /**
1663
+ * @param int - A 64-bit bigint representing the Timestamp.
1664
+ */
1665
+ constructor(int: bigint);
1666
+ /**
1667
+ * @param long - A 64-bit Long representing the Timestamp.
1668
+ */
1669
+ constructor(long: Long);
1670
+ /**
1671
+ * @param value - A pair of two values indicating timestamp and increment.
1672
+ */
1673
+ constructor(value: {
1674
+ t: number;
1675
+ i: number;
1676
+ });
1677
+ toJSON(): {
1678
+ $timestamp: string;
1679
+ };
1680
+ /**
1681
+ * Returns a Timestamp represented by the given (32-bit) integer value.
1682
+ * @deprecated Stores `value` in the low 32 bits (increment), leaving t = 0. Use `new Timestamp({ t, i })` or `Timestamp.fromBits(lowBits, highBits)` for explicit construction.
1683
+ */
1684
+ static fromInt(value: number): Timestamp;
1685
+ /**
1686
+ * Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned.
1687
+ * @deprecated Splits `value` across (t, i) as a uint64; the result rarely matches user intent. Use `new Timestamp({ t, i })` or `Timestamp.fromBits(lowBits, highBits)` for explicit construction.
1688
+ */
1689
+ static fromNumber(value: number): Timestamp;
1690
+ /**
1691
+ * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits.
1692
+ *
1693
+ * @param lowBits - the low 32-bits.
1694
+ * @param highBits - the high 32-bits.
1695
+ */
1696
+ static fromBits(lowBits: number, highBits: number): Timestamp;
1697
+ /**
1698
+ * Returns a Timestamp from the given string, optionally using the given radix.
1699
+ *
1700
+ * @param str - the textual representation of the Timestamp.
1701
+ * @param optRadix - the radix in which the text is written.
1702
+ */
1703
+ static fromString(str: string, optRadix: number): Timestamp;
1704
+ /* Excluded from this release type: toExtendedJSON */
1705
+ /* Excluded from this release type: fromExtendedJSON */
1706
+ inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
1707
+ /** @deprecated Not applicable to Timestamp; Timestamp is not intended to be used as a Long. */
1708
+ add: Long['add'];
1709
+ /** @deprecated Not applicable to Timestamp; Timestamp is not intended to be used as a Long. */
1710
+ subtract: Long['subtract'];
1711
+ /** @deprecated Not applicable to Timestamp; Timestamp is not intended to be used as a Long. */
1712
+ sub: Long['sub'];
1713
+ /** @deprecated Not applicable to Timestamp; Timestamp is not intended to be used as a Long. */
1714
+ multiply: Long['multiply'];
1715
+ /** @deprecated Not applicable to Timestamp; Timestamp is not intended to be used as a Long. */
1716
+ mul: Long['mul'];
1717
+ /** @deprecated Not applicable to Timestamp; Timestamp is not intended to be used as a Long. */
1718
+ divide: Long['divide'];
1719
+ /** @deprecated Not applicable to Timestamp; Timestamp is not intended to be used as a Long. */
1720
+ div: Long['div'];
1721
+ /** @deprecated Not applicable to Timestamp; Timestamp is not intended to be used as a Long. */
1722
+ modulo: Long['modulo'];
1723
+ /** @deprecated Not applicable to Timestamp; Timestamp is not intended to be used as a Long. */
1724
+ mod: Long['mod'];
1725
+ /** @deprecated Not applicable to Timestamp; Timestamp is not intended to be used as a Long. */
1726
+ rem: Long['rem'];
1727
+ /** @deprecated Not applicable to Timestamp as the underlying Long is always unsigned. */
1728
+ negate: Long['negate'];
1729
+ /** @deprecated Not applicable to Timestamp as the underlying Long is always unsigned. */
1730
+ neg: Long['neg'];
1731
+ /** @deprecated Not applicable to Timestamp; Timestamp is not intended to be used as a Long. */
1732
+ and: Long['and'];
1733
+ /** @deprecated Not applicable to Timestamp; Timestamp is not intended to be used as a Long. */
1734
+ or: Long['or'];
1735
+ /** @deprecated Not applicable to Timestamp; Timestamp is not intended to be used as a Long. */
1736
+ xor: Long['xor'];
1737
+ /** @deprecated Not applicable to Timestamp; Timestamp is not intended to be used as a Long. */
1738
+ not: Long['not'];
1739
+ /** @deprecated Not applicable to Timestamp; Timestamp is not intended to be used as a Long. */
1740
+ shiftLeft: Long['shiftLeft'];
1741
+ /** @deprecated Not applicable to Timestamp; Timestamp is not intended to be used as a Long. */
1742
+ shl: Long['shl'];
1743
+ /** @deprecated Not applicable to Timestamp; Timestamp is not intended to be used as a Long. */
1744
+ shiftRight: Long['shiftRight'];
1745
+ /** @deprecated Not applicable to Timestamp; Timestamp is not intended to be used as a Long. */
1746
+ shr: Long['shr'];
1747
+ /** @deprecated Not applicable to Timestamp; Timestamp is not intended to be used as a Long. */
1748
+ shiftRightUnsigned: Long['shiftRightUnsigned'];
1749
+ /** @deprecated Not applicable to Timestamp; Timestamp is not intended to be used as a Long. */
1750
+ shr_u: Long['shr_u'];
1751
+ /** @deprecated Not applicable to Timestamp; Timestamp is not intended to be used as a Long. */
1752
+ shru: Long['shru'];
1753
+ /** @deprecated Not applicable to Timestamp as the underlying Long is always unsigned. */
1754
+ toSigned: Long['toSigned'];
1755
+ /** @deprecated Not applicable to Timestamp as the underlying Long is always unsigned (this is a no-op). */
1756
+ toUnsigned: Long['toUnsigned'];
1757
+ /** @deprecated Not applicable to Timestamp as the underlying Long is always unsigned (is always false). */
1758
+ isNegative: Long['isNegative'];
1759
+ /** @deprecated Not applicable to Timestamp as the underlying Long is always unsigned (is always true). */
1760
+ isPositive: Long['isPositive'];
1761
+ /** @deprecated Not applicable to Timestamp as the underlying Long is always unsigned (is always true). */
1762
+ unsigned: Long['unsigned'];
1763
+ /** @deprecated Not applicable to Timestamp; use `.t` for seconds since the Unix epoch, or `.i` for the increment ordinal. */
1764
+ toInt: Long['toInt'];
1765
+ /** @deprecated Not applicable to Timestamp; use `.t` for seconds since the Unix epoch, or `.i` for the increment ordinal. */
1766
+ toNumber: Long['toNumber'];
1767
+ /** @deprecated Not applicable to Timestamp; use `.t` for seconds since the Unix epoch, or `.i` for the increment ordinal. */
1768
+ toBytes: Long['toBytes'];
1769
+ /** @deprecated Not applicable to Timestamp; use `.t` for seconds since the Unix epoch, or `.i` for the increment ordinal. */
1770
+ toBytesLE: Long['toBytesLE'];
1771
+ /** @deprecated Not applicable to Timestamp; use `.t` for seconds since the Unix epoch, or `.i` for the increment ordinal. */
1772
+ toBytesBE: Long['toBytesBE'];
1773
+ /** @deprecated Incompatible with Timestamp: returns a signed integer, but Timestamp is always unsigned. Use `.t` for seconds since the Unix epoch. */
1774
+ getHighBits: Long['getHighBits'];
1775
+ /** @deprecated Not applicable to Timestamp; use `.t` for seconds since the Unix epoch. */
1776
+ getHighBitsUnsigned: Long['getHighBitsUnsigned'];
1777
+ /** @deprecated Incompatible with Timestamp: returns a signed integer, but Timestamp is always unsigned. Use `.i` for the increment ordinal. */
1778
+ getLowBits: Long['getLowBits'];
1779
+ /** @deprecated Not applicable to Timestamp; use `.i` for the increment ordinal. */
1780
+ getLowBitsUnsigned: Long['getLowBitsUnsigned'];
1781
+ /** @deprecated Not applicable to Timestamp; use `.i` instead. */
1782
+ low: Long['low'];
1783
+ /** @deprecated Not applicable to Timestamp; use `.t` instead. */
1784
+ high: Long['high'];
1785
+ /** @deprecated Use .compare() for general comparison, or .equals(), .lessThan(), .greaterThan() for specific cases. */
1786
+ comp: Long['comp'];
1787
+ /** @deprecated Compare `.t` and `.i` against `0` explicitly. */
1788
+ isZero: Long['isZero'];
1789
+ /** @deprecated Compare `.t` and `.i` against `0` explicitly. */
1790
+ eqz: Long['eqz'];
1791
+ /** @deprecated Not applicable to Timestamp. Use the bsonType symbol or _bsontype === 'Timestamp' to identify a Timestamp. */
1792
+ __isLong__: Long['__isLong__'];
1793
+ /** @deprecated Not applicable to Timestamp. */
1794
+ getNumBitsAbs: Long['getNumBitsAbs'];
1795
+ /** @deprecated Not applicable to Timestamp; tests parity of the increment only. */
1796
+ isEven: Long['isEven'];
1797
+ /** @deprecated Not applicable to Timestamp; tests parity of the increment only. */
1798
+ isOdd: Long['isOdd'];
1799
+ }
1800
+
1801
+ /** @public */
1802
+ export declare interface TimestampExtended {
1803
+ $timestamp: {
1804
+ t: number;
1805
+ i: number;
1806
+ };
1807
+ }
1808
+
1809
+ /**
1810
+ * @public
1811
+ *
1812
+ * Inherited `Long` members surfaced on `Timestamp`.
1813
+ * When `Long` gains a new member: add it here if it should pass through, or
1814
+ * add a `@deprecated declare` line on the `Timestamp` class if it should be
1815
+ * surfaced as deprecated. Anything left unclassified is silently dropped from
1816
+ * the public type — preventing accidental behavioral bleed-through.
1817
+ */
1818
+ declare type TimestampKept = 'toBigInt' | 'toString' | 'compare' | 'equals' | 'eq' | 'notEquals' | 'neq' | 'ne' | 'lessThan' | 'lt' | 'lessThanOrEqual' | 'lte' | 'le' | 'greaterThan' | 'gt' | 'greaterThanOrEqual' | 'gte' | 'ge';
1819
+
1820
+ /**
1821
+ * @public
1822
+ * @deprecated This type is no longer used internally and will be removed in a future version.
1823
+ */
1824
+ export declare type TimestampOverrides = '_bsontype' | 'toExtendedJSON' | 'fromExtendedJSON' | 'inspect' | typeof bsonType;
1825
+
1826
+ /**
1827
+ * A class representation of the BSON UUID type.
1828
+ * @public
1829
+ */
1830
+ export declare class UUID extends Binary {
1831
+ /**
1832
+ * Create a UUID type
1833
+ *
1834
+ * When the argument to the constructor is omitted a random v4 UUID will be generated.
1835
+ *
1836
+ * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer.
1837
+ */
1838
+ constructor(input?: string | Uint8Array | UUID);
1839
+ /**
1840
+ * The UUID bytes
1841
+ * @readonly
1842
+ */
1843
+ get id(): Uint8Array;
1844
+ set id(value: Uint8Array);
1845
+ /**
1846
+ * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated)
1847
+ * @param includeDashes - should the string exclude dash-separators.
1848
+ */
1849
+ toHexString(includeDashes?: boolean): string;
1850
+ /**
1851
+ * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified.
1852
+ */
1853
+ toString(encoding?: 'hex' | 'base64'): string;
1854
+ /**
1855
+ * Converts the id into its JSON string representation.
1856
+ * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
1857
+ */
1858
+ toJSON(): string;
1859
+ /**
1860
+ * Compares the equality of this UUID with `otherID`.
1861
+ *
1862
+ * @param otherId - UUID instance to compare against.
1863
+ */
1864
+ equals(otherId: string | Uint8Array | UUID): boolean;
1865
+ /**
1866
+ * Creates a Binary instance from the current UUID.
1867
+ */
1868
+ toBinary(): Binary;
1869
+ /**
1870
+ * Generates a populated buffer containing a v4 uuid
1871
+ */
1872
+ static generate(): Uint8Array;
1873
+ /**
1874
+ * Checks if a value is a valid bson UUID
1875
+ * @param input - UUID, string or Buffer to validate.
1876
+ */
1877
+ static isValid(input: string | Uint8Array | UUID | Binary): boolean;
1878
+ /**
1879
+ * Creates an UUID from a hex string representation of an UUID.
1880
+ * @param hexString - 32 or 36 character hex string (dashes excluded/included).
1881
+ */
1882
+ static createFromHexString(hexString: string): UUID;
1883
+ /** Creates an UUID from a base64 string representation of an UUID. */
1884
+ static createFromBase64(base64: string): UUID;
1885
+ /* Excluded from this release type: bytesFromString */
1886
+ /* Excluded from this release type: isValidUUIDString */
1887
+ /**
1888
+ * Converts to a string representation of this Id.
1889
+ *
1890
+ * @returns return the 36 character hex string representation.
1891
+ *
1892
+ */
1893
+ inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
1894
+ }
1895
+
1896
+ /** @public */
1897
+ export declare type UUIDExtended = {
1898
+ $uuid: string;
1899
+ };
1900
+
1901
+ export { }
gateway/node_modules/bson/etc/prepare.js ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #! /usr/bin/env node
2
+ var cp = require('child_process');
3
+ var fs = require('fs');
4
+
5
+ var nodeMajorVersion = +process.version.match(/^v(\d+)\.\d+/)[1];
6
+
7
+ if (fs.existsSync('src') && nodeMajorVersion >= 10) {
8
+ cp.spawnSync('npm', ['run', 'build'], { stdio: 'inherit', shell: true });
9
+ } else {
10
+ if (!fs.existsSync('lib')) {
11
+ console.warn('BSON: No compiled javascript present, the library is not installed correctly.');
12
+ if (nodeMajorVersion < 10) {
13
+ console.warn(
14
+ 'This library can only be compiled in nodejs version 10 or later, currently running: ' +
15
+ nodeMajorVersion
16
+ );
17
+ }
18
+ }
19
+ }
gateway/node_modules/bson/package.json ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "bson",
3
+ "description": "A bson parser for node.js and the browser",
4
+ "keywords": [
5
+ "mongodb",
6
+ "bson",
7
+ "parser"
8
+ ],
9
+ "files": [
10
+ "lib",
11
+ "src",
12
+ "bson.d.ts",
13
+ "etc/prepare.js",
14
+ "vendor"
15
+ ],
16
+ "types": "bson.d.ts",
17
+ "version": "7.3.2",
18
+ "author": {
19
+ "name": "The MongoDB NodeJS Team",
20
+ "email": "dbx-node@mongodb.com"
21
+ },
22
+ "license": "Apache-2.0",
23
+ "contributors": [],
24
+ "repository": "mongodb/js-bson",
25
+ "bugs": {
26
+ "url": "https://jira.mongodb.org/projects/NODE/issues/"
27
+ },
28
+ "devDependencies": {
29
+ "@istanbuljs/nyc-config-typescript": "^1.0.2",
30
+ "@microsoft/api-extractor": "^7.52.5",
31
+ "@rollup/plugin-node-resolve": "^16.0.1",
32
+ "@rollup/plugin-typescript": "^12.1.2",
33
+ "@types/chai": "^4.3.17",
34
+ "@types/mocha": "^10.0.7",
35
+ "@types/node": "^24.2.1",
36
+ "@types/sinon": "^21.0.0",
37
+ "@types/sinon-chai": "^3.2.12",
38
+ "@typescript-eslint/eslint-plugin": "^8.31.1",
39
+ "@typescript-eslint/parser": "^8.31.1",
40
+ "benchmark": "^2.1.4",
41
+ "chai": "^4.4.1",
42
+ "chalk": "^5.3.0",
43
+ "dbx-js-tools": "github:mongodb-js/dbx-js-tools#main",
44
+ "eslint": "^9.33.0",
45
+ "eslint-config-prettier": "^10.1.2",
46
+ "eslint-plugin-prettier": "^5.2.6",
47
+ "eslint-plugin-tsdoc": "^0.5.2",
48
+ "magic-string": "^0.30.11",
49
+ "mocha": "^11.7.1",
50
+ "node-fetch": "^3.3.2",
51
+ "nyc": "^17.1.0",
52
+ "prettier": "^3.5.3",
53
+ "rollup": "^4.40.1",
54
+ "sinon": "^21.0.0",
55
+ "sinon-chai": "^3.7.0",
56
+ "source-map-support": "^0.5.21",
57
+ "tar": "^7.4.3",
58
+ "ts-node": "^10.9.2",
59
+ "tsd": "^0.33.0",
60
+ "typescript": "^5.8.3",
61
+ "typescript-cached-transpile": "0.0.6",
62
+ "uuid": "^13.0.0"
63
+ },
64
+ "tsd": {
65
+ "directory": "test/types",
66
+ "compilerOptions": {
67
+ "strict": true,
68
+ "target": "esnext",
69
+ "module": "commonjs",
70
+ "moduleResolution": "node"
71
+ }
72
+ },
73
+ "config": {
74
+ "native": false
75
+ },
76
+ "main": "./lib/bson.cjs",
77
+ "module": "./lib/bson.node.mjs",
78
+ "exports": {
79
+ "browser": {
80
+ "types": "./bson.d.ts",
81
+ "default": "./lib/bson.mjs"
82
+ },
83
+ "react-native": "./lib/bson.rn.cjs",
84
+ "default": {
85
+ "types": "./bson.d.ts",
86
+ "import": "./lib/bson.node.mjs",
87
+ "require": "./lib/bson.cjs"
88
+ }
89
+ },
90
+ "compass:exports": {
91
+ "import": "./lib/bson.cjs",
92
+ "require": "./lib/bson.cjs"
93
+ },
94
+ "engines": {
95
+ "node": ">=20.19.0"
96
+ },
97
+ "scripts": {
98
+ "pretest": "npm run build",
99
+ "test": "npm run check:node && npm run check:web",
100
+ "check:node": "WEB=false mocha test/node",
101
+ "check:tsd": "npm run build:dts && tsd",
102
+ "check:web": "WEB=true mocha test/node",
103
+ "check:granular-bench": "npm run build:bench && npm run check:baseline-bench && node ./test/bench/etc/run_granular_benchmarks.js",
104
+ "check:spec-bench": "npm run build:bench && npm run check:baseline-bench && node ./test/bench/lib/spec/bsonBench.js",
105
+ "check:custom-bench": "npm run build && npm run check:baseline-bench && node ./test/bench/custom/main.mjs",
106
+ "check:baseline-bench": "node ./test/bench/etc/cpuBaseline.js",
107
+ "build:bench": "cd test/bench && npx tsc",
108
+ "build:ts": "node ./node_modules/typescript/bin/tsc",
109
+ "build:dts": "npm run build:ts && api-extractor run --typescript-compiler-folder node_modules/typescript --local && node etc/clean_definition_files.cjs",
110
+ "build:bundle": "rollup -c rollup.config.mjs",
111
+ "build": "npm run build:dts && npm run build:bundle",
112
+ "check:lint": "ESLINT_USE_FLAT_CONFIG=false eslint -v && ESLINT_USE_FLAT_CONFIG=false eslint --ext '.js,.ts' --max-warnings=0 src test && npm run build:dts && npm run check:tsd",
113
+ "format": "ESLINT_USE_FLAT_CONFIG=false eslint --ext '.js,.ts' src test --fix",
114
+ "check:coverage": "nyc --check-coverage npm run check:node",
115
+ "prepare": "node etc/prepare.js",
116
+ "release": "standard-version -i HISTORY.md"
117
+ }
118
+ }
gateway/node_modules/bson/src/binary.ts ADDED
@@ -0,0 +1,751 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { type InspectFn, defaultInspect, isAnyArrayBuffer, isUint8Array } from './parser/utils';
2
+ import type { EJSONOptions } from './extended_json';
3
+ import { BSONError } from './error';
4
+ import { BSON_BINARY_SUBTYPE_UUID_NEW } from './constants';
5
+ import { ByteUtils } from './utils/byte_utils';
6
+ import { BSONValue } from './bson_value';
7
+ import { NumberUtils } from './utils/number_utils';
8
+
9
+ /** @public */
10
+ export type BinarySequence = Uint8Array | number[];
11
+
12
+ /** @public */
13
+ export interface BinaryExtendedLegacy {
14
+ $type: string;
15
+ $binary: string;
16
+ }
17
+
18
+ /** @public */
19
+ export interface BinaryExtended {
20
+ $binary: {
21
+ subType: string;
22
+ base64: string;
23
+ };
24
+ }
25
+
26
+ /**
27
+ * A class representation of the BSON Binary type.
28
+ * @public
29
+ * @category BSONType
30
+ */
31
+ export class Binary extends BSONValue {
32
+ get _bsontype(): 'Binary' {
33
+ return 'Binary';
34
+ }
35
+
36
+ /**
37
+ * Binary default subtype
38
+ * @internal
39
+ */
40
+ private static readonly BSON_BINARY_SUBTYPE_DEFAULT = 0;
41
+
42
+ /** Initial buffer default size */
43
+ static readonly BUFFER_SIZE = 256;
44
+ /** Default BSON type */
45
+ static readonly SUBTYPE_DEFAULT = 0;
46
+ /** Function BSON type */
47
+ static readonly SUBTYPE_FUNCTION = 1;
48
+ /**
49
+ * Legacy default BSON Binary type
50
+ * @deprecated BSON Binary subtype 2 is deprecated in the BSON specification
51
+ */
52
+ static readonly SUBTYPE_BYTE_ARRAY = 2;
53
+ /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */
54
+ static readonly SUBTYPE_UUID_OLD = 3;
55
+ /** UUID BSON type */
56
+ static readonly SUBTYPE_UUID = 4;
57
+ /** MD5 BSON type */
58
+ static readonly SUBTYPE_MD5 = 5;
59
+ /** Encrypted BSON type */
60
+ static readonly SUBTYPE_ENCRYPTED = 6;
61
+ /** Column BSON type */
62
+ static readonly SUBTYPE_COLUMN = 7;
63
+ /** Sensitive BSON type */
64
+ static readonly SUBTYPE_SENSITIVE = 8;
65
+ /** Vector BSON type */
66
+ static readonly SUBTYPE_VECTOR = 9;
67
+ /** User BSON type */
68
+ static readonly SUBTYPE_USER_DEFINED = 128;
69
+
70
+ /** datatype of a Binary Vector (subtype: 9) */
71
+ static readonly VECTOR_TYPE = Object.freeze({
72
+ Int8: 0x03,
73
+ Float32: 0x27,
74
+ PackedBit: 0x10
75
+ } as const);
76
+
77
+ /**
78
+ * The bytes of the Binary value.
79
+ *
80
+ * The format of a Binary value in BSON is defined as:
81
+ * ```txt
82
+ * binary ::= int32 subtype (byte*)
83
+ * ```
84
+ *
85
+ * This `buffer` is the "(byte*)" segment.
86
+ *
87
+ * Unless the value is subtype 2, then deserialize will read the first 4 bytes as an int32 and set this to the remaining bytes.
88
+ *
89
+ * ```txt
90
+ * binary ::= int32 unsigned_byte(2) int32 (byte*)
91
+ * ```
92
+ *
93
+ * @see https://bsonspec.org/spec.html
94
+ */
95
+ public buffer: Uint8Array;
96
+ /**
97
+ * The binary subtype.
98
+ *
99
+ * Current defined values are:
100
+ *
101
+ * - `unsigned_byte(0)` Generic binary subtype
102
+ * - `unsigned_byte(1)` Function
103
+ * - `unsigned_byte(2)` Binary (Deprecated)
104
+ * - `unsigned_byte(3)` UUID (Deprecated)
105
+ * - `unsigned_byte(4)` UUID
106
+ * - `unsigned_byte(5)` MD5
107
+ * - `unsigned_byte(6)` Encrypted BSON value
108
+ * - `unsigned_byte(7)` Compressed BSON column
109
+ * - `unsigned_byte(8)` Sensitive
110
+ * - `unsigned_byte(9)` Vector
111
+ * - `unsigned_byte(128)` - `unsigned_byte(255)` User defined
112
+ */
113
+ public sub_type: number;
114
+ /**
115
+ * The Binary's `buffer` can be larger than the Binary's content.
116
+ * This property is used to determine where the content ends in the buffer.
117
+ */
118
+ public position: number;
119
+
120
+ /**
121
+ * Create a new Binary instance.
122
+ * @param buffer - a buffer object containing the binary data.
123
+ * @param subType - the option binary type.
124
+ */
125
+ constructor(buffer?: BinarySequence, subType?: number) {
126
+ super();
127
+ if (
128
+ !(buffer == null) &&
129
+ typeof buffer === 'string' &&
130
+ !ArrayBuffer.isView(buffer) &&
131
+ !isAnyArrayBuffer(buffer) &&
132
+ !Array.isArray(buffer)
133
+ ) {
134
+ throw new BSONError('Binary can only be constructed from Uint8Array or number[]');
135
+ }
136
+
137
+ this.sub_type = (subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT) & 0xff;
138
+
139
+ if (buffer == null) {
140
+ // create an empty binary buffer
141
+ this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE);
142
+ this.position = 0;
143
+ } else {
144
+ this.buffer = Array.isArray(buffer)
145
+ ? ByteUtils.fromNumberArray(buffer)
146
+ : ByteUtils.toLocalBufferType(buffer);
147
+ this.position = this.buffer.byteLength;
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Updates this binary with byte_value.
153
+ *
154
+ * @param byteValue - a single byte we wish to write.
155
+ */
156
+ put(byteValue: string | number | Uint8Array | number[]): void {
157
+ // If it's a string and a has more than one character throw an error
158
+ if (typeof byteValue === 'string' && byteValue.length !== 1) {
159
+ throw new BSONError('only accepts single character String');
160
+ } else if (typeof byteValue !== 'number' && byteValue.length !== 1)
161
+ throw new BSONError('only accepts single character Uint8Array or Array');
162
+
163
+ // Decode the byte value once
164
+ let decodedByte: number;
165
+ if (typeof byteValue === 'string') {
166
+ decodedByte = byteValue.charCodeAt(0);
167
+ } else if (typeof byteValue === 'number') {
168
+ decodedByte = byteValue;
169
+ } else {
170
+ decodedByte = byteValue[0];
171
+ }
172
+
173
+ if (decodedByte < 0 || decodedByte > 255) {
174
+ throw new BSONError('only accepts number in a valid unsigned byte range 0-255');
175
+ }
176
+
177
+ if (this.buffer.byteLength > this.position) {
178
+ this.buffer[this.position++] = decodedByte;
179
+ } else {
180
+ const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length);
181
+ newSpace.set(this.buffer, 0);
182
+ this.buffer = newSpace;
183
+ this.buffer[this.position++] = decodedByte;
184
+ }
185
+ }
186
+
187
+ /**
188
+ * Writes a buffer to the binary.
189
+ *
190
+ * @param sequence - a string or buffer to be written to the Binary BSON object.
191
+ * @param offset - specify the binary of where to write the content.
192
+ */
193
+ write(sequence: BinarySequence, offset: number): void {
194
+ offset = typeof offset === 'number' ? offset : this.position;
195
+
196
+ // If the buffer is to small let's extend the buffer
197
+ if (this.buffer.byteLength < offset + sequence.length) {
198
+ const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length);
199
+ newSpace.set(this.buffer, 0);
200
+
201
+ // Assign the new buffer
202
+ this.buffer = newSpace;
203
+ }
204
+
205
+ if (ArrayBuffer.isView(sequence)) {
206
+ this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset);
207
+ this.position =
208
+ offset + sequence.byteLength > this.position ? offset + sequence.length : this.position;
209
+ } else if (typeof sequence === 'string') {
210
+ throw new BSONError('input cannot be string');
211
+ }
212
+ }
213
+
214
+ /**
215
+ * Returns a view of **length** bytes starting at **position**.
216
+ *
217
+ * @param position - read from the given position in the Binary.
218
+ * @param length - the number of bytes to read.
219
+ */
220
+ read(position: number, length: number): Uint8Array {
221
+ length = length && length > 0 ? length : this.position;
222
+ const end = position + length;
223
+ return this.buffer.subarray(position, end > this.position ? this.position : end);
224
+ }
225
+
226
+ /** returns a view of the binary value as a Uint8Array */
227
+ value(): Uint8Array {
228
+ // Optimize to serialize for the situation where the data == size of buffer
229
+ return this.buffer.length === this.position
230
+ ? this.buffer
231
+ : this.buffer.subarray(0, this.position);
232
+ }
233
+
234
+ /** the length of the binary sequence */
235
+ length(): number {
236
+ return this.position;
237
+ }
238
+
239
+ toJSON(): string {
240
+ return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
241
+ }
242
+
243
+ toString(encoding?: 'hex' | 'base64' | 'utf8' | 'utf-8'): string {
244
+ if (encoding === 'hex') return ByteUtils.toHex(this.buffer.subarray(0, this.position));
245
+ if (encoding === 'base64') return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
246
+ if (encoding === 'utf8' || encoding === 'utf-8')
247
+ return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
248
+ return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
249
+ }
250
+
251
+ /** @internal */
252
+ toExtendedJSON(options?: EJSONOptions): BinaryExtendedLegacy | BinaryExtended {
253
+ options = options || {};
254
+
255
+ if (this.sub_type === Binary.SUBTYPE_VECTOR) {
256
+ validateBinaryVector(this);
257
+ }
258
+
259
+ const base64String = ByteUtils.toBase64(this.buffer);
260
+
261
+ const subType = Number(this.sub_type).toString(16);
262
+ if (options.legacy) {
263
+ return {
264
+ $binary: base64String,
265
+ $type: subType.length === 1 ? '0' + subType : subType
266
+ };
267
+ }
268
+ return {
269
+ $binary: {
270
+ base64: base64String,
271
+ subType: subType.length === 1 ? '0' + subType : subType
272
+ }
273
+ };
274
+ }
275
+
276
+ toUUID(): UUID {
277
+ if (this.sub_type === Binary.SUBTYPE_UUID) {
278
+ return new UUID(this.buffer.subarray(0, this.position));
279
+ }
280
+
281
+ throw new BSONError(
282
+ `Binary sub_type "${this.sub_type}" (${typeof this.sub_type}) is not supported for converting to UUID. Only 0x${Binary.SUBTYPE_UUID.toString(16).padStart(2, '0')} is currently supported.`
283
+ );
284
+ }
285
+
286
+ /** Creates an Binary instance from a hex digit string */
287
+ static createFromHexString(hex: string, subType?: number): Binary {
288
+ return new Binary(ByteUtils.fromHex(hex), subType);
289
+ }
290
+
291
+ /** Creates an Binary instance from a base64 string */
292
+ static createFromBase64(base64: string, subType?: number): Binary {
293
+ return new Binary(ByteUtils.fromBase64(base64), subType);
294
+ }
295
+
296
+ /** @internal */
297
+ static fromExtendedJSON(
298
+ doc: BinaryExtendedLegacy | BinaryExtended | UUIDExtended,
299
+ options?: EJSONOptions
300
+ ): Binary {
301
+ options = options || {};
302
+ let data: Uint8Array | undefined;
303
+ let type;
304
+ if ('$binary' in doc) {
305
+ if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) {
306
+ type = doc.$type ? parseInt(doc.$type, 16) : 0;
307
+ data = ByteUtils.fromBase64(doc.$binary);
308
+ } else {
309
+ if (typeof doc.$binary !== 'string') {
310
+ type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
311
+ data = ByteUtils.fromBase64(doc.$binary.base64);
312
+ }
313
+ }
314
+ } else if ('$uuid' in doc) {
315
+ type = 4;
316
+ data = UUID.bytesFromString(doc.$uuid);
317
+ }
318
+ if (!data) {
319
+ throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`);
320
+ }
321
+ return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type);
322
+ }
323
+
324
+ inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
325
+ inspect ??= defaultInspect;
326
+ const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position));
327
+ const base64Arg = inspect(base64, options);
328
+ const subTypeArg = inspect(this.sub_type, options);
329
+ return `Binary.createFromBase64(${base64Arg}, ${subTypeArg})`;
330
+ }
331
+
332
+ /**
333
+ * If this Binary represents a Int8 Vector (`binary.buffer[0] === Binary.VECTOR_TYPE.Int8`),
334
+ * returns a copy of the bytes in a new Int8Array.
335
+ *
336
+ * If the Binary is not a Vector, or the datatype is not Int8, an error is thrown.
337
+ */
338
+ public toInt8Array(): Int8Array {
339
+ if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
340
+ throw new BSONError('Binary sub_type is not Vector');
341
+ }
342
+
343
+ if (this.buffer[0] !== Binary.VECTOR_TYPE.Int8) {
344
+ throw new BSONError('Binary datatype field is not Int8');
345
+ }
346
+
347
+ validateBinaryVector(this);
348
+
349
+ return new Int8Array(
350
+ this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position)
351
+ );
352
+ }
353
+
354
+ /**
355
+ * If this Binary represents a Float32 Vector (`binary.buffer[0] === Binary.VECTOR_TYPE.Float32`),
356
+ * returns a copy of the bytes in a new Float32Array.
357
+ *
358
+ * If the Binary is not a Vector, or the datatype is not Float32, an error is thrown.
359
+ */
360
+ public toFloat32Array(): Float32Array {
361
+ if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
362
+ throw new BSONError('Binary sub_type is not Vector');
363
+ }
364
+
365
+ if (this.buffer[0] !== Binary.VECTOR_TYPE.Float32) {
366
+ throw new BSONError('Binary datatype field is not Float32');
367
+ }
368
+
369
+ validateBinaryVector(this);
370
+
371
+ const floatBytes = new Uint8Array(
372
+ this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position)
373
+ );
374
+
375
+ if (NumberUtils.isBigEndian) ByteUtils.swap32(floatBytes);
376
+
377
+ return new Float32Array(floatBytes.buffer);
378
+ }
379
+
380
+ /**
381
+ * If this Binary represents packed bit Vector (`binary.buffer[0] === Binary.VECTOR_TYPE.PackedBit`),
382
+ * returns a copy of the bytes that are packed bits.
383
+ *
384
+ * Use `toBits` to get the unpacked bits.
385
+ *
386
+ * If the Binary is not a Vector, or the datatype is not PackedBit, an error is thrown.
387
+ */
388
+ public toPackedBits(): Uint8Array {
389
+ if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
390
+ throw new BSONError('Binary sub_type is not Vector');
391
+ }
392
+
393
+ if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) {
394
+ throw new BSONError('Binary datatype field is not packed bit');
395
+ }
396
+
397
+ validateBinaryVector(this);
398
+
399
+ return new Uint8Array(
400
+ this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position)
401
+ );
402
+ }
403
+
404
+ /**
405
+ * If this Binary represents a Packed bit Vector (`binary.buffer[0] === Binary.VECTOR_TYPE.PackedBit`),
406
+ * returns a copy of the bit unpacked into a new Int8Array.
407
+ *
408
+ * Use `toPackedBits` to get the bits still in packed form.
409
+ *
410
+ * If the Binary is not a Vector, or the datatype is not PackedBit, an error is thrown.
411
+ */
412
+ public toBits(): Int8Array {
413
+ if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
414
+ throw new BSONError('Binary sub_type is not Vector');
415
+ }
416
+
417
+ if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) {
418
+ throw new BSONError('Binary datatype field is not packed bit');
419
+ }
420
+
421
+ validateBinaryVector(this);
422
+
423
+ const byteCount = this.length() - 2;
424
+ const bitCount = byteCount * 8 - this.buffer[1];
425
+ const bits = new Int8Array(bitCount);
426
+
427
+ for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {
428
+ const byteOffset = (bitOffset / 8) | 0;
429
+ const byte = this.buffer[byteOffset + 2];
430
+ const shift = 7 - (bitOffset % 8);
431
+ const bit = (byte >> shift) & 1;
432
+ bits[bitOffset] = bit;
433
+ }
434
+
435
+ return bits;
436
+ }
437
+
438
+ /**
439
+ * Constructs a Binary representing an Int8 Vector.
440
+ * @param array - The array to store as a view on the Binary class
441
+ */
442
+ public static fromInt8Array(array: Int8Array): Binary {
443
+ const buffer = ByteUtils.allocate(array.byteLength + 2);
444
+ buffer[0] = Binary.VECTOR_TYPE.Int8;
445
+ buffer[1] = 0;
446
+ const intBytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
447
+ buffer.set(intBytes, 2);
448
+ const bin = new this(buffer, this.SUBTYPE_VECTOR);
449
+ validateBinaryVector(bin);
450
+ return bin;
451
+ }
452
+
453
+ /** Constructs a Binary representing an Float32 Vector. */
454
+ public static fromFloat32Array(array: Float32Array): Binary {
455
+ const binaryBytes = ByteUtils.allocate(array.byteLength + 2);
456
+ binaryBytes[0] = Binary.VECTOR_TYPE.Float32;
457
+ binaryBytes[1] = 0;
458
+
459
+ const floatBytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
460
+ binaryBytes.set(floatBytes, 2);
461
+
462
+ if (NumberUtils.isBigEndian) ByteUtils.swap32(new Uint8Array(binaryBytes.buffer, 2));
463
+
464
+ const bin = new this(binaryBytes, this.SUBTYPE_VECTOR);
465
+ validateBinaryVector(bin);
466
+ return bin;
467
+ }
468
+
469
+ /**
470
+ * Constructs a Binary representing a packed bit Vector.
471
+ *
472
+ * Use `fromBits` to pack an array of 1s and 0s.
473
+ */
474
+ public static fromPackedBits(array: Uint8Array, padding = 0): Binary {
475
+ const buffer = ByteUtils.allocate(array.byteLength + 2);
476
+ buffer[0] = Binary.VECTOR_TYPE.PackedBit;
477
+ buffer[1] = padding;
478
+ buffer.set(array, 2);
479
+ const bin = new this(buffer, this.SUBTYPE_VECTOR);
480
+ validateBinaryVector(bin);
481
+ return bin;
482
+ }
483
+
484
+ /**
485
+ * Constructs a Binary representing an Packed Bit Vector.
486
+ * @param array - The array of 1s and 0s to pack into the Binary instance
487
+ */
488
+ public static fromBits(bits: ArrayLike<number>): Binary {
489
+ const byteLength = (bits.length + 7) >>> 3; // ceil(bits.length / 8)
490
+ const bytes = new Uint8Array(byteLength + 2);
491
+ bytes[0] = Binary.VECTOR_TYPE.PackedBit;
492
+
493
+ const remainder = bits.length % 8;
494
+ bytes[1] = remainder === 0 ? 0 : 8 - remainder;
495
+
496
+ for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {
497
+ const byteOffset = bitOffset >>> 3; // floor(bitOffset / 8)
498
+ const bit = bits[bitOffset];
499
+
500
+ if (bit !== 0 && bit !== 1) {
501
+ throw new BSONError(
502
+ `Invalid bit value at ${bitOffset}: must be 0 or 1, found ${bits[bitOffset]}`
503
+ );
504
+ }
505
+
506
+ if (bit === 0) continue;
507
+
508
+ const shift = 7 - (bitOffset % 8);
509
+ bytes[byteOffset + 2] |= bit << shift;
510
+ }
511
+
512
+ return new this(bytes, Binary.SUBTYPE_VECTOR);
513
+ }
514
+ }
515
+
516
+ export function validateBinaryVector(vector: Binary): void {
517
+ if (vector.sub_type !== Binary.SUBTYPE_VECTOR) return;
518
+
519
+ const size = vector.position;
520
+
521
+ // NOTE: Validation is only applied to **KNOWN** vector types
522
+ // If a new datatype is introduced, a future version of the library will need to add validation
523
+ const datatype = vector.buffer[0];
524
+
525
+ // NOTE: We do not enable noUncheckedIndexedAccess so TS believes this is always number
526
+ // a Binary vector may be empty, in which case the padding is undefined
527
+ // this possible value is tolerable for our validation checks
528
+ const padding: number | undefined = vector.buffer[1];
529
+
530
+ if (
531
+ (datatype === Binary.VECTOR_TYPE.Float32 || datatype === Binary.VECTOR_TYPE.Int8) &&
532
+ padding !== 0
533
+ ) {
534
+ throw new BSONError('Invalid Vector: padding must be zero for int8 and float32 vectors');
535
+ }
536
+
537
+ if (datatype === Binary.VECTOR_TYPE.Float32) {
538
+ if (size !== 0 && size - 2 !== 0 && (size - 2) % 4 !== 0) {
539
+ throw new BSONError('Invalid Vector: Float32 vector must contain a multiple of 4 bytes');
540
+ }
541
+ }
542
+
543
+ if (datatype === Binary.VECTOR_TYPE.PackedBit && padding !== 0 && size === 2) {
544
+ throw new BSONError(
545
+ 'Invalid Vector: padding must be zero for packed bit vectors that are empty'
546
+ );
547
+ }
548
+
549
+ if (datatype === Binary.VECTOR_TYPE.PackedBit && padding > 7) {
550
+ throw new BSONError(
551
+ `Invalid Vector: padding must be a value between 0 and 7. found: ${padding}`
552
+ );
553
+ }
554
+ }
555
+
556
+ /** @public */
557
+ export type UUIDExtended = {
558
+ $uuid: string;
559
+ };
560
+
561
+ const UUID_BYTE_LENGTH = 16;
562
+ const UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i;
563
+ const UUID_WITH_DASHES = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;
564
+
565
+ /**
566
+ * A class representation of the BSON UUID type.
567
+ * @public
568
+ */
569
+ export class UUID extends Binary {
570
+ /**
571
+ * Create a UUID type
572
+ *
573
+ * When the argument to the constructor is omitted a random v4 UUID will be generated.
574
+ *
575
+ * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer.
576
+ */
577
+ constructor(input?: string | Uint8Array | UUID) {
578
+ let bytes: Uint8Array;
579
+ if (input == null) {
580
+ bytes = UUID.generate();
581
+ } else if (input instanceof UUID) {
582
+ bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));
583
+ } else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) {
584
+ bytes = ByteUtils.toLocalBufferType(input);
585
+ } else if (typeof input === 'string') {
586
+ bytes = UUID.bytesFromString(input);
587
+ } else {
588
+ throw new BSONError(
589
+ 'Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'
590
+ );
591
+ }
592
+ super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW);
593
+ }
594
+
595
+ /**
596
+ * The UUID bytes
597
+ * @readonly
598
+ */
599
+ get id(): Uint8Array {
600
+ return this.buffer;
601
+ }
602
+
603
+ set id(value: Uint8Array) {
604
+ this.buffer = value;
605
+ }
606
+
607
+ /**
608
+ * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated)
609
+ * @param includeDashes - should the string exclude dash-separators.
610
+ */
611
+ toHexString(includeDashes = true): string {
612
+ if (includeDashes) {
613
+ return [
614
+ ByteUtils.toHex(this.buffer.subarray(0, 4)),
615
+ ByteUtils.toHex(this.buffer.subarray(4, 6)),
616
+ ByteUtils.toHex(this.buffer.subarray(6, 8)),
617
+ ByteUtils.toHex(this.buffer.subarray(8, 10)),
618
+ ByteUtils.toHex(this.buffer.subarray(10, 16))
619
+ ].join('-');
620
+ }
621
+ return ByteUtils.toHex(this.buffer);
622
+ }
623
+
624
+ /**
625
+ * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified.
626
+ */
627
+ toString(encoding?: 'hex' | 'base64'): string {
628
+ if (encoding === 'hex') return ByteUtils.toHex(this.id);
629
+ if (encoding === 'base64') return ByteUtils.toBase64(this.id);
630
+ return this.toHexString();
631
+ }
632
+
633
+ /**
634
+ * Converts the id into its JSON string representation.
635
+ * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
636
+ */
637
+ toJSON(): string {
638
+ return this.toHexString();
639
+ }
640
+
641
+ /**
642
+ * Compares the equality of this UUID with `otherID`.
643
+ *
644
+ * @param otherId - UUID instance to compare against.
645
+ */
646
+ equals(otherId: string | Uint8Array | UUID): boolean {
647
+ if (!otherId) {
648
+ return false;
649
+ }
650
+
651
+ if (otherId instanceof UUID) {
652
+ return ByteUtils.equals(otherId.id, this.id);
653
+ }
654
+
655
+ try {
656
+ return ByteUtils.equals(new UUID(otherId).id, this.id);
657
+ } catch {
658
+ return false;
659
+ }
660
+ }
661
+
662
+ /**
663
+ * Creates a Binary instance from the current UUID.
664
+ */
665
+ toBinary(): Binary {
666
+ return new Binary(this.id, Binary.SUBTYPE_UUID);
667
+ }
668
+
669
+ /**
670
+ * Generates a populated buffer containing a v4 uuid
671
+ */
672
+ static generate(): Uint8Array {
673
+ const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH);
674
+
675
+ // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
676
+ // Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js
677
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
678
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
679
+
680
+ return bytes;
681
+ }
682
+
683
+ /**
684
+ * Checks if a value is a valid bson UUID
685
+ * @param input - UUID, string or Buffer to validate.
686
+ */
687
+ static isValid(input: string | Uint8Array | UUID | Binary): boolean {
688
+ if (!input) {
689
+ return false;
690
+ }
691
+
692
+ if (typeof input === 'string') {
693
+ return UUID.isValidUUIDString(input);
694
+ }
695
+
696
+ if (isUint8Array(input)) {
697
+ return input.byteLength === UUID_BYTE_LENGTH;
698
+ }
699
+
700
+ return (
701
+ input._bsontype === 'Binary' &&
702
+ input.sub_type === this.SUBTYPE_UUID &&
703
+ input.buffer.byteLength === 16
704
+ );
705
+ }
706
+
707
+ /**
708
+ * Creates an UUID from a hex string representation of an UUID.
709
+ * @param hexString - 32 or 36 character hex string (dashes excluded/included).
710
+ */
711
+ static override createFromHexString(hexString: string): UUID {
712
+ const buffer = UUID.bytesFromString(hexString);
713
+ return new UUID(buffer);
714
+ }
715
+
716
+ /** Creates an UUID from a base64 string representation of an UUID. */
717
+ static override createFromBase64(base64: string): UUID {
718
+ return new UUID(ByteUtils.fromBase64(base64));
719
+ }
720
+
721
+ /** @internal */
722
+ static bytesFromString(representation: string) {
723
+ if (!UUID.isValidUUIDString(representation)) {
724
+ throw new BSONError(
725
+ 'UUID string representation must be 32 hex digits or canonical hyphenated representation'
726
+ );
727
+ }
728
+ return ByteUtils.fromHex(representation.replace(/-/g, ''));
729
+ }
730
+
731
+ /**
732
+ * @internal
733
+ *
734
+ * Validates a string to be a hex digit sequence with or without dashes.
735
+ * The canonical hyphenated representation of a uuid is hex in 8-4-4-4-12 groups.
736
+ */
737
+ static isValidUUIDString(representation: string) {
738
+ return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation);
739
+ }
740
+
741
+ /**
742
+ * Converts to a string representation of this Id.
743
+ *
744
+ * @returns return the 36 character hex string representation.
745
+ *
746
+ */
747
+ inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
748
+ inspect ??= defaultInspect;
749
+ return `new UUID(${inspect(this.toHexString(), options)})`;
750
+ }
751
+ }
gateway/node_modules/bson/src/bson.ts ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Binary, UUID } from './binary';
2
+ import { Code } from './code';
3
+ import { DBRef } from './db_ref';
4
+ import { Decimal128 } from './decimal128';
5
+ import { Double } from './double';
6
+ import { Int32 } from './int_32';
7
+ import { Long } from './long';
8
+ import { MaxKey } from './max_key';
9
+ import { MinKey } from './min_key';
10
+ import { ObjectId } from './objectid';
11
+ import { internalCalculateObjectSize } from './parser/calculate_size';
12
+ // Parts of the parser
13
+ import { internalDeserialize, type DeserializeOptions } from './parser/deserializer';
14
+ import { serializeInto, type SerializeOptions } from './parser/serializer';
15
+ import { BSONRegExp } from './regexp';
16
+ import { BSONSymbol } from './symbol';
17
+ import { Timestamp } from './timestamp';
18
+ import { ByteUtils } from './utils/byte_utils';
19
+ import { NumberUtils } from './utils/number_utils';
20
+ export type { UUIDExtended, BinaryExtended, BinaryExtendedLegacy, BinarySequence } from './binary';
21
+ export type { CodeExtended } from './code';
22
+ export type { DBRefLike } from './db_ref';
23
+ export type { Decimal128Extended } from './decimal128';
24
+ export type { DoubleExtended } from './double';
25
+ export type {
26
+ EJSONOptions,
27
+ EJSONOptionsBase,
28
+ EJSONSerializeOptions,
29
+ EJSONParseOptions
30
+ } from './extended_json';
31
+ export type { Int32Extended } from './int_32';
32
+ export type { LongExtended } from './long';
33
+ export type { MaxKeyExtended } from './max_key';
34
+ export type { MinKeyExtended } from './min_key';
35
+ export type { ObjectIdExtended, ObjectIdLike } from './objectid';
36
+ export type { BSONRegExpExtended, BSONRegExpExtendedLegacy } from './regexp';
37
+ export type { BSONSymbolExtended } from './symbol';
38
+ export type { LongWithoutOverrides, TimestampExtended, TimestampOverrides } from './timestamp';
39
+ export type { LongWithoutOverridesClass } from './timestamp';
40
+ export type { SerializeOptions, DeserializeOptions };
41
+
42
+ export {
43
+ Code,
44
+ BSONSymbol,
45
+ DBRef,
46
+ Binary,
47
+ ObjectId,
48
+ UUID,
49
+ Long,
50
+ Timestamp,
51
+ Double,
52
+ Int32,
53
+ MinKey,
54
+ MaxKey,
55
+ BSONRegExp,
56
+ Decimal128,
57
+ NumberUtils,
58
+ ByteUtils
59
+ };
60
+ export { BSONValue, bsonType, type BSONTypeTag } from './bson_value';
61
+ export { BSONError, BSONVersionError, BSONRuntimeError, BSONOffsetError } from './error';
62
+ export { BSONType } from './constants';
63
+ export { EJSON } from './extended_json';
64
+ export { onDemand, type OnDemand } from './parser/on_demand/index';
65
+
66
+ /** @public */
67
+ export interface Document {
68
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
69
+ [key: string]: any;
70
+ }
71
+
72
+ /** @internal */
73
+ // Default Max Size
74
+ const MAXSIZE = 1024 * 1024 * 17;
75
+
76
+ // Current Internal Temporary Serialization Buffer
77
+ let buffer = ByteUtils.allocate(MAXSIZE);
78
+
79
+ /**
80
+ * Sets the size of the internal serialization buffer.
81
+ *
82
+ * @param size - The desired size for the internal serialization buffer in bytes
83
+ * @public
84
+ */
85
+ export function setInternalBufferSize(size: number): void {
86
+ // Resize the internal serialization buffer if needed
87
+ if (buffer.length < size) {
88
+ buffer = ByteUtils.allocate(size);
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Serialize a Javascript object.
94
+ *
95
+ * @param object - the Javascript object to serialize.
96
+ * @returns Buffer object containing the serialized object.
97
+ * @public
98
+ */
99
+ export function serialize(object: Document, options: SerializeOptions = {}): Uint8Array {
100
+ // Unpack the options
101
+ const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
102
+ const serializeFunctions =
103
+ typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
104
+ const ignoreUndefined =
105
+ typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
106
+ const minInternalBufferSize =
107
+ typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE;
108
+
109
+ // Resize the internal serialization buffer if needed
110
+ if (buffer.length < minInternalBufferSize) {
111
+ buffer = ByteUtils.allocate(minInternalBufferSize);
112
+ }
113
+
114
+ // Attempt to serialize
115
+ const serializationIndex = serializeInto(
116
+ buffer,
117
+ object,
118
+ checkKeys,
119
+ 0,
120
+ serializeFunctions,
121
+ ignoreUndefined,
122
+ null
123
+ );
124
+
125
+ // Create the final buffer
126
+ const finishedBuffer = ByteUtils.allocateUnsafe(serializationIndex);
127
+
128
+ // Copy into the finished buffer
129
+ finishedBuffer.set(buffer.subarray(0, serializationIndex), 0);
130
+
131
+ // Return the buffer
132
+ return finishedBuffer;
133
+ }
134
+
135
+ /**
136
+ * Serialize a Javascript object using a predefined Buffer and index into the buffer,
137
+ * useful when pre-allocating the space for serialization.
138
+ *
139
+ * @param object - the Javascript object to serialize.
140
+ * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object.
141
+ * @returns the index pointing to the last written byte in the buffer.
142
+ * @public
143
+ */
144
+ export function serializeWithBufferAndIndex(
145
+ object: Document,
146
+ finalBuffer: Uint8Array,
147
+ options: SerializeOptions = {}
148
+ ): number {
149
+ // Unpack the options
150
+ const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
151
+ const serializeFunctions =
152
+ typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
153
+ const ignoreUndefined =
154
+ typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
155
+ const startIndex = typeof options.index === 'number' ? options.index : 0;
156
+
157
+ // Attempt to serialize
158
+ const serializationIndex = serializeInto(
159
+ buffer,
160
+ object,
161
+ checkKeys,
162
+ 0,
163
+ serializeFunctions,
164
+ ignoreUndefined,
165
+ null
166
+ );
167
+
168
+ finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex);
169
+
170
+ // Return the index
171
+ return startIndex + serializationIndex - 1;
172
+ }
173
+
174
+ /**
175
+ * Deserialize data as BSON.
176
+ *
177
+ * @param buffer - the buffer containing the serialized set of BSON documents.
178
+ * @returns returns the deserialized Javascript Object.
179
+ * @public
180
+ */
181
+ export function deserialize(buffer: Uint8Array, options: DeserializeOptions = {}): Document {
182
+ return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options);
183
+ }
184
+
185
+ /** @public */
186
+ export type CalculateObjectSizeOptions = Pick<
187
+ SerializeOptions,
188
+ 'serializeFunctions' | 'ignoreUndefined'
189
+ >;
190
+
191
+ /**
192
+ * Calculate the bson size for a passed in Javascript object.
193
+ *
194
+ * @param object - the Javascript object to calculate the BSON byte size for
195
+ * @returns size of BSON object in bytes
196
+ * @public
197
+ */
198
+ export function calculateObjectSize(
199
+ object: Document,
200
+ options: CalculateObjectSizeOptions = {}
201
+ ): number {
202
+ options = options || {};
203
+
204
+ const serializeFunctions =
205
+ typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
206
+ const ignoreUndefined =
207
+ typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
208
+
209
+ return internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined);
210
+ }
211
+
212
+ /**
213
+ * Deserialize stream data as BSON documents.
214
+ *
215
+ * @param data - the buffer containing the serialized set of BSON documents.
216
+ * @param startIndex - the start index in the data Buffer where the deserialization is to start.
217
+ * @param numberOfDocuments - number of documents to deserialize.
218
+ * @param documents - an array where to store the deserialized documents.
219
+ * @param docStartIndex - the index in the documents array from where to start inserting documents.
220
+ * @param options - additional options used for the deserialization.
221
+ * @returns next index in the buffer after deserialization **x** numbers of documents.
222
+ * @public
223
+ */
224
+ export function deserializeStream(
225
+ data: Uint8Array | ArrayBuffer,
226
+ startIndex: number,
227
+ numberOfDocuments: number,
228
+ documents: Document[],
229
+ docStartIndex: number,
230
+ options: DeserializeOptions
231
+ ): number {
232
+ const internalOptions = Object.assign(
233
+ { allowObjectSmallerThanBufferSize: true, index: 0 },
234
+ options
235
+ );
236
+ const bufferData = ByteUtils.toLocalBufferType(data);
237
+
238
+ let index = startIndex;
239
+ // Loop over all documents
240
+ for (let i = 0; i < numberOfDocuments; i++) {
241
+ // Find size of the document
242
+ const size = NumberUtils.getInt32LE(bufferData, index);
243
+ // Update options with index
244
+ internalOptions.index = index;
245
+ // Parse the document at this point
246
+ documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions);
247
+ // Adjust index by the document size
248
+ index = index + size;
249
+ }
250
+
251
+ // Return object containing end index of parsing and list of documents
252
+ return index;
253
+ }
gateway/node_modules/bson/src/bson_value.ts ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { BSON_MAJOR_VERSION } from './constants';
2
+ import { type InspectFn } from './parser/utils';
3
+ import { BSON_VERSION_SYMBOL } from './constants';
4
+
5
+ /** @public */
6
+ export type BSONTypeTag =
7
+ | 'BSONRegExp'
8
+ | 'BSONSymbol'
9
+ | 'ObjectId'
10
+ | 'Binary'
11
+ | 'Decimal128'
12
+ | 'Double'
13
+ | 'Int32'
14
+ | 'Long'
15
+ | 'MaxKey'
16
+ | 'MinKey'
17
+ | 'Timestamp'
18
+ | 'Code'
19
+ | 'DBRef';
20
+
21
+ /** @public */
22
+ export const bsonType = Symbol.for('@@mdb.bson.type');
23
+
24
+ /** @public */
25
+ export abstract class BSONValue {
26
+ /** @public */
27
+ public abstract get _bsontype(): BSONTypeTag;
28
+
29
+ public get [bsonType](): this['_bsontype'] {
30
+ return this._bsontype;
31
+ }
32
+
33
+ /** @internal */
34
+ get [BSON_VERSION_SYMBOL](): typeof BSON_MAJOR_VERSION {
35
+ return BSON_MAJOR_VERSION;
36
+ }
37
+
38
+ [Symbol.for('nodejs.util.inspect.custom')](
39
+ depth?: number,
40
+ options?: unknown,
41
+ inspect?: InspectFn
42
+ ): string {
43
+ return this.inspect(depth, options, inspect);
44
+ }
45
+
46
+ /**
47
+ * @public
48
+ * Prints a human-readable string of BSON value information
49
+ * If invoked manually without node.js.inspect function, this will default to a modified JSON.stringify
50
+ */
51
+ public abstract inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
52
+
53
+ /** @internal */
54
+ abstract toExtendedJSON(): unknown;
55
+ }
gateway/node_modules/bson/src/code.ts ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Document } from './bson';
2
+ import { BSONValue } from './bson_value';
3
+ import { type InspectFn, defaultInspect } from './parser/utils';
4
+
5
+ /** @public */
6
+ export interface CodeExtended {
7
+ $code: string;
8
+ $scope?: Document;
9
+ }
10
+
11
+ /**
12
+ * A class representation of the BSON Code type.
13
+ * @public
14
+ * @category BSONType
15
+ */
16
+ export class Code extends BSONValue {
17
+ get _bsontype(): 'Code' {
18
+ return 'Code';
19
+ }
20
+
21
+ code: string;
22
+
23
+ // a code instance having a null scope is what determines whether
24
+ // it is BSONType 0x0D (just code) / 0x0F (code with scope)
25
+ scope: Document | null;
26
+
27
+ /**
28
+ * @param code - a string or function.
29
+ * @param scope - an optional scope for the function.
30
+ */
31
+ constructor(code: string | Function, scope?: Document | null) {
32
+ super();
33
+ this.code = code.toString();
34
+ this.scope = scope ?? null;
35
+ }
36
+
37
+ toJSON(): { code: string; scope?: Document } {
38
+ if (this.scope != null) {
39
+ return { code: this.code, scope: this.scope };
40
+ }
41
+
42
+ return { code: this.code };
43
+ }
44
+
45
+ /** @internal */
46
+ toExtendedJSON(): CodeExtended {
47
+ if (this.scope) {
48
+ return { $code: this.code, $scope: this.scope };
49
+ }
50
+
51
+ return { $code: this.code };
52
+ }
53
+
54
+ /** @internal */
55
+ static fromExtendedJSON(doc: CodeExtended): Code {
56
+ return new Code(doc.$code, doc.$scope);
57
+ }
58
+
59
+ inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
60
+ inspect ??= defaultInspect;
61
+ let parametersString = inspect(this.code, options);
62
+ const multiLineFn = parametersString.includes('\n');
63
+ if (this.scope != null) {
64
+ parametersString += `,${multiLineFn ? '\n' : ' '}${inspect(this.scope, options)}`;
65
+ }
66
+ const endingNewline = multiLineFn && this.scope === null;
67
+ return `new Code(${multiLineFn ? '\n' : ''}${parametersString}${endingNewline ? '\n' : ''})`;
68
+ }
69
+ }
gateway/node_modules/bson/src/constants.ts ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** @internal */
2
+ export const BSON_MAJOR_VERSION = 7;
3
+
4
+ /** @internal */
5
+ export const BSON_VERSION_SYMBOL = Symbol.for('@@mdb.bson.version');
6
+
7
+ /** @internal */
8
+ export const BSON_INT32_MAX = 0x7fffffff;
9
+ /** @internal */
10
+ export const BSON_INT32_MIN = -0x80000000;
11
+ /** @internal */
12
+ export const BSON_INT64_MAX = Math.pow(2, 63) - 1;
13
+ /** @internal */
14
+ export const BSON_INT64_MIN = -Math.pow(2, 63);
15
+
16
+ /**
17
+ * Any integer up to 2^53 can be precisely represented by a double.
18
+ * @internal
19
+ */
20
+ export const JS_INT_MAX = Math.pow(2, 53);
21
+
22
+ /**
23
+ * Any integer down to -2^53 can be precisely represented by a double.
24
+ * @internal
25
+ */
26
+ export const JS_INT_MIN = -Math.pow(2, 53);
27
+
28
+ /** Number BSON Type @internal */
29
+ export const BSON_DATA_NUMBER = 1;
30
+
31
+ /** String BSON Type @internal */
32
+ export const BSON_DATA_STRING = 2;
33
+
34
+ /** Object BSON Type @internal */
35
+ export const BSON_DATA_OBJECT = 3;
36
+
37
+ /** Array BSON Type @internal */
38
+ export const BSON_DATA_ARRAY = 4;
39
+
40
+ /** Binary BSON Type @internal */
41
+ export const BSON_DATA_BINARY = 5;
42
+
43
+ /** Binary BSON Type @internal */
44
+ export const BSON_DATA_UNDEFINED = 6;
45
+
46
+ /** ObjectId BSON Type @internal */
47
+ export const BSON_DATA_OID = 7;
48
+
49
+ /** Boolean BSON Type @internal */
50
+ export const BSON_DATA_BOOLEAN = 8;
51
+
52
+ /** Date BSON Type @internal */
53
+ export const BSON_DATA_DATE = 9;
54
+
55
+ /** null BSON Type @internal */
56
+ export const BSON_DATA_NULL = 10;
57
+
58
+ /** RegExp BSON Type @internal */
59
+ export const BSON_DATA_REGEXP = 11;
60
+
61
+ /** Code BSON Type @internal */
62
+ export const BSON_DATA_DBPOINTER = 12;
63
+
64
+ /** Code BSON Type @internal */
65
+ export const BSON_DATA_CODE = 13;
66
+
67
+ /** Symbol BSON Type @internal */
68
+ export const BSON_DATA_SYMBOL = 14;
69
+
70
+ /** Code with Scope BSON Type @internal */
71
+ export const BSON_DATA_CODE_W_SCOPE = 15;
72
+
73
+ /** 32 bit Integer BSON Type @internal */
74
+ export const BSON_DATA_INT = 16;
75
+
76
+ /** Timestamp BSON Type @internal */
77
+ export const BSON_DATA_TIMESTAMP = 17;
78
+
79
+ /** Long BSON Type @internal */
80
+ export const BSON_DATA_LONG = 18;
81
+
82
+ /** Decimal128 BSON Type @internal */
83
+ export const BSON_DATA_DECIMAL128 = 19;
84
+
85
+ /** MinKey BSON Type @internal */
86
+ export const BSON_DATA_MIN_KEY = 0xff;
87
+
88
+ /** MaxKey BSON Type @internal */
89
+ export const BSON_DATA_MAX_KEY = 0x7f;
90
+
91
+ /** Binary Default Type @internal */
92
+ export const BSON_BINARY_SUBTYPE_DEFAULT = 0;
93
+
94
+ /** Binary Function Type @internal */
95
+ export const BSON_BINARY_SUBTYPE_FUNCTION = 1;
96
+
97
+ /** Binary Byte Array Type @internal */
98
+ export const BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
99
+
100
+ /** Binary Deprecated UUID Type @deprecated Please use BSON_BINARY_SUBTYPE_UUID_NEW @internal */
101
+ export const BSON_BINARY_SUBTYPE_UUID = 3;
102
+
103
+ /** Binary UUID Type @internal */
104
+ export const BSON_BINARY_SUBTYPE_UUID_NEW = 4;
105
+
106
+ /** Binary MD5 Type @internal */
107
+ export const BSON_BINARY_SUBTYPE_MD5 = 5;
108
+
109
+ /** Encrypted BSON type @internal */
110
+ export const BSON_BINARY_SUBTYPE_ENCRYPTED = 6;
111
+
112
+ /** Column BSON type @internal */
113
+ export const BSON_BINARY_SUBTYPE_COLUMN = 7;
114
+
115
+ /** Sensitive BSON type @internal */
116
+ export const BSON_BINARY_SUBTYPE_SENSITIVE = 8;
117
+
118
+ /** Binary User Defined Type @internal */
119
+ export const BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
120
+
121
+ /** @public */
122
+ export const BSONType = Object.freeze({
123
+ double: 1,
124
+ string: 2,
125
+ object: 3,
126
+ array: 4,
127
+ binData: 5,
128
+ undefined: 6,
129
+ objectId: 7,
130
+ bool: 8,
131
+ date: 9,
132
+ null: 10,
133
+ regex: 11,
134
+ dbPointer: 12,
135
+ javascript: 13,
136
+ symbol: 14,
137
+ javascriptWithScope: 15,
138
+ int: 16,
139
+ timestamp: 17,
140
+ long: 18,
141
+ decimal: 19,
142
+ minKey: -1,
143
+ maxKey: 127
144
+ } as const);
145
+
146
+ /** @public */
147
+ export type BSONType = (typeof BSONType)[keyof typeof BSONType];
gateway/node_modules/bson/src/db_ref.ts ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Document } from './bson';
2
+ import { BSONValue } from './bson_value';
3
+ import type { EJSONOptions } from './extended_json';
4
+ import type { ObjectId } from './objectid';
5
+ import { type InspectFn, defaultInspect } from './parser/utils';
6
+
7
+ /** @public */
8
+ export interface DBRefLike {
9
+ $ref: string;
10
+ $id: ObjectId;
11
+ $db?: string;
12
+ }
13
+
14
+ /** @internal */
15
+ export function isDBRefLike(value: unknown): value is DBRefLike {
16
+ return (
17
+ value != null &&
18
+ typeof value === 'object' &&
19
+ '$id' in value &&
20
+ value.$id != null &&
21
+ '$ref' in value &&
22
+ typeof value.$ref === 'string' &&
23
+ // If '$db' is defined it MUST be a string, otherwise it should be absent
24
+ (!('$db' in value) || ('$db' in value && typeof value.$db === 'string'))
25
+ );
26
+ }
27
+
28
+ /**
29
+ * A class representation of the BSON DBRef type.
30
+ * @public
31
+ * @category BSONType
32
+ */
33
+ export class DBRef extends BSONValue {
34
+ get _bsontype(): 'DBRef' {
35
+ return 'DBRef';
36
+ }
37
+
38
+ collection!: string;
39
+ oid!: ObjectId;
40
+ db?: string;
41
+ fields!: Document;
42
+
43
+ /**
44
+ * @param collection - the collection name.
45
+ * @param oid - the reference ObjectId.
46
+ * @param db - optional db name, if omitted the reference is local to the current db.
47
+ */
48
+ constructor(collection: string, oid: ObjectId, db?: string, fields?: Document) {
49
+ super();
50
+ // check if namespace has been provided
51
+ const parts = collection.split('.');
52
+ if (parts.length === 2) {
53
+ db = parts.shift();
54
+ collection = parts.shift()!;
55
+ }
56
+
57
+ this.collection = collection;
58
+ this.oid = oid;
59
+ this.db = db;
60
+ this.fields = fields || {};
61
+ }
62
+
63
+ // Property provided for compatibility with the 1.x parser
64
+ // the 1.x parser used a "namespace" property, while 4.x uses "collection"
65
+
66
+ /** @internal */
67
+ get namespace(): string {
68
+ return this.collection;
69
+ }
70
+
71
+ set namespace(value: string) {
72
+ this.collection = value;
73
+ }
74
+
75
+ toJSON(): DBRefLike & Document {
76
+ const o = Object.assign(
77
+ {
78
+ $ref: this.collection,
79
+ $id: this.oid
80
+ },
81
+ this.fields
82
+ );
83
+
84
+ if (this.db != null) o.$db = this.db;
85
+ return o;
86
+ }
87
+
88
+ /** @internal */
89
+ toExtendedJSON(options?: EJSONOptions): DBRefLike {
90
+ options = options || {};
91
+ let o: DBRefLike = {
92
+ $ref: this.collection,
93
+ $id: this.oid
94
+ };
95
+
96
+ if (options.legacy) {
97
+ return o;
98
+ }
99
+
100
+ if (this.db) o.$db = this.db;
101
+ o = Object.assign(o, this.fields);
102
+ return o;
103
+ }
104
+
105
+ /** @internal */
106
+ static fromExtendedJSON(doc: DBRefLike): DBRef {
107
+ const copy = Object.assign({}, doc) as Partial<DBRefLike>;
108
+ delete copy.$ref;
109
+ delete copy.$id;
110
+ delete copy.$db;
111
+ return new DBRef(doc.$ref, doc.$id, doc.$db, copy);
112
+ }
113
+
114
+ inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
115
+ inspect ??= defaultInspect;
116
+
117
+ const args = [
118
+ inspect(this.namespace, options),
119
+ inspect(this.oid, options),
120
+ ...(this.db ? [inspect(this.db, options)] : []),
121
+ ...(Object.keys(this.fields).length > 0 ? [inspect(this.fields, options)] : [])
122
+ ];
123
+
124
+ args[1] = inspect === defaultInspect ? `new ObjectId(${args[1]})` : args[1];
125
+
126
+ return `new DBRef(${args.join(', ')})`;
127
+ }
128
+ }
gateway/node_modules/bson/src/decimal128.ts ADDED
@@ -0,0 +1,855 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { BSONValue } from './bson_value';
2
+ import { BSONError } from './error';
3
+ import { Long } from './long';
4
+ import { type InspectFn, defaultInspect, isUint8Array } from './parser/utils';
5
+ import { ByteUtils } from './utils/byte_utils';
6
+
7
+ const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
8
+ const PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
9
+ const PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
10
+
11
+ const EXPONENT_MAX = 6111;
12
+ const EXPONENT_MIN = -6176;
13
+ const EXPONENT_BIAS = 6176;
14
+ const MAX_DIGITS = 34;
15
+
16
+ // Nan value bits as 32 bit values (due to lack of longs)
17
+ const NAN_BUFFER = ByteUtils.fromNumberArray(
18
+ [
19
+ 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
20
+ ].reverse()
21
+ );
22
+ // Infinity value bits 32 bit values (due to lack of longs)
23
+ const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray(
24
+ [
25
+ 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
26
+ ].reverse()
27
+ );
28
+ const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray(
29
+ [
30
+ 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
31
+ ].reverse()
32
+ );
33
+
34
+ const EXPONENT_REGEX = /^([-+])?(\d+)?$/;
35
+
36
+ // Extract least significant 5 bits
37
+ const COMBINATION_MASK = 0x1f;
38
+ // Extract least significant 14 bits
39
+ const EXPONENT_MASK = 0x3fff;
40
+ // Value of combination field for Inf
41
+ const COMBINATION_INFINITY = 30;
42
+ // Value of combination field for NaN
43
+ const COMBINATION_NAN = 31;
44
+
45
+ // Detect if the value is a digit
46
+ function isDigit(value: string): boolean {
47
+ return !isNaN(parseInt(value, 10));
48
+ }
49
+
50
+ // Divide two uint128 values
51
+ function divideu128(value: { parts: [number, number, number, number] }) {
52
+ const DIVISOR = Long.fromNumber(1000 * 1000 * 1000);
53
+ let _rem = Long.fromNumber(0);
54
+
55
+ if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
56
+ return { quotient: value, rem: _rem };
57
+ }
58
+
59
+ for (let i = 0; i <= 3; i++) {
60
+ // Adjust remainder to match value of next dividend
61
+ _rem = _rem.shiftLeft(32);
62
+ // Add the divided to _rem
63
+ _rem = _rem.add(new Long(value.parts[i], 0));
64
+ value.parts[i] = _rem.div(DIVISOR).low;
65
+ _rem = _rem.modulo(DIVISOR);
66
+ }
67
+
68
+ return { quotient: value, rem: _rem };
69
+ }
70
+
71
+ // Multiply two Long values and return the 128 bit value
72
+ function multiply64x2(left: Long, right: Long): { high: Long; low: Long } {
73
+ if (!left && !right) {
74
+ return { high: Long.fromNumber(0), low: Long.fromNumber(0) };
75
+ }
76
+
77
+ const leftHigh = left.shiftRightUnsigned(32);
78
+ const leftLow = new Long(left.getLowBits(), 0);
79
+ const rightHigh = right.shiftRightUnsigned(32);
80
+ const rightLow = new Long(right.getLowBits(), 0);
81
+
82
+ let productHigh = leftHigh.multiply(rightHigh);
83
+ let productMid = leftHigh.multiply(rightLow);
84
+ const productMid2 = leftLow.multiply(rightHigh);
85
+ let productLow = leftLow.multiply(rightLow);
86
+
87
+ productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
88
+ productMid = new Long(productMid.getLowBits(), 0)
89
+ .add(productMid2)
90
+ .add(productLow.shiftRightUnsigned(32));
91
+
92
+ productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
93
+ productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0));
94
+
95
+ // Return the 128 bit result
96
+ return { high: productHigh, low: productLow };
97
+ }
98
+
99
+ function lessThan(left: Long, right: Long): boolean {
100
+ // Make values unsigned
101
+ const uhleft = left.high >>> 0;
102
+ const uhright = right.high >>> 0;
103
+
104
+ // Compare high bits first
105
+ if (uhleft < uhright) {
106
+ return true;
107
+ } else if (uhleft === uhright) {
108
+ const ulleft = left.low >>> 0;
109
+ const ulright = right.low >>> 0;
110
+ if (ulleft < ulright) return true;
111
+ }
112
+
113
+ return false;
114
+ }
115
+
116
+ function invalidErr(string: string, message: string) {
117
+ throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`);
118
+ }
119
+
120
+ /** @public */
121
+ export interface Decimal128Extended {
122
+ $numberDecimal: string;
123
+ }
124
+
125
+ /**
126
+ * A class representation of the BSON Decimal128 type.
127
+ * @public
128
+ * @category BSONType
129
+ */
130
+ export class Decimal128 extends BSONValue {
131
+ get _bsontype(): 'Decimal128' {
132
+ return 'Decimal128';
133
+ }
134
+
135
+ readonly bytes!: Uint8Array;
136
+
137
+ /**
138
+ * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order,
139
+ * or a string representation as returned by .toString()
140
+ */
141
+ constructor(bytes: Uint8Array | string) {
142
+ super();
143
+ if (typeof bytes === 'string') {
144
+ this.bytes = Decimal128.fromString(bytes).bytes;
145
+ } else if (bytes instanceof Uint8Array || isUint8Array(bytes)) {
146
+ if (bytes.byteLength !== 16) {
147
+ throw new BSONError('Decimal128 must take a Buffer of 16 bytes');
148
+ }
149
+ this.bytes = bytes;
150
+ } else {
151
+ throw new BSONError('Decimal128 must take a Buffer or string');
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Create a Decimal128 instance from a string representation
157
+ *
158
+ * @param representation - a numeric string representation.
159
+ */
160
+ static fromString(representation: string): Decimal128 {
161
+ return Decimal128._fromString(representation, { allowRounding: false });
162
+ }
163
+
164
+ /**
165
+ * Create a Decimal128 instance from a string representation, allowing for rounding to 34
166
+ * significant digits
167
+ *
168
+ * @example Example of a number that will be rounded
169
+ * ```ts
170
+ * > let d = Decimal128.fromString('37.499999999999999196428571428571375')
171
+ * Uncaught:
172
+ * BSONError: "37.499999999999999196428571428571375" is not a valid Decimal128 string - inexact rounding
173
+ * at invalidErr (/home/wajames/js-bson/lib/bson.cjs:1402:11)
174
+ * at Decimal128.fromStringInternal (/home/wajames/js-bson/lib/bson.cjs:1633:25)
175
+ * at Decimal128.fromString (/home/wajames/js-bson/lib/bson.cjs:1424:27)
176
+ *
177
+ * > d = Decimal128.fromStringWithRounding('37.499999999999999196428571428571375')
178
+ * new Decimal128("37.49999999999999919642857142857138")
179
+ * ```
180
+ * @param representation - a numeric string representation.
181
+ */
182
+ static fromStringWithRounding(representation: string): Decimal128 {
183
+ return Decimal128._fromString(representation, { allowRounding: true });
184
+ }
185
+
186
+ private static _fromString(representation: string, options: { allowRounding: boolean }) {
187
+ // Parse state tracking
188
+ let isNegative = false;
189
+ let sawSign = false;
190
+ let sawRadix = false;
191
+ let foundNonZero = false;
192
+
193
+ // Total number of significant digits (no leading or trailing zero)
194
+ let significantDigits = 0;
195
+ // Total number of significand digits read
196
+ let nDigitsRead = 0;
197
+ // Total number of digits (no leading zeros)
198
+ let nDigits = 0;
199
+ // The number of the digits after radix
200
+ let radixPosition = 0;
201
+ // The index of the first non-zero in *str*
202
+ let firstNonZero = 0;
203
+
204
+ // Digits Array
205
+ const digits = [0];
206
+ // The number of digits in digits
207
+ let nDigitsStored = 0;
208
+ // Insertion pointer for digits
209
+ let digitsInsert = 0;
210
+ // The index of the last digit
211
+ let lastDigit = 0;
212
+
213
+ // Exponent
214
+ let exponent = 0;
215
+ // The high 17 digits of the significand
216
+ let significandHigh = new Long(0, 0);
217
+ // The low 17 digits of the significand
218
+ let significandLow = new Long(0, 0);
219
+ // The biased exponent
220
+ let biasedExponent = 0;
221
+
222
+ // Read index
223
+ let index = 0;
224
+
225
+ // Naively prevent against REDOS attacks.
226
+ // TODO: implementing a custom parsing for this, or refactoring the regex would yield
227
+ // further gains.
228
+ if (representation.length >= 7000) {
229
+ throw new BSONError('' + representation + ' not a valid Decimal128 string');
230
+ }
231
+
232
+ // Results
233
+ const stringMatch = representation.match(PARSE_STRING_REGEXP);
234
+ const infMatch = representation.match(PARSE_INF_REGEXP);
235
+ const nanMatch = representation.match(PARSE_NAN_REGEXP);
236
+
237
+ // Validate the string
238
+ if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) {
239
+ throw new BSONError('' + representation + ' not a valid Decimal128 string');
240
+ }
241
+
242
+ if (stringMatch) {
243
+ // full_match = stringMatch[0]
244
+ // sign = stringMatch[1]
245
+
246
+ const unsignedNumber = stringMatch[2];
247
+ // stringMatch[3] is undefined if a whole number (ex "1", 12")
248
+ // but defined if a number w/ decimal in it (ex "1.0, 12.2")
249
+
250
+ const e = stringMatch[4];
251
+ const expSign = stringMatch[5];
252
+ const expNumber = stringMatch[6];
253
+
254
+ // they provided e, but didn't give an exponent number. for ex "1e"
255
+ if (e && expNumber === undefined) invalidErr(representation, 'missing exponent power');
256
+
257
+ // they provided e, but didn't give a number before it. for ex "e1"
258
+ if (e && unsignedNumber === undefined) invalidErr(representation, 'missing exponent base');
259
+
260
+ if (e === undefined && (expSign || expNumber)) {
261
+ invalidErr(representation, 'missing e before exponent');
262
+ }
263
+ }
264
+
265
+ // Get the negative or positive sign
266
+ if (representation[index] === '+' || representation[index] === '-') {
267
+ sawSign = true;
268
+ isNegative = representation[index++] === '-';
269
+ }
270
+
271
+ // Check if user passed Infinity or NaN
272
+ if (!isDigit(representation[index]) && representation[index] !== '.') {
273
+ if (representation[index] === 'i' || representation[index] === 'I') {
274
+ return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
275
+ } else if (representation[index] === 'N') {
276
+ return new Decimal128(NAN_BUFFER);
277
+ }
278
+ }
279
+
280
+ // Read all the digits
281
+ while (isDigit(representation[index]) || representation[index] === '.') {
282
+ if (representation[index] === '.') {
283
+ if (sawRadix) invalidErr(representation, 'contains multiple periods');
284
+
285
+ sawRadix = true;
286
+ index = index + 1;
287
+ continue;
288
+ }
289
+
290
+ if (nDigitsStored < MAX_DIGITS) {
291
+ if (representation[index] !== '0' || foundNonZero) {
292
+ if (!foundNonZero) {
293
+ firstNonZero = nDigitsRead;
294
+ }
295
+
296
+ foundNonZero = true;
297
+
298
+ // Only store 34 digits
299
+ digits[digitsInsert++] = parseInt(representation[index], 10);
300
+ nDigitsStored = nDigitsStored + 1;
301
+ }
302
+ }
303
+
304
+ if (foundNonZero) nDigits = nDigits + 1;
305
+ if (sawRadix) radixPosition = radixPosition + 1;
306
+
307
+ nDigitsRead = nDigitsRead + 1;
308
+ index = index + 1;
309
+ }
310
+
311
+ if (sawRadix && !nDigitsRead)
312
+ throw new BSONError('' + representation + ' not a valid Decimal128 string');
313
+
314
+ // Read exponent if exists
315
+ if (representation[index] === 'e' || representation[index] === 'E') {
316
+ // Read exponent digits
317
+ const match = representation.substr(++index).match(EXPONENT_REGEX);
318
+
319
+ // No digits read
320
+ if (!match || !match[2]) return new Decimal128(NAN_BUFFER);
321
+
322
+ // Get exponent
323
+ exponent = parseInt(match[0], 10);
324
+
325
+ // Adjust the index
326
+ index = index + match[0].length;
327
+ }
328
+
329
+ // Return not a number
330
+ if (representation[index]) return new Decimal128(NAN_BUFFER);
331
+
332
+ // Done reading input
333
+ // Find first non-zero digit in digits
334
+ if (!nDigitsStored) {
335
+ digits[0] = 0;
336
+ nDigits = 1;
337
+ nDigitsStored = 1;
338
+ significantDigits = 0;
339
+ } else {
340
+ lastDigit = nDigitsStored - 1;
341
+ significantDigits = nDigits;
342
+ if (significantDigits !== 1) {
343
+ while (
344
+ representation[
345
+ firstNonZero + significantDigits - 1 + Number(sawSign) + Number(sawRadix)
346
+ ] === '0'
347
+ ) {
348
+ significantDigits = significantDigits - 1;
349
+ }
350
+ }
351
+ }
352
+
353
+ // Normalization of exponent
354
+ // Correct exponent based on radix position, and shift significand as needed
355
+ // to represent user input
356
+
357
+ // Overflow prevention
358
+ if (exponent <= radixPosition && radixPosition > exponent + (1 << 14)) {
359
+ exponent = EXPONENT_MIN;
360
+ } else {
361
+ exponent = exponent - radixPosition;
362
+ }
363
+
364
+ // Attempt to normalize the exponent
365
+ while (exponent > EXPONENT_MAX) {
366
+ // Shift exponent to significand and decrease
367
+ lastDigit = lastDigit + 1;
368
+ if (lastDigit >= MAX_DIGITS) {
369
+ // Check if we have a zero then just hard clamp, otherwise fail
370
+ if (significantDigits === 0) {
371
+ exponent = EXPONENT_MAX;
372
+ break;
373
+ }
374
+
375
+ invalidErr(representation, 'overflow');
376
+ }
377
+ exponent = exponent - 1;
378
+ }
379
+
380
+ if (options.allowRounding) {
381
+ while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
382
+ // Shift last digit. can only do this if < significant digits than # stored.
383
+ if (lastDigit === 0 && significantDigits < nDigitsStored) {
384
+ exponent = EXPONENT_MIN;
385
+ significantDigits = 0;
386
+ break;
387
+ }
388
+
389
+ if (nDigitsStored < nDigits) {
390
+ // adjust to match digits not stored
391
+ nDigits = nDigits - 1;
392
+ } else {
393
+ // adjust to round
394
+ lastDigit = lastDigit - 1;
395
+ }
396
+
397
+ if (exponent < EXPONENT_MAX) {
398
+ exponent = exponent + 1;
399
+ } else {
400
+ // Check if we have a zero then just hard clamp, otherwise fail
401
+ const digitsString = digits.join('');
402
+ if (digitsString.match(/^0+$/)) {
403
+ exponent = EXPONENT_MAX;
404
+ break;
405
+ }
406
+ invalidErr(representation, 'overflow');
407
+ }
408
+ }
409
+
410
+ // Round
411
+ // We've normalized the exponent, but might still need to round.
412
+ if (lastDigit + 1 < significantDigits) {
413
+ let endOfString = nDigitsRead;
414
+
415
+ // If we have seen a radix point, 'string' is 1 longer than we have
416
+ // documented with ndigits_read, so inc the position of the first nonzero
417
+ // digit and the position that digits are read to.
418
+ if (sawRadix) {
419
+ firstNonZero = firstNonZero + 1;
420
+ endOfString = endOfString + 1;
421
+ }
422
+ // if negative, we need to increment again to account for - sign at start.
423
+ if (sawSign) {
424
+ firstNonZero = firstNonZero + 1;
425
+ endOfString = endOfString + 1;
426
+ }
427
+
428
+ const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
429
+ let roundBit = 0;
430
+
431
+ if (roundDigit >= 5) {
432
+ roundBit = 1;
433
+ if (roundDigit === 5) {
434
+ roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0;
435
+ for (let i = firstNonZero + lastDigit + 2; i < endOfString; i++) {
436
+ if (parseInt(representation[i], 10)) {
437
+ roundBit = 1;
438
+ break;
439
+ }
440
+ }
441
+ }
442
+ }
443
+
444
+ if (roundBit) {
445
+ let dIdx = lastDigit;
446
+
447
+ for (; dIdx >= 0; dIdx--) {
448
+ if (++digits[dIdx] > 9) {
449
+ digits[dIdx] = 0;
450
+
451
+ // overflowed most significant digit
452
+ if (dIdx === 0) {
453
+ if (exponent < EXPONENT_MAX) {
454
+ exponent = exponent + 1;
455
+ digits[dIdx] = 1;
456
+ } else {
457
+ return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
458
+ }
459
+ }
460
+ } else {
461
+ break;
462
+ }
463
+ }
464
+ }
465
+ }
466
+ } else {
467
+ while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
468
+ // Shift last digit. can only do this if < significant digits than # stored.
469
+ if (lastDigit === 0) {
470
+ if (significantDigits === 0) {
471
+ exponent = EXPONENT_MIN;
472
+ break;
473
+ }
474
+
475
+ invalidErr(representation, 'exponent underflow');
476
+ }
477
+
478
+ if (nDigitsStored < nDigits) {
479
+ if (
480
+ representation[nDigits - 1 + Number(sawSign) + Number(sawRadix)] !== '0' &&
481
+ significantDigits !== 0
482
+ ) {
483
+ invalidErr(representation, 'inexact rounding');
484
+ }
485
+ // adjust to match digits not stored
486
+ nDigits = nDigits - 1;
487
+ } else {
488
+ if (digits[lastDigit] !== 0) {
489
+ invalidErr(representation, 'inexact rounding');
490
+ }
491
+ // adjust to round
492
+ lastDigit = lastDigit - 1;
493
+ }
494
+
495
+ if (exponent < EXPONENT_MAX) {
496
+ exponent = exponent + 1;
497
+ } else {
498
+ invalidErr(representation, 'overflow');
499
+ }
500
+ }
501
+
502
+ // Round
503
+ // We've normalized the exponent, but might still need to round.
504
+ if (lastDigit + 1 < significantDigits) {
505
+ // If we have seen a radix point, 'string' is 1 longer than we have
506
+ // documented with ndigits_read, so inc the position of the first nonzero
507
+ // digit and the position that digits are read to.
508
+ if (sawRadix) {
509
+ firstNonZero = firstNonZero + 1;
510
+ }
511
+ // if saw sign, we need to increment again to account for - or + sign at start.
512
+ if (sawSign) {
513
+ firstNonZero = firstNonZero + 1;
514
+ }
515
+
516
+ const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
517
+
518
+ if (roundDigit !== 0) {
519
+ invalidErr(representation, 'inexact rounding');
520
+ }
521
+ }
522
+ }
523
+
524
+ // Encode significand
525
+ // The high 17 digits of the significand
526
+ significandHigh = Long.fromNumber(0);
527
+ // The low 17 digits of the significand
528
+ significandLow = Long.fromNumber(0);
529
+
530
+ // read a zero
531
+ if (significantDigits === 0) {
532
+ significandHigh = Long.fromNumber(0);
533
+ significandLow = Long.fromNumber(0);
534
+ } else if (lastDigit < 17) {
535
+ let dIdx = 0;
536
+ significandLow = Long.fromNumber(digits[dIdx++]);
537
+ significandHigh = new Long(0, 0);
538
+
539
+ for (; dIdx <= lastDigit; dIdx++) {
540
+ significandLow = significandLow.multiply(Long.fromNumber(10));
541
+ significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
542
+ }
543
+ } else {
544
+ let dIdx = 0;
545
+ significandHigh = Long.fromNumber(digits[dIdx++]);
546
+
547
+ for (; dIdx <= lastDigit - 17; dIdx++) {
548
+ significandHigh = significandHigh.multiply(Long.fromNumber(10));
549
+ significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx]));
550
+ }
551
+
552
+ significandLow = Long.fromNumber(digits[dIdx++]);
553
+
554
+ for (; dIdx <= lastDigit; dIdx++) {
555
+ significandLow = significandLow.multiply(Long.fromNumber(10));
556
+ significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
557
+ }
558
+ }
559
+
560
+ const significand = multiply64x2(significandHigh, Long.fromString('100000000000000000'));
561
+ significand.low = significand.low.add(significandLow);
562
+
563
+ if (lessThan(significand.low, significandLow)) {
564
+ significand.high = significand.high.add(Long.fromNumber(1));
565
+ }
566
+
567
+ // Biased exponent
568
+ biasedExponent = exponent + EXPONENT_BIAS;
569
+ const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) };
570
+
571
+ // Encode combination, exponent, and significand.
572
+ if (
573
+ significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))
574
+ ) {
575
+ // Encode '11' into bits 1 to 3
576
+ dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61));
577
+ dec.high = dec.high.or(
578
+ Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))
579
+ );
580
+ dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff)));
581
+ } else {
582
+ dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49));
583
+ dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff)));
584
+ }
585
+
586
+ dec.low = significand.low;
587
+
588
+ // Encode sign
589
+ if (isNegative) {
590
+ dec.high = dec.high.or(Long.fromString('9223372036854775808'));
591
+ }
592
+
593
+ // Encode into a buffer
594
+ const buffer = ByteUtils.allocateUnsafe(16);
595
+ index = 0;
596
+
597
+ // Encode the low 64 bits of the decimal
598
+ // Encode low bits
599
+ buffer[index++] = dec.low.low & 0xff;
600
+ buffer[index++] = (dec.low.low >> 8) & 0xff;
601
+ buffer[index++] = (dec.low.low >> 16) & 0xff;
602
+ buffer[index++] = (dec.low.low >> 24) & 0xff;
603
+ // Encode high bits
604
+ buffer[index++] = dec.low.high & 0xff;
605
+ buffer[index++] = (dec.low.high >> 8) & 0xff;
606
+ buffer[index++] = (dec.low.high >> 16) & 0xff;
607
+ buffer[index++] = (dec.low.high >> 24) & 0xff;
608
+
609
+ // Encode the high 64 bits of the decimal
610
+ // Encode low bits
611
+ buffer[index++] = dec.high.low & 0xff;
612
+ buffer[index++] = (dec.high.low >> 8) & 0xff;
613
+ buffer[index++] = (dec.high.low >> 16) & 0xff;
614
+ buffer[index++] = (dec.high.low >> 24) & 0xff;
615
+ // Encode high bits
616
+ buffer[index++] = dec.high.high & 0xff;
617
+ buffer[index++] = (dec.high.high >> 8) & 0xff;
618
+ buffer[index++] = (dec.high.high >> 16) & 0xff;
619
+ buffer[index++] = (dec.high.high >> 24) & 0xff;
620
+
621
+ // Return the new Decimal128
622
+ return new Decimal128(buffer);
623
+ }
624
+ /** Create a string representation of the raw Decimal128 value */
625
+ toString(): string {
626
+ // Note: bits in this routine are referred to starting at 0,
627
+ // from the sign bit, towards the coefficient.
628
+
629
+ // decoded biased exponent (14 bits)
630
+ let biased_exponent;
631
+ // the number of significand digits
632
+ let significand_digits = 0;
633
+ // the base-10 digits in the significand
634
+ const significand = new Array<number>(36);
635
+ for (let i = 0; i < significand.length; i++) significand[i] = 0;
636
+ // read pointer into significand
637
+ let index = 0;
638
+
639
+ // true if the number is zero
640
+ let is_zero = false;
641
+
642
+ // the most significant significand bits (50-46)
643
+ let significand_msb;
644
+ // temporary storage for significand decoding
645
+ let significand128: { parts: [number, number, number, number] } = { parts: [0, 0, 0, 0] };
646
+ // indexing variables
647
+ let j, k;
648
+
649
+ // Output string
650
+ const string: string[] = [];
651
+
652
+ // Unpack index
653
+ index = 0;
654
+
655
+ // Buffer reference
656
+ const buffer = this.bytes;
657
+
658
+ // Unpack the low 64bits into a long
659
+ // bits 96 - 127
660
+ const low =
661
+ buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
662
+ // bits 64 - 95
663
+ const midl =
664
+ buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
665
+
666
+ // Unpack the high 64bits into a long
667
+ // bits 32 - 63
668
+ const midh =
669
+ buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
670
+ // bits 0 - 31
671
+ const high =
672
+ buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
673
+
674
+ // Unpack index
675
+ index = 0;
676
+
677
+ // Create the state of the decimal
678
+ const dec = {
679
+ low: new Long(low, midl),
680
+ high: new Long(midh, high)
681
+ };
682
+
683
+ if (dec.high.lessThan(Long.ZERO)) {
684
+ string.push('-');
685
+ }
686
+
687
+ // Decode combination field and exponent
688
+ // bits 1 - 5
689
+ const combination = (high >> 26) & COMBINATION_MASK;
690
+
691
+ if (combination >> 3 === 3) {
692
+ // Check for 'special' values
693
+ if (combination === COMBINATION_INFINITY) {
694
+ return string.join('') + 'Infinity';
695
+ } else if (combination === COMBINATION_NAN) {
696
+ return 'NaN';
697
+ } else {
698
+ biased_exponent = (high >> 15) & EXPONENT_MASK;
699
+ significand_msb = 0x08 + ((high >> 14) & 0x01);
700
+ }
701
+ } else {
702
+ significand_msb = (high >> 14) & 0x07;
703
+ biased_exponent = (high >> 17) & EXPONENT_MASK;
704
+ }
705
+
706
+ // unbiased exponent
707
+ const exponent = biased_exponent - EXPONENT_BIAS;
708
+
709
+ // Create string of significand digits
710
+
711
+ // Convert the 114-bit binary number represented by
712
+ // (significand_high, significand_low) to at most 34 decimal
713
+ // digits through modulo and division.
714
+ significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14);
715
+ significand128.parts[1] = midh;
716
+ significand128.parts[2] = midl;
717
+ significand128.parts[3] = low;
718
+
719
+ if (
720
+ significand128.parts[0] === 0 &&
721
+ significand128.parts[1] === 0 &&
722
+ significand128.parts[2] === 0 &&
723
+ significand128.parts[3] === 0
724
+ ) {
725
+ is_zero = true;
726
+ } else {
727
+ for (k = 3; k >= 0; k--) {
728
+ let least_digits = 0;
729
+ // Perform the divide
730
+ const result = divideu128(significand128);
731
+ significand128 = result.quotient;
732
+ least_digits = result.rem.low;
733
+
734
+ // We now have the 9 least significant digits (in base 2).
735
+ // Convert and output to string.
736
+ if (!least_digits) continue;
737
+
738
+ for (j = 8; j >= 0; j--) {
739
+ // significand[k * 9 + j] = Math.round(least_digits % 10);
740
+ significand[k * 9 + j] = least_digits % 10;
741
+ // least_digits = Math.round(least_digits / 10);
742
+ least_digits = Math.floor(least_digits / 10);
743
+ }
744
+ }
745
+ }
746
+
747
+ // Output format options:
748
+ // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd
749
+ // Regular - ddd.ddd
750
+
751
+ if (is_zero) {
752
+ significand_digits = 1;
753
+ significand[index] = 0;
754
+ } else {
755
+ significand_digits = 36;
756
+ while (!significand[index]) {
757
+ significand_digits = significand_digits - 1;
758
+ index = index + 1;
759
+ }
760
+ }
761
+
762
+ // the exponent if scientific notation is used
763
+ const scientific_exponent = significand_digits - 1 + exponent;
764
+
765
+ // The scientific exponent checks are dictated by the string conversion
766
+ // specification and are somewhat arbitrary cutoffs.
767
+ //
768
+ // We must check exponent > 0, because if this is the case, the number
769
+ // has trailing zeros. However, we *cannot* output these trailing zeros,
770
+ // because doing so would change the precision of the value, and would
771
+ // change stored data if the string converted number is round tripped.
772
+ if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
773
+ // Scientific format
774
+
775
+ // if there are too many significant digits, we should just be treating numbers
776
+ // as + or - 0 and using the non-scientific exponent (this is for the "invalid
777
+ // representation should be treated as 0/-0" spec cases in decimal128-1.json)
778
+ if (significand_digits > 34) {
779
+ string.push(`${0}`);
780
+ if (exponent > 0) string.push(`E+${exponent}`);
781
+ else if (exponent < 0) string.push(`E${exponent}`);
782
+ return string.join('');
783
+ }
784
+
785
+ string.push(`${significand[index++]}`);
786
+ significand_digits = significand_digits - 1;
787
+
788
+ if (significand_digits) {
789
+ string.push('.');
790
+ }
791
+
792
+ for (let i = 0; i < significand_digits; i++) {
793
+ string.push(`${significand[index++]}`);
794
+ }
795
+
796
+ // Exponent
797
+ string.push('E');
798
+ if (scientific_exponent > 0) {
799
+ string.push(`+${scientific_exponent}`);
800
+ } else {
801
+ string.push(`${scientific_exponent}`);
802
+ }
803
+ } else {
804
+ // Regular format with no decimal place
805
+ if (exponent >= 0) {
806
+ for (let i = 0; i < significand_digits; i++) {
807
+ string.push(`${significand[index++]}`);
808
+ }
809
+ } else {
810
+ let radix_position = significand_digits + exponent;
811
+
812
+ // non-zero digits before radix
813
+ if (radix_position > 0) {
814
+ for (let i = 0; i < radix_position; i++) {
815
+ string.push(`${significand[index++]}`);
816
+ }
817
+ } else {
818
+ string.push('0');
819
+ }
820
+
821
+ string.push('.');
822
+ // add leading zeros after radix
823
+ while (radix_position++ < 0) {
824
+ string.push('0');
825
+ }
826
+
827
+ for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) {
828
+ string.push(`${significand[index++]}`);
829
+ }
830
+ }
831
+ }
832
+
833
+ return string.join('');
834
+ }
835
+
836
+ toJSON(): Decimal128Extended {
837
+ return { $numberDecimal: this.toString() };
838
+ }
839
+
840
+ /** @internal */
841
+ toExtendedJSON(): Decimal128Extended {
842
+ return { $numberDecimal: this.toString() };
843
+ }
844
+
845
+ /** @internal */
846
+ static fromExtendedJSON(doc: Decimal128Extended): Decimal128 {
847
+ return Decimal128.fromString(doc.$numberDecimal);
848
+ }
849
+
850
+ inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
851
+ inspect ??= defaultInspect;
852
+ const d128string = inspect(this.toString(), options);
853
+ return `new Decimal128(${d128string})`;
854
+ }
855
+ }
gateway/node_modules/bson/src/double.ts ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { BSONValue } from './bson_value';
2
+ import { BSONError } from './error';
3
+ import type { EJSONOptions } from './extended_json';
4
+ import { type InspectFn, defaultInspect } from './parser/utils';
5
+
6
+ /** @public */
7
+ export interface DoubleExtended {
8
+ $numberDouble: string;
9
+ }
10
+
11
+ /**
12
+ * A class representation of the BSON Double type.
13
+ * @public
14
+ * @category BSONType
15
+ */
16
+ export class Double extends BSONValue {
17
+ get _bsontype(): 'Double' {
18
+ return 'Double';
19
+ }
20
+
21
+ value!: number;
22
+ /**
23
+ * Create a Double type
24
+ *
25
+ * @param value - the number we want to represent as a double.
26
+ */
27
+ constructor(value: number) {
28
+ super();
29
+ if ((value as unknown) instanceof Number) {
30
+ value = value.valueOf();
31
+ }
32
+
33
+ this.value = +value;
34
+ }
35
+
36
+ /**
37
+ * Attempt to create an double type from string.
38
+ *
39
+ * This method will throw a BSONError on any string input that is not representable as a IEEE-754 64-bit double.
40
+ * Notably, this method will also throw on the following string formats:
41
+ * - Strings in non-decimal and non-exponential formats (binary, hex, or octal digits)
42
+ * - Strings with characters other than numeric, floating point, or leading sign characters (Note: 'Infinity', '-Infinity', and 'NaN' input strings are still allowed)
43
+ * - Strings with leading and/or trailing whitespace
44
+ *
45
+ * Strings with leading zeros, however, are also allowed
46
+ *
47
+ * @param value - the string we want to represent as a double.
48
+ */
49
+ static fromString(value: string): Double {
50
+ const coercedValue = Number(value);
51
+
52
+ if (value === 'NaN') return new Double(NaN);
53
+ if (value === 'Infinity') return new Double(Infinity);
54
+ if (value === '-Infinity') return new Double(-Infinity);
55
+
56
+ if (!Number.isFinite(coercedValue)) {
57
+ throw new BSONError(`Input: ${value} is not representable as a Double`);
58
+ }
59
+ if (value.trim() !== value) {
60
+ throw new BSONError(`Input: '${value}' contains whitespace`);
61
+ }
62
+ if (value === '') {
63
+ throw new BSONError(`Input is an empty string`);
64
+ }
65
+ if (/[^-0-9.+eE]/.test(value)) {
66
+ throw new BSONError(`Input: '${value}' is not in decimal or exponential notation`);
67
+ }
68
+ return new Double(coercedValue);
69
+ }
70
+
71
+ /**
72
+ * Access the number value.
73
+ *
74
+ * @returns returns the wrapped double number.
75
+ */
76
+ valueOf(): number {
77
+ return this.value;
78
+ }
79
+
80
+ toJSON(): number {
81
+ return this.value;
82
+ }
83
+
84
+ toString(radix?: number): string {
85
+ return this.value.toString(radix);
86
+ }
87
+
88
+ /** @internal */
89
+ toExtendedJSON(options?: EJSONOptions): number | DoubleExtended {
90
+ if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) {
91
+ return this.value;
92
+ }
93
+
94
+ if (Object.is(Math.sign(this.value), -0)) {
95
+ // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user
96
+ // explicitly provided `-0` then we need to ensure the sign makes it into the output
97
+ return { $numberDouble: '-0.0' };
98
+ }
99
+
100
+ return {
101
+ $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString()
102
+ };
103
+ }
104
+
105
+ /** @internal */
106
+ static fromExtendedJSON(doc: DoubleExtended, options?: EJSONOptions): number | Double {
107
+ const doubleValue = parseFloat(doc.$numberDouble);
108
+ return options && options.relaxed ? doubleValue : new Double(doubleValue);
109
+ }
110
+
111
+ inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
112
+ inspect ??= defaultInspect;
113
+ return `new Double(${inspect(this.value, options)})`;
114
+ }
115
+ }
gateway/node_modules/bson/src/error.ts ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { BSON_MAJOR_VERSION } from './constants';
2
+
3
+ /**
4
+ * @public
5
+ * @category Error
6
+ *
7
+ * `BSONError` objects are thrown when BSON encounters an error.
8
+ *
9
+ * This is the parent class for all the other errors thrown by this library.
10
+ */
11
+ export class BSONError extends Error {
12
+ /**
13
+ * @internal
14
+ * The underlying algorithm for isBSONError may change to improve how strict it is
15
+ * about determining if an input is a BSONError. But it must remain backwards compatible
16
+ * with previous minors & patches of the current major version.
17
+ */
18
+ protected get bsonError(): true {
19
+ return true;
20
+ }
21
+
22
+ override get name(): string {
23
+ return 'BSONError';
24
+ }
25
+
26
+ constructor(message: string, options?: { cause?: unknown }) {
27
+ super(message, options);
28
+ }
29
+
30
+ /**
31
+ * @public
32
+ *
33
+ * All errors thrown from the BSON library inherit from `BSONError`.
34
+ * This method can assist with determining if an error originates from the BSON library
35
+ * even if it does not pass an `instanceof` check against this class' constructor.
36
+ *
37
+ * @param value - any javascript value that needs type checking
38
+ */
39
+ public static isBSONError(value: unknown): value is BSONError {
40
+ return (
41
+ value != null &&
42
+ typeof value === 'object' &&
43
+ 'bsonError' in value &&
44
+ value.bsonError === true &&
45
+ // Do not access the following properties, just check existence
46
+ 'name' in value &&
47
+ 'message' in value &&
48
+ 'stack' in value
49
+ );
50
+ }
51
+ }
52
+
53
+ /**
54
+ * @public
55
+ * @category Error
56
+ */
57
+ export class BSONVersionError extends BSONError {
58
+ get name(): 'BSONVersionError' {
59
+ return 'BSONVersionError';
60
+ }
61
+
62
+ constructor() {
63
+ super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`);
64
+ }
65
+ }
66
+
67
+ /**
68
+ * @public
69
+ * @category Error
70
+ *
71
+ * An error generated when BSON functions encounter an unexpected input
72
+ * or reaches an unexpected/invalid internal state
73
+ *
74
+ */
75
+ export class BSONRuntimeError extends BSONError {
76
+ get name(): 'BSONRuntimeError' {
77
+ return 'BSONRuntimeError';
78
+ }
79
+
80
+ constructor(message: string) {
81
+ super(message);
82
+ }
83
+ }
84
+
85
+ /**
86
+ * @public
87
+ * @category Error
88
+ *
89
+ * @experimental
90
+ *
91
+ * An error generated when BSON bytes are invalid.
92
+ * Reports the offset the parser was able to reach before encountering the error.
93
+ */
94
+ export class BSONOffsetError extends BSONError {
95
+ public get name(): 'BSONOffsetError' {
96
+ return 'BSONOffsetError';
97
+ }
98
+
99
+ public offset: number;
100
+
101
+ constructor(message: string, offset: number, options?: { cause?: unknown }) {
102
+ super(`${message}. offset: ${offset}`, options);
103
+ this.offset = offset;
104
+ }
105
+ }
gateway/node_modules/bson/src/extended_json.ts ADDED
@@ -0,0 +1,557 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Binary } from './binary';
2
+ import type { Document } from './bson';
3
+ import { Code } from './code';
4
+ import {
5
+ BSON_INT32_MAX,
6
+ BSON_INT32_MIN,
7
+ BSON_INT64_MAX,
8
+ BSON_INT64_MIN,
9
+ BSON_MAJOR_VERSION,
10
+ BSON_VERSION_SYMBOL
11
+ } from './constants';
12
+ import { DBRef, isDBRefLike } from './db_ref';
13
+ import { Decimal128 } from './decimal128';
14
+ import { Double } from './double';
15
+ import { BSONError, BSONRuntimeError, BSONVersionError } from './error';
16
+ import { Int32 } from './int_32';
17
+ import { Long } from './long';
18
+ import { MaxKey } from './max_key';
19
+ import { MinKey } from './min_key';
20
+ import { ObjectId } from './objectid';
21
+ import { isDate, isRegExp, isMap } from './parser/utils';
22
+ import { BSONRegExp } from './regexp';
23
+ import { BSONSymbol } from './symbol';
24
+ import { Timestamp } from './timestamp';
25
+
26
+ /** @public */
27
+ export type EJSONOptionsBase = {
28
+ /**
29
+ * Output using the Extended JSON v1 spec
30
+ * @defaultValue `false`
31
+ */
32
+ legacy?: boolean;
33
+ /**
34
+ * Enable Extended JSON's `relaxed` mode, which attempts to return native JS types where possible, rather than BSON types
35
+ * @defaultValue `false`
36
+ */
37
+ relaxed?: boolean;
38
+ };
39
+
40
+ /** @public */
41
+ export type EJSONSerializeOptions = EJSONOptionsBase & {
42
+ /**
43
+ * Omits undefined values from the output instead of converting them to null
44
+ * @defaultValue `false`
45
+ */
46
+ ignoreUndefined?: boolean;
47
+ };
48
+
49
+ /** @public */
50
+ export type EJSONParseOptions = EJSONOptionsBase & {
51
+ /**
52
+ * Enable native bigint support
53
+ * @defaultValue `false`
54
+ */
55
+ useBigInt64?: boolean;
56
+ };
57
+
58
+ /** @public */
59
+ export type EJSONOptions = EJSONSerializeOptions & EJSONParseOptions;
60
+
61
+ /** @internal */
62
+ type BSONType =
63
+ | Binary
64
+ | Code
65
+ | DBRef
66
+ | Decimal128
67
+ | Double
68
+ | Int32
69
+ | Long
70
+ | MaxKey
71
+ | MinKey
72
+ | ObjectId
73
+ | BSONRegExp
74
+ | BSONSymbol
75
+ | Timestamp;
76
+
77
+ function isBSONType(value: unknown): value is BSONType {
78
+ return (
79
+ value != null &&
80
+ typeof value === 'object' &&
81
+ '_bsontype' in value &&
82
+ typeof value._bsontype === 'string'
83
+ );
84
+ }
85
+
86
+ // all the types where we don't need to do any special processing and can just pass the EJSON
87
+ //straight to type.fromExtendedJSON
88
+ const keysToCodecs = {
89
+ $oid: ObjectId,
90
+ $binary: Binary,
91
+ $uuid: Binary,
92
+ $symbol: BSONSymbol,
93
+ $numberInt: Int32,
94
+ $numberDecimal: Decimal128,
95
+ $numberDouble: Double,
96
+ $numberLong: Long,
97
+ $minKey: MinKey,
98
+ $maxKey: MaxKey,
99
+ $regex: BSONRegExp,
100
+ $regularExpression: BSONRegExp,
101
+ $timestamp: Timestamp
102
+ } as const;
103
+
104
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
105
+ function deserializeValue(value: any, options: EJSONOptions = {}) {
106
+ if (typeof value === 'number') {
107
+ // TODO(NODE-4377): EJSON js number handling diverges from BSON
108
+ const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN;
109
+ const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN;
110
+
111
+ if (options.relaxed || options.legacy) {
112
+ return value;
113
+ }
114
+
115
+ if (Number.isInteger(value) && !Object.is(value, -0)) {
116
+ // interpret as being of the smallest BSON integer type that can represent the number exactly
117
+ if (in32BitRange) {
118
+ return new Int32(value);
119
+ }
120
+ if (in64BitRange) {
121
+ if (options.useBigInt64) {
122
+ return BigInt(value);
123
+ }
124
+ return Long.fromNumber(value);
125
+ }
126
+ }
127
+
128
+ // If the number is a non-integer or out of integer range, should interpret as BSON Double.
129
+ return new Double(value);
130
+ }
131
+
132
+ // from here on out we're looking for bson types, so bail if its not an object
133
+ if (value == null || typeof value !== 'object') return value;
134
+
135
+ // upgrade deprecated undefined to null
136
+ if (value.$undefined) return null;
137
+
138
+ const keys = Object.keys(value).filter(
139
+ k => k.startsWith('$') && value[k] != null
140
+ ) as (keyof typeof keysToCodecs)[];
141
+ for (let i = 0; i < keys.length; i++) {
142
+ const c = keysToCodecs[keys[i]];
143
+ if (c) return c.fromExtendedJSON(value, options);
144
+ }
145
+
146
+ if (value.$date != null) {
147
+ const d = value.$date;
148
+ const date = new Date();
149
+
150
+ if (options.legacy) {
151
+ if (typeof d === 'number') date.setTime(d);
152
+ else if (typeof d === 'string') date.setTime(Date.parse(d));
153
+ else if (typeof d === 'bigint') date.setTime(Number(d));
154
+ else throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
155
+ } else {
156
+ if (typeof d === 'string') date.setTime(Date.parse(d));
157
+ else if (Long.isLong(d)) date.setTime(d.toNumber());
158
+ else if (typeof d === 'number' && options.relaxed) date.setTime(d);
159
+ else if (typeof d === 'bigint') date.setTime(Number(d));
160
+ else throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
161
+ }
162
+ return date;
163
+ }
164
+
165
+ if (value.$code != null) {
166
+ const copy = Object.assign({}, value);
167
+ if (value.$scope) {
168
+ copy.$scope = deserializeValue(value.$scope);
169
+ }
170
+
171
+ return Code.fromExtendedJSON(value);
172
+ }
173
+
174
+ if (isDBRefLike(value) || value.$dbPointer) {
175
+ const v = value.$ref ? value : value.$dbPointer;
176
+
177
+ // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped)
178
+ // because of the order JSON.parse goes through the document
179
+ if (v instanceof DBRef) return v;
180
+
181
+ const dollarKeys = Object.keys(v).filter(k => k.startsWith('$'));
182
+ let valid = true;
183
+ dollarKeys.forEach(k => {
184
+ if (['$ref', '$id', '$db'].indexOf(k) === -1) valid = false;
185
+ });
186
+
187
+ // only make DBRef if $ keys are all valid
188
+ if (valid) return DBRef.fromExtendedJSON(v);
189
+ }
190
+
191
+ return value;
192
+ }
193
+
194
+ type EJSONSerializeInternalOptions = EJSONSerializeOptions & {
195
+ seenObjects: { obj: unknown; propertyName: string }[];
196
+ };
197
+
198
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
199
+ function serializeArray(array: any[], options: EJSONSerializeInternalOptions): any[] {
200
+ return array.map((v: unknown, index: number) => {
201
+ options.seenObjects.push({ propertyName: `index ${index}`, obj: null });
202
+ try {
203
+ return serializeValue(v, options);
204
+ } finally {
205
+ options.seenObjects.pop();
206
+ }
207
+ });
208
+ }
209
+
210
+ function getISOString(date: Date) {
211
+ const isoStr = date.toISOString();
212
+ // we should only show milliseconds in timestamp if they're non-zero
213
+ return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z';
214
+ }
215
+
216
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
217
+ function serializeValue(value: any, options: EJSONSerializeInternalOptions): any {
218
+ if (value instanceof Map || isMap(value)) {
219
+ const obj: Record<string, unknown> = Object.create(null);
220
+ for (const [k, v] of value) {
221
+ if (typeof k !== 'string') {
222
+ throw new BSONError('Can only serialize maps with string keys');
223
+ }
224
+ obj[k] = v;
225
+ }
226
+
227
+ return serializeValue(obj, options);
228
+ }
229
+
230
+ if ((typeof value === 'object' || typeof value === 'function') && value !== null) {
231
+ const index = options.seenObjects.findIndex(entry => entry.obj === value);
232
+ if (index !== -1) {
233
+ const props = options.seenObjects.map(entry => entry.propertyName);
234
+ const leadingPart = props
235
+ .slice(0, index)
236
+ .map(prop => `${prop} -> `)
237
+ .join('');
238
+ const alreadySeen = props[index];
239
+ const circularPart =
240
+ ' -> ' +
241
+ props
242
+ .slice(index + 1, props.length - 1)
243
+ .map(prop => `${prop} -> `)
244
+ .join('');
245
+ const current = props[props.length - 1];
246
+ const leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2);
247
+ const dashes = '-'.repeat(
248
+ circularPart.length + (alreadySeen.length + current.length) / 2 - 1
249
+ );
250
+
251
+ throw new BSONError(
252
+ 'Converting circular structure to EJSON:\n' +
253
+ ` ${leadingPart}${alreadySeen}${circularPart}${current}\n` +
254
+ ` ${leadingSpace}\\${dashes}/`
255
+ );
256
+ }
257
+ options.seenObjects[options.seenObjects.length - 1].obj = value;
258
+ }
259
+
260
+ if (Array.isArray(value)) return serializeArray(value, options);
261
+
262
+ if (value === undefined) return options.ignoreUndefined ? undefined : null;
263
+
264
+ if (value instanceof Date || isDate(value)) {
265
+ const dateNum = value.getTime(),
266
+ // is it in year range 1970-9999?
267
+ // 253402300800000 is the first instant of year 10000 (+010000-01-01T00:00:00Z).
268
+ // It is the exclusive upper bound: a relaxed date is emitted as an ISO 8601 string,
269
+ // which only has a 4-digit year, so year 10000 and later are kept as a numeric timestamp.
270
+ inRange = dateNum > -1 && dateNum < 253402300800000;
271
+
272
+ if (options.legacy) {
273
+ return options.relaxed && inRange
274
+ ? { $date: value.getTime() }
275
+ : { $date: getISOString(value) };
276
+ }
277
+ return options.relaxed && inRange
278
+ ? { $date: getISOString(value) }
279
+ : { $date: { $numberLong: value.getTime().toString() } };
280
+ }
281
+
282
+ if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) {
283
+ if (Number.isInteger(value) && !Object.is(value, -0)) {
284
+ // interpret as being of the smallest BSON integer type that can represent the number exactly
285
+ if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
286
+ return { $numberInt: value.toString() };
287
+ }
288
+ if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) {
289
+ // TODO(NODE-4377): EJSON js number handling diverges from BSON
290
+ return { $numberLong: value.toString() };
291
+ }
292
+ }
293
+ return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() };
294
+ }
295
+
296
+ if (typeof value === 'bigint') {
297
+ if (!options.relaxed) {
298
+ return { $numberLong: BigInt.asIntN(64, value).toString() };
299
+ }
300
+ return Number(BigInt.asIntN(64, value));
301
+ }
302
+
303
+ if (value instanceof RegExp || isRegExp(value)) {
304
+ let flags = value.flags;
305
+ if (flags === undefined) {
306
+ const match = value.toString().match(/[gimuy]*$/);
307
+ if (match) {
308
+ flags = match[0];
309
+ }
310
+ }
311
+
312
+ const rx = new BSONRegExp(value.source, flags);
313
+ return rx.toExtendedJSON(options);
314
+ }
315
+
316
+ if (value != null && typeof value === 'object') return serializeDocument(value, options);
317
+ return value;
318
+ }
319
+
320
+ const BSON_TYPE_MAPPINGS = {
321
+ Binary: (o: Binary) => new Binary(o.value(), o.sub_type),
322
+ Code: (o: Code) => new Code(o.code, o.scope),
323
+ DBRef: (o: DBRef) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields), // "namespace" for 1.x library backwards compat
324
+ Decimal128: (o: Decimal128) => new Decimal128(o.bytes),
325
+ Double: (o: Double) => new Double(o.value),
326
+ Int32: (o: Int32) => new Int32(o.value),
327
+ Long: (
328
+ o: Long & {
329
+ low_: number;
330
+ high_: number;
331
+ unsigned_: boolean | undefined;
332
+ }
333
+ ) =>
334
+ Long.fromBits(
335
+ // underscore variants for 1.x backwards compatibility
336
+ o.low != null ? o.low : o.low_,
337
+ o.low != null ? o.high : o.high_,
338
+ o.low != null ? o.unsigned : o.unsigned_
339
+ ),
340
+ MaxKey: () => new MaxKey(),
341
+ MinKey: () => new MinKey(),
342
+ ObjectId: (o: ObjectId) => new ObjectId(o),
343
+ BSONRegExp: (o: BSONRegExp) => new BSONRegExp(o.pattern, o.options),
344
+ BSONSymbol: (o: BSONSymbol) => new BSONSymbol(o.value),
345
+ Timestamp: (o: Timestamp) => Timestamp.fromBits(o.low, o.high)
346
+ } as const;
347
+
348
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
349
+ function serializeDocument(doc: any, options: EJSONSerializeInternalOptions) {
350
+ if (doc == null || typeof doc !== 'object') throw new BSONError('not an object instance');
351
+
352
+ const bsontype: BSONType['_bsontype'] = doc._bsontype;
353
+ if (typeof bsontype === 'undefined') {
354
+ // It's a regular object. Recursively serialize its property values.
355
+ const _doc: Document = {};
356
+ for (const name of Object.keys(doc)) {
357
+ options.seenObjects.push({ propertyName: name, obj: null });
358
+ try {
359
+ const value = serializeValue(doc[name], options);
360
+ if (name === '__proto__') {
361
+ Object.defineProperty(_doc, name, {
362
+ value,
363
+ writable: true,
364
+ enumerable: true,
365
+ configurable: true
366
+ });
367
+ } else {
368
+ _doc[name] = value;
369
+ }
370
+ } finally {
371
+ options.seenObjects.pop();
372
+ }
373
+ }
374
+ return _doc;
375
+ } else if (
376
+ doc != null &&
377
+ typeof doc === 'object' &&
378
+ typeof doc._bsontype === 'string' &&
379
+ doc[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION
380
+ ) {
381
+ throw new BSONVersionError();
382
+ } else if (isBSONType(doc)) {
383
+ // the "document" is really just a BSON type object
384
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
385
+ let outDoc: any = doc;
386
+ if (typeof outDoc.toExtendedJSON !== 'function') {
387
+ // There's no EJSON serialization function on the object. It's probably an
388
+ // object created by a previous version of this library (or another library)
389
+ // that's duck-typing objects to look like they were generated by this library).
390
+ // Copy the object into this library's version of that type.
391
+ const mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
392
+ if (!mapper) {
393
+ throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
394
+ }
395
+ outDoc = mapper(outDoc);
396
+ }
397
+
398
+ // Two BSON types may have nested objects that may need to be serialized too
399
+ if (bsontype === 'Code' && outDoc.scope) {
400
+ outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options));
401
+ } else if (bsontype === 'DBRef' && outDoc.oid) {
402
+ outDoc = new DBRef(
403
+ serializeValue(outDoc.collection, options),
404
+ serializeValue(outDoc.oid, options),
405
+ serializeValue(outDoc.db, options),
406
+ serializeValue(outDoc.fields, options)
407
+ );
408
+ }
409
+
410
+ return outDoc.toExtendedJSON(options);
411
+ } else {
412
+ throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype);
413
+ }
414
+ }
415
+
416
+ /**
417
+ * Parse an Extended JSON string, constructing the JavaScript value or object described by that
418
+ * string.
419
+ *
420
+ * @example
421
+ * ```js
422
+ * const { EJSON } = require('bson');
423
+ * const text = '{ "int32": { "$numberInt": "10" } }';
424
+ *
425
+ * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }
426
+ * console.log(EJSON.parse(text, { relaxed: false }));
427
+ *
428
+ * // prints { int32: 10 }
429
+ * console.log(EJSON.parse(text));
430
+ * ```
431
+ */
432
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
433
+ function parse(text: string, options?: EJSONParseOptions): any {
434
+ const ejsonOptions = {
435
+ useBigInt64: options?.useBigInt64 ?? false,
436
+ relaxed: options?.relaxed ?? true,
437
+ legacy: options?.legacy ?? false
438
+ };
439
+ return JSON.parse(text, (key, value) => {
440
+ if (key.indexOf('\x00') !== -1) {
441
+ throw new BSONError(
442
+ `BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`
443
+ );
444
+ }
445
+ return deserializeValue(value, ejsonOptions);
446
+ });
447
+ }
448
+
449
+ /* eslint-disable @typescript-eslint/no-explicit-any */
450
+ /**
451
+ * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer
452
+ * function is specified or optionally including only the specified properties if a replacer array
453
+ * is specified.
454
+ *
455
+ * @param value - The value to convert to extended JSON
456
+ * @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
457
+ * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes.
458
+ * @param options - Optional settings
459
+ *
460
+ * @example
461
+ * ```js
462
+ * const { EJSON } = require('bson');
463
+ * const Int32 = require('mongodb').Int32;
464
+ * const doc = { int32: new Int32(10) };
465
+ *
466
+ * // prints '{"int32":{"$numberInt":"10"}}'
467
+ * console.log(EJSON.stringify(doc, { relaxed: false }));
468
+ *
469
+ * // prints '{"int32":10}'
470
+ * console.log(EJSON.stringify(doc));
471
+ *
472
+ * // prints '{"int32":{"$numberInt":"10"}}' with 2 space indentation
473
+ * console.log(EJSON.stringify(doc, { relaxed: false }, 2));
474
+ * ```
475
+ */
476
+ function stringify(
477
+ value: any,
478
+ replacer?: (number | string)[] | ((this: any, key: string, value: any) => any) | null,
479
+ space?: string | number,
480
+ options?: EJSONSerializeOptions
481
+ ): string;
482
+ function stringify(
483
+ value: any,
484
+ replacer?: (number | string)[] | ((this: any, key: string, value: any) => any) | null,
485
+ options?: EJSONSerializeOptions
486
+ ): string;
487
+ function stringify(value: any, options?: EJSONSerializeOptions, space?: string | number): string;
488
+ function stringify(
489
+ value: any,
490
+ replacerOrOptions?:
491
+ | (number | string)[]
492
+ | ((this: any, key: string, value: any) => any)
493
+ | null
494
+ | EJSONSerializeOptions,
495
+ spaceOrOptions?: string | number | EJSONSerializeOptions,
496
+ options?: EJSONSerializeOptions
497
+ ): string {
498
+ /* eslint-enable @typescript-eslint/no-explicit-any */
499
+
500
+ if (spaceOrOptions != null && typeof spaceOrOptions === 'object') {
501
+ options = spaceOrOptions;
502
+ spaceOrOptions = undefined;
503
+ }
504
+ if (
505
+ replacerOrOptions != null &&
506
+ typeof replacerOrOptions === 'object' &&
507
+ !Array.isArray(replacerOrOptions)
508
+ ) {
509
+ options = replacerOrOptions;
510
+ replacerOrOptions = undefined;
511
+ }
512
+
513
+ const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, {
514
+ seenObjects: [{ propertyName: '(root)', obj: null }]
515
+ });
516
+
517
+ const doc = serializeValue(value, serializeOptions);
518
+ return JSON.stringify(doc, replacerOrOptions as Parameters<JSON['stringify']>[1], spaceOrOptions);
519
+ }
520
+
521
+ /**
522
+ * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.
523
+ *
524
+ * @param value - The object to serialize
525
+ * @param options - Optional settings passed to the `stringify` function
526
+ */
527
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
528
+ function EJSONserialize(value: any, options?: EJSONSerializeOptions): Document {
529
+ options = options || {};
530
+ return JSON.parse(stringify(value, options));
531
+ }
532
+
533
+ /**
534
+ * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types
535
+ *
536
+ * @param ejson - The Extended JSON object to deserialize
537
+ * @param options - Optional settings passed to the parse method
538
+ */
539
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
540
+ function EJSONdeserialize(ejson: Document, options?: EJSONParseOptions): any {
541
+ options = options || {};
542
+ return parse(JSON.stringify(ejson), options);
543
+ }
544
+
545
+ /** @public */
546
+ const EJSON: {
547
+ parse: typeof parse;
548
+ stringify: typeof stringify;
549
+ serialize: typeof EJSONserialize;
550
+ deserialize: typeof EJSONdeserialize;
551
+ } = Object.create(null);
552
+ EJSON.parse = parse;
553
+ EJSON.stringify = stringify;
554
+ EJSON.serialize = EJSONserialize;
555
+ EJSON.deserialize = EJSONdeserialize;
556
+ Object.freeze(EJSON);
557
+ export { EJSON };
gateway/node_modules/bson/src/index.ts ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as BSON from './bson';
2
+
3
+ // Export all named properties from BSON to support
4
+ // import { ObjectId, serialize } from 'bson';
5
+ // const { ObjectId, serialize } = require('bson');
6
+ export * from './bson';
7
+
8
+ // Export BSON as a namespace to support:
9
+ // import { BSON } from 'bson';
10
+ // const { BSON } = require('bson');
11
+ export { BSON };
12
+
13
+ // BSON does **NOT** have a default export
14
+
15
+ // The following will crash in es module environments
16
+ // import BSON from 'bson';
17
+
18
+ // The following will work as expected, BSON as a namespace of all the APIs (BSON.ObjectId, BSON.serialize)
19
+ // const BSON = require('bson');
gateway/node_modules/bson/src/int_32.ts ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { BSONValue } from './bson_value';
2
+ import { BSON_INT32_MAX, BSON_INT32_MIN } from './constants';
3
+ import { BSONError } from './error';
4
+ import type { EJSONOptions } from './extended_json';
5
+ import { type InspectFn, defaultInspect } from './parser/utils';
6
+ import { removeLeadingZerosAndExplicitPlus } from './utils/string_utils';
7
+
8
+ /** @public */
9
+ export interface Int32Extended {
10
+ $numberInt: string;
11
+ }
12
+
13
+ /**
14
+ * A class representation of a BSON Int32 type.
15
+ * @public
16
+ * @category BSONType
17
+ */
18
+ export class Int32 extends BSONValue {
19
+ get _bsontype(): 'Int32' {
20
+ return 'Int32';
21
+ }
22
+
23
+ value!: number;
24
+ /**
25
+ * Create an Int32 type
26
+ *
27
+ * @param value - the number we want to represent as an int32.
28
+ */
29
+ constructor(value: number | string) {
30
+ super();
31
+ if ((value as unknown) instanceof Number) {
32
+ value = value.valueOf();
33
+ }
34
+
35
+ this.value = +value | 0;
36
+ }
37
+
38
+ /**
39
+ * Attempt to create an Int32 type from string.
40
+ *
41
+ * This method will throw a BSONError on any string input that is not representable as an Int32.
42
+ * Notably, this method will also throw on the following string formats:
43
+ * - Strings in non-decimal formats (exponent notation, binary, hex, or octal digits)
44
+ * - Strings non-numeric and non-leading sign characters (ex: '2.0', '24,000')
45
+ * - Strings with leading and/or trailing whitespace
46
+ *
47
+ * Strings with leading zeros, however, are allowed.
48
+ *
49
+ * @param value - the string we want to represent as an int32.
50
+ */
51
+ static fromString(value: string): Int32 {
52
+ const cleanedValue = removeLeadingZerosAndExplicitPlus(value);
53
+
54
+ const coercedValue = Number(value);
55
+
56
+ if (BSON_INT32_MAX < coercedValue) {
57
+ throw new BSONError(`Input: '${value}' is larger than the maximum value for Int32`);
58
+ } else if (BSON_INT32_MIN > coercedValue) {
59
+ throw new BSONError(`Input: '${value}' is smaller than the minimum value for Int32`);
60
+ } else if (!Number.isSafeInteger(coercedValue)) {
61
+ throw new BSONError(`Input: '${value}' is not a safe integer`);
62
+ } else if (coercedValue.toString() !== cleanedValue) {
63
+ // catch all case
64
+ throw new BSONError(`Input: '${value}' is not a valid Int32 string`);
65
+ }
66
+ return new Int32(coercedValue);
67
+ }
68
+
69
+ /**
70
+ * Access the number value.
71
+ *
72
+ * @returns returns the wrapped int32 number.
73
+ */
74
+ valueOf(): number {
75
+ return this.value;
76
+ }
77
+
78
+ toString(radix?: number): string {
79
+ return this.value.toString(radix);
80
+ }
81
+
82
+ toJSON(): number {
83
+ return this.value;
84
+ }
85
+
86
+ /** @internal */
87
+ toExtendedJSON(options?: EJSONOptions): number | Int32Extended {
88
+ if (options && (options.relaxed || options.legacy)) return this.value;
89
+ return { $numberInt: this.value.toString() };
90
+ }
91
+
92
+ /** @internal */
93
+ static fromExtendedJSON(doc: Int32Extended, options?: EJSONOptions): number | Int32 {
94
+ return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt);
95
+ }
96
+
97
+ inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
98
+ inspect ??= defaultInspect;
99
+ return `new Int32(${inspect(this.value, options)})`;
100
+ }
101
+ }
gateway/node_modules/bson/src/long.ts ADDED
@@ -0,0 +1,1240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { BSONValue } from './bson_value';
2
+ import { BSONError } from './error';
3
+ import type { EJSONOptions } from './extended_json';
4
+ import { type InspectFn, defaultInspect } from './parser/utils';
5
+ import type { Timestamp } from './timestamp';
6
+ import * as StringUtils from './utils/string_utils';
7
+
8
+ interface LongWASMHelpers {
9
+ /** Gets the high bits of the last operation performed */
10
+ get_high(this: void): number;
11
+ div_u(
12
+ this: void,
13
+ lowBits: number,
14
+ highBits: number,
15
+ lowBitsDivisor: number,
16
+ highBitsDivisor: number
17
+ ): number;
18
+ div_s(
19
+ this: void,
20
+ lowBits: number,
21
+ highBits: number,
22
+ lowBitsDivisor: number,
23
+ highBitsDivisor: number
24
+ ): number;
25
+ rem_u(
26
+ this: void,
27
+ lowBits: number,
28
+ highBits: number,
29
+ lowBitsDivisor: number,
30
+ highBitsDivisor: number
31
+ ): number;
32
+ rem_s(
33
+ this: void,
34
+ lowBits: number,
35
+ highBits: number,
36
+ lowBitsDivisor: number,
37
+ highBitsDivisor: number
38
+ ): number;
39
+ mul(
40
+ this: void,
41
+ lowBits: number,
42
+ highBits: number,
43
+ lowBitsMultiplier: number,
44
+ highBitsMultiplier: number
45
+ ): number;
46
+ }
47
+
48
+ /**
49
+ * wasm optimizations, to do native i64 multiplication and divide
50
+ */
51
+ let wasm: LongWASMHelpers | undefined = undefined;
52
+
53
+ /* We do not want to have to include DOM types just for this check */
54
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
55
+ declare const WebAssembly: any;
56
+
57
+ try {
58
+ wasm = new WebAssembly.Instance(
59
+ new WebAssembly.Module(
60
+ // prettier-ignore
61
+ 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])
62
+ ),
63
+ {}
64
+ ).exports as unknown as LongWASMHelpers;
65
+ } catch {
66
+ // no wasm support
67
+ }
68
+
69
+ const TWO_PWR_16_DBL = 1 << 16;
70
+ const TWO_PWR_24_DBL = 1 << 24;
71
+ const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
72
+ const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
73
+ const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
74
+
75
+ /** A cache of the Long representations of small integer values. */
76
+ const INT_CACHE: { [key: number]: Long } = {};
77
+
78
+ /** A cache of the Long representations of small unsigned integer values. */
79
+ const UINT_CACHE: { [key: number]: Long } = {};
80
+
81
+ const MAX_INT64_STRING_LENGTH = 20;
82
+
83
+ const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/;
84
+
85
+ /** @public */
86
+ export interface LongExtended {
87
+ $numberLong: string;
88
+ }
89
+
90
+ /**
91
+ * A class representing a 64-bit integer
92
+ * @public
93
+ * @category BSONType
94
+ * @remarks
95
+ * The internal representation of a long is the two given signed, 32-bit values.
96
+ * We use 32-bit pieces because these are the size of integers on which
97
+ * Javascript performs bit-operations. For operations like addition and
98
+ * multiplication, we split each number into 16 bit pieces, which can easily be
99
+ * multiplied within Javascript's floating-point representation without overflow
100
+ * or change in sign.
101
+ * In the algorithms below, we frequently reduce the negative case to the
102
+ * positive case by negating the input(s) and then post-processing the result.
103
+ * Note that we must ALWAYS check specially whether those values are MIN_VALUE
104
+ * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
105
+ * a positive number, it overflows back into a negative). Not handling this
106
+ * case would often result in infinite recursion.
107
+ * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class.
108
+ */
109
+ export class Long extends BSONValue {
110
+ get _bsontype(): 'Long' {
111
+ return 'Long';
112
+ }
113
+
114
+ /** An indicator used to reliably determine if an object is a Long or not. */
115
+ get __isLong__(): boolean {
116
+ return true;
117
+ }
118
+
119
+ /**
120
+ * The high 32 bits as a signed value.
121
+ */
122
+ high: number;
123
+
124
+ /**
125
+ * The low 32 bits as a signed value.
126
+ */
127
+ low: number;
128
+
129
+ /**
130
+ * Whether unsigned or not.
131
+ */
132
+ unsigned: boolean;
133
+
134
+ /**
135
+ * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
136
+ *
137
+ * @param low - The low (signed) 32 bits of the long
138
+ * @param high - The high (signed) 32 bits of the long
139
+ * @param unsigned - Whether unsigned or not, defaults to signed
140
+ */
141
+ constructor(low: number, high?: number, unsigned?: boolean);
142
+ /**
143
+ * Constructs a 64 bit two's-complement integer, given a bigint representation.
144
+ *
145
+ * @param value - BigInt representation of the long value
146
+ * @param unsigned - Whether unsigned or not, defaults to signed
147
+ */
148
+ constructor(value: bigint, unsigned?: boolean);
149
+ /**
150
+ * Constructs a 64 bit two's-complement integer, given a string representation.
151
+ *
152
+ * @param value - String representation of the long value
153
+ * @param unsigned - Whether unsigned or not, defaults to signed
154
+ */
155
+ constructor(value: string, unsigned?: boolean);
156
+ constructor(
157
+ lowOrValue: number | bigint | string = 0,
158
+ highOrUnsigned?: number | boolean,
159
+ unsigned?: boolean
160
+ ) {
161
+ super();
162
+ const unsignedBool = typeof highOrUnsigned === 'boolean' ? highOrUnsigned : Boolean(unsigned);
163
+ const high = typeof highOrUnsigned === 'number' ? highOrUnsigned : 0;
164
+ const res =
165
+ typeof lowOrValue === 'string'
166
+ ? Long.fromString(lowOrValue, unsignedBool)
167
+ : typeof lowOrValue === 'bigint'
168
+ ? Long.fromBigInt(lowOrValue, unsignedBool)
169
+ : { low: lowOrValue | 0, high: high | 0, unsigned: unsignedBool };
170
+ this.low = res.low;
171
+ this.high = res.high;
172
+ this.unsigned = res.unsigned;
173
+ }
174
+
175
+ static TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL);
176
+
177
+ /** Maximum unsigned value. */
178
+ static MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true);
179
+ /** Signed zero */
180
+ static ZERO = Long.fromInt(0);
181
+ /** Unsigned zero. */
182
+ static UZERO = Long.fromInt(0, true);
183
+ /** Signed one. */
184
+ static ONE = Long.fromInt(1);
185
+ /** Unsigned one. */
186
+ static UONE = Long.fromInt(1, true);
187
+ /** Signed negative one. */
188
+ static NEG_ONE = Long.fromInt(-1);
189
+ /** Maximum signed value. */
190
+ static MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false);
191
+ /** Minimum signed value. */
192
+ static MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false);
193
+
194
+ /**
195
+ * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits.
196
+ * Each is assumed to use 32 bits.
197
+ * @param lowBits - The low 32 bits
198
+ * @param highBits - The high 32 bits
199
+ * @param unsigned - Whether unsigned or not, defaults to signed
200
+ * @returns The corresponding Long value
201
+ */
202
+ static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long {
203
+ return new Long(lowBits, highBits, unsigned);
204
+ }
205
+
206
+ /**
207
+ * Returns a Long representing the given 32 bit integer value.
208
+ * @param value - The 32 bit integer in question
209
+ * @param unsigned - Whether unsigned or not, defaults to signed
210
+ * @returns The corresponding Long value
211
+ */
212
+ static fromInt(value: number, unsigned?: boolean): Long {
213
+ let obj, cachedObj, cache;
214
+ if (unsigned) {
215
+ value >>>= 0;
216
+ if ((cache = 0 <= value && value < 256)) {
217
+ cachedObj = UINT_CACHE[value];
218
+ if (cachedObj) return cachedObj;
219
+ }
220
+ obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true);
221
+ if (cache) UINT_CACHE[value] = obj;
222
+ return obj;
223
+ } else {
224
+ value |= 0;
225
+ if ((cache = -128 <= value && value < 128)) {
226
+ cachedObj = INT_CACHE[value];
227
+ if (cachedObj) return cachedObj;
228
+ }
229
+ obj = Long.fromBits(value, value < 0 ? -1 : 0, false);
230
+ if (cache) INT_CACHE[value] = obj;
231
+ return obj;
232
+ }
233
+ }
234
+
235
+ /**
236
+ * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
237
+ * @param value - The number in question
238
+ * @param unsigned - Whether unsigned or not, defaults to signed
239
+ * @returns The corresponding Long value
240
+ */
241
+ static fromNumber(value: number, unsigned?: boolean): Long {
242
+ if (isNaN(value)) return unsigned ? Long.UZERO : Long.ZERO;
243
+ if (unsigned) {
244
+ if (value < 0) return Long.UZERO;
245
+ if (value >= TWO_PWR_64_DBL) return Long.MAX_UNSIGNED_VALUE;
246
+ } else {
247
+ if (value <= -TWO_PWR_63_DBL) return Long.MIN_VALUE;
248
+ if (value + 1 >= TWO_PWR_63_DBL) return Long.MAX_VALUE;
249
+ }
250
+ if (value < 0) return Long.fromNumber(-value, unsigned).neg();
251
+ return Long.fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
252
+ }
253
+
254
+ /**
255
+ * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
256
+ * @param value - The number in question
257
+ * @param unsigned - Whether unsigned or not, defaults to signed
258
+ * @returns The corresponding Long value
259
+ */
260
+ static fromBigInt(value: bigint, unsigned?: boolean): Long {
261
+ const FROM_BIGINT_BIT_MASK = 0xffffffffn;
262
+ const FROM_BIGINT_BIT_SHIFT = 32n;
263
+ return new Long(
264
+ Number(value & FROM_BIGINT_BIT_MASK),
265
+ Number((value >> FROM_BIGINT_BIT_SHIFT) & FROM_BIGINT_BIT_MASK),
266
+ unsigned
267
+ );
268
+ }
269
+
270
+ /**
271
+ * @internal
272
+ * Returns a Long representation of the given string, written using the specified radix.
273
+ * Throws an error if `throwsError` is set to true and any of the following conditions are true:
274
+ * - the string contains invalid characters for the given radix
275
+ * - the string contains whitespace
276
+ * @param str - The textual representation of the Long
277
+ * @param unsigned - Whether unsigned or not, defaults to signed
278
+ * @param radix - The radix in which the text is written (2-36), defaults to 10
279
+ * @returns The corresponding Long value
280
+ */
281
+ private static _fromString(str: string, unsigned: boolean, radix: number): Long {
282
+ if (str.length === 0) throw new BSONError('empty string');
283
+ if (radix < 2 || 36 < radix) throw new BSONError('radix');
284
+
285
+ let p;
286
+ if ((p = str.indexOf('-')) > 0) throw new BSONError('interior hyphen');
287
+ else if (p === 0) {
288
+ return Long._fromString(str.substring(1), unsigned, radix).neg();
289
+ }
290
+
291
+ // Do several (8) digits each time through the loop, so as to
292
+ // minimize the calls to the very expensive emulated div.
293
+ const radixToPower = Long.fromNumber(Math.pow(radix, 8));
294
+
295
+ let result = Long.ZERO;
296
+ for (let i = 0; i < str.length; i += 8) {
297
+ const size = Math.min(8, str.length - i),
298
+ value = parseInt(str.substring(i, i + size), radix);
299
+ if (size < 8) {
300
+ const power = Long.fromNumber(Math.pow(radix, size));
301
+ result = result.mul(power).add(Long.fromNumber(value));
302
+ } else {
303
+ result = result.mul(radixToPower);
304
+ result = result.add(Long.fromNumber(value));
305
+ }
306
+ }
307
+ result.unsigned = unsigned;
308
+ return result;
309
+ }
310
+
311
+ /**
312
+ * Returns a signed Long representation of the given string, written using radix 10.
313
+ * Will throw an error if the given text is not exactly representable as a Long.
314
+ * Throws an error if any of the following conditions are true:
315
+ * - the string contains invalid characters for the radix 10
316
+ * - the string contains whitespace
317
+ * - the value the string represents is too large or too small to be a Long
318
+ * Unlike Long.fromString, this method does not coerce '+/-Infinity' and 'NaN' to Long.Zero
319
+ * @param str - The textual representation of the Long
320
+ * @returns The corresponding Long value
321
+ */
322
+ static fromStringStrict(str: string): Long;
323
+ /**
324
+ * Returns a Long representation of the given string, written using the radix 10.
325
+ * Will throw an error if the given parameters are not exactly representable as a Long.
326
+ * Throws an error if any of the following conditions are true:
327
+ * - the string contains invalid characters for the given radix
328
+ * - the string contains whitespace
329
+ * - the value the string represents is too large or too small to be a Long
330
+ * Unlike Long.fromString, this method does not coerce '+/-Infinity' and 'NaN' to Long.Zero
331
+ * @param str - The textual representation of the Long
332
+ * @param unsigned - Whether unsigned or not, defaults to signed
333
+ * @returns The corresponding Long value
334
+ */
335
+ static fromStringStrict(str: string, unsigned?: boolean): Long;
336
+ /**
337
+ * Returns a signed Long representation of the given string, written using the specified radix.
338
+ * Will throw an error if the given parameters are not exactly representable as a Long.
339
+ * Throws an error if any of the following conditions are true:
340
+ * - the string contains invalid characters for the given radix
341
+ * - the string contains whitespace
342
+ * - the value the string represents is too large or too small to be a Long
343
+ * Unlike Long.fromString, this method does not coerce '+/-Infinity' and 'NaN' to Long.Zero
344
+ * @param str - The textual representation of the Long
345
+ * @param radix - The radix in which the text is written (2-36), defaults to 10
346
+ * @returns The corresponding Long value
347
+ */
348
+ static fromStringStrict(str: string, radix?: boolean): Long;
349
+ /**
350
+ * Returns a Long representation of the given string, written using the specified radix.
351
+ * Will throw an error if the given parameters are not exactly representable as a Long.
352
+ * Throws an error if any of the following conditions are true:
353
+ * - the string contains invalid characters for the given radix
354
+ * - the string contains whitespace
355
+ * - the value the string represents is too large or too small to be a Long
356
+ * Unlike Long.fromString, this method does not coerce '+/-Infinity' and 'NaN' to Long.Zero
357
+ * @param str - The textual representation of the Long
358
+ * @param unsigned - Whether unsigned or not, defaults to signed
359
+ * @param radix - The radix in which the text is written (2-36), defaults to 10
360
+ * @returns The corresponding Long value
361
+ */
362
+ static fromStringStrict(str: string, unsigned?: boolean, radix?: number): Long;
363
+ static fromStringStrict(str: string, unsignedOrRadix?: boolean | number, radix?: number): Long {
364
+ let unsigned = false;
365
+ if (typeof unsignedOrRadix === 'number') {
366
+ // For goog.math.long compatibility
367
+ ((radix = unsignedOrRadix), (unsignedOrRadix = false));
368
+ } else {
369
+ unsigned = !!unsignedOrRadix;
370
+ }
371
+ radix ??= 10;
372
+
373
+ if (str.trim() !== str) {
374
+ throw new BSONError(`Input: '${str}' contains leading and/or trailing whitespace`);
375
+ }
376
+ if (!StringUtils.validateStringCharacters(str, radix)) {
377
+ throw new BSONError(`Input: '${str}' contains invalid characters for radix: ${radix}`);
378
+ }
379
+
380
+ // remove leading zeros (for later string comparison and to make math faster)
381
+ const cleanedStr = StringUtils.removeLeadingZerosAndExplicitPlus(str);
382
+
383
+ // check roundtrip result
384
+ const result = Long._fromString(cleanedStr, unsigned, radix);
385
+ if (result.toString(radix).toLowerCase() !== cleanedStr.toLowerCase()) {
386
+ throw new BSONError(
387
+ `Input: ${str} is not representable as ${result.unsigned ? 'an unsigned' : 'a signed'} 64-bit Long ${radix != null ? `with radix: ${radix}` : ''}`
388
+ );
389
+ }
390
+ return result;
391
+ }
392
+
393
+ /**
394
+ * Returns a signed Long representation of the given string, written using radix 10.
395
+ *
396
+ * If the input string is empty, this function will throw a BSONError.
397
+ *
398
+ * If input string does not have valid signed 64-bit Long representation, this method will return a coerced value:
399
+ * - inputs that overflow 64-bit signed long will be coerced to Long.MAX_VALUE and Long.MIN_VALUE respectively
400
+ * - 'NaN' or '+/-Infinity' are coerced to Long.ZERO
401
+ * - other invalid characters sequences have variable behavior
402
+ *
403
+ * @param str - The textual representation of the Long
404
+ * @returns The corresponding Long value
405
+ */
406
+ static fromString(str: string): Long;
407
+ /**
408
+ * Returns a signed Long representation of the given string, written using the provided radix.
409
+ *
410
+ * If the input string is empty or a provided radix is not within (2-36), this function will throw a BSONError.
411
+ *
412
+ * If input parameters do not have valid signed 64-bit Long representation, this method will return a coerced value:
413
+ * - inputs that overflow 64-bit signed long will be coerced to Long.MAX_VALUE and Long.MIN_VALUE respectively
414
+ * - if the radix is less than 24, 'NaN' is coerced to Long.ZERO
415
+ * - if the radix is less than 35, '+/-Infinity' inputs are coerced to Long.ZERO
416
+ * - other invalid characters sequences have variable behavior
417
+ * @param str - The textual representation of the Long
418
+ * @param radix - The radix in which the text is written (2-36), defaults to 10
419
+ * @returns The corresponding Long value
420
+ */
421
+ static fromString(str: string, radix?: number): Long;
422
+ /**
423
+ * Returns a Long representation of the given string, written using radix 10.
424
+ *
425
+ * If the input string is empty, this function will throw a BSONError.
426
+ *
427
+ * If input parameters do not have a valid 64-bit Long representation, this method will return a coerced value:
428
+ * - inputs that overflow 64-bit long will be coerced to max or min (if signed) values
429
+ * - if the radix is less than 24, 'NaN' is coerced to Long.ZERO
430
+ * - if the radix is less than 35, '+/-Infinity' inputs are coerced to Long.ZERO
431
+ * - other invalid characters sequences have variable behavior
432
+ * @param str - The textual representation of the Long
433
+ * @param unsigned - Whether unsigned or not, defaults to signed
434
+ * @returns The corresponding Long value
435
+ */
436
+ static fromString(str: string, unsigned?: boolean): Long;
437
+ /**
438
+ * Returns a Long representation of the given string, written using the specified radix.
439
+ *
440
+ * If the input string is empty or a provided radix is not within (2-36), this function will throw a BSONError.
441
+ *
442
+ * If input parameters do not have a valid 64-bit Long representation, this method will return a coerced value:
443
+ * - inputs that overflow 64-bit long will be coerced to max or min (if signed) values
444
+ * - if the radix is less than 24, 'NaN' is coerced to Long.ZERO
445
+ * - if the radix is less than 35, '+/-Infinity' inputs are coerced to Long.ZERO
446
+ * - other invalid characters sequences have variable behavior
447
+ * @param str - The textual representation of the Long
448
+ * @param unsigned - Whether unsigned or not, defaults to signed
449
+ * @param radix - The radix in which the text is written (2-36), defaults to 10
450
+ * @returns The corresponding Long value
451
+ */
452
+ static fromString(str: string, unsigned?: boolean, radix?: number): Long;
453
+ static fromString(str: string, unsignedOrRadix?: boolean | number, radix?: number): Long {
454
+ let unsigned = false;
455
+ if (typeof unsignedOrRadix === 'number') {
456
+ // For goog.math.long compatibility
457
+ ((radix = unsignedOrRadix), (unsignedOrRadix = false));
458
+ } else {
459
+ unsigned = !!unsignedOrRadix;
460
+ }
461
+ radix ??= 10;
462
+ if (str === 'NaN' && radix < 24) {
463
+ // radix does not support n, so coerce to zero
464
+ return Long.ZERO;
465
+ } else if ((str === 'Infinity' || str === '+Infinity' || str === '-Infinity') && radix < 35) {
466
+ // radix does not support y, so coerce to zero
467
+ return Long.ZERO;
468
+ }
469
+ return Long._fromString(str, unsigned, radix);
470
+ }
471
+
472
+ /**
473
+ * Creates a Long from its byte representation.
474
+ * @param bytes - Byte representation
475
+ * @param unsigned - Whether unsigned or not, defaults to signed
476
+ * @param le - Whether little or big endian, defaults to big endian
477
+ * @returns The corresponding Long value
478
+ */
479
+ static fromBytes(bytes: number[], unsigned?: boolean, le?: boolean): Long {
480
+ return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
481
+ }
482
+
483
+ /**
484
+ * Creates a Long from its little endian byte representation.
485
+ * @param bytes - Little endian byte representation
486
+ * @param unsigned - Whether unsigned or not, defaults to signed
487
+ * @returns The corresponding Long value
488
+ */
489
+ static fromBytesLE(bytes: number[], unsigned?: boolean): Long {
490
+ return new Long(
491
+ bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24),
492
+ bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24),
493
+ unsigned
494
+ );
495
+ }
496
+
497
+ /**
498
+ * Creates a Long from its big endian byte representation.
499
+ * @param bytes - Big endian byte representation
500
+ * @param unsigned - Whether unsigned or not, defaults to signed
501
+ * @returns The corresponding Long value
502
+ */
503
+ static fromBytesBE(bytes: number[], unsigned?: boolean): Long {
504
+ return new Long(
505
+ (bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7],
506
+ (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3],
507
+ unsigned
508
+ );
509
+ }
510
+
511
+ /**
512
+ * Tests if the specified object is a Long.
513
+ */
514
+ static isLong(value: unknown): value is Long {
515
+ return (
516
+ value != null &&
517
+ typeof value === 'object' &&
518
+ '__isLong__' in value &&
519
+ value.__isLong__ === true
520
+ );
521
+ }
522
+
523
+ /**
524
+ * Converts the specified value to a Long.
525
+ * @param unsigned - Whether unsigned or not, defaults to signed
526
+ */
527
+ static fromValue(
528
+ val: number | string | { low: number; high: number; unsigned?: boolean },
529
+ unsigned?: boolean
530
+ ): Long {
531
+ if (typeof val === 'number') return Long.fromNumber(val, unsigned);
532
+ if (typeof val === 'string') return Long.fromString(val, unsigned);
533
+ // Throws for non-objects, converts non-instanceof Long:
534
+ return Long.fromBits(
535
+ val.low,
536
+ val.high,
537
+ typeof unsigned === 'boolean' ? unsigned : val.unsigned
538
+ );
539
+ }
540
+
541
+ /** Returns the sum of this and the specified Long. */
542
+ add(addend: string | number | Long | Timestamp): Long {
543
+ if (!Long.isLong(addend)) addend = Long.fromValue(addend);
544
+
545
+ // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
546
+
547
+ const a48 = this.high >>> 16;
548
+ const a32 = this.high & 0xffff;
549
+ const a16 = this.low >>> 16;
550
+ const a00 = this.low & 0xffff;
551
+
552
+ const b48 = addend.high >>> 16;
553
+ const b32 = addend.high & 0xffff;
554
+ const b16 = addend.low >>> 16;
555
+ const b00 = addend.low & 0xffff;
556
+
557
+ let c48 = 0,
558
+ c32 = 0,
559
+ c16 = 0,
560
+ c00 = 0;
561
+ c00 += a00 + b00;
562
+ c16 += c00 >>> 16;
563
+ c00 &= 0xffff;
564
+ c16 += a16 + b16;
565
+ c32 += c16 >>> 16;
566
+ c16 &= 0xffff;
567
+ c32 += a32 + b32;
568
+ c48 += c32 >>> 16;
569
+ c32 &= 0xffff;
570
+ c48 += a48 + b48;
571
+ c48 &= 0xffff;
572
+ return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
573
+ }
574
+
575
+ /**
576
+ * Returns the sum of this and the specified Long.
577
+ * @returns Sum
578
+ */
579
+ and(other: string | number | Long | Timestamp): Long {
580
+ if (!Long.isLong(other)) other = Long.fromValue(other);
581
+ return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned);
582
+ }
583
+
584
+ /**
585
+ * Compares this Long's value with the specified's.
586
+ * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater
587
+ */
588
+ compare(other: string | number | Long | Timestamp): 0 | 1 | -1 {
589
+ if (!Long.isLong(other)) other = Long.fromValue(other);
590
+ if (this.eq(other)) return 0;
591
+ const thisNeg = this.isNegative(),
592
+ otherNeg = other.isNegative();
593
+ if (thisNeg && !otherNeg) return -1;
594
+ if (!thisNeg && otherNeg) return 1;
595
+ // At this point the sign bits are the same
596
+ if (!this.unsigned) return this.sub(other).isNegative() ? -1 : 1;
597
+ // Both are positive if at least one is unsigned
598
+ return other.high >>> 0 > this.high >>> 0 ||
599
+ (other.high === this.high && other.low >>> 0 > this.low >>> 0)
600
+ ? -1
601
+ : 1;
602
+ }
603
+
604
+ /** This is an alias of {@link Long.compare} */
605
+ comp(other: string | number | Long | Timestamp): 0 | 1 | -1 {
606
+ return this.compare(other);
607
+ }
608
+
609
+ /**
610
+ * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned.
611
+ * @returns Quotient
612
+ */
613
+ divide(divisor: string | number | Long | Timestamp): Long {
614
+ if (!Long.isLong(divisor)) divisor = Long.fromValue(divisor);
615
+ if (divisor.isZero()) throw new BSONError('division by zero');
616
+
617
+ // use wasm support if present
618
+ if (wasm) {
619
+ // guard against signed division overflow: the largest
620
+ // negative number / -1 would be 1 larger than the largest
621
+ // positive number, due to two's complement.
622
+ if (
623
+ !this.unsigned &&
624
+ this.high === -0x80000000 &&
625
+ divisor.low === -1 &&
626
+ divisor.high === -1
627
+ ) {
628
+ // be consistent with non-wasm code path
629
+ return this;
630
+ }
631
+ const low = (this.unsigned ? wasm.div_u : wasm.div_s)(
632
+ this.low,
633
+ this.high,
634
+ divisor.low,
635
+ divisor.high
636
+ );
637
+ return Long.fromBits(low, wasm.get_high(), this.unsigned);
638
+ }
639
+
640
+ if (this.isZero()) return this.unsigned ? Long.UZERO : Long.ZERO;
641
+ let approx, rem, res;
642
+ if (!this.unsigned) {
643
+ // This section is only relevant for signed longs and is derived from the
644
+ // closure library as a whole.
645
+ if (this.eq(Long.MIN_VALUE)) {
646
+ if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) return Long.MIN_VALUE;
647
+ // recall that -MIN_VALUE == MIN_VALUE
648
+ else if (divisor.eq(Long.MIN_VALUE)) return Long.ONE;
649
+ else {
650
+ // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
651
+ const halfThis = this.shr(1);
652
+ approx = halfThis.div(divisor).shl(1);
653
+ if (approx.eq(Long.ZERO)) {
654
+ return divisor.isNegative() ? Long.ONE : Long.NEG_ONE;
655
+ } else {
656
+ rem = this.sub(divisor.mul(approx));
657
+ res = approx.add(rem.div(divisor));
658
+ return res;
659
+ }
660
+ }
661
+ } else if (divisor.eq(Long.MIN_VALUE)) return this.unsigned ? Long.UZERO : Long.ZERO;
662
+ if (this.isNegative()) {
663
+ if (divisor.isNegative()) return this.neg().div(divisor.neg());
664
+ return this.neg().div(divisor).neg();
665
+ } else if (divisor.isNegative()) return this.div(divisor.neg()).neg();
666
+ res = Long.ZERO;
667
+ } else {
668
+ // The algorithm below has not been made for unsigned longs. It's therefore
669
+ // required to take special care of the MSB prior to running it.
670
+ if (!divisor.unsigned) divisor = divisor.toUnsigned();
671
+ if (divisor.gt(this)) return Long.UZERO;
672
+ if (divisor.gt(this.shru(1)))
673
+ // 15 >>> 1 = 7 ; with divisor = 8 ; true
674
+ return Long.UONE;
675
+ res = Long.UZERO;
676
+ }
677
+
678
+ // Repeat the following until the remainder is less than other: find a
679
+ // floating-point that approximates remainder / other *from below*, add this
680
+ // into the result, and subtract it from the remainder. It is critical that
681
+ // the approximate value is less than or equal to the real value so that the
682
+ // remainder never becomes negative.
683
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
684
+ rem = this;
685
+ while (rem.gte(divisor)) {
686
+ // Approximate the result of division. This may be a little greater or
687
+ // smaller than the actual value.
688
+ approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
689
+
690
+ // We will tweak the approximate result by changing it in the 48-th digit or
691
+ // the smallest non-fractional digit, whichever is larger.
692
+ const log2 = Math.ceil(Math.log(approx) / Math.LN2);
693
+ const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);
694
+ // Decrease the approximation until it is smaller than the remainder. Note
695
+ // that if it is too large, the product overflows and is negative.
696
+ let approxRes = Long.fromNumber(approx);
697
+ let approxRem = approxRes.mul(divisor);
698
+ while (approxRem.isNegative() || approxRem.gt(rem)) {
699
+ approx -= delta;
700
+ approxRes = Long.fromNumber(approx, this.unsigned);
701
+ approxRem = approxRes.mul(divisor);
702
+ }
703
+
704
+ // We know the answer can't be zero... and actually, zero would cause
705
+ // infinite recursion since we would make no progress.
706
+ if (approxRes.isZero()) approxRes = Long.ONE;
707
+
708
+ res = res.add(approxRes);
709
+ rem = rem.sub(approxRem);
710
+ }
711
+ return res;
712
+ }
713
+
714
+ /**This is an alias of {@link Long.divide} */
715
+ div(divisor: string | number | Long | Timestamp): Long {
716
+ return this.divide(divisor);
717
+ }
718
+
719
+ /**
720
+ * Tests if this Long's value equals the specified's.
721
+ * @param other - Other value
722
+ */
723
+ equals(other: string | number | Long | Timestamp): boolean {
724
+ if (!Long.isLong(other)) other = Long.fromValue(other);
725
+ if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
726
+ return false;
727
+ return this.high === other.high && this.low === other.low;
728
+ }
729
+
730
+ /** This is an alias of {@link Long.equals} */
731
+ eq(other: string | number | Long | Timestamp): boolean {
732
+ return this.equals(other);
733
+ }
734
+
735
+ /** Gets the high 32 bits as a signed integer. */
736
+ getHighBits(): number {
737
+ return this.high;
738
+ }
739
+
740
+ /** Gets the high 32 bits as an unsigned integer. */
741
+ getHighBitsUnsigned(): number {
742
+ return this.high >>> 0;
743
+ }
744
+
745
+ /** Gets the low 32 bits as a signed integer. */
746
+ getLowBits(): number {
747
+ return this.low;
748
+ }
749
+
750
+ /** Gets the low 32 bits as an unsigned integer. */
751
+ getLowBitsUnsigned(): number {
752
+ return this.low >>> 0;
753
+ }
754
+
755
+ /** Gets the number of bits needed to represent the absolute value of this Long. */
756
+ getNumBitsAbs(): number {
757
+ if (this.isNegative()) {
758
+ // Unsigned Longs are never negative
759
+ return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
760
+ }
761
+ const val = this.high !== 0 ? this.high : this.low;
762
+ let bit: number;
763
+ for (bit = 31; bit > 0; bit--) if ((val & (1 << bit)) !== 0) break;
764
+ return this.high !== 0 ? bit + 33 : bit + 1;
765
+ }
766
+
767
+ /** Tests if this Long's value is greater than the specified's. */
768
+ greaterThan(other: string | number | Long | Timestamp): boolean {
769
+ return this.comp(other) > 0;
770
+ }
771
+
772
+ /** This is an alias of {@link Long.greaterThan} */
773
+ gt(other: string | number | Long | Timestamp): boolean {
774
+ return this.greaterThan(other);
775
+ }
776
+
777
+ /** Tests if this Long's value is greater than or equal the specified's. */
778
+ greaterThanOrEqual(other: string | number | Long | Timestamp): boolean {
779
+ return this.comp(other) >= 0;
780
+ }
781
+
782
+ /** This is an alias of {@link Long.greaterThanOrEqual} */
783
+ gte(other: string | number | Long | Timestamp): boolean {
784
+ return this.greaterThanOrEqual(other);
785
+ }
786
+ /** This is an alias of {@link Long.greaterThanOrEqual} */
787
+ ge(other: string | number | Long | Timestamp): boolean {
788
+ return this.greaterThanOrEqual(other);
789
+ }
790
+
791
+ /** Tests if this Long's value is even. */
792
+ isEven(): boolean {
793
+ return (this.low & 1) === 0;
794
+ }
795
+
796
+ /** Tests if this Long's value is negative. */
797
+ isNegative(): boolean {
798
+ return !this.unsigned && this.high < 0;
799
+ }
800
+
801
+ /** Tests if this Long's value is odd. */
802
+ isOdd(): boolean {
803
+ return (this.low & 1) === 1;
804
+ }
805
+
806
+ /** Tests if this Long's value is positive. */
807
+ isPositive(): boolean {
808
+ return this.unsigned || this.high >= 0;
809
+ }
810
+
811
+ /** Tests if this Long's value equals zero. */
812
+ isZero(): boolean {
813
+ return this.high === 0 && this.low === 0;
814
+ }
815
+
816
+ /** Tests if this Long's value is less than the specified's. */
817
+ lessThan(other: string | number | Long | Timestamp): boolean {
818
+ return this.comp(other) < 0;
819
+ }
820
+
821
+ /** This is an alias of {@link Long#lessThan}. */
822
+ lt(other: string | number | Long | Timestamp): boolean {
823
+ return this.lessThan(other);
824
+ }
825
+
826
+ /** Tests if this Long's value is less than or equal the specified's. */
827
+ lessThanOrEqual(other: string | number | Long | Timestamp): boolean {
828
+ return this.comp(other) <= 0;
829
+ }
830
+
831
+ /** This is an alias of {@link Long.lessThanOrEqual} */
832
+ lte(other: string | number | Long | Timestamp): boolean {
833
+ return this.lessThanOrEqual(other);
834
+ }
835
+
836
+ /** Returns this Long modulo the specified. */
837
+ modulo(divisor: string | number | Long | Timestamp): Long {
838
+ if (!Long.isLong(divisor)) divisor = Long.fromValue(divisor);
839
+
840
+ // use wasm support if present
841
+ if (wasm) {
842
+ const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(
843
+ this.low,
844
+ this.high,
845
+ divisor.low,
846
+ divisor.high
847
+ );
848
+ return Long.fromBits(low, wasm.get_high(), this.unsigned);
849
+ }
850
+
851
+ return this.sub(this.div(divisor).mul(divisor));
852
+ }
853
+
854
+ /** This is an alias of {@link Long.modulo} */
855
+ mod(divisor: string | number | Long | Timestamp): Long {
856
+ return this.modulo(divisor);
857
+ }
858
+ /** This is an alias of {@link Long.modulo} */
859
+ rem(divisor: string | number | Long | Timestamp): Long {
860
+ return this.modulo(divisor);
861
+ }
862
+
863
+ /**
864
+ * Returns the product of this and the specified Long.
865
+ * @param multiplier - Multiplier
866
+ * @returns Product
867
+ */
868
+ multiply(multiplier: string | number | Long | Timestamp): Long {
869
+ if (this.isZero()) return Long.ZERO;
870
+ if (!Long.isLong(multiplier)) multiplier = Long.fromValue(multiplier);
871
+
872
+ // use wasm support if present
873
+ if (wasm) {
874
+ const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
875
+ return Long.fromBits(low, wasm.get_high(), this.unsigned);
876
+ }
877
+
878
+ if (multiplier.isZero()) return Long.ZERO;
879
+ if (this.eq(Long.MIN_VALUE)) return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO;
880
+ if (multiplier.eq(Long.MIN_VALUE)) return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;
881
+
882
+ if (this.isNegative()) {
883
+ if (multiplier.isNegative()) return this.neg().mul(multiplier.neg());
884
+ else return this.neg().mul(multiplier).neg();
885
+ } else if (multiplier.isNegative()) return this.mul(multiplier.neg()).neg();
886
+
887
+ // If both longs are small, use float multiplication
888
+ if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24))
889
+ return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
890
+
891
+ // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
892
+ // We can skip products that would overflow.
893
+
894
+ const a48 = this.high >>> 16;
895
+ const a32 = this.high & 0xffff;
896
+ const a16 = this.low >>> 16;
897
+ const a00 = this.low & 0xffff;
898
+
899
+ const b48 = multiplier.high >>> 16;
900
+ const b32 = multiplier.high & 0xffff;
901
+ const b16 = multiplier.low >>> 16;
902
+ const b00 = multiplier.low & 0xffff;
903
+
904
+ let c48 = 0,
905
+ c32 = 0,
906
+ c16 = 0,
907
+ c00 = 0;
908
+ c00 += a00 * b00;
909
+ c16 += c00 >>> 16;
910
+ c00 &= 0xffff;
911
+ c16 += a16 * b00;
912
+ c32 += c16 >>> 16;
913
+ c16 &= 0xffff;
914
+ c16 += a00 * b16;
915
+ c32 += c16 >>> 16;
916
+ c16 &= 0xffff;
917
+ c32 += a32 * b00;
918
+ c48 += c32 >>> 16;
919
+ c32 &= 0xffff;
920
+ c32 += a16 * b16;
921
+ c48 += c32 >>> 16;
922
+ c32 &= 0xffff;
923
+ c32 += a00 * b32;
924
+ c48 += c32 >>> 16;
925
+ c32 &= 0xffff;
926
+ c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
927
+ c48 &= 0xffff;
928
+ return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
929
+ }
930
+
931
+ /** This is an alias of {@link Long.multiply} */
932
+ mul(multiplier: string | number | Long | Timestamp): Long {
933
+ return this.multiply(multiplier);
934
+ }
935
+
936
+ /** Returns the Negation of this Long's value. */
937
+ negate(): Long {
938
+ if (!this.unsigned && this.eq(Long.MIN_VALUE)) return Long.MIN_VALUE;
939
+ return this.not().add(Long.ONE);
940
+ }
941
+
942
+ /** This is an alias of {@link Long.negate} */
943
+ neg(): Long {
944
+ return this.negate();
945
+ }
946
+
947
+ /** Returns the bitwise NOT of this Long. */
948
+ not(): Long {
949
+ return Long.fromBits(~this.low, ~this.high, this.unsigned);
950
+ }
951
+
952
+ /** Tests if this Long's value differs from the specified's. */
953
+ notEquals(other: string | number | Long | Timestamp): boolean {
954
+ return !this.equals(other);
955
+ }
956
+
957
+ /** This is an alias of {@link Long.notEquals} */
958
+ neq(other: string | number | Long | Timestamp): boolean {
959
+ return this.notEquals(other);
960
+ }
961
+ /** This is an alias of {@link Long.notEquals} */
962
+ ne(other: string | number | Long | Timestamp): boolean {
963
+ return this.notEquals(other);
964
+ }
965
+
966
+ /**
967
+ * Returns the bitwise OR of this Long and the specified.
968
+ */
969
+ or(other: number | string | Long): Long {
970
+ if (!Long.isLong(other)) other = Long.fromValue(other);
971
+ return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned);
972
+ }
973
+
974
+ /**
975
+ * Returns this Long with bits shifted to the left by the given amount.
976
+ * @param numBits - Number of bits
977
+ * @returns Shifted Long
978
+ */
979
+ shiftLeft(numBits: number | Long): Long {
980
+ if (Long.isLong(numBits)) numBits = numBits.toInt();
981
+ if ((numBits &= 63) === 0) return this;
982
+ else if (numBits < 32)
983
+ return Long.fromBits(
984
+ this.low << numBits,
985
+ (this.high << numBits) | (this.low >>> (32 - numBits)),
986
+ this.unsigned
987
+ );
988
+ else return Long.fromBits(0, this.low << (numBits - 32), this.unsigned);
989
+ }
990
+
991
+ /** This is an alias of {@link Long.shiftLeft} */
992
+ shl(numBits: number | Long): Long {
993
+ return this.shiftLeft(numBits);
994
+ }
995
+
996
+ /**
997
+ * Returns this Long with bits arithmetically shifted to the right by the given amount.
998
+ * @param numBits - Number of bits
999
+ * @returns Shifted Long
1000
+ */
1001
+ shiftRight(numBits: number | Long): Long {
1002
+ if (Long.isLong(numBits)) numBits = numBits.toInt();
1003
+ if ((numBits &= 63) === 0) return this;
1004
+ else if (numBits < 32)
1005
+ return Long.fromBits(
1006
+ (this.low >>> numBits) | (this.high << (32 - numBits)),
1007
+ this.high >> numBits,
1008
+ this.unsigned
1009
+ );
1010
+ else return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
1011
+ }
1012
+
1013
+ /** This is an alias of {@link Long.shiftRight} */
1014
+ shr(numBits: number | Long): Long {
1015
+ return this.shiftRight(numBits);
1016
+ }
1017
+
1018
+ /**
1019
+ * Returns this Long with bits logically shifted to the right by the given amount.
1020
+ * @param numBits - Number of bits
1021
+ * @returns Shifted Long
1022
+ */
1023
+ shiftRightUnsigned(numBits: Long | number): Long {
1024
+ if (Long.isLong(numBits)) numBits = numBits.toInt();
1025
+ numBits &= 63;
1026
+ if (numBits === 0) return this;
1027
+ else {
1028
+ const high = this.high;
1029
+ if (numBits < 32) {
1030
+ const low = this.low;
1031
+ return Long.fromBits(
1032
+ (low >>> numBits) | (high << (32 - numBits)),
1033
+ high >>> numBits,
1034
+ this.unsigned
1035
+ );
1036
+ } else if (numBits === 32) return Long.fromBits(high, 0, this.unsigned);
1037
+ else return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned);
1038
+ }
1039
+ }
1040
+
1041
+ /** This is an alias of {@link Long.shiftRightUnsigned} */
1042
+ shr_u(numBits: number | Long): Long {
1043
+ return this.shiftRightUnsigned(numBits);
1044
+ }
1045
+ /** This is an alias of {@link Long.shiftRightUnsigned} */
1046
+ shru(numBits: number | Long): Long {
1047
+ return this.shiftRightUnsigned(numBits);
1048
+ }
1049
+
1050
+ /**
1051
+ * Returns the difference of this and the specified Long.
1052
+ * @param subtrahend - Subtrahend
1053
+ * @returns Difference
1054
+ */
1055
+ subtract(subtrahend: string | number | Long | Timestamp): Long {
1056
+ if (!Long.isLong(subtrahend)) subtrahend = Long.fromValue(subtrahend);
1057
+ return this.add(subtrahend.neg());
1058
+ }
1059
+
1060
+ /** This is an alias of {@link Long.subtract} */
1061
+ sub(subtrahend: string | number | Long | Timestamp): Long {
1062
+ return this.subtract(subtrahend);
1063
+ }
1064
+
1065
+ /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */
1066
+ toInt(): number {
1067
+ return this.unsigned ? this.low >>> 0 : this.low;
1068
+ }
1069
+
1070
+ /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */
1071
+ toNumber(): number {
1072
+ if (this.unsigned) return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
1073
+ return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
1074
+ }
1075
+
1076
+ /** Converts the Long to a BigInt (arbitrary precision). */
1077
+ toBigInt(): bigint {
1078
+ return BigInt(this.toString());
1079
+ }
1080
+
1081
+ /**
1082
+ * Converts this Long to its byte representation.
1083
+ * @param le - Whether little or big endian, defaults to big endian
1084
+ * @returns Byte representation
1085
+ */
1086
+ toBytes(le?: boolean): number[] {
1087
+ return le ? this.toBytesLE() : this.toBytesBE();
1088
+ }
1089
+
1090
+ /**
1091
+ * Converts this Long to its little endian byte representation.
1092
+ * @returns Little endian byte representation
1093
+ */
1094
+ toBytesLE(): number[] {
1095
+ const hi = this.high,
1096
+ lo = this.low;
1097
+ return [
1098
+ lo & 0xff,
1099
+ (lo >>> 8) & 0xff,
1100
+ (lo >>> 16) & 0xff,
1101
+ lo >>> 24,
1102
+ hi & 0xff,
1103
+ (hi >>> 8) & 0xff,
1104
+ (hi >>> 16) & 0xff,
1105
+ hi >>> 24
1106
+ ];
1107
+ }
1108
+
1109
+ /**
1110
+ * Converts this Long to its big endian byte representation.
1111
+ * @returns Big endian byte representation
1112
+ */
1113
+ toBytesBE(): number[] {
1114
+ const hi = this.high,
1115
+ lo = this.low;
1116
+ return [
1117
+ hi >>> 24,
1118
+ (hi >>> 16) & 0xff,
1119
+ (hi >>> 8) & 0xff,
1120
+ hi & 0xff,
1121
+ lo >>> 24,
1122
+ (lo >>> 16) & 0xff,
1123
+ (lo >>> 8) & 0xff,
1124
+ lo & 0xff
1125
+ ];
1126
+ }
1127
+
1128
+ /**
1129
+ * Converts this Long to signed.
1130
+ */
1131
+ toSigned(): Long {
1132
+ if (!this.unsigned) return this;
1133
+ return Long.fromBits(this.low, this.high, false);
1134
+ }
1135
+
1136
+ /**
1137
+ * Converts the Long to a string written in the specified radix.
1138
+ * @param radix - Radix (2-36), defaults to 10
1139
+ * @throws RangeError If `radix` is out of range
1140
+ */
1141
+ toString(radix?: number): string {
1142
+ radix = radix || 10;
1143
+ if (radix < 2 || 36 < radix) throw new BSONError('radix');
1144
+ if (this.isZero()) return '0';
1145
+ if (this.isNegative()) {
1146
+ // Unsigned Longs are never negative
1147
+ if (this.eq(Long.MIN_VALUE)) {
1148
+ // We need to change the Long value before it can be negated, so we remove
1149
+ // the bottom-most digit in this base and then recurse to do the rest.
1150
+ const radixLong = Long.fromNumber(radix),
1151
+ div = this.div(radixLong),
1152
+ rem1 = div.mul(radixLong).sub(this);
1153
+ return div.toString(radix) + rem1.toInt().toString(radix);
1154
+ } else return '-' + this.neg().toString(radix);
1155
+ }
1156
+
1157
+ // Do several (6) digits each time through the loop, so as to
1158
+ // minimize the calls to the very expensive emulated div.
1159
+ const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned);
1160
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
1161
+ let rem: Long = this;
1162
+ let result = '';
1163
+ while (true) {
1164
+ const remDiv = rem.div(radixToPower);
1165
+ const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0;
1166
+ let digits = intval.toString(radix);
1167
+ rem = remDiv;
1168
+ if (rem.isZero()) {
1169
+ return digits + result;
1170
+ } else {
1171
+ while (digits.length < 6) digits = '0' + digits;
1172
+ result = '' + digits + result;
1173
+ }
1174
+ }
1175
+ }
1176
+
1177
+ /** Converts this Long to unsigned. */
1178
+ toUnsigned(): Long {
1179
+ if (this.unsigned) return this;
1180
+ return Long.fromBits(this.low, this.high, true);
1181
+ }
1182
+
1183
+ /** Returns the bitwise XOR of this Long and the given one. */
1184
+ xor(other: Long | number | string): Long {
1185
+ if (!Long.isLong(other)) other = Long.fromValue(other);
1186
+ return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
1187
+ }
1188
+
1189
+ /** This is an alias of {@link Long.isZero} */
1190
+ eqz(): boolean {
1191
+ return this.isZero();
1192
+ }
1193
+
1194
+ /** This is an alias of {@link Long.lessThanOrEqual} */
1195
+ le(other: string | number | Long | Timestamp): boolean {
1196
+ return this.lessThanOrEqual(other);
1197
+ }
1198
+
1199
+ /*
1200
+ ****************************************************************
1201
+ * BSON SPECIFIC ADDITIONS *
1202
+ ****************************************************************
1203
+ */
1204
+ toExtendedJSON(options?: EJSONOptions): number | LongExtended {
1205
+ if (options && options.relaxed) return this.toNumber();
1206
+ return { $numberLong: this.toString() };
1207
+ }
1208
+ static fromExtendedJSON(
1209
+ doc: { $numberLong: string },
1210
+ options?: EJSONOptions
1211
+ ): number | Long | bigint {
1212
+ const { useBigInt64 = false, relaxed = true } = { ...options };
1213
+
1214
+ if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) {
1215
+ throw new BSONError('$numberLong string is too long');
1216
+ }
1217
+
1218
+ if (!DECIMAL_REG_EX.test(doc.$numberLong)) {
1219
+ throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`);
1220
+ }
1221
+
1222
+ if (useBigInt64) {
1223
+ const bigIntResult = BigInt(doc.$numberLong);
1224
+ return BigInt.asIntN(64, bigIntResult);
1225
+ }
1226
+
1227
+ const longResult = Long.fromString(doc.$numberLong);
1228
+ if (relaxed) {
1229
+ return longResult.toNumber();
1230
+ }
1231
+ return longResult;
1232
+ }
1233
+
1234
+ inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
1235
+ inspect ??= defaultInspect;
1236
+ const longVal = inspect(this.toString(), options);
1237
+ const unsignedVal = this.unsigned ? `, ${inspect(this.unsigned, options)}` : '';
1238
+ return `new Long(${longVal}${unsignedVal})`;
1239
+ }
1240
+ }
gateway/node_modules/bson/src/max_key.ts ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { BSONValue } from './bson_value';
2
+
3
+ /** @public */
4
+ export interface MaxKeyExtended {
5
+ $maxKey: 1;
6
+ }
7
+
8
+ /**
9
+ * A class representation of the BSON MaxKey type.
10
+ * @public
11
+ * @category BSONType
12
+ */
13
+ export class MaxKey extends BSONValue {
14
+ get _bsontype(): 'MaxKey' {
15
+ return 'MaxKey';
16
+ }
17
+
18
+ /** @internal */
19
+ toExtendedJSON(): MaxKeyExtended {
20
+ return { $maxKey: 1 };
21
+ }
22
+
23
+ /** @internal */
24
+ static fromExtendedJSON(): MaxKey {
25
+ return new MaxKey();
26
+ }
27
+
28
+ inspect(): string {
29
+ return 'new MaxKey()';
30
+ }
31
+ }
gateway/node_modules/bson/src/min_key.ts ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { BSONValue } from './bson_value';
2
+
3
+ /** @public */
4
+ export interface MinKeyExtended {
5
+ $minKey: 1;
6
+ }
7
+
8
+ /**
9
+ * A class representation of the BSON MinKey type.
10
+ * @public
11
+ * @category BSONType
12
+ */
13
+ export class MinKey extends BSONValue {
14
+ get _bsontype(): 'MinKey' {
15
+ return 'MinKey';
16
+ }
17
+
18
+ /** @internal */
19
+ toExtendedJSON(): MinKeyExtended {
20
+ return { $minKey: 1 };
21
+ }
22
+
23
+ /** @internal */
24
+ static fromExtendedJSON(): MinKey {
25
+ return new MinKey();
26
+ }
27
+
28
+ inspect(): string {
29
+ return 'new MinKey()';
30
+ }
31
+ }
gateway/node_modules/bson/src/objectid.ts ADDED
@@ -0,0 +1,546 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { BSONValue } from './bson_value';
2
+ import { BSONError } from './error';
3
+ import { type InspectFn, defaultInspect } from './parser/utils';
4
+ import { ByteUtils } from './utils/byte_utils';
5
+ import { NumberUtils } from './utils/number_utils';
6
+
7
+ /** ObjectId hexString cache @internal */
8
+ const __idCache = new WeakMap(); // TODO(NODE-6549): convert this to #__id private field when target updated to ES2022
9
+
10
+ /** byte (0-255): its 2-character lowercase hex pair @internal */
11
+ const byteToHex: string[] = [];
12
+ for (let n = 0; n < 256; n++) byteToHex.push(n.toString(16).padStart(2, '0'));
13
+
14
+ /** hex char code: nibble (0-15); indices are the codes of 0-9, a-f, A-F @internal */
15
+ const hexCharCodeToNibble = new Int8Array(103);
16
+ for (let c = 48; c <= 57; c++) hexCharCodeToNibble[c] = c - 48; // '0'-'9'
17
+ for (let c = 65; c <= 70; c++) hexCharCodeToNibble[c] = c - 55; // 'A'-'F'
18
+ for (let c = 97; c <= 102; c++) hexCharCodeToNibble[c] = c - 87; // 'a'-'f'
19
+
20
+ /** @public */
21
+ export interface ObjectIdLike {
22
+ id: string | Uint8Array;
23
+ __id?: string;
24
+ toHexString(): string;
25
+ }
26
+
27
+ /** @public */
28
+ export interface ObjectIdExtended {
29
+ $oid: string;
30
+ }
31
+
32
+ /**
33
+ * A class representation of the BSON ObjectId type.
34
+ * @public
35
+ * @category BSONType
36
+ */
37
+ export class ObjectId extends BSONValue {
38
+ get _bsontype(): 'ObjectId' {
39
+ return 'ObjectId';
40
+ }
41
+
42
+ /** @internal */
43
+ private static index = 0;
44
+
45
+ /** Unique sequence for the current process (initialized on first use)
46
+ * @internal
47
+ */
48
+ private static PROCESS_UNIQUE: Uint8Array | null = null;
49
+
50
+ /** @internal */
51
+ private static resetState = (): void => {
52
+ this.index = Math.floor(Math.random() * 0x1000000);
53
+ // PROCESS_UNIQUE is (re)generated lazily on first use rather than here, so that merely loading
54
+ // BSON never calls secure random at module-evaluation time. Runtimes such as Cloudflare Workers
55
+ // forbid generating random values in the global scope.
56
+ this.PROCESS_UNIQUE = null;
57
+ };
58
+
59
+ static {
60
+ this.resetState();
61
+ // https://nodejs.org/api/v8.html#startup-snapshot-api
62
+ // @ts-expect-error Node.js types not present since this is an optional API
63
+ const { startupSnapshot } = globalThis?.process?.getBuiltinModule?.('v8') ?? {};
64
+ if (startupSnapshot?.isBuildingSnapshot?.()) {
65
+ startupSnapshot?.addDeserializeCallback?.(this.resetState);
66
+ }
67
+ }
68
+
69
+ static cacheHexString: boolean;
70
+
71
+ /**
72
+ * The 12 ObjectId bytes packed as four 24-bit integers (bytes 0-2, 3-5, 6-8, 9-11).
73
+ * The 24-bit width keeps each value inside V8's small-integer (Smi) range so it stays stored
74
+ * inline, which keeps the object small. The fields are enumerable own properties, so two
75
+ * ObjectIds with the same bytes stay equal under structural comparison such as deepStrictEqual.
76
+ * @internal
77
+ */
78
+ private i0!: number;
79
+ /** @internal */
80
+ private i1!: number;
81
+ /** @internal */
82
+ private i2!: number;
83
+ /** @internal */
84
+ private i3!: number;
85
+
86
+ /** Pack 12 bytes into the four integer fields. @internal */
87
+ private setFromBytes(b: Uint8Array, offset = 0): void {
88
+ this.i0 = (b[offset] << 16) | (b[offset + 1] << 8) | b[offset + 2];
89
+ this.i1 = (b[offset + 3] << 16) | (b[offset + 4] << 8) | b[offset + 5];
90
+ this.i2 = (b[offset + 6] << 16) | (b[offset + 7] << 8) | b[offset + 8];
91
+ this.i3 = (b[offset + 9] << 16) | (b[offset + 10] << 8) | b[offset + 11];
92
+ }
93
+
94
+ /**
95
+ * Pack a validated 24-character hex string into the four integer fields. The caller must have
96
+ * already validated the string; every character is assumed to be a hex digit.
97
+ * @internal
98
+ */
99
+ private setFromHex(s: string): void {
100
+ const t = hexCharCodeToNibble;
101
+ this.i0 =
102
+ (t[s.charCodeAt(0)] << 20) |
103
+ (t[s.charCodeAt(1)] << 16) |
104
+ (t[s.charCodeAt(2)] << 12) |
105
+ (t[s.charCodeAt(3)] << 8) |
106
+ (t[s.charCodeAt(4)] << 4) |
107
+ t[s.charCodeAt(5)];
108
+ this.i1 =
109
+ (t[s.charCodeAt(6)] << 20) |
110
+ (t[s.charCodeAt(7)] << 16) |
111
+ (t[s.charCodeAt(8)] << 12) |
112
+ (t[s.charCodeAt(9)] << 8) |
113
+ (t[s.charCodeAt(10)] << 4) |
114
+ t[s.charCodeAt(11)];
115
+ this.i2 =
116
+ (t[s.charCodeAt(12)] << 20) |
117
+ (t[s.charCodeAt(13)] << 16) |
118
+ (t[s.charCodeAt(14)] << 12) |
119
+ (t[s.charCodeAt(15)] << 8) |
120
+ (t[s.charCodeAt(16)] << 4) |
121
+ t[s.charCodeAt(17)];
122
+ this.i3 =
123
+ (t[s.charCodeAt(18)] << 20) |
124
+ (t[s.charCodeAt(19)] << 16) |
125
+ (t[s.charCodeAt(20)] << 12) |
126
+ (t[s.charCodeAt(21)] << 8) |
127
+ (t[s.charCodeAt(22)] << 4) |
128
+ t[s.charCodeAt(23)];
129
+ }
130
+
131
+ /** To generate a new ObjectId, use ObjectId() with no argument. */
132
+ constructor();
133
+ /**
134
+ * Create ObjectId from a 24 character hex string.
135
+ *
136
+ * @param inputId - A 24 character hex string.
137
+ */
138
+ constructor(inputId: string);
139
+ /**
140
+ * Create ObjectId from the BSON ObjectId type.
141
+ *
142
+ * @param inputId - The BSON ObjectId type.
143
+ */
144
+ constructor(inputId: ObjectId);
145
+ /**
146
+ * Create ObjectId from the object type that has the toHexString method.
147
+ *
148
+ * @param inputId - The ObjectIdLike type.
149
+ */
150
+ constructor(inputId: ObjectIdLike);
151
+ /**
152
+ * Create ObjectId from a 12 byte binary Buffer.
153
+ *
154
+ * @param inputId - A 12 byte binary Buffer.
155
+ */
156
+ constructor(inputId: Uint8Array);
157
+ /**
158
+ * Implementation overload.
159
+ *
160
+ * @param inputId - All input types that are used in the constructor implementation.
161
+ */
162
+ constructor(inputId?: string | ObjectId | ObjectIdLike | Uint8Array);
163
+ /**
164
+ * Read 12 bytes from `source` starting at `offset` directly into the packed fields.
165
+ * Used by the deserializer on a hot path.
166
+ * @internal
167
+ */
168
+ constructor(source: Uint8Array, offset: number);
169
+ /**
170
+ * Create a new ObjectId.
171
+ *
172
+ * @param inputId - An input value to create a new ObjectId from.
173
+ */
174
+ constructor(inputId?: string | ObjectId | ObjectIdLike | Uint8Array, offset?: number) {
175
+ super();
176
+ if (typeof offset === 'number') {
177
+ // Fast path used by the deserializer: read the 12 bytes directly from source at offset.
178
+ this.setFromBytes(inputId as Uint8Array, offset);
179
+ return;
180
+ }
181
+ // workingId is set based on type of input and whether valid id exists for the input
182
+ let workingId;
183
+ if (typeof inputId === 'object' && inputId && 'id' in inputId) {
184
+ if (
185
+ ObjectId.is(inputId) &&
186
+ typeof inputId.i0 === 'number' &&
187
+ typeof inputId.i1 === 'number' &&
188
+ typeof inputId.i2 === 'number' &&
189
+ typeof inputId.i3 === 'number'
190
+ ) {
191
+ // Same-build ObjectId: copy the packed fields directly. The general path below would
192
+ // hit the id getter (which allocates) and then re-decode a hex round trip.
193
+ this.i0 = inputId.i0;
194
+ this.i1 = inputId.i1;
195
+ this.i2 = inputId.i2;
196
+ this.i3 = inputId.i3;
197
+ return;
198
+ }
199
+ if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) {
200
+ throw new BSONError('Argument passed in must have an id that is of type string or Buffer');
201
+ }
202
+ if ('toHexString' in inputId && typeof inputId.toHexString === 'function') {
203
+ workingId = ByteUtils.fromHex(inputId.toHexString());
204
+ } else {
205
+ workingId = inputId.id;
206
+ }
207
+ } else {
208
+ workingId = inputId;
209
+ }
210
+
211
+ // The following cases use workingId to construct an ObjectId
212
+ if (workingId == null) {
213
+ // The most common use case (blank id, new objectId instance):
214
+ // generate a new id directly into the packed fields.
215
+ const time = Math.floor(Date.now() / 1000);
216
+ const inc = ObjectId.getInc();
217
+ const pu = (ObjectId.PROCESS_UNIQUE ??= ByteUtils.randomBytes(5));
218
+ this.i0 = (time >>> 8) & 0xffffff;
219
+ this.i1 = ((time & 0xff) << 16) | (pu[0] << 8) | pu[1];
220
+ this.i2 = (pu[2] << 16) | (pu[3] << 8) | pu[4];
221
+ this.i3 = inc & 0xffffff;
222
+ } else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) {
223
+ // Normalize a non-Uint8Array view (DataView, Int8Array, ...) to a byte buffer so its
224
+ // bytes are read correctly.
225
+ this.setFromBytes(
226
+ workingId instanceof Uint8Array ? workingId : ByteUtils.toLocalBufferType(workingId)
227
+ );
228
+ } else if (typeof workingId === 'string') {
229
+ if (ObjectId.validateHexString(workingId)) {
230
+ this.setFromHex(workingId);
231
+ // If we are caching the hex string
232
+ if (ObjectId.cacheHexString) {
233
+ __idCache.set(this, workingId);
234
+ }
235
+ } else {
236
+ throw new BSONError(
237
+ 'input must be a 24 character hex string, 12 byte Uint8Array, or an integer'
238
+ );
239
+ }
240
+ } else {
241
+ throw new BSONError('Argument passed in does not match the accepted types');
242
+ }
243
+ }
244
+
245
+ /**
246
+ * The ObjectId bytes, rebuilt from the packed integer fields on each access. Every read
247
+ * returns a freshly allocated 12-byte buffer.
248
+ * @readonly
249
+ */
250
+ get id(): Uint8Array {
251
+ const b = ByteUtils.allocateUnsafe(12);
252
+ b[0] = (this.i0 >>> 16) & 0xff;
253
+ b[1] = (this.i0 >>> 8) & 0xff;
254
+ b[2] = this.i0 & 0xff;
255
+ b[3] = (this.i1 >>> 16) & 0xff;
256
+ b[4] = (this.i1 >>> 8) & 0xff;
257
+ b[5] = this.i1 & 0xff;
258
+ b[6] = (this.i2 >>> 16) & 0xff;
259
+ b[7] = (this.i2 >>> 8) & 0xff;
260
+ b[8] = this.i2 & 0xff;
261
+ b[9] = (this.i3 >>> 16) & 0xff;
262
+ b[10] = (this.i3 >>> 8) & 0xff;
263
+ b[11] = this.i3 & 0xff;
264
+ return b;
265
+ }
266
+
267
+ set id(value: Uint8Array) {
268
+ const bytes = value instanceof Uint8Array ? value : ByteUtils.toLocalBufferType(value);
269
+ this.setFromBytes(bytes);
270
+ if (ObjectId.cacheHexString) {
271
+ __idCache.set(this, ByteUtils.toHex(bytes));
272
+ }
273
+ }
274
+
275
+ /**
276
+ * @internal
277
+ * Validates the input string is a valid hex representation of an ObjectId.
278
+ */
279
+ private static validateHexString(string: string): boolean {
280
+ if (string?.length !== 24) return false;
281
+ for (let i = 0; i < 24; i++) {
282
+ const char = string.charCodeAt(i);
283
+ if (
284
+ // Check for ASCII 0-9
285
+ (char >= 48 && char <= 57) ||
286
+ // Check for ASCII a-f
287
+ (char >= 97 && char <= 102) ||
288
+ // Check for ASCII A-F
289
+ (char >= 65 && char <= 70)
290
+ ) {
291
+ continue;
292
+ }
293
+ return false;
294
+ }
295
+ return true;
296
+ }
297
+
298
+ /** Returns the ObjectId id as a 24 lowercase character hex string representation */
299
+ toHexString(): string {
300
+ if (ObjectId.cacheHexString) {
301
+ const __id = __idCache.get(this);
302
+ if (__id) return __id;
303
+ }
304
+
305
+ // Encode the four packed integers to hex via a byte->pair lookup table.
306
+ const i0 = this.i0;
307
+ const i1 = this.i1;
308
+ const i2 = this.i2;
309
+ const i3 = this.i3;
310
+ const hexString =
311
+ byteToHex[(i0 >>> 16) & 0xff] +
312
+ byteToHex[(i0 >>> 8) & 0xff] +
313
+ byteToHex[i0 & 0xff] +
314
+ byteToHex[(i1 >>> 16) & 0xff] +
315
+ byteToHex[(i1 >>> 8) & 0xff] +
316
+ byteToHex[i1 & 0xff] +
317
+ byteToHex[(i2 >>> 16) & 0xff] +
318
+ byteToHex[(i2 >>> 8) & 0xff] +
319
+ byteToHex[i2 & 0xff] +
320
+ byteToHex[(i3 >>> 16) & 0xff] +
321
+ byteToHex[(i3 >>> 8) & 0xff] +
322
+ byteToHex[i3 & 0xff];
323
+
324
+ if (ObjectId.cacheHexString) {
325
+ __idCache.set(this, hexString);
326
+ }
327
+
328
+ return hexString;
329
+ }
330
+
331
+ /**
332
+ * Update the ObjectId index
333
+ * @internal
334
+ */
335
+ private static getInc(): number {
336
+ return (ObjectId.index = (ObjectId.index + 1) % 0x1000000);
337
+ }
338
+
339
+ /**
340
+ * Generate a 12 byte id buffer used in ObjectId's
341
+ *
342
+ * @param time - pass in a second based timestamp.
343
+ */
344
+ static generate(time?: number): Uint8Array {
345
+ if ('number' !== typeof time) {
346
+ time = Math.floor(Date.now() / 1000);
347
+ }
348
+
349
+ const inc = ObjectId.getInc();
350
+ const buffer = ByteUtils.allocateUnsafe(12);
351
+
352
+ // 4-byte timestamp
353
+ NumberUtils.setInt32BE(buffer, 0, time);
354
+
355
+ // 5-byte process unique (generated lazily on first use, see NODE-7667)
356
+ const PROCESS_UNIQUE = (this.PROCESS_UNIQUE ??= ByteUtils.randomBytes(5));
357
+ buffer[4] = PROCESS_UNIQUE[0];
358
+ buffer[5] = PROCESS_UNIQUE[1];
359
+ buffer[6] = PROCESS_UNIQUE[2];
360
+ buffer[7] = PROCESS_UNIQUE[3];
361
+ buffer[8] = PROCESS_UNIQUE[4];
362
+
363
+ // 3-byte counter
364
+ buffer[11] = inc & 0xff;
365
+ buffer[10] = (inc >>> 8) & 0xff;
366
+ buffer[9] = (inc >>> 16) & 0xff;
367
+
368
+ return buffer;
369
+ }
370
+
371
+ /**
372
+ * Converts the id into a 24 character hex string for printing, unless encoding is provided.
373
+ * @param encoding - hex or base64
374
+ */
375
+ toString(encoding?: 'hex' | 'base64'): string {
376
+ if (encoding === 'base64') return ByteUtils.toBase64(this.id);
377
+ if (encoding === 'hex') return this.toHexString();
378
+ return this.toHexString();
379
+ }
380
+
381
+ /** Converts to its JSON the 24 character hex string representation. */
382
+ toJSON(): string {
383
+ return this.toHexString();
384
+ }
385
+
386
+ /** @internal */
387
+ private static is(variable: unknown): variable is ObjectId {
388
+ return (
389
+ variable != null &&
390
+ typeof variable === 'object' &&
391
+ '_bsontype' in variable &&
392
+ variable._bsontype === 'ObjectId'
393
+ );
394
+ }
395
+
396
+ /**
397
+ * Compares the equality of this ObjectId with `otherID`.
398
+ *
399
+ * @param otherId - ObjectId instance to compare against.
400
+ */
401
+ equals(otherId: string | ObjectId | ObjectIdLike | undefined | null): boolean {
402
+ if (otherId === undefined || otherId === null) {
403
+ return false;
404
+ }
405
+
406
+ if (
407
+ ObjectId.is(otherId) &&
408
+ typeof otherId.i0 === 'number' &&
409
+ typeof otherId.i1 === 'number' &&
410
+ typeof otherId.i2 === 'number' &&
411
+ typeof otherId.i3 === 'number'
412
+ ) {
413
+ // Same-build ObjectId (all four packed fields present): compare them directly. i3 (the
414
+ // counter / low bytes) differs most often between two ids, so checking it first fails fast.
415
+ return (
416
+ this.i3 === otherId.i3 &&
417
+ this.i0 === otherId.i0 &&
418
+ this.i1 === otherId.i1 &&
419
+ this.i2 === otherId.i2
420
+ );
421
+ }
422
+
423
+ if (typeof otherId === 'string') {
424
+ return otherId.toLowerCase() === this.toHexString();
425
+ }
426
+
427
+ if (typeof otherId === 'object' && typeof otherId.toHexString === 'function') {
428
+ // ObjectId-like values, and ObjectIds from a different bson build, compare by their
429
+ // public hex representation.
430
+ const otherIdString = otherId.toHexString();
431
+ const thisIdString = this.toHexString();
432
+ return typeof otherIdString === 'string' && otherIdString.toLowerCase() === thisIdString;
433
+ }
434
+
435
+ return false;
436
+ }
437
+
438
+ /** Returns the generation date (accurate up to the second) that this ID was generated. */
439
+ getTimestamp(): Date {
440
+ const timestamp = new Date();
441
+ // Bytes 0-3 (the big-endian timestamp) are i0's three bytes followed by i1's top byte.
442
+ const time = this.i0 * 0x100 + (this.i1 >>> 16);
443
+ timestamp.setTime(time * 1000);
444
+ return timestamp;
445
+ }
446
+
447
+ /** @internal */
448
+ static createPk(): ObjectId {
449
+ return new ObjectId();
450
+ }
451
+
452
+ /** @internal */
453
+ serializeInto(uint8array: Uint8Array, index: number): 12 {
454
+ uint8array[index] = (this.i0 >>> 16) & 0xff;
455
+ uint8array[index + 1] = (this.i0 >>> 8) & 0xff;
456
+ uint8array[index + 2] = this.i0 & 0xff;
457
+ uint8array[index + 3] = (this.i1 >>> 16) & 0xff;
458
+ uint8array[index + 4] = (this.i1 >>> 8) & 0xff;
459
+ uint8array[index + 5] = this.i1 & 0xff;
460
+ uint8array[index + 6] = (this.i2 >>> 16) & 0xff;
461
+ uint8array[index + 7] = (this.i2 >>> 8) & 0xff;
462
+ uint8array[index + 8] = this.i2 & 0xff;
463
+ uint8array[index + 9] = (this.i3 >>> 16) & 0xff;
464
+ uint8array[index + 10] = (this.i3 >>> 8) & 0xff;
465
+ uint8array[index + 11] = this.i3 & 0xff;
466
+ return 12;
467
+ }
468
+
469
+ /**
470
+ * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId.
471
+ *
472
+ * @param time - an integer number representing a number of seconds.
473
+ */
474
+ static createFromTime(time: number): ObjectId {
475
+ const buffer = ByteUtils.allocate(12);
476
+ for (let i = 11; i >= 4; i--) buffer[i] = 0;
477
+ // Encode time into first 4 bytes
478
+ NumberUtils.setInt32BE(buffer, 0, time);
479
+ // Return the new objectId
480
+ return new ObjectId(buffer);
481
+ }
482
+
483
+ /**
484
+ * Creates an ObjectId from a hex string representation of an ObjectId.
485
+ *
486
+ * @param hexString - create a ObjectId from a passed in 24 character hexstring.
487
+ */
488
+ static createFromHexString(hexString: string): ObjectId {
489
+ if (hexString?.length !== 24) {
490
+ throw new BSONError('hex string must be 24 characters');
491
+ }
492
+
493
+ return new ObjectId(ByteUtils.fromHex(hexString));
494
+ }
495
+
496
+ /** Creates an ObjectId instance from a base64 string */
497
+ static createFromBase64(base64: string): ObjectId {
498
+ if (base64?.length !== 16) {
499
+ throw new BSONError('base64 string must be 16 characters');
500
+ }
501
+
502
+ return new ObjectId(ByteUtils.fromBase64(base64));
503
+ }
504
+
505
+ /**
506
+ * Checks if a value can be used to create a valid bson ObjectId
507
+ * @param id - any JS value
508
+ */
509
+ static isValid(id: string | ObjectId | ObjectIdLike | Uint8Array): boolean {
510
+ if (id == null) return false;
511
+ if (typeof id === 'string') return ObjectId.validateHexString(id);
512
+
513
+ try {
514
+ new ObjectId(id);
515
+ return true;
516
+ } catch {
517
+ return false;
518
+ }
519
+ }
520
+
521
+ /** @internal */
522
+ toExtendedJSON(): ObjectIdExtended {
523
+ if (this.toHexString) return { $oid: this.toHexString() };
524
+ return { $oid: this.toString('hex') };
525
+ }
526
+
527
+ /** @internal */
528
+ static fromExtendedJSON(doc: ObjectIdExtended): ObjectId {
529
+ return new ObjectId(doc.$oid);
530
+ }
531
+
532
+ /** @internal */
533
+ private isCached(): boolean {
534
+ return ObjectId.cacheHexString && __idCache.has(this);
535
+ }
536
+
537
+ /**
538
+ * Converts to a string representation of this Id.
539
+ *
540
+ * @returns return the 24 character hex string representation.
541
+ */
542
+ inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
543
+ inspect ??= defaultInspect;
544
+ return `new ObjectId(${inspect(this.toHexString(), options)})`;
545
+ }
546
+ }
gateway/node_modules/bson/src/parse_utf8.ts ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { BSONError } from './error';
2
+
3
+ type TextDecoder = {
4
+ readonly encoding: string;
5
+ readonly fatal: boolean;
6
+ readonly ignoreBOM: boolean;
7
+ decode(input?: Uint8Array): string;
8
+ };
9
+ type TextDecoderConstructor = {
10
+ new (label: 'utf8', options: { fatal: boolean; ignoreBOM?: boolean }): TextDecoder;
11
+ };
12
+
13
+ // parse utf8 globals
14
+ declare const TextDecoder: TextDecoderConstructor;
15
+ let TextDecoderFatal: TextDecoder;
16
+ let TextDecoderNonFatal: TextDecoder;
17
+
18
+ /**
19
+ * Determines if the passed in bytes are valid utf8
20
+ * @param bytes - An array of 8-bit bytes. Must be indexable and have length property
21
+ * @param start - The index to start validating
22
+ * @param end - The index to end validating
23
+ */
24
+ export function parseUtf8(buffer: Uint8Array, start: number, end: number, fatal: boolean): string {
25
+ if (fatal) {
26
+ TextDecoderFatal ??= new TextDecoder('utf8', { fatal: true });
27
+ try {
28
+ return TextDecoderFatal.decode(buffer.subarray(start, end));
29
+ } catch (cause) {
30
+ throw new BSONError('Invalid UTF-8 string in BSON document', { cause });
31
+ }
32
+ }
33
+ TextDecoderNonFatal ??= new TextDecoder('utf8', { fatal: false });
34
+ return TextDecoderNonFatal.decode(buffer.subarray(start, end));
35
+ }
gateway/node_modules/bson/src/parser/calculate_size.ts ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Binary } from '../binary';
2
+ import type { Document } from '../bson';
3
+ import { BSONError, BSONVersionError } from '../error';
4
+ import * as constants from '../constants';
5
+ import { ByteUtils } from '../utils/byte_utils';
6
+ import { isAnyArrayBuffer, isDate, isMap, isRegExp } from './utils';
7
+
8
+ export function internalCalculateObjectSize(
9
+ object: Document,
10
+ serializeFunctions?: boolean,
11
+ ignoreUndefined?: boolean
12
+ ): number {
13
+ // Each stack entry carries its own ignoreUndefined so DBRef fields can force ignoreUndefined=true
14
+ // regardless of the caller's setting, matching the behavior of serializeInto.
15
+ const objectStack: Array<{ obj: Document; ignoreUndefined: boolean }> = [
16
+ { obj: object, ignoreUndefined: ignoreUndefined ?? false }
17
+ ];
18
+ let total = 0;
19
+
20
+ while (objectStack.length > 0) {
21
+ const { obj, ignoreUndefined: frameIgnoreUndefined } = objectStack.pop()!;
22
+ total += 5; // 4-byte size field + null terminator
23
+
24
+ const isObjArray = Array.isArray(obj);
25
+ const isObjMap = !isObjArray && (obj instanceof Map || isMap(obj));
26
+ let target = obj;
27
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
28
+ if (!isObjArray && !isObjMap && typeof (obj as any)?.toBSON === 'function') {
29
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
30
+ target = (obj as any).toBSON();
31
+ }
32
+
33
+ if (isObjArray) {
34
+ const array = target as unknown[];
35
+ for (let i = 0; i < array.length; i++) {
36
+ total += calculateElementSize(
37
+ i.toString(),
38
+ array[i],
39
+ serializeFunctions,
40
+ true,
41
+ frameIgnoreUndefined,
42
+ objectStack
43
+ );
44
+ }
45
+ } else if (isObjMap) {
46
+ for (const [key, value] of target as Map<string, unknown>) {
47
+ total += calculateElementSize(
48
+ key,
49
+ value,
50
+ serializeFunctions,
51
+ false,
52
+ frameIgnoreUndefined,
53
+ objectStack
54
+ );
55
+ }
56
+ } else {
57
+ for (const key of Object.keys(target)) {
58
+ total += calculateElementSize(
59
+ key,
60
+ target[key],
61
+ serializeFunctions,
62
+ false,
63
+ frameIgnoreUndefined,
64
+ objectStack
65
+ );
66
+ }
67
+ }
68
+ }
69
+
70
+ return total;
71
+ }
72
+
73
+ /** @internal */
74
+ function calculateElementSize(
75
+ name: string,
76
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
77
+ value: any,
78
+ serializeFunctions = false,
79
+ isArray = false,
80
+ ignoreUndefined = false,
81
+ objectStack: Array<{ obj: Document; ignoreUndefined: boolean }>
82
+ ): number {
83
+ // If we have toBSON defined, override the current object
84
+ if (typeof value?.toBSON === 'function') {
85
+ value = value.toBSON();
86
+ }
87
+
88
+ switch (typeof value) {
89
+ case 'string':
90
+ return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1;
91
+ case 'number':
92
+ if (
93
+ Math.floor(value) === value &&
94
+ value >= constants.JS_INT_MIN &&
95
+ value <= constants.JS_INT_MAX
96
+ ) {
97
+ if (value >= constants.BSON_INT32_MIN && value <= constants.BSON_INT32_MAX) {
98
+ // 32 bit
99
+ return ByteUtils.utf8ByteLength(name) + 1 + (4 + 1);
100
+ } else {
101
+ return ByteUtils.utf8ByteLength(name) + 1 + (8 + 1);
102
+ }
103
+ } else {
104
+ // 64 bit
105
+ return ByteUtils.utf8ByteLength(name) + 1 + (8 + 1);
106
+ }
107
+ case 'undefined':
108
+ if (isArray || !ignoreUndefined) return ByteUtils.utf8ByteLength(name) + 1 + 1;
109
+ return 0;
110
+ case 'boolean':
111
+ return ByteUtils.utf8ByteLength(name) + 1 + (1 + 1);
112
+ case 'object':
113
+ if (
114
+ value != null &&
115
+ typeof value._bsontype === 'string' &&
116
+ value[constants.BSON_VERSION_SYMBOL] !== constants.BSON_MAJOR_VERSION
117
+ ) {
118
+ throw new BSONVersionError();
119
+ } else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
120
+ return ByteUtils.utf8ByteLength(name) + 1 + 1;
121
+ } else if (value._bsontype === 'ObjectId') {
122
+ return ByteUtils.utf8ByteLength(name) + 1 + (12 + 1);
123
+ } else if (value instanceof Date || isDate(value)) {
124
+ return ByteUtils.utf8ByteLength(name) + 1 + (8 + 1);
125
+ } else if (
126
+ ArrayBuffer.isView(value) ||
127
+ value instanceof ArrayBuffer ||
128
+ isAnyArrayBuffer(value)
129
+ ) {
130
+ return ByteUtils.utf8ByteLength(name) + 1 + (1 + 4 + 1) + value.byteLength;
131
+ } else if (
132
+ value._bsontype === 'Long' ||
133
+ value._bsontype === 'Double' ||
134
+ value._bsontype === 'Timestamp'
135
+ ) {
136
+ return ByteUtils.utf8ByteLength(name) + 1 + (8 + 1);
137
+ } else if (value._bsontype === 'Decimal128') {
138
+ return ByteUtils.utf8ByteLength(name) + 1 + (16 + 1);
139
+ } else if (value._bsontype === 'Int32') {
140
+ return ByteUtils.utf8ByteLength(name) + 1 + (4 + 1);
141
+ } else if (value._bsontype === 'Code') {
142
+ // Calculate size depending on the availability of a scope
143
+ if (value.scope != null && Object.keys(value.scope).length > 0) {
144
+ objectStack.push({ obj: value.scope, ignoreUndefined });
145
+ return (
146
+ ByteUtils.utf8ByteLength(name) +
147
+ 1 +
148
+ 1 +
149
+ 4 +
150
+ 4 +
151
+ ByteUtils.utf8ByteLength(value.code.toString()) +
152
+ 1
153
+ );
154
+ } else {
155
+ return (
156
+ ByteUtils.utf8ByteLength(name) +
157
+ 1 +
158
+ 1 +
159
+ 4 +
160
+ ByteUtils.utf8ByteLength(value.code.toString()) +
161
+ 1
162
+ );
163
+ }
164
+ } else if (value._bsontype === 'Binary') {
165
+ const binary: Binary = value;
166
+ // Check what kind of subtype we have
167
+ if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
168
+ return ByteUtils.utf8ByteLength(name) + 1 + (binary.position + 1 + 4 + 1 + 4);
169
+ } else {
170
+ return ByteUtils.utf8ByteLength(name) + 1 + (binary.position + 1 + 4 + 1);
171
+ }
172
+ } else if (value._bsontype === 'BSONSymbol') {
173
+ return (
174
+ ByteUtils.utf8ByteLength(name) + 1 + ByteUtils.utf8ByteLength(value.value) + 4 + 1 + 1
175
+ );
176
+ } else if (value._bsontype === 'DBRef') {
177
+ // Set up correct object for serialization
178
+ const ordered_values = Object.assign(
179
+ {
180
+ $ref: value.collection,
181
+ $id: value.oid
182
+ },
183
+ value.fields
184
+ );
185
+
186
+ // Add db reference if it exists
187
+ if (value.db != null) {
188
+ ordered_values['$db'] = value.db;
189
+ }
190
+
191
+ // DBRef fields always use ignoreUndefined=true to match serializeInto behavior.
192
+ objectStack.push({ obj: ordered_values, ignoreUndefined: true });
193
+ return ByteUtils.utf8ByteLength(name) + 1 + 1;
194
+ } else if (value instanceof RegExp || isRegExp(value)) {
195
+ return (
196
+ ByteUtils.utf8ByteLength(name) +
197
+ 1 +
198
+ 1 +
199
+ ByteUtils.utf8ByteLength(value.source) +
200
+ 1 +
201
+ (value.global ? 1 : 0) +
202
+ (value.ignoreCase ? 1 : 0) +
203
+ (value.multiline ? 1 : 0) +
204
+ 1
205
+ );
206
+ } else if (value._bsontype === 'BSONRegExp') {
207
+ return (
208
+ ByteUtils.utf8ByteLength(name) +
209
+ 1 +
210
+ 1 +
211
+ ByteUtils.utf8ByteLength(value.pattern) +
212
+ 1 +
213
+ ByteUtils.utf8ByteLength(value.options) +
214
+ 1
215
+ );
216
+ } else {
217
+ objectStack.push({ obj: value, ignoreUndefined });
218
+ return ByteUtils.utf8ByteLength(name) + 1 + 1;
219
+ }
220
+ case 'function':
221
+ if (serializeFunctions) {
222
+ return (
223
+ ByteUtils.utf8ByteLength(name) +
224
+ 1 +
225
+ 1 +
226
+ 4 +
227
+ ByteUtils.utf8ByteLength(value.toString()) +
228
+ 1
229
+ );
230
+ }
231
+ return 0;
232
+ case 'bigint':
233
+ return ByteUtils.utf8ByteLength(name) + 1 + (8 + 1);
234
+ case 'symbol':
235
+ return 0;
236
+ default:
237
+ throw new BSONError(`Unrecognized JS type: ${typeof value}`);
238
+ }
239
+ }
gateway/node_modules/bson/src/parser/deserializer.ts ADDED
@@ -0,0 +1,793 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Binary, UUID } from '../binary';
2
+ import type { Document } from '../bson';
3
+ import { Code } from '../code';
4
+ import * as constants from '../constants';
5
+ import { DBRef, isDBRefLike } from '../db_ref';
6
+ import { Decimal128 } from '../decimal128';
7
+ import { Double } from '../double';
8
+ import { BSONError } from '../error';
9
+ import { Int32 } from '../int_32';
10
+ import { Long } from '../long';
11
+ import { MaxKey } from '../max_key';
12
+ import { MinKey } from '../min_key';
13
+ import { ObjectId } from '../objectid';
14
+ import { BSONRegExp } from '../regexp';
15
+ import { BSONSymbol } from '../symbol';
16
+ import { Timestamp } from '../timestamp';
17
+ import { ByteUtils } from '../utils/byte_utils';
18
+ import { NumberUtils } from '../utils/number_utils';
19
+
20
+ /** @public */
21
+ export interface DeserializeOptions {
22
+ /**
23
+ * when deserializing a Long return as a BigInt.
24
+ * @defaultValue `false`
25
+ */
26
+ useBigInt64?: boolean;
27
+ /**
28
+ * when deserializing a Long will fit it into a Number if it's smaller than 53 bits.
29
+ * @defaultValue `true`
30
+ */
31
+ promoteLongs?: boolean;
32
+ /**
33
+ * when deserializing a Binary will return it as a node.js Buffer instance.
34
+ * @defaultValue `false`
35
+ */
36
+ promoteBuffers?: boolean;
37
+ /**
38
+ * when deserializing will promote BSON values to their Node.js closest equivalent types.
39
+ * @defaultValue `true`
40
+ */
41
+ promoteValues?: boolean;
42
+ /**
43
+ * allow to specify if there what fields we wish to return as unserialized raw buffer.
44
+ * @defaultValue `null`
45
+ */
46
+ fieldsAsRaw?: Document;
47
+ /**
48
+ * return BSON regular expressions as BSONRegExp instances.
49
+ * @defaultValue `false`
50
+ */
51
+ bsonRegExp?: boolean;
52
+ /**
53
+ * allows the buffer to be larger than the parsed BSON object.
54
+ * @defaultValue `false`
55
+ */
56
+ allowObjectSmallerThanBufferSize?: boolean;
57
+ /**
58
+ * Offset into buffer to begin reading document from
59
+ * @defaultValue `0`
60
+ */
61
+ index?: number;
62
+
63
+ raw?: boolean;
64
+ /** Allows for opt-out utf-8 validation for all keys or
65
+ * specified keys. Must be all true or all false.
66
+ *
67
+ * @example
68
+ * ```js
69
+ * // disables validation on all keys
70
+ * validation: { utf8: false }
71
+ *
72
+ * // enables validation only on specified keys a, b, and c
73
+ * validation: { utf8: { a: true, b: true, c: true } }
74
+ *
75
+ * // disables validation only on specified keys a, b
76
+ * validation: { utf8: { a: false, b: false } }
77
+ * ```
78
+ */
79
+ validation?: { utf8: boolean | Record<string, true> | Record<string, false> };
80
+ }
81
+
82
+ // Internal long versions
83
+ const JS_INT_MAX_LONG = Long.fromNumber(constants.JS_INT_MAX);
84
+ const JS_INT_MIN_LONG = Long.fromNumber(constants.JS_INT_MIN);
85
+
86
+ export function internalDeserialize(
87
+ buffer: Uint8Array,
88
+ options: DeserializeOptions,
89
+ isArray?: boolean
90
+ ): Document {
91
+ options = options == null ? {} : options;
92
+ const index = options && options.index ? options.index : 0;
93
+ // Read the document size
94
+ const size = NumberUtils.getInt32LE(buffer, index);
95
+
96
+ if (size < 5) {
97
+ throw new BSONError(`bson size must be >= 5, is ${size}`);
98
+ }
99
+
100
+ if (options.allowObjectSmallerThanBufferSize && buffer.length < size) {
101
+ throw new BSONError(`buffer length ${buffer.length} must be >= bson size ${size}`);
102
+ }
103
+
104
+ if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) {
105
+ throw new BSONError(`buffer length ${buffer.length} must === bson size ${size}`);
106
+ }
107
+
108
+ if (size + index > buffer.byteLength) {
109
+ throw new BSONError(
110
+ `(bson size ${size} + options.index ${index} must be <= buffer length ${buffer.byteLength})`
111
+ );
112
+ }
113
+
114
+ // Illegal end value
115
+ if (buffer[index + size - 1] !== 0) {
116
+ throw new BSONError(
117
+ "One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"
118
+ );
119
+ }
120
+
121
+ // Start deserialization
122
+ return deserializeObject(buffer, index, options, isArray);
123
+ }
124
+
125
+ interface NestedParsingFrame {
126
+ // One of 3 supported types:
127
+ // - constants.BSON_DATA_OBJECT
128
+ // - constants.BSON_DATA_ARRAY
129
+ // - constants.BSON_DATA_CODE_W_SCOPE
130
+ elementType:
131
+ | typeof constants.BSON_DATA_OBJECT
132
+ | typeof constants.BSON_DATA_ARRAY
133
+ | typeof constants.BSON_DATA_CODE_W_SCOPE;
134
+ // Document that we will fill out as we parse the nested object
135
+ holdingDocument: Document;
136
+ // The name of the key we will set the parsed object on once we finish parsing the nested object, this is used in the onComplete callback to know where to set the parsed nested object in the parent document
137
+ propertyName: string | number;
138
+ // The index in the buffer where the current object ends, used to know when we are done parsing the current object and can pop the stack
139
+ lastIndex: number;
140
+ // Whether the current frame is parsing an array, used to know whether to interpret keys as strings or array indices
141
+ isArray: boolean;
142
+ // The next array index to use if this frame is parsing an array, used to assign numeric keys to array elements without having to utf-8 decode the key from the buffer
143
+ arrayIndex: number;
144
+ // When true, all objects in this frame will be returned as raw bson buffers without parsing.
145
+ // This is used when the fieldsAsRaw option is used on a parent object, and is inherited by nested frames.
146
+ // It can also be set to true if the global raw option is set, but it cannot be set to true for a frame if the global raw option is false.
147
+ raw: boolean;
148
+ // When true, this frame may be a DBRef. This is set to false if we encounter a key that is not valid for a DBRef, and is left as null for arrays since they cannot be DBRefs.
149
+ isPossibleDBRef: boolean | null;
150
+ // The utf-8 validation setting for this frame, used to determine whether to utf-8 validate keys in this frame. This is determined based on the global utf-8 validation setting and the specific keys specified in the validation option.
151
+ validationSetting: boolean;
152
+ functionString: string | null; // only used for Code with Scope
153
+ // The enclosing frame, or null at the top level. The parsing stack is a linked list threaded
154
+ // through this field rather than a separate array, which avoids array push/pop churn per frame.
155
+ prev: NestedParsingFrame | null;
156
+ }
157
+
158
+ const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/;
159
+
160
+ // Assigns a parsed value into the destination document, guarding the __proto__ key to avoid
161
+ // prototype pollution.
162
+ function assignValue(dest: Document, name: string | number, value: unknown): void {
163
+ if (name === '__proto__') {
164
+ Object.defineProperty(dest, name, {
165
+ value,
166
+ writable: true,
167
+ enumerable: true,
168
+ configurable: true
169
+ });
170
+ } else {
171
+ dest[name] = value;
172
+ }
173
+ }
174
+
175
+ // Promotes a plain document to a DBRef instance when it has the DBRef shape ($ref/$id[/$db]).
176
+ function toPotentialDbRef(doc: Document): DBRef | Document {
177
+ if (isDBRefLike(doc)) {
178
+ const { $ref, $id, $db, ...fields } = doc;
179
+ return new DBRef($ref, $id, $db, fields);
180
+ }
181
+ return doc;
182
+ }
183
+
184
+ function deserializeObject(
185
+ buffer: Uint8Array,
186
+ index: number,
187
+ options: DeserializeOptions,
188
+ isArray = false
189
+ ) {
190
+ // Settings configured from options parameter
191
+
192
+ // Strips prototype chain so inherited properties don't affect option reads.
193
+ options = { ...options };
194
+
195
+ // Used to track fields that should be returned as raw bson buffers without parsing, this is set based on the fieldsAsRaw option and is inherited by nested frames when parsing nested objects
196
+ const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw'];
197
+
198
+ // Return raw bson buffer instead of parsing it
199
+ const raw = options['raw'] == null ? false : options['raw'];
200
+
201
+ // Return BSONRegExp objects instead of native regular expressions
202
+ const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false;
203
+
204
+ // Controls the promotion of values vs wrapper classes
205
+ const promoteBuffers = options.promoteBuffers ?? false;
206
+ const promoteLongs = options.promoteLongs ?? true;
207
+ const promoteValues = options.promoteValues ?? true;
208
+ const useBigInt64 = options.useBigInt64 ?? false;
209
+
210
+ // Validate bigint and long promotion settings
211
+ if (useBigInt64 && !promoteValues) {
212
+ throw new BSONError('Must either request bigint or Long for int64 deserialization');
213
+ }
214
+ if (useBigInt64 && !promoteLongs) {
215
+ throw new BSONError('Must either request bigint or Long for int64 deserialization');
216
+ }
217
+
218
+ // Ensures default validation option if none given
219
+ const validation = options.validation == null ? { utf8: true } : options.validation;
220
+
221
+ // Shows if global utf-8 validation is enabled or disabled
222
+ let globalUTFValidation = true;
223
+ // Reflects utf-8 validation setting regardless of global or specific key validation
224
+ let validationSetting: boolean;
225
+ // Set of keys either to enable or disable validation on
226
+ let utf8KeysSet;
227
+
228
+ // Check for boolean uniformity and empty validation option
229
+ const utf8ValidatedKeys = validation.utf8;
230
+ if (typeof utf8ValidatedKeys === 'boolean') {
231
+ validationSetting = utf8ValidatedKeys;
232
+ } else {
233
+ globalUTFValidation = false;
234
+ const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) {
235
+ return utf8ValidatedKeys[key];
236
+ });
237
+ if (utf8ValidationValues.length === 0) {
238
+ throw new BSONError('UTF-8 validation setting cannot be empty');
239
+ }
240
+ if (typeof utf8ValidationValues[0] !== 'boolean') {
241
+ throw new BSONError('Invalid UTF-8 validation option, must specify boolean values');
242
+ }
243
+ validationSetting = utf8ValidationValues[0];
244
+ // Ensures boolean uniformity in utf-8 validation (all true or all false)
245
+ if (!utf8ValidationValues.every(item => item === validationSetting)) {
246
+ throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false');
247
+ }
248
+ }
249
+
250
+ // Add keys to set that will either be validated or not based on validationSetting
251
+ if (!globalUTFValidation) {
252
+ utf8KeysSet = new Set();
253
+
254
+ for (const key of Object.keys(utf8ValidatedKeys)) {
255
+ utf8KeysSet.add(key);
256
+ }
257
+ }
258
+
259
+ // Begin parsing the document
260
+
261
+ // Set the start index
262
+ const startIndex = index;
263
+
264
+ // Validate that we have at least 4 bytes of buffer
265
+ if (buffer.length < 5) throw new BSONError('corrupt bson message < 5 bytes long');
266
+
267
+ // Read the document size
268
+ const size = NumberUtils.getInt32LE(buffer, index);
269
+ // Skip past the size field
270
+ index += 4;
271
+
272
+ // Ensure buffer is valid size
273
+ if (size < 5 || size > buffer.length) throw new BSONError('corrupt bson message');
274
+
275
+ // Create holding object
276
+ const rootObject: Document = isArray ? [] : {};
277
+ // Used for arrays to skip having to perform utf8 decoding
278
+ let arrayIndex = 0;
279
+
280
+ let isPossibleDBRef = isArray ? false : null;
281
+
282
+ // Top of the parsing stack (a linked list via each frame's `prev`), or null at the top level.
283
+ let currentFrame: NestedParsingFrame | null = null;
284
+ // Destination object for the current frame (the parent's holdingDocument, or rootObject at the
285
+ // top level). Maintained alongside currentFrame so per-field assignment never recomputes it.
286
+ let currentDest: Document = rootObject;
287
+ // Whether the current frame is an array. Maintained alongside currentFrame so the per-field key
288
+ // logic does not branch on currentFrame every iteration.
289
+ let currentIsArray = isArray;
290
+
291
+ // While we have more left data left keep parsing
292
+ while (true) {
293
+ // Read the type
294
+ const elementType = buffer[index++];
295
+
296
+ // If we get a zero it's the last byte, exit
297
+ if (elementType === 0) {
298
+ // 0 byte marks end of document.
299
+ if (currentFrame) {
300
+ // If we're in a frame, that means the end of the current nested document
301
+ if (index === currentFrame.lastIndex) {
302
+ // Snapshot the completed frame before updating currentFrame to the parent.
303
+ const completedFrame: NestedParsingFrame = currentFrame;
304
+ currentFrame = completedFrame.prev;
305
+ if (currentFrame === null) {
306
+ currentDest = rootObject;
307
+ currentIsArray = isArray;
308
+ } else {
309
+ currentDest = currentFrame.holdingDocument;
310
+ currentIsArray = currentFrame.isArray;
311
+ }
312
+ // finish the frame
313
+ let result: Document = completedFrame.holdingDocument;
314
+ switch (completedFrame.elementType) {
315
+ case constants.BSON_DATA_OBJECT:
316
+ // if this is a DBRef, we need to construct a DBRef object instead of a plain object
317
+ if (completedFrame.isPossibleDBRef) {
318
+ result = toPotentialDbRef(result);
319
+ }
320
+ break;
321
+ case constants.BSON_DATA_ARRAY:
322
+ // nothing to do, the holding document is already an array and the keys were set as numeric indices
323
+ break;
324
+ case constants.BSON_DATA_CODE_W_SCOPE:
325
+ // the holding document is the scope, we need to construct a Code object with the function string and scope
326
+ result = new Code(completedFrame.functionString!, completedFrame.holdingDocument);
327
+ break;
328
+ default:
329
+ throw new BSONError('Unexpected element type in frame stack');
330
+ }
331
+ // set the value in the parent document (currentDest now points to the parent's document)
332
+ assignValue(currentDest, completedFrame.propertyName, result);
333
+ continue;
334
+ } else {
335
+ // Current index does not match the last index of the frame, the document is malformed
336
+ if (currentFrame.elementType === constants.BSON_DATA_ARRAY) {
337
+ throw new BSONError('corrupted array bson');
338
+ }
339
+ throw new BSONError('Bad BSON Document: object not properly terminated');
340
+ }
341
+ } else {
342
+ // If we're not in a frame, that means the end of the root document, so we break out of the loop and return the object
343
+ break;
344
+ }
345
+ }
346
+
347
+ // Get the start search index
348
+ let i = index;
349
+ // Locate the end of the c string
350
+ while (buffer[i] !== 0x00 && i < buffer.length) {
351
+ i++;
352
+ }
353
+
354
+ // If are at the end of the buffer there is a problem with the document
355
+ if (i >= buffer.byteLength) throw new BSONError('Bad BSON Document: illegal CString');
356
+
357
+ // Represents the key
358
+ const name = currentIsArray
359
+ ? currentFrame !== null
360
+ ? currentFrame.arrayIndex++
361
+ : arrayIndex++
362
+ : ByteUtils.toUTF8(buffer, index, i, false);
363
+
364
+ // shouldValidateKey is true if the key should be validated, false otherwise.
365
+ // Within a nested frame the original code passed a collapsed boolean validation option,
366
+ // so all keys in the frame are validated uniformly using the frame's setting.
367
+ let shouldValidateKey: boolean;
368
+ if (currentFrame !== null) {
369
+ shouldValidateKey = currentFrame.validationSetting;
370
+ } else if (globalUTFValidation || utf8KeysSet?.has(name)) {
371
+ shouldValidateKey = validationSetting;
372
+ } else {
373
+ shouldValidateKey = !validationSetting;
374
+ }
375
+
376
+ // Route DBRef key tracking to the current frame; the root variable handles the root doc.
377
+ if (currentFrame !== null) {
378
+ if (currentFrame.isPossibleDBRef !== false && typeof name === 'string' && name[0] === '$') {
379
+ currentFrame.isPossibleDBRef = allowedDBRefKeys.test(name);
380
+ }
381
+ } else if (isPossibleDBRef !== false && (name as string)[0] === '$') {
382
+ isPossibleDBRef = allowedDBRefKeys.test(name as string);
383
+ }
384
+ let value;
385
+ let isDeferredValue = false;
386
+
387
+ index = i + 1;
388
+
389
+ if (elementType === constants.BSON_DATA_STRING) {
390
+ const stringSize = NumberUtils.getInt32LE(buffer, index);
391
+ index += 4;
392
+ if (
393
+ stringSize <= 0 ||
394
+ stringSize > buffer.length - index ||
395
+ buffer[index + stringSize - 1] !== 0
396
+ ) {
397
+ throw new BSONError('bad string length in bson');
398
+ }
399
+ value = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
400
+ index = index + stringSize;
401
+ } else if (elementType === constants.BSON_DATA_OID) {
402
+ // ObjectId reads these 12 bytes from the wire buffer at this offset into its own fields
403
+ // and keeps no reference to the source, so the buffer can be passed directly.
404
+ value = new ObjectId(buffer, index);
405
+ index = index + 12;
406
+ } else if (elementType === constants.BSON_DATA_INT && promoteValues === false) {
407
+ value = new Int32(NumberUtils.getInt32LE(buffer, index));
408
+ index += 4;
409
+ } else if (elementType === constants.BSON_DATA_INT) {
410
+ value = NumberUtils.getInt32LE(buffer, index);
411
+ index += 4;
412
+ } else if (elementType === constants.BSON_DATA_NUMBER) {
413
+ value = NumberUtils.getFloat64LE(buffer, index);
414
+ index += 8;
415
+ if (promoteValues === false) value = new Double(value);
416
+ } else if (elementType === constants.BSON_DATA_DATE) {
417
+ const lowBits = NumberUtils.getInt32LE(buffer, index);
418
+ const highBits = NumberUtils.getInt32LE(buffer, index + 4);
419
+ index += 8;
420
+
421
+ value = new Date(new Long(lowBits, highBits).toNumber());
422
+ } else if (elementType === constants.BSON_DATA_BOOLEAN) {
423
+ if (buffer[index] !== 0 && buffer[index] !== 1)
424
+ throw new BSONError('illegal boolean type value');
425
+ value = buffer[index++] === 1;
426
+ } else if (elementType === constants.BSON_DATA_OBJECT) {
427
+ const objectSize = NumberUtils.getInt32LE(buffer, index);
428
+
429
+ if (objectSize < 5 || objectSize > buffer.length - index)
430
+ throw new BSONError('bad embedded document length in bson');
431
+
432
+ // We have a raw value: either the global raw option, or the parent frame requested raw elements.
433
+ if (raw || (currentFrame?.raw ?? false)) {
434
+ value = buffer.subarray(index, index + objectSize);
435
+ index = index + objectSize;
436
+ } else {
437
+ isDeferredValue = true;
438
+ const objectFrame: NestedParsingFrame = {
439
+ holdingDocument: {},
440
+ elementType: constants.BSON_DATA_OBJECT,
441
+ propertyName: name,
442
+ functionString: null,
443
+ lastIndex: index + objectSize,
444
+ isArray: false,
445
+ arrayIndex: 0,
446
+ raw: false,
447
+ isPossibleDBRef: null, // we don't know if this is a DBRef until we parse the keys, so we start with null and set to false if we encounter a key that is not valid for a DBRef
448
+ validationSetting: shouldValidateKey,
449
+ prev: currentFrame
450
+ };
451
+ currentFrame = objectFrame;
452
+ currentDest = objectFrame.holdingDocument;
453
+ currentIsArray = false;
454
+ index = index + 4;
455
+ }
456
+ } else if (elementType === constants.BSON_DATA_ARRAY) {
457
+ const objectSize = NumberUtils.getInt32LE(buffer, index);
458
+
459
+ if (objectSize < 5 || objectSize > buffer.length - index)
460
+ throw new BSONError('bad embedded array length in bson');
461
+
462
+ // Stop index
463
+ const stopIndex = index + objectSize;
464
+
465
+ // fieldsAsRaw match: push with raw=true so embedded objects inside come back as raw bytes.
466
+ // Also propagate raw from the parent frame (nested arrays inside a raw array stay raw).
467
+ const arrayRaw = !!(fieldsAsRaw && fieldsAsRaw[name]) || (currentFrame?.raw ?? false);
468
+ isDeferredValue = true;
469
+ const arrayFrame: NestedParsingFrame = {
470
+ holdingDocument: [],
471
+ elementType: constants.BSON_DATA_ARRAY,
472
+ propertyName: name,
473
+ functionString: null,
474
+ lastIndex: stopIndex,
475
+ isArray: true,
476
+ arrayIndex: 0,
477
+ raw: arrayRaw,
478
+ isPossibleDBRef: false,
479
+ validationSetting: shouldValidateKey,
480
+ prev: currentFrame
481
+ };
482
+ currentFrame = arrayFrame;
483
+ currentDest = arrayFrame.holdingDocument;
484
+ currentIsArray = true;
485
+ index = index + 4;
486
+ } else if (elementType === constants.BSON_DATA_UNDEFINED) {
487
+ value = undefined;
488
+ } else if (elementType === constants.BSON_DATA_NULL) {
489
+ value = null;
490
+ } else if (elementType === constants.BSON_DATA_LONG) {
491
+ if (useBigInt64) {
492
+ value = NumberUtils.getBigInt64LE(buffer, index);
493
+ index += 8;
494
+ } else {
495
+ // Unpack the low and high bits
496
+ const lowBits = NumberUtils.getInt32LE(buffer, index);
497
+ const highBits = NumberUtils.getInt32LE(buffer, index + 4);
498
+ index += 8;
499
+
500
+ const long = new Long(lowBits, highBits);
501
+ // Promote the long if possible
502
+ if (promoteLongs && promoteValues === true) {
503
+ value =
504
+ long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG)
505
+ ? long.toNumber()
506
+ : long;
507
+ } else {
508
+ value = long;
509
+ }
510
+ }
511
+ } else if (elementType === constants.BSON_DATA_DECIMAL128) {
512
+ // Buffer to contain the decimal bytes
513
+ const bytes = ByteUtils.allocateUnsafe(16);
514
+ // Copy the next 16 bytes into the bytes buffer
515
+ for (let i = 0; i < 16; i++) bytes[i] = buffer[index + i];
516
+ // Update index
517
+ index = index + 16;
518
+ // Assign the new Decimal128 value
519
+ value = new Decimal128(bytes);
520
+ } else if (elementType === constants.BSON_DATA_BINARY) {
521
+ let binarySize = NumberUtils.getInt32LE(buffer, index);
522
+ index += 4;
523
+ const totalBinarySize = binarySize;
524
+ const subType = buffer[index++];
525
+
526
+ // Did we have a negative binary size, throw
527
+ if (binarySize < 0) throw new BSONError('Negative binary type element size found');
528
+
529
+ // Is the length longer than the document
530
+ if (binarySize > buffer.byteLength)
531
+ throw new BSONError('Binary type size larger than document size');
532
+
533
+ // If we have subtype 2 skip the 4 bytes for the size
534
+ if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
535
+ binarySize = NumberUtils.getInt32LE(buffer, index);
536
+ index += 4;
537
+ if (binarySize < 0)
538
+ throw new BSONError('Negative binary type element size found for subtype 0x02');
539
+ if (binarySize > totalBinarySize - 4)
540
+ throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
541
+ if (binarySize < totalBinarySize - 4)
542
+ throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
543
+ }
544
+
545
+ if (promoteBuffers && promoteValues) {
546
+ value = ByteUtils.toLocalBufferType(buffer.subarray(index, index + binarySize));
547
+ } else {
548
+ value = new Binary(buffer.subarray(index, index + binarySize), subType);
549
+ if (subType === constants.BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) {
550
+ value = value.toUUID();
551
+ }
552
+ }
553
+
554
+ // Update the index
555
+ index = index + binarySize;
556
+ } else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === false) {
557
+ // Get the start search index
558
+ i = index;
559
+ // Locate the end of the c string
560
+ while (buffer[i] !== 0x00 && i < buffer.length) {
561
+ i++;
562
+ }
563
+ // If are at the end of the buffer there is a problem with the document
564
+ if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString');
565
+ // Return the C string
566
+ const source = ByteUtils.toUTF8(buffer, index, i, false);
567
+ // Create the regexp
568
+ index = i + 1;
569
+
570
+ // Get the start search index
571
+ i = index;
572
+ // Locate the end of the c string
573
+ while (buffer[i] !== 0x00 && i < buffer.length) {
574
+ i++;
575
+ }
576
+ // If are at the end of the buffer there is a problem with the document
577
+ if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString');
578
+ // Return the C string
579
+ const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false);
580
+ index = i + 1;
581
+
582
+ // For each option add the corresponding one for javascript
583
+ const optionsArray = new Array(regExpOptions.length);
584
+
585
+ // Parse options
586
+ for (i = 0; i < regExpOptions.length; i++) {
587
+ switch (regExpOptions[i]) {
588
+ case 'm':
589
+ optionsArray[i] = 'm';
590
+ break;
591
+ case 's':
592
+ optionsArray[i] = 'g';
593
+ break;
594
+ case 'i':
595
+ optionsArray[i] = 'i';
596
+ break;
597
+ }
598
+ }
599
+
600
+ value = new RegExp(source, optionsArray.join(''));
601
+ } else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === true) {
602
+ // Get the start search index
603
+ i = index;
604
+ // Locate the end of the c string
605
+ while (buffer[i] !== 0x00 && i < buffer.length) {
606
+ i++;
607
+ }
608
+ // If are at the end of the buffer there is a problem with the document
609
+ if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString');
610
+ // Return the C string
611
+ const source = ByteUtils.toUTF8(buffer, index, i, false);
612
+ index = i + 1;
613
+
614
+ // Get the start search index
615
+ i = index;
616
+ // Locate the end of the c string
617
+ while (buffer[i] !== 0x00 && i < buffer.length) {
618
+ i++;
619
+ }
620
+ // If are at the end of the buffer there is a problem with the document
621
+ if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString');
622
+ // Return the C string
623
+ const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false);
624
+ index = i + 1;
625
+
626
+ // Set the object
627
+ value = new BSONRegExp(source, regExpOptions);
628
+ } else if (elementType === constants.BSON_DATA_SYMBOL) {
629
+ const stringSize = NumberUtils.getInt32LE(buffer, index);
630
+ index += 4;
631
+ if (
632
+ stringSize <= 0 ||
633
+ stringSize > buffer.length - index ||
634
+ buffer[index + stringSize - 1] !== 0
635
+ ) {
636
+ throw new BSONError('bad string length in bson');
637
+ }
638
+ const symbol = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
639
+ value = promoteValues ? symbol : new BSONSymbol(symbol);
640
+ index = index + stringSize;
641
+ } else if (elementType === constants.BSON_DATA_TIMESTAMP) {
642
+ value = new Timestamp({
643
+ i: NumberUtils.getUint32LE(buffer, index),
644
+ t: NumberUtils.getUint32LE(buffer, index + 4)
645
+ });
646
+ index += 8;
647
+ } else if (elementType === constants.BSON_DATA_MIN_KEY) {
648
+ value = new MinKey();
649
+ } else if (elementType === constants.BSON_DATA_MAX_KEY) {
650
+ value = new MaxKey();
651
+ } else if (elementType === constants.BSON_DATA_CODE) {
652
+ const stringSize = NumberUtils.getInt32LE(buffer, index);
653
+ index += 4;
654
+ if (
655
+ stringSize <= 0 ||
656
+ stringSize > buffer.length - index ||
657
+ buffer[index + stringSize - 1] !== 0
658
+ ) {
659
+ throw new BSONError('bad string length in bson');
660
+ }
661
+ const functionString = ByteUtils.toUTF8(
662
+ buffer,
663
+ index,
664
+ index + stringSize - 1,
665
+ shouldValidateKey
666
+ );
667
+
668
+ value = new Code(functionString);
669
+
670
+ // Update parse index position
671
+ index = index + stringSize;
672
+ } else if (elementType === constants.BSON_DATA_CODE_W_SCOPE) {
673
+ const totalSize = NumberUtils.getInt32LE(buffer, index);
674
+ index += 4;
675
+
676
+ // Element cannot be shorter than totalSize + stringSize + documentSize + terminator
677
+ if (totalSize < 4 + 4 + 4 + 1) {
678
+ throw new BSONError('code_w_scope total size shorter minimum expected length');
679
+ }
680
+
681
+ // Get the code string size
682
+ const stringSize = NumberUtils.getInt32LE(buffer, index);
683
+ index += 4;
684
+ // Check if we have a valid string
685
+ if (
686
+ stringSize <= 0 ||
687
+ stringSize > buffer.length - index ||
688
+ buffer[index + stringSize - 1] !== 0
689
+ ) {
690
+ throw new BSONError('bad string length in bson');
691
+ }
692
+
693
+ // Javascript function
694
+ const functionString = ByteUtils.toUTF8(
695
+ buffer,
696
+ index,
697
+ index + stringSize - 1,
698
+ shouldValidateKey
699
+ );
700
+ // Update parse index position
701
+ index = index + stringSize;
702
+ // Parse the element
703
+ const _index = index;
704
+ // Decode the size of the object document
705
+ const objectSize = NumberUtils.getInt32LE(buffer, index);
706
+
707
+ if (objectSize < 5 || objectSize > buffer.length - index)
708
+ throw new BSONError('bad scope document size in code_w_scope');
709
+
710
+ // Check if field length is too short
711
+ if (totalSize < 4 + 4 + objectSize + stringSize) {
712
+ throw new BSONError('code_w_scope total size is too short, truncating scope');
713
+ }
714
+
715
+ // Check if totalSize field is too long
716
+ if (totalSize > 4 + 4 + objectSize + stringSize) {
717
+ throw new BSONError('code_w_scope total size is too long, clips outer document');
718
+ }
719
+
720
+ isDeferredValue = true;
721
+ const scopeFrame: NestedParsingFrame = {
722
+ holdingDocument: {},
723
+ elementType: constants.BSON_DATA_CODE_W_SCOPE,
724
+ propertyName: name,
725
+ functionString: functionString,
726
+ lastIndex: _index + objectSize,
727
+ isArray: false,
728
+ arrayIndex: 0,
729
+ raw: false,
730
+ isPossibleDBRef: null,
731
+ validationSetting: shouldValidateKey,
732
+ prev: currentFrame
733
+ };
734
+ currentFrame = scopeFrame;
735
+ currentDest = scopeFrame.holdingDocument;
736
+ currentIsArray = false;
737
+ index = index + 4; // move index past the size of the object, the rest of the object will be parsed in subsequent iterations of this loop
738
+ } else if (elementType === constants.BSON_DATA_DBPOINTER) {
739
+ // Get the code string size
740
+ const stringSize = NumberUtils.getInt32LE(buffer, index);
741
+ index += 4;
742
+ // Check if we have a valid string
743
+ if (
744
+ stringSize <= 0 ||
745
+ stringSize > buffer.length - index ||
746
+ buffer[index + stringSize - 1] !== 0
747
+ )
748
+ throw new BSONError('bad string length in bson');
749
+ // Namespace
750
+ const namespace = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
751
+ // Update parse index position
752
+ index = index + stringSize;
753
+
754
+ // Read the oid
755
+ const oidBuffer = ByteUtils.allocateUnsafe(12);
756
+ for (let i = 0; i < 12; i++) oidBuffer[i] = buffer[index + i];
757
+ const oid = new ObjectId(oidBuffer);
758
+
759
+ // Update the index
760
+ index = index + 12;
761
+
762
+ // Upgrade to DBRef type
763
+ value = new DBRef(namespace, oid);
764
+ } else {
765
+ throw new BSONError(
766
+ `Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`
767
+ );
768
+ }
769
+
770
+ // If we have the value, set it on the target object
771
+ if (!isDeferredValue) {
772
+ assignValue(currentDest, name, value);
773
+ }
774
+ }
775
+
776
+ // Check if we have any frames left on the stack, if we do then we had a malformed document
777
+ if (currentFrame !== null) {
778
+ throw new BSONError('corrupted bson, more objects expected based on the current document size');
779
+ }
780
+ const object = rootObject;
781
+
782
+ // Check if the deserialization was against a valid array/object
783
+ if (size !== index - startIndex) {
784
+ if (isArray) throw new BSONError('corrupt array bson');
785
+ throw new BSONError('corrupt object bson');
786
+ }
787
+
788
+ // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef
789
+ if (!isPossibleDBRef) return object;
790
+
791
+ // If the object is DBRef-like, create a new DBRef instance
792
+ return toPotentialDbRef(object);
793
+ }
gateway/node_modules/bson/src/parser/on_demand/index.ts ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { ByteUtils } from '../../utils/byte_utils';
2
+ import { NumberUtils } from '../../utils/number_utils';
3
+ import { type BSONElement, parseToElements } from './parse_to_elements';
4
+ /**
5
+ * @experimental
6
+ * @public
7
+ *
8
+ * A new set of BSON APIs that are currently experimental and not intended for production use.
9
+ */
10
+ export type OnDemand = {
11
+ parseToElements: (this: void, bytes: Uint8Array, startOffset?: number) => Iterable<BSONElement>;
12
+ // Types
13
+ BSONElement: BSONElement;
14
+
15
+ // Utils
16
+ ByteUtils: ByteUtils;
17
+ NumberUtils: NumberUtils;
18
+ };
19
+
20
+ /**
21
+ * @experimental
22
+ * @public
23
+ */
24
+ const onDemand: OnDemand = Object.create(null);
25
+
26
+ onDemand.parseToElements = parseToElements;
27
+ onDemand.ByteUtils = ByteUtils;
28
+ onDemand.NumberUtils = NumberUtils;
29
+
30
+ Object.freeze(onDemand);
31
+
32
+ export { onDemand };
gateway/node_modules/bson/src/parser/on_demand/parse_to_elements.ts ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { BSONOffsetError } from '../../error';
2
+ import { NumberUtils } from '../../utils/number_utils';
3
+
4
+ /**
5
+ * @internal
6
+ *
7
+ * @remarks
8
+ * - This enum is const so the code we produce will inline the numbers
9
+ * - `minKey` is set to 255 so unsigned comparisons succeed
10
+ * - Modify with caution, double check the bundle contains literals
11
+ */
12
+ const BSONElementType = {
13
+ double: 1,
14
+ string: 2,
15
+ object: 3,
16
+ array: 4,
17
+ binData: 5,
18
+ undefined: 6,
19
+ objectId: 7,
20
+ bool: 8,
21
+ date: 9,
22
+ null: 10,
23
+ regex: 11,
24
+ dbPointer: 12,
25
+ javascript: 13,
26
+ symbol: 14,
27
+ javascriptWithScope: 15,
28
+ int: 16,
29
+ timestamp: 17,
30
+ long: 18,
31
+ decimal: 19,
32
+ minKey: 255,
33
+ maxKey: 127
34
+ } as const;
35
+
36
+ type BSONElementType = (typeof BSONElementType)[keyof typeof BSONElementType];
37
+
38
+ /**
39
+ * @public
40
+ * @experimental
41
+ */
42
+ export type BSONElement = [
43
+ type: number,
44
+ nameOffset: number,
45
+ nameLength: number,
46
+ offset: number,
47
+ length: number
48
+ ];
49
+
50
+ function getSize(source: Uint8Array, offset: number) {
51
+ try {
52
+ return NumberUtils.getNonnegativeInt32LE(source, offset);
53
+ } catch (cause) {
54
+ throw new BSONOffsetError('BSON size cannot be negative', offset, { cause });
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Searches for null terminator of a BSON element's value (Never the document null terminator)
60
+ * **Does not** bounds check since this should **ONLY** be used within parseToElements which has asserted that `bytes` ends with a `0x00`.
61
+ * So this will at most iterate to the document's terminator and error if that is the offset reached.
62
+ */
63
+ function findNull(bytes: Uint8Array, offset: number): number {
64
+ let nullTerminatorOffset = offset;
65
+
66
+ for (; bytes[nullTerminatorOffset] !== 0x00; nullTerminatorOffset++);
67
+
68
+ if (nullTerminatorOffset === bytes.length - 1) {
69
+ // We reached the null terminator of the document, not a value's
70
+ throw new BSONOffsetError('Null terminator not found', offset);
71
+ }
72
+
73
+ return nullTerminatorOffset;
74
+ }
75
+
76
+ /**
77
+ * @public
78
+ * @experimental
79
+ */
80
+ export function parseToElements(
81
+ bytes: Uint8Array,
82
+ startOffset: number | null = 0
83
+ ): Iterable<BSONElement> {
84
+ startOffset ??= 0;
85
+
86
+ if (bytes.length < 5) {
87
+ throw new BSONOffsetError(
88
+ `Input must be at least 5 bytes, got ${bytes.length} bytes`,
89
+ startOffset
90
+ );
91
+ }
92
+
93
+ const documentSize = getSize(bytes, startOffset);
94
+
95
+ if (documentSize > bytes.length - startOffset) {
96
+ throw new BSONOffsetError(
97
+ `Parsed documentSize (${documentSize} bytes) does not match input length (${bytes.length} bytes)`,
98
+ startOffset
99
+ );
100
+ }
101
+
102
+ if (bytes[startOffset + documentSize - 1] !== 0x00) {
103
+ throw new BSONOffsetError('BSON documents must end in 0x00', startOffset + documentSize);
104
+ }
105
+
106
+ const elements: BSONElement[] = [];
107
+ let offset = startOffset + 4;
108
+
109
+ while (offset <= documentSize + startOffset) {
110
+ const type = bytes[offset];
111
+ offset += 1;
112
+
113
+ if (type === 0) {
114
+ if (offset - startOffset !== documentSize) {
115
+ throw new BSONOffsetError(`Invalid 0x00 type byte`, offset);
116
+ }
117
+ break;
118
+ }
119
+
120
+ const nameOffset = offset;
121
+ const nameLength = findNull(bytes, offset) - nameOffset;
122
+ offset += nameLength + 1;
123
+
124
+ let length: number;
125
+
126
+ if (
127
+ type === BSONElementType.double ||
128
+ type === BSONElementType.long ||
129
+ type === BSONElementType.date ||
130
+ type === BSONElementType.timestamp
131
+ ) {
132
+ length = 8;
133
+ } else if (type === BSONElementType.int) {
134
+ length = 4;
135
+ } else if (type === BSONElementType.objectId) {
136
+ length = 12;
137
+ } else if (type === BSONElementType.decimal) {
138
+ length = 16;
139
+ } else if (type === BSONElementType.bool) {
140
+ length = 1;
141
+ } else if (
142
+ type === BSONElementType.null ||
143
+ type === BSONElementType.undefined ||
144
+ type === BSONElementType.maxKey ||
145
+ type === BSONElementType.minKey
146
+ ) {
147
+ length = 0;
148
+ }
149
+ // Needs a size calculation
150
+ else if (type === BSONElementType.regex) {
151
+ length = findNull(bytes, findNull(bytes, offset) + 1) + 1 - offset;
152
+ } else if (
153
+ type === BSONElementType.object ||
154
+ type === BSONElementType.array ||
155
+ type === BSONElementType.javascriptWithScope
156
+ ) {
157
+ length = getSize(bytes, offset);
158
+ } else if (
159
+ type === BSONElementType.string ||
160
+ type === BSONElementType.binData ||
161
+ type === BSONElementType.dbPointer ||
162
+ type === BSONElementType.javascript ||
163
+ type === BSONElementType.symbol
164
+ ) {
165
+ length = getSize(bytes, offset) + 4;
166
+ if (type === BSONElementType.binData) {
167
+ // binary subtype
168
+ length += 1;
169
+ }
170
+ if (type === BSONElementType.dbPointer) {
171
+ // dbPointer's objectId
172
+ length += 12;
173
+ }
174
+ } else {
175
+ throw new BSONOffsetError(
176
+ `Invalid 0x${type.toString(16).padStart(2, '0')} type byte`,
177
+ offset
178
+ );
179
+ }
180
+
181
+ if (length > documentSize) {
182
+ throw new BSONOffsetError('value reports length larger than document', offset);
183
+ }
184
+
185
+ elements.push([type, nameOffset, nameLength, offset, length]);
186
+ offset += length;
187
+ }
188
+
189
+ return elements;
190
+ }
gateway/node_modules/bson/src/parser/serializer.ts ADDED
@@ -0,0 +1,748 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Binary, validateBinaryVector } from '../binary';
2
+ import type { BSONSymbol, DBRef, Document, MaxKey } from '../bson';
3
+ import { bsonType } from '../bson_value';
4
+ import type { Code } from '../code';
5
+ import * as constants from '../constants';
6
+ import type { Decimal128 } from '../decimal128';
7
+ import type { Double } from '../double';
8
+ import { BSONError, BSONVersionError } from '../error';
9
+ import type { Int32 } from '../int_32';
10
+ import { Long } from '../long';
11
+ import type { MinKey } from '../min_key';
12
+ import type { ObjectId } from '../objectid';
13
+ import type { BSONRegExp } from '../regexp';
14
+ import { ByteUtils } from '../utils/byte_utils';
15
+ import { NumberUtils } from '../utils/number_utils';
16
+ import { isAnyArrayBuffer, isDate, isMap, isRegExp, isUint8Array } from './utils';
17
+
18
+ /** @public */
19
+ export interface SerializeOptions {
20
+ /**
21
+ * the serializer will check if keys are valid.
22
+ * @defaultValue `false`
23
+ */
24
+ checkKeys?: boolean;
25
+ /**
26
+ * serialize the javascript functions
27
+ * @defaultValue `false`
28
+ */
29
+ serializeFunctions?: boolean;
30
+ /**
31
+ * serialize will not emit undefined fields
32
+ * note that the driver sets this to `false`
33
+ * @defaultValue `true`
34
+ */
35
+ ignoreUndefined?: boolean;
36
+ /** @internal Resize internal buffer */
37
+ minInternalBufferSize?: number;
38
+ /**
39
+ * the index in the buffer where we wish to start serializing into
40
+ * @defaultValue `0`
41
+ */
42
+ index?: number;
43
+ }
44
+
45
+ const regexp = /\x00/; // eslint-disable-line no-control-regex
46
+ const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']);
47
+
48
+ function serializeString(buffer: Uint8Array, key: string, value: string, index: number) {
49
+ // Encode String type
50
+ buffer[index++] = constants.BSON_DATA_STRING;
51
+ // Number of written bytes
52
+ const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
53
+ // Encode the name
54
+ index = index + numberOfWrittenBytes + 1;
55
+ buffer[index - 1] = 0;
56
+ // Write the string
57
+ const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4);
58
+ // Write the size of the string to buffer
59
+ NumberUtils.setInt32LE(buffer, index, size + 1);
60
+ // Update index
61
+ index = index + 4 + size;
62
+ // Write zero
63
+ buffer[index++] = 0;
64
+ return index;
65
+ }
66
+
67
+ function serializeNumber(buffer: Uint8Array, key: string, value: number, index: number) {
68
+ const isNegativeZero = Object.is(value, -0);
69
+
70
+ const type =
71
+ !isNegativeZero &&
72
+ Number.isSafeInteger(value) &&
73
+ value <= constants.BSON_INT32_MAX &&
74
+ value >= constants.BSON_INT32_MIN
75
+ ? constants.BSON_DATA_INT
76
+ : constants.BSON_DATA_NUMBER;
77
+
78
+ buffer[index++] = type;
79
+
80
+ const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
81
+ index = index + numberOfWrittenBytes;
82
+ buffer[index++] = 0x00;
83
+
84
+ if (type === constants.BSON_DATA_INT) {
85
+ index += NumberUtils.setInt32LE(buffer, index, value);
86
+ } else {
87
+ index += NumberUtils.setFloat64LE(buffer, index, value);
88
+ }
89
+
90
+ return index;
91
+ }
92
+
93
+ function serializeBigInt(buffer: Uint8Array, key: string, value: bigint, index: number) {
94
+ buffer[index++] = constants.BSON_DATA_LONG;
95
+ // Number of written bytes
96
+ const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
97
+ // Encode the name
98
+ index += numberOfWrittenBytes;
99
+ buffer[index++] = 0;
100
+
101
+ index += NumberUtils.setBigInt64LE(buffer, index, value);
102
+
103
+ return index;
104
+ }
105
+
106
+ function serializeNull(buffer: Uint8Array, key: string, _: unknown, index: number) {
107
+ // Set long type
108
+ buffer[index++] = constants.BSON_DATA_NULL;
109
+
110
+ // Number of written bytes
111
+ const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
112
+
113
+ // Encode the name
114
+ index = index + numberOfWrittenBytes;
115
+ buffer[index++] = 0;
116
+ return index;
117
+ }
118
+
119
+ function serializeBoolean(buffer: Uint8Array, key: string, value: boolean, index: number) {
120
+ // Write the type
121
+ buffer[index++] = constants.BSON_DATA_BOOLEAN;
122
+ // Number of written bytes
123
+ const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
124
+ // Encode the name
125
+ index = index + numberOfWrittenBytes;
126
+ buffer[index++] = 0;
127
+ // Encode the boolean value
128
+ buffer[index++] = value ? 1 : 0;
129
+ return index;
130
+ }
131
+
132
+ function serializeDate(buffer: Uint8Array, key: string, value: Date, index: number) {
133
+ // Write the type
134
+ buffer[index++] = constants.BSON_DATA_DATE;
135
+ // Number of written bytes
136
+ const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
137
+ // Encode the name
138
+ index = index + numberOfWrittenBytes;
139
+ buffer[index++] = 0;
140
+
141
+ // Write the date
142
+ const dateInMilis = Long.fromNumber(value.getTime());
143
+ const lowBits = dateInMilis.getLowBits();
144
+ const highBits = dateInMilis.getHighBits();
145
+ // Encode low bits
146
+ index += NumberUtils.setInt32LE(buffer, index, lowBits);
147
+ // Encode high bits
148
+ index += NumberUtils.setInt32LE(buffer, index, highBits);
149
+ return index;
150
+ }
151
+
152
+ function serializeRegExp(buffer: Uint8Array, key: string, value: RegExp, index: number) {
153
+ // Write the type
154
+ buffer[index++] = constants.BSON_DATA_REGEXP;
155
+ // Number of written bytes
156
+ const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
157
+
158
+ // Encode the name
159
+ index = index + numberOfWrittenBytes;
160
+ buffer[index++] = 0;
161
+ if (value.source && value.source.match(regexp) != null) {
162
+ throw new BSONError('value ' + value.source + ' must not contain null bytes');
163
+ }
164
+ // Adjust the index
165
+ index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index);
166
+ // Write zero
167
+ buffer[index++] = 0x00;
168
+ // Write the parameters
169
+ if (value.ignoreCase) buffer[index++] = 0x69; // i
170
+ if (value.global) buffer[index++] = 0x73; // s
171
+ if (value.multiline) buffer[index++] = 0x6d; // m
172
+
173
+ // Add ending zero
174
+ buffer[index++] = 0x00;
175
+ return index;
176
+ }
177
+
178
+ function serializeBSONRegExp(buffer: Uint8Array, key: string, value: BSONRegExp, index: number) {
179
+ // Write the type
180
+ buffer[index++] = constants.BSON_DATA_REGEXP;
181
+ // Number of written bytes
182
+ const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
183
+ // Encode the name
184
+ index = index + numberOfWrittenBytes;
185
+ buffer[index++] = 0;
186
+
187
+ // Check the pattern for 0 bytes
188
+ if (value.pattern.match(regexp) != null) {
189
+ // The BSON spec doesn't allow keys with null bytes because keys are
190
+ // null-terminated.
191
+ throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes');
192
+ }
193
+
194
+ // Adjust the index
195
+ index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index);
196
+ // Write zero
197
+ buffer[index++] = 0x00;
198
+ // Write the options
199
+ const sortedOptions = value.options.split('').sort().join('');
200
+ index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index);
201
+ // Add ending zero
202
+ buffer[index++] = 0x00;
203
+ return index;
204
+ }
205
+
206
+ function serializeMinMax(buffer: Uint8Array, key: string, value: MinKey | MaxKey, index: number) {
207
+ // Write the type of either min or max key
208
+ if (value === null) {
209
+ buffer[index++] = constants.BSON_DATA_NULL;
210
+ } else if (value[bsonType] === 'MinKey') {
211
+ buffer[index++] = constants.BSON_DATA_MIN_KEY;
212
+ } else {
213
+ buffer[index++] = constants.BSON_DATA_MAX_KEY;
214
+ }
215
+
216
+ // Number of written bytes
217
+ const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
218
+ // Encode the name
219
+ index = index + numberOfWrittenBytes;
220
+ buffer[index++] = 0;
221
+ return index;
222
+ }
223
+
224
+ function serializeObjectId(buffer: Uint8Array, key: string, value: ObjectId, index: number) {
225
+ // Write the type
226
+ buffer[index++] = constants.BSON_DATA_OID;
227
+ // Number of written bytes
228
+ const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
229
+
230
+ // Encode the name
231
+ index = index + numberOfWrittenBytes;
232
+ buffer[index++] = 0;
233
+
234
+ index += value.serializeInto(buffer, index);
235
+
236
+ // Adjust index
237
+ return index;
238
+ }
239
+
240
+ function serializeBuffer(buffer: Uint8Array, key: string, value: Uint8Array, index: number) {
241
+ // Write the type
242
+ buffer[index++] = constants.BSON_DATA_BINARY;
243
+ // Number of written bytes
244
+ const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
245
+ // Encode the name
246
+ index = index + numberOfWrittenBytes;
247
+ buffer[index++] = 0;
248
+ // Get size of the buffer (current write point)
249
+ const size = value.length;
250
+ // Write the size of the string to buffer
251
+ index += NumberUtils.setInt32LE(buffer, index, size);
252
+ // Write the default subtype
253
+ buffer[index++] = constants.BSON_BINARY_SUBTYPE_DEFAULT;
254
+ // Copy the content form the binary field to the buffer
255
+ if (size <= 16) {
256
+ for (let i = 0; i < size; i++) buffer[index + i] = value[i];
257
+ } else {
258
+ buffer.set(value, index);
259
+ }
260
+ // Adjust the index
261
+ index = index + size;
262
+ return index;
263
+ }
264
+
265
+ function serializeDecimal128(buffer: Uint8Array, key: string, value: Decimal128, index: number) {
266
+ buffer[index++] = constants.BSON_DATA_DECIMAL128;
267
+ // Number of written bytes
268
+ const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
269
+ // Encode the name
270
+ index = index + numberOfWrittenBytes;
271
+ buffer[index++] = 0;
272
+ // Write the data from the value
273
+ for (let i = 0; i < 16; i++) buffer[index + i] = value.bytes[i];
274
+ return index + 16;
275
+ }
276
+
277
+ function serializeLong(buffer: Uint8Array, key: string, value: Long, index: number) {
278
+ // Write the type
279
+ buffer[index++] =
280
+ value[bsonType] === 'Long' ? constants.BSON_DATA_LONG : constants.BSON_DATA_TIMESTAMP;
281
+ // Number of written bytes
282
+ const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
283
+ // Encode the name
284
+ index = index + numberOfWrittenBytes;
285
+ buffer[index++] = 0;
286
+ // Write the date
287
+ const lowBits = value.getLowBits();
288
+ const highBits = value.getHighBits();
289
+ // Encode low bits
290
+ index += NumberUtils.setInt32LE(buffer, index, lowBits);
291
+ // Encode high bits
292
+ index += NumberUtils.setInt32LE(buffer, index, highBits);
293
+ return index;
294
+ }
295
+
296
+ function serializeInt32(buffer: Uint8Array, key: string, value: Int32 | number, index: number) {
297
+ value = value.valueOf();
298
+ // Set int type 32 bits or less
299
+ buffer[index++] = constants.BSON_DATA_INT;
300
+ // Number of written bytes
301
+ const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
302
+ // Encode the name
303
+ index = index + numberOfWrittenBytes;
304
+ buffer[index++] = 0;
305
+ // Write the int value
306
+ index += NumberUtils.setInt32LE(buffer, index, value);
307
+ return index;
308
+ }
309
+
310
+ function serializeDouble(buffer: Uint8Array, key: string, value: Double, index: number) {
311
+ // Encode as double
312
+ buffer[index++] = constants.BSON_DATA_NUMBER;
313
+
314
+ // Number of written bytes
315
+ const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
316
+
317
+ // Encode the name
318
+ index = index + numberOfWrittenBytes;
319
+ buffer[index++] = 0;
320
+
321
+ // Write float
322
+ index += NumberUtils.setFloat64LE(buffer, index, value.value);
323
+
324
+ return index;
325
+ }
326
+
327
+ function serializeFunction(buffer: Uint8Array, key: string, value: Function, index: number) {
328
+ buffer[index++] = constants.BSON_DATA_CODE;
329
+ // Number of written bytes
330
+ const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
331
+ // Encode the name
332
+ index = index + numberOfWrittenBytes;
333
+ buffer[index++] = 0;
334
+ // Function string
335
+ const functionString = value.toString();
336
+
337
+ // Write the string
338
+ const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
339
+ // Write the size of the string to buffer
340
+ NumberUtils.setInt32LE(buffer, index, size);
341
+ // Update index
342
+ index = index + 4 + size - 1;
343
+ // Write zero
344
+ buffer[index++] = 0;
345
+ return index;
346
+ }
347
+
348
+ function serializeBinary(buffer: Uint8Array, key: string, value: Binary, index: number) {
349
+ // Write the type
350
+ buffer[index++] = constants.BSON_DATA_BINARY;
351
+ // Number of written bytes
352
+ const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
353
+ // Encode the name
354
+ index = index + numberOfWrittenBytes;
355
+ buffer[index++] = 0;
356
+ // Extract the buffer
357
+ const data = value.buffer;
358
+ // Calculate size
359
+ let size = value.position;
360
+ // Add the deprecated 02 type 4 bytes of size to total
361
+ if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4;
362
+ // Write the size of the string to buffer
363
+ index += NumberUtils.setInt32LE(buffer, index, size);
364
+ // Write the subtype to the buffer
365
+ buffer[index++] = value.sub_type;
366
+
367
+ // If we have binary type 2 the 4 first bytes are the size
368
+ if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
369
+ size = size - 4;
370
+ index += NumberUtils.setInt32LE(buffer, index, size);
371
+ }
372
+
373
+ if (value.sub_type === Binary.SUBTYPE_VECTOR) {
374
+ validateBinaryVector(value);
375
+ }
376
+
377
+ if (size <= 16) {
378
+ for (let i = 0; i < size; i++) buffer[index + i] = data[i];
379
+ } else {
380
+ buffer.set(data, index);
381
+ }
382
+ // Adjust the index
383
+ index = index + value.position;
384
+ return index;
385
+ }
386
+
387
+ function serializeSymbol(buffer: Uint8Array, key: string, value: BSONSymbol, index: number) {
388
+ // Write the type
389
+ buffer[index++] = constants.BSON_DATA_SYMBOL;
390
+ // Number of written bytes
391
+ const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
392
+ // Encode the name
393
+ index = index + numberOfWrittenBytes;
394
+ buffer[index++] = 0;
395
+ // Write the string
396
+ const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 1;
397
+ // Write the size of the string to buffer
398
+ NumberUtils.setInt32LE(buffer, index, size);
399
+ // Update index
400
+ index = index + 4 + size - 1;
401
+ // Write zero
402
+ buffer[index++] = 0;
403
+ return index;
404
+ }
405
+
406
+ interface SerializationFrame {
407
+ /** Original object passed to this frame — used for cycle-detection (path.delete). */
408
+ sourceObject: Document;
409
+ /** True when serializing a BSON array; affects key format and type byte. */
410
+ isArray: boolean;
411
+ /** Buffer offset where this object's 4-byte size field will be written. */
412
+ objectSizeIndex: number;
413
+ /** Buffer offset for code-with-scope wrapper size, or null if not applicable. */
414
+ codeSizeIndex: number | null;
415
+ /**
416
+ * Object being iterated. For plain objects this may be the toBSON() result of
417
+ * sourceObject; for arrays and Maps it equals sourceObject.
418
+ */
419
+ iterTarget: Document;
420
+ /**
421
+ * Pre-computed Object.keys() of iterTarget for plain objects.
422
+ * Null for arrays (use keyIndex as numeric index) and Maps (use mapIterator).
423
+ */
424
+ keys: string[] | null;
425
+ /** Next index into keys[] for plain objects, or next array index for arrays. */
426
+ keyIndex: number;
427
+ /** Active iterator for Map objects; null for arrays and plain objects. */
428
+ mapIterator: IterableIterator<[unknown, unknown]> | null;
429
+ /** The enclosing frame, or null at the root. The stack is a linked list via this field. */
430
+ prev: SerializationFrame | null;
431
+ /** Whether to validate keys for this frame's document (may differ from caller, e.g. DBRef uses false). */
432
+ checkKeys: boolean;
433
+ /** Whether undefined values are skipped (may differ from caller, e.g. DBRef uses true). */
434
+ ignoreUndefined: boolean;
435
+ }
436
+
437
+ function makeFrame(
438
+ sourceObject: Document,
439
+ objectSizeIndex: number,
440
+ codeSizeIndex: number | null,
441
+ prev: SerializationFrame | null,
442
+ checkKeys: boolean,
443
+ ignoreUndefined: boolean
444
+ ): SerializationFrame {
445
+ if (Array.isArray(sourceObject)) {
446
+ return {
447
+ sourceObject,
448
+ isArray: true,
449
+ objectSizeIndex,
450
+ codeSizeIndex,
451
+ iterTarget: sourceObject,
452
+ keys: null,
453
+ keyIndex: 0,
454
+ mapIterator: null,
455
+ prev,
456
+ checkKeys,
457
+ ignoreUndefined
458
+ };
459
+ }
460
+ if (sourceObject instanceof Map || isMap(sourceObject)) {
461
+ return {
462
+ sourceObject,
463
+ isArray: false,
464
+ objectSizeIndex,
465
+ codeSizeIndex,
466
+ iterTarget: sourceObject,
467
+ keys: null,
468
+ keyIndex: 0,
469
+ mapIterator: (sourceObject as Map<unknown, unknown>).entries(),
470
+ prev,
471
+ checkKeys,
472
+ ignoreUndefined
473
+ };
474
+ }
475
+ // Plain object: call toBSON() if defined to obtain the object to iterate.
476
+ let target: Document = sourceObject;
477
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
478
+ if (typeof (target as any)?.toBSON === 'function') {
479
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
480
+ target = (target as any).toBSON() as Document;
481
+ if (target != null && typeof target !== 'object') {
482
+ throw new BSONError('toBSON function did not return an object');
483
+ }
484
+ }
485
+ return {
486
+ sourceObject,
487
+ isArray: false,
488
+ objectSizeIndex,
489
+ codeSizeIndex,
490
+ iterTarget: target,
491
+ keys: Object.keys(target as object),
492
+ keyIndex: 0,
493
+ mapIterator: null,
494
+ prev,
495
+ checkKeys,
496
+ ignoreUndefined
497
+ };
498
+ }
499
+
500
+ export function serializeInto(
501
+ buffer: Uint8Array,
502
+ object: Document,
503
+ checkKeys: boolean,
504
+ startingIndex: number,
505
+ serializeFunctions: boolean,
506
+ ignoreUndefined: boolean,
507
+ path: Set<Document> | null
508
+ ): number {
509
+ if (path == null) {
510
+ // We are at the root input
511
+ if (object == null) {
512
+ // ONLY the root should turn into an empty document
513
+ // BSON Empty document has a size of 5 (LE)
514
+ buffer[0] = 0x05;
515
+ buffer[1] = 0x00;
516
+ buffer[2] = 0x00;
517
+ buffer[3] = 0x00;
518
+ // All documents end with null terminator
519
+ buffer[4] = 0x00;
520
+ return 5;
521
+ }
522
+
523
+ if (Array.isArray(object)) {
524
+ throw new BSONError('serialize does not support an array as the root input');
525
+ }
526
+ if (typeof object !== 'object') {
527
+ throw new BSONError('serialize does not support non-object as the root input');
528
+ } else if ('_bsontype' in object && typeof object._bsontype === 'string') {
529
+ throw new BSONError(`BSON types cannot be serialized as a document`);
530
+ } else if (
531
+ isDate(object) ||
532
+ isRegExp(object) ||
533
+ isUint8Array(object) ||
534
+ isAnyArrayBuffer(object)
535
+ ) {
536
+ throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`);
537
+ }
538
+
539
+ path = new Set();
540
+ }
541
+
542
+ path.add(object);
543
+
544
+ let currentFrame: SerializationFrame | null = makeFrame(
545
+ object,
546
+ startingIndex,
547
+ null,
548
+ null,
549
+ checkKeys,
550
+ ignoreUndefined
551
+ );
552
+ let index = startingIndex + 4;
553
+
554
+ while (currentFrame !== null) {
555
+ const frame: SerializationFrame = currentFrame;
556
+
557
+ // Advance to the next key-value pair, or finalize the frame if exhausted.
558
+ let key: string;
559
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
560
+ let value: any;
561
+ if (frame.mapIterator !== null) {
562
+ const next = frame.mapIterator.next();
563
+ if (next.done) {
564
+ buffer[index++] = 0x00;
565
+ NumberUtils.setInt32LE(buffer, frame.objectSizeIndex, index - frame.objectSizeIndex);
566
+ if (frame.codeSizeIndex !== null) {
567
+ NumberUtils.setInt32LE(buffer, frame.codeSizeIndex, index - frame.codeSizeIndex);
568
+ }
569
+ path.delete(frame.sourceObject);
570
+ currentFrame = frame.prev;
571
+ continue;
572
+ }
573
+ key = next.value[0] as string;
574
+ value = next.value[1];
575
+ } else if (frame.keys !== null) {
576
+ if (frame.keyIndex >= frame.keys.length) {
577
+ buffer[index++] = 0x00;
578
+ NumberUtils.setInt32LE(buffer, frame.objectSizeIndex, index - frame.objectSizeIndex);
579
+ if (frame.codeSizeIndex !== null) {
580
+ NumberUtils.setInt32LE(buffer, frame.codeSizeIndex, index - frame.codeSizeIndex);
581
+ }
582
+ path.delete(frame.sourceObject);
583
+ currentFrame = frame.prev;
584
+ continue;
585
+ }
586
+ key = frame.keys[frame.keyIndex++];
587
+ value = (frame.iterTarget as Record<string, unknown>)[key];
588
+ } else {
589
+ // Array: use keyIndex as the numeric index.
590
+ const arr = frame.iterTarget as unknown[];
591
+ if (frame.keyIndex >= arr.length) {
592
+ buffer[index++] = 0x00;
593
+ NumberUtils.setInt32LE(buffer, frame.objectSizeIndex, index - frame.objectSizeIndex);
594
+ if (frame.codeSizeIndex !== null) {
595
+ NumberUtils.setInt32LE(buffer, frame.codeSizeIndex, index - frame.codeSizeIndex);
596
+ }
597
+ path.delete(frame.sourceObject);
598
+ currentFrame = frame.prev;
599
+ continue;
600
+ }
601
+ const i = frame.keyIndex++;
602
+ key = String(i);
603
+ value = arr[i];
604
+ }
605
+
606
+ if (typeof value?.toBSON === 'function') {
607
+ value = value.toBSON();
608
+ }
609
+
610
+ if (!frame.isArray && typeof key === 'string' && !(key[0] === '$' && ignoreKeys.has(key))) {
611
+ if (regexp.test(key)) {
612
+ throw new BSONError('key ' + key + ' must not contain null bytes');
613
+ }
614
+ if (frame.checkKeys) {
615
+ if ('$' === key[0]) {
616
+ throw new BSONError('key ' + key + " must not start with '$'");
617
+ } else if (key.includes('.')) {
618
+ throw new BSONError('key ' + key + " must not contain '.'");
619
+ }
620
+ }
621
+ }
622
+
623
+ const type = typeof value;
624
+
625
+ if (value === undefined) {
626
+ if (frame.isArray || frame.ignoreUndefined === false) {
627
+ index = serializeNull(buffer, key, value, index);
628
+ }
629
+ } else if (value === null) {
630
+ index = serializeNull(buffer, key, value, index);
631
+ } else if (type === 'string') {
632
+ index = serializeString(buffer, key, value, index);
633
+ } else if (type === 'number') {
634
+ index = serializeNumber(buffer, key, value, index);
635
+ } else if (type === 'bigint') {
636
+ index = serializeBigInt(buffer, key, value, index);
637
+ } else if (type === 'boolean') {
638
+ index = serializeBoolean(buffer, key, value, index);
639
+ } else if (type === 'object' && value._bsontype == null) {
640
+ if (value instanceof Date || isDate(value)) {
641
+ index = serializeDate(buffer, key, value, index);
642
+ } else if (value instanceof Uint8Array || isUint8Array(value)) {
643
+ index = serializeBuffer(buffer, key, value, index);
644
+ } else if (value instanceof RegExp || isRegExp(value)) {
645
+ index = serializeRegExp(buffer, key, value, index);
646
+ } else {
647
+ if (path.has(value)) {
648
+ throw new BSONError('Cannot convert circular structure to BSON');
649
+ }
650
+ const nestedIsArray = Array.isArray(value);
651
+ buffer[index++] = nestedIsArray ? constants.BSON_DATA_ARRAY : constants.BSON_DATA_OBJECT;
652
+ index += ByteUtils.encodeUTF8Into(buffer, key, index);
653
+ buffer[index++] = 0x00;
654
+ const nestedStartIndex = index;
655
+ path.add(value);
656
+ currentFrame = makeFrame(
657
+ value,
658
+ nestedStartIndex,
659
+ null,
660
+ frame,
661
+ frame.checkKeys,
662
+ frame.ignoreUndefined
663
+ );
664
+ index += 4;
665
+ }
666
+ } else if (type === 'object') {
667
+ if (value[constants.BSON_VERSION_SYMBOL] !== constants.BSON_MAJOR_VERSION) {
668
+ throw new BSONVersionError();
669
+ }
670
+ const tag = value[bsonType];
671
+ if (tag === 'ObjectId') {
672
+ index = serializeObjectId(buffer, key, value, index);
673
+ } else if (tag === 'Decimal128') {
674
+ index = serializeDecimal128(buffer, key, value, index);
675
+ } else if (tag === 'Long' || tag === 'Timestamp') {
676
+ index = serializeLong(buffer, key, value, index);
677
+ } else if (tag === 'Double') {
678
+ index = serializeDouble(buffer, key, value, index);
679
+ } else if (tag === 'Code') {
680
+ const codeValue = value as Code;
681
+ if (codeValue.scope && typeof codeValue.scope === 'object') {
682
+ buffer[index++] = constants.BSON_DATA_CODE_W_SCOPE;
683
+ index += ByteUtils.encodeUTF8Into(buffer, key, index);
684
+ buffer[index++] = 0x00;
685
+ const codeTotalSizeIndex = index;
686
+ index += 4;
687
+ const functionString = codeValue.code;
688
+ const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
689
+ NumberUtils.setInt32LE(buffer, index, codeSize);
690
+ buffer[index + 4 + codeSize - 1] = 0;
691
+ index = index + codeSize + 4;
692
+ const scope = codeValue.scope;
693
+ if (path.has(scope)) {
694
+ throw new BSONError('Cannot convert circular structure to BSON');
695
+ }
696
+ path.add(scope);
697
+ currentFrame = makeFrame(
698
+ scope,
699
+ index,
700
+ codeTotalSizeIndex,
701
+ frame,
702
+ frame.checkKeys,
703
+ frame.ignoreUndefined
704
+ );
705
+ index += 4;
706
+ } else {
707
+ buffer[index++] = constants.BSON_DATA_CODE;
708
+ index += ByteUtils.encodeUTF8Into(buffer, key, index);
709
+ buffer[index++] = 0x00;
710
+ const functionString = codeValue.code.toString();
711
+ const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
712
+ NumberUtils.setInt32LE(buffer, index, size);
713
+ index = index + 4 + size - 1;
714
+ buffer[index++] = 0;
715
+ }
716
+ } else if (tag === 'Binary') {
717
+ index = serializeBinary(buffer, key, value, index);
718
+ } else if (tag === 'BSONSymbol') {
719
+ index = serializeSymbol(buffer, key, value, index);
720
+ } else if (tag === 'DBRef') {
721
+ const dbref = value as DBRef;
722
+ const orderedValues: Document = Object.assign(
723
+ { $ref: dbref.collection, $id: dbref.oid },
724
+ dbref.db != null ? { $db: dbref.db } : null,
725
+ dbref.fields
726
+ );
727
+ buffer[index++] = constants.BSON_DATA_OBJECT;
728
+ index += ByteUtils.encodeUTF8Into(buffer, key, index);
729
+ buffer[index++] = 0x00;
730
+ path.add(orderedValues);
731
+ currentFrame = makeFrame(orderedValues, index, null, frame, false, true);
732
+ index += 4;
733
+ } else if (tag === 'BSONRegExp') {
734
+ index = serializeBSONRegExp(buffer, key, value, index);
735
+ } else if (tag === 'Int32') {
736
+ index = serializeInt32(buffer, key, value, index);
737
+ } else if (tag === 'MinKey' || tag === 'MaxKey') {
738
+ index = serializeMinMax(buffer, key, value, index);
739
+ } else if (typeof value._bsontype !== 'undefined') {
740
+ throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
741
+ }
742
+ } else if (type === 'function' && serializeFunctions) {
743
+ index = serializeFunction(buffer, key, value, index);
744
+ }
745
+ }
746
+
747
+ return index;
748
+ }
gateway/node_modules/bson/src/parser/utils.ts ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const TypedArrayPrototypeGetSymbolToStringTag = (() => {
2
+ // Type check system lovingly referenced from:
3
+ // https://github.com/nodejs/node/blob/7450332339ed40481f470df2a3014e2ec355d8d8/lib/internal/util/types.js#L13-L15
4
+ // eslint-disable-next-line @typescript-eslint/unbound-method -- the intention is to call this method with a bound value
5
+ const g = Object.getOwnPropertyDescriptor(
6
+ Object.getPrototypeOf(Uint8Array.prototype),
7
+ Symbol.toStringTag
8
+ )!.get!;
9
+
10
+ return (value: unknown) => g.call(value);
11
+ })();
12
+
13
+ export function isUint8Array(value: unknown): value is Uint8Array {
14
+ return TypedArrayPrototypeGetSymbolToStringTag(value) === 'Uint8Array';
15
+ }
16
+
17
+ export function isAnyArrayBuffer(value: unknown): value is ArrayBuffer {
18
+ return (
19
+ typeof value === 'object' &&
20
+ value != null &&
21
+ Symbol.toStringTag in value &&
22
+ (value[Symbol.toStringTag] === 'ArrayBuffer' ||
23
+ value[Symbol.toStringTag] === 'SharedArrayBuffer')
24
+ );
25
+ }
26
+
27
+ export function isRegExp(regexp: unknown): regexp is RegExp {
28
+ return regexp instanceof RegExp || Object.prototype.toString.call(regexp) === '[object RegExp]';
29
+ }
30
+
31
+ export function isMap(value: unknown): value is Map<unknown, unknown> {
32
+ return (
33
+ typeof value === 'object' &&
34
+ value != null &&
35
+ Symbol.toStringTag in value &&
36
+ value[Symbol.toStringTag] === 'Map'
37
+ );
38
+ }
39
+
40
+ export function isDate(date: unknown): date is Date {
41
+ return date instanceof Date || Object.prototype.toString.call(date) === '[object Date]';
42
+ }
43
+
44
+ export type InspectFn = (x: unknown, options?: unknown) => string;
45
+ export function defaultInspect(x: unknown, _options?: unknown): string {
46
+ return JSON.stringify(x, (k: string, v: unknown) => {
47
+ if (typeof v === 'bigint') {
48
+ return { $numberLong: `${v}` };
49
+ } else if (isMap(v)) {
50
+ return Object.fromEntries(v);
51
+ }
52
+ return v;
53
+ });
54
+ }
55
+
56
+ /** @internal */
57
+ type StylizeFunction = (x: string, style: string) => string;
58
+ /** @internal */
59
+ export function getStylizeFunction(options?: unknown): StylizeFunction | undefined {
60
+ const stylizeExists =
61
+ options != null &&
62
+ typeof options === 'object' &&
63
+ 'stylize' in options &&
64
+ typeof options.stylize === 'function';
65
+
66
+ if (stylizeExists) {
67
+ return options.stylize as StylizeFunction;
68
+ }
69
+ }
gateway/node_modules/bson/src/regexp.ts ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { BSONValue } from './bson_value';
2
+ import { BSONError } from './error';
3
+ import type { EJSONOptions } from './extended_json';
4
+ import { type InspectFn, defaultInspect, getStylizeFunction } from './parser/utils';
5
+
6
+ function alphabetize(str: string): string {
7
+ return str.split('').sort().join('');
8
+ }
9
+
10
+ /** @public */
11
+ export interface BSONRegExpExtendedLegacy {
12
+ $regex: string | BSONRegExp;
13
+ $options: string;
14
+ }
15
+
16
+ /** @public */
17
+ export interface BSONRegExpExtended {
18
+ $regularExpression: {
19
+ pattern: string;
20
+ options: string;
21
+ };
22
+ }
23
+
24
+ /**
25
+ * A class representation of the BSON RegExp type.
26
+ * @public
27
+ * @category BSONType
28
+ */
29
+ export class BSONRegExp extends BSONValue {
30
+ get _bsontype(): 'BSONRegExp' {
31
+ return 'BSONRegExp';
32
+ }
33
+
34
+ pattern!: string;
35
+ options!: string;
36
+ /**
37
+ * @param pattern - The regular expression pattern to match
38
+ * @param options - The regular expression options
39
+ */
40
+ constructor(pattern: string, options?: string) {
41
+ super();
42
+ this.pattern = pattern;
43
+ this.options = alphabetize(options ?? '');
44
+
45
+ if (this.pattern.indexOf('\x00') !== -1) {
46
+ throw new BSONError(
47
+ `BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`
48
+ );
49
+ }
50
+ if (this.options.indexOf('\x00') !== -1) {
51
+ throw new BSONError(
52
+ `BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`
53
+ );
54
+ }
55
+
56
+ // Validate options
57
+ for (let i = 0; i < this.options.length; i++) {
58
+ if (
59
+ !(
60
+ this.options[i] === 'i' ||
61
+ this.options[i] === 'm' ||
62
+ this.options[i] === 'x' ||
63
+ this.options[i] === 'l' ||
64
+ this.options[i] === 's' ||
65
+ this.options[i] === 'u'
66
+ )
67
+ ) {
68
+ throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`);
69
+ }
70
+ }
71
+ }
72
+
73
+ static parseOptions(options?: string): string {
74
+ return options ? options.split('').sort().join('') : '';
75
+ }
76
+
77
+ /** @internal */
78
+ toExtendedJSON(options?: EJSONOptions): BSONRegExpExtendedLegacy | BSONRegExpExtended {
79
+ options = options || {};
80
+ if (options.legacy) {
81
+ return { $regex: this.pattern, $options: this.options };
82
+ }
83
+ return { $regularExpression: { pattern: this.pattern, options: this.options } };
84
+ }
85
+
86
+ /** @internal */
87
+ static fromExtendedJSON(doc: BSONRegExpExtendedLegacy | BSONRegExpExtended): BSONRegExp {
88
+ if ('$regex' in doc) {
89
+ if (typeof doc.$regex !== 'string') {
90
+ // This is for $regex query operators that have extended json values.
91
+ if (doc.$regex._bsontype === 'BSONRegExp') {
92
+ return doc as unknown as BSONRegExp;
93
+ }
94
+ } else {
95
+ return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options));
96
+ }
97
+ }
98
+ if ('$regularExpression' in doc) {
99
+ return new BSONRegExp(
100
+ doc.$regularExpression.pattern,
101
+ BSONRegExp.parseOptions(doc.$regularExpression.options)
102
+ );
103
+ }
104
+ throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`);
105
+ }
106
+
107
+ inspect(depth?: number, options?: unknown, inspect?: InspectFn): string {
108
+ const stylize = getStylizeFunction(options) ?? (v => v);
109
+ inspect ??= defaultInspect;
110
+ const pattern = stylize(inspect(this.pattern), 'regexp');
111
+ const flags = stylize(inspect(this.options), 'regexp');
112
+ return `new BSONRegExp(${pattern}, ${flags})`;
113
+ }
114
+ }