diff --git a/.eslintrc.json b/.eslintrc.json index 404f9cffdd6..a1fad4ea222 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -1,6 +1,9 @@ { "root": true, "parser": "@typescript-eslint/parser", + "ignorePatterns": [ + "test/tools/runner/bundle/**" + ], "parserOptions": { "ecmaVersion": 2023 }, @@ -346,4 +349,4 @@ } } ] -} \ No newline at end of file +} diff --git a/.evergreen/config.yml b/.evergreen/config.yml index 08808893c0d..7eafc434994 100644 --- a/.evergreen/config.yml +++ b/.evergreen/config.yml @@ -3725,6 +3725,60 @@ buildvariants: - test-tls-support-5.0 - test-tls-support-4.4 - test-tls-support-4.2 + - name: rhel80-large-nodeless + display_name: rhel8 Nodeless + run_on: rhel80-large + expansions: + MONGODB_BUNDLED: true + NODE_LTS_VERSION: latest + CLIENT_ENCRYPTION: true + tasks: + - test-latest-server + - test-latest-replica_set + - test-latest-sharded_cluster + - test-rapid-server + - test-rapid-replica_set + - test-rapid-sharded_cluster + - test-8.0-server + - test-8.0-replica_set + - test-8.0-sharded_cluster + - test-7.0-server + - test-7.0-replica_set + - test-7.0-sharded_cluster + - test-6.0-server + - test-6.0-replica_set + - test-6.0-sharded_cluster + - test-5.0-server + - test-5.0-replica_set + - test-5.0-sharded_cluster + - test-4.4-server + - test-4.4-replica_set + - test-4.4-sharded_cluster + - test-4.2-server + - test-4.2-replica_set + - test-4.2-sharded_cluster + - test-latest-server-v1-api + - test-x509-authentication + - test-atlas-connectivity + - test-5.0-load-balanced + - test-6.0-load-balanced + - test-7.0-load-balanced + - test-8.0-load-balanced + - test-rapid-load-balanced + - test-latest-load-balanced + - test-auth-kerberos + - test-auth-ldap + - test-socks5-csfle + - test-socks5-tls + - test-snappy-compression + - test-zstd-compression + - test-tls-support-latest + - test-tls-support-8.0 + - test-tls-support-7.0 + - test-tls-support-6.0 + - test-tls-support-5.0 + - test-tls-support-4.4 + - test-tls-support-4.2 - name: windows-2022-latest-large-iron display_name: Windows Node20.19.0 run_on: windows-2022-latest-large @@ -3857,6 +3911,49 @@ buildvariants: - test-tls-support-5.0 - test-tls-support-4.4 - test-tls-support-4.2 + - name: windows-2022-latest-large-nodeless + display_name: Windows Nodeless + run_on: windows-2022-latest-large + expansions: + MONGODB_BUNDLED: true + NODE_LTS_VERSION: latest + CLIENT_ENCRYPTION: false + tasks: + - test-latest-server + - test-latest-replica_set + - test-latest-sharded_cluster + - test-rapid-server + - test-rapid-replica_set + - test-rapid-sharded_cluster + - test-8.0-server + - test-8.0-replica_set + - test-8.0-sharded_cluster + - test-7.0-server + - test-7.0-replica_set + - test-7.0-sharded_cluster + - test-6.0-server + - test-6.0-replica_set + - test-6.0-sharded_cluster + - test-5.0-server + - test-5.0-replica_set + - test-5.0-sharded_cluster + - test-4.4-server + - test-4.4-replica_set + - test-4.4-sharded_cluster + - test-4.2-server + - test-4.2-replica_set + - test-4.2-sharded_cluster + - test-latest-server-v1-api + - test-socks5-tls + - test-snappy-compression + - test-zstd-compression + - test-tls-support-latest + - test-tls-support-8.0 + - test-tls-support-7.0 + - test-tls-support-6.0 + - test-tls-support-5.0 + - test-tls-support-4.4 + - test-tls-support-4.2 - name: rhel8-node20.19.0-test-csfle-mongocryptd display_name: rhel 8 Node20.19.0 test mongocryptd run_on: rhel80-large diff --git a/.evergreen/generate_evergreen_tasks.js b/.evergreen/generate_evergreen_tasks.js index c18531b8679..3ea18211ba8 100644 --- a/.evergreen/generate_evergreen_tasks.js +++ b/.evergreen/generate_evergreen_tasks.js @@ -417,6 +417,20 @@ for (const { } BUILD_VARIANTS.push(buildVariantData); } + + // add Node-less variant + const buildVariantData = { + name: `${osName}-nodeless`, + display_name: `${osDisplayName} Nodeless`, + run_on, + expansions: { + MONGODB_BUNDLED: true, + NODE_LTS_VERSION: 'latest' + }, + tasks: tasks.map(({ name }) => name) + }; + buildVariantData.expansions.CLIENT_ENCRYPTION = clientEncryption; + BUILD_VARIANTS.push(buildVariantData); } // Running CSFLE tests with mongocryptd diff --git a/.evergreen/run-azure-kms-tests.sh b/.evergreen/run-azure-kms-tests.sh index c8818962d48..c0d56c92595 100644 --- a/.evergreen/run-azure-kms-tests.sh +++ b/.evergreen/run-azure-kms-tests.sh @@ -18,4 +18,6 @@ export MONGODB_URI="mongodb://localhost:27017" export EXPECTED_AZUREKMS_OUTCOME=${EXPECTED_AZUREKMS_OUTCOME:-omitted} export TEST_CSFLE=true +npm run build:bundle + npx mocha --config test/mocha_mongodb.js test/integration/client-side-encryption/client_side_encryption.prose.19.on_demand_azure.test.ts diff --git a/.evergreen/run-gcp-kms-tests.sh b/.evergreen/run-gcp-kms-tests.sh index ecc88e535e3..f18ed9c0695 100644 --- a/.evergreen/run-gcp-kms-tests.sh +++ b/.evergreen/run-gcp-kms-tests.sh @@ -20,4 +20,6 @@ export MONGODB_URI="mongodb://localhost:27017" export EXPECTED_GCPKMS_OUTCOME=${EXPECTED_GCPKMS_OUTCOME:-omitted} export TEST_CSFLE=true +npm run build:bundle + npx mocha --config test/mocha_mongodb.js test/integration/client-side-encryption/client_side_encryption.prose.17.on_demand_gcp.test.ts diff --git a/.evergreen/run-mongosh-scope-test.sh b/.evergreen/run-mongosh-scope-test.sh index e2477dda4c9..d9d5451f152 100644 --- a/.evergreen/run-mongosh-scope-test.sh +++ b/.evergreen/run-mongosh-scope-test.sh @@ -13,4 +13,6 @@ export SCOPES=$(./node_modules/lerna/cli.js ls --all --json) cd - +npm run build:bundle + npx mocha --config test/manual/mocharc.json test/manual/mongosh_scopes.test.ts diff --git a/.gitignore b/.gitignore index ffc4acb3e91..ff5518925b1 100644 --- a/.gitignore +++ b/.gitignore @@ -108,3 +108,5 @@ uri.txt crypt_shared.sh *keytab +driver.bundle.js +test/tools/runner/bundle/ diff --git a/etc/build-runtime-barrel.mjs b/etc/build-runtime-barrel.mjs new file mode 100644 index 00000000000..3f89b79168a --- /dev/null +++ b/etc/build-runtime-barrel.mjs @@ -0,0 +1,19 @@ +import fs from 'node:fs/promises'; +import path from 'node:path'; + +// eslint-disable-next-line no-restricted-globals +const useBundled = process.env.MONGODB_BUNDLED === 'true'; + +const rootDir = path.join(import.meta.dirname, '..'); +const outputBarrelFile = path.join(rootDir, 'test/mongodb.ts'); +const source = useBundled ? './mongodb_bundled' : './mongodb_all'; + +const contents = + `// This file is auto-generated. Do not edit.\n` + + `// Run 'npm run build:runtime-barrel' to regenerate.\n` + + `export const runNodelessTests = ${useBundled};\n` + + `export * from '${source}';\n`; +await fs.writeFile(outputBarrelFile, contents); + +// eslint-disable-next-line no-console +console.log(`✓ ${outputBarrelFile} now re-exports from ${source}`); diff --git a/etc/bundle-driver.mjs b/etc/bundle-driver.mjs new file mode 100755 index 00000000000..f9c4c5dd1b9 --- /dev/null +++ b/etc/bundle-driver.mjs @@ -0,0 +1,53 @@ +#!/usr/bin/env node +import fs from 'node:fs/promises'; +import { isBuiltin } from 'node:module'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import * as esbuild from 'esbuild'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const rootDir = path.join(__dirname, '..'); + +const outdir = path.join(rootDir, 'test/tools/runner/bundle/'); +await fs.rm(outdir, { recursive: true, force: true }); + +const outputBundleFile = path.join(outdir, 'driver-bundle.js'); +await esbuild.build({ + entryPoints: [path.join(rootDir, 'test/mongodb_all.ts')], + bundle: true, + outfile: outputBundleFile, + platform: 'node', + format: 'cjs', + target: 'node20', + external: [ + '@aws-sdk/credential-providers', + '@mongodb-js/saslprep', + '@mongodb-js/zstd', + '@napi-rs/snappy*', + 'bson', + 'gcp-metadata', + 'kerberos', + 'mongodb-client-encryption', + 'mongodb-connection-string-url', + 'snappy', + 'socks' + ], + plugins: [ + { + name: 'externalize-node-builtins', + setup(build) { + build.onResolve({ filter: /.*/ }, args => { + if (isBuiltin(args.path)) { + return { path: args.path, external: true }; + } + }); + } + } + ], + sourcemap: 'inline', + logLevel: 'info' +}); + +// eslint-disable-next-line no-console +console.log(`✓ Driver bundle created at ${outputBundleFile}`); diff --git a/package-lock.json b/package-lock.json index b1def2b859d..c04187daa97 100644 --- a/package-lock.json +++ b/package-lock.json @@ -34,9 +34,11 @@ "@typescript-eslint/eslint-plugin": "^8.46.3", "@typescript-eslint/parser": "^8.31.1", "aws4": "^1.13.2", + "baseline-browser-mapping": "^2.10.0", "chai": "^4.4.1", "chai-subset": "^1.6.0", "chalk": "^4.1.2", + "esbuild": "^0.27.2", "eslint": "^9.39.1", "eslint-config-prettier": "^10.1.8", "eslint-plugin-mocha": "^10.4.1", @@ -847,7 +849,6 @@ "integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@babel/code-frame": "^7.27.1", "@babel/generator": "^7.28.5", @@ -1142,6 +1143,448 @@ "tslib": "^2.4.0" } }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.2.tgz", + "integrity": "sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.2.tgz", + "integrity": "sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.2.tgz", + "integrity": "sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.2.tgz", + "integrity": "sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.2.tgz", + "integrity": "sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.2.tgz", + "integrity": "sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.2.tgz", + "integrity": "sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.2.tgz", + "integrity": "sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.2.tgz", + "integrity": "sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.2.tgz", + "integrity": "sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.2.tgz", + "integrity": "sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.2.tgz", + "integrity": "sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.2.tgz", + "integrity": "sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.2.tgz", + "integrity": "sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.2.tgz", + "integrity": "sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.2.tgz", + "integrity": "sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.2.tgz", + "integrity": "sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.2.tgz", + "integrity": "sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.2.tgz", + "integrity": "sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.2.tgz", + "integrity": "sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.2.tgz", + "integrity": "sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.2.tgz", + "integrity": "sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.2.tgz", + "integrity": "sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.2.tgz", + "integrity": "sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.2.tgz", + "integrity": "sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.2.tgz", + "integrity": "sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, "node_modules/@eslint-community/eslint-utils": { "version": "4.9.0", "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.0.tgz", @@ -3026,8 +3469,7 @@ "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.3.20.tgz", "integrity": "sha512-/pC9HAB5I/xMlc5FP77qjCnI16ChlJfW0tGa0IUcFn38VJrTV6DeZ60NU5KZBtaOZqjdpwTWohz5HU1RrhiYxQ==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@types/chai-subset": { "version": "1.3.6", @@ -3129,7 +3571,6 @@ "integrity": "sha512-BICHQ67iqxQGFSzfCFTT7MRQ5XcBjG5aeKh5Ok38UBbPe5fxTyE+aHFxwVrGyr8GNlqFMLKD1D3P2K/1ks8tog==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "undici-types": "~6.21.0" } @@ -3261,7 +3702,6 @@ "integrity": "sha512-sbaQ27XBUopBkRiuY/P9sWGOWUW4rl8fDoHIUmLpZd8uldsTyB4/Zg6bWTegPoTLnKj9Hqgn3QD6cjPNB32Odw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@eslint-community/regexpp": "^4.10.0", "@typescript-eslint/scope-manager": "8.46.3", @@ -3292,7 +3732,6 @@ "integrity": "sha512-6m1I5RmHBGTnUGS113G04DMu3CpSdxCAU/UvtjNWL4Nuf3MW9tQhiJqRlHzChIkhy6kZSAQmc+I1bcGjE3yNKg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.46.3", "@typescript-eslint/types": "8.46.3", @@ -3538,7 +3977,6 @@ "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "dev": true, "license": "MIT", - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -3599,7 +4037,6 @@ "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -3805,13 +4242,16 @@ "license": "MIT" }, "node_modules/baseline-browser-mapping": { - "version": "2.8.25", - "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.8.25.tgz", - "integrity": "sha512-2NovHVesVF5TXefsGX1yzx1xgr7+m9JQenvz6FQY3qd+YXkKkYiv+vTCc7OriP9mcDZpTC5mAOYN4ocd29+erA==", + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.0.tgz", + "integrity": "sha512-lIyg0szRfYbiy67j9KN8IyeD7q7hcmqnJ1ddWmNt19ItGpNN64mnllmxUNFIOdOm6by97jlL6wfpTTJrmnjWAA==", "dev": true, "license": "Apache-2.0", "bin": { - "baseline-browser-mapping": "dist/cli.js" + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" } }, "node_modules/bignumber.js": { @@ -3915,7 +4355,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "baseline-browser-mapping": "^2.8.19", "caniuse-lite": "^1.0.30001751", @@ -4093,7 +4532,6 @@ "integrity": "sha512-RITGBfijLkBddZvnn8jdqoTypxvqbOLYQkGGxXzeFjVHvudaPw0HNFD9x928/eUwYWd2dPCugVqspGALTZZQKw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "assertion-error": "^1.1.0", "check-error": "^1.0.3", @@ -4664,6 +5102,48 @@ "dev": true, "license": "MIT" }, + "node_modules/esbuild": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.2.tgz", + "integrity": "sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.2", + "@esbuild/android-arm": "0.27.2", + "@esbuild/android-arm64": "0.27.2", + "@esbuild/android-x64": "0.27.2", + "@esbuild/darwin-arm64": "0.27.2", + "@esbuild/darwin-x64": "0.27.2", + "@esbuild/freebsd-arm64": "0.27.2", + "@esbuild/freebsd-x64": "0.27.2", + "@esbuild/linux-arm": "0.27.2", + "@esbuild/linux-arm64": "0.27.2", + "@esbuild/linux-ia32": "0.27.2", + "@esbuild/linux-loong64": "0.27.2", + "@esbuild/linux-mips64el": "0.27.2", + "@esbuild/linux-ppc64": "0.27.2", + "@esbuild/linux-riscv64": "0.27.2", + "@esbuild/linux-s390x": "0.27.2", + "@esbuild/linux-x64": "0.27.2", + "@esbuild/netbsd-arm64": "0.27.2", + "@esbuild/netbsd-x64": "0.27.2", + "@esbuild/openbsd-arm64": "0.27.2", + "@esbuild/openbsd-x64": "0.27.2", + "@esbuild/openharmony-arm64": "0.27.2", + "@esbuild/sunos-x64": "0.27.2", + "@esbuild/win32-arm64": "0.27.2", + "@esbuild/win32-ia32": "0.27.2", + "@esbuild/win32-x64": "0.27.2" + } + }, "node_modules/escalade": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", @@ -4700,7 +5180,6 @@ "integrity": "sha512-BhHmn2yNOFA9H9JmmIVKJmd288g9hrVRDkdoIgRCRuSySRUHH7r/DI6aAXW9T1WwUuY3DFgrcaqB+deURBLR5g==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.1", @@ -4761,7 +5240,6 @@ "integrity": "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==", "dev": true, "license": "MIT", - "peer": true, "bin": { "eslint-config-prettier": "bin/cli.js" }, @@ -7336,7 +7814,6 @@ "integrity": "sha512-U42vQ4czpKa0QdI1hu950XuNhYqgoM+ZF1HT+VuUHL9hPfDPVvNQyltmMqdE9bUHMVa+8yNbc3QKTj8zQhlVxQ==", "dev": true, "license": "ISC", - "peer": true, "dependencies": { "@istanbuljs/load-nyc-config": "^1.0.0", "@istanbuljs/schema": "^0.1.2", @@ -8021,7 +8498,6 @@ "integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==", "dev": true, "license": "MIT", - "peer": true, "bin": { "prettier": "bin/prettier.cjs" }, @@ -8877,7 +9353,6 @@ "integrity": "sha512-a2N2TDY1uGviajJ6r4D1CyRAkzE9NNVlYOV1wX5xQDuAk0ONgzgRl0EjCQuRCPxOwp13ghsMwt9Gdldujs39qw==", "dev": true, "license": "BSD-3-Clause", - "peer": true, "dependencies": { "@sinonjs/commons": "^3.0.1", "@sinonjs/fake-timers": "11.2.2", @@ -9660,7 +10135,6 @@ "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==", "dev": true, "license": "Apache-2.0", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" diff --git a/package.json b/package.json index 1f97a7595b4..f57814f0829 100644 --- a/package.json +++ b/package.json @@ -85,6 +85,7 @@ "chai": "^4.4.1", "chai-subset": "^1.6.0", "chalk": "^4.1.2", + "esbuild": "^0.27.2", "eslint": "^9.39.1", "eslint-config-prettier": "^10.1.8", "eslint-plugin-mocha": "^10.4.1", @@ -131,32 +132,40 @@ "check:bench": "npm --prefix test/benchmarks/driver_bench start", "check:coverage": "nyc npm run test:all", "check:integration-coverage": "nyc npm run check:test", - "check:lambda": "nyc mocha --config test/mocha_lambda.js test/integration/node-specific/examples/handler.test.js", - "check:lambda:aws": "nyc mocha --config test/mocha_lambda.js test/integration/node-specific/examples/aws_handler.test.js", + "check:lambda": "npm run build:bundle && nyc mocha --config test/mocha_lambda.js test/integration/node-specific/examples/handler.test.js", + "check:lambda:aws": "npm run build:bundle && nyc mocha --config test/mocha_lambda.js test/integration/node-specific/examples/aws_handler.test.js", "check:lint": "npm run build:dts && npm run check:dts && npm run check:eslint && npm run check:tsd", "check:eslint": "npm run build:dts && ESLINT_USE_FLAT_CONFIG=false eslint -v && ESLINT_USE_FLAT_CONFIG=false eslint --max-warnings=0 --ext '.js,.ts' src test", "check:tsd": "tsd --version && tsd", - "check:dependencies": "mocha test/action/dependency.test.ts", - "check:dts": "node ./node_modules/typescript/bin/tsc --target es2023 --module commonjs --noEmit mongodb.d.ts && tsd", - "check:search-indexes": "nyc mocha --config test/mocha_mongodb.js test/manual/search-index-management.prose.test.ts", - "check:test": "mocha --config test/mocha_mongodb.js test/integration", - "check:unit": "nyc mocha test/unit", + "check:dependencies": "npm run build:bundle && mocha test/action/dependency.test.ts", + "check:dts": "npm run build:bundle && node ./node_modules/typescript/bin/tsc --target es2023 --module commonjs --noEmit mongodb.d.ts && tsd", + "check:search-indexes": "npm run build:bundle && nyc mocha --config test/mocha_mongodb.js test/manual/search-index-management.prose.test.ts", + "check:test": "npm run build:bundle && nyc mocha --config test/mocha_mongodb.js test/integration", + "check:test-bundled": "MONGODB_BUNDLED=true npm run check:test", + "check:unit": "npm run build:bundle && nyc mocha test/unit", + "check:unit-bundled": "MONGODB_BUNDLED=true npm run check:unit", "check:ts": "node ./node_modules/typescript/bin/tsc -v && node ./node_modules/typescript/bin/tsc --noEmit", - "check:atlas": "nyc mocha --config test/manual/mocharc.js test/manual/atlas_connectivity.test.ts", - "check:drivers-atlas-testing": "nyc mocha --config test/mocha_mongodb.js test/atlas/drivers_atlas_testing.test.ts", - "check:aws": "nyc mocha --config test/mocha_mongodb.js test/integration/auth/mongodb_aws.test.ts test/integration/auth/mongodb_aws.prose.test.ts", - "check:oidc-auth": "nyc mocha --config test/mocha_mongodb.js test/integration/auth/auth.spec.test.ts", - "check:oidc-test": "nyc mocha --config test/mocha_mongodb.js test/integration/auth/mongodb_oidc.prose.test.ts", - "check:kerberos": "nyc mocha --config test/manual/mocharc.js test/manual/kerberos.test.ts", - "check:tls": "nyc mocha --config test/manual/mocharc.js test/manual/tls_support.test.ts", - "check:ldap": "nyc mocha --config test/manual/mocharc.js test/manual/ldap.test.ts", - "check:socks5": "nyc mocha --config test/manual/mocharc.js test/manual/socks5.test.ts", - "check:csfle": "nyc mocha --config test/mocha_mongodb.js test/integration/client-side-encryption", - "check:snappy": "nyc mocha test/unit/assorted/snappy.test.js", - "check:x509": "nyc mocha test/manual/x509_auth.test.ts", + "check:atlas": "npm run build:bundle && nyc mocha --config test/manual/mocharc.js test/manual/atlas_connectivity.test.ts", + "check:drivers-atlas-testing": "npm run build:bundle && nyc mocha --config test/mocha_mongodb.js test/atlas/drivers_atlas_testing.test.ts", + "check:aws": "npm run build:bundle && nyc mocha --config test/mocha_mongodb.js test/integration/auth/mongodb_aws.test.ts test/integration/auth/mongodb_aws.prose.test.ts", + "check:oidc-auth": "npm run build:bundle && nyc mocha --config test/mocha_mongodb.js test/integration/auth/auth.spec.test.ts", + "check:oidc-test": "npm run build:bundle && nyc mocha --config test/mocha_mongodb.js test/integration/auth/mongodb_oidc.prose.test.ts", + "check:kerberos": "npm run build:bundle && nyc mocha --config test/manual/mocharc.js test/manual/kerberos.test.ts", + "check:tls": "npm run build:bundle && nyc mocha --config test/manual/mocharc.js test/manual/tls_support.test.ts", + "check:ldap": "npm run build:bundle && nyc mocha --config test/manual/mocharc.js test/manual/ldap.test.ts", + "check:socks5": "npm run build:bundle && nyc mocha --config test/manual/mocharc.js test/manual/socks5.test.ts", + "check:csfle": "npm run build:bundle && nyc mocha --config test/mocha_mongodb.js test/integration/client-side-encryption", + "check:snappy": "npm run build:bundle && nyc mocha test/unit/assorted/snappy.test.js", + "check:x509": "npm run build:bundle && nyc mocha test/manual/x509_auth.test.ts", + "build:bundle": "npm run bundle:driver && npm run bundle:types && npm run build:runtime-barrel", + "build:runtime-barrel": "node etc/build-runtime-barrel.mjs", + "bundle:driver": "node etc/bundle-driver.mjs", + "bundle:types": "npx tsc --project ./tsconfig.json --declaration --emitDeclarationOnly --declarationDir test/tools/runner/bundle/types", "fix:eslint": "npm run check:eslint -- --fix", "prepare": "node etc/prepare.js", "preview:docs": "ts-node etc/docs/preview.ts", + "switch:to-bundled": "MONGODB_BUNDLED=true npm run build:runtime-barrel", + "switch:to-unbundled": "MONGODB_BUNDLED=false npm run build:runtime-barrel", "test": "npm run check:lint && npm run test:all", "test:all": "npm run check:unit && npm run check:test", "update:docs": "npm run build:docs -- --yes" diff --git a/src/operations/client_bulk_write/command_builder.ts b/src/operations/client_bulk_write/command_builder.ts index 6e937f058c7..dee80facca9 100644 --- a/src/operations/client_bulk_write/command_builder.ts +++ b/src/operations/client_bulk_write/command_builder.ts @@ -242,7 +242,7 @@ function validateBufferSize(name: string, buffer: Uint8Array, maxBsonObjectSize: } /** @internal */ -interface ClientInsertOperation { +export interface ClientInsertOperation { insert: number; document: OptionalId; } diff --git a/src/runtime_adapters.ts b/src/runtime_adapters.ts index bb998d4bd09..e0a3e915696 100644 --- a/src/runtime_adapters.ts +++ b/src/runtime_adapters.ts @@ -1,4 +1,4 @@ -/* eslint-disable no-restricted-imports, @typescript-eslint/no-require-imports */ +/* eslint-disable no-restricted-imports*/ // We squash the restricted import errors here because we are using type-only imports, which // do not impact the driver's actual runtime dependencies. @@ -43,7 +43,9 @@ export interface Runtime { * not provided by in `options`, and returns a `Runtime`. */ export function resolveRuntimeAdapters(options: MongoClientOptions): Runtime { + const correctRequire = (globalThis as any).__driver_require || require; + return { - os: options.runtimeAdapters?.os ?? require('os') + os: options.runtimeAdapters?.os ?? correctRequire('os') }; } diff --git a/test/csfle-kms-providers.ts b/test/csfle-kms-providers.ts index f18ac70de9d..ed4cfd7e793 100644 --- a/test/csfle-kms-providers.ts +++ b/test/csfle-kms-providers.ts @@ -1,6 +1,6 @@ import * as process from 'process'; -import { type KMSProviders } from './mongodb'; +import { type KMSProviders } from './mongodb_all'; const csfleKMSProviders = { aws: { diff --git a/test/integration/client-side-encryption/client_side_encryption.prose.21.automatic_data_encryption_keys.test.ts b/test/integration/client-side-encryption/client_side_encryption.prose.21.automatic_data_encryption_keys.test.ts index b1ff4a6f077..d7d49d3341a 100644 --- a/test/integration/client-side-encryption/client_side_encryption.prose.21.automatic_data_encryption_keys.test.ts +++ b/test/integration/client-side-encryption/client_side_encryption.prose.21.automatic_data_encryption_keys.test.ts @@ -12,6 +12,7 @@ import { MongoCryptCreateEncryptedCollectionError, MongoServerError } from '../../mongodb'; +import { ensureTypeByName } from '../../tools/utils'; const metadata: MongoDBMetadataUI = { requires: { clientSideEncryption: true, @@ -94,7 +95,7 @@ describe('21. Automatic Data Encryption Keys', () => { }) .catch(error => error); - expect(result).to.be.instanceOf(TypeError); + ensureTypeByName(result, 'TypeError'); }); it('Case 3: Invalid keyId', metadata, async () => { diff --git a/test/integration/crud/crud_api.test.ts b/test/integration/crud/crud_api.test.ts index 6ec29becc47..b174a5b6601 100644 --- a/test/integration/crud/crud_api.test.ts +++ b/test/integration/crud/crud_api.test.ts @@ -15,7 +15,7 @@ import { ObjectId, ReturnDocument } from '../../mongodb'; -import { type FailCommandFailPoint } from '../../tools/utils'; +import { ensureTypeByName, type FailCommandFailPoint } from '../../tools/utils'; import { assert as test } from '../shared'; const DB_NAME = 'crud_api_tests'; @@ -808,7 +808,7 @@ describe('CRUD API', function () { .collection('t20_1') .bulkWrite(ops, { ordered: true, writeConcern: { w: 1 } }) .catch(err => err); - expect(err).to.be.instanceOf(MongoBulkWriteError); + ensureTypeByName(err, 'MongoBulkWriteError'); }); describe('sort support', function () { diff --git a/test/integration/crud/misc_cursors.test.ts b/test/integration/crud/misc_cursors.test.ts index 70a8ccf196d..0fb75397749 100644 --- a/test/integration/crud/misc_cursors.test.ts +++ b/test/integration/crud/misc_cursors.test.ts @@ -8,7 +8,7 @@ import { ReadPreference, ServerType } from '../../mongodb'; -import { runLater, sleep } from '../../tools/utils'; +import { ensureTypeByName, runLater, sleep } from '../../tools/utils'; import { assert as test, filterForCommands, setupDatabase } from '../shared'; describe('Cursor', function () { @@ -1529,7 +1529,7 @@ describe('Cursor', function () { const promise = cursor.forEach(() => { // do nothing }); - expect(promise).to.exist.and.to.be.an.instanceof(Promise); + ensureTypeByName(promise, 'Promise'); return promise; }); }); diff --git a/test/integration/node-specific/resource_clean_up.test.ts b/test/integration/node-specific/resource_clean_up.test.ts index db74ced8b09..1b9709ec545 100644 --- a/test/integration/node-specific/resource_clean_up.test.ts +++ b/test/integration/node-specific/resource_clean_up.test.ts @@ -2,6 +2,7 @@ import * as v8 from 'node:v8'; import { expect } from 'chai'; +import { runNodelessTests } from '../../mongodb'; import { isTLSEnabled } from '../../tools/runner/filters/tls_filter'; import { sleep } from '../../tools/utils'; import { runScriptAndReturnHeapInfo } from './resource_tracking_script_builder'; @@ -91,7 +92,7 @@ describe('Driver Resources', () => { context('when 100s of operations are executed and complete', () => { beforeEach(function () { - if (this.currentTest && typeof v8.queryObjects !== 'function') { + if ((this.currentTest && typeof v8.queryObjects !== 'function') || runNodelessTests) { this.currentTest.skipReason = 'Test requires v8.queryObjects API to count Promises'; this.currentTest?.skip(); } diff --git a/test/mongodb.ts b/test/mongodb.ts index 60fe06cefe1..f1a8e2160eb 100644 --- a/test/mongodb.ts +++ b/test/mongodb.ts @@ -1,134 +1,4 @@ -// As the centralized import for all src code for tests, we intentionally import from `src` in this file. -/* eslint-disable @typescript-eslint/no-restricted-imports */ - -export * from '../src/admin'; -export * from '../src/bson'; -export * from '../src/bulk/common'; -export * from '../src/bulk/ordered'; -export * from '../src/bulk/unordered'; -export * from '../src/change_stream'; -export * from '../src/client-side-encryption/auto_encrypter'; -export * from '../src/client-side-encryption/client_encryption'; -export * from '../src/client-side-encryption/errors'; -export * from '../src/client-side-encryption/mongocryptd_manager'; -export * from '../src/client-side-encryption/providers/aws'; -export * from '../src/client-side-encryption/providers/azure'; -export * from '../src/client-side-encryption/providers/gcp'; -export * from '../src/client-side-encryption/providers/index'; -export * from '../src/client-side-encryption/state_machine'; -export * from '../src/cmap/auth/auth_provider'; -export * from '../src/cmap/auth/aws_temporary_credentials'; -export * from '../src/cmap/auth/aws4'; -export * from '../src/cmap/auth/gssapi'; -export * from '../src/cmap/auth/mongo_credentials'; -export * from '../src/cmap/auth/mongodb_aws'; -export * from '../src/cmap/auth/mongodb_oidc'; -export * from '../src/cmap/auth/mongodb_oidc/automated_callback_workflow'; -export * from '../src/cmap/auth/mongodb_oidc/azure_machine_workflow'; -export * from '../src/cmap/auth/mongodb_oidc/callback_workflow'; -export * from '../src/cmap/auth/mongodb_oidc/command_builders'; -export * from '../src/cmap/auth/mongodb_oidc/gcp_machine_workflow'; -export * from '../src/cmap/auth/mongodb_oidc/human_callback_workflow'; -export * from '../src/cmap/auth/mongodb_oidc/k8s_machine_workflow'; -export * from '../src/cmap/auth/mongodb_oidc/token_cache'; -export * from '../src/cmap/auth/mongodb_oidc/token_machine_workflow'; -export * from '../src/cmap/auth/plain'; -export * from '../src/cmap/auth/providers'; -export * from '../src/cmap/auth/scram'; -export * from '../src/cmap/auth/x509'; -export * from '../src/cmap/command_monitoring_events'; -export * from '../src/cmap/commands'; -export * from '../src/cmap/connect'; -export * from '../src/cmap/connection'; -export * from '../src/cmap/connection_pool'; -export * from '../src/cmap/connection_pool_events'; -export * from '../src/cmap/errors'; -export * from '../src/cmap/handshake/client_metadata'; -export * from '../src/cmap/metrics'; -export * from '../src/cmap/stream_description'; -export * from '../src/cmap/wire_protocol/compression'; -export * from '../src/cmap/wire_protocol/constants'; -export * from '../src/cmap/wire_protocol/on_data'; -export * from '../src/cmap/wire_protocol/on_demand/document'; -export * from '../src/cmap/wire_protocol/responses'; -export * from '../src/cmap/wire_protocol/shared'; -export * from '../src/collection'; -export * from '../src/connection_string'; -export * from '../src/constants'; -export * from '../src/cursor/abstract_cursor'; -export * from '../src/cursor/aggregation_cursor'; -export * from '../src/cursor/change_stream_cursor'; -export * from '../src/cursor/client_bulk_write_cursor'; -export * from '../src/cursor/explainable_cursor'; -export * from '../src/cursor/find_cursor'; -export * from '../src/cursor/list_collections_cursor'; -export * from '../src/cursor/list_indexes_cursor'; -export * from '../src/cursor/list_search_indexes_cursor'; -export * from '../src/cursor/run_command_cursor'; -export * from '../src/db'; -export * from '../src/deps'; -export * from '../src/encrypter'; -export * from '../src/error'; -export * from '../src/explain'; -export * from '../src/gridfs/download'; -export * from '../src/gridfs/index'; -export * from '../src/gridfs/upload'; -export * from '../src/mongo_client'; -export * from '../src/mongo_client_auth_providers'; -export * from '../src/mongo_logger'; -export * from '../src/mongo_types'; -export * from '../src/operations/aggregate'; -export * from '../src/operations/client_bulk_write/client_bulk_write'; -export * from '../src/operations/client_bulk_write/command_builder'; -export * from '../src/operations/client_bulk_write/common'; -export * from '../src/operations/client_bulk_write/executor'; -export * from '../src/operations/client_bulk_write/results_merger'; -export * from '../src/operations/command'; -export * from '../src/operations/count'; -export * from '../src/operations/create_collection'; -export * from '../src/operations/delete'; -export * from '../src/operations/distinct'; -export * from '../src/operations/drop'; -export * from '../src/operations/end_sessions'; -export * from '../src/operations/estimated_document_count'; -export * from '../src/operations/execute_operation'; -export * from '../src/operations/find'; -export * from '../src/operations/find_and_modify'; -export * from '../src/operations/get_more'; -export * from '../src/operations/indexes'; -export * from '../src/operations/insert'; -export * from '../src/operations/kill_cursors'; -export * from '../src/operations/list_collections'; -export * from '../src/operations/list_databases'; -export * from '../src/operations/operation'; -export * from '../src/operations/profiling_level'; -export * from '../src/operations/remove_user'; -export * from '../src/operations/rename'; -export * from '../src/operations/run_command'; -export * from '../src/operations/search_indexes/create'; -export * from '../src/operations/search_indexes/drop'; -export * from '../src/operations/search_indexes/update'; -export * from '../src/operations/set_profiling_level'; -export * from '../src/operations/stats'; -export * from '../src/operations/update'; -export * from '../src/operations/validate_collection'; -export * from '../src/read_concern'; -export * from '../src/read_preference'; -export * from '../src/runtime_adapters'; -export * from '../src/sdam/common'; -export * from '../src/sdam/events'; -export * from '../src/sdam/monitor'; -export * from '../src/sdam/server'; -export * from '../src/sdam/server_description'; -export * from '../src/sdam/server_selection'; -export * from '../src/sdam/server_selection_events'; -export * from '../src/sdam/srv_polling'; -export * from '../src/sdam/topology'; -export * from '../src/sdam/topology_description'; -export * from '../src/sessions'; -export * from '../src/sort'; -export * from '../src/timeout'; -export * from '../src/token_bucket'; -export * from '../src/transactions'; -export * from '../src/utils'; -export * from '../src/write_concern'; +// This file is auto-generated. Do not edit. +// Run 'npm run build:runtime-barrel' to regenerate. +export const runNodelessTests = false; +export * from './mongodb_all'; diff --git a/test/mongodb_all.ts b/test/mongodb_all.ts new file mode 100644 index 00000000000..16beb26c902 --- /dev/null +++ b/test/mongodb_all.ts @@ -0,0 +1,137 @@ +// As the centralized import for all src code for tests, we intentionally import from `src` in this file. +/* eslint-disable @typescript-eslint/no-restricted-imports */ + +export * from '../src/admin'; +export * from '../src/bson'; +export * from '../src/bulk/common'; +export * from '../src/bulk/ordered'; +export * from '../src/bulk/unordered'; +export * from '../src/change_stream'; +export * from '../src/client-side-encryption/auto_encrypter'; +export * from '../src/client-side-encryption/client_encryption'; +export * from '../src/client-side-encryption/errors'; +export * from '../src/client-side-encryption/mongocryptd_manager'; +export * from '../src/client-side-encryption/providers/aws'; +export * from '../src/client-side-encryption/providers/azure'; +export * from '../src/client-side-encryption/providers/gcp'; +export * from '../src/client-side-encryption/providers/index'; +export * from '../src/client-side-encryption/state_machine'; +export * from '../src/cmap/auth/auth_provider'; +export * from '../src/cmap/auth/aws_temporary_credentials'; +export * from '../src/cmap/auth/aws4'; +export * from '../src/cmap/auth/gssapi'; +export * from '../src/cmap/auth/mongo_credentials'; +export * from '../src/cmap/auth/mongodb_aws'; +export * from '../src/cmap/auth/mongodb_oidc'; +export * from '../src/cmap/auth/mongodb_oidc/automated_callback_workflow'; +export * from '../src/cmap/auth/mongodb_oidc/azure_machine_workflow'; +export * from '../src/cmap/auth/mongodb_oidc/callback_workflow'; +export * from '../src/cmap/auth/mongodb_oidc/command_builders'; +export * from '../src/cmap/auth/mongodb_oidc/gcp_machine_workflow'; +export * from '../src/cmap/auth/mongodb_oidc/human_callback_workflow'; +export * from '../src/cmap/auth/mongodb_oidc/k8s_machine_workflow'; +export * from '../src/cmap/auth/mongodb_oidc/token_cache'; +export * from '../src/cmap/auth/mongodb_oidc/token_machine_workflow'; +export * from '../src/cmap/auth/plain'; +export * from '../src/cmap/auth/providers'; +export * from '../src/cmap/auth/scram'; +export * from '../src/cmap/auth/x509'; +export * from '../src/cmap/command_monitoring_events'; +export * from '../src/cmap/commands'; +export * from '../src/cmap/connect'; +export * from '../src/cmap/connection'; +export * from '../src/cmap/connection_pool'; +export * from '../src/cmap/connection_pool_events'; +export * from '../src/cmap/errors'; +export * from '../src/cmap/handshake/client_metadata'; +export * from '../src/cmap/metrics'; +export * from '../src/cmap/stream_description'; +export * from '../src/cmap/wire_protocol/compression'; +export * from '../src/cmap/wire_protocol/constants'; +export * from '../src/cmap/wire_protocol/on_data'; +export * from '../src/cmap/wire_protocol/on_demand/document'; +export * from '../src/cmap/wire_protocol/responses'; +export * from '../src/cmap/wire_protocol/shared'; +export * from '../src/collection'; +export * from '../src/connection_string'; +export * from '../src/constants'; +export * from '../src/cursor/abstract_cursor'; +export * from '../src/cursor/aggregation_cursor'; +export * from '../src/cursor/change_stream_cursor'; +export * from '../src/cursor/client_bulk_write_cursor'; +export * from '../src/cursor/explainable_cursor'; +export * from '../src/cursor/find_cursor'; +export * from '../src/cursor/list_collections_cursor'; +export * from '../src/cursor/list_indexes_cursor'; +export * from '../src/cursor/list_search_indexes_cursor'; +export * from '../src/cursor/run_command_cursor'; +export * from '../src/db'; +export * from '../src/deps'; +export * from '../src/encrypter'; +export * from '../src/error'; +export * from '../src/explain'; +export * from '../src/gridfs/download'; +export * from '../src/gridfs/index'; +export * from '../src/gridfs/upload'; +export * from '../src/mongo_client'; +export * from '../src/mongo_client_auth_providers'; +export * from '../src/mongo_logger'; +export * from '../src/mongo_types'; +export * from '../src/operations/aggregate'; +export * from '../src/operations/client_bulk_write/client_bulk_write'; +export * from '../src/operations/client_bulk_write/command_builder'; +export * from '../src/operations/client_bulk_write/common'; +export * from '../src/operations/client_bulk_write/executor'; +export * from '../src/operations/client_bulk_write/results_merger'; +export * from '../src/operations/command'; +export * from '../src/operations/count'; +export * from '../src/operations/create_collection'; +export * from '../src/operations/delete'; +export * from '../src/operations/distinct'; +export * from '../src/operations/drop'; +export * from '../src/operations/end_sessions'; +export * from '../src/operations/estimated_document_count'; +export * from '../src/operations/execute_operation'; +export * from '../src/operations/find'; +export * from '../src/operations/find_and_modify'; +export * from '../src/operations/get_more'; +export * from '../src/operations/indexes'; +export * from '../src/operations/insert'; +export * from '../src/operations/kill_cursors'; +export * from '../src/operations/list_collections'; +export * from '../src/operations/list_databases'; +export * from '../src/operations/operation'; +export * from '../src/operations/profiling_level'; +export * from '../src/operations/remove_user'; +export * from '../src/operations/rename'; +export * from '../src/operations/run_command'; +export * from '../src/operations/search_indexes/create'; +export * from '../src/operations/search_indexes/drop'; +export * from '../src/operations/search_indexes/update'; +export * from '../src/operations/set_profiling_level'; +export * from '../src/operations/stats'; +export * from '../src/operations/update'; +export * from '../src/operations/validate_collection'; +export * from '../src/read_concern'; +export * from '../src/read_preference'; +export * from '../src/runtime_adapters'; +export * from '../src/sdam/common'; +export * from '../src/sdam/events'; +export * from '../src/sdam/monitor'; +export * from '../src/sdam/server'; +export * from '../src/sdam/server_description'; +export * from '../src/sdam/server_selection'; +export * from '../src/sdam/server_selection_events'; +export * from '../src/sdam/srv_polling'; +export * from '../src/sdam/topology'; +export * from '../src/sdam/topology_description'; +export * from '../src/sessions'; +export * from '../src/sort'; +export * from '../src/timeout'; +export * from '../src/token_bucket'; +export * from '../src/transactions'; +export * from '../src/utils'; +export * from '../src/write_concern'; + +// Must be last for precedence +export * from '../src/index'; diff --git a/test/mongodb_bundled.ts b/test/mongodb_bundled.ts new file mode 100644 index 00000000000..a9322653765 --- /dev/null +++ b/test/mongodb_bundled.ts @@ -0,0 +1,552 @@ +import { loadContextifiedMongoDBModule } from './tools/runner/vm_context_helper'; + +type all = typeof import('./mongodb_all'); +let exportSource: all; +try { + exportSource = loadContextifiedMongoDBModule(); +} catch (error) { + throw new Error( + `Failed to load contextified MongoDB module: ${error instanceof Error ? error.message : String(error)}` + ); +} + +// Export public API from the contextified module +// Hint: This list IS NOT automatically alphabetized +// To re-sort: Highlight the list and use VSCode's "Sort Lines Ascending" command +export const { + abortable, + AbstractCursor, + AggregateOperation, + AggregationCursor, + applySession, + Aspect, + AUTH_MECHS_AUTH_SRC_EXTERNAL, + AuthContext, + AuthMechanism, + AuthProvider, + AutoEncrypter, + AutomatedCallbackWorkflow, + aws4Sign, + AWSSDKCredentialProvider, + azureCallback, + Binary, + BSON, + BSONError, + BSONRegExp, + BSONSymbol, + BSONType, + BufferPool, + buildDeleteManyOperation, + buildDeleteOneOperation, + buildInsertOneOperation, + buildReplaceOneOperation, + buildUpdateManyOperation, + buildUpdateOneOperation, + CallbackWorkflow, + CancellationToken, + ChangeStream, + ChangeStreamCursor, + checkParentDomainMatch, + ClientBulkWriteCommandBuilder, + ClientBulkWriteCursorResponse, + ClientBulkWriteResultsMerger, + ClientEncryption, + ClientSession, + CMAP_EVENTS, + Code, + Collection, + COMMAND_FAILED, + COMMAND_STARTED, + COMMAND_SUCCEEDED, + CommandFailedEvent, + CommandStartedEvent, + CommandSucceededEvent, + compareObjectId, + compareTopologyVersion, + compress, + Compressor, + connect, + CONNECTION_CHECK_OUT_FAILED, + CONNECTION_CHECK_OUT_STARTED, + CONNECTION_CHECKED_IN, + CONNECTION_CHECKED_OUT, + CONNECTION_CLOSED, + CONNECTION_CREATED, + CONNECTION_POOL_CLEARED, + CONNECTION_POOL_CLOSED, + CONNECTION_POOL_CREATED, + CONNECTION_POOL_READY, + CONNECTION_READY, + Connection, + ConnectionCheckedInEvent, + ConnectionCheckedOutEvent, + ConnectionCheckOutFailedEvent, + ConnectionCheckOutStartedEvent, + ConnectionClosedEvent, + ConnectionCreatedEvent, + ConnectionPool, + ConnectionPoolClearedEvent, + ConnectionPoolClosedEvent, + ConnectionPoolCreatedEvent, + ConnectionPoolMetrics, + ConnectionPoolReadyEvent, + ConnectionReadyEvent, + COSMOS_DB_MSG, + CountOperation, + CreateCollectionOperation, + CreateIndexesOperation, + CreateSearchIndexesOperation, + createStdioLogger, + CryptoConnection, + CSOTTimeoutContext, + CursorResponse, + CursorTimeoutContext, + CursorTimeoutMode, + Db, + DBRef, + DbStatsOperation, + Decimal128, + decompress, + decorateWithExplain, + DEFAULT_ALLOWED_HOSTS, + DEFAULT_MAX_DOCUMENT_LENGTH, + DEFAULT_PK_FACTORY, + DeleteManyOperation, + DeleteOneOperation, + DeleteOperation, + DeprioritizedServers, + deserialize, + DistinctOperation, + DOCUMENT_DB_MSG, + DocumentSequence, + Double, + DropCollectionOperation, + DropDatabaseOperation, + DropIndexOperation, + DropSearchIndexOperation, + EJSON, + enumToString, + EstimatedDocumentCountOperation, + Explain, + ExplainVerbosity, + fetchAzureKMSToken, + filterOutOptions, + FindAndModifyOperation, + FindCursor, + FindOneAndDeleteOperation, + FindOneAndReplaceOperation, + FindOneAndUpdateOperation, + FindOperation, + formatSort, + gcpCallback, + getAwsCredentialProvider, + getFAASEnv, + getGcpMetadata, + getMongoDBClientEncryption, + GetMoreOperation, + getTopology, + GridFSBucket, + GSSAPI, + GSSAPICanonicalizationValue, + hasAtomicOperators, + HEARTBEAT_EVENTS, + HostAddress, + hostMatchesWildcards, + INITIAL_TOKEN_BUCKET_SIZE, + InsertOneOperation, + InsertOperation, + Int32, + isDriverInfoEqual, + isEmptyCredentials, + isHello, + isRecord, + isResumableError, + isRetryableReadError, + isStateChangeError, + isUint8Array, + KillCursorsOperation, + LEGACY_HELLO_COMMAND, + LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE, + LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE, + LegacyTimeoutContext, + LimitedSizeDocument, + List, + ListCollectionsCursor, + ListCollectionsOperation, + ListDatabasesOperation, + ListIndexesOperation, + Long, + makeClientMetadata, + MAX_SUPPORTED_SERVER_VERSION, + MAX_SUPPORTED_WIRE_VERSION, + MaxKey, + MIN_SECONDARY_WRITE_WIRE_VERSION, + MIN_SUPPORTED_SERVER_VERSION, + MIN_SUPPORTED_WIRE_VERSION, + MinKey, + MongoAPIError, + MongoAWSError, + MongoBatchReExecutionError, + MongoBulkWriteError, + MongoClient, + MongoClientAuthProviders, + MongoClientBulkWriteError, + MongoClientClosedError, + MongoCompatibilityError, + MongoCredentials, + MongoCryptAzureKMSRequestError, + MongoCryptCreateDataKeyError, + MongoCryptCreateEncryptedCollectionError, + MongocryptdManager, + MongoCryptError, + MongoCryptInvalidArgumentError, + MongoCursorExhaustedError, + MONGODB_ERROR_CODES, + MongoDBAWS, + MongoDBCollectionNamespace, + MongoDBNamespace, + MongoDBResponse, + MongoDriverError, + MongoError, + MongoErrorLabel, + MongoInvalidArgumentError, + MongoLoggableComponent, + MongoLogger, + MongoMissingCredentialsError, + MongoMissingDependencyError, + MongoNetworkError, + MongoNetworkTimeoutError, + MongoNotConnectedError, + MongoOperationTimeoutError, + MongoParseError, + MongoRuntimeError, + MongoServerError, + MongoServerSelectionError, + MongoSystemError, + MongoUnexpectedServerResponseError, + MongoWriteConcernError, + Monitor, + MonitorInterval, + needsRetryableWriteLabel, + NODE_IS_RECOVERING_ERROR_MESSAGE, + noop, + ns, + ObjectId, + OIDC_VERSION, + OnDemandDocument, + OP_MSG, + OP_QUERY, + OpCompressedRequest, + OpMsgRequest, + OpMsgResponse, + OpQueryRequest, + OpReply, + parseOptions, + parseSeverityFromString, + performGSSAPICanonicalizeHostName, + PoolClearedError, + PoolClosedError, + prepareHandshakeDocument, + processTimeMS, + ProfilingLevel, + ProfilingLevelOperation, + promiseWithResolvers, + ReadConcern, + ReadConcernLevel, + ReadPreference, + readPreferenceServerSelector, + refreshKMSCredentials, + RemoveUserOperation, + RenameOperation, + ReplaceOneOperation, + resolveCname, + resolveRuntimeAdapters, + resolveSRVRecord, + resolveTimeoutOptions, + ReturnDocument, + RTTSampler, + RunCommandOperation, + RunCursorCommandOperation, + sameServerSelector, + ScramSHA256, + secondaryWritableServerSelector, + SENSITIVE_COMMANDS, + serialize, + SERVER_CLOSED, + SERVER_DESCRIPTION_CHANGED, + SERVER_HEARTBEAT_FAILED, + SERVER_HEARTBEAT_STARTED, + SERVER_HEARTBEAT_SUCCEEDED, + SERVER_OPENING, + Server, + ServerApiVersion, + ServerClosedEvent, + ServerDescription, + ServerDescriptionChangedEvent, + ServerHeartbeatFailedEvent, + ServerHeartbeatStartedEvent, + ServerHeartbeatSucceededEvent, + ServerOpeningEvent, + ServerSelectionEvent, + ServerSession, + ServerSessionPool, + ServerType, + setDifference, + SetProfilingLevelOperation, + SeverityLevel, + shuffle, + SizedMessageTransform, + squashError, + SrvPoller, + SrvPollingEvent, + StateMachine, + StreamDescription, + stringifyWithMaxLen, + Timeout, + TimeoutContext, + TimeoutError, + Timestamp, + tokenCache, + TokenCache, + tokenMachineCallback, + TOPOLOGY_CLOSED, + TOPOLOGY_DESCRIPTION_CHANGED, + TOPOLOGY_EVENTS, + TOPOLOGY_OPENING, + Topology, + TopologyClosedEvent, + TopologyDescription, + TopologyDescriptionChangedEvent, + TopologyOpeningEvent, + TopologyType, + Transaction, + uncompressibleCommands, + UpdateManyOperation, + UpdateOneOperation, + UpdateOperation, + UpdateSearchIndexOperation, + UUID, + ValidateCollectionOperation, + WaitQueueTimeoutError, + writableServerSelector, + WriteConcern +} = exportSource; + +// Export types from the contextified module +// Hint: This list IS automatically alphabetized, so add new types anywhere in the list and it will stay organized +export type { + AbstractOperation, + Admin, + AnyClientBulkWriteModel, + AutoEncryptionOptions, + AWSCredentials, + BSONSerializeOptions, + BSONTypeAlias, + ChangeStreamCollModDocument, + ChangeStreamCreateDocument, + ChangeStreamCreateIndexDocument, + ChangeStreamDeleteDocument, + ChangeStreamDocument, + ChangeStreamDocumentCommon, + ChangeStreamDocumentKey, + ChangeStreamDropDatabaseDocument, + ChangeStreamDropDocument, + ChangeStreamDropIndexDocument, + ChangeStreamInsertDocument, + ChangeStreamInvalidateDocument, + ChangeStreamNameSpace, + ChangeStreamOptions, + ChangeStreamRefineCollectionShardKeyDocument, + ChangeStreamRenameDocument, + ChangeStreamReplaceDocument, + ChangeStreamReshardCollectionDocument, + ChangeStreamShardCollectionDocument, + ChangeStreamUpdateDocument, + ClientBulkWriteModel, + ClientBulkWriteResult, + ClientDeleteManyModel, + ClientDeleteOneModel, + ClientEncryptionDataKeyProvider, + ClientInsertOneModel, + ClientMetadata, + ClientReplaceOneModel, + ClientUpdateManyModel, + ClientUpdateOneModel, + ClusterTime, + CollectionInfo, + CollectionOptions, + CommandOptions, + CompressorName, + ConnectionOptions, + ConnectionPoolOptions, + ConnectOptions, + CreateIndexesOptions, + DataKey, + DbOptions, + Document, + DriverInfo, + Filter, + FindOptions, + IndexDirection, + InferIdType, + KMSProviders, + Log, + MongoChangeStreamError, + MongoClientOptions, + MongoDBLogWritable, + MongoDBResponseConstructor, + MongoLoggerOptions, + MongoOptions, + OneOrMore, + OptionalId, + ReadPreferenceMode, + ResumeToken, + Runtime, + ServerApi, + ServerSessionId, + Sort, + TagSet, + TopologyVersion, + TransactionOptions, + UpdateDescription, + UpdateFilter, + W, + WithId, + WithoutId, + WriteConcernSettings +} from './tools/runner/bundle/types/index'; + +// Export "clashing" types from the contextified module. +// These are types that clash with the objects of the same name (eg Collection), so we need to export them separately to avoid type errors. +// Hint: This list IS automatically alphabetized, so add new types anywhere in the list and it will stay organized +import type { + AbstractCursor as _AbstractCursor, + AuthMechanism as _AuthMechanism, + ChangeStream as _ChangeStream, + ClientEncryption as _ClientEncryption, + ClientSession as _ClientSession, + Collection as _Collection, + CommandFailedEvent as _CommandFailedEvent, + CommandStartedEvent as _CommandStartedEvent, + CommandSucceededEvent as _CommandSucceededEvent, + Connection as _Connection, + ConnectionCheckedInEvent as _ConnectionCheckedInEvent, + ConnectionCheckedOutEvent as _ConnectionCheckedOutEvent, + ConnectionCheckOutFailedEvent as _ConnectionCheckOutFailedEvent, + ConnectionCheckOutStartedEvent as _ConnectionCheckOutStartedEvent, + ConnectionClosedEvent as _ConnectionClosedEvent, + ConnectionCreatedEvent as _ConnectionCreatedEvent, + ConnectionPool as _ConnectionPool, + ConnectionPoolClearedEvent as _ConnectionPoolClearedEvent, + ConnectionPoolClosedEvent as _ConnectionPoolClosedEvent, + ConnectionPoolCreatedEvent as _ConnectionPoolCreatedEvent, + ConnectionPoolReadyEvent as _ConnectionPoolReadyEvent, + ConnectionReadyEvent as _ConnectionReadyEvent, + CSOTTimeoutContext as _CSOTTimeoutContext, + CursorTimeoutContext as _CursorTimeoutContext, + Db as _Db, + FindCursor as _FindCursor, + GridFSBucket as _GridFSBucket, + HostAddress as _HostAddress, + MongoClient as _MongoClient, + MongoCredentials as _MongoCredentials, + MongoError as _MongoError, + Monitor as _Monitor, + MonitorInterval as _MonitorInterval, + ObjectId as _ObjectId, + OnDemandDocument as _OnDemandDocument, + RTTSampler as _RTTSampler, + Server as _Server, + ServerApiVersion as _ServerApiVersion, + ServerClosedEvent as _ServerClosedEvent, + ServerDescription as _ServerDescription, + ServerDescriptionChangedEvent as _ServerDescriptionChangedEvent, + ServerHeartbeatFailedEvent as _ServerHeartbeatFailedEvent, + ServerHeartbeatStartedEvent as _ServerHeartbeatStartedEvent, + ServerHeartbeatSucceededEvent as _ServerHeartbeatSucceededEvent, + ServerOpeningEvent as _ServerOpeningEvent, + ServerSessionPool as _ServerSessionPool, + Timeout as _Timeout, + TimeoutContext as _TimeoutContext, + Topology as _Topology, + TopologyClosedEvent as _TopologyClosedEvent, + TopologyDescription as _TopologyDescription, + TopologyDescriptionChangedEvent as _TopologyDescriptionChangedEvent, + TopologyOpeningEvent as _TopologyOpeningEvent, + TopologyOptions as _TopologyOptions, + TopologyType as _TopologyType, + UUID as _UUID +} from './tools/runner/bundle/types/index'; + +// Export "clashing" types from the contextified module +// Hint: This list IS NOT automatically alphabetized +// To re-sort: Highlight the list and use VSCode's "Sort Lines Ascending" command +export type AbstractCursor = _AbstractCursor; +export type AuthMechanism = _AuthMechanism; +export type ChangeStream = _ChangeStream; +export type ClientEncryption = _ClientEncryption; +export type ClientSession = _ClientSession; +export type Collection = _Collection; +export type CommandFailedEvent = _CommandFailedEvent; +export type CommandStartedEvent = _CommandStartedEvent; +export type CommandSucceededEvent = _CommandSucceededEvent; +export type Connection = _Connection; +export type ConnectionCheckedInEvent = _ConnectionCheckedInEvent; +export type ConnectionCheckedOutEvent = _ConnectionCheckedOutEvent; +export type ConnectionCheckOutFailedEvent = _ConnectionCheckOutFailedEvent; +export type ConnectionCheckOutStartedEvent = _ConnectionCheckOutStartedEvent; +export type ConnectionClosedEvent = _ConnectionClosedEvent; +export type ConnectionCreatedEvent = _ConnectionCreatedEvent; +export type ConnectionPool = _ConnectionPool; +export type ConnectionPoolClearedEvent = _ConnectionPoolClearedEvent; +export type ConnectionPoolClosedEvent = _ConnectionPoolClosedEvent; +export type ConnectionPoolCreatedEvent = _ConnectionPoolCreatedEvent; +export type ConnectionPoolReadyEvent = _ConnectionPoolReadyEvent; +export type ConnectionReadyEvent = _ConnectionReadyEvent; +export type CSOTTimeoutContext = _CSOTTimeoutContext; +export type CursorTimeoutContext = _CursorTimeoutContext; +export type Db = _Db; +export type FindCursor = _FindCursor; +export type GridFSBucket = _GridFSBucket; +export type HostAddress = _HostAddress; +export type MongoClient = _MongoClient; +export type MongoCredentials = _MongoCredentials; +export type MongoError = _MongoError; +export type Monitor = _Monitor; +export type MonitorInterval = _MonitorInterval; +export type ObjectId = _ObjectId; +export type OnDemandDocument = _OnDemandDocument; +export type RTTSampler = _RTTSampler; +export type Server = _Server; +export type ServerApiVersion = _ServerApiVersion; +export type ServerClosedEvent = _ServerClosedEvent; +export type ServerDescription = _ServerDescription; +export type ServerDescriptionChangedEvent = _ServerDescriptionChangedEvent; +export type ServerHeartbeatFailedEvent = _ServerHeartbeatFailedEvent; +export type ServerHeartbeatStartedEvent = _ServerHeartbeatStartedEvent; +export type ServerHeartbeatSucceededEvent = _ServerHeartbeatSucceededEvent; +export type ServerOpeningEvent = _ServerOpeningEvent; +export type ServerSessionPool = _ServerSessionPool; +export type Timeout = _Timeout; +export type TimeoutContext = _TimeoutContext; +export type Topology = _Topology; +export type TopologyClosedEvent = _TopologyClosedEvent; +export type TopologyDescription = _TopologyDescription; +export type TopologyDescriptionChangedEvent = _TopologyDescriptionChangedEvent; +export type TopologyOpeningEvent = _TopologyOpeningEvent; +export type TopologyOptions = _TopologyOptions; +export type TopologyType = _TopologyType; +export type UUID = _UUID; + +// Export specific types from other files in the contextified module +// Hint: This list IS automatically alphabetized, so add new types anywhere in the list and it will stay organized +export type { AzureKMSRequestOptions } from './tools/runner/bundle/types/client-side-encryption/providers/azure'; +export type { AwsSigv4Options } from './tools/runner/bundle/types/cmap/auth/aws4'; +export type { + MongoDBOIDC, + OIDCCallbackFunction, + OIDCCallbackParams, + OIDCResponse +} from './tools/runner/bundle/types/cmap/auth/mongodb_oidc'; +import type { ClientBulkWriteCursorResponse as _ClientBulkWriteCursorResponse } from './tools/runner/bundle/types/cmap/wire_protocol/responses'; +export type ClientBulkWriteCursorResponse = _ClientBulkWriteCursorResponse; diff --git a/test/readme.md b/test/readme.md index 9baec615852..eadd83a90b7 100644 --- a/test/readme.md +++ b/test/readme.md @@ -43,9 +43,13 @@ about the types of tests and how to run them. - [AWS Authentication tests](#aws-authentication-tests) - [Running AWS tests](#running-aws-tests) - [Container Tests](#container-tests) + - [Node-less Runtime Testing](#node-less-runtime-testing) + - [Design](#design) + - [Running tests in Node-less Runtime](#running-tests-in-node-less-runtime) - [GCP](#gcp) - [Azure](#azure) - [AWS](#aws) + - [Running tests with TLS](#running-tests-with-tls) - [TODO Special Env Sections](#todo-special-env-sections) - [Testing driver changes with mongosh](#testing-driver-changes-with-mongosh) - [Point mongosh to the driver](#point-mongosh-to-the-driver) @@ -715,6 +719,49 @@ our existing integration test suite and run Evergreen patches against a single i _Note that in cases where the tests need to run longer than one hour to ensure that tokens expire that the mocha timeout must be increased in order for the test not to timeout._ +### Node-less Runtime Testing + +We are starting to remove explicit Node requirements, and are making it possible for users to provide us with the required functionality. + +To that end, need to run our tests in a Node-less environment. These tests need to fail if our code erroneously uses Node. + +#### Design + +The approach we are taking is to modify our unit and integration tests to run against a patched version of the driver, where any illegal `require` calls are blocked. + +Here are a few of the relevant components of this system: + +1. [test/mongodb_all.ts](test/mongodb.ts) + - Test entrypoint that exports Driver and all internal types. +2. [etc/bundle-driver.mjs](etc/bundle-driver.mjs) + - Creates a CommonJS bundle (Driver and all internal types) from `test/mongodb_all.ts`. +3. [test/tools/runner/vm_context_helper.ts](./tools/runner/vm_context_helper.ts) + - Special VM that blocks specific `require` calls. +4. [test/mongodb_bundled.ts](./mongodb_bundled.ts) + - Exports MongoDB from CommonJS bundle created by `etc/bundle-driver.mjs`, using `vm_context_helper.ts` to detect usages of blocked `require` calls. + - This file is currently maintained by hand and needs to export types explicitly. We may want to generate this file as well. +5. [test/mongodb.ts](./mongodb.ts) + - Generated "barrel file". It exports either `test/mongodb.ts` (Driver + all internal types) or `test/mongodb_bundled.ts` (Driver + all internal types, loaded from bundle, and using `vm_context_helper.ts` to block `require` calls.) +6. [etc/build-runtime-barrel.mjs](./etc/build-runtime-barrel.mjs) + - Generates the barrel file `test/mongodb.ts` based on `MONGODB_BUNDLED` env var. + +#### Running tests in Node-less Runtime + +To run opted-in unit or integration tests in a Node-less runtime, run: + + `npm run check:unit-bundled` +or + `npm run check:test-bundled` + +Either command will: + +1. Create a bundle from `test/mongodb.ts` +2. Regenerate the barrel file to export from the generated bundle +3. Run unit or integ tests + +Note: the barrel file will point to the bundle after either script is used. +You can either revert that change, or run `npm run switch:to-unbundled` to use the unbundled imports. + ## GCP 1. Add a new GCP prose test to `test/integration/auth/mongodb_oidc_gcp.prose.06.test.ts` that mimics the behaviour that @@ -748,7 +795,7 @@ We tests TLS in two suites in CI: Setting up a local environment is the same for both suites. -First, configure a server with TLS enabled by following the steps in [Runing the Tests Locally](#Running-the-Tests-Locally) with the environment +First, configure a server with TLS enabled by following the steps in [Runing the Tests Locally](#Running-the-Tests-Locally) with the environment variable `SSL=SSL` set. Then, in addition to setting the `MONGODB_URI` environment varialbe, set the following environment variables: diff --git a/test/tools/runner/config.ts b/test/tools/runner/config.ts index a16661f5d67..8f6078b79c3 100644 --- a/test/tools/runner/config.ts +++ b/test/tools/runner/config.ts @@ -220,7 +220,10 @@ export class TestConfiguration { return uri.indexOf('MONGODB-OIDC') > -1 && uri.indexOf(`ENVIRONMENT:${env}`) > -1; } - newClient(urlOrQueryOptions?: string | Record, serverOptions?: MongoClientOptions) { + newClient( + urlOrQueryOptions?: string | Record, + serverOptions?: MongoClientOptions + ): MongoClient { const baseOptions: MongoClientOptions = this.compressor ? { compressors: this.compressor @@ -239,7 +242,8 @@ export class TestConfiguration { throw new Error(`Cannot use options to specify host/port, must be in ${urlOrQueryOptions}`); } - return new MongoClient(urlOrQueryOptions, serverOptions); + const newClient: MongoClient = new MongoClient(urlOrQueryOptions, serverOptions); + return newClient; } const queryOptions = urlOrQueryOptions ?? {}; diff --git a/test/tools/runner/vm_context_helper.ts b/test/tools/runner/vm_context_helper.ts new file mode 100644 index 00000000000..64e3e5be9dd --- /dev/null +++ b/test/tools/runner/vm_context_helper.ts @@ -0,0 +1,126 @@ +/* eslint-disable @typescript-eslint/no-require-imports */ + +import * as fs from 'node:fs'; +import { isBuiltin } from 'node:module'; +import * as path from 'node:path'; +import * as vm from 'node:vm'; + +const allowedModules = new Set([ + '@aws-sdk/credential-providers', + '@mongodb-js/saslprep', + '@mongodb-js/zstd', + 'bson', + 'gcp-metadata', + 'kerberos', + 'mongodb-client-encryption', + 'mongodb-connection-string-url', + 'path', + 'snappy', + 'socks' +]); +const blockedModules = new Set(['os']); + +// TODO: NODE-7460 - Remove Error and other unnecessary exports +const exposedGlobals = new Set([ + 'AbortController', + 'AbortSignal', + 'BigInt', + 'Buffer', + 'Date', + 'Error', + 'Headers', + 'Map', + 'Math', + 'Promise', + 'TextDecoder', + 'TextEncoder', + 'URL', + 'URLSearchParams', + + 'console', + 'crypto', + 'performance', + 'process', + + 'clearImmediate', + 'clearInterval', + 'clearTimeout', + 'setImmediate', + 'setInterval', + 'setTimeout', + 'queueMicrotask' +]); + +/** + * Creates a require function that blocks access to specified core modules + */ +function createRestrictedRequire() { + return function restrictedRequire(moduleName: string) { + const isModuleBuiltin = isBuiltin(moduleName); + const isModuleAllowed = allowedModules.has(moduleName); + const isModuleBlocked = blockedModules.has(moduleName); + const shouldAllow = isModuleAllowed || isModuleBuiltin; + const shouldBlock = isModuleBlocked || !shouldAllow; + + if (shouldBlock) { + throw new Error(`Access to core module '${moduleName}' is restricted in this context`); + } + return require(moduleName); + } as NodeJS.Require; +} + +const context = { + __proto__: null, + + // Custom require that blocks core modules + require: createRestrictedRequire(), + + // Driver require + __driver_require: require, + + // Needed for some modules + global: undefined as any, + globalThis: undefined as any +}; + +// Expose allowed globals in the context +for (const globalName of exposedGlobals) { + if (globalName in global) { + context[globalName] = (global as any)[globalName]; + } +} + +// Create a sandbox context with necessary globals +const sandbox = vm.createContext(context); + +// Make global and globalThis point to the sandbox +sandbox.global = sandbox; +sandbox.globalThis = sandbox; + +/** + * Load the bundled MongoDB driver module in a VM context + * This allows us to control the globals that the driver has access to + */ +export function loadContextifiedMongoDBModule(): typeof import('../../mongodb_all') { + const bundlePath = path.join(__dirname, 'bundle/driver-bundle.js'); + + if (!fs.existsSync(bundlePath)) { + throw new Error(`Driver bundle not found at ${bundlePath}. Run 'npm run bundle:driver' first.`); + } + + const bundleCode = fs.readFileSync(bundlePath, 'utf8'); + + const exportsContainer = { __proto__: null }; + const moduleContainer = { __proto__: null, exports: exportsContainer }; + + // Wrap the bundle in a CommonJS-style wrapper + const wrapper = `(function(exports, module, require) {${bundleCode}})`; + + const script = new vm.Script(wrapper, { filename: bundlePath }); + const fn = script.runInContext(sandbox); + + // Execute the bundle with the restricted require from the sandbox + fn(moduleContainer.exports, moduleContainer, sandbox.require); + + return moduleContainer.exports as unknown as typeof import('../../mongodb_all'); +} diff --git a/test/tools/utils.ts b/test/tools/utils.ts index d587e9864d4..7a77b82a73d 100644 --- a/test/tools/utils.ts +++ b/test/tools/utils.ts @@ -14,6 +14,7 @@ import { inspect, promisify } from 'util'; import { type AnyClientBulkWriteModel, type Document, + EJSON, type HostAddress, MongoClient, type MongoClientOptions, @@ -32,6 +33,18 @@ export function ensureCalledWith(stub: any, args: any[]) { args.forEach((m: any) => expect(stub).to.have.been.calledWith(m)); } +export function checkTypeByName(obj: any, typeName: string): boolean { + if (obj !== null && obj.constructor != null && obj.constructor.name === typeName) { + return true; + } + return false; +} +export function ensureTypeByName(obj: any, typeName: string): void { + expect(obj).to.be.not.null; + expect(obj.constructor).to.be.not.null; + expect(obj.constructor.name).to.equal(typeName); +} + export class EventCollector { private _events: Record; private _timeout: number; diff --git a/test/unit/assorted/server_discovery_and_monitoring.spec.test.ts b/test/unit/assorted/server_discovery_and_monitoring.spec.test.ts index 7012836395b..c9abe0e5a4d 100644 --- a/test/unit/assorted/server_discovery_and_monitoring.spec.test.ts +++ b/test/unit/assorted/server_discovery_and_monitoring.spec.test.ts @@ -18,6 +18,7 @@ import { MongoServerError, ns, RunCommandOperation, + runNodelessTests, Server, SERVER_CLOSED, SERVER_DESCRIPTION_CHANGED, @@ -40,7 +41,7 @@ import { TopologyOpeningEvent, type TopologyVersion } from '../../mongodb'; -import { ejson, fakeServer } from '../../tools/utils'; +import { checkTypeByName, ejson, fakeServer } from '../../tools/utils'; const SDAM_EVENT_CLASSES = { ServerDescriptionChangedEvent, @@ -193,17 +194,25 @@ function assertMonitoringOutcome(outcome: any): asserts outcome is MonitoringOut describe('Server Discovery and Monitoring (spec)', function () { let serverConnect: sinon.SinonStub; - before(() => { + before(function () { serverConnect = sinon.stub(Server.prototype, 'connect').callsFake(function () { this.s.state = 'connected'; this.emit('connect'); }); }); - after(() => { + after(function () { serverConnect.restore(); }); + beforeEach(function () { + if (runNodelessTests) { + this.currentTest.skipReason = + 'SDAM spec tests rely heavily on stubbing Connection behavior, which is not currently possible in nodeless environments'; + this.currentTest.skip(); + } + }); + const specTests = collectTests(); for (const specTestName of Object.keys(specTests)) { describe(specTestName, () => { @@ -455,11 +464,11 @@ async function executeSDAMTest(testData: SDAMTest) { const isApplicationError = error => { // These errors all come from the withConnection stub - return ( - error instanceof MongoNetworkError || - error instanceof MongoNetworkTimeoutError || - error instanceof MongoServerError - ); + const result = + checkTypeByName(error, 'MongoNetworkError') || + checkTypeByName(error, 'MongoNetworkTimeoutError') || + checkTypeByName(error, 'MongoServerError'); + return result; }; expect( thrownError, diff --git a/test/unit/assorted/server_selection_spec_helper.js b/test/unit/assorted/server_selection_spec_helper.js index 573788c9e7d..0510573574a 100644 --- a/test/unit/assorted/server_selection_spec_helper.js +++ b/test/unit/assorted/server_selection_spec_helper.js @@ -1,6 +1,8 @@ 'use strict'; const { + writableServerSelector, + readPreferenceServerSelector, MongoServerSelectionError, ReadPreference, ServerType, @@ -119,11 +121,11 @@ export async function executeServerSelectionTest(testDefinition) { let selector; if (testDefinition.operation === 'write') { - selector = ServerSelectors.writableServerSelector(); + selector = writableServerSelector(); } else if (testDefinition.operation === 'read' || testDefinition.read_preference) { try { const readPreference = readPreferenceFromDefinition(testDefinition.read_preference); - selector = ServerSelectors.readPreferenceServerSelector(readPreference); + selector = readPreferenceServerSelector(readPreference); } catch (e) { if (testDefinition.error) return topology.close(); throw e; diff --git a/test/unit/client-side-encryption/client_encryption.test.ts b/test/unit/client-side-encryption/client_encryption.test.ts index 7914c6ae328..c5e26cc39ac 100644 --- a/test/unit/client-side-encryption/client_encryption.test.ts +++ b/test/unit/client-side-encryption/client_encryption.test.ts @@ -8,6 +8,7 @@ import { MongoCryptCreateDataKeyError, MongoCryptCreateEncryptedCollectionError } from '../../mongodb'; +import { ensureTypeByName } from '../../tools/utils'; class MockClient { options: any; s: { options: any }; @@ -99,27 +100,24 @@ describe('ClientEncryption', function () { const error = await clientEncryption .createEncryptedCollection(db, collectionName) .catch(error => error); - expect(error) - .to.be.instanceOf(TypeError) - .to.match(/provider/); + ensureTypeByName(error, 'TypeError'); + expect(error.message).to.match(/provider/); }); it('throws TypeError if options.createCollectionOptions are omitted', async () => { const error = await clientEncryption .createEncryptedCollection(db, collectionName, {}) .catch(error => error); - expect(error) - .to.be.instanceOf(TypeError) - .to.match(/encryptedFields/); + ensureTypeByName(error, 'TypeError'); + expect(error.message).to.match(/encryptedFields/); }); it('throws TypeError if options.createCollectionOptions.encryptedFields are omitted', async () => { const error = await clientEncryption .createEncryptedCollection(db, collectionName, { createCollectionOptions: {} }) .catch(error => error); - expect(error) - .to.be.instanceOf(TypeError) - .to.match(/Cannot read properties/); + ensureTypeByName(error, 'TypeError'); + expect(error.message).to.match(/Cannot read properties/); }); }); diff --git a/test/unit/client-side-encryption/providers/credentialsProvider.test.ts b/test/unit/client-side-encryption/providers/credentialsProvider.test.ts index 7e8ce19ebbc..6dd66db2e95 100644 --- a/test/unit/client-side-encryption/providers/credentialsProvider.test.ts +++ b/test/unit/client-side-encryption/providers/credentialsProvider.test.ts @@ -15,7 +15,7 @@ import { MongoNetworkTimeoutError, refreshKMSCredentials, tokenCache -} from '../../../mongodb'; +} from '../../../mongodb_all'; // continue to import from mongodb_all, skipping these tests for nodeless import * as requirements from '../requirements.helper'; const originalAccessKeyId = process.env.AWS_ACCESS_KEY_ID; diff --git a/test/unit/cmap/commands.test.ts b/test/unit/cmap/commands.test.ts index 5725f5b2490..3bd13de98f6 100644 --- a/test/unit/cmap/commands.test.ts +++ b/test/unit/cmap/commands.test.ts @@ -123,7 +123,7 @@ describe('commands', function () { it('throws an exception', function () { const response = new OpReply(message, header, body); - expect(() => response.parse()).to.throw(RangeError, /outside buffer bounds/); + expect(() => response.parse()).to.throw(/outside buffer bounds/); }); }); @@ -140,7 +140,7 @@ describe('commands', function () { it('throws an exception', function () { const response = new OpReply(message, header, body); - expect(() => response.parse()).to.throw(RangeError, /Invalid array length/i); + expect(() => response.parse()).to.throw(/Invalid array length/i); }); }); }); diff --git a/test/unit/cmap/handshake/client_metadata.test.ts b/test/unit/cmap/handshake/client_metadata.test.ts index 0915f2e2bd5..be8e2c2ca24 100644 --- a/test/unit/cmap/handshake/client_metadata.test.ts +++ b/test/unit/cmap/handshake/client_metadata.test.ts @@ -10,7 +10,8 @@ import { getFAASEnv, LimitedSizeDocument, makeClientMetadata, - MongoInvalidArgumentError + MongoInvalidArgumentError, + runNodelessTests } from '../../../mongodb'; import { runtime } from '../../../tools/utils'; describe('client metadata module', () => { @@ -315,6 +316,14 @@ describe('client metadata module', () => { }); context('when globalThis indicates alternative runtime', () => { + beforeEach(function () { + if (runNodelessTests) { + this.currentTest.skipReason = + 'These tests are meant to run in node and will fail in nodeless environments'; + this.currentTest.skip(); + } + }); + context('deno', () => { afterEach(() => { expect(delete globalThis.Deno, 'failed to delete Deno global').to.be.true; diff --git a/test/unit/commands.test.ts b/test/unit/commands.test.ts index 3f601c678c0..4bda290ac3b 100644 --- a/test/unit/commands.test.ts +++ b/test/unit/commands.test.ts @@ -11,6 +11,7 @@ import { OpCompressedRequest, OpMsgRequest, OpQueryRequest, + runNodelessTests, uncompressibleCommands } from '../mongodb'; @@ -89,20 +90,30 @@ describe('class OpCompressedRequest', () => { expect(compressedMessage).to.deep.equal(expectedCompressedCommand); }); - it('respects the zlib compression level', async () => { - const spy = sinon.spy(compression, 'compress'); - const [messageHeader] = await new OpCompressedRequest(msg, { - agreedCompressor: 'snappy', - zlibCompressionLevel: 3 - }).toBin(); + describe('zlib compression', function () { + before(function () { + if (runNodelessTests) { + this.currentTest.skipReason = + 'This test relies on sinon spying on the compress() function, which is not currently possible in nodeless environments'; + this.currentTest.skip(); + } + }); - expect(messageHeader.readInt32LE(12), 'opcode is not OP_COMPRESSED').to.equal(2012); + it('respects the zlib compression level', async function () { + const spy = sinon.spy(compression, 'compress'); + const [messageHeader] = await new OpCompressedRequest(msg, { + agreedCompressor: 'snappy', + zlibCompressionLevel: 3 + }).toBin(); - expect(spy).to.have.been.called; + expect(messageHeader.readInt32LE(12), 'opcode is not OP_COMPRESSED').to.equal(2012); - expect(spy.args[0][0]).to.deep.equal({ - agreedCompressor: 'snappy', - zlibCompressionLevel: 3 + expect(spy).to.have.been.called; + + expect(spy.args[0][0]).to.deep.equal({ + agreedCompressor: 'snappy', + zlibCompressionLevel: 3 + }); }); }); }); diff --git a/test/unit/mongo_client.test.ts b/test/unit/mongo_client.test.ts index 80e53450dd4..73650950899 100644 --- a/test/unit/mongo_client.test.ts +++ b/test/unit/mongo_client.test.ts @@ -23,6 +23,7 @@ import { SeverityLevel, WriteConcern } from '../mongodb'; +import { ensureTypeByName } from '../tools/utils'; describe('MongoClient', function () { it('programmatic options should override URI options', function () { @@ -1207,7 +1208,7 @@ describe('MongoClient', function () { it('when client.close is pending, client.closeLock is set', () => { client.close(); - expect(client.closeLock).to.be.instanceOf(Promise); + ensureTypeByName(client.closeLock, 'Promise'); }); it('when client.close is not pending, client.closeLock is not set', async () => { diff --git a/test/unit/nodeless.test.ts b/test/unit/nodeless.test.ts new file mode 100644 index 00000000000..655c65cdd71 --- /dev/null +++ b/test/unit/nodeless.test.ts @@ -0,0 +1,17 @@ +import { expect } from 'chai'; +import { env } from 'process'; + +import { runNodelessTests } from '../mongodb'; + +describe('Nodeless tests', function () { + it('runNodelessTests variable should match env vars', function () { + const nodelessEnv = env.MONGODB_BUNDLED; + const expectedNodeless = nodelessEnv === 'true'; + const actualNodeless = runNodelessTests; + expect(actualNodeless).to.equal( + expectedNodeless, + `runNodelessTests (${actualNodeless}) does not match MONGODB_BUNDLED env var (${nodelessEnv})` + + " run 'npm run build:runtime-barrel' to update the barrel file" + ); + }); +}); diff --git a/test/unit/sdam/monitor.test.ts b/test/unit/sdam/monitor.test.ts index 03edc953618..81af1450965 100644 --- a/test/unit/sdam/monitor.test.ts +++ b/test/unit/sdam/monitor.test.ts @@ -16,6 +16,7 @@ import { Monitor, MonitorInterval, RTTSampler, + runNodelessTests, ServerDescription, type ServerHeartbeatFailedEvent, type ServerHeartbeatStartedEvent, @@ -362,6 +363,12 @@ describe('monitoring', function () { let timerSandbox, clock, executor, fnSpy; beforeEach(function () { + if (runNodelessTests) { + this.currentTest.skipReason = + 'sinon.useFakeTimers is not yet supported in a nodeless environment'; + this.skip(); + } + timerSandbox = createTimerSandbox(); clock = sinon.useFakeTimers(); fnSpy = sinon.spy(cb => { @@ -370,6 +377,10 @@ describe('monitoring', function () { }); afterEach(function () { + if (runNodelessTests) { + this.skip(); + } + if (executor) { executor.stop(); } diff --git a/test/unit/utils.test.ts b/test/unit/utils.test.ts index e0783eb5302..003d5fabc7b 100644 --- a/test/unit/utils.test.ts +++ b/test/unit/utils.test.ts @@ -24,7 +24,7 @@ import { MongoRuntimeError, shuffle } from '../mongodb'; -import { sleep } from '../tools/utils'; +import { ensureTypeByName, sleep } from '../tools/utils'; describe('driver utils', function () { describe('.hasAtomicOperators', function () { @@ -463,8 +463,7 @@ describe('driver utils', function () { describe('*[Symbol.iterator]()', () => { it('should be instanceof GeneratorFunction', () => { const list = new List(); - // eslint-disable-next-line @typescript-eslint/no-empty-function - expect(list[Symbol.iterator]).to.be.instanceOf(function* () {}.constructor); + ensureTypeByName(list[Symbol.iterator], 'GeneratorFunction'); }); it('should only run generator for the number of items in the list', () => { diff --git a/tsconfig.json b/tsconfig.json index 74fb09c6ff8..6604ef28717 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -43,4 +43,4 @@ "include": [ "src/**/*" ] -} \ No newline at end of file +}