From 5817b0c7d7aa8778915247938add089e4c7008db Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Wed, 5 Feb 2025 00:46:18 -0800 Subject: [PATCH 01/64] chore!: migrate gax to Node 18 --- gax/migrate-to-node18.cjs | 64 ++++++++++++++++++++++++++ gax/package.json | 94 ++++++++++++++++++++------------------- gax/samples/package.json | 4 +- 3 files changed, 115 insertions(+), 47 deletions(-) create mode 100644 gax/migrate-to-node18.cjs diff --git a/gax/migrate-to-node18.cjs b/gax/migrate-to-node18.cjs new file mode 100644 index 000000000..a7f55f7f5 --- /dev/null +++ b/gax/migrate-to-node18.cjs @@ -0,0 +1,64 @@ +const path = require('path'); +const fs = require('fs'); +const execSync = require('child_process').execSync; + +const NODE_VERSION = '18'; +const PREV_NODE_VERSION = '14'; +async function main() { + // Grab package.json + const jsonPath = path.join(__dirname, 'package.json').toString(); + let packageJson = fs.readFileSync(jsonPath, 'utf8'); + packageJson = JSON.parse(packageJson); + + console.log('updating engines field...'); + packageJson.engines.node = `>=${NODE_VERSION}`; + fs.writeFileSync(jsonPath, JSON.stringify(packageJson, null, 2)); + + console.log('updating all dependencies to latest'); + if (packageJson.dependencies) { + for (const dep of Object.keys(packageJson.dependencies)) { + console.log(`npm i ${dep}@latest --engines-strict`); + execSync(`npm i ${dep}@latest --engines-strict`); + } + } + if (packageJson.devDependencies) { + for (const dep of Object.keys(packageJson.devDependencies)) { + console.log(`npm i ${dep}@latest -D --engines-strict`); + execSync(`npm i ${dep}@latest -D --engines-strict`); + } + } + + let samplesPackageJson; + let samplesJsonPath; + try { + samplesJsonPath = path + .join(__dirname, 'samples', 'package.json') + .toString(); + samplesPackageJson = fs.readFileSync(samplesJsonPath, 'utf8'); + samplesPackageJson = JSON.parse(samplesPackageJson); + } catch (err) { + console.log( + 'Repo does not have a samples directory; skipping updating samples' + ); + } + + if (samplesPackageJson) { + // Update engines field + console.log('updating samples engines field...'); + samplesPackageJson.engines.node = `>=${NODE_VERSION}`; + fs.writeFileSync( + samplesJsonPath, + JSON.stringify(samplesPackageJson, null, 2) + ); + } + + execSync( + `rm -rf .kokoro/continuous/node${PREV_NODE_VERSION} .kokoro/presubmit/node${PREV_NODE_VERSION}` + ); + execSync('npm login --registry https://wombat-dressing-room.appspot.com'); + execSync( + `npm dist-tag add ${packageJson.name}@${packageJson.version} legacy-${PREV_NODE_VERSION} --registry=https://wombat-dressing-room.appspot.com/` + ); +} + +main(); \ No newline at end of file diff --git a/gax/package.json b/gax/package.json index dece0f0cd..1733b1961 100644 --- a/gax/package.json +++ b/gax/package.json @@ -10,61 +10,60 @@ "!build/src/**/*.map" ], "dependencies": { - "@grpc/grpc-js": "^1.10.9", + "@grpc/grpc-js": "^1.12.6", "@grpc/proto-loader": "^0.7.13", "@types/long": "^5.0.0", "abort-controller": "^3.0.0", - "duplexify": "^4.0.0", - "google-auth-library": "^9.3.0", - "node-fetch": "^2.7.0", + "duplexify": "^4.1.3", + "google-auth-library": "^9.15.1", + "node-fetch": "^3.3.2", "object-hash": "^3.0.0", "proto3-json-serializer": "^2.0.2", - "retry-request": "^7.0.0", - "uuid": "^9.0.1", - "protobufjs": "^7.3.2" + "protobufjs": "^7.4.0", + "retry-request": "^7.0.2", + "uuid": "^11.0.5" }, "devDependencies": { - "@types/uuid": "^9.0.7", "@babel/plugin-proposal-private-methods": "^7.18.6", - "@types/mocha": "^9.0.0", - "@types/ncp": "^2.0.1", - "@types/node": "^20.5.0", - "@types/node-fetch": "^2.6.11", - "@types/object-hash": "^3.0.0", - "@types/proxyquire": "^1.3.28", - "@types/pumpify": "^1.4.1", - "@types/sinon": "^17.0.0", - "@types/uglify-js": "^3.17.0", - "c8": "^9.0.0", - "cheerio": "1.0.0-rc.12", - "codecov": "^3.1.0", - "execa": "^5.0.0", - "glob": "10.4.5", + "@types/mocha": "^10.0.10", + "@types/ncp": "^2.0.8", + "@types/node": "^22.13.1", + "@types/node-fetch": "^2.6.12", + "@types/object-hash": "^3.0.6", + "@types/proxyquire": "^1.3.31", + "@types/pumpify": "^1.4.4", + "@types/sinon": "^17.0.3", + "@types/uglify-js": "^3.17.5", + "@types/uuid": "^10.0.0", + "c8": "^10.1.3", + "cheerio": "^1.0.0", + "codecov": "^3.8.3", + "execa": "^9.5.2", + "glob": "^11.0.1", "google-proto-files": "^4.2.0", - "gts": "^5.0.0", - "jackspeak": "3.4.3", - "jsdoc": "^4.0.0", + "gts": "^6.0.2", + "jackspeak": "^4.0.2", + "jsdoc": "^4.0.4", "jsdoc-fresh": "^3.0.0", "jsdoc-region-tag": "^3.0.0", - "linkinator": "^4.0.0", - "lru-cache": "10.4.3", - "long": "^5.0.0", - "mkdirp": "^2.0.0", - "mocha": "^9.0.0", + "linkinator": "^6.1.2", + "long": "^5.2.4", + "lru-cache": "^11.0.2", + "mkdirp": "^3.0.1", + "mocha": "^11.1.0", "ncp": "^2.0.0", - "null-loader": "^4.0.0", - "pdfmake": "0.2.12", - "protobufjs-cli": "1.1.3", - "proxyquire": "^2.0.1", - "pumpify": "^2.0.0", - "sinon": "^18.0.0", - "stream-events": "^1.0.4", - "ts-loader": "^8.0.0", - "typescript": "^5.1.6", - "uglify-js": "^3.17.0", - "walkdir": "^0.4.0", - "webpack": "^4.0.0", - "webpack-cli": "^4.0.0" + "null-loader": "^4.0.1", + "pdfmake": "^0.2.18", + "protobufjs-cli": "^1.1.3", + "proxyquire": "^2.1.3", + "pumpify": "^2.0.1", + "sinon": "^19.0.2", + "stream-events": "^1.0.5", + "typescript": "^5.7.3", + "uglify-js": "^3.19.3", + "walkdir": "^0.4.1", + "webpack": "^5.97.1", + "webpack-cli": "^6.0.1" }, "scripts": { "docs": "jsdoc -c .jsdoc.js", @@ -95,6 +94,11 @@ "keywords": [ "grpc" ], + "exports": { + ".": "./build/src/index.js", + "./fallback": "./build/src/fallback.js", + "./gax": "./build/src/gax.js" + }, "repository": { "type": "git", "url": "https://github.com/googleapis/gax-nodejs.git", @@ -107,7 +111,7 @@ }, "homepage": "https://github.com/googleapis/gax-nodejs#readme", "engines": { - "node": ">=14" + "node": ">=18" }, "browser": "build/src/fallback.js" -} +} \ No newline at end of file diff --git a/gax/samples/package.json b/gax/samples/package.json index fe458a230..525850957 100644 --- a/gax/samples/package.json +++ b/gax/samples/package.json @@ -3,7 +3,7 @@ "license": "Apache-2.0", "author": "Google LLC", "engines": { - "node": ">=10" + "node": ">=18" }, "repository": "googleapis/gax-nodejs", "private": true, @@ -20,4 +20,4 @@ "c8": "^9.0.0", "mocha": "^9.0.0" } -} +} \ No newline at end of file From 0645b00a3364c080bf29771fdb178499cc192170 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Wed, 5 Feb 2025 00:48:06 -0800 Subject: [PATCH 02/64] cleanup --- gax/migrate-to-node18.cjs | 64 --------------------------------------- gax/package.json | 1 + 2 files changed, 1 insertion(+), 64 deletions(-) delete mode 100644 gax/migrate-to-node18.cjs diff --git a/gax/migrate-to-node18.cjs b/gax/migrate-to-node18.cjs deleted file mode 100644 index a7f55f7f5..000000000 --- a/gax/migrate-to-node18.cjs +++ /dev/null @@ -1,64 +0,0 @@ -const path = require('path'); -const fs = require('fs'); -const execSync = require('child_process').execSync; - -const NODE_VERSION = '18'; -const PREV_NODE_VERSION = '14'; -async function main() { - // Grab package.json - const jsonPath = path.join(__dirname, 'package.json').toString(); - let packageJson = fs.readFileSync(jsonPath, 'utf8'); - packageJson = JSON.parse(packageJson); - - console.log('updating engines field...'); - packageJson.engines.node = `>=${NODE_VERSION}`; - fs.writeFileSync(jsonPath, JSON.stringify(packageJson, null, 2)); - - console.log('updating all dependencies to latest'); - if (packageJson.dependencies) { - for (const dep of Object.keys(packageJson.dependencies)) { - console.log(`npm i ${dep}@latest --engines-strict`); - execSync(`npm i ${dep}@latest --engines-strict`); - } - } - if (packageJson.devDependencies) { - for (const dep of Object.keys(packageJson.devDependencies)) { - console.log(`npm i ${dep}@latest -D --engines-strict`); - execSync(`npm i ${dep}@latest -D --engines-strict`); - } - } - - let samplesPackageJson; - let samplesJsonPath; - try { - samplesJsonPath = path - .join(__dirname, 'samples', 'package.json') - .toString(); - samplesPackageJson = fs.readFileSync(samplesJsonPath, 'utf8'); - samplesPackageJson = JSON.parse(samplesPackageJson); - } catch (err) { - console.log( - 'Repo does not have a samples directory; skipping updating samples' - ); - } - - if (samplesPackageJson) { - // Update engines field - console.log('updating samples engines field...'); - samplesPackageJson.engines.node = `>=${NODE_VERSION}`; - fs.writeFileSync( - samplesJsonPath, - JSON.stringify(samplesPackageJson, null, 2) - ); - } - - execSync( - `rm -rf .kokoro/continuous/node${PREV_NODE_VERSION} .kokoro/presubmit/node${PREV_NODE_VERSION}` - ); - execSync('npm login --registry https://wombat-dressing-room.appspot.com'); - execSync( - `npm dist-tag add ${packageJson.name}@${packageJson.version} legacy-${PREV_NODE_VERSION} --registry=https://wombat-dressing-room.appspot.com/` - ); -} - -main(); \ No newline at end of file diff --git a/gax/package.json b/gax/package.json index 1733b1961..933be8f84 100644 --- a/gax/package.json +++ b/gax/package.json @@ -60,6 +60,7 @@ "sinon": "^19.0.2", "stream-events": "^1.0.5", "typescript": "^5.7.3", + "ts-loader": "^8.0.0", "uglify-js": "^3.19.3", "walkdir": "^0.4.1", "webpack": "^5.97.1", From 25cec21562efabdf1db45294928bdfb616bbe9e7 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Wed, 5 Feb 2025 00:56:19 -0800 Subject: [PATCH 03/64] chore: upgrade to node 18 --- .github/.OwlBot.lock.yaml | 2 +- .github/sync-repo-settings.yaml | 4 ++-- .github/workflows/ci.yaml | 22 ++++++++++---------- .kokoro/common.cfg | 2 +- .kokoro/continuous/node14/common.cfg | 24 ---------------------- .kokoro/continuous/node14/lint.cfg | 4 ---- .kokoro/continuous/node14/samples-test.cfg | 12 ----------- .kokoro/continuous/node14/system-test.cfg | 12 ----------- .kokoro/continuous/node14/test.cfg | 0 .kokoro/presubmit/node14/common.cfg | 24 ---------------------- .kokoro/presubmit/node14/samples-test.cfg | 12 ----------- .kokoro/presubmit/node14/system-test.cfg | 12 ----------- .kokoro/presubmit/node14/test.cfg | 0 .kokoro/release/docs.cfg | 2 +- .kokoro/release/publish.cfg | 2 +- .kokoro/samples-test.sh | 2 +- .kokoro/system-test.sh | 2 +- .kokoro/test.bat | 2 +- .kokoro/test.sh | 2 +- gax/test/browser-test/package.json | 2 +- gax/test/showcase-echo-client/package.json | 2 +- gax/test/showcase-server/package.json | 4 ++-- gax/test/test-application/package.json | 2 +- package.json | 2 +- 24 files changed, 27 insertions(+), 127 deletions(-) delete mode 100644 .kokoro/continuous/node14/common.cfg delete mode 100644 .kokoro/continuous/node14/lint.cfg delete mode 100644 .kokoro/continuous/node14/samples-test.cfg delete mode 100644 .kokoro/continuous/node14/system-test.cfg delete mode 100644 .kokoro/continuous/node14/test.cfg delete mode 100644 .kokoro/presubmit/node14/common.cfg delete mode 100644 .kokoro/presubmit/node14/samples-test.cfg delete mode 100644 .kokoro/presubmit/node14/system-test.cfg delete mode 100644 .kokoro/presubmit/node14/test.cfg diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 39a62ca6b..dd6699188 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-nodejs:latest - digest: sha256:0d39e59663287ae929c1d4ccf8ebf7cef9946826c9b86eda7e85d8d752dbb584 + digest: sha256:fe04ae044dadf5ad88d979dbcc85e0e99372fb5d6316790341e6aca5e4e3fbc8 # created: 2024-11-21T22:39:44.342569463Z diff --git a/.github/sync-repo-settings.yaml b/.github/sync-repo-settings.yaml index fa2795c8f..5f9e868b3 100644 --- a/.github/sync-repo-settings.yaml +++ b/.github/sync-repo-settings.yaml @@ -11,9 +11,9 @@ branchProtectionRules: - docs - lint-gax - lint-tools - - test-gax (14) + - test-gax (18) - test-gax (16) - - test-tools (14) + - test-tools (18) - test-tools (16) - cla/google - windows-gax diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index c686ad3bd..2b8b95cdd 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -9,7 +9,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - node: [14, 16] + node: [18, 20] steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -30,7 +30,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - node: [14, 16] + node: [18, 16] steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -51,7 +51,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - node: [14, 16] + node: [18, 20] steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -72,7 +72,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - node: [14, 16] + node: [18, 16] steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -95,7 +95,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - run: cd gax; npm install - run: cd gax; npm test env: @@ -106,7 +106,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - run: cd tools; npm install - run: cd tools; npm test env: @@ -117,7 +117,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - run: cd logging-utils; npm install - run: cd logging-utils; npm test env: @@ -128,7 +128,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - run: cd gax; npm install - run: cd gax; npm run lint lint-tools: @@ -137,7 +137,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - run: cd tools; npm install - run: cd tools; npm run lint lint-logging-utils: @@ -146,7 +146,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - run: cd logging-utils; npm install - run: cd logging-utils; npm run lint docs: @@ -155,7 +155,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - run: cd gax; npm install - run: cd gax; npm run docs - uses: JustinBeckwith/linkinator-action@v1 diff --git a/.kokoro/common.cfg b/.kokoro/common.cfg index bda58c77b..a205e8ffe 100644 --- a/.kokoro/common.cfg +++ b/.kokoro/common.cfg @@ -16,7 +16,7 @@ build_file: "gax-nodejs/.kokoro/trampoline_v2.sh" # Configure the docker image for kokoro-trampoline. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/node:14-user" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" } env_vars: { key: "TRAMPOLINE_BUILD_FILE" diff --git a/.kokoro/continuous/node14/common.cfg b/.kokoro/continuous/node14/common.cfg deleted file mode 100644 index bda58c77b..000000000 --- a/.kokoro/continuous/node14/common.cfg +++ /dev/null @@ -1,24 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -# Build logs will be here -action { - define_artifacts { - regex: "**/*sponge_log.xml" - } -} - -# Download trampoline resources. -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" - -# Use the trampoline script to run in docker. -build_file: "gax-nodejs/.kokoro/trampoline_v2.sh" - -# Configure the docker image for kokoro-trampoline. -env_vars: { - key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/node:14-user" -} -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/gax-nodejs/.kokoro/test.sh" -} diff --git a/.kokoro/continuous/node14/lint.cfg b/.kokoro/continuous/node14/lint.cfg deleted file mode 100644 index 018ec7aa0..000000000 --- a/.kokoro/continuous/node14/lint.cfg +++ /dev/null @@ -1,4 +0,0 @@ -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/gax-nodejs/.kokoro/lint.sh" -} diff --git a/.kokoro/continuous/node14/samples-test.cfg b/.kokoro/continuous/node14/samples-test.cfg deleted file mode 100644 index 3fb9c46ca..000000000 --- a/.kokoro/continuous/node14/samples-test.cfg +++ /dev/null @@ -1,12 +0,0 @@ -# Download resources for system tests (service account key, etc.) -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/gax-nodejs/.kokoro/samples-test.sh" -} - -env_vars: { - key: "SECRET_MANAGER_KEYS" - value: "long-door-651-kokoro-system-test-service-account" -} \ No newline at end of file diff --git a/.kokoro/continuous/node14/system-test.cfg b/.kokoro/continuous/node14/system-test.cfg deleted file mode 100644 index 8a980142a..000000000 --- a/.kokoro/continuous/node14/system-test.cfg +++ /dev/null @@ -1,12 +0,0 @@ -# Download resources for system tests (service account key, etc.) -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/gax-nodejs/.kokoro/system-test.sh" -} - -env_vars: { - key: "SECRET_MANAGER_KEYS" - value: "long-door-651-kokoro-system-test-service-account" -} \ No newline at end of file diff --git a/.kokoro/continuous/node14/test.cfg b/.kokoro/continuous/node14/test.cfg deleted file mode 100644 index e69de29bb..000000000 diff --git a/.kokoro/presubmit/node14/common.cfg b/.kokoro/presubmit/node14/common.cfg deleted file mode 100644 index bda58c77b..000000000 --- a/.kokoro/presubmit/node14/common.cfg +++ /dev/null @@ -1,24 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -# Build logs will be here -action { - define_artifacts { - regex: "**/*sponge_log.xml" - } -} - -# Download trampoline resources. -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" - -# Use the trampoline script to run in docker. -build_file: "gax-nodejs/.kokoro/trampoline_v2.sh" - -# Configure the docker image for kokoro-trampoline. -env_vars: { - key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/node:14-user" -} -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/gax-nodejs/.kokoro/test.sh" -} diff --git a/.kokoro/presubmit/node14/samples-test.cfg b/.kokoro/presubmit/node14/samples-test.cfg deleted file mode 100644 index 3fb9c46ca..000000000 --- a/.kokoro/presubmit/node14/samples-test.cfg +++ /dev/null @@ -1,12 +0,0 @@ -# Download resources for system tests (service account key, etc.) -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/gax-nodejs/.kokoro/samples-test.sh" -} - -env_vars: { - key: "SECRET_MANAGER_KEYS" - value: "long-door-651-kokoro-system-test-service-account" -} \ No newline at end of file diff --git a/.kokoro/presubmit/node14/system-test.cfg b/.kokoro/presubmit/node14/system-test.cfg deleted file mode 100644 index 8a980142a..000000000 --- a/.kokoro/presubmit/node14/system-test.cfg +++ /dev/null @@ -1,12 +0,0 @@ -# Download resources for system tests (service account key, etc.) -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/gax-nodejs/.kokoro/system-test.sh" -} - -env_vars: { - key: "SECRET_MANAGER_KEYS" - value: "long-door-651-kokoro-system-test-service-account" -} \ No newline at end of file diff --git a/.kokoro/presubmit/node14/test.cfg b/.kokoro/presubmit/node14/test.cfg deleted file mode 100644 index e69de29bb..000000000 diff --git a/.kokoro/release/docs.cfg b/.kokoro/release/docs.cfg index e83e720e8..7256aba7a 100644 --- a/.kokoro/release/docs.cfg +++ b/.kokoro/release/docs.cfg @@ -11,7 +11,7 @@ before_action { # doc publications use a Python image. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/node:14-user" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" } # Download trampoline resources. diff --git a/.kokoro/release/publish.cfg b/.kokoro/release/publish.cfg index 6e0e6efc9..f2b47538f 100644 --- a/.kokoro/release/publish.cfg +++ b/.kokoro/release/publish.cfg @@ -30,7 +30,7 @@ build_file: "gax-nodejs/.kokoro/trampoline_v2.sh" # Configure the docker image for kokoro-trampoline. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/node:14-user" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" } env_vars: { diff --git a/.kokoro/samples-test.sh b/.kokoro/samples-test.sh index 8c5d108cb..c1cb0fc77 100755 --- a/.kokoro/samples-test.sh +++ b/.kokoro/samples-test.sh @@ -56,7 +56,7 @@ fi # codecov combines coverage across integration and unit tests. Include # the logic below for any environment you wish to collect coverage for: -COVERAGE_NODE=14 +COVERAGE_NODE=18 if npx check-node-version@3.3.0 --silent --node $COVERAGE_NODE; then NYC_BIN=./node_modules/nyc/bin/nyc.js if [ -f "$NYC_BIN" ]; then diff --git a/.kokoro/system-test.sh b/.kokoro/system-test.sh index 1f6a2f6ac..1a7df166e 100755 --- a/.kokoro/system-test.sh +++ b/.kokoro/system-test.sh @@ -51,7 +51,7 @@ npm run system-test # codecov combines coverage across integration and unit tests. Include # the logic below for any environment you wish to collect coverage for: -COVERAGE_NODE=14 +COVERAGE_NODE=18 if npx check-node-version@3.3.0 --silent --node $COVERAGE_NODE; then NYC_BIN=./node_modules/nyc/bin/nyc.js if [ -f "$NYC_BIN" ]; then diff --git a/.kokoro/test.bat b/.kokoro/test.bat index 0bb124052..baa52982b 100644 --- a/.kokoro/test.bat +++ b/.kokoro/test.bat @@ -21,7 +21,7 @@ cd .. @rem we upgrade Node.js in the image: SET PATH=%PATH%;/cygdrive/c/Program Files/nodejs/npm -call nvm use v14.17.3 +call nvm use v18 call which node call npm install || goto :error diff --git a/.kokoro/test.sh b/.kokoro/test.sh index 862d478d3..0d9f6392a 100755 --- a/.kokoro/test.sh +++ b/.kokoro/test.sh @@ -39,7 +39,7 @@ npm test # codecov combines coverage across integration and unit tests. Include # the logic below for any environment you wish to collect coverage for: -COVERAGE_NODE=14 +COVERAGE_NODE=18 if npx check-node-version@3.3.0 --silent --node $COVERAGE_NODE; then NYC_BIN=./node_modules/nyc/bin/nyc.js if [ -f "$NYC_BIN" ]; then diff --git a/gax/test/browser-test/package.json b/gax/test/browser-test/package.json index 5171769db..45b4889ae 100644 --- a/gax/test/browser-test/package.json +++ b/gax/test/browser-test/package.json @@ -8,7 +8,7 @@ "build/test" ], "engines": { - "node": ">=14" + "node": ">=18" }, "license": "Apache-2.0", "keywords": [], diff --git a/gax/test/showcase-echo-client/package.json b/gax/test/showcase-echo-client/package.json index 3720c326f..32f42eda0 100644 --- a/gax/test/showcase-echo-client/package.json +++ b/gax/test/showcase-echo-client/package.json @@ -40,6 +40,6 @@ "typescript": "^4.5.5" }, "engines": { - "node": ">=v14" + "node": ">=v18" } } diff --git a/gax/test/showcase-server/package.json b/gax/test/showcase-server/package.json index 327552427..ca548d18f 100644 --- a/gax/test/showcase-server/package.json +++ b/gax/test/showcase-server/package.json @@ -22,10 +22,10 @@ }, "devDependencies": { "@types/download": "^8.0.1", - "@types/node": "^14.11.2", + "@types/node": "^18.11.2", "typescript": "^4.0.3" }, "engines": { - "node": ">=14" + "node": ">=18" } } diff --git a/gax/test/test-application/package.json b/gax/test/test-application/package.json index dbef3840c..6af31e90d 100644 --- a/gax/test/test-application/package.json +++ b/gax/test/test-application/package.json @@ -32,6 +32,6 @@ "showcase-server": "./showcase-server.tgz" }, "engines": { - "node": ">=14.0.0" + "node": ">=18.0.0" } } diff --git a/package.json b/package.json index e0003f91f..4717726b2 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,7 @@ "url": "https://github.com/googleapis/gax-nodejs/issues" }, "engines": { - "node": ">=14" + "node": ">=18" }, "homepage": "https://github.com/googleapis/gax-nodejs#readme" } From e4bb7737aeb0946e4850f4d13afb6e2d7600e3c2 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 5 Feb 2025 08:57:44 +0000 Subject: [PATCH 04/64] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .eslintignore | 1 - .github/CODEOWNERS | 7 +++++-- .github/auto-approve.yml | 3 ++- .github/release-trigger.yml | 1 - .kokoro/continuous/node12/lint.cfg | 4 ++++ .kokoro/continuous/node12/samples-test.cfg | 12 ++++++++++++ .kokoro/continuous/node12/system-test.cfg | 12 ++++++++++++ .kokoro/continuous/node12/test.cfg | 0 .kokoro/presubmit/node12/samples-test.cfg | 12 ++++++++++++ .kokoro/presubmit/node12/system-test.cfg | 12 ++++++++++++ .kokoro/presubmit/node12/test.cfg | 0 .kokoro/release/docs-devsite.cfg | 2 +- .kokoro/release/docs-devsite.sh | 5 ++--- .kokoro/release/docs.sh | 2 +- renovate.json | 1 - 15 files changed, 63 insertions(+), 11 deletions(-) create mode 100644 .kokoro/continuous/node12/lint.cfg create mode 100644 .kokoro/continuous/node12/samples-test.cfg create mode 100644 .kokoro/continuous/node12/system-test.cfg create mode 100644 .kokoro/continuous/node12/test.cfg create mode 100644 .kokoro/presubmit/node12/samples-test.cfg create mode 100644 .kokoro/presubmit/node12/system-test.cfg create mode 100644 .kokoro/presubmit/node12/test.cfg diff --git a/.eslintignore b/.eslintignore index c4a0963e9..ea5b04aeb 100644 --- a/.eslintignore +++ b/.eslintignore @@ -5,4 +5,3 @@ build/ docs/ protos/ samples/generated/ -system-test/**/fixtures diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index e436d6cfb..e643f1002 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -5,5 +5,8 @@ # https://help.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners#codeowners-syntax -# Unless specified, the jsteam is the default owner for nodejs repositories. -* @googleapis/actools @googleapis/jsteam \ No newline at end of file +# The yoshi-nodejs team is the default owner for nodejs repositories. +* @googleapis/yoshi-nodejs @googleapis/actools + +# The github automation team is the default owner for the auto-approve file. +.github/auto-approve.yml @googleapis/github-automation diff --git a/.github/auto-approve.yml b/.github/auto-approve.yml index 7cba0af63..4cd91cc16 100644 --- a/.github/auto-approve.yml +++ b/.github/auto-approve.yml @@ -1,2 +1,3 @@ processes: - - "NodeDependency" \ No newline at end of file + - "NodeDependency" + - "OwlBotTemplateChanges" diff --git a/.github/release-trigger.yml b/.github/release-trigger.yml index 6fd487cd1..d4ca94189 100644 --- a/.github/release-trigger.yml +++ b/.github/release-trigger.yml @@ -1,2 +1 @@ enabled: true -multiScmName: gax-nodejs \ No newline at end of file diff --git a/.kokoro/continuous/node12/lint.cfg b/.kokoro/continuous/node12/lint.cfg new file mode 100644 index 000000000..018ec7aa0 --- /dev/null +++ b/.kokoro/continuous/node12/lint.cfg @@ -0,0 +1,4 @@ +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/gax-nodejs/.kokoro/lint.sh" +} diff --git a/.kokoro/continuous/node12/samples-test.cfg b/.kokoro/continuous/node12/samples-test.cfg new file mode 100644 index 000000000..3fb9c46ca --- /dev/null +++ b/.kokoro/continuous/node12/samples-test.cfg @@ -0,0 +1,12 @@ +# Download resources for system tests (service account key, etc.) +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/gax-nodejs/.kokoro/samples-test.sh" +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "long-door-651-kokoro-system-test-service-account" +} \ No newline at end of file diff --git a/.kokoro/continuous/node12/system-test.cfg b/.kokoro/continuous/node12/system-test.cfg new file mode 100644 index 000000000..8a980142a --- /dev/null +++ b/.kokoro/continuous/node12/system-test.cfg @@ -0,0 +1,12 @@ +# Download resources for system tests (service account key, etc.) +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/gax-nodejs/.kokoro/system-test.sh" +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "long-door-651-kokoro-system-test-service-account" +} \ No newline at end of file diff --git a/.kokoro/continuous/node12/test.cfg b/.kokoro/continuous/node12/test.cfg new file mode 100644 index 000000000..e69de29bb diff --git a/.kokoro/presubmit/node12/samples-test.cfg b/.kokoro/presubmit/node12/samples-test.cfg new file mode 100644 index 000000000..3fb9c46ca --- /dev/null +++ b/.kokoro/presubmit/node12/samples-test.cfg @@ -0,0 +1,12 @@ +# Download resources for system tests (service account key, etc.) +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/gax-nodejs/.kokoro/samples-test.sh" +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "long-door-651-kokoro-system-test-service-account" +} \ No newline at end of file diff --git a/.kokoro/presubmit/node12/system-test.cfg b/.kokoro/presubmit/node12/system-test.cfg new file mode 100644 index 000000000..8a980142a --- /dev/null +++ b/.kokoro/presubmit/node12/system-test.cfg @@ -0,0 +1,12 @@ +# Download resources for system tests (service account key, etc.) +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/gax-nodejs/.kokoro/system-test.sh" +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "long-door-651-kokoro-system-test-service-account" +} \ No newline at end of file diff --git a/.kokoro/presubmit/node12/test.cfg b/.kokoro/presubmit/node12/test.cfg new file mode 100644 index 000000000..e69de29bb diff --git a/.kokoro/release/docs-devsite.cfg b/.kokoro/release/docs-devsite.cfg index e377d60d2..32bdd1e48 100644 --- a/.kokoro/release/docs-devsite.cfg +++ b/.kokoro/release/docs-devsite.cfg @@ -11,7 +11,7 @@ before_action { # doc publications use a Python image. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" + value: "gcr.io/cloud-devrel-kokoro-resources/node:14-user" } # Download trampoline resources. diff --git a/.kokoro/release/docs-devsite.sh b/.kokoro/release/docs-devsite.sh index 81a89f6c1..2198e67fe 100755 --- a/.kokoro/release/docs-devsite.sh +++ b/.kokoro/release/docs-devsite.sh @@ -25,6 +25,5 @@ if [[ -z "$CREDENTIALS" ]]; then fi npm install -npm install --no-save @google-cloud/cloud-rad@^0.4.0 -# publish docs to devsite -npx @google-cloud/cloud-rad . cloud-rad +npm install --no-save @google-cloud/cloud-rad@^0.2.5 +npx @google-cloud/cloud-rad \ No newline at end of file diff --git a/.kokoro/release/docs.sh b/.kokoro/release/docs.sh index e9079a605..1d8f3f490 100755 --- a/.kokoro/release/docs.sh +++ b/.kokoro/release/docs.sh @@ -16,7 +16,7 @@ set -eo pipefail -# build jsdocs (Python is installed on the Node 18 docker image). +# build jsdocs (Python is installed on the Node 10 docker image). if [[ -z "$CREDENTIALS" ]]; then # if CREDENTIALS are explicitly set, assume we're testing locally # and don't set NPM_CONFIG_PREFIX. diff --git a/renovate.json b/renovate.json index c5c702cf4..26428fcfc 100644 --- a/renovate.json +++ b/renovate.json @@ -4,7 +4,6 @@ "docker:disable", ":disableDependencyDashboard" ], - "constraintsFiltering": "strict", "pinVersions": false, "rebaseStalePrs": true, "schedule": [ From bb2ffeed5f6663cc36688a2286ee0b92f134dda2 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Wed, 5 Feb 2025 01:05:15 -0800 Subject: [PATCH 05/64] migrate to node 18 --- tools/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/package.json b/tools/package.json index 2e175337e..8b09bf223 100644 --- a/tools/package.json +++ b/tools/package.json @@ -58,6 +58,6 @@ "typescript": "^5.1.6" }, "engines": { - "node": ">=14" + "node": ">=18" } } From d6cf4a24565908188192e2d273d06274ac6f7641 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Wed, 5 Feb 2025 01:07:57 -0800 Subject: [PATCH 06/64] downgrade dep --- gax/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gax/package.json b/gax/package.json index 933be8f84..bb8684ad2 100644 --- a/gax/package.json +++ b/gax/package.json @@ -39,7 +39,7 @@ "cheerio": "^1.0.0", "codecov": "^3.8.3", "execa": "^9.5.2", - "glob": "^11.0.1", + "glob": "10.4.5", "google-proto-files": "^4.2.0", "gts": "^6.0.2", "jackspeak": "^4.0.2", From 5c3bb9e39bfd9fb6d25de2eee88d4bee35ce802d Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Wed, 5 Feb 2025 01:10:26 -0800 Subject: [PATCH 07/64] update package.json --- gax/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gax/package.json b/gax/package.json index bb8684ad2..19f3e6813 100644 --- a/gax/package.json +++ b/gax/package.json @@ -42,7 +42,7 @@ "glob": "10.4.5", "google-proto-files": "^4.2.0", "gts": "^6.0.2", - "jackspeak": "^4.0.2", + "jackspeak": "^3.0.2", "jsdoc": "^4.0.4", "jsdoc-fresh": "^3.0.0", "jsdoc-region-tag": "^3.0.0", From 41e6f43246e3ea9b8467f0db635c67cb1f73622c Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Wed, 5 Feb 2025 01:11:34 -0800 Subject: [PATCH 08/64] downgrade dep --- gax/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gax/package.json b/gax/package.json index 19f3e6813..319b63cce 100644 --- a/gax/package.json +++ b/gax/package.json @@ -48,7 +48,7 @@ "jsdoc-region-tag": "^3.0.0", "linkinator": "^6.1.2", "long": "^5.2.4", - "lru-cache": "^11.0.2", + "lru-cache": "^10.0.0", "mkdirp": "^3.0.1", "mocha": "^11.1.0", "ncp": "^2.0.0", From 77a09d90b5e828355a485fc9b73f0ef8fcfd369e Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Wed, 5 Feb 2025 10:59:10 -0800 Subject: [PATCH 09/64] chore: update to node-feth v3 and fix typings issues --- gax/package.json | 4 ++-- gax/src/fallbackServiceStub.ts | 11 ++++++++--- gax/test/showcase-server/src/index.ts | 2 +- gax/test/system-test/test.clientlibs.ts | 2 +- gax/tsconfig.json | 2 ++ 5 files changed, 14 insertions(+), 7 deletions(-) diff --git a/gax/package.json b/gax/package.json index 319b63cce..099946654 100644 --- a/gax/package.json +++ b/gax/package.json @@ -59,8 +59,8 @@ "pumpify": "^2.0.1", "sinon": "^19.0.2", "stream-events": "^1.0.5", - "typescript": "^5.7.3", "ts-loader": "^8.0.0", + "typescript": "^5.7.3", "uglify-js": "^3.19.3", "walkdir": "^0.4.1", "webpack": "^5.97.1", @@ -115,4 +115,4 @@ "node": ">=18" }, "browser": "build/src/fallback.js" -} \ No newline at end of file +} diff --git a/gax/src/fallbackServiceStub.ts b/gax/src/fallbackServiceStub.ts index cf28522b8..869a9e7f4 100644 --- a/gax/src/fallbackServiceStub.ts +++ b/gax/src/fallbackServiceStub.ts @@ -1,3 +1,4 @@ +/* eslint-disable prettier/prettier */ /** * Copyright 2021 Google LLC * @@ -17,8 +18,11 @@ /* global window */ /* global AbortController */ -import nodeFetch from 'node-fetch'; -import {Response as NodeFetchResponse, RequestInit} from 'node-fetch'; +import { + Response as NodeFetchResponse, + RequestInfo, + RequestInit, +} from 'node-fetch'; import {AbortController as NodeAbortController} from 'abort-controller'; import {hasWindowFetch, hasAbortController, isNodeJS} from './featureDetection'; @@ -27,6 +31,8 @@ import {StreamArrayParser} from './streamArrayParser'; import {pipeline, PipelineSource} from 'stream'; import type {Agent as HttpAgent} from 'http'; import type {Agent as HttpsAgent} from 'https'; +const nodeFetch = (url: URL | RequestInfo, request: RequestInit | undefined) => + import('node-fetch').then(({default: fetch}) => fetch(url, request)); interface NodeFetchType { (url: RequestInfo, init?: RequestInit): Promise; @@ -161,7 +167,6 @@ export function generateServiceStub( body: fetchParameters.body as | string | Buffer - | Uint8Array | undefined, method: fetchParameters.method, signal: cancelSignal, diff --git a/gax/test/showcase-server/src/index.ts b/gax/test/showcase-server/src/index.ts index a82c17087..846dcfe5a 100644 --- a/gax/test/showcase-server/src/index.ts +++ b/gax/test/showcase-server/src/index.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as execa from 'execa'; +import {execa} from 'execa'; import * as download from 'download'; import * as fs from 'fs'; import * as fsp from 'fs/promises'; diff --git a/gax/test/system-test/test.clientlibs.ts b/gax/test/system-test/test.clientlibs.ts index b236a7b3e..b750b0eed 100644 --- a/gax/test/system-test/test.clientlibs.ts +++ b/gax/test/system-test/test.clientlibs.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as execa from 'execa'; +import {execa} from 'execa'; import * as fs from 'fs'; import * as fsp from 'fs/promises'; import * as path from 'path'; diff --git a/gax/tsconfig.json b/gax/tsconfig.json index 0921b23c8..986489909 100644 --- a/gax/tsconfig.json +++ b/gax/tsconfig.json @@ -15,5 +15,7 @@ "src/*/*.ts", "test/system-test/*.ts", "test/unit/*.ts", + "*/*.json", + "test/fixtures/*.json" ] } From f0f5b2f8463092423cfed0697be253ce2cc97b1e Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Wed, 5 Feb 2025 11:09:24 -0800 Subject: [PATCH 10/64] downgrade execa --- gax/package.json | 2 +- gax/test/showcase-server/src/index.ts | 2 +- gax/test/system-test/test.clientlibs.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/gax/package.json b/gax/package.json index 099946654..809e53376 100644 --- a/gax/package.json +++ b/gax/package.json @@ -38,7 +38,7 @@ "c8": "^10.1.3", "cheerio": "^1.0.0", "codecov": "^3.8.3", - "execa": "^9.5.2", + "execa": "^5.0.0", "glob": "10.4.5", "google-proto-files": "^4.2.0", "gts": "^6.0.2", diff --git a/gax/test/showcase-server/src/index.ts b/gax/test/showcase-server/src/index.ts index 846dcfe5a..a82c17087 100644 --- a/gax/test/showcase-server/src/index.ts +++ b/gax/test/showcase-server/src/index.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import {execa} from 'execa'; +import * as execa from 'execa'; import * as download from 'download'; import * as fs from 'fs'; import * as fsp from 'fs/promises'; diff --git a/gax/test/system-test/test.clientlibs.ts b/gax/test/system-test/test.clientlibs.ts index b750b0eed..b236a7b3e 100644 --- a/gax/test/system-test/test.clientlibs.ts +++ b/gax/test/system-test/test.clientlibs.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import {execa} from 'execa'; +import * as execa from 'execa'; import * as fs from 'fs'; import * as fsp from 'fs/promises'; import * as path from 'path'; From 8557ddad850061911cab5ff0786fc763d7c46798 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Wed, 5 Feb 2025 11:15:30 -0800 Subject: [PATCH 11/64] try to make node-fetch v3 work --- gax/test/unit/grpc-fallback.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/gax/test/unit/grpc-fallback.ts b/gax/test/unit/grpc-fallback.ts index 0c3c94952..949f7e9c5 100644 --- a/gax/test/unit/grpc-fallback.ts +++ b/gax/test/unit/grpc-fallback.ts @@ -19,7 +19,8 @@ import * as assert from 'assert'; import {describe, it, beforeEach, afterEach, before, after} from 'mocha'; -import * as nodeFetch from 'node-fetch'; +const nodeFetch = (url: any, request: any) => + import('node-fetch').then(({default: fetch}) => fetch(url, request)); import * as abortController from 'abort-controller'; import * as protobuf from 'protobufjs'; import * as sinon from 'sinon'; From eb21931f66550702249fc00b304a81d6e954e50a Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Wed, 5 Feb 2025 11:16:51 -0800 Subject: [PATCH 12/64] update node version --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 2b8b95cdd..acb365ab3 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -72,7 +72,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - node: [18, 16] + node: [18, 20] steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 From 4417e5127ce62c59b2e64be7a60f8c8fc76bbbeb Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Wed, 5 Feb 2025 11:31:31 -0800 Subject: [PATCH 13/64] update regapic --- gax/test/unit/regapic.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/gax/test/unit/regapic.ts b/gax/test/unit/regapic.ts index 6c85e75dd..a8f9d1071 100644 --- a/gax/test/unit/regapic.ts +++ b/gax/test/unit/regapic.ts @@ -16,7 +16,6 @@ import * as assert from 'assert'; import {describe, it, afterEach, before} from 'mocha'; -import * as nodeFetch from 'node-fetch'; import * as protobuf from 'protobufjs'; import * as path from 'path'; import * as sinon from 'sinon'; @@ -27,6 +26,8 @@ import * as transcoding from '../../src/transcoding'; import {OAuth2Client} from 'google-auth-library'; import {GrpcClientOptions} from '../../src'; import {StreamArrayParser} from '../../src/streamArrayParser'; +const nodeFetch = (url: any, request: any) => + import('node-fetch').then(({default: fetch}) => fetch(url, request)); const authClient = { async getRequestHeaders() { From fafdf8d8c4770cbd2b4de4e3d0b1eb49f916fa98 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Wed, 5 Feb 2025 15:29:55 -0800 Subject: [PATCH 14/64] chore: update regapic imports --- gax/test/unit/regapic.ts | 758 ++++++++++++++++++++------------------- package-lock.json | 15 +- package.json | 5 +- 3 files changed, 414 insertions(+), 364 deletions(-) diff --git a/gax/test/unit/regapic.ts b/gax/test/unit/regapic.ts index a8f9d1071..a9d134dc0 100644 --- a/gax/test/unit/regapic.ts +++ b/gax/test/unit/regapic.ts @@ -22,10 +22,10 @@ import * as sinon from 'sinon'; import * as stream from 'stream'; import echoProtoJson = require('../fixtures/echo.json'); import {GrpcClient} from '../../src/fallback'; -import * as transcoding from '../../src/transcoding'; import {OAuth2Client} from 'google-auth-library'; import {GrpcClientOptions} from '../../src'; import {StreamArrayParser} from '../../src/streamArrayParser'; +import esmock from 'esmock'; const nodeFetch = (url: any, request: any) => import('node-fetch').then(({default: fetch}) => fetch(url, request)); @@ -51,7 +51,6 @@ const opts = { describe('REGAPIC', () => { let gaxGrpc: GrpcClient, gaxGrpcNumericEnums: GrpcClient, - gaxGrpcMinifyJson: GrpcClient, protos: protobuf.NamespaceBase, libProtos: protobuf.NamespaceBase, echoService: protobuf.Service, @@ -69,10 +68,6 @@ describe('REGAPIC', () => { ...opts, numericEnums: true, }); - gaxGrpcMinifyJson = new GrpcClient({ - ...opts, - minifyJson: true, - }); protos = gaxGrpc.loadProto(echoProtoJson); echoService = protos.lookupService('Echo'); const TEST_JSON = path.resolve( @@ -92,32 +87,42 @@ describe('REGAPIC', () => { sinon.restore(); }); - it('should make a request', done => { + it('should make a request', async () => { const requestObject = {content: 'test-content'}; - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(requestObject))); + + const {GrpcClient} = await esmock( + '../../src/fallback.js', + {}, + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(requestObject)) + ); + }, + }); }, - }) + } ); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { - echoStub.echo(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual(err, null); - assert.strictEqual( - requestObject.content, - (result as {content: string}).content - ); - done(); + const gaxGrpcMock = new GrpcClient(); + + (await gaxGrpcMock) + .createStub(echoService, stubOptions) + .then((echoStub: any) => { + echoStub.echo(requestObject, {}, {}, (err?: {}, result?: {}) => { + assert.strictEqual(err, null); + assert.strictEqual( + requestObject.content, + (result as {content: string}).content + ); + }); }); - }); }); - it('should make a streaming request', done => { + it('should make a streaming request', async () => { const requestObject = {content: 'test content'}; const responseObject = [{content: 'test'}, {content: 'content'}]; const responseObjectJson = JSON.stringify(responseObject, null, ' '); @@ -127,14 +132,22 @@ describe('REGAPIC', () => { responseStream.push(null); // incomplete types for nodeFetch, so... // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - body: responseStream, - }) + const {GrpcClient} = await esmock( + '../../src/fallback.js', + {}, + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + body: responseStream, + }); + }, + } ); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { + const gaxGrpcMock = new GrpcClient(); + + gaxGrpcMock.createStub(echoService, stubOptions).then((echoStub: any) => { const stream = echoStub.expand( requestObject, {}, @@ -142,165 +155,220 @@ describe('REGAPIC', () => { () => {} ) as StreamArrayParser; const results: {}[] = []; - stream.on('data', data => { + stream.on('data', (data: {}) => { results.push(data); }); - stream.on('error', done); + stream.on('error', () => { + return; + }); stream.on('end', () => { assert.deepStrictEqual(results, responseObject); - done(); }); }); }); - it('should handle fetch failure', done => { + it('should handle fetch failure', async () => { const requestObject = {content: 'test-content'}; - sinon - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - .stub(nodeFetch, 'Promise' as any) - .returns(Promise.reject(new Error('Fetch error'))); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { + const {GrpcClient} = await esmock( + '../../src/fallback.js', + {}, + { + 'node-fetch': () => { + return Promise.reject(new Error('Fetch error')); + }, + } + ); + + const gaxGrpcMock = new GrpcClient(); + + gaxGrpcMock.createStub(echoService, stubOptions).then((echoStub: any) => { echoStub.echo(requestObject, {}, {}, (err?: {}) => { assert.strictEqual((err as Error).message, 'Fetch error'); - done(); }); }); }); - it('should handle streaming request failure', done => { + it('should handle streaming request failure', async () => { const requestObject = {content: 'test content'}; - sinon - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - .stub(nodeFetch, 'Promise' as any) - .returns(Promise.reject(new Error('Fetch error'))); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { + const {GrpcClient} = await esmock( + '../../src/fallback.js', + {}, + { + 'node-fetch': () => { + return Promise.reject(new Error('Fetch error')); + }, + } + ); + + const gaxGrpcMock = new GrpcClient(); + gaxGrpc.createStub(echoService, stubOptions).then((echoStub: any) => { const stream = echoStub.expand(requestObject) as StreamArrayParser; - stream.on('error', err => { + stream.on('error', (err: Error) => { assert.strictEqual((err as Error).message, 'Fetch error'); - done(); }); }); }); describe('should support enum conversion in proto message', () => { - it('should support enum conversion in proto message response', done => { + it('should support enum conversion in proto message response', async () => { const requestObject = {name: 'shelves/shelf-name'}; const responseObject = { name: 'shelf-name', theme: 'shelf-theme', type: 1, }; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); + const spy = sinon.spy(); + + const {GrpcClient} = await esmock( + '../../src/fallback.js', + {}, + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)) + ); + }, + }); }, - }) + '../../src/transcoding.js': {transcode: spy}, + } ); - gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { - libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); - assert.strictEqual(err, null); - assert.strictEqual( - 'shelf-name', - (result as {name: {}; theme: {}; type: {}}).name - ); - assert.strictEqual( - 'TYPEONE', - (result as {name: {}; theme: {}; type: {}}).type - ); - done(); + const gaxGrpcMock = new GrpcClient(); + + gaxGrpcMock + .createStub(libraryService, stubOptions) + .then((libStub: any) => { + libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { + assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); + assert.strictEqual(err, null); + assert.strictEqual( + 'shelf-name', + (result as {name: {}; theme: {}; type: {}}).name + ); + assert.strictEqual( + 'TYPEONE', + (result as {name: {}; theme: {}; type: {}}).type + ); + }); }); - }, /* catch: */ done); }); - it('should support enum conversion in proto message request using symbolic name', done => { + it('should support enum conversion in proto message request using symbolic name', async () => { const shelf = { name: 'shelf-name', theme: 'shelf-theme', type: 'TYPEONE', }; const requestObject = {shelf: shelf}; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + const spy = sinon.spy(); + + const {GrpcClient} = await esmock( + '../../src/fallback.js', + {}, + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); }, - }) + '../../src/transcoding.js': {transcode: spy}, + } ); - gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { - libStub.createShelf(requestObject, {}, {}, (err?: {}) => { - assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); - assert.strictEqual(err, null); - done(); + + const gaxGrpcMock = new GrpcClient(); + + gaxGrpcMock + .createStub(libraryService, stubOptions) + .then((libStub: any) => { + libStub.createShelf(requestObject, {}, {}, (err?: {}) => { + assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); + assert.strictEqual(err, null); + }); }); - }, /* catch: */ done); }); - it('should support enum conversion in proto message request using type value', done => { + it('should support enum conversion in proto message request using type value', async () => { const shelf = { name: 'shelf-name', theme: 'shelf-theme', type: 1, }; const requestObject = {shelf: shelf}; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + const spy = sinon.spy(); + + const {GrpcClient} = await esmock( + '../../src/fallback.js', + {}, + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); }, - }) + '../../src/transcoding.js': {transcode: spy}, + } ); - gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { - libStub.createShelf(requestObject, {}, {}, (err?: {}) => { - assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); - assert.strictEqual(err, null); - done(); + + const gaxGrpcMock = new GrpcClient(); + gaxGrpcMock + .createStub(libraryService, stubOptions) + .then((libStub: any) => { + libStub.createShelf(requestObject, {}, {}, (err?: {}) => { + assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); + assert.strictEqual(err, null); + }); }); - }, /* catch: */ done); }); }); describe('should support enum conversion in proto message with numeric enums enabled', () => { - it('should support enum conversion in proto message response', done => { + it('should support enum conversion in proto message response', async () => { const requestObject = {name: 'shelves/shelf-name'}; const responseObject = { name: 'shelf-name', theme: 'shelf-theme', type: 100, // unknown enum value }; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); + const spy = sinon.spy(); + + const {GrpcClient} = await esmock( + '../../src/fallback.js', + {}, + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)) + ); + }, + }); }, - }) + '../../src/transcoding.js': {transcode: spy}, + } ); - gaxGrpcNumericEnums + const gaxGrpcNumericEnumsMock = new GrpcClient({ + ...opts, + numericEnums: true, + }); + + gaxGrpcNumericEnumsMock .createStub(libraryService, stubOptions) - .then(libStub => { + .then((libStub: any) => { libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { assert.strictEqual( spy.getCall(0).returnValue?.queryString, @@ -315,48 +383,53 @@ describe('REGAPIC', () => { 100, (result as {name: {}; theme: {}; type: {}}).type ); - done(); }); - }, /* catch: */ done); + }); }); - it('should request numeric enums if passed as symbolic name', done => { + it('should request numeric enums if passed as symbolic name', async () => { const shelf = { name: 'shelf-name', theme: 'shelf-theme', type: 'TYPEONE', }; const requestObject = {shelf: shelf}; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + const spy = sinon.spy(); + + const {GrpcClient} = await esmock( + '../../src/fallback.js', + {}, + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); }, - }) + '../../src/transcoding.js': {transcode: spy}, + } ); - gaxGrpcNumericEnums + + const gaxGrpcNumericEnumsMock = new GrpcClient({ + ...opts, + numericEnums: true, + }); + gaxGrpcNumericEnumsMock .createStub(libraryService, stubOptions) - .then(libStub => { + .then((libStub: any) => { libStub.createShelf(requestObject, {}, {}, (err?: {}) => { assert.strictEqual( - 'string', - typeof spy.getCall(0).returnValue?.queryString - ); - assert.match( - spy.getCall(0).returnValue?.queryString, - /\$alt=json%3Benum-encoding=int(&.*)?$/ + spy.getCall(0).returnValue?.queryString, + '$alt=json%3Benum-encoding=int' ); assert.strictEqual(err, null); - done(); }); - }, /* catch: */ done); + }); }); - it('should preserve query string when appending numeric enums parameter', done => { + it('should preserve query string when appending numeric enums parameter', async () => { const shelf = { name: 'shelf-name', theme: 'shelf-theme', @@ -366,66 +439,86 @@ describe('REGAPIC', () => { shelf: shelf, queryStringParameter: 'must-be-preserved', }; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + const spy = sinon.spy(); + + const {GrpcClient} = await esmock( + '../../src/fallback.js', + {}, + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); }, - }) + '../../src/transcoding.js': {transcode: spy}, + } ); - gaxGrpcNumericEnums + + const gaxGrpcNumericEnumsMock = new GrpcClient({ + ...opts, + numericEnums: true, + }); + gaxGrpcNumericEnumsMock .createStub(libraryService, stubOptions) - .then(libStub => { + .then((libStub: any) => { libStub.createShelf(requestObject, {}, {}, (err?: {}) => { assert.strictEqual( spy.getCall(0).returnValue?.queryString, 'queryStringParameter=must-be-preserved&$alt=json%3Benum-encoding=int' ); assert.strictEqual(err, null); - done(); }); - }, /* catch: */ done); + }); }); - it('should request numeric enums if passed as an unknown number', done => { + it('should request numeric enums if passed as an unknown number', async () => { const shelf = { name: 'shelf-name', theme: 'shelf-theme', type: 100, }; const requestObject = {shelf: shelf}; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + const spy = sinon.spy(); + + const {GrpcClient} = await esmock( + '../../src/fallback.js', + {}, + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); }, - }) + '../../src/transcoding.js': {transcode: spy}, + } ); - gaxGrpcNumericEnums + + const gaxGrpcNumericEnumsMock = new GrpcClient({ + ...opts, + numericEnums: true, + }); + gaxGrpcNumericEnumsMock .createStub(libraryService, stubOptions) - .then(libStub => { + .then((libStub: any) => { libStub.createShelf(requestObject, {}, {}, (err?: {}) => { assert.strictEqual( spy.getCall(0).returnValue?.queryString, '$alt=json%3Benum-encoding=int' ); assert.strictEqual(err, null); - done(); }); - }, /* catch: */ done); + }); }); }); describe('should support long data type conversion in proto message', () => { - it('large number long data type conversion in proto message response', done => { + it('large number long data type conversion in proto message response', async () => { const requestObject = {name: 'shelves/shelf-name/books/book-name'}; const responseObject = { name: 'book-name', @@ -434,49 +527,59 @@ describe('REGAPIC', () => { read: true, bookId: 9007199254740992, }; - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); + + const {GrpcClient} = await esmock( + '../../src/fallback.js', + {}, + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)) + ); + }, + }); }, - }) + } ); - gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { - libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual(err, null); - assert.strictEqual( - 'book-name', - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).name - ); - assert.strictEqual( - '9007199254740992', - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).bookId - ); - done(); + + const gaxGrpcMock = new GrpcClient(); + gaxGrpcMock + .createStub(libraryService, stubOptions) + .then((libStub: any) => { + libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { + assert.strictEqual(err, null); + assert.strictEqual( + 'book-name', + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).name + ); + assert.strictEqual( + '9007199254740992', + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).bookId + ); + }); }); - }, /* catch: */ done); }); - it('small number long data type conversion in proto message response', done => { + it('small number long data type conversion in proto message response', async () => { const requestObject = {name: 'shelves/shelf-name/books/book-name'}; const responseObject = { name: 'book-name', @@ -486,48 +589,58 @@ describe('REGAPIC', () => { bookId: 42, }; // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); + const {GrpcClient} = await esmock( + '../../src/fallback.js', + {}, + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)) + ); + }, + }); }, - }) + } ); - gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { - libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual(err, null); - assert.strictEqual( - 'book-name', - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).name - ); - assert.strictEqual( - '42', - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).bookId - ); - done(); + + const gaxGrpcMock = new GrpcClient(); + gaxGrpcMock + .createStub(libraryService, stubOptions) + .then((libStub: any) => { + libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { + assert.strictEqual(err, null); + assert.strictEqual( + 'book-name', + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).name + ); + assert.strictEqual( + '42', + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).bookId + ); + }); }); - }, /* catch: */ done); }); - it('long data type conversion in proto message request', done => { + it('long data type conversion in proto message request', async () => { const bookId = 9007199254740992; const requestObject = {name: `shelves/shelf-name/book_id/${bookId}`}; const responseObject = { @@ -539,134 +652,55 @@ describe('REGAPIC', () => { }; // incomplete types for nodeFetch, so... // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); - }, - }) - ); - gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { - libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual(err, null); - assert.strictEqual( - 'book-name', - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).name - ); - assert.strictEqual( - bookId.toString(), - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).bookId - ); - done(); - }); - }, /* catch: */ done); - }); - }); - - describe('should support json minification', () => { - it('should send prettyPrint=0 when json minification is requested', done => { - const requestObject = {name: 'shelves/shelf-name'}; - const responseObject = { - name: 'shelf-name', - theme: 'shelf-theme', - type: 100, // unknown enum value - }; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); + const {GrpcClient} = await esmock( + '../../src/fallback.js', + {}, + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)) + ); + }, + }); }, - }) + } ); - gaxGrpcMinifyJson + const gaxGrpcMock = new GrpcClient(); + gaxGrpcMock .createStub(libraryService, stubOptions) - .then(libStub => { - libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual( - 'string', - typeof spy.getCall(0).returnValue?.queryString - ); - assert.match( - spy.getCall(0).returnValue?.queryString, - /\$prettyPrint=0(&.*)?$/ - ); + .then((libStub: any) => { + libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { assert.strictEqual(err, null); assert.strictEqual( - 'shelf-name', - (result as {name: {}; theme: {}; type: {}}).name + 'book-name', + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).name ); assert.strictEqual( - 100, - (result as {name: {}; theme: {}; type: {}}).type + bookId.toString(), + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).bookId ); - done(); }); - }, /* catch: */ done); - }); - - it('should not send prettyPrint setting when json minification is not requested', done => { - const requestObject = {name: 'shelves/shelf-name'}; - const responseObject = { - name: 'shelf-name', - theme: 'shelf-theme', - type: 100, // unknown enum value - }; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); - }, - }) - ); - - gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { - libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual( - 'string', - typeof spy.getCall(0).returnValue?.queryString - ); - assert.doesNotMatch( - spy.getCall(0).returnValue?.queryString, - /prettyPrint/ - ); - assert.strictEqual(err, null); - assert.strictEqual( - 'shelf-name', - (result as {name: {}; theme: {}; type: {}}).name - ); - assert.strictEqual( - 100, - (result as {name: {}; theme: {}; type: {}}).type - ); - done(); }); - }, /* catch: */ done); }); }); }); diff --git a/package-lock.json b/package-lock.json index e12807202..fc6fd8d7c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6,8 +6,21 @@ "": { "name": "gax-nodejs", "license": "Apache-2.0", + "devDependencies": { + "esmock": "^2.7.0" + }, "engines": { - "node": ">=14" + "node": ">=18" + } + }, + "node_modules/esmock": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/esmock/-/esmock-2.7.0.tgz", + "integrity": "sha512-nYSvky0rP//13eYIGJ7b1dhsaBxtS370UoDWbILo1jHlO4hrCUkp/LD3e54QVhySxAGLsufxi5A4+wUAxPUIrg==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14.16.0" } } } diff --git a/package.json b/package.json index 4717726b2..d239dfe52 100644 --- a/package.json +++ b/package.json @@ -17,5 +17,8 @@ "engines": { "node": ">=18" }, - "homepage": "https://github.com/googleapis/gax-nodejs#readme" + "homepage": "https://github.com/googleapis/gax-nodejs#readme", + "devDependencies": { + "esmock": "^2.7.0" + } } From 2998c86ac0a71ae948bf58f647dcb03b0a510a2e Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Wed, 5 Feb 2025 15:37:32 -0800 Subject: [PATCH 15/64] reconfigure mocking --- gax/test/unit/regapic.ts | 352 ++++++++++++++++----------------------- package-lock.json | 136 ++++++++++++++- package.json | 3 +- 3 files changed, 283 insertions(+), 208 deletions(-) diff --git a/gax/test/unit/regapic.ts b/gax/test/unit/regapic.ts index a9d134dc0..ede89dfb4 100644 --- a/gax/test/unit/regapic.ts +++ b/gax/test/unit/regapic.ts @@ -25,9 +25,7 @@ import {GrpcClient} from '../../src/fallback'; import {OAuth2Client} from 'google-auth-library'; import {GrpcClientOptions} from '../../src'; import {StreamArrayParser} from '../../src/streamArrayParser'; -import esmock from 'esmock'; -const nodeFetch = (url: any, request: any) => - import('node-fetch').then(({default: fetch}) => fetch(url, request)); +import * as proxyquire from 'proxyquire'; const authClient = { async getRequestHeaders() { @@ -90,22 +88,16 @@ describe('REGAPIC', () => { it('should make a request', async () => { const requestObject = {content: 'test-content'}; - const {GrpcClient} = await esmock( - '../../src/fallback.js', - {}, - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve( - Buffer.from(JSON.stringify(requestObject)) - ); - }, - }); - }, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(requestObject))); + }, + }); + }, + }); const gaxGrpcMock = new GrpcClient(); @@ -132,18 +124,14 @@ describe('REGAPIC', () => { responseStream.push(null); // incomplete types for nodeFetch, so... // eslint-disable-next-line @typescript-eslint/no-explicit-any - const {GrpcClient} = await esmock( - '../../src/fallback.js', - {}, - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - body: responseStream, - }); - }, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + body: responseStream, + }); + }, + }); const gaxGrpcMock = new GrpcClient(); @@ -170,15 +158,11 @@ describe('REGAPIC', () => { it('should handle fetch failure', async () => { const requestObject = {content: 'test-content'}; - const {GrpcClient} = await esmock( - '../../src/fallback.js', - {}, - { - 'node-fetch': () => { - return Promise.reject(new Error('Fetch error')); - }, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.reject(new Error('Fetch error')); + }, + }); const gaxGrpcMock = new GrpcClient(); @@ -192,15 +176,11 @@ describe('REGAPIC', () => { it('should handle streaming request failure', async () => { const requestObject = {content: 'test content'}; - const {GrpcClient} = await esmock( - '../../src/fallback.js', - {}, - { - 'node-fetch': () => { - return Promise.reject(new Error('Fetch error')); - }, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.reject(new Error('Fetch error')); + }, + }); const gaxGrpcMock = new GrpcClient(); gaxGrpc.createStub(echoService, stubOptions).then((echoStub: any) => { @@ -221,23 +201,19 @@ describe('REGAPIC', () => { }; const spy = sinon.spy(); - const {GrpcClient} = await esmock( - '../../src/fallback.js', - {}, - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve( - Buffer.from(JSON.stringify(responseObject)) - ); - }, - }); - }, - '../../src/transcoding.js': {transcode: spy}, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)) + ); + }, + }); + }, + '../../src/transcoding.js': {transcode: spy}, + }); const gaxGrpcMock = new GrpcClient(); @@ -268,21 +244,17 @@ describe('REGAPIC', () => { const requestObject = {shelf: shelf}; const spy = sinon.spy(); - const {GrpcClient} = await esmock( - '../../src/fallback.js', - {}, - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); - }, - }); - }, - '../../src/transcoding.js': {transcode: spy}, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); + }, + '../../src/transcoding.js': {transcode: spy}, + }); const gaxGrpcMock = new GrpcClient(); @@ -305,21 +277,17 @@ describe('REGAPIC', () => { const requestObject = {shelf: shelf}; const spy = sinon.spy(); - const {GrpcClient} = await esmock( - '../../src/fallback.js', - {}, - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); - }, - }); - }, - '../../src/transcoding.js': {transcode: spy}, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); + }, + '../../src/transcoding.js': {transcode: spy}, + }); const gaxGrpcMock = new GrpcClient(); gaxGrpcMock @@ -343,23 +311,19 @@ describe('REGAPIC', () => { }; const spy = sinon.spy(); - const {GrpcClient} = await esmock( - '../../src/fallback.js', - {}, - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve( - Buffer.from(JSON.stringify(responseObject)) - ); - }, - }); - }, - '../../src/transcoding.js': {transcode: spy}, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)) + ); + }, + }); + }, + '../../src/transcoding.js': {transcode: spy}, + }); const gaxGrpcNumericEnumsMock = new GrpcClient({ ...opts, @@ -396,21 +360,17 @@ describe('REGAPIC', () => { const requestObject = {shelf: shelf}; const spy = sinon.spy(); - const {GrpcClient} = await esmock( - '../../src/fallback.js', - {}, - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); - }, - }); - }, - '../../src/transcoding.js': {transcode: spy}, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); + }, + '../../src/transcoding.js': {transcode: spy}, + }); const gaxGrpcNumericEnumsMock = new GrpcClient({ ...opts, @@ -441,21 +401,17 @@ describe('REGAPIC', () => { }; const spy = sinon.spy(); - const {GrpcClient} = await esmock( - '../../src/fallback.js', - {}, - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); - }, - }); - }, - '../../src/transcoding.js': {transcode: spy}, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); + }, + '../../src/transcoding.js': {transcode: spy}, + }); const gaxGrpcNumericEnumsMock = new GrpcClient({ ...opts, @@ -483,21 +439,17 @@ describe('REGAPIC', () => { const requestObject = {shelf: shelf}; const spy = sinon.spy(); - const {GrpcClient} = await esmock( - '../../src/fallback.js', - {}, - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); - }, - }); - }, - '../../src/transcoding.js': {transcode: spy}, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); + }, + '../../src/transcoding.js': {transcode: spy}, + }); const gaxGrpcNumericEnumsMock = new GrpcClient({ ...opts, @@ -528,22 +480,18 @@ describe('REGAPIC', () => { bookId: 9007199254740992, }; - const {GrpcClient} = await esmock( - '../../src/fallback.js', - {}, - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve( - Buffer.from(JSON.stringify(responseObject)) - ); - }, - }); - }, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)) + ); + }, + }); + }, + }); const gaxGrpcMock = new GrpcClient(); gaxGrpcMock @@ -589,22 +537,18 @@ describe('REGAPIC', () => { bookId: 42, }; // incomplete types for nodeFetch, so... - const {GrpcClient} = await esmock( - '../../src/fallback.js', - {}, - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve( - Buffer.from(JSON.stringify(responseObject)) - ); - }, - }); - }, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)) + ); + }, + }); + }, + }); const gaxGrpcMock = new GrpcClient(); gaxGrpcMock @@ -652,22 +596,18 @@ describe('REGAPIC', () => { }; // incomplete types for nodeFetch, so... // eslint-disable-next-line @typescript-eslint/no-explicit-any - const {GrpcClient} = await esmock( - '../../src/fallback.js', - {}, - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve( - Buffer.from(JSON.stringify(responseObject)) - ); - }, - }); - }, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)) + ); + }, + }); + }, + }); const gaxGrpcMock = new GrpcClient(); gaxGrpcMock diff --git a/package-lock.json b/package-lock.json index fc6fd8d7c..fe213798f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,7 +7,8 @@ "name": "gax-nodejs", "license": "Apache-2.0", "devDependencies": { - "esmock": "^2.7.0" + "esmock": "^2.7.0", + "proxyquire": "^2.1.3" }, "engines": { "node": ">=18" @@ -22,6 +23,139 @@ "engines": { "node": ">=14.16.0" } + }, + "node_modules/fill-keys": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/fill-keys/-/fill-keys-1.0.2.tgz", + "integrity": "sha512-tcgI872xXjwFF4xgQmLxi76GnwJG3g/3isB1l4/G5Z4zrbddGpBjqZCO9oEAcB5wX0Hj/5iQB3toxfO7in1hHA==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-object": "~1.0.1", + "merge-descriptors": "~1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/is-core-module": { + "version": "2.16.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", + "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-object": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-object/-/is-object-1.0.2.tgz", + "integrity": "sha512-2rRIahhZr2UWb45fIOuvZGpFtz0TyOZLf32KxBbSoUCeZR495zCKlWUKKUByk3geS2eAs7ZAABt0Y/Rx0GiQGA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/module-not-found-error": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/module-not-found-error/-/module-not-found-error-1.0.1.tgz", + "integrity": "sha512-pEk4ECWQXV6z2zjhRZUongnLJNUeGQJ3w6OQ5ctGwD+i5o93qjRQUk2Rt6VdNeu3sEP0AB4LcfvdebpxBRVr4g==", + "dev": true, + "license": "MIT" + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, + "node_modules/proxyquire": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/proxyquire/-/proxyquire-2.1.3.tgz", + "integrity": "sha512-BQWfCqYM+QINd+yawJz23tbBM40VIGXOdDw3X344KcclI/gtBbdWF6SlQ4nK/bYhF9d27KYug9WzljHC6B9Ysg==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-keys": "^1.0.2", + "module-not-found-error": "^1.0.1", + "resolve": "^1.11.1" + } + }, + "node_modules/resolve": { + "version": "1.22.10", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.10.tgz", + "integrity": "sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-core-module": "^2.16.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } } } } diff --git a/package.json b/package.json index d239dfe52..6135c3719 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,7 @@ }, "homepage": "https://github.com/googleapis/gax-nodejs#readme", "devDependencies": { - "esmock": "^2.7.0" + "esmock": "^2.7.0", + "proxyquire": "^2.1.3" } } From f513fc5265d1e7ecf5aa18a6dae69dcd2d3454cf Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Wed, 5 Feb 2025 16:03:12 -0800 Subject: [PATCH 16/64] chore: use node-fetch v3 --- gax/test/unit/grpc-fallback.ts | 186 ++++++++++++++++++++------------- gax/test/unit/regapic.ts | 14 +-- 2 files changed, 120 insertions(+), 80 deletions(-) diff --git a/gax/test/unit/grpc-fallback.ts b/gax/test/unit/grpc-fallback.ts index 949f7e9c5..557d518a5 100644 --- a/gax/test/unit/grpc-fallback.ts +++ b/gax/test/unit/grpc-fallback.ts @@ -27,6 +27,7 @@ import * as sinon from 'sinon'; import echoProtoJson = require('../fixtures/echo.json'); import {GrpcClient} from '../../src/fallback'; import {GoogleError} from '../../src'; +import * as proxyquire from 'proxyquire'; // @ts-ignore const hasAbortController = typeof AbortController !== 'undefined'; @@ -276,33 +277,36 @@ describe('grpc-fallback', () => { assert(headers['x-goog-api-client'][0].match('grpc-web/')); }); - it('should make a request', done => { + it('should make a request', async () => { const requestObject = {content: 'test-content'}; const responseType = protos.lookupType('EchoResponse'); const response = responseType.create(requestObject); // request === response for EchoService - //@ts-ignore - sinon.stub(nodeFetch, 'Promise').returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(response))); - }, - }) - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(response))); + }, + }); + }, + }); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { - echoStub.echo(requestObject, {}, {}, (err?: Error, result?: {}) => { - assert.strictEqual(err, null); - assert.strictEqual( - requestObject.content, - (result as {content: string}).content - ); - done(); + const gaxGrpcMock = new GrpcClient(); + gaxGrpcMock + .createStub(echoService, stubOptions) + .then((echoStub: {echo: any}) => { + echoStub.echo(requestObject, {}, {}, (err?: Error, result?: {}) => { + assert.strictEqual(err, null); + assert.strictEqual( + requestObject.content, + (result as {content: string}).content + ); + }); }); - }); }); - it('should handle an API error', done => { + it('should handle an API error', async () => { const requestObject = {content: 'test-content'}; // example of an actual google.rpc.Status error message returned by Language API const expectedMessage = @@ -335,16 +339,21 @@ describe('grpc-fallback', () => { }, ], }; - //@ts-ignore - sinon.stub(nodeFetch, 'Promise').returns( - Promise.resolve({ - ok: false, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(jsonError))); - }, - }) - ); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { + + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(jsonError))); + }, + }); + }, + }); + + const gaxGrpcMock = new GrpcClient(); + + gaxGrpcMock.createStub(echoService, stubOptions).then((echoStub: any) => { echoStub.echo(requestObject, {}, {}, (err?: Error) => { assert(err instanceof GoogleError); assert.strictEqual(err.message, expectedMessage); @@ -353,45 +362,48 @@ describe('grpc-fallback', () => { JSON.stringify(err.statusDetails), JSON.stringify(expectedError.details) ); - done(); }); }); }); - it('should handle a null response from the API ', done => { + it('should handle a null response from the API ', async () => { const requestObject = {content: 'test-content'}; const expectedMessage = 'Received null response from RPC Echo'; - //@ts-ignore - sinon.stub(nodeFetch, 'Promise').returns( - Promise.resolve({ - ok: false, - arrayBuffer: () => { - return Promise.resolve(Buffer.from('')); - }, - }) - ); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(expectedMessage))); + }, + }); + }, + }); + + const gaxGrpcMock = new GrpcClient(); + + gaxGrpcMock.createStub(echoService, stubOptions).then((echoStub: any) => { echoStub.echo(requestObject, {}, {}, (err?: Error) => { assert(err instanceof Error); assert.strictEqual(err.message, expectedMessage); - done(); }); }); }); - it('should handle a fetch error', done => { + it('should handle a fetch error', async () => { const requestObject = {content: 'test-content'}; - //@ts-ignore - sinon.stub(nodeFetch, 'Promise').rejects(new Error('fetch error')); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { - echoStub.echo(requestObject, {}, {}, (err?: Error) => { - assert.strictEqual(err?.message, 'fetch error'); - done(); - }); + + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.reject(new Error('fetch error')); + }, }); + + const gaxGrpcMock = new GrpcClient(); + gaxGrpcMock.createStub(echoService, stubOptions).then((echoStub: any) => { }); - it('should promote ErrorInfo if exist in fallback-rest error', done => { + it('should promote ErrorInfo if exist in fallback-rest error', async () => { const requestObject = {content: 'test-content'}; // example of an actual google.rpc.Status error message returned by Translate API const errorInfo = { @@ -427,18 +439,21 @@ describe('grpc-fallback', () => { auth: authStub, fallback: 'rest', }; - // @ts-ignore incomplete options - gaxGrpc = new GrpcClient(opts); - //@ts-ignore - sinon.stub(nodeFetch, 'Promise').returns( - Promise.resolve({ - ok: false, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(serverError))); - }, - }) - ); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { + + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(serverError))); + }, + }); + }, + }); + + const gaxGrpcMock = new GrpcClient(opts); + + gaxGrpcMock.createStub(echoService, stubOptions).then((echoStub: any) => { echoStub.echo(requestObject, {}, {}, (err?: Error) => { assert(err instanceof GoogleError); assert.strictEqual( @@ -453,16 +468,30 @@ describe('grpc-fallback', () => { JSON.stringify(err.errorInfoMetadata), JSON.stringify(errorInfo.metadata) ); - done(); }); }); }); it('should be able to cancel an API call using AbortController', async () => { - // @ts-ignore - sinon.stub(nodeFetch, 'Promise').returns(Promise.resolve({})); + const opts = { + auth: authStub, + fallback: 'rest', + }; + + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify({}))); + }, + }); + }, + }); + + const gaxGrpcMock = new GrpcClient(opts); + const echoStub = await gaxGrpcMock.createStub(echoService, stubOptions); - const echoStub = await gaxGrpc.createStub(echoService, stubOptions); const request = {content: 'content' + new Date().toString()}; const call = echoStub.echo(request, {}, {}, () => {}); @@ -472,12 +501,23 @@ describe('grpc-fallback', () => { assert.strictEqual(createdAbortControllers[0].abortCalled, true); }); - it('should have close method', done => { - // @ts-ignore - sinon.stub(nodeFetch, 'Promise').returns(Promise.resolve({})); - gaxGrpc.createStub(echoService, stubOptions).then(stub => { + it('should have close method', async () => { + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve({}); + }, + }); + }, + }); + + const gaxGrpcMock = new GrpcClient(); + + gaxGrpcMock.createStub(echoService, stubOptions).then((stub: any) => { stub.close({}, {}, {}, () => {}); - done(); }); }); }); +}); diff --git a/gax/test/unit/regapic.ts b/gax/test/unit/regapic.ts index ede89dfb4..1d3b32cad 100644 --- a/gax/test/unit/regapic.ts +++ b/gax/test/unit/regapic.ts @@ -212,7 +212,7 @@ describe('REGAPIC', () => { }, }); }, - '../../src/transcoding.js': {transcode: spy}, + 'transcoding.js': {transcode: spy}, }); const gaxGrpcMock = new GrpcClient(); @@ -253,7 +253,7 @@ describe('REGAPIC', () => { }, }); }, - '../../src/transcoding.js': {transcode: spy}, + 'transcoding.js': {transcode: spy}, }); const gaxGrpcMock = new GrpcClient(); @@ -286,7 +286,7 @@ describe('REGAPIC', () => { }, }); }, - '../../src/transcoding.js': {transcode: spy}, + 'transcoding.js': {transcode: spy}, }); const gaxGrpcMock = new GrpcClient(); @@ -322,7 +322,7 @@ describe('REGAPIC', () => { }, }); }, - '../../src/transcoding.js': {transcode: spy}, + 'transcoding.js': {transcode: spy}, }); const gaxGrpcNumericEnumsMock = new GrpcClient({ @@ -369,7 +369,7 @@ describe('REGAPIC', () => { }, }); }, - '../../src/transcoding.js': {transcode: spy}, + 'transcoding.js': {transcode: spy}, }); const gaxGrpcNumericEnumsMock = new GrpcClient({ @@ -410,7 +410,7 @@ describe('REGAPIC', () => { }, }); }, - '../../src/transcoding.js': {transcode: spy}, + 'transcoding.js': {transcode: spy}, }); const gaxGrpcNumericEnumsMock = new GrpcClient({ @@ -448,7 +448,7 @@ describe('REGAPIC', () => { }, }); }, - '../../src/transcoding.js': {transcode: spy}, + 'transcoding.js': {transcode: spy}, }); const gaxGrpcNumericEnumsMock = new GrpcClient({ From 014633260d0e5de1eb6ed37758a66949fc5ab9d3 Mon Sep 17 00:00:00 2001 From: sofisl <55454395+sofisl@users.noreply.github.com> Date: Wed, 5 Feb 2025 16:05:58 -0800 Subject: [PATCH 17/64] Update CODEOWNERS --- .github/CODEOWNERS | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index e643f1002..0cde21c3c 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -6,7 +6,4 @@ # The yoshi-nodejs team is the default owner for nodejs repositories. -* @googleapis/yoshi-nodejs @googleapis/actools - -# The github automation team is the default owner for the auto-approve file. -.github/auto-approve.yml @googleapis/github-automation +* @googleapis/jsteam @googleapis/actools From aee416790f719784b2d28c0a7087acecf1173254 Mon Sep 17 00:00:00 2001 From: sofisl <55454395+sofisl@users.noreply.github.com> Date: Wed, 5 Feb 2025 16:06:21 -0800 Subject: [PATCH 18/64] Update release-trigger.yml --- .github/release-trigger.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/release-trigger.yml b/.github/release-trigger.yml index d4ca94189..09d9f5e8a 100644 --- a/.github/release-trigger.yml +++ b/.github/release-trigger.yml @@ -1 +1,2 @@ enabled: true +multiScmName: gax-nodejs From 1f59b358b4febfb3a1e7c682837af08c511197f0 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 6 Feb 2025 00:08:22 +0000 Subject: [PATCH 19/64] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .github/CODEOWNERS | 5 ++++- .github/release-trigger.yml | 1 - 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 0cde21c3c..e643f1002 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -6,4 +6,7 @@ # The yoshi-nodejs team is the default owner for nodejs repositories. -* @googleapis/jsteam @googleapis/actools +* @googleapis/yoshi-nodejs @googleapis/actools + +# The github automation team is the default owner for the auto-approve file. +.github/auto-approve.yml @googleapis/github-automation diff --git a/.github/release-trigger.yml b/.github/release-trigger.yml index 09d9f5e8a..d4ca94189 100644 --- a/.github/release-trigger.yml +++ b/.github/release-trigger.yml @@ -1,2 +1 @@ enabled: true -multiScmName: gax-nodejs From f9f4fba264f52dd3b0d691f7103f162b137e7a2b Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 6 Feb 2025 00:09:25 +0000 Subject: [PATCH 20/64] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .github/CODEOWNERS | 5 ++++- .github/release-trigger.yml | 1 - 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 0cde21c3c..e643f1002 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -6,4 +6,7 @@ # The yoshi-nodejs team is the default owner for nodejs repositories. -* @googleapis/jsteam @googleapis/actools +* @googleapis/yoshi-nodejs @googleapis/actools + +# The github automation team is the default owner for the auto-approve file. +.github/auto-approve.yml @googleapis/github-automation diff --git a/.github/release-trigger.yml b/.github/release-trigger.yml index 09d9f5e8a..d4ca94189 100644 --- a/.github/release-trigger.yml +++ b/.github/release-trigger.yml @@ -1,2 +1 @@ enabled: true -multiScmName: gax-nodejs From 2df36905aa552dfe127de2043e5c69509be0727c Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 6 Feb 2025 00:09:34 +0000 Subject: [PATCH 21/64] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .github/CODEOWNERS | 5 ++++- .github/release-trigger.yml | 1 - 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 0cde21c3c..e643f1002 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -6,4 +6,7 @@ # The yoshi-nodejs team is the default owner for nodejs repositories. -* @googleapis/jsteam @googleapis/actools +* @googleapis/yoshi-nodejs @googleapis/actools + +# The github automation team is the default owner for the auto-approve file. +.github/auto-approve.yml @googleapis/github-automation diff --git a/.github/release-trigger.yml b/.github/release-trigger.yml index 09d9f5e8a..d4ca94189 100644 --- a/.github/release-trigger.yml +++ b/.github/release-trigger.yml @@ -1,2 +1 @@ enabled: true -multiScmName: gax-nodejs From c61ef4f2da717a017ba2bf7f6189d6b53b5d9021 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Thu, 6 Feb 2025 11:06:33 -0800 Subject: [PATCH 22/64] attempt to get browser tests working --- gax/test/showcase-echo-client/package.json | 2 +- gax/test/showcase-echo-client/tsconfig.json | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/gax/test/showcase-echo-client/package.json b/gax/test/showcase-echo-client/package.json index 32f42eda0..e4dc00ed7 100644 --- a/gax/test/showcase-echo-client/package.json +++ b/gax/test/showcase-echo-client/package.json @@ -37,7 +37,7 @@ "devDependencies": { "@types/node": "^20.11.26", "gapic-tools": "./gapic-tools.tgz", - "typescript": "^4.5.5" + "typescript": "^5.7.3" }, "engines": { "node": ">=v18" diff --git a/gax/test/showcase-echo-client/tsconfig.json b/gax/test/showcase-echo-client/tsconfig.json index 81cb00448..625c704d6 100644 --- a/gax/test/showcase-echo-client/tsconfig.json +++ b/gax/test/showcase-echo-client/tsconfig.json @@ -12,5 +12,8 @@ "include": [ "src/*.ts", "src/**/*.ts", + "*/*.json", + "*.json", + "'../../protos/protos.json" ] } From 9bba5b956ff9f9d0068ee5f2cdaba241ac334abb Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Thu, 6 Feb 2025 11:23:31 -0800 Subject: [PATCH 23/64] add json file to tsconfig --- gax/test/showcase-echo-client/tsconfig.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gax/test/showcase-echo-client/tsconfig.json b/gax/test/showcase-echo-client/tsconfig.json index 625c704d6..fa0b724e2 100644 --- a/gax/test/showcase-echo-client/tsconfig.json +++ b/gax/test/showcase-echo-client/tsconfig.json @@ -13,7 +13,7 @@ "src/*.ts", "src/**/*.ts", "*/*.json", - "*.json", + "./*.json", "'../../protos/protos.json" ] } From 383f9570576543d6faf62250387b70b97aeb6511 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Thu, 6 Feb 2025 11:44:49 -0800 Subject: [PATCH 24/64] retry --- gax/test/showcase-echo-client/tsconfig.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/gax/test/showcase-echo-client/tsconfig.json b/gax/test/showcase-echo-client/tsconfig.json index fa0b724e2..cad8a79b5 100644 --- a/gax/test/showcase-echo-client/tsconfig.json +++ b/gax/test/showcase-echo-client/tsconfig.json @@ -14,6 +14,8 @@ "src/**/*.ts", "*/*.json", "./*.json", - "'../../protos/protos.json" + "/echo_client_config.json", + "./sequence_service_client_config.json'", + "../../protos/protos.json" ] } From 49b3074adf563ba61b29623e65df08ea85c27646 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Fri, 7 Feb 2025 10:32:57 -0800 Subject: [PATCH 25/64] retry --- gax/package.json | 3 ++- gax/test/showcase-echo-client/tsconfig.json | 3 +-- gax/tsconfig.json | 3 ++- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/gax/package.json b/gax/package.json index 809e53376..a9fe5614d 100644 --- a/gax/package.json +++ b/gax/package.json @@ -98,7 +98,8 @@ "exports": { ".": "./build/src/index.js", "./fallback": "./build/src/fallback.js", - "./gax": "./build/src/gax.js" + "./gax": "./build/src/gax.js", + "./build/src/protobuf": "./build/src/protobuf" }, "repository": { "type": "git", diff --git a/gax/test/showcase-echo-client/tsconfig.json b/gax/test/showcase-echo-client/tsconfig.json index cad8a79b5..9de655ca2 100644 --- a/gax/test/showcase-echo-client/tsconfig.json +++ b/gax/test/showcase-echo-client/tsconfig.json @@ -12,9 +12,8 @@ "include": [ "src/*.ts", "src/**/*.ts", - "*/*.json", "./*.json", - "/echo_client_config.json", + "./echo_client_config.json", "./sequence_service_client_config.json'", "../../protos/protos.json" ] diff --git a/gax/tsconfig.json b/gax/tsconfig.json index 986489909..d100bcc08 100644 --- a/gax/tsconfig.json +++ b/gax/tsconfig.json @@ -16,6 +16,7 @@ "test/system-test/*.ts", "test/unit/*.ts", "*/*.json", - "test/fixtures/*.json" + "test/fixtures/*.json", + "test/showcase-echo-client/*/*.json" ] } From b1506ffc8fc55f587df66d4516c4f649a037b11b Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Fri, 7 Feb 2025 11:55:25 -0800 Subject: [PATCH 26/64] retry --- gax/package.json | 2 +- gax/test/showcase-echo-client/tsconfig.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/gax/package.json b/gax/package.json index a9fe5614d..a3bf3cf06 100644 --- a/gax/package.json +++ b/gax/package.json @@ -99,7 +99,7 @@ ".": "./build/src/index.js", "./fallback": "./build/src/fallback.js", "./gax": "./build/src/gax.js", - "./build/src/protobuf": "./build/src/protobuf" + "./build/src/protobuf": "./build/src/protobuf.js" }, "repository": { "type": "git", diff --git a/gax/test/showcase-echo-client/tsconfig.json b/gax/test/showcase-echo-client/tsconfig.json index 9de655ca2..d61cb4342 100644 --- a/gax/test/showcase-echo-client/tsconfig.json +++ b/gax/test/showcase-echo-client/tsconfig.json @@ -14,7 +14,7 @@ "src/**/*.ts", "./*.json", "./echo_client_config.json", - "./sequence_service_client_config.json'", + "./sequence_service_client_config.json", "../../protos/protos.json" ] } From 2124ee7d8cc37c8ab2027fd86f9413fc260f303f Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Fri, 7 Feb 2025 12:32:28 -0800 Subject: [PATCH 27/64] retry --- gax/test/showcase-echo-client/tsconfig.json | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/gax/test/showcase-echo-client/tsconfig.json b/gax/test/showcase-echo-client/tsconfig.json index d61cb4342..e43e06476 100644 --- a/gax/test/showcase-echo-client/tsconfig.json +++ b/gax/test/showcase-echo-client/tsconfig.json @@ -12,9 +12,7 @@ "include": [ "src/*.ts", "src/**/*.ts", - "./*.json", - "./echo_client_config.json", - "./sequence_service_client_config.json", - "../../protos/protos.json" + "src/**/*.json", + "protos/protos.json" ] } From 8b0fb9b9ed03c4fd9b004ac9872d197ccdf42ce1 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Fri, 7 Feb 2025 12:42:32 -0800 Subject: [PATCH 28/64] more ts changes --- gax/test/showcase-server/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gax/test/showcase-server/package.json b/gax/test/showcase-server/package.json index ca548d18f..54d7cd6bd 100644 --- a/gax/test/showcase-server/package.json +++ b/gax/test/showcase-server/package.json @@ -23,7 +23,7 @@ "devDependencies": { "@types/download": "^8.0.1", "@types/node": "^18.11.2", - "typescript": "^4.0.3" + "typescript": "^5.7.3" }, "engines": { "node": ">=18" From 08808cbde8ad4eab93f438081993f0d20da4ce9d Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Fri, 7 Feb 2025 13:37:43 -0800 Subject: [PATCH 29/64] retry --- gax/src/fallbackServiceStub.ts | 2 +- gax/test/browser-test/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/gax/src/fallbackServiceStub.ts b/gax/src/fallbackServiceStub.ts index 869a9e7f4..b85edc376 100644 --- a/gax/src/fallbackServiceStub.ts +++ b/gax/src/fallbackServiceStub.ts @@ -18,7 +18,7 @@ /* global window */ /* global AbortController */ -import { +import type { Response as NodeFetchResponse, RequestInfo, RequestInit, diff --git a/gax/test/browser-test/package.json b/gax/test/browser-test/package.json index 45b4889ae..56d93db33 100644 --- a/gax/test/browser-test/package.json +++ b/gax/test/browser-test/package.json @@ -40,7 +40,7 @@ "showcase-echo-client": "./showcase-echo-client.tgz", "showcase-server": "./showcase-server.tgz", "sinon": "^14.0.0", - "typescript": "^4.0.3", + "typescript": "^5.7.3", "webpack": "^4.0.0", "webpack-cli": "^4.0.0" } From 03edc2f93ecfc3e629fe6fe31b23d437011b45f4 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Fri, 7 Feb 2025 14:05:13 -0800 Subject: [PATCH 30/64] retry --- gax/src/fallbackServiceStub.ts | 16 ++++++++-------- gax/test/browser-test/tsconfig.json | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/gax/src/fallbackServiceStub.ts b/gax/src/fallbackServiceStub.ts index b85edc376..db4f31afc 100644 --- a/gax/src/fallbackServiceStub.ts +++ b/gax/src/fallbackServiceStub.ts @@ -18,11 +18,11 @@ /* global window */ /* global AbortController */ -import type { - Response as NodeFetchResponse, - RequestInfo, - RequestInit, -} from 'node-fetch'; +// import type { +// Response as NodeFetchResponse, +// RequestInfo, +// RequestInit, +// } from 'node-fetch'; import {AbortController as NodeAbortController} from 'abort-controller'; import {hasWindowFetch, hasAbortController, isNodeJS} from './featureDetection'; @@ -31,7 +31,7 @@ import {StreamArrayParser} from './streamArrayParser'; import {pipeline, PipelineSource} from 'stream'; import type {Agent as HttpAgent} from 'http'; import type {Agent as HttpsAgent} from 'https'; -const nodeFetch = (url: URL | RequestInfo, request: RequestInit | undefined) => +const nodeFetch = (url: any, request: any) => import('node-fetch').then(({default: fetch}) => fetch(url, request)); interface NodeFetchType { @@ -159,7 +159,7 @@ export function generateServiceStub( authClient .getRequestHeaders() .then(authHeader => { - const fetchRequest: RequestInit = { + const fetchRequest: any = { headers: { ...authHeader, ...headers, @@ -182,7 +182,7 @@ export function generateServiceStub( } return fetch(url, fetchRequest as {}); }) - .then((response: Response | NodeFetchResponse) => { + .then((response: any) => { if (response.ok && rpc.responseStream) { pipeline( response.body as PipelineSource, diff --git a/gax/test/browser-test/tsconfig.json b/gax/test/browser-test/tsconfig.json index 696defbe7..00a57df71 100644 --- a/gax/test/browser-test/tsconfig.json +++ b/gax/test/browser-test/tsconfig.json @@ -4,7 +4,7 @@ "rootDir": ".", "outDir": "build", "resolveJsonModule": true, - "lib": ["ES2018", "DOM"] + "lib": ["DOM"] }, "include": [ "src/**/*.ts", From 490ff7ab8ab0bd1b5a8f8b43c1e53bc24e9aa02b Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Fri, 7 Feb 2025 16:41:01 -0800 Subject: [PATCH 31/64] retry loading node fetch --- gax/src/fallbackServiceStub.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/gax/src/fallbackServiceStub.ts b/gax/src/fallbackServiceStub.ts index db4f31afc..328c1c2ab 100644 --- a/gax/src/fallbackServiceStub.ts +++ b/gax/src/fallbackServiceStub.ts @@ -31,9 +31,14 @@ import {StreamArrayParser} from './streamArrayParser'; import {pipeline, PipelineSource} from 'stream'; import type {Agent as HttpAgent} from 'http'; import type {Agent as HttpsAgent} from 'https'; -const nodeFetch = (url: any, request: any) => - import('node-fetch').then(({default: fetch}) => fetch(url, request)); +// const nodeFetch = (url: any, request: any) => +// import('node-fetch').then(({default: fetch}) => fetch(url, request)); +async function loadNodeFetch() { + return await import('node-fetch'); // Path to the module +} + +const nodeFetch = loadNodeFetch(); interface NodeFetchType { (url: RequestInfo, init?: RequestInit): Promise; } From f53600cd86d0b01b3092d874db2d0e2f39d8f380 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Fri, 7 Feb 2025 17:10:53 -0800 Subject: [PATCH 32/64] reattempt to lalow dynamic import --- gax/tsconfig.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/gax/tsconfig.json b/gax/tsconfig.json index d100bcc08..3b87b26f9 100644 --- a/gax/tsconfig.json +++ b/gax/tsconfig.json @@ -2,10 +2,13 @@ "extends": "./node_modules/gts/tsconfig-google.json", "compilerOptions": { "lib": ["es2018", "dom"], + "module": "commonjs", + "target": "es2018", "rootDir": ".", "outDir": "build", "noImplicitAny": true, - "resolveJsonModule": true + "resolveJsonModule": true, + "moduleResolution": "node" }, "include": [ "src/*.ts", From 7c74e6c9e894430f578e6075d1c196833197243a Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Fri, 7 Feb 2025 17:34:40 -0800 Subject: [PATCH 33/64] revert node-fetch --- gax/package.json | 2 +- gax/src/fallbackServiceStub.ts | 20 +++++--------------- gax/tsconfig.json | 8 +------- 3 files changed, 7 insertions(+), 23 deletions(-) diff --git a/gax/package.json b/gax/package.json index a3bf3cf06..6f17b4f8d 100644 --- a/gax/package.json +++ b/gax/package.json @@ -16,7 +16,7 @@ "abort-controller": "^3.0.0", "duplexify": "^4.1.3", "google-auth-library": "^9.15.1", - "node-fetch": "^3.3.2", + "node-fetch": "^2.7.0", "object-hash": "^3.0.0", "proto3-json-serializer": "^2.0.2", "protobufjs": "^7.4.0", diff --git a/gax/src/fallbackServiceStub.ts b/gax/src/fallbackServiceStub.ts index 328c1c2ab..cf28522b8 100644 --- a/gax/src/fallbackServiceStub.ts +++ b/gax/src/fallbackServiceStub.ts @@ -1,4 +1,3 @@ -/* eslint-disable prettier/prettier */ /** * Copyright 2021 Google LLC * @@ -18,11 +17,8 @@ /* global window */ /* global AbortController */ -// import type { -// Response as NodeFetchResponse, -// RequestInfo, -// RequestInit, -// } from 'node-fetch'; +import nodeFetch from 'node-fetch'; +import {Response as NodeFetchResponse, RequestInit} from 'node-fetch'; import {AbortController as NodeAbortController} from 'abort-controller'; import {hasWindowFetch, hasAbortController, isNodeJS} from './featureDetection'; @@ -31,14 +27,7 @@ import {StreamArrayParser} from './streamArrayParser'; import {pipeline, PipelineSource} from 'stream'; import type {Agent as HttpAgent} from 'http'; import type {Agent as HttpsAgent} from 'https'; -// const nodeFetch = (url: any, request: any) => -// import('node-fetch').then(({default: fetch}) => fetch(url, request)); -async function loadNodeFetch() { - return await import('node-fetch'); // Path to the module -} - -const nodeFetch = loadNodeFetch(); interface NodeFetchType { (url: RequestInfo, init?: RequestInit): Promise; } @@ -164,7 +153,7 @@ export function generateServiceStub( authClient .getRequestHeaders() .then(authHeader => { - const fetchRequest: any = { + const fetchRequest: RequestInit = { headers: { ...authHeader, ...headers, @@ -172,6 +161,7 @@ export function generateServiceStub( body: fetchParameters.body as | string | Buffer + | Uint8Array | undefined, method: fetchParameters.method, signal: cancelSignal, @@ -187,7 +177,7 @@ export function generateServiceStub( } return fetch(url, fetchRequest as {}); }) - .then((response: any) => { + .then((response: Response | NodeFetchResponse) => { if (response.ok && rpc.responseStream) { pipeline( response.body as PipelineSource, diff --git a/gax/tsconfig.json b/gax/tsconfig.json index 3b87b26f9..0921b23c8 100644 --- a/gax/tsconfig.json +++ b/gax/tsconfig.json @@ -2,13 +2,10 @@ "extends": "./node_modules/gts/tsconfig-google.json", "compilerOptions": { "lib": ["es2018", "dom"], - "module": "commonjs", - "target": "es2018", "rootDir": ".", "outDir": "build", "noImplicitAny": true, - "resolveJsonModule": true, - "moduleResolution": "node" + "resolveJsonModule": true }, "include": [ "src/*.ts", @@ -18,8 +15,5 @@ "src/*/*.ts", "test/system-test/*.ts", "test/unit/*.ts", - "*/*.json", - "test/fixtures/*.json", - "test/showcase-echo-client/*/*.json" ] } From b458afea23112e6867ca634fbc3347000638f032 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Fri, 7 Feb 2025 17:48:23 -0800 Subject: [PATCH 34/64] readd json files --- gax/test/browser-test/tsconfig.json | 3 ++- gax/tsconfig.json | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/gax/test/browser-test/tsconfig.json b/gax/test/browser-test/tsconfig.json index 00a57df71..21b519c62 100644 --- a/gax/test/browser-test/tsconfig.json +++ b/gax/test/browser-test/tsconfig.json @@ -8,6 +8,7 @@ }, "include": [ "src/**/*.ts", - "test/**/*.ts" + "test/**/*.ts", + "src/**/*.json", ] } diff --git a/gax/tsconfig.json b/gax/tsconfig.json index 0921b23c8..89730f442 100644 --- a/gax/tsconfig.json +++ b/gax/tsconfig.json @@ -15,5 +15,6 @@ "src/*/*.ts", "test/system-test/*.ts", "test/unit/*.ts", + "protos/protos/**/*.json" ] } From fe0010a61e78ae1740130296bdf255cd3ea558c8 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Fri, 7 Feb 2025 18:00:03 -0800 Subject: [PATCH 35/64] readd json files --- gax/test/unit/grpc-fallback.ts | 189 ++++----- gax/test/unit/regapic.ts | 747 +++++++++++++++++---------------- gax/tsconfig.json | 4 +- 3 files changed, 463 insertions(+), 477 deletions(-) diff --git a/gax/test/unit/grpc-fallback.ts b/gax/test/unit/grpc-fallback.ts index 557d518a5..0c3c94952 100644 --- a/gax/test/unit/grpc-fallback.ts +++ b/gax/test/unit/grpc-fallback.ts @@ -19,15 +19,13 @@ import * as assert from 'assert'; import {describe, it, beforeEach, afterEach, before, after} from 'mocha'; -const nodeFetch = (url: any, request: any) => - import('node-fetch').then(({default: fetch}) => fetch(url, request)); +import * as nodeFetch from 'node-fetch'; import * as abortController from 'abort-controller'; import * as protobuf from 'protobufjs'; import * as sinon from 'sinon'; import echoProtoJson = require('../fixtures/echo.json'); import {GrpcClient} from '../../src/fallback'; import {GoogleError} from '../../src'; -import * as proxyquire from 'proxyquire'; // @ts-ignore const hasAbortController = typeof AbortController !== 'undefined'; @@ -277,36 +275,33 @@ describe('grpc-fallback', () => { assert(headers['x-goog-api-client'][0].match('grpc-web/')); }); - it('should make a request', async () => { + it('should make a request', done => { const requestObject = {content: 'test-content'}; const responseType = protos.lookupType('EchoResponse'); const response = responseType.create(requestObject); // request === response for EchoService - const {GrpcClient} = await proxyquire('../../src/fallback.js', { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(response))); - }, - }); - }, - }); + //@ts-ignore + sinon.stub(nodeFetch, 'Promise').returns( + Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(response))); + }, + }) + ); - const gaxGrpcMock = new GrpcClient(); - gaxGrpcMock - .createStub(echoService, stubOptions) - .then((echoStub: {echo: any}) => { - echoStub.echo(requestObject, {}, {}, (err?: Error, result?: {}) => { - assert.strictEqual(err, null); - assert.strictEqual( - requestObject.content, - (result as {content: string}).content - ); - }); + gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { + echoStub.echo(requestObject, {}, {}, (err?: Error, result?: {}) => { + assert.strictEqual(err, null); + assert.strictEqual( + requestObject.content, + (result as {content: string}).content + ); + done(); }); + }); }); - it('should handle an API error', async () => { + it('should handle an API error', done => { const requestObject = {content: 'test-content'}; // example of an actual google.rpc.Status error message returned by Language API const expectedMessage = @@ -339,21 +334,16 @@ describe('grpc-fallback', () => { }, ], }; - - const {GrpcClient} = await proxyquire('../../src/fallback.js', { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(jsonError))); - }, - }); - }, - }); - - const gaxGrpcMock = new GrpcClient(); - - gaxGrpcMock.createStub(echoService, stubOptions).then((echoStub: any) => { + //@ts-ignore + sinon.stub(nodeFetch, 'Promise').returns( + Promise.resolve({ + ok: false, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(jsonError))); + }, + }) + ); + gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { echoStub.echo(requestObject, {}, {}, (err?: Error) => { assert(err instanceof GoogleError); assert.strictEqual(err.message, expectedMessage); @@ -362,48 +352,45 @@ describe('grpc-fallback', () => { JSON.stringify(err.statusDetails), JSON.stringify(expectedError.details) ); + done(); }); }); }); - it('should handle a null response from the API ', async () => { + it('should handle a null response from the API ', done => { const requestObject = {content: 'test-content'}; const expectedMessage = 'Received null response from RPC Echo'; - const {GrpcClient} = await proxyquire('../../src/fallback.js', { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(expectedMessage))); - }, - }); - }, - }); - - const gaxGrpcMock = new GrpcClient(); - - gaxGrpcMock.createStub(echoService, stubOptions).then((echoStub: any) => { + //@ts-ignore + sinon.stub(nodeFetch, 'Promise').returns( + Promise.resolve({ + ok: false, + arrayBuffer: () => { + return Promise.resolve(Buffer.from('')); + }, + }) + ); + gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { echoStub.echo(requestObject, {}, {}, (err?: Error) => { assert(err instanceof Error); assert.strictEqual(err.message, expectedMessage); + done(); }); }); }); - it('should handle a fetch error', async () => { + it('should handle a fetch error', done => { const requestObject = {content: 'test-content'}; - - const {GrpcClient} = await proxyquire('../../src/fallback.js', { - 'node-fetch': () => { - return Promise.reject(new Error('fetch error')); - }, + //@ts-ignore + sinon.stub(nodeFetch, 'Promise').rejects(new Error('fetch error')); + gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { + echoStub.echo(requestObject, {}, {}, (err?: Error) => { + assert.strictEqual(err?.message, 'fetch error'); + done(); + }); }); - - const gaxGrpcMock = new GrpcClient(); - gaxGrpcMock.createStub(echoService, stubOptions).then((echoStub: any) => { }); - it('should promote ErrorInfo if exist in fallback-rest error', async () => { + it('should promote ErrorInfo if exist in fallback-rest error', done => { const requestObject = {content: 'test-content'}; // example of an actual google.rpc.Status error message returned by Translate API const errorInfo = { @@ -439,21 +426,18 @@ describe('grpc-fallback', () => { auth: authStub, fallback: 'rest', }; - - const {GrpcClient} = await proxyquire('../../src/fallback.js', { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(serverError))); - }, - }); - }, - }); - - const gaxGrpcMock = new GrpcClient(opts); - - gaxGrpcMock.createStub(echoService, stubOptions).then((echoStub: any) => { + // @ts-ignore incomplete options + gaxGrpc = new GrpcClient(opts); + //@ts-ignore + sinon.stub(nodeFetch, 'Promise').returns( + Promise.resolve({ + ok: false, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(serverError))); + }, + }) + ); + gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { echoStub.echo(requestObject, {}, {}, (err?: Error) => { assert(err instanceof GoogleError); assert.strictEqual( @@ -468,30 +452,16 @@ describe('grpc-fallback', () => { JSON.stringify(err.errorInfoMetadata), JSON.stringify(errorInfo.metadata) ); + done(); }); }); }); it('should be able to cancel an API call using AbortController', async () => { - const opts = { - auth: authStub, - fallback: 'rest', - }; - - const {GrpcClient} = await proxyquire('../../src/fallback.js', { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify({}))); - }, - }); - }, - }); - - const gaxGrpcMock = new GrpcClient(opts); - const echoStub = await gaxGrpcMock.createStub(echoService, stubOptions); + // @ts-ignore + sinon.stub(nodeFetch, 'Promise').returns(Promise.resolve({})); + const echoStub = await gaxGrpc.createStub(echoService, stubOptions); const request = {content: 'content' + new Date().toString()}; const call = echoStub.echo(request, {}, {}, () => {}); @@ -501,23 +471,12 @@ describe('grpc-fallback', () => { assert.strictEqual(createdAbortControllers[0].abortCalled, true); }); - it('should have close method', async () => { - const {GrpcClient} = await proxyquire('../../src/fallback.js', { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve({}); - }, - }); - }, - }); - - const gaxGrpcMock = new GrpcClient(); - - gaxGrpcMock.createStub(echoService, stubOptions).then((stub: any) => { + it('should have close method', done => { + // @ts-ignore + sinon.stub(nodeFetch, 'Promise').returns(Promise.resolve({})); + gaxGrpc.createStub(echoService, stubOptions).then(stub => { stub.close({}, {}, {}, () => {}); + done(); }); }); }); -}); diff --git a/gax/test/unit/regapic.ts b/gax/test/unit/regapic.ts index 1d3b32cad..6c85e75dd 100644 --- a/gax/test/unit/regapic.ts +++ b/gax/test/unit/regapic.ts @@ -16,16 +16,17 @@ import * as assert from 'assert'; import {describe, it, afterEach, before} from 'mocha'; +import * as nodeFetch from 'node-fetch'; import * as protobuf from 'protobufjs'; import * as path from 'path'; import * as sinon from 'sinon'; import * as stream from 'stream'; import echoProtoJson = require('../fixtures/echo.json'); import {GrpcClient} from '../../src/fallback'; +import * as transcoding from '../../src/transcoding'; import {OAuth2Client} from 'google-auth-library'; import {GrpcClientOptions} from '../../src'; import {StreamArrayParser} from '../../src/streamArrayParser'; -import * as proxyquire from 'proxyquire'; const authClient = { async getRequestHeaders() { @@ -49,6 +50,7 @@ const opts = { describe('REGAPIC', () => { let gaxGrpc: GrpcClient, gaxGrpcNumericEnums: GrpcClient, + gaxGrpcMinifyJson: GrpcClient, protos: protobuf.NamespaceBase, libProtos: protobuf.NamespaceBase, echoService: protobuf.Service, @@ -66,6 +68,10 @@ describe('REGAPIC', () => { ...opts, numericEnums: true, }); + gaxGrpcMinifyJson = new GrpcClient({ + ...opts, + minifyJson: true, + }); protos = gaxGrpc.loadProto(echoProtoJson); echoService = protos.lookupService('Echo'); const TEST_JSON = path.resolve( @@ -85,36 +91,32 @@ describe('REGAPIC', () => { sinon.restore(); }); - it('should make a request', async () => { + it('should make a request', done => { const requestObject = {content: 'test-content'}; + // incomplete types for nodeFetch, so... + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sinon.stub(nodeFetch, 'Promise' as any).returns( + Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(requestObject))); + }, + }) + ); - const {GrpcClient} = await proxyquire('../../src/fallback.js', { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(requestObject))); - }, - }); - }, - }); - - const gaxGrpcMock = new GrpcClient(); - - (await gaxGrpcMock) - .createStub(echoService, stubOptions) - .then((echoStub: any) => { - echoStub.echo(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual(err, null); - assert.strictEqual( - requestObject.content, - (result as {content: string}).content - ); - }); + gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { + echoStub.echo(requestObject, {}, {}, (err?: {}, result?: {}) => { + assert.strictEqual(err, null); + assert.strictEqual( + requestObject.content, + (result as {content: string}).content + ); + done(); }); + }); }); - it('should make a streaming request', async () => { + it('should make a streaming request', done => { const requestObject = {content: 'test content'}; const responseObject = [{content: 'test'}, {content: 'content'}]; const responseObjectJson = JSON.stringify(responseObject, null, ' '); @@ -124,18 +126,14 @@ describe('REGAPIC', () => { responseStream.push(null); // incomplete types for nodeFetch, so... // eslint-disable-next-line @typescript-eslint/no-explicit-any - const {GrpcClient} = await proxyquire('../../src/fallback.js', { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - body: responseStream, - }); - }, - }); - - const gaxGrpcMock = new GrpcClient(); + sinon.stub(nodeFetch, 'Promise' as any).returns( + Promise.resolve({ + ok: true, + body: responseStream, + }) + ); - gaxGrpcMock.createStub(echoService, stubOptions).then((echoStub: any) => { + gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { const stream = echoStub.expand( requestObject, {}, @@ -143,196 +141,165 @@ describe('REGAPIC', () => { () => {} ) as StreamArrayParser; const results: {}[] = []; - stream.on('data', (data: {}) => { + stream.on('data', data => { results.push(data); }); - stream.on('error', () => { - return; - }); + stream.on('error', done); stream.on('end', () => { assert.deepStrictEqual(results, responseObject); + done(); }); }); }); - it('should handle fetch failure', async () => { + it('should handle fetch failure', done => { const requestObject = {content: 'test-content'}; + sinon + // incomplete types for nodeFetch, so... + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .stub(nodeFetch, 'Promise' as any) + .returns(Promise.reject(new Error('Fetch error'))); - const {GrpcClient} = await proxyquire('../../src/fallback.js', { - 'node-fetch': () => { - return Promise.reject(new Error('Fetch error')); - }, - }); - - const gaxGrpcMock = new GrpcClient(); - - gaxGrpcMock.createStub(echoService, stubOptions).then((echoStub: any) => { + gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { echoStub.echo(requestObject, {}, {}, (err?: {}) => { assert.strictEqual((err as Error).message, 'Fetch error'); + done(); }); }); }); - it('should handle streaming request failure', async () => { + it('should handle streaming request failure', done => { const requestObject = {content: 'test content'}; + sinon + // incomplete types for nodeFetch, so... + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .stub(nodeFetch, 'Promise' as any) + .returns(Promise.reject(new Error('Fetch error'))); - const {GrpcClient} = await proxyquire('../../src/fallback.js', { - 'node-fetch': () => { - return Promise.reject(new Error('Fetch error')); - }, - }); - - const gaxGrpcMock = new GrpcClient(); - gaxGrpc.createStub(echoService, stubOptions).then((echoStub: any) => { + gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { const stream = echoStub.expand(requestObject) as StreamArrayParser; - stream.on('error', (err: Error) => { + stream.on('error', err => { assert.strictEqual((err as Error).message, 'Fetch error'); + done(); }); }); }); describe('should support enum conversion in proto message', () => { - it('should support enum conversion in proto message response', async () => { + it('should support enum conversion in proto message response', done => { const requestObject = {name: 'shelves/shelf-name'}; const responseObject = { name: 'shelf-name', theme: 'shelf-theme', type: 1, }; - const spy = sinon.spy(); - - const {GrpcClient} = await proxyquire('../../src/fallback.js', { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve( - Buffer.from(JSON.stringify(responseObject)) - ); - }, - }); - }, - 'transcoding.js': {transcode: spy}, - }); - - const gaxGrpcMock = new GrpcClient(); + const spy = sinon.spy(transcoding, 'transcode'); + // incomplete types for nodeFetch, so... + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sinon.stub(nodeFetch, 'Promise' as any).returns( + Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); + }, + }) + ); - gaxGrpcMock - .createStub(libraryService, stubOptions) - .then((libStub: any) => { - libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); - assert.strictEqual(err, null); - assert.strictEqual( - 'shelf-name', - (result as {name: {}; theme: {}; type: {}}).name - ); - assert.strictEqual( - 'TYPEONE', - (result as {name: {}; theme: {}; type: {}}).type - ); - }); + gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { + libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { + assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); + assert.strictEqual(err, null); + assert.strictEqual( + 'shelf-name', + (result as {name: {}; theme: {}; type: {}}).name + ); + assert.strictEqual( + 'TYPEONE', + (result as {name: {}; theme: {}; type: {}}).type + ); + done(); }); + }, /* catch: */ done); }); - it('should support enum conversion in proto message request using symbolic name', async () => { + it('should support enum conversion in proto message request using symbolic name', done => { const shelf = { name: 'shelf-name', theme: 'shelf-theme', type: 'TYPEONE', }; const requestObject = {shelf: shelf}; - const spy = sinon.spy(); - - const {GrpcClient} = await proxyquire('../../src/fallback.js', { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); - }, - }); - }, - 'transcoding.js': {transcode: spy}, - }); - - const gaxGrpcMock = new GrpcClient(); - - gaxGrpcMock - .createStub(libraryService, stubOptions) - .then((libStub: any) => { - libStub.createShelf(requestObject, {}, {}, (err?: {}) => { - assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); - assert.strictEqual(err, null); - }); + const spy = sinon.spy(transcoding, 'transcode'); + // incomplete types for nodeFetch, so... + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sinon.stub(nodeFetch, 'Promise' as any).returns( + Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }) + ); + gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { + libStub.createShelf(requestObject, {}, {}, (err?: {}) => { + assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); + assert.strictEqual(err, null); + done(); }); + }, /* catch: */ done); }); - it('should support enum conversion in proto message request using type value', async () => { + it('should support enum conversion in proto message request using type value', done => { const shelf = { name: 'shelf-name', theme: 'shelf-theme', type: 1, }; const requestObject = {shelf: shelf}; - const spy = sinon.spy(); - - const {GrpcClient} = await proxyquire('../../src/fallback.js', { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); - }, - }); - }, - 'transcoding.js': {transcode: spy}, - }); - - const gaxGrpcMock = new GrpcClient(); - gaxGrpcMock - .createStub(libraryService, stubOptions) - .then((libStub: any) => { - libStub.createShelf(requestObject, {}, {}, (err?: {}) => { - assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); - assert.strictEqual(err, null); - }); + const spy = sinon.spy(transcoding, 'transcode'); + // incomplete types for nodeFetch, so... + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sinon.stub(nodeFetch, 'Promise' as any).returns( + Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }) + ); + gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { + libStub.createShelf(requestObject, {}, {}, (err?: {}) => { + assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); + assert.strictEqual(err, null); + done(); }); + }, /* catch: */ done); }); }); describe('should support enum conversion in proto message with numeric enums enabled', () => { - it('should support enum conversion in proto message response', async () => { + it('should support enum conversion in proto message response', done => { const requestObject = {name: 'shelves/shelf-name'}; const responseObject = { name: 'shelf-name', theme: 'shelf-theme', type: 100, // unknown enum value }; - const spy = sinon.spy(); - - const {GrpcClient} = await proxyquire('../../src/fallback.js', { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve( - Buffer.from(JSON.stringify(responseObject)) - ); - }, - }); - }, - 'transcoding.js': {transcode: spy}, - }); - - const gaxGrpcNumericEnumsMock = new GrpcClient({ - ...opts, - numericEnums: true, - }); + const spy = sinon.spy(transcoding, 'transcode'); + // incomplete types for nodeFetch, so... + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sinon.stub(nodeFetch, 'Promise' as any).returns( + Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); + }, + }) + ); - gaxGrpcNumericEnumsMock + gaxGrpcNumericEnums .createStub(libraryService, stubOptions) - .then((libStub: any) => { + .then(libStub => { libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { assert.strictEqual( spy.getCall(0).returnValue?.queryString, @@ -347,49 +314,48 @@ describe('REGAPIC', () => { 100, (result as {name: {}; theme: {}; type: {}}).type ); + done(); }); - }); + }, /* catch: */ done); }); - it('should request numeric enums if passed as symbolic name', async () => { + it('should request numeric enums if passed as symbolic name', done => { const shelf = { name: 'shelf-name', theme: 'shelf-theme', type: 'TYPEONE', }; const requestObject = {shelf: shelf}; - const spy = sinon.spy(); - - const {GrpcClient} = await proxyquire('../../src/fallback.js', { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); - }, - }); - }, - 'transcoding.js': {transcode: spy}, - }); - - const gaxGrpcNumericEnumsMock = new GrpcClient({ - ...opts, - numericEnums: true, - }); - gaxGrpcNumericEnumsMock + const spy = sinon.spy(transcoding, 'transcode'); + // incomplete types for nodeFetch, so... + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sinon.stub(nodeFetch, 'Promise' as any).returns( + Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }) + ); + gaxGrpcNumericEnums .createStub(libraryService, stubOptions) - .then((libStub: any) => { + .then(libStub => { libStub.createShelf(requestObject, {}, {}, (err?: {}) => { assert.strictEqual( - spy.getCall(0).returnValue?.queryString, - '$alt=json%3Benum-encoding=int' + 'string', + typeof spy.getCall(0).returnValue?.queryString + ); + assert.match( + spy.getCall(0).returnValue?.queryString, + /\$alt=json%3Benum-encoding=int(&.*)?$/ ); assert.strictEqual(err, null); + done(); }); - }); + }, /* catch: */ done); }); - it('should preserve query string when appending numeric enums parameter', async () => { + it('should preserve query string when appending numeric enums parameter', done => { const shelf = { name: 'shelf-name', theme: 'shelf-theme', @@ -399,78 +365,66 @@ describe('REGAPIC', () => { shelf: shelf, queryStringParameter: 'must-be-preserved', }; - const spy = sinon.spy(); - - const {GrpcClient} = await proxyquire('../../src/fallback.js', { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); - }, - }); - }, - 'transcoding.js': {transcode: spy}, - }); - - const gaxGrpcNumericEnumsMock = new GrpcClient({ - ...opts, - numericEnums: true, - }); - gaxGrpcNumericEnumsMock + const spy = sinon.spy(transcoding, 'transcode'); + // incomplete types for nodeFetch, so... + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sinon.stub(nodeFetch, 'Promise' as any).returns( + Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }) + ); + gaxGrpcNumericEnums .createStub(libraryService, stubOptions) - .then((libStub: any) => { + .then(libStub => { libStub.createShelf(requestObject, {}, {}, (err?: {}) => { assert.strictEqual( spy.getCall(0).returnValue?.queryString, 'queryStringParameter=must-be-preserved&$alt=json%3Benum-encoding=int' ); assert.strictEqual(err, null); + done(); }); - }); + }, /* catch: */ done); }); - it('should request numeric enums if passed as an unknown number', async () => { + it('should request numeric enums if passed as an unknown number', done => { const shelf = { name: 'shelf-name', theme: 'shelf-theme', type: 100, }; const requestObject = {shelf: shelf}; - const spy = sinon.spy(); - - const {GrpcClient} = await proxyquire('../../src/fallback.js', { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); - }, - }); - }, - 'transcoding.js': {transcode: spy}, - }); - - const gaxGrpcNumericEnumsMock = new GrpcClient({ - ...opts, - numericEnums: true, - }); - gaxGrpcNumericEnumsMock + const spy = sinon.spy(transcoding, 'transcode'); + // incomplete types for nodeFetch, so... + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sinon.stub(nodeFetch, 'Promise' as any).returns( + Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }) + ); + gaxGrpcNumericEnums .createStub(libraryService, stubOptions) - .then((libStub: any) => { + .then(libStub => { libStub.createShelf(requestObject, {}, {}, (err?: {}) => { assert.strictEqual( spy.getCall(0).returnValue?.queryString, '$alt=json%3Benum-encoding=int' ); assert.strictEqual(err, null); + done(); }); - }); + }, /* catch: */ done); }); }); describe('should support long data type conversion in proto message', () => { - it('large number long data type conversion in proto message response', async () => { + it('large number long data type conversion in proto message response', done => { const requestObject = {name: 'shelves/shelf-name/books/book-name'}; const responseObject = { name: 'book-name', @@ -479,55 +433,49 @@ describe('REGAPIC', () => { read: true, bookId: 9007199254740992, }; - - const {GrpcClient} = await proxyquire('../../src/fallback.js', { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve( - Buffer.from(JSON.stringify(responseObject)) - ); - }, - }); - }, - }); - - const gaxGrpcMock = new GrpcClient(); - gaxGrpcMock - .createStub(libraryService, stubOptions) - .then((libStub: any) => { - libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual(err, null); - assert.strictEqual( - 'book-name', - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).name - ); - assert.strictEqual( - '9007199254740992', - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).bookId - ); - }); + // incomplete types for nodeFetch, so... + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sinon.stub(nodeFetch, 'Promise' as any).returns( + Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); + }, + }) + ); + gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { + libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { + assert.strictEqual(err, null); + assert.strictEqual( + 'book-name', + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).name + ); + assert.strictEqual( + '9007199254740992', + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).bookId + ); + done(); }); + }, /* catch: */ done); }); - it('small number long data type conversion in proto message response', async () => { + it('small number long data type conversion in proto message response', done => { const requestObject = {name: 'shelves/shelf-name/books/book-name'}; const responseObject = { name: 'book-name', @@ -537,54 +485,48 @@ describe('REGAPIC', () => { bookId: 42, }; // incomplete types for nodeFetch, so... - const {GrpcClient} = await proxyquire('../../src/fallback.js', { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve( - Buffer.from(JSON.stringify(responseObject)) - ); - }, - }); - }, - }); - - const gaxGrpcMock = new GrpcClient(); - gaxGrpcMock - .createStub(libraryService, stubOptions) - .then((libStub: any) => { - libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual(err, null); - assert.strictEqual( - 'book-name', - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).name - ); - assert.strictEqual( - '42', - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).bookId - ); - }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sinon.stub(nodeFetch, 'Promise' as any).returns( + Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); + }, + }) + ); + gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { + libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { + assert.strictEqual(err, null); + assert.strictEqual( + 'book-name', + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).name + ); + assert.strictEqual( + '42', + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).bookId + ); + done(); }); + }, /* catch: */ done); }); - it('long data type conversion in proto message request', async () => { + it('long data type conversion in proto message request', done => { const bookId = 9007199254740992; const requestObject = {name: `shelves/shelf-name/book_id/${bookId}`}; const responseObject = { @@ -596,51 +538,134 @@ describe('REGAPIC', () => { }; // incomplete types for nodeFetch, so... // eslint-disable-next-line @typescript-eslint/no-explicit-any - const {GrpcClient} = await proxyquire('../../src/fallback.js', { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve( - Buffer.from(JSON.stringify(responseObject)) - ); - }, - }); - }, - }); + sinon.stub(nodeFetch, 'Promise' as any).returns( + Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); + }, + }) + ); + gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { + libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { + assert.strictEqual(err, null); + assert.strictEqual( + 'book-name', + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).name + ); + assert.strictEqual( + bookId.toString(), + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).bookId + ); + done(); + }); + }, /* catch: */ done); + }); + }); + + describe('should support json minification', () => { + it('should send prettyPrint=0 when json minification is requested', done => { + const requestObject = {name: 'shelves/shelf-name'}; + const responseObject = { + name: 'shelf-name', + theme: 'shelf-theme', + type: 100, // unknown enum value + }; + const spy = sinon.spy(transcoding, 'transcode'); + // incomplete types for nodeFetch, so... + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sinon.stub(nodeFetch, 'Promise' as any).returns( + Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); + }, + }) + ); - const gaxGrpcMock = new GrpcClient(); - gaxGrpcMock + gaxGrpcMinifyJson .createStub(libraryService, stubOptions) - .then((libStub: any) => { - libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { + .then(libStub => { + libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { + assert.strictEqual( + 'string', + typeof spy.getCall(0).returnValue?.queryString + ); + assert.match( + spy.getCall(0).returnValue?.queryString, + /\$prettyPrint=0(&.*)?$/ + ); assert.strictEqual(err, null); assert.strictEqual( - 'book-name', - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).name + 'shelf-name', + (result as {name: {}; theme: {}; type: {}}).name ); assert.strictEqual( - bookId.toString(), - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).bookId + 100, + (result as {name: {}; theme: {}; type: {}}).type ); + done(); }); + }, /* catch: */ done); + }); + + it('should not send prettyPrint setting when json minification is not requested', done => { + const requestObject = {name: 'shelves/shelf-name'}; + const responseObject = { + name: 'shelf-name', + theme: 'shelf-theme', + type: 100, // unknown enum value + }; + const spy = sinon.spy(transcoding, 'transcode'); + // incomplete types for nodeFetch, so... + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sinon.stub(nodeFetch, 'Promise' as any).returns( + Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); + }, + }) + ); + + gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { + libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { + assert.strictEqual( + 'string', + typeof spy.getCall(0).returnValue?.queryString + ); + assert.doesNotMatch( + spy.getCall(0).returnValue?.queryString, + /prettyPrint/ + ); + assert.strictEqual(err, null); + assert.strictEqual( + 'shelf-name', + (result as {name: {}; theme: {}; type: {}}).name + ); + assert.strictEqual( + 100, + (result as {name: {}; theme: {}; type: {}}).type + ); + done(); }); + }, /* catch: */ done); }); }); }); diff --git a/gax/tsconfig.json b/gax/tsconfig.json index 89730f442..9a5a0c4da 100644 --- a/gax/tsconfig.json +++ b/gax/tsconfig.json @@ -15,6 +15,8 @@ "src/*/*.ts", "test/system-test/*.ts", "test/unit/*.ts", - "protos/protos/**/*.json" + "protos/**/*.json", + "src/*.json", + "test/fixtures/*.json" ] } From a4ff5d8e2a71833bd3d147f07e166b643c27e306 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Fri, 7 Feb 2025 18:16:16 -0800 Subject: [PATCH 36/64] downgrade types/node --- gax/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gax/package.json b/gax/package.json index 6f17b4f8d..0286915bf 100644 --- a/gax/package.json +++ b/gax/package.json @@ -27,7 +27,7 @@ "@babel/plugin-proposal-private-methods": "^7.18.6", "@types/mocha": "^10.0.10", "@types/ncp": "^2.0.8", - "@types/node": "^22.13.1", + "@types/node": "^21.0.0", "@types/node-fetch": "^2.6.12", "@types/object-hash": "^3.0.6", "@types/proxyquire": "^1.3.31", From d769766e942daa6748e4e44e3e004ffe82e3a933 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Fri, 7 Feb 2025 18:32:51 -0800 Subject: [PATCH 37/64] retry --- gax/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gax/package.json b/gax/package.json index 0286915bf..c9a8f2f3d 100644 --- a/gax/package.json +++ b/gax/package.json @@ -27,7 +27,7 @@ "@babel/plugin-proposal-private-methods": "^7.18.6", "@types/mocha": "^10.0.10", "@types/ncp": "^2.0.8", - "@types/node": "^21.0.0", + "@types/node": "^20.5.0", "@types/node-fetch": "^2.6.12", "@types/object-hash": "^3.0.6", "@types/proxyquire": "^1.3.31", From 4dae5f2f3589cf4daab1da670488f4073c230712 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Tue, 11 Feb 2025 19:23:39 -0800 Subject: [PATCH 38/64] retry browser test --- gax/test/browser-test/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gax/test/browser-test/package.json b/gax/test/browser-test/package.json index 56d93db33..3f797e065 100644 --- a/gax/test/browser-test/package.json +++ b/gax/test/browser-test/package.json @@ -25,7 +25,7 @@ }, "devDependencies": { "@types/mocha": "^9.1.1", - "@types/node": "^14.11.2", + "@types/node": "^20.5.0", "@types/sinon": "^10.0.13", "google-gax": "./google-gax.tgz", "is-docker": "^2.2.1", From 088b8957152aef62c4efabd32cc6a2a1481e5613 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Tue, 11 Feb 2025 19:24:45 -0800 Subject: [PATCH 39/64] PR cleanup; --- .github/CODEOWNERS | 5 +---- package.json | 6 +----- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index e643f1002..0cde21c3c 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -6,7 +6,4 @@ # The yoshi-nodejs team is the default owner for nodejs repositories. -* @googleapis/yoshi-nodejs @googleapis/actools - -# The github automation team is the default owner for the auto-approve file. -.github/auto-approve.yml @googleapis/github-automation +* @googleapis/jsteam @googleapis/actools diff --git a/package.json b/package.json index 6135c3719..4717726b2 100644 --- a/package.json +++ b/package.json @@ -17,9 +17,5 @@ "engines": { "node": ">=18" }, - "homepage": "https://github.com/googleapis/gax-nodejs#readme", - "devDependencies": { - "esmock": "^2.7.0", - "proxyquire": "^2.1.3" - } + "homepage": "https://github.com/googleapis/gax-nodejs#readme" } From dc68ddc4ecc8fc2dd3351b4f3ad670ec0f90dff7 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 12 Feb 2025 03:26:21 +0000 Subject: [PATCH 40/64] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .github/CODEOWNERS | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 0cde21c3c..e643f1002 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -6,4 +6,7 @@ # The yoshi-nodejs team is the default owner for nodejs repositories. -* @googleapis/jsteam @googleapis/actools +* @googleapis/yoshi-nodejs @googleapis/actools + +# The github automation team is the default owner for the auto-approve file. +.github/auto-approve.yml @googleapis/github-automation From 6a17aa6547e13c775721265a6ffbf23800cbeea9 Mon Sep 17 00:00:00 2001 From: sofisl <55454395+sofisl@users.noreply.github.com> Date: Tue, 11 Feb 2025 22:22:39 -0800 Subject: [PATCH 41/64] Update .OwlBot.lock.yaml --- .github/.OwlBot.lock.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index dd6699188..5045289c5 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-nodejs:latest - digest: sha256:fe04ae044dadf5ad88d979dbcc85e0e99372fb5d6316790341e6aca5e4e3fbc8 + digest: sha256:ff8ecb77eb8c20b8f2c3379cf2033e494152b9b89b9695e5defceb1b78b8568f # created: 2024-11-21T22:39:44.342569463Z From fb21aad4a81cd223e9fae66232d88cefdea4b00c Mon Sep 17 00:00:00 2001 From: sofisl <55454395+sofisl@users.noreply.github.com> Date: Tue, 11 Feb 2025 22:25:55 -0800 Subject: [PATCH 42/64] Update .OwlBot.lock.yaml --- .github/.OwlBot.lock.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 5045289c5..39a62ca6b 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-nodejs:latest - digest: sha256:ff8ecb77eb8c20b8f2c3379cf2033e494152b9b89b9695e5defceb1b78b8568f + digest: sha256:0d39e59663287ae929c1d4ccf8ebf7cef9946826c9b86eda7e85d8d752dbb584 # created: 2024-11-21T22:39:44.342569463Z From ec75dadee58e166c13d2ab806262823608e52e70 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 12 Feb 2025 06:27:26 +0000 Subject: [PATCH 43/64] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .eslintignore | 1 + .github/CODEOWNERS | 7 +- .github/auto-approve.yml | 3 +- .github/release-trigger.yml | 1 + .kokoro/release/docs-devsite.cfg | 2 +- .kokoro/release/docs-devsite.sh | 5 +- .kokoro/release/docs.sh | 2 +- package-lock.json | 147 ------------------------------- renovate.json | 1 + 9 files changed, 11 insertions(+), 158 deletions(-) diff --git a/.eslintignore b/.eslintignore index ea5b04aeb..c4a0963e9 100644 --- a/.eslintignore +++ b/.eslintignore @@ -5,3 +5,4 @@ build/ docs/ protos/ samples/generated/ +system-test/**/fixtures diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index e643f1002..e436d6cfb 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -5,8 +5,5 @@ # https://help.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners#codeowners-syntax -# The yoshi-nodejs team is the default owner for nodejs repositories. -* @googleapis/yoshi-nodejs @googleapis/actools - -# The github automation team is the default owner for the auto-approve file. -.github/auto-approve.yml @googleapis/github-automation +# Unless specified, the jsteam is the default owner for nodejs repositories. +* @googleapis/actools @googleapis/jsteam \ No newline at end of file diff --git a/.github/auto-approve.yml b/.github/auto-approve.yml index 4cd91cc16..7cba0af63 100644 --- a/.github/auto-approve.yml +++ b/.github/auto-approve.yml @@ -1,3 +1,2 @@ processes: - - "NodeDependency" - - "OwlBotTemplateChanges" + - "NodeDependency" \ No newline at end of file diff --git a/.github/release-trigger.yml b/.github/release-trigger.yml index d4ca94189..6fd487cd1 100644 --- a/.github/release-trigger.yml +++ b/.github/release-trigger.yml @@ -1 +1,2 @@ enabled: true +multiScmName: gax-nodejs \ No newline at end of file diff --git a/.kokoro/release/docs-devsite.cfg b/.kokoro/release/docs-devsite.cfg index 32bdd1e48..e377d60d2 100644 --- a/.kokoro/release/docs-devsite.cfg +++ b/.kokoro/release/docs-devsite.cfg @@ -11,7 +11,7 @@ before_action { # doc publications use a Python image. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/node:14-user" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" } # Download trampoline resources. diff --git a/.kokoro/release/docs-devsite.sh b/.kokoro/release/docs-devsite.sh index 2198e67fe..81a89f6c1 100755 --- a/.kokoro/release/docs-devsite.sh +++ b/.kokoro/release/docs-devsite.sh @@ -25,5 +25,6 @@ if [[ -z "$CREDENTIALS" ]]; then fi npm install -npm install --no-save @google-cloud/cloud-rad@^0.2.5 -npx @google-cloud/cloud-rad \ No newline at end of file +npm install --no-save @google-cloud/cloud-rad@^0.4.0 +# publish docs to devsite +npx @google-cloud/cloud-rad . cloud-rad diff --git a/.kokoro/release/docs.sh b/.kokoro/release/docs.sh index 1d8f3f490..e9079a605 100755 --- a/.kokoro/release/docs.sh +++ b/.kokoro/release/docs.sh @@ -16,7 +16,7 @@ set -eo pipefail -# build jsdocs (Python is installed on the Node 10 docker image). +# build jsdocs (Python is installed on the Node 18 docker image). if [[ -z "$CREDENTIALS" ]]; then # if CREDENTIALS are explicitly set, assume we're testing locally # and don't set NPM_CONFIG_PREFIX. diff --git a/package-lock.json b/package-lock.json index fe213798f..dcbf3b673 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6,156 +6,9 @@ "": { "name": "gax-nodejs", "license": "Apache-2.0", - "devDependencies": { - "esmock": "^2.7.0", - "proxyquire": "^2.1.3" - }, "engines": { "node": ">=18" } - }, - "node_modules/esmock": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/esmock/-/esmock-2.7.0.tgz", - "integrity": "sha512-nYSvky0rP//13eYIGJ7b1dhsaBxtS370UoDWbILo1jHlO4hrCUkp/LD3e54QVhySxAGLsufxi5A4+wUAxPUIrg==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=14.16.0" - } - }, - "node_modules/fill-keys": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/fill-keys/-/fill-keys-1.0.2.tgz", - "integrity": "sha512-tcgI872xXjwFF4xgQmLxi76GnwJG3g/3isB1l4/G5Z4zrbddGpBjqZCO9oEAcB5wX0Hj/5iQB3toxfO7in1hHA==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-object": "~1.0.1", - "merge-descriptors": "~1.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/function-bind": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/hasown": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", - "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/is-core-module": { - "version": "2.16.1", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", - "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", - "dev": true, - "license": "MIT", - "dependencies": { - "hasown": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-object": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-object/-/is-object-1.0.2.tgz", - "integrity": "sha512-2rRIahhZr2UWb45fIOuvZGpFtz0TyOZLf32KxBbSoUCeZR495zCKlWUKKUByk3geS2eAs7ZAABt0Y/Rx0GiQGA==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/merge-descriptors": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", - "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/module-not-found-error": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/module-not-found-error/-/module-not-found-error-1.0.1.tgz", - "integrity": "sha512-pEk4ECWQXV6z2zjhRZUongnLJNUeGQJ3w6OQ5ctGwD+i5o93qjRQUk2Rt6VdNeu3sEP0AB4LcfvdebpxBRVr4g==", - "dev": true, - "license": "MIT" - }, - "node_modules/path-parse": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", - "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", - "dev": true, - "license": "MIT" - }, - "node_modules/proxyquire": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/proxyquire/-/proxyquire-2.1.3.tgz", - "integrity": "sha512-BQWfCqYM+QINd+yawJz23tbBM40VIGXOdDw3X344KcclI/gtBbdWF6SlQ4nK/bYhF9d27KYug9WzljHC6B9Ysg==", - "dev": true, - "license": "MIT", - "dependencies": { - "fill-keys": "^1.0.2", - "module-not-found-error": "^1.0.1", - "resolve": "^1.11.1" - } - }, - "node_modules/resolve": { - "version": "1.22.10", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.10.tgz", - "integrity": "sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-core-module": "^2.16.0", - "path-parse": "^1.0.7", - "supports-preserve-symlinks-flag": "^1.0.0" - }, - "bin": { - "resolve": "bin/resolve" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/supports-preserve-symlinks-flag": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", - "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } } } } diff --git a/renovate.json b/renovate.json index 26428fcfc..c5c702cf4 100644 --- a/renovate.json +++ b/renovate.json @@ -4,6 +4,7 @@ "docker:disable", ":disableDependencyDashboard" ], + "constraintsFiltering": "strict", "pinVersions": false, "rebaseStalePrs": true, "schedule": [ From 16e0200bd901d7ab5140fe61097a71d9a31e2873 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Tue, 11 Feb 2025 23:39:50 -0800 Subject: [PATCH 44/64] revert change to tsconfig --- gax/test/browser-test/tsconfig.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gax/test/browser-test/tsconfig.json b/gax/test/browser-test/tsconfig.json index 21b519c62..e0568a21d 100644 --- a/gax/test/browser-test/tsconfig.json +++ b/gax/test/browser-test/tsconfig.json @@ -4,7 +4,7 @@ "rootDir": ".", "outDir": "build", "resolveJsonModule": true, - "lib": ["DOM"] + "lib": ["ES2018", "DOM"] }, "include": [ "src/**/*.ts", From 5f44ad85fb6032ab6e04ae1d9f409e45483c3baa Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Tue, 11 Feb 2025 23:42:34 -0800 Subject: [PATCH 45/64] remove node 12 configs --- .kokoro/continuous/node12/lint.cfg | 4 ---- .kokoro/continuous/node12/samples-test.cfg | 12 ------------ .kokoro/continuous/node12/system-test.cfg | 12 ------------ .kokoro/continuous/node12/test.cfg | 0 .kokoro/presubmit/node12/samples-test.cfg | 12 ------------ .kokoro/presubmit/node12/system-test.cfg | 12 ------------ .kokoro/presubmit/node12/test.cfg | 0 7 files changed, 52 deletions(-) delete mode 100644 .kokoro/continuous/node12/lint.cfg delete mode 100644 .kokoro/continuous/node12/samples-test.cfg delete mode 100644 .kokoro/continuous/node12/system-test.cfg delete mode 100644 .kokoro/continuous/node12/test.cfg delete mode 100644 .kokoro/presubmit/node12/samples-test.cfg delete mode 100644 .kokoro/presubmit/node12/system-test.cfg delete mode 100644 .kokoro/presubmit/node12/test.cfg diff --git a/.kokoro/continuous/node12/lint.cfg b/.kokoro/continuous/node12/lint.cfg deleted file mode 100644 index 018ec7aa0..000000000 --- a/.kokoro/continuous/node12/lint.cfg +++ /dev/null @@ -1,4 +0,0 @@ -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/gax-nodejs/.kokoro/lint.sh" -} diff --git a/.kokoro/continuous/node12/samples-test.cfg b/.kokoro/continuous/node12/samples-test.cfg deleted file mode 100644 index 3fb9c46ca..000000000 --- a/.kokoro/continuous/node12/samples-test.cfg +++ /dev/null @@ -1,12 +0,0 @@ -# Download resources for system tests (service account key, etc.) -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/gax-nodejs/.kokoro/samples-test.sh" -} - -env_vars: { - key: "SECRET_MANAGER_KEYS" - value: "long-door-651-kokoro-system-test-service-account" -} \ No newline at end of file diff --git a/.kokoro/continuous/node12/system-test.cfg b/.kokoro/continuous/node12/system-test.cfg deleted file mode 100644 index 8a980142a..000000000 --- a/.kokoro/continuous/node12/system-test.cfg +++ /dev/null @@ -1,12 +0,0 @@ -# Download resources for system tests (service account key, etc.) -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/gax-nodejs/.kokoro/system-test.sh" -} - -env_vars: { - key: "SECRET_MANAGER_KEYS" - value: "long-door-651-kokoro-system-test-service-account" -} \ No newline at end of file diff --git a/.kokoro/continuous/node12/test.cfg b/.kokoro/continuous/node12/test.cfg deleted file mode 100644 index e69de29bb..000000000 diff --git a/.kokoro/presubmit/node12/samples-test.cfg b/.kokoro/presubmit/node12/samples-test.cfg deleted file mode 100644 index 3fb9c46ca..000000000 --- a/.kokoro/presubmit/node12/samples-test.cfg +++ /dev/null @@ -1,12 +0,0 @@ -# Download resources for system tests (service account key, etc.) -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/gax-nodejs/.kokoro/samples-test.sh" -} - -env_vars: { - key: "SECRET_MANAGER_KEYS" - value: "long-door-651-kokoro-system-test-service-account" -} \ No newline at end of file diff --git a/.kokoro/presubmit/node12/system-test.cfg b/.kokoro/presubmit/node12/system-test.cfg deleted file mode 100644 index 8a980142a..000000000 --- a/.kokoro/presubmit/node12/system-test.cfg +++ /dev/null @@ -1,12 +0,0 @@ -# Download resources for system tests (service account key, etc.) -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/gax-nodejs/.kokoro/system-test.sh" -} - -env_vars: { - key: "SECRET_MANAGER_KEYS" - value: "long-door-651-kokoro-system-test-service-account" -} \ No newline at end of file diff --git a/.kokoro/presubmit/node12/test.cfg b/.kokoro/presubmit/node12/test.cfg deleted file mode 100644 index e69de29bb..000000000 From 2286d6343b3d63e67ee1ce0f004183569be1b946 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Wed, 12 Feb 2025 22:45:54 -0800 Subject: [PATCH 46/64] fix: upgrade webpack to v5 to match the new typescript version --- gax/package.json | 1 + gax/src/index.ts | 2 +- gax/test/browser-test/karma.conf.js | 14 ++++----- gax/test/browser-test/package.json | 22 +++++++++----- gax/test/browser-test/test/test.endtoend.ts | 4 ++- .../browser-test/test/test.grpc-fallback.ts | 1 + gax/test/browser-test/tsconfig.json | 2 +- gax/test/browser-test/webpack.config.js | 29 +++++++++++++++---- 8 files changed, 51 insertions(+), 24 deletions(-) diff --git a/gax/package.json b/gax/package.json index c9a8f2f3d..65872b542 100644 --- a/gax/package.json +++ b/gax/package.json @@ -35,6 +35,7 @@ "@types/sinon": "^17.0.3", "@types/uglify-js": "^3.17.5", "@types/uuid": "^10.0.0", + "assert": "^2.1.0", "c8": "^10.1.3", "cheerio": "^1.0.0", "codecov": "^3.8.3", diff --git a/gax/src/index.ts b/gax/src/index.ts index 2393ce798..1baf2e566 100644 --- a/gax/src/index.ts +++ b/gax/src/index.ts @@ -76,7 +76,7 @@ export {OperationsClient} from './operationsClient'; export {IamClient} from './iamService'; export {LocationsClient} from './locationService'; -export const createByteLengthFunction = GrpcClient.createByteLengthFunction; +export const createByteLengthFunction = GrpcClient?.createByteLengthFunction; export const version = require('../../package.json').version; import * as protobuf from 'protobufjs'; diff --git a/gax/test/browser-test/karma.conf.js b/gax/test/browser-test/karma.conf.js index 8b79b3868..db543d346 100644 --- a/gax/test/browser-test/karma.conf.js +++ b/gax/test/browser-test/karma.conf.js @@ -30,26 +30,23 @@ module.exports = function (config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', - // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['mocha', 'child-process'], + files: ['./test/*.ts'], client: { childProcess: { path: path.relative( process.cwd(), // eslint-disable-next-line n/no-missing-require - require.resolve('showcase-server/build/src/index.js') + require.resolve('showcase-server/build/src/index.js'), ), args: [], options: {}, }, }, - // list of files / patterns to load in the browser - files: ['./test/test.*.ts'], - // list of files / patterns to exclude exclude: [], @@ -60,7 +57,6 @@ module.exports = function (config) { }, webpack: webpackConfig, - // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter @@ -96,14 +92,16 @@ module.exports = function (config) { // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true, - + // list of files / patterns to load in the browser // Concurrency level // how many browser should be started simultaneous concurrency: Infinity, - // set correct MIME type when serving .ts files (already compiled to JavaScript): mime: { 'text/javascript': ['ts'], }, + browserDisconnectTimeout: 60000, // Increase to 60 seconds (or more) + browserNoActivityTimeout: 60000, + mode: 'development', }); }; diff --git a/gax/test/browser-test/package.json b/gax/test/browser-test/package.json index 3f797e065..e98611d88 100644 --- a/gax/test/browser-test/package.json +++ b/gax/test/browser-test/package.json @@ -27,21 +27,29 @@ "@types/mocha": "^9.1.1", "@types/node": "^20.5.0", "@types/sinon": "^10.0.13", + "assert": "^2.1.0", + "core-js": "^3.40.0", "google-gax": "./google-gax.tgz", + "https-browserify": "^1.0.0", "is-docker": "^2.2.1", - "karma": "^6.0.0", - "karma-child-process": "^1.0.3", - "karma-chrome-launcher": "^3.0.0", - "karma-mocha": "^2.0.0", - "karma-sourcemap-loader": "^0.3.7", - "karma-webpack": "^4.0.0", + "karma": "^6.4.4", + "karma-child-process": "^1.0.14", + "karma-chrome-launcher": "^3.2.0", + "karma-mocha": "^2.0.1", + "karma-sourcemap-loader": "^0.4.0", + "karma-webpack": "^5.0.1", "mocha": "^10.0.0", + "process": "^0.11.10", "puppeteer": "^16.0.0", + "querystring-es3": "^0.2.1", "showcase-echo-client": "./showcase-echo-client.tgz", "showcase-server": "./showcase-server.tgz", "sinon": "^14.0.0", + "stream-browserify": "^3.0.0", + "stream-http": "^3.2.0", "typescript": "^5.7.3", - "webpack": "^4.0.0", + "url": "^0.11.4", + "webpack": "^5.97.1", "webpack-cli": "^4.0.0" } } diff --git a/gax/test/browser-test/test/test.endtoend.ts b/gax/test/browser-test/test/test.endtoend.ts index 1d9556dbc..77cec9f94 100644 --- a/gax/test/browser-test/test/test.endtoend.ts +++ b/gax/test/browser-test/test/test.endtoend.ts @@ -18,6 +18,7 @@ import * as assert from 'assert'; import {describe, it, before} from 'mocha'; import {GoogleAuth} from 'google-gax'; import {EchoClient} from 'showcase-echo-client'; +import 'core-js/stable'; function sleep(timeout: number) { return new Promise(resolve => { @@ -25,7 +26,7 @@ function sleep(timeout: number) { }); } -describe('Run tests against gRPC server', () => { +describe('Run tests against gRPC server', async function () { const authStub = { getClient: async () => { return { @@ -76,6 +77,7 @@ describe('Run tests against gRPC server', () => { }); it('should be able to call simple RPC methods', async () => { + this.timeout(80000); const request = { content: 'test', }; diff --git a/gax/test/browser-test/test/test.grpc-fallback.ts b/gax/test/browser-test/test/test.grpc-fallback.ts index 768242e9b..1b294036d 100644 --- a/gax/test/browser-test/test/test.grpc-fallback.ts +++ b/gax/test/browser-test/test/test.grpc-fallback.ts @@ -21,6 +21,7 @@ import {after, afterEach, before, beforeEach, describe, it} from 'mocha'; import * as sinon from 'sinon'; import {protobuf, GoogleAuth, fallback} from 'google-gax'; import {EchoClient} from 'showcase-echo-client'; +import 'core-js/stable'; import echoProtoJson = require('showcase-echo-client/build/protos/protos.json'); diff --git a/gax/test/browser-test/tsconfig.json b/gax/test/browser-test/tsconfig.json index e0568a21d..21b519c62 100644 --- a/gax/test/browser-test/tsconfig.json +++ b/gax/test/browser-test/tsconfig.json @@ -4,7 +4,7 @@ "rootDir": ".", "outDir": "build", "resolveJsonModule": true, - "lib": ["ES2018", "DOM"] + "lib": ["DOM"] }, "include": [ "src/**/*.ts", diff --git a/gax/test/browser-test/webpack.config.js b/gax/test/browser-test/webpack.config.js index b8a8b6a11..143d71323 100644 --- a/gax/test/browser-test/webpack.config.js +++ b/gax/test/browser-test/webpack.config.js @@ -13,12 +13,32 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +const webpack = require('webpack'); module.exports = { entry: './build/src/index.js', resolve: { extensions: ['.ts', '.js', '.json'], + fallback: { + fs: 'empty', + child_process: 'empty', + // eslint-disable-next-line n/no-extraneous-require + assert: require.resolve('assert/'), + util: require.resolve('util'), + stream: require.resolve('stream-browserify'), + http: require.resolve('stream-http'), + https: require.resolve('https-browserify'), + querystring: require.resolve('querystring-es3'), + url: require.resolve('url/'), + }, }, + plugins: [ + new webpack.ProvidePlugin({ + process: 'process/browser', + }), + new webpack.ProvidePlugin({ + Buffer: ['buffer', 'Buffer'], + }), + ], module: { rules: [ { @@ -44,9 +64,6 @@ module.exports = { }, ], }, - node: { - fs: 'empty', - child_process: 'empty', - }, - mode: 'production', + cache: false, + mode: 'development', }; From 11d5c643c0198095e770e16b1dd1d1e44fa879e4 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Thu, 13 Feb 2025 00:16:42 -0800 Subject: [PATCH 47/64] run lint --- gax/samples/pagination.js | 4 +- gax/samples/quickstart.js | 2 +- gax/src/apiCaller.ts | 8 +- gax/src/apitypes.ts | 16 +- gax/src/bundlingCalls/bundleApiCaller.ts | 2 +- gax/src/bundlingCalls/bundleDescriptor.ts | 4 +- gax/src/bundlingCalls/bundleExecutor.ts | 14 +- gax/src/bundlingCalls/bundlingUtils.ts | 2 +- gax/src/bundlingCalls/task.ts | 8 +- gax/src/call.ts | 8 +- gax/src/clientInterface.ts | 4 +- gax/src/createApiCall.ts | 18 +- gax/src/fallback.ts | 26 +- gax/src/fallbackRest.ts | 10 +- gax/src/fallbackServiceStub.ts | 14 +- gax/src/gax.ts | 40 +-- gax/src/googleError.ts | 14 +- gax/src/grpc.ts | 38 +-- gax/src/iamService.ts | 44 +-- gax/src/locationService.ts | 40 +-- .../longRunningCalls/longRunningApiCaller.ts | 8 +- .../longRunningCalls/longRunningDescriptor.ts | 2 +- gax/src/longRunningCalls/longrunning.ts | 16 +- gax/src/normalCalls/normalApiCaller.ts | 2 +- gax/src/normalCalls/retries.ts | 8 +- gax/src/normalCalls/timeout.ts | 2 +- gax/src/operationsClient.ts | 34 +-- gax/src/paginationCalls/pageDescriptor.ts | 16 +- gax/src/paginationCalls/pagedApiCaller.ts | 14 +- gax/src/paginationCalls/resourceCollector.ts | 2 +- gax/src/pathTemplate.ts | 20 +- gax/src/streamArrayParser.ts | 6 +- gax/src/streamingCalls/streamDescriptor.ts | 2 +- gax/src/streamingCalls/streaming.ts | 30 +- gax/src/streamingCalls/streamingApiCaller.ts | 10 +- gax/src/transcoding.ts | 34 +-- gax/src/util.ts | 2 +- gax/test/system-test/test.clientlibs.ts | 16 +- gax/test/unit/apiCallable.ts | 50 ++-- gax/test/unit/bundling.ts | 22 +- gax/test/unit/fallbackError.ts | 14 +- gax/test/unit/gax.ts | 8 +- gax/test/unit/googleError.ts | 44 +-- gax/test/unit/grpc-fallback.ts | 22 +- gax/test/unit/grpc.ts | 66 ++--- gax/test/unit/iamService.ts | 68 ++--- gax/test/unit/locationService.ts | 62 ++-- gax/test/unit/longrunning.ts | 62 ++-- gax/test/unit/operationClient.ts | 178 +++++------ gax/test/unit/pagedIteration.ts | 58 ++-- gax/test/unit/pathTemplate.ts | 16 +- gax/test/unit/regapic.ts | 80 ++--- gax/test/unit/routingHeader.ts | 2 +- gax/test/unit/status.ts | 16 +- gax/test/unit/streamArrayParser.ts | 8 +- gax/test/unit/streaming.ts | 280 +++++++++--------- gax/test/unit/transcoding.ts | 122 ++++---- gax/test/unit/util.ts | 10 +- gax/test/unit/utils.ts | 10 +- gax/test/unit/warning.ts | 2 +- gax/webpack.config.js | 4 +- 61 files changed, 872 insertions(+), 872 deletions(-) diff --git a/gax/samples/pagination.js b/gax/samples/pagination.js index ad8ca6d97..a175bf34b 100644 --- a/gax/samples/pagination.js +++ b/gax/samples/pagination.js @@ -54,14 +54,14 @@ async function main() { const pageDescriptor = new gax.PageDescriptor( /* requestPageTokenField: */ 'pageToken', /* responsePageTokenField: */ 'nextPageToken', - /* resourceField: */ 'animals' + /* resourceField: */ 'animals', ); // Create API call: const wrappedFunction = gax.createApiCall( /* func: */ doStuff, /* settings: */ settings, - /* descriptor: */ pageDescriptor + /* descriptor: */ pageDescriptor, ); // Call it! diff --git a/gax/samples/quickstart.js b/gax/samples/quickstart.js index 35fc0bfd1..01463c8bb 100644 --- a/gax/samples/quickstart.js +++ b/gax/samples/quickstart.js @@ -45,7 +45,7 @@ async function main() { const settings = new gax.CallSettings(); settings.retry = gax.createRetryOptions( /* retryCodes: */ [42], - /* backoffSettings: */ gax.createDefaultBackoffSettings() + /* backoffSettings: */ gax.createDefaultBackoffSettings(), ); // and use createApiCall to get a promisifed function that handles retries! diff --git a/gax/src/apiCaller.ts b/gax/src/apiCaller.ts index 5c9590f1d..80857cb87 100644 --- a/gax/src/apiCaller.ts +++ b/gax/src/apiCaller.ts @@ -39,20 +39,20 @@ export interface APICaller { apiCall: SimpleCallbackFunction, argument: {}, settings: {}, - canceller: OngoingCallPromise | OngoingCall | StreamProxy + canceller: OngoingCallPromise | OngoingCall | StreamProxy, ): void; fail( canceller: OngoingCallPromise | OngoingCall | CancellableStream, - err: GoogleError + err: GoogleError, ): void; result( - canceller: OngoingCallPromise | OngoingCall | CancellableStream + canceller: OngoingCallPromise | OngoingCall | CancellableStream, ): CancellablePromise | CancellableStream; } export function createAPICaller( settings: CallSettings, - descriptor: Descriptor | undefined + descriptor: Descriptor | undefined, ): APICaller { if (!descriptor) { return new NormalApiCaller(); diff --git a/gax/src/apitypes.ts b/gax/src/apitypes.ts index 8a6d49087..6004cc63a 100644 --- a/gax/src/apitypes.ts +++ b/gax/src/apitypes.ts @@ -59,7 +59,7 @@ export type APICallback = ( err: GoogleError | null, response?: ResponseType, next?: NextPageRequestType, - rawResponse?: RawResponseType + rawResponse?: RawResponseType, ) => void; // The following five types mimic various gRPC calls (regular UnaryCall and @@ -68,21 +68,21 @@ export type UnaryCall = ( argument: {}, metadata: {}, options: {}, - callback: APICallback + callback: APICallback, ) => GRPCCallResult; export type ServerStreamingCall = ( argument: {}, metadata: {}, - options: {} + options: {}, ) => Duplex & GRPCCallResult; export type ClientStreamingCall = ( metadata: {}, options: {}, - callback?: APICallback + callback?: APICallback, ) => Duplex & GRPCCallResult; export type BiDiStreamingCall = ( metadata: {}, - options: {} + options: {}, ) => Duplex & GRPCCallResult; export type GRPCCall = | UnaryCall @@ -98,21 +98,21 @@ export interface GaxCallPromise { ( argument: {}, callOptions?: CallOptions, - callback?: APICallback + callback?: APICallback, ): CancellablePromise; } export interface GaxCallStream { ( argument: {}, callOptions?: CallOptions, - callback?: APICallback + callback?: APICallback, ): CancellableStream; } export interface GaxCall { ( argument: {}, callOptions?: CallOptions, - callback?: APICallback + callback?: APICallback, ): GaxCallResult; } export interface GRPCCallOtherArgs { diff --git a/gax/src/bundlingCalls/bundleApiCaller.ts b/gax/src/bundlingCalls/bundleApiCaller.ts index 78952a238..cb8c9097a 100644 --- a/gax/src/bundlingCalls/bundleApiCaller.ts +++ b/gax/src/bundlingCalls/bundleApiCaller.ts @@ -49,7 +49,7 @@ export class BundleApiCaller implements APICaller { apiCall: SimpleCallbackFunction, argument: {}, settings: CallSettings, - status: OngoingCallPromise + status: OngoingCallPromise, ) { if (!settings.isBundling) { throw new GoogleError('Bundling enabled with no isBundling!'); diff --git a/gax/src/bundlingCalls/bundleDescriptor.ts b/gax/src/bundlingCalls/bundleDescriptor.ts index cb6daad86..5765fe887 100644 --- a/gax/src/bundlingCalls/bundleDescriptor.ts +++ b/gax/src/bundlingCalls/bundleDescriptor.ts @@ -62,7 +62,7 @@ export class BundleDescriptor implements Descriptor { bundledField: string, requestDiscriminatorFields: string[], subresponseField: string | null, - byteLengthFunction: Function + byteLengthFunction: Function, ) { if (!byteLengthFunction && typeof subresponseField === 'function') { byteLengthFunction = subresponseField; @@ -80,7 +80,7 @@ export class BundleDescriptor implements Descriptor { return new NormalApiCaller(); } return new BundleApiCaller( - new BundleExecutor(settings.bundleOptions!, this) + new BundleExecutor(settings.bundleOptions!, this), ); } } diff --git a/gax/src/bundlingCalls/bundleExecutor.ts b/gax/src/bundlingCalls/bundleExecutor.ts index 21f7ffdb3..61c8dbb8e 100644 --- a/gax/src/bundlingCalls/bundleExecutor.ts +++ b/gax/src/bundlingCalls/bundleExecutor.ts @@ -86,7 +86,7 @@ export class BundleExecutor { */ constructor( bundleOptions: BundleOptions, - bundleDescriptor: BundleDescriptor + bundleDescriptor: BundleDescriptor, ) { this._options = bundleOptions; this._descriptor = bundleDescriptor; @@ -107,11 +107,11 @@ export class BundleExecutor { schedule( apiCall: SimpleCallbackFunction, request: {[index: string]: Array<{}> | string}, - callback?: TaskCallback + callback?: TaskCallback, ) { const bundleId = computeBundleId( request, - this._descriptor.requestDiscriminatorFields + this._descriptor.requestDiscriminatorFields, ); callback = (callback || noop) as TaskCallback; if (bundleId === undefined) { @@ -119,7 +119,7 @@ export class BundleExecutor { 'bundling_schedule_bundleid_undefined', 'The request does not have enough information for request bundling. ' + `Invoking immediately. Request: ${JSON.stringify(request)} ` + - `discriminator fields: ${this._descriptor.requestDiscriminatorFields}` + `discriminator fields: ${this._descriptor.requestDiscriminatorFields}`, ); return apiCall(request, callback); } @@ -127,7 +127,7 @@ export class BundleExecutor { warn( 'bundling_no_bundled_field', `Request does not contain field ${this._descriptor.bundledField} that must present for bundling. ` + - `Invoking immediately. Request: ${JSON.stringify(request)}` + `Invoking immediately. Request: ${JSON.stringify(request)}`, ); return apiCall(request, callback); } @@ -137,7 +137,7 @@ export class BundleExecutor { apiCall, request, this._descriptor.bundledField, - this._descriptor.subresponseField + this._descriptor.subresponseField, ); } let task = this._tasks[bundleId]; @@ -194,7 +194,7 @@ export class BundleExecutor { apiCall, request, this._descriptor.bundledField, - this._descriptor.subresponseField + this._descriptor.subresponseField, ); task = this._tasks[bundleId]; } diff --git a/gax/src/bundlingCalls/bundlingUtils.ts b/gax/src/bundlingCalls/bundlingUtils.ts index 20a04b029..e058f567e 100644 --- a/gax/src/bundlingCalls/bundlingUtils.ts +++ b/gax/src/bundlingCalls/bundlingUtils.ts @@ -33,7 +33,7 @@ import {RequestType} from '../apitypes'; */ export function computeBundleId( obj: RequestType, - discriminatorFields: string[] + discriminatorFields: string[], ) { const ids: unknown[] = []; let hasIds = false; diff --git a/gax/src/bundlingCalls/task.ts b/gax/src/bundlingCalls/task.ts index f4a72c583..c3dbafda9 100644 --- a/gax/src/bundlingCalls/task.ts +++ b/gax/src/bundlingCalls/task.ts @@ -54,7 +54,7 @@ export interface TaskCallback extends APICallback { export function deepCopyForResponse( // eslint-disable-next-line @typescript-eslint/no-explicit-any obj: any, - subresponseInfo: SubResponseInfo | null + subresponseInfo: SubResponseInfo | null, ) { // eslint-disable-next-line @typescript-eslint/no-explicit-any let result: any; @@ -91,7 +91,7 @@ export function deepCopyForResponse( // those subresponses are not shared among callbacks. result[key] = obj[key].slice( subresponseInfo.start, - subresponseInfo.end + subresponseInfo.end, ); } else { result[key] = deepCopyForResponse(obj[key], null); @@ -126,7 +126,7 @@ export class Task { apiCall: SimpleCallbackFunction, bundlingRequest: {}, bundledField: string, - subresponseField?: string | null + subresponseField?: string | null, ) { this._apiCall = apiCall; this._request = bundlingRequest; @@ -210,7 +210,7 @@ export class Task { self._data[i].callback(err, responses[i]); } } - } + }, ); return ids; } diff --git a/gax/src/call.ts b/gax/src/call.ts index b2fddacf0..8484e36d2 100644 --- a/gax/src/call.ts +++ b/gax/src/call.ts @@ -84,11 +84,11 @@ export class OngoingCall { err: GoogleError | null, response?: ResponseType, next?: NextPageRequestType, - rawResponse?: RawResponseType + rawResponse?: RawResponseType, ) => { this.completed = true; setImmediate(this.callback!, err, response, next, rawResponse); - } + }, ); if (canceller instanceof Promise) { canceller.catch(err => { @@ -113,14 +113,14 @@ export class OngoingCallPromise extends OngoingCall { */ constructor() { let resolveCallback: ( - result: [ResponseType, NextPageRequestType, RawResponseType] + result: [ResponseType, NextPageRequestType, RawResponseType], ) => void; let rejectCallback: (err: Error) => void; const callback: APICallback = ( err: GoogleError | null, response?: ResponseType, next?: NextPageRequestType, - rawResponse?: RawResponseType + rawResponse?: RawResponseType, ) => { if (err) { // If gRPC metadata exist, parsed google.rpc.status details. diff --git a/gax/src/clientInterface.ts b/gax/src/clientInterface.ts index 810892762..b9f3bd8b8 100644 --- a/gax/src/clientInterface.ts +++ b/gax/src/clientInterface.ts @@ -60,7 +60,7 @@ export interface Callback< err: Error | null | undefined, value?: ResponseObject | null, nextRequest?: NextRequestObject, - rawResponse?: RawResponseObject + rawResponse?: RawResponseObject, ): void; } @@ -80,7 +80,7 @@ export interface PaginationCallback< err: Error | null, values?: ResponseType[], nextPageRequest?: RequestObject, - rawResponse?: ResponseObject + rawResponse?: ResponseObject, ): void; } diff --git a/gax/src/createApiCall.ts b/gax/src/createApiCall.ts index e36b98e4e..b3fdee987 100644 --- a/gax/src/createApiCall.ts +++ b/gax/src/createApiCall.ts @@ -58,7 +58,7 @@ export function createApiCall( settings: CallSettings, descriptor?: Descriptor, // eslint-disable-next-line @typescript-eslint/no-unused-vars - _fallback?: boolean | 'proto' | 'rest' // unused here, used in fallback.ts implementation + _fallback?: boolean | 'proto' | 'rest', // unused here, used in fallback.ts implementation ): GaxCall { // we want to be able to accept both promise resolving to a function and a // function. Currently client librares are only calling this method with a @@ -70,7 +70,7 @@ export function createApiCall( return ( request: RequestType, callOptions?: CallOptions, - callback?: APICallback + callback?: APICallback, ) => { let currentApiCaller = apiCaller; @@ -81,7 +81,7 @@ export function createApiCall( // If Gax streaming retries are enabled, check settings passed at call time and convert parameters if needed const convertedRetryOptions = convertRetryOptions( callOptions, - gaxStreamingRetries + gaxStreamingRetries, ); thisSettings = settings.merge(convertedRetryOptions); } else { @@ -109,7 +109,7 @@ export function createApiCall( if (retry.retryCodes.length > 0 && retry.shouldRetryFn) { warn( 'either_retrycodes_or_shouldretryfn', - 'Only one of retryCodes or shouldRetryFn may be defined. Ignoring retryCodes.' + 'Only one of retryCodes or shouldRetryFn may be defined. Ignoring retryCodes.', ); retry.retryCodes = []; } @@ -119,19 +119,19 @@ export function createApiCall( retry.getResumptionRequestFn ) { throw new Error( - 'getResumptionRequestFn can only be used when gaxStreamingRetries is set to true.' + 'getResumptionRequestFn can only be used when gaxStreamingRetries is set to true.', ); } } if (!streaming && retry) { if (retry.shouldRetryFn) { throw new Error( - 'Using a function to determine retry eligibility is only supported with server streaming calls' + 'Using a function to determine retry eligibility is only supported with server streaming calls', ); } if (retry.getResumptionRequestFn) { throw new Error( - 'Resumption strategy can only be used with server streaming retries' + 'Resumption strategy can only be used with server streaming retries', ); } if (retry.retryCodes && retry.retryCodes.length > 0) { @@ -141,14 +141,14 @@ export function createApiCall( func, thisSettings.retry!, thisSettings.otherArgs as GRPCCallOtherArgs, - thisSettings.apiName + thisSettings.apiName, ); } } return addTimeoutArg( func, thisSettings.timeout, - thisSettings.otherArgs as GRPCCallOtherArgs + thisSettings.otherArgs as GRPCCallOtherArgs, ); }) .then((apiCall: SimpleCallbackFunction) => { diff --git a/gax/src/fallback.ts b/gax/src/fallback.ts index 9e779f027..5b73d0ceb 100644 --- a/gax/src/fallback.ts +++ b/gax/src/fallback.ts @@ -126,13 +126,13 @@ export class GrpcClient { * A string is accepted for compatibility, all non-empty string values enable the HTTP REST fallback. */ fallback?: boolean | string; - } = {} + } = {}, ) { if (!isNodeJS()) { if (!options.auth) { throw new Error( JSON.stringify(options) + - 'You need to pass auth instance to use gRPC-fallback client in browser or other non-Node.js environments. Use OAuth2Client from google-auth-library.' + 'You need to pass auth instance to use gRPC-fallback client in browser or other non-Node.js environments. Use OAuth2Client from google-auth-library.', ); } this.auth = options.auth as OAuth2Client; @@ -196,7 +196,7 @@ export class GrpcClient { serviceName: string, clientConfig: gax.ClientConfig, configOverrides: gax.ClientConfig, - headers: OutgoingHttpHeaders + headers: OutgoingHttpHeaders, ) { function buildMetadata(abTests: {}, moreHeaders: OutgoingHttpHeaders) { const metadata: OutgoingHttpHeaders = {}; @@ -220,7 +220,7 @@ export class GrpcClient { )[0] ) { clientVersions.push( - ...(metadata[CLIENT_VERSION_HEADER] as string[])[0].split(' ') + ...(metadata[CLIENT_VERSION_HEADER] as string[])[0].split(' '), ); } clientVersions.push(`grpc-web/${version}`); @@ -244,7 +244,7 @@ export class GrpcClient { ).push(...value); } else { throw new Error( - `Can not add value ${value} to the call metadata.` + `Can not add value ${value} to the call metadata.`, ); } } @@ -260,7 +260,7 @@ export class GrpcClient { clientConfig, configOverrides, Status, - {metadataBuilder: buildMetadata} + {metadataBuilder: buildMetadata}, ); } @@ -280,7 +280,7 @@ export class GrpcClient { opts: ClientStubOptions, // For consistency with createStub in grpc.ts, customServicePath is defined: // eslint-disable-next-line @typescript-eslint/no-unused-vars - customServicePath?: boolean + customServicePath?: boolean, ) { if (!this.authClient) { if (this.auth && 'getClient' in this.auth) { @@ -300,7 +300,7 @@ export class GrpcClient { if (universeFromAuth && opts.universeDomain !== universeFromAuth) { throw new Error( `The configured universe domain (${opts.universeDomain}) does not match the universe domain found in the credentials (${universeFromAuth}). ` + - "If you haven't configured the universe domain explicitly, googleapis.com is the default." + "If you haven't configured the universe domain explicitly, googleapis.com is the default.", ); } } @@ -319,7 +319,7 @@ export class GrpcClient { } if (!servicePath) { throw new Error( - `Cannot determine service API path for service ${service.name}.` + `Cannot determine service API path for service ${service.name}.`, ); } @@ -346,7 +346,7 @@ export class GrpcClient { encoder, decoder, this.numericEnums, - this.minifyJson + this.minifyJson, ); return serviceStub; @@ -411,7 +411,7 @@ export function createApiCall( settings: gax.CallSettings, descriptor?: Descriptor, // eslint-disable-next-line @typescript-eslint/no-unused-vars - _fallback?: boolean | string // unused; for compatibility only + _fallback?: boolean | string, // unused; for compatibility only ): GaxCall { if ( descriptor && @@ -420,14 +420,14 @@ export function createApiCall( ) { return () => { throw new Error( - 'The REST transport currently does not support client-streaming or bidi-stream calls.' + 'The REST transport currently does not support client-streaming or bidi-stream calls.', ); }; } if (descriptor && 'streaming' in descriptor && !isNodeJS()) { return () => { throw new Error( - 'Server streaming over the REST transport is only supported in Node.js.' + 'Server streaming over the REST transport is only supported in Node.js.', ); }; } diff --git a/gax/src/fallbackRest.ts b/gax/src/fallbackRest.ts index 87984f03e..b6e5f7621 100644 --- a/gax/src/fallbackRest.ts +++ b/gax/src/fallbackRest.ts @@ -29,7 +29,7 @@ export function encodeRequest( servicePort: number, request: {}, numericEnums: boolean, - minifyJson: boolean + minifyJson: boolean, ): FetchParameters { const headers: {[key: string]: string} = { 'Content-Type': 'application/json', @@ -51,7 +51,7 @@ export function encodeRequest( throw new Error( `Cannot build HTTP request for ${JSON.stringify(json)}, method: ${ rpc.name - }` + }`, ); } @@ -75,7 +75,7 @@ export function encodeRequest( const body = JSON.stringify(transcoded.data); const url = `${protocol}://${servicePath}:${servicePort}/${transcoded.url.replace( /^\//, - '' + '', )}?${transcoded.queryString}`; return { @@ -89,7 +89,7 @@ export function encodeRequest( export function decodeResponse( rpc: protobuf.Method, ok: boolean, - response: Buffer | ArrayBuffer + response: Buffer | ArrayBuffer, ): {} { // eslint-disable-next-line n/no-unsupported-features/node-builtins const decodedString = new TextDecoder().decode(response); @@ -104,7 +104,7 @@ export function decodeResponse( const message = serializer.fromProto3JSON(rpc.resolvedResponseType!, json); if (!message) { throw new Error( - `Received null or malformed response from JSON serializer from RPC ${rpc.name}` + `Received null or malformed response from JSON serializer from RPC ${rpc.name}`, ); } return rpc.resolvedResponseType!.toObject(message, defaultToObjectOptions); diff --git a/gax/src/fallbackServiceStub.ts b/gax/src/fallbackServiceStub.ts index cf28522b8..f38b1507c 100644 --- a/gax/src/fallbackServiceStub.ts +++ b/gax/src/fallbackServiceStub.ts @@ -58,7 +58,7 @@ export interface FallbackServiceStub { request: {}, options?: {}, metadata?: {}, - callback?: (err?: Error, response?: {} | undefined) => void + callback?: (err?: Error, response?: {} | undefined) => void, ) => StreamArrayParser | {cancel: () => void}; } @@ -84,15 +84,15 @@ export function generateServiceStub( servicePort: number, request: {}, numericEnums: boolean, - minifyJson: boolean + minifyJson: boolean, ) => FetchParameters, responseDecoder: ( rpc: protobuf.Method, ok: boolean, - response: Buffer | ArrayBuffer + response: Buffer | ArrayBuffer, ) => {}, numericEnums: boolean, - minifyJson: boolean + minifyJson: boolean, ) { const fetch = hasWindowFetch() ? window.fetch @@ -109,7 +109,7 @@ export function generateServiceStub( request: {}, options?: {[name: string]: string}, _metadata?: {} | Function, - callback?: Function + callback?: Function, ) => { options ??= {}; @@ -125,7 +125,7 @@ export function generateServiceStub( servicePort, request, numericEnums, - minifyJson + minifyJson, ); } catch (err) { // we could not encode parameters; pass error to the callback @@ -193,7 +193,7 @@ export function generateServiceStub( } streamArrayParser.emit('error', err); } - } + }, ); return; } else { diff --git a/gax/src/gax.ts b/gax/src/gax.ts index 64f381443..a38152c24 100644 --- a/gax/src/gax.ts +++ b/gax/src/gax.ts @@ -86,7 +86,7 @@ export class RetryOptions { retryCodes: number[], backoffSettings: BackoffSettings, shouldRetryFn?: (error: GoogleError) => boolean, - getResumptionRequestFn?: (request: RequestType) => RequestType + getResumptionRequestFn?: (request: RequestType) => RequestType, ) { this.retryCodes = retryCodes; this.backoffSettings = backoffSettings; @@ -324,7 +324,7 @@ export class CallSettings { */ export function convertRetryOptions( options?: CallOptions, - gaxStreamingRetries?: boolean + gaxStreamingRetries?: boolean, ): CallOptions | undefined { // options will be undefined if no CallOptions object is passed at call time if (!options) { @@ -343,21 +343,21 @@ export function convertRetryOptions( warn( 'retry_request_options', 'objectMode override is not supported. It is set to true internally by default in gax.', - 'UnsupportedParameterWarning' + 'UnsupportedParameterWarning', ); } if (options.retryRequestOptions.noResponseRetries !== undefined) { warn( 'retry_request_options', 'noResponseRetries override is not supported. Please specify retry codes or a function to determine retry eligibility.', - 'UnsupportedParameterWarning' + 'UnsupportedParameterWarning', ); } if (options.retryRequestOptions.currentRetryAttempt !== undefined) { warn( 'retry_request_options', 'currentRetryAttempt override is not supported. Retry attempts are tracked internally.', - 'UnsupportedParameterWarning' + 'UnsupportedParameterWarning', ); } @@ -392,7 +392,7 @@ export function convertRetryOptions( warn( 'retry_request_options_no_max_retries_timeout', 'Neither maxRetries nor totalTimeout were passed. Defaulting to totalTimeout of 30000ms.', - 'MissingParameterWarning' + 'MissingParameterWarning', ); } } @@ -408,14 +408,14 @@ export function convertRetryOptions( const convertedRetryOptions = createRetryOptions( retryCodes, backoffSettings, - shouldRetryFn + shouldRetryFn, ); options.retry = convertedRetryOptions; delete options.retryRequestOptions; // completely remove them to avoid any further confusion warn( 'retry_request_options', 'retryRequestOptions will be deprecated in a future release. Please use retryOptions to pass retry options at call time', - 'DeprecationWarning' + 'DeprecationWarning', ); } return options; @@ -436,7 +436,7 @@ export function createRetryOptions( retryCodes: number[], backoffSettings: BackoffSettings, shouldRetryFn?: (error: GoogleError) => boolean, - getResumptionRequestFn?: (request: RequestType) => RequestType + getResumptionRequestFn?: (request: RequestType) => RequestType, ): RetryOptions { return { retryCodes, @@ -478,7 +478,7 @@ export function createBackoffSettings( initialRpcTimeoutMillis: number | null, rpcTimeoutMultiplier: number | null, maxRpcTimeoutMillis: number | null, - totalTimeoutMillis: number | null + totalTimeoutMillis: number | null, ): BackoffSettings { return { initialRetryDelayMillis, @@ -527,7 +527,7 @@ export function createMaxRetriesBackoffSettings( initialRpcTimeoutMillis: number, rpcTimeoutMultiplier: number, maxRpcTimeoutMillis: number, - maxRetries: number + maxRetries: number, ): BackoffSettings { return { initialRetryDelayMillis, @@ -607,7 +607,7 @@ function constructRetry( methodConfig: MethodConfig | null, retryCodes: {[index: string]: string[]} | undefined, retryParams: {[index: string]: {}} | undefined, - retryNames: {[index: string]: {}} + retryNames: {[index: string]: {}}, ): RetryOptions | null | undefined { if (!methodConfig) { return null; @@ -633,7 +633,7 @@ function constructRetry( params.initial_rpc_timeout_millis, params.rpc_timeout_multiplier, params.max_rpc_timeout_millis, - params.total_timeout_millis + params.total_timeout_millis, ); } return createRetryOptions(codes!, backoffSettings!); @@ -654,7 +654,7 @@ function constructRetry( */ function mergeRetryOptions( retry: RetryOptions, - overrides: Partial + overrides: Partial, ): RetryOptions | null { if (!overrides) { return null; @@ -686,7 +686,7 @@ function mergeRetryOptions( retryCodes!, backoffSettings!, shouldRetryFn!, - getResumptionRequestFn! + getResumptionRequestFn!, ); } @@ -790,7 +790,7 @@ export function constructSettings( clientConfig: ClientConfig, configOverrides: ClientConfig, retryNames: {}, - otherArgs?: {} + otherArgs?: {}, ) { otherArgs = otherArgs || {}; // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -818,7 +818,7 @@ export function constructSettings( methodConfig, serviceConfig.retry_codes, serviceConfig.retry_params, - retryNames + retryNames, ); let bundlingConfig = methodConfig!.bundling; let timeout = methodConfig!.timeout_millis; @@ -838,8 +838,8 @@ export function constructSettings( overridingMethod, overrides.retry_codes, overrides.retry_params, - retryNames - )! + retryNames, + )!, ); } const apiName = serviceName; @@ -865,7 +865,7 @@ export function createByteLengthFunction(message: typeof Message) { const stringified = JSON.stringify(obj); warn( 'error_encoding_protobufjs_object', - `Cannot encode protobuf.js object: ${stringified}: ${err}` + `Cannot encode protobuf.js object: ${stringified}: ${err}`, ); // We failed to encode the object properly, let's just return an upper boundary of its length. // It's only needed for calculating the size of the batch, so it's safe if it's bigger than needed. diff --git a/gax/src/googleError.ts b/gax/src/googleError.ts index e9070b68f..e7305dbc4 100644 --- a/gax/src/googleError.ts +++ b/gax/src/googleError.ts @@ -38,7 +38,7 @@ export class GoogleError extends Error { if (err.metadata && err.metadata.get('grpc-status-details-bin')) { const statusDetailsObj: GRPCStatusDetailsObject = decoder.decodeGRPCStatusDetails( - err.metadata.get('grpc-status-details-bin') as [] + err.metadata.get('grpc-status-details-bin') as [], ); if ( statusDetailsObj && @@ -88,7 +88,7 @@ export class GoogleError extends Error { const proto3Error = decoder.decodeHTTPError(json['error']); const error = Object.assign( new GoogleError(json['error']['message']), - proto3Error + proto3Error, ); // Get gRPC Status Code if ( @@ -182,7 +182,7 @@ export class GoogleErrorDecoder { const match = anyValue.type_url.match(/^type.googleapis.com\/(.*)/); if (!match) { throw new Error( - `Unknown type encoded in google.protobuf.any: ${anyValue.type_url}` + `Unknown type encoded in google.protobuf.any: ${anyValue.type_url}`, ); } const typeName = match[1]; @@ -239,14 +239,14 @@ export class GoogleErrorDecoder { // Decodes gRPC metadata error details which is an instance of google.rpc.Status. decodeGRPCStatusDetails( - bufferArr: Buffer[] | ArrayBuffer[] + bufferArr: Buffer[] | ArrayBuffer[], ): GRPCStatusDetailsObject { const details: protobuf.Message<{}>[] = []; let errorInfo; bufferArr.forEach(buffer => { const uint8array = new Uint8Array(buffer); const rpcStatus = this.statusType.decode( - uint8array + uint8array, ) as unknown as RpcStatus; for (const detail of rpcStatus.details) { try { @@ -272,7 +272,7 @@ export class GoogleErrorDecoder { const errorMessage = serializer.fromProto3JSON(this.statusType, json); if (!errorMessage) { throw new Error( - `Received error message ${json}, but failed to serialize as proto3 message` + `Received error message ${json}, but failed to serialize as proto3 message`, ); } return this.statusType.toObject(errorMessage, defaultToObjectOptions); @@ -280,7 +280,7 @@ export class GoogleErrorDecoder { // Decodes http error details which is an instance of Array. decodeHttpStatusDetails( - rawDetails: Array + rawDetails: Array, ): GRPCStatusDetailsObject { // eslint-disable-next-line @typescript-eslint/no-unused-vars const details: protobuf.Message<{}>[] = []; diff --git a/gax/src/grpc.ts b/gax/src/grpc.ts index ff8d06f67..fb828bf0b 100644 --- a/gax/src/grpc.ts +++ b/gax/src/grpc.ts @@ -41,7 +41,7 @@ import * as commonProtoFiles from './protosList.json'; import {google} from '../protos/http'; // use the correct path separator for the OS we are running on const COMMON_PROTO_FILES: string[] = commonProtoFiles.map(file => - file.replace(/[/\\]/g, path.sep) + file.replace(/[/\\]/g, path.sep), ); export interface GrpcClientOptions extends GoogleAuthOptions { @@ -131,7 +131,7 @@ export class GrpcClient { */ private static protoCacheKey( filename: string | string[], - options: grpcProtoLoader.Options + options: grpcProtoLoader.Options, ) { if ( !filename || @@ -204,13 +204,13 @@ export class GrpcClient { ? grpc.credentials.createSsl( null, Buffer.from(opts.key), - Buffer.from(opts.cert) + Buffer.from(opts.cert), ) : grpc.credentials.createSsl(); const client = await this.auth.getClient(); const credentials = grpc.credentials.combineChannelCredentials( sslCreds, - grpc.credentials.createFromGoogleCredential(client) + grpc.credentials.createFromGoogleCredential(client), ); return credentials; } @@ -243,7 +243,7 @@ export class GrpcClient { loadFromProto( filename: string | string[], options: grpcProtoLoader.Options, - ignoreCache = false + ignoreCache = false, ) { const cacheKey = GrpcClient.protoCacheKey(filename, options); let grpcPackage = cacheKey @@ -275,7 +275,7 @@ export class GrpcClient { loadProto( protoPath: string, filename?: string | string[], - ignoreCache = false + ignoreCache = false, ) { if (!filename) { filename = path.basename(protoPath); @@ -325,7 +325,7 @@ export class GrpcClient { } return function buildMetadata( abTests?: {}, - moreHeaders?: OutgoingHttpHeaders + moreHeaders?: OutgoingHttpHeaders, ) { // TODO: bring the A/B testing info into the metadata. let copied = false; @@ -365,14 +365,14 @@ export class GrpcClient { serviceName: string, clientConfig: gax.ClientConfig, configOverrides: gax.ClientConfig, - headers: OutgoingHttpHeaders + headers: OutgoingHttpHeaders, ) { return gax.constructSettings( serviceName, clientConfig, configOverrides, this.grpc.status, - {metadataBuilder: this.metadataBuilder(headers)} + {metadataBuilder: this.metadataBuilder(headers)}, ); } @@ -392,7 +392,7 @@ export class GrpcClient { async createStub( CreateStub: typeof ClientStub, options: ClientStubOptions, - customServicePath?: boolean + customServicePath?: boolean, ) { // The following options are understood by grpc-gcp and need a special treatment // (should be passed without a `grpc.` prefix) @@ -403,12 +403,12 @@ export class GrpcClient { ]; const [cert, key] = await this._detectClientCertificate( options, - options.universeDomain + options.universeDomain, ); const servicePath = this._mtlsServicePath( options.servicePath, customServicePath, - cert && key + cert && key, ); const opts = Object.assign({}, options, {cert, key, servicePath}); const serviceAddress = servicePath + ':' + opts.port; @@ -420,7 +420,7 @@ export class GrpcClient { if (universeFromAuth && options.universeDomain !== universeFromAuth) { throw new Error( `The configured universe domain (${options.universeDomain}) does not match the universe domain found in the credentials (${universeFromAuth}). ` + - "If you haven't configured the universe domain explicitly, googleapis.com is the default." + "If you haven't configured the universe domain explicitly, googleapis.com is the default.", ); } } @@ -453,7 +453,7 @@ export class GrpcClient { const stub = new CreateStub( serviceAddress, creds, - grpcOptions as ClientOptions + grpcOptions as ClientOptions, ); return stub; } @@ -467,7 +467,7 @@ export class GrpcClient { */ async _detectClientCertificate( opts?: ClientOptions, - universeDomain?: string + universeDomain?: string, ) { const certRegex = /(?-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----)/s; @@ -480,7 +480,7 @@ export class GrpcClient { ) { if (universeDomain && universeDomain !== 'googleapis.com') { throw new Error( - 'mTLS is not supported outside of googleapis.com universe domain.' + 'mTLS is not supported outside of googleapis.com universe domain.', ); } if (opts?.cert && opts?.key) { @@ -491,7 +491,7 @@ export class GrpcClient { const metadataPath = join( os.homedir(), '.secureConnect', - 'context_aware_metadata.json' + 'context_aware_metadata.json', ); const metadata = JSON.parse(await readFileAsync(metadataPath)); if (!metadata.cert_provider_command) { @@ -499,7 +499,7 @@ export class GrpcClient { } const stdout = await execFileAsync( metadata.cert_provider_command[0], - metadata.cert_provider_command.slice(1) + metadata.cert_provider_command.slice(1), ); const matchCert = stdout.toString().match(certRegex); const matchKey = stdout.toString().match(keyRegex); @@ -526,7 +526,7 @@ export class GrpcClient { _mtlsServicePath( servicePath: string | undefined, customServicePath: boolean | undefined, - hasCertificate: boolean + hasCertificate: boolean, ): string | undefined { // If user provides a custom service path, return the current service // path and do not attempt to add mtls subdomain: diff --git a/gax/src/iamService.ts b/gax/src/iamService.ts index 758536775..161b2ceca 100644 --- a/gax/src/iamService.ts +++ b/gax/src/iamService.ts @@ -49,7 +49,7 @@ export class IamClient { constructor( gaxGrpc: GrpcClient | FallbackGrpcClient, // eslint-disable-next-line @typescript-eslint/no-explicit-any - options: ClientOptions + options: ClientOptions, ) { this.gaxGrpc = gaxGrpc; // Ensure that options include the service address and port. @@ -61,7 +61,7 @@ export class IamClient { apiEndpoint: options.apiEndpoint, fallback: options.fallback, }, - options + options, ) as ClientOptions & ClientStubOptions; version = opts.fallback ? fallback.version : version; opts.scopes = (this.constructor as typeof IamClient).scopes; @@ -90,7 +90,7 @@ export class IamClient { 'google.iam.v1.IAMPolicy', gapicConfig as gax.ClientConfig, opts!.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')} + {'x-goog-api-client': clientHeader.join(' ')}, ); this.innerApiCalls = {}; } @@ -117,7 +117,7 @@ export class IamClient { this._opts.fallback ? this._protos.lookupService('google.iam.v1.IAMPolicy') : this._protos.google.iam.v1.IAMPolicy, - this._opts + this._opts, ) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -139,12 +139,12 @@ export class IamClient { }, (err: Error | null | undefined) => () => { throw err; - } + }, ); this.innerApiCalls[methodName] = createApiCall( innerCallPromise, this._defaults[methodName], - this.descriptors.page[methodName] + this.descriptors.page[methodName], ); } return this.iamPolicyStub; @@ -202,7 +202,7 @@ export class IamClient { getIamPolicy( request: protos.google.iam.v1.GetIamPolicyRequest, - options?: gax.CallOptions + options?: gax.CallOptions, ): Promise<[protos.google.iam.v1.Policy]>; getIamPolicy( request: protos.google.iam.v1.GetIamPolicyRequest, @@ -211,7 +211,7 @@ export class IamClient { protos.google.iam.v1.Policy, protos.google.iam.v1.GetIamPolicyRequest | null | undefined, {} | null | undefined - > + >, ): void; getIamPolicy( request: protos.google.iam.v1.GetIamPolicyRequest, @@ -219,7 +219,7 @@ export class IamClient { protos.google.iam.v1.Policy, protos.google.iam.v1.GetIamPolicyRequest | null | undefined, {} | null | undefined - > + >, ): void; getIamPolicy( request: protos.google.iam.v1.GetIamPolicyRequest, @@ -234,7 +234,7 @@ export class IamClient { protos.google.iam.v1.Policy, protos.google.iam.v1.GetIamPolicyRequest | null | undefined, {} | null | undefined - > + >, ): Promise<[protos.google.iam.v1.Policy]> { let options: gax.CallOptions; if (optionsOrCallback instanceof Function && callback === undefined) { @@ -261,7 +261,7 @@ export class IamClient { setIamPolicy( request: protos.google.iam.v1.SetIamPolicyRequest, - options?: gax.CallOptions + options?: gax.CallOptions, ): Promise<[protos.google.iam.v1.Policy]>; setIamPolicy( request: protos.google.iam.v1.SetIamPolicyRequest, @@ -270,7 +270,7 @@ export class IamClient { protos.google.iam.v1.Policy, protos.google.iam.v1.SetIamPolicyRequest | null | undefined, {} | null | undefined - > + >, ): void; setIamPolicy( request: protos.google.iam.v1.SetIamPolicyRequest, @@ -278,7 +278,7 @@ export class IamClient { protos.google.iam.v1.Policy, protos.google.iam.v1.SetIamPolicyRequest | null | undefined, {} | null | undefined - > + >, ): void; setIamPolicy( request: protos.google.iam.v1.SetIamPolicyRequest, @@ -293,7 +293,7 @@ export class IamClient { protos.google.iam.v1.Policy, protos.google.iam.v1.SetIamPolicyRequest | null | undefined, {} | null | undefined - > + >, ): Promise<[protos.google.iam.v1.Policy]> { let options: gax.CallOptions; if (optionsOrCallback instanceof Function && callback === undefined) { @@ -319,7 +319,7 @@ export class IamClient { } testIamPermissions( request: protos.google.iam.v1.TestIamPermissionsRequest, - options?: gax.CallOptions + options?: gax.CallOptions, ): Promise<[protos.google.iam.v1.TestIamPermissionsResponse]>; testIamPermissions( request: protos.google.iam.v1.TestIamPermissionsRequest, @@ -327,7 +327,7 @@ export class IamClient { protos.google.iam.v1.TestIamPermissionsResponse, protos.google.iam.v1.TestIamPermissionsRequest | null | undefined, {} | null | undefined - > + >, ): void; testIamPermissions( request: protos.google.iam.v1.TestIamPermissionsRequest, @@ -336,7 +336,7 @@ export class IamClient { protos.google.iam.v1.TestIamPermissionsResponse, protos.google.iam.v1.TestIamPermissionsRequest | null | undefined, {} | null | undefined - > + >, ): void; testIamPermissions( request: protos.google.iam.v1.TestIamPermissionsRequest, @@ -351,7 +351,7 @@ export class IamClient { protos.google.iam.v1.TestIamPermissionsResponse, protos.google.iam.v1.TestIamPermissionsRequest | null | undefined, {} | null | undefined - > + >, ): Promise<[protos.google.iam.v1.TestIamPermissionsResponse]> { let options: gax.CallOptions; if (optionsOrCallback instanceof Function && callback === undefined) { @@ -407,7 +407,7 @@ export interface IamClient { protos.google.iam.v1.Policy, protos.google.iam.v1.GetIamPolicyRequest | null | undefined, {} | null | undefined - > + >, ): Promise<[protos.google.iam.v1.Policy]>; setIamPolicy(request: protos.google.iam.v1.SetIamPolicyRequest): void; setIamPolicy( @@ -423,10 +423,10 @@ export interface IamClient { protos.google.iam.v1.Policy, protos.google.iam.v1.SetIamPolicyRequest | null | undefined, {} | null | undefined - > + >, ): Promise<[protos.google.iam.v1.Policy]>; testIamPermissions( - request: protos.google.iam.v1.TestIamPermissionsRequest + request: protos.google.iam.v1.TestIamPermissionsRequest, ): void; testIamPermissions( request: protos.google.iam.v1.TestIamPermissionsRequest, @@ -441,6 +441,6 @@ export interface IamClient { protos.google.iam.v1.TestIamPermissionsResponse, protos.google.iam.v1.TestIamPermissionsRequest | null | undefined, {} | null | undefined - > + >, ): Promise<[protos.google.iam.v1.TestIamPermissionsResponse]>; } diff --git a/gax/src/locationService.ts b/gax/src/locationService.ts index bfe49b865..825c4a3cf 100644 --- a/gax/src/locationService.ts +++ b/gax/src/locationService.ts @@ -100,7 +100,7 @@ export class LocationsClient { constructor( gaxGrpc: GrpcClient | FallbackGrpcClient, // eslint-disable-next-line @typescript-eslint/no-explicit-any - opts: ClientOptions + opts: ClientOptions, ) { // Ensure that options include all the required fields. this.gaxGrpc = gaxGrpc; @@ -158,7 +158,7 @@ export class LocationsClient { listLocations: new PageDescriptor( 'pageToken', 'nextPageToken', - 'locations' + 'locations', ), }; @@ -167,7 +167,7 @@ export class LocationsClient { 'google.cloud.location.Locations', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')} + {'x-goog-api-client': clientHeader.join(' ')}, ); // Set up a dictionary of "inner API calls"; the core implementation @@ -201,12 +201,12 @@ export class LocationsClient { this.locationsStub = this.gaxGrpc.createStub( this._opts.fallback ? (this._protos as protobuf.Root).lookupService( - 'google.cloud.location.Locations' + 'google.cloud.location.Locations', ) : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.location.Locations, this._opts, - this._providedCustomServicePath + this._providedCustomServicePath, ) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides @@ -224,14 +224,14 @@ export class LocationsClient { }, (err: Error | null | undefined) => () => { throw err; - } + }, ); const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = createApiCall( callPromise, this._defaults[methodName], - descriptor + descriptor, ); this.innerApiCalls[methodName] = apiCall; @@ -281,7 +281,7 @@ export class LocationsClient { getProjectId(): Promise; getProjectId(callback: Callback): void; getProjectId( - callback?: Callback + callback?: Callback, ): Promise | void { if (callback) { this.auth.getProjectId(callback); @@ -295,7 +295,7 @@ export class LocationsClient { // ------------------- getLocation( request?: protos.google.cloud.location.IGetLocationRequest, - options?: gax.CallOptions + options?: gax.CallOptions, ): Promise; getLocation( request: protos.google.cloud.location.IGetLocationRequest, @@ -304,7 +304,7 @@ export class LocationsClient { protos.google.cloud.location.ILocation, protos.google.cloud.location.IGetLocationRequest | null | undefined, {} | null | undefined - > + >, ): void; getLocation( request: protos.google.cloud.location.IGetLocationRequest, @@ -312,7 +312,7 @@ export class LocationsClient { protos.google.cloud.location.ILocation, protos.google.cloud.location.IGetLocationRequest | null | undefined, {} | null | undefined - > + >, ): void; /** * Gets information about a location. @@ -344,7 +344,7 @@ export class LocationsClient { protos.google.cloud.location.ILocation, protos.google.cloud.location.IGetLocationRequest | null | undefined, {} | null | undefined - > + >, ): Promise { request = request || {}; let options: gax.CallOptions; @@ -367,7 +367,7 @@ export class LocationsClient { listLocations( request?: protos.google.cloud.location.IListLocationsRequest, - options?: gax.CallOptions + options?: gax.CallOptions, ): Promise< [ protos.google.cloud.location.ILocation[], @@ -382,7 +382,7 @@ export class LocationsClient { protos.google.cloud.location.IListLocationsRequest, protos.google.cloud.location.IListLocationsResponse | null | undefined, protos.google.cloud.location.ILocation - > + >, ): void; listLocations( request: protos.google.cloud.location.IListLocationsRequest, @@ -390,7 +390,7 @@ export class LocationsClient { protos.google.cloud.location.IListLocationsRequest, protos.google.cloud.location.IListLocationsResponse | null | undefined, protos.google.cloud.location.ILocation - > + >, ): void; /** * Lists information about the supported locations for this service. @@ -433,7 +433,7 @@ export class LocationsClient { protos.google.cloud.location.IListLocationsRequest, protos.google.cloud.location.IListLocationsResponse | null | undefined, protos.google.cloud.location.ILocation - > + >, ): Promise< [ protos.google.cloud.location.ILocation[], @@ -492,7 +492,7 @@ export class LocationsClient { */ listLocationsAsync( request: protos.google.cloud.location.IListLocationsRequest, - options?: gax.CallOptions + options?: gax.CallOptions, ): AsyncIterable { request = request || {}; options = options || {}; @@ -508,7 +508,7 @@ export class LocationsClient { return this.descriptors.page.listLocations.asyncIterate( this.innerApiCalls['listLocations'] as GaxCall, request as unknown as RequestType, - callSettings + callSettings, ) as AsyncIterable; } @@ -545,11 +545,11 @@ export interface LocationsClient { protos.google.cloud.location.ILocation, protos.google.cloud.location.IGetLocationRequest | null | undefined, {} | null | undefined - > + >, ): Promise; listLocationsAsync( request: protos.google.cloud.location.IListLocationsRequest, - options?: gax.CallOptions + options?: gax.CallOptions, ): AsyncIterable; } diff --git a/gax/src/longRunningCalls/longRunningApiCaller.ts b/gax/src/longRunningCalls/longRunningApiCaller.ts index 7f4501dcc..c0c17f985 100644 --- a/gax/src/longRunningCalls/longRunningApiCaller.ts +++ b/gax/src/longRunningCalls/longRunningApiCaller.ts @@ -58,7 +58,7 @@ export class LongrunningApiCaller implements APICaller { apiCall: SimpleCallbackFunction, argument: {}, settings: CallOptions, - canceller: OngoingCallPromise + canceller: OngoingCallPromise, ) { canceller.call((argument, callback) => { return this._wrapOperation(apiCall, settings, argument, callback); @@ -69,7 +69,7 @@ export class LongrunningApiCaller implements APICaller { apiCall: SimpleCallbackFunction, settings: CallOptions, argument: {}, - callback: APICallback + callback: APICallback, ) { let backoffSettings: BackoffSettings | undefined = settings.longrunning; if (!backoffSettings) { @@ -89,11 +89,11 @@ export class LongrunningApiCaller implements APICaller { rawResponse as operationProtos.google.longrunning.Operation, longrunningDescriptor, backoffSettings!, - settings + settings, ); callback(null, operation, rawResponse); - } + }, ); } diff --git a/gax/src/longRunningCalls/longRunningDescriptor.ts b/gax/src/longRunningCalls/longRunningDescriptor.ts index 673e167c5..58b823853 100644 --- a/gax/src/longRunningCalls/longRunningDescriptor.ts +++ b/gax/src/longRunningCalls/longRunningDescriptor.ts @@ -37,7 +37,7 @@ export class LongRunningDescriptor implements Descriptor { constructor( operationsClient: OperationsClient, responseDecoder: AnyDecoder, - metadataDecoder: AnyDecoder + metadataDecoder: AnyDecoder, ) { this.operationsClient = operationsClient; this.responseDecoder = responseDecoder; diff --git a/gax/src/longRunningCalls/longrunning.ts b/gax/src/longRunningCalls/longrunning.ts index e061ccf99..492406c08 100644 --- a/gax/src/longRunningCalls/longrunning.ts +++ b/gax/src/longRunningCalls/longrunning.ts @@ -37,7 +37,7 @@ export interface GetOperationCallback { err?: Error | null, result?: {}, metadata?: {}, - rawResponse?: LROOperation + rawResponse?: LROOperation, ): void; } @@ -75,7 +75,7 @@ export class Operation extends EventEmitter { grpcOp: LROOperation, longrunningDescriptor: LongRunningDescriptor, backoffSettings: BackoffSettings, - callOptions?: CallOptions + callOptions?: CallOptions, ) { super(); this.completeListeners = 0; @@ -186,7 +186,7 @@ export class Operation extends EventEmitter { request.name = this.latestResponse.name; this.currentCallPromise_ = operationsClient.getOperationInternal( request, - this._callOptions! + this._callOptions!, ); const noCallbackPromise = this.currentCallPromise_.then( @@ -201,7 +201,7 @@ export class Operation extends EventEmitter { return; } return Promise.reject(err); - } + }, ); if (!callback) { @@ -292,7 +292,7 @@ export class Operation extends EventEmitter { if (now.getTime() >= deadline) { const error = new GoogleError( - 'Total timeout exceeded before any response was received' + 'Total timeout exceeded before any response was received', ); error.code = Status.DEADLINE_EXCEEDED; setImmediate(emit, 'error', error); @@ -312,7 +312,7 @@ export class Operation extends EventEmitter { (rawResponse && !arrayEquals( rawResponse.metadata.value!, - previousMetadataBytes + previousMetadataBytes, ))) ) { setImmediate(emit, 'progress', metadata, rawResponse); @@ -353,7 +353,7 @@ export class Operation extends EventEmitter { 'complete', (result, metadata, rawResponse) => { resolve([result, metadata, rawResponse]); - } + }, ); }); } @@ -376,7 +376,7 @@ export function operation( op: LROOperation, longrunningDescriptor: LongRunningDescriptor, backoffSettings: BackoffSettings, - callOptions?: CallOptions + callOptions?: CallOptions, ) { return new Operation(op, longrunningDescriptor, backoffSettings, callOptions); } diff --git a/gax/src/normalCalls/normalApiCaller.ts b/gax/src/normalCalls/normalApiCaller.ts index 50c424efb..b2da678f9 100644 --- a/gax/src/normalCalls/normalApiCaller.ts +++ b/gax/src/normalCalls/normalApiCaller.ts @@ -38,7 +38,7 @@ export class NormalApiCaller implements APICaller { apiCall: SimpleCallbackFunction, argument: {}, settings: {}, - canceller: OngoingCallPromise + canceller: OngoingCallPromise, ): void { canceller.call(apiCall, argument); } diff --git a/gax/src/normalCalls/retries.ts b/gax/src/normalCalls/retries.ts index ed67a4679..b0dc8c3c7 100644 --- a/gax/src/normalCalls/retries.ts +++ b/gax/src/normalCalls/retries.ts @@ -46,7 +46,7 @@ export function retryable( func: GRPCCall, retry: RetryOptions, otherArgs: GRPCCallOtherArgs, - apiName?: string + apiName?: string, ): SimpleCallbackFunction { const delayMult = retry.backoffSettings.retryDelayMultiplier; const maxDelay = retry.backoffSettings.maxRetryDelayMillis; @@ -86,7 +86,7 @@ export function retryable( retry.backoffSettings.totalTimeoutMillis } milliseconds ${ err ? `retrying error ${err} ` : '' - } before any response was received.` + } before any response was received.`, ); error.code = Status.DEADLINE_EXCEEDED; callback(error); @@ -97,7 +97,7 @@ export function retryable( const error = new GoogleError( 'Exceeded maximum number of retries ' + (err ? `retrying error ${err} ` : '') + - 'before any response was received' + 'before any response was received', ); error.code = Status.DEADLINE_EXCEEDED; callback(error); @@ -149,7 +149,7 @@ export function retryable( if (maxRetries && deadline!) { const error = new GoogleError( 'Cannot set both totalTimeoutMillis and maxRetries ' + - 'in backoffSettings.' + 'in backoffSettings.', ); error.code = Status.INVALID_ARGUMENT; callback(error); diff --git a/gax/src/normalCalls/timeout.ts b/gax/src/normalCalls/timeout.ts index b1790d854..440a89cb5 100644 --- a/gax/src/normalCalls/timeout.ts +++ b/gax/src/normalCalls/timeout.ts @@ -40,7 +40,7 @@ export function addTimeoutArg( func: GRPCCall, timeout: number, otherArgs: GRPCCallOtherArgs, - abTests?: {} + abTests?: {}, ): SimpleCallbackFunction { // TODO: this assumes the other arguments consist of metadata and options, // which is specific to gRPC calls. Remove the hidden dependency on gRPC. diff --git a/gax/src/operationsClient.ts b/gax/src/operationsClient.ts index 2941ff436..a9920f911 100644 --- a/gax/src/operationsClient.ts +++ b/gax/src/operationsClient.ts @@ -70,7 +70,7 @@ export class OperationsClient { gaxGrpc: GrpcClient | FallbackGrpcClient, // eslint-disable-next-line @typescript-eslint/no-explicit-any operationsProtos: any, - options: ClientOptions + options: ClientOptions, ) { const opts = Object.assign( { @@ -78,7 +78,7 @@ export class OperationsClient { port: DEFAULT_SERVICE_PORT, clientConfig: {}, }, - options + options, ) as ClientOptions & ClientStubOptions; const googleApiClient = ['gl-node/' + process.versions.node]; @@ -96,7 +96,7 @@ export class OperationsClient { 'google.longrunning.Operations', configData, opts.clientConfig || {}, - {'x-goog-api-client': googleApiClient.join(' ')} + {'x-goog-api-client': googleApiClient.join(' ')}, ); this.auth = gaxGrpc.auth; @@ -109,7 +109,7 @@ export class OperationsClient { listOperations: new PageDescriptor( 'pageToken', 'nextPageToken', - 'operations' + 'operations', ), }; // Put together the "service stub" for @@ -118,7 +118,7 @@ export class OperationsClient { opts.fallback ? operationsProtos.lookupService('google.longrunning.Operations') : operationsProtos.google.longrunning.Operations, - opts + opts, ) as Promise<{[method: string]: Function}>; const operationsStubMethods = [ 'getOperation', @@ -136,12 +136,12 @@ export class OperationsClient { }, err => () => { throw err; - } + }, ); this.innerApiCalls[methodName] = createApiCall( innerCallPromise, defaults[methodName], - this.descriptor[methodName] + this.descriptor[methodName], ); } } @@ -177,7 +177,7 @@ export class OperationsClient { protos.google.longrunning.Operation, protos.google.longrunning.GetOperationRequest, {} | null | undefined - > + >, ): CancellablePromise { request = request || {}; options = options || {}; @@ -227,7 +227,7 @@ export class OperationsClient { protos.google.longrunning.Operation, protos.google.longrunning.GetOperationRequest, {} | null | undefined - > + >, ): Promise<[protos.google.longrunning.Operation]> { let options: gax.CallOptions; if (optionsOrCallback instanceof Function && callback === undefined) { @@ -335,7 +335,7 @@ export class OperationsClient { protos.google.longrunning.ListOperationsResponse, protos.google.longrunning.ListOperationsRequest, {} | null | undefined - > + >, ): Promise { let options: gax.CallOptions; if (optionsOrCallback instanceof Function && callback === undefined) { @@ -399,13 +399,13 @@ export class OperationsClient { */ listOperationsStream( request: protos.google.longrunning.ListOperationsRequest, - options?: gax.CallOptions + options?: gax.CallOptions, ): Transform { const callSettings = new gax.CallSettings(options); return this.descriptor.listOperations.createStream( this.innerApiCalls.listOperations as GaxCall, request, - callSettings + callSettings, ); } /** @@ -432,7 +432,7 @@ export class OperationsClient { */ listOperationsAsync( request: protos.google.longrunning.ListOperationsRequest, - options?: gax.CallOptions + options?: gax.CallOptions, ): AsyncIterable { request = request || {}; options = options || {}; @@ -440,7 +440,7 @@ export class OperationsClient { return this.descriptor.listOperations.asyncIterate( this.innerApiCalls.listOperations as GaxCall, request as unknown as RequestType, - callSettings + callSettings, ) as AsyncIterable; } @@ -487,7 +487,7 @@ export class OperationsClient { protos.google.longrunning.CancelOperationRequest, protos.google.protobuf.Empty, {} | undefined | null - > + >, ): Promise { let options: gax.CallOptions; if (optionsOrCallback instanceof Function && callback === undefined) { @@ -542,7 +542,7 @@ export class OperationsClient { protos.google.protobuf.Empty, protos.google.longrunning.DeleteOperationRequest, {} | null | undefined - > + >, ): Promise { let options: gax.CallOptions; if (optionsOrCallback instanceof Function && callback === undefined) { @@ -570,7 +570,7 @@ export class OperationsClientBuilder { */ constructor( gaxGrpc: GrpcClient | FallbackGrpcClient, - protoJson?: protobuf.Root + protoJson?: protobuf.Root, ) { if (protoJson && gaxGrpc.httpRules) { // overwrite the http rules if provide in service yaml. diff --git a/gax/src/paginationCalls/pageDescriptor.ts b/gax/src/paginationCalls/pageDescriptor.ts index 80aeb9766..9fc57c55d 100644 --- a/gax/src/paginationCalls/pageDescriptor.ts +++ b/gax/src/paginationCalls/pageDescriptor.ts @@ -49,7 +49,7 @@ export class PageDescriptor implements Descriptor { constructor( requestPageTokenField: string, responsePageTokenField: string, - resourceField: string + resourceField: string, ) { this.requestPageTokenField = requestPageTokenField; this.responsePageTokenField = responsePageTokenField; @@ -62,13 +62,13 @@ export class PageDescriptor implements Descriptor { createStream( apiCall: GaxCall, request: {}, - options: CallSettings + options: CallSettings, ): Transform { if (options?.autoPaginate) { warn( 'autoPaginate true', 'Autopaginate will always be set to false in stream paging methods. See more info at https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#auto-pagination for more information on how to configure paging calls', - 'AutopaginateTrueWarning' + 'AutopaginateTrueWarning', ); } const stream = new PassThrough({objectMode: true}); @@ -80,7 +80,7 @@ export class PageDescriptor implements Descriptor { err: Error | null, resources: Array, next: NextPageRequestType, - apiResp: RawResponseType + apiResp: RawResponseType, ) { if (err) { stream.emit('error', err); @@ -143,13 +143,13 @@ export class PageDescriptor implements Descriptor { asyncIterate( apiCall: GaxCall, request: RequestType, - options?: CallSettings + options?: CallSettings, ): AsyncIterable<{} | undefined> { if (options?.autoPaginate) { warn( 'autoPaginate true', 'Autopaginate will always be set to false in Async paging methods. See more info at https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#auto-pagination for more information on how to configure paging calls', - 'AutopaginateTrueWarning' + 'AutopaginateTrueWarning', ); } options = Object.assign({}, options, {autoPaginate: false}); @@ -160,7 +160,7 @@ export class PageDescriptor implements Descriptor { createIterator( apiCall: GaxCall, request: RequestType, - options: CallSettings + options: CallSettings, ): AsyncIterable<{} | undefined> { const asyncIterable = { [Symbol.asyncIterator]() { @@ -179,7 +179,7 @@ export class PageDescriptor implements Descriptor { let result: {} | [ResponseType] | null; [result, nextPageRequest] = (await apiCall( nextPageRequest!, - options + options, )) as ResultTuple; // For pagination response with protobuf map type, use tuple as representation. if (result && !Array.isArray(result)) { diff --git a/gax/src/paginationCalls/pagedApiCaller.ts b/gax/src/paginationCalls/pagedApiCaller.ts index bf92b76cc..e22bcf3f5 100644 --- a/gax/src/paginationCalls/pagedApiCaller.ts +++ b/gax/src/paginationCalls/pagedApiCaller.ts @@ -59,7 +59,7 @@ export class PagedApiCaller implements APICaller { */ private generateParseResponseCallback( request: NextPageRequestType, - callback: APICallback + callback: APICallback, ): APICallback { const resourceFieldName = this.pageDescriptor.resourceField; const responsePageTokenFieldName = @@ -72,13 +72,13 @@ export class PagedApiCaller implements APICaller { } if (!request) { callback( - new GoogleError('Undefined request in pagination method callback.') + new GoogleError('Undefined request in pagination method callback.'), ); return; } if (!response) { callback( - new GoogleError('Undefined response in pagination method callback.') + new GoogleError('Undefined response in pagination method callback.'), ); return; } @@ -109,7 +109,7 @@ export class PagedApiCaller implements APICaller { argument, metadata, options, - self.generateParseResponseCallback(argument, callback) + self.generateParseResponseCallback(argument, callback), ); }; } @@ -144,7 +144,7 @@ export class PagedApiCaller implements APICaller { apiCall: SimpleCallbackFunction, request: RequestType, settings: CallOptions, - ongoingCall: OngoingCall + ongoingCall: OngoingCall, ) { request = Object.assign({}, request); @@ -157,7 +157,7 @@ export class PagedApiCaller implements APICaller { warn( 'autoPaginate true', 'Providing a pageSize without setting autoPaginate to false will still return all results. See https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#auto-pagination for more information on how to configure manual paging', - 'AutopaginateTrueWarning' + 'AutopaginateTrueWarning', ); } @@ -166,7 +166,7 @@ export class PagedApiCaller implements APICaller { const resourceCollector = new ResourceCollector(apiCall, maxResults); resourceCollector.processAllPages(request).then( resources => ongoingCall.callback(null, resources), - err => ongoingCall.callback(err) + err => ongoingCall.callback(err), ); } diff --git a/gax/src/paginationCalls/resourceCollector.ts b/gax/src/paginationCalls/resourceCollector.ts index 268b5b143..bf64a374b 100644 --- a/gax/src/paginationCalls/resourceCollector.ts +++ b/gax/src/paginationCalls/resourceCollector.ts @@ -45,7 +45,7 @@ export class ResourceCollector { private callback( err: Error | null, resources: Array<{}>, - nextPageRequest: NextPageRequestType + nextPageRequest: NextPageRequestType, ) { if (err) { // Something went wrong with this request - failing everything diff --git a/gax/src/pathTemplate.ts b/gax/src/pathTemplate.ts index ae208448c..636b90db7 100644 --- a/gax/src/pathTemplate.ts +++ b/gax/src/pathTemplate.ts @@ -52,11 +52,11 @@ export class PathTemplate { // if the path contains a wildcard, then the length may differ by 1. if (!this.data.includes('**')) { throw new TypeError( - `This path ${path} does not match path template ${this.data}, the number of parameters is not same.` + `This path ${path} does not match path template ${this.data}, the number of parameters is not same.`, ); } else if (pathSegments.length !== this.segments.length + 1) { throw new TypeError( - `This path ${path} does not match path template ${this.data}, the number of parameters is not same with one wildcard.` + `This path ${path} does not match path template ${this.data}, the number of parameters is not same with one wildcard.`, ); } } @@ -68,18 +68,18 @@ export class PathTemplate { if (this.segments[index] !== pathSegments[0]) { if (!this.segments[index].includes('*')) { throw new TypeError( - `segment does not match, ${this.segments[index]} and ${pathSegments[index]}.` + `segment does not match, ${this.segments[index]} and ${pathSegments[index]}.`, ); } else { let segment = this.segments[index]; const matches = segment.match(/\{[$0-9a-zA-Z_]+=.*?\}/g); if (!matches) { throw new Error( - `Error processing path template segment ${segment}` + `Error processing path template segment ${segment}`, ); } const variables = matches.map(str => - str.replace(/^\{/, '').replace(/=.*/, '') + str.replace(/^\{/, '').replace(/=.*/, ''), ); if (segment.includes('**')) { bindings[variables[0]] = pathSegments[0] + '/' + pathSegments[1]; @@ -96,7 +96,7 @@ export class PathTemplate { const value = pathSegments[0].split(/[-_.~]/); if (value.length !== variables.length) { throw new Error( - `segment ${segment} does not match ${pathSegments[0]}` + `segment ${segment} does not match ${pathSegments[0]}`, ); } for (const v of variables) { @@ -107,7 +107,7 @@ export class PathTemplate { // segment: {blurb_id=*}.{legacy_user=*} matching pathSegments: ['bar~user2'] should fail if (segment !== pathSegments[0]) { throw new TypeError( - `non slash resource pattern ${this.segments[index]} and ${pathSegments[0]} should have same separator` + `non slash resource pattern ${this.segments[index]} and ${pathSegments[0]} should have same separator`, ); } } @@ -136,7 +136,7 @@ export class PathTemplate { Object.keys(bindings).length } does not match the number of needed variables ${ Object.keys(this.bindings).length - }` + }`, ); } let path = this.inspect(); @@ -195,11 +195,11 @@ export class PathTemplate { } else if ((matches = segment.match(/\{[0-9a-zA-Z-.~_]+(?:=.*?)?\}/g))) { for (const subsegment of matches) { const pairMatch = subsegment.match( - /^\{([0-9a-zA-Z-.~_]+)(?:=(.*?))?\}$/ + /^\{([0-9a-zA-Z-.~_]+)(?:=(.*?))?\}$/, ); if (!pairMatch) { throw new Error( - `Cannot process path template segment ${subsegment}` + `Cannot process path template segment ${subsegment}`, ); } const key = pairMatch[1]; diff --git a/gax/src/streamArrayParser.ts b/gax/src/streamArrayParser.ts index 7aa03c1f4..4d001894a 100644 --- a/gax/src/streamArrayParser.ts +++ b/gax/src/streamArrayParser.ts @@ -75,9 +75,9 @@ export class StreamArrayParser extends Transform { 'error', new Error( `Internal Error: API service stream data must start with a '[' and close with the corresponding ']', but it start with ${String.fromCharCode( - chunk[0] - )}` - ) + chunk[0], + )}`, + ), ); } curIndex++; diff --git a/gax/src/streamingCalls/streamDescriptor.ts b/gax/src/streamingCalls/streamDescriptor.ts index fc6090d09..2ac1490fb 100644 --- a/gax/src/streamingCalls/streamDescriptor.ts +++ b/gax/src/streamingCalls/streamDescriptor.ts @@ -31,7 +31,7 @@ export class StreamDescriptor implements Descriptor { constructor( streamType: StreamType, rest?: boolean, - gaxStreamingRetries?: boolean + gaxStreamingRetries?: boolean, ) { this.type = streamType; this.streaming = true; diff --git a/gax/src/streamingCalls/streaming.ts b/gax/src/streamingCalls/streaming.ts index 5dd6fd9e1..4f67fece2 100644 --- a/gax/src/streamingCalls/streaming.ts +++ b/gax/src/streamingCalls/streaming.ts @@ -55,17 +55,17 @@ export interface DuplexifyConstructor { obj( writable?: Writable | false | null, readable?: Readable | false | null, - options?: DuplexifyOptions + options?: DuplexifyOptions, ): Duplexify; new ( writable?: Writable | false | null, readable?: Readable | false | null, - options?: DuplexifyOptions + options?: DuplexifyOptions, ): Duplexify; ( writable?: Writable | false | null, readable?: Readable | false | null, - options?: DuplexifyOptions + options?: DuplexifyOptions, ): Duplexify; } @@ -117,7 +117,7 @@ export class StreamProxy extends duplexify implements GRPCCallResult { type: StreamType, callback: APICallback, rest?: boolean, - gaxServerStreamingRetries?: boolean + gaxServerStreamingRetries?: boolean, ) { super(undefined, undefined, { objectMode: true, @@ -163,7 +163,7 @@ export class StreamProxy extends duplexify implements GRPCCallResult { totalTimeoutMillis: number, originalError: GoogleError, originalTimeout: number | undefined, - retries: number + retries: number, ): void { const now = new Date(); @@ -177,7 +177,7 @@ export class StreamProxy extends duplexify implements GRPCCallResult { const error = new GoogleError( `Total timeout of API exceeded ${originalTimeout} milliseconds ${ originalError ? `retrying error ${originalError} ` : '' - } before any response was received.` + } before any response was received.`, ); error.code = Status.DEADLINE_EXCEEDED; throw error; @@ -191,7 +191,7 @@ export class StreamProxy extends duplexify implements GRPCCallResult { const error = new GoogleError( 'Exceeded maximum number of retries ' + (originalError ? `retrying error ${originalError} ` : '') + - 'before any response was received' + 'before any response was received', ); error.code = Status.DEADLINE_EXCEEDED; throw error; @@ -293,7 +293,7 @@ export class StreamProxy extends duplexify implements GRPCCallResult { apiCall: SimpleCallbackFunction, argument: {}, retryRequestOptions: RetryRequestOptions = {}, - retry: RetryOptions + retry: RetryOptions, ) { this.apiCall = apiCall; this.argument = argument; @@ -330,7 +330,7 @@ export class StreamProxy extends duplexify implements GRPCCallResult { } const stream = apiCall( argument, - this._callback + this._callback, ) as CancellableStream; this.stream = stream; this.forwardEvents(stream); @@ -373,7 +373,7 @@ export class StreamProxy extends duplexify implements GRPCCallResult { * @returns {CancellableStream} - the stream that handles retry logic */ private newStreamingRetryRequest( - opts: streamingRetryRequestOptions + opts: streamingRetryRequestOptions, ): CancellableStream { // at this point, it would be unexpected if retry were undefined // but if it is, provide a logical default so we don't run into trouble @@ -397,7 +397,7 @@ export class StreamProxy extends duplexify implements GRPCCallResult { } const transientErrorHelper = ( error: Error, - requestStream: CancellableStream + requestStream: CancellableStream, ) => { const e = GoogleError.parseGRPCStatusDetails(error); e.note = @@ -488,7 +488,7 @@ export class StreamProxy extends duplexify implements GRPCCallResult { if (maxRetries && totalTimeout) { const newError = new GoogleError( 'Cannot set both totalTimeoutMillis and maxRetries ' + - 'in backoffSettings.' + 'in backoffSettings.', ); newError.code = Status.INVALID_ARGUMENT; // clean up the request stream and retryStreams, silently destroy it on the request stream @@ -507,11 +507,11 @@ export class StreamProxy extends duplexify implements GRPCCallResult { timeout!, error, totalTimeout, - retries + retries, ); } catch (error: unknown) { const e = GoogleError.parseGRPCStatusDetails( - error as GoogleError + error as GoogleError, ); // clean up the request stream and retryStreams, silently destroy it on the request stream // but do raise it on destruction of the retryStream so the consumer can see it @@ -558,7 +558,7 @@ export class StreamProxy extends duplexify implements GRPCCallResult { } const newStream = this.apiCall!( retryArgument, - this._callback + this._callback, ) as CancellableStream; return newStream; }; diff --git a/gax/src/streamingCalls/streamingApiCaller.ts b/gax/src/streamingCalls/streamingApiCaller.ts index 68ddb9855..66bc77fe7 100644 --- a/gax/src/streamingCalls/streamingApiCaller.ts +++ b/gax/src/streamingCalls/streamingApiCaller.ts @@ -48,7 +48,7 @@ export class StreamingApiCaller implements APICaller { this.descriptor.type, callback, this.descriptor.rest, - this.descriptor.gaxStreamingRetries + this.descriptor.gaxStreamingRetries, ); } @@ -63,7 +63,7 @@ export class StreamingApiCaller implements APICaller { argument: {}, metadata: {}, options: {}, - callback?: APICallback + callback?: APICallback, ) => { return (func as ClientStreamingCall)(metadata, options, callback); }; @@ -74,7 +74,7 @@ export class StreamingApiCaller implements APICaller { default: warn( 'streaming_wrap_unknown_stream_type', - `Unknown stream type: ${this.descriptor.type}` + `Unknown stream type: ${this.descriptor.type}`, ); } return func; @@ -84,13 +84,13 @@ export class StreamingApiCaller implements APICaller { apiCall: SimpleCallbackFunction, argument: {}, settings: CallSettings, - stream: StreamProxy + stream: StreamProxy, ) { stream.setStream( apiCall, argument, settings.retryRequestOptions, - settings.retry! + settings.retry!, ); } diff --git a/gax/src/transcoding.ts b/gax/src/transcoding.ts index d4cdf614b..37b399f50 100644 --- a/gax/src/transcoding.ts +++ b/gax/src/transcoding.ts @@ -50,7 +50,7 @@ export type ParsedOptionsType = Array< export function getField( request: JSONObject, field: string, - allowObjects = false // in most cases, we need leaf fields + allowObjects = false, // in most cases, we need leaf fields ): JSONValue | undefined { const parts = field.split('.'); let value: JSONValue = request; @@ -74,7 +74,7 @@ export function getField( export function deepCopyWithoutMatchedFields( request: JSONObject, fieldsToSkip: Set, - fullNamePrefix = '' + fullNamePrefix = '', ): JSONObject { if (typeof request !== 'object' || request === null) { return request; @@ -89,13 +89,13 @@ export function deepCopyWithoutMatchedFields( if (Array.isArray(copy[key])) { // a field of an array cannot be addressed as "request.field", so we omit the skipping logic for array descendants copy[key] = (copy[key] as JSONObject[]).map(value => - deepCopyWithoutMatchedFields(value, new Set()) + deepCopyWithoutMatchedFields(value, new Set()), ); } else if (typeof copy[key] === 'object' && copy[key] !== null) { copy[key] = deepCopyWithoutMatchedFields( copy[key] as JSONObject, fieldsToSkip, - nextFullNamePrefix + nextFullNamePrefix, ); } } @@ -120,7 +120,7 @@ export function deleteField(request: JSONObject, field: string): void { export function buildQueryStringComponents( request: JSONObject, - prefix = '' + prefix = '', ): string[] { const resultList = []; for (const key in request) { @@ -128,19 +128,19 @@ export function buildQueryStringComponents( for (const value of request[key] as JSONObject[]) { resultList.push( `${prefix}${encodeWithoutSlashes(key)}=${encodeWithoutSlashes( - value.toString() - )}` + value.toString(), + )}`, ); } } else if (typeof request[key] === 'object' && request[key] !== null) { resultList.push( - ...buildQueryStringComponents(request[key] as JSONObject, `${key}.`) + ...buildQueryStringComponents(request[key] as JSONObject, `${key}.`), ); } else { resultList.push( `${prefix}${encodeWithoutSlashes(key)}=${encodeWithoutSlashes( - request[key] === null ? 'null' : request[key]!.toString() - )}` + request[key] === null ? 'null' : request[key]!.toString(), + )}`, ); } } @@ -167,7 +167,7 @@ function escapeRegExp(str: string) { export function applyPattern( pattern: string, - fieldValue: string + fieldValue: string, ): string | undefined { if (!pattern || pattern === '*') { return encodeWithSlashes(fieldValue); @@ -183,7 +183,7 @@ export function applyPattern( escapeRegExp(pattern) .replace(/\\\*\\\*/g, '(.+)') .replace(/\\\*/g, '([^/]+)') + - '$' + '$', ); if (!fieldValue.match(regex)) { @@ -205,7 +205,7 @@ interface MatchResult { export function match( request: JSONObject, - pattern: string + pattern: string, ): MatchResult | undefined { let url = pattern; const matchedFields = []; @@ -223,7 +223,7 @@ export function match( } const appliedPattern = applyPattern( pattern, - fieldValue === null ? 'null' : fieldValue!.toString() + fieldValue === null ? 'null' : fieldValue!.toString(), ); if (appliedPattern === undefined) { return undefined; @@ -268,7 +268,7 @@ export function isProto3OptionalField(field: Field) { export function transcode( request: JSONObject, - parsedOptions: ParsedOptionsType + parsedOptions: ParsedOptionsType, ): TranscodedRequest | undefined { const httpRules = []; for (const option of parsedOptions) { @@ -313,7 +313,7 @@ export function transcode( data = getField( queryStringObject, fieldToCamelCase(httpRule.body), - /*allowObjects:*/ true + /*allowObjects:*/ true, ); deleteField(queryStringObject, fieldToCamelCase(httpRule.body)); } else { @@ -337,7 +337,7 @@ export function transcode( // Override the protobuf json's the http rules. export function overrideHttpRules( httpRules: Array, - protoJson: protobuf.Root + protoJson: protobuf.Root, ) { for (const rule of httpRules) { if (!rule.selector) { diff --git a/gax/src/util.ts b/gax/src/util.ts index 8aab5e316..7948df28c 100644 --- a/gax/src/util.ts +++ b/gax/src/util.ts @@ -88,7 +88,7 @@ export function toCamelCase(str: string) { return '_' + w; } return capitalize(w); - }) + }), ); return result.join(''); } diff --git a/gax/test/system-test/test.clientlibs.ts b/gax/test/system-test/test.clientlibs.ts index b236a7b3e..e7b4c95b8 100644 --- a/gax/test/system-test/test.clientlibs.ts +++ b/gax/test/system-test/test.clientlibs.ts @@ -43,7 +43,7 @@ const toolsTarball = path.join(gaxDir, toolsBasename); async function latestRelease( cwd: string, - inMonorepo: boolean + inMonorepo: boolean, ): Promise { // tags in the monorepo follow the format -major.minor.patch e.g. batch-0.0.1 // or the format -vmajor.minor.patch e.g. batch-v0.0.1 @@ -84,12 +84,12 @@ async function latestRelease( function monoRepoPackageSubdirectory(packageName: string): string { return `${monoRepoDirectory}/packages/google-cloud-${packageName.replace( '-', - '' + '', )}`; } async function preparePackage( packageName: string, - inMonorepo: boolean + inMonorepo: boolean, ): Promise { // clone googleapis/google-cloud node if monorepo, googleapis/nodejs- if not const repoUrl = inMonorepo @@ -101,7 +101,7 @@ async function preparePackage( await execa( 'git', ['clone', repoUrl, inMonorepo ? monoRepoDirectory : packageName], - {stdio: 'inherit'} + {stdio: 'inherit'}, ); clonedRepos.push(repoUrl); } catch (error: unknown) { @@ -118,7 +118,7 @@ async function preparePackage( const packagePath = monoRepoPackageSubdirectory(packageName); // used if in monoRepo const packageJson = path.join( inMonorepo ? packagePath : packageName, - 'package.json' + 'package.json', ); const packageJsonStr = (await readFile(packageJson)).toString(); const packageJsonObj = JSON.parse(packageJsonStr); @@ -140,7 +140,7 @@ enum TestResult { async function runScript( packageName: string, inMonorepo: boolean, - script: string + script: string, ): Promise { try { await execa('npm', ['run', script], { @@ -160,7 +160,7 @@ async function runScript( async function runSystemTest( packageName: string, - inMonorepo: boolean + inMonorepo: boolean, ): Promise { return await runScript(packageName, inMonorepo, 'system-test'); } @@ -183,7 +183,7 @@ describe('Run system tests for some libraries', () => { }); await fs.promises.rename( path.join(gaxDir, '..', 'tools', toolsBasename), - toolsTarball + toolsTarball, ); if (!fs.existsSync(toolsTarball)) { throw new Error(`npm pack tarball ${toolsTarball} does not exist`); diff --git a/gax/test/unit/apiCallable.ts b/gax/test/unit/apiCallable.ts index 4a17d590b..1da92da4c 100644 --- a/gax/test/unit/apiCallable.ts +++ b/gax/test/unit/apiCallable.ts @@ -40,7 +40,7 @@ describe('createApiCall', () => { argument: {}, metadata: {}, options: {deadline: string}, - callback: Function + callback: Function, ) { deadlineArg = options.deadline; callback(null, argument); @@ -58,7 +58,7 @@ describe('createApiCall', () => { argument: {}, metadata: {}, options: {deadline: {getTime: Function}}, - callback: Function + callback: Function, ) { callback(null, options.deadline.getTime()); } @@ -78,7 +78,7 @@ describe('createApiCall', () => { argument: {}, metadata: {}, options: {deadline: {getTime: Function}}, - callback: Function + callback: Function, ) { callback(null, options.deadline.getTime()); } @@ -91,7 +91,7 @@ describe('createApiCall', () => { timeout: 30000, retry: gax.createRetryOptions( [], - gax.createBackoffSettings(100, 1.2, 1000, 2000, 1.5, 30000, 45000) + gax.createBackoffSettings(100, 1.2, 1000, 2000, 1.5, 30000, 45000), ), }, }); @@ -112,7 +112,7 @@ describe('createApiCall', () => { argument: {}, metadata: {}, options: {deadline: {getTime: Function}}, - callback: Function + callback: Function, ) { callback(null, options.deadline.getTime()); } @@ -176,7 +176,7 @@ describe('createApiCall', () => { retry: { retryCodes: overrideRetryCodes, }, - } + }, ); }); it('errors when you override custom retry.shouldRetryFn with a function on a non streaming call', async () => { @@ -209,13 +209,13 @@ describe('createApiCall', () => { retry: { shouldRetryFn: overrideRetryCodes, }, - } + }, ); } catch (err) { assert(err instanceof Error); assert.strictEqual( err.message, - 'Using a function to determine retry eligibility is only supported with server streaming calls' + 'Using a function to determine retry eligibility is only supported with server streaming calls', ); } }); @@ -229,7 +229,7 @@ describe('createApiCall', () => { null, 1.5, 3000, - 4500 + 4500, ); // eslint-disable-next-line @typescript-eslint/no-explicit-any sinon.stub(retries, 'retryable').callsFake((func, retry): any => { @@ -253,7 +253,7 @@ describe('createApiCall', () => { retry: { backoffSettings: overriBackoffSettings, }, - } + }, ); }); @@ -266,7 +266,7 @@ describe('createApiCall', () => { null, 1.5, 3000, - 4500 + 4500, ); // "resumption" strategy is to just return the original request const getResumptionRequestFn = (originalRequest: RequestType) => { @@ -282,7 +282,7 @@ describe('createApiCall', () => { [1], initialBackoffSettings, undefined, - getResumptionRequestFn + getResumptionRequestFn, ), }, }); @@ -294,13 +294,13 @@ describe('createApiCall', () => { retry: { backoffSettings: overriBackoffSettings, }, - } + }, ); } catch (err) { assert(err instanceof Error); assert.strictEqual( err.message, - 'Resumption strategy can only be used with server streaming retries' + 'Resumption strategy can only be used with server streaming retries', ); } }); @@ -313,7 +313,7 @@ describe('Promise', () => { argument: {}, metadata: {}, options: {deadline: string}, - callback: Function + callback: Function, ) { deadlineArg = options.deadline; callback(null, 42); @@ -418,7 +418,7 @@ describe('Promise', () => { assert.strictEqual(response, 42); done(); }), - undefined + undefined, ); }); }); @@ -436,7 +436,7 @@ describe('retryable', () => { argument: {}, metadata: {}, options: {deadline: string}, - callback: Function + callback: Function, ) { deadlineArg = options.deadline; toAttempt--; @@ -462,7 +462,7 @@ describe('retryable', () => { argument: {}, metadata: {}, options: {deadline: string}, - callback: Function + callback: Function, ) { deadlineArg = options.deadline; toAttempt--; @@ -515,7 +515,7 @@ describe('retryable', () => { it("doesn't retry if no codes", done => { const retryOptions = gax.createRetryOptions( [], - gax.createBackoffSettings(1, 2, 3, 4, 5, 6, 7) + gax.createBackoffSettings(1, 2, 3, 4, 5, 6, 7), ); const settings = {settings: {timeout: 0, retry: retryOptions}}; const spy = sinon.spy(fail); @@ -560,7 +560,7 @@ describe('retryable', () => { 0, 0, 0, - toAttempt + toAttempt, ); const maxRetriesRetryOptions = utils.createRetryOptions(backoff); @@ -575,7 +575,7 @@ describe('retryable', () => { assert.strictEqual(spy.callCount, toAttempt); assert.match( err.message, - /Exceeded maximum number of retries retrying error Error before any response was received/ + /Exceeded maximum number of retries retrying error Error before any response was received/, ); done(); }); @@ -588,7 +588,7 @@ describe('retryable', () => { assert.ok(err instanceof GoogleError); assert.match( err.message, - /Total timeout of API TestApi exceeded 100 milliseconds retrying error Error {2}before any response was received/ + /Total timeout of API TestApi exceeded 100 milliseconds retrying error Error {2}before any response was received/, ); assert.strictEqual(err!.code, status.DEADLINE_EXCEEDED); done(); @@ -606,7 +606,7 @@ describe('retryable', () => { 0, 0, 0, - maxRetries + maxRetries, ); const maxRetriesRetryOptions = utils.createRetryOptions(backoff); maxRetriesRetryOptions.backoffSettings.totalTimeoutMillis = 100; @@ -668,7 +668,7 @@ describe('retryable', () => { assert(err!.note); const now = new Date(); assert( - now.getTime() - startTime.getTime() >= backoff.totalTimeoutMillis! + now.getTime() - startTime.getTime() >= backoff.totalTimeoutMillis!, ); const callsLowerBound = backoff.totalTimeoutMillis! / @@ -706,7 +706,7 @@ describe('retryable', () => { 0, 0, 0, - 5 + 5, ); mockBuilder.withExactArgs({retry: '1'}); return apiCall({}, {retry: utils.createRetryOptions(backoff)}); diff --git a/gax/test/unit/bundling.ts b/gax/test/unit/bundling.ts index d757d311b..27bd077e4 100644 --- a/gax/test/unit/bundling.ts +++ b/gax/test/unit/bundling.ts @@ -107,7 +107,7 @@ describe('computeBundleId', () => { it(t.message, () => { assert.strictEqual( computeBundleId(t.object as unknown as RequestType, t.fields), - t.want + t.want, ); }); }); @@ -215,7 +215,7 @@ describe('Task', () => { task: any, elements: string[] | number[], // eslint-disable-next-line @typescript-eslint/no-explicit-any - callback?: any + callback?: any, ) { if (!callback) { callback = () => {}; @@ -256,7 +256,7 @@ describe('Task', () => { assert.strictEqual( task.getElementCount(), baseCount! + t.want, - t.message + t.message, ); }); }); @@ -271,7 +271,7 @@ describe('Task', () => { extendElements(task, t.data); assert.strictEqual( task.getRequestByteSize(), - baseSize! + t.want * sizePerData + baseSize! + t.want * sizePerData, ); }); }); @@ -511,7 +511,7 @@ describe('Executor', () => { 'field1', ['field2'], 'field1', - byteLength + byteLength, ); return new BundleExecutor(options, descriptor); } @@ -636,9 +636,9 @@ describe('Executor', () => { assert.deepStrictEqual(resp.field1, [3, 4]); assert.strictEqual(spyApi.callCount, 1); done(); - } + }, ); - } + }, ); assert.strictEqual(spyApi.callCount, 0); canceller.cancel(); @@ -750,7 +750,7 @@ describe('Executor', () => { assert(err instanceof GoogleError); assert.strictEqual(err!.code, status.INVALID_ARGUMENT); done(); - } + }, ); }); @@ -787,7 +787,7 @@ describe('Executor', () => { assert(err instanceof GoogleError); assert.strictEqual(err!.code, status.INVALID_ARGUMENT); done(); - } + }, ); }); @@ -862,7 +862,7 @@ describe('bundleable', () => { 'field1', ['field2'], 'field1', - byteLength + byteLength, ); const settings = { settings: {bundleOptions}, @@ -983,7 +983,7 @@ describe('bundleable', () => { 'data', ['log_name'], 'data', - byteLength + byteLength, ); const settings = { settings: {bundleOptions}, diff --git a/gax/test/unit/fallbackError.ts b/gax/test/unit/fallbackError.ts index de8ba72b1..c79b5c528 100644 --- a/gax/test/unit/fallbackError.ts +++ b/gax/test/unit/fallbackError.ts @@ -46,7 +46,7 @@ describe('gRPC-fallback error decoding', () => { assert.strictEqual(decodedError.message, expectedError.message); assert.strictEqual( JSON.stringify(decodedError.statusDetails), - JSON.stringify(expectedError.details) + JSON.stringify(expectedError.details), ); }); @@ -56,7 +56,7 @@ describe('gRPC-fallback error decoding', () => { const errorBin = fs.readFileSync(fixtureName); const expectedError = Object.assign( new Error( - '3 INVALID_ARGUMENT: One of content, or gcs_content_uri must be set.' + '3 INVALID_ARGUMENT: One of content, or gcs_content_uri must be set.', ), { code: 3, @@ -70,7 +70,7 @@ describe('gRPC-fallback error decoding', () => { ], }, ], - } + }, ); const decoder = new GoogleErrorDecoder(); const decodedError = decoder.decodeErrorFromBuffer(errorBin); @@ -80,7 +80,7 @@ describe('gRPC-fallback error decoding', () => { assert.strictEqual(decodedError.message, expectedError.message); assert.strictEqual( JSON.stringify(decodedError.statusDetails), - JSON.stringify(expectedError.details) + JSON.stringify(expectedError.details), ); }); @@ -91,7 +91,7 @@ describe('gRPC-fallback error decoding', () => { '..', 'protos', 'google', - 'rpc' + 'rpc', ); const root = protobuf.loadSync([ path.join(protos_path, 'error_details.proto'), @@ -115,7 +115,7 @@ describe('gRPC-fallback error decoding', () => { reason: errorInfo.reason, domain: errorInfo.domain, errorInfoMetadata: errorInfo.metadata, - } + }, ); const status = Object.assign(new Error('mock error.'), { code: 7, @@ -134,7 +134,7 @@ describe('gRPC-fallback error decoding', () => { assert.strictEqual(decodedError.message, expectedError.message); assert.strictEqual( JSON.stringify(decodedError.statusDetails), - JSON.stringify(expectedError.details) + JSON.stringify(expectedError.details), ); }); }); diff --git a/gax/test/unit/gax.ts b/gax/test/unit/gax.ts index 846dd51a0..1dee1c5ea 100644 --- a/gax/test/unit/gax.ts +++ b/gax/test/unit/gax.ts @@ -76,7 +76,7 @@ function expectRetryOptions(obj: gax.RetryOptions) { assert.ok(obj instanceof Object); ['retryCodes', 'backoffSettings'].forEach(k => // eslint-disable-next-line no-prototype-builtins - assert.ok(obj.hasOwnProperty(k)) + assert.ok(obj.hasOwnProperty(k)), ); assert.ok(Array.isArray(obj.retryCodes)); expectBackoffSettings(obj.backoffSettings); @@ -106,7 +106,7 @@ describe('gax construct settings', () => { A_CONFIG, {}, RETRY_DICT, - otherArgs + otherArgs, ); let settings = defaults.bundlingMethod; assert.strictEqual(settings.timeout, 40000); @@ -137,7 +137,7 @@ describe('gax construct settings', () => { SERVICE_NAME, A_CONFIG, overrides, - RETRY_DICT + RETRY_DICT, ); let settings = defaults.bundlingMethod; assert.strictEqual(settings.timeout, 40000); @@ -179,7 +179,7 @@ describe('gax construct settings', () => { SERVICE_NAME, A_CONFIG, overrides, - RETRY_DICT + RETRY_DICT, ); let settings = defaults.bundlingMethod; diff --git a/gax/test/unit/googleError.ts b/gax/test/unit/googleError.ts index a4bc7bd1d..6166177a4 100644 --- a/gax/test/unit/googleError.ts +++ b/gax/test/unit/googleError.ts @@ -34,7 +34,7 @@ describe('gRPC-google error decoding', () => { __dirname, '..', 'fixtures', - 'multipleErrors.json' + 'multipleErrors.json', ); const protos_path = path.resolve( __dirname, @@ -42,7 +42,7 @@ describe('gRPC-google error decoding', () => { '..', 'protos', 'google', - 'rpc' + 'rpc', ); const root = protobuf.loadSync([ path.join(protos_path, 'error_details.proto'), @@ -72,17 +72,17 @@ describe('gRPC-google error decoding', () => { const Status = root.lookupType('google.rpc.Status'); const statusBuffer = Status.encode(status).finish() as Buffer; const gRPCStatusDetailsObj = decoder.decodeGRPCStatusDetails( - new Array(statusBuffer) + new Array(statusBuffer), ); assert.strictEqual( JSON.stringify(expectedErrorArr), - JSON.stringify(gRPCStatusDetailsObj.details) + JSON.stringify(gRPCStatusDetailsObj.details), ); assert.deepStrictEqual( JSON.stringify(gRPCStatusDetailsObj.errorInfo), JSON.stringify( - objs.find(item => item.type === 'google.rpc.ErrorInfo')?.value - ) + objs.find(item => item.type === 'google.rpc.ErrorInfo')?.value, + ), ); }); @@ -96,7 +96,7 @@ describe('gRPC-google error decoding', () => { // nested error messages have different types so we can't use deepStrictEqual here assert.strictEqual( JSON.stringify(gRPCStatusDetailsObj.details), - JSON.stringify([]) + JSON.stringify([]), ); assert.strictEqual(gRPCStatusDetailsObj.errorInfo, undefined); }); @@ -112,7 +112,7 @@ describe('gRPC-google error decoding', () => { assert.strictEqual( JSON.stringify(decodedError), - '{"code":3,"message":"test","statusDetails":[]}' + '{"code":3,"message":"test","statusDetails":[]}', ); }); @@ -129,7 +129,7 @@ describe('gRPC-google error decoding', () => { assert.strictEqual( JSON.stringify(gRPCStatusDetailsObj.details), - JSON.stringify([]) + JSON.stringify([]), ); }); @@ -146,7 +146,7 @@ describe('gRPC-google error decoding', () => { 0, err .toString() - .indexOf('Error: Unknown type encoded in google.protobuf.any:') + .indexOf('Error: Unknown type encoded in google.protobuf.any:'), ); } }); @@ -197,7 +197,7 @@ describe('parse grpc status details with ErrorInfo from grpc metadata', () => { { code: 7, metadata: metadata, - } + }, ); const decodedError = GoogleError.parseGRPCStatusDetails(grpcError); assert(decodedError instanceof GoogleError); @@ -205,7 +205,7 @@ describe('parse grpc status details with ErrorInfo from grpc metadata', () => { assert.strictEqual(decodedError.reason, errorInfoObj.reason); assert.strictEqual( JSON.stringify(decodedError.errorInfoMetadata), - JSON.stringify(errorInfoObj.metadata) + JSON.stringify(errorInfoObj.metadata), ); }); @@ -233,19 +233,19 @@ describe('parse grpc status details with ErrorInfo from grpc metadata', () => { { code: 7, metadata: metadata, - } + }, ); const decodedError = GoogleError.parseGRPCStatusDetails(grpcError); assert(decodedError instanceof GoogleError); assert.strictEqual( JSON.stringify(decodedError.statusDetails), - JSON.stringify([errorInfoObj]) + JSON.stringify([errorInfoObj]), ); assert.strictEqual(decodedError.domain, errorInfoObj.domain); assert.strictEqual(decodedError.reason, errorInfoObj.reason); assert.strictEqual( JSON.stringify(decodedError.errorInfoMetadata), - JSON.stringify(errorInfoObj.metadata) + JSON.stringify(errorInfoObj.metadata), ); }); @@ -257,7 +257,7 @@ describe('parse grpc status details with ErrorInfo from grpc metadata', () => { { code: 7, metadata: metadata, - } + }, ); const decodedError = GoogleError.parseGRPCStatusDetails(grpcError); assert(decodedError instanceof GoogleError); @@ -269,7 +269,7 @@ describe('parse grpc status details with ErrorInfo from grpc metadata', () => { new GoogleError('mock error without metadata'), { code: 7, - } + }, ); const decodedError = GoogleError.parseGRPCStatusDetails(grpcError); assert(decodedError instanceof GoogleError); @@ -319,7 +319,7 @@ describe('map http status code to gRPC status code', () => { }, }; const errorAlreadyExists = GoogleError.parseHttpError( - errorJsonAlreadyExistss + errorJsonAlreadyExistss, ); assert.deepStrictEqual(errorAborted.code, Status.ABORTED); assert.deepStrictEqual(errorAlreadyExists.code, Status.ALREADY_EXISTS); @@ -359,14 +359,14 @@ describe('http error decoding', () => { assert.deepStrictEqual(error.code, rpcCodeFromHttpStatusCode(403)); assert.deepStrictEqual( error.statusDetails?.length, - json['error']['details'].length + json['error']['details'].length, ); assert.deepStrictEqual(error.message, json['error']['message']); assert.deepStrictEqual(error.reason, errorInfo.reason); assert.deepStrictEqual(error.domain, errorInfo.domain); assert.deepStrictEqual( JSON.stringify(error.errorInfoMetadata), - JSON.stringify(errorInfo.metadata) + JSON.stringify(errorInfo.metadata), ); }); @@ -375,14 +375,14 @@ describe('http error decoding', () => { assert.deepStrictEqual(error.code, rpcCodeFromHttpStatusCode(403)); assert.deepStrictEqual( error.statusDetails?.length, - json['error']['details'].length + json['error']['details'].length, ); assert.deepStrictEqual(error.message, json['error']['message']); assert.deepStrictEqual(error.reason, errorInfo.reason); assert.deepStrictEqual(error.domain, errorInfo.domain); assert.deepStrictEqual( JSON.stringify(error.errorInfoMetadata), - JSON.stringify(errorInfo.metadata) + JSON.stringify(errorInfo.metadata), ); }); }); diff --git a/gax/test/unit/grpc-fallback.ts b/gax/test/unit/grpc-fallback.ts index 0c3c94952..227e50001 100644 --- a/gax/test/unit/grpc-fallback.ts +++ b/gax/test/unit/grpc-fallback.ts @@ -140,7 +140,7 @@ describe('createStub', () => { const opts = {...stubOptions, universeDomain: 'example.com'}; assert.rejects( gaxGrpc.createStub(echoService, opts), - /configured universe domain/ + /configured universe domain/, ); }); @@ -148,7 +148,7 @@ describe('createStub', () => { authClient.universeDomain = 'example.com'; assert.rejects( gaxGrpc.createStub(echoService, stubOptions), - /configured universe domain/ + /configured universe domain/, ); // reset to default value authClient.universeDomain = 'googleapis.com'; @@ -268,7 +268,7 @@ describe('grpc-fallback', () => { 'google.showcase.v1beta1.Echo', gapicConfig, {}, - {} + {}, ); const metadataBuilder = settings.echo.otherArgs.metadataBuilder; const headers = metadataBuilder(); @@ -286,7 +286,7 @@ describe('grpc-fallback', () => { arrayBuffer: () => { return Promise.resolve(Buffer.from(JSON.stringify(response))); }, - }) + }), ); gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { @@ -294,7 +294,7 @@ describe('grpc-fallback', () => { assert.strictEqual(err, null); assert.strictEqual( requestObject.content, - (result as {content: string}).content + (result as {content: string}).content, ); done(); }); @@ -341,7 +341,7 @@ describe('grpc-fallback', () => { arrayBuffer: () => { return Promise.resolve(Buffer.from(JSON.stringify(jsonError))); }, - }) + }), ); gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { echoStub.echo(requestObject, {}, {}, (err?: Error) => { @@ -350,7 +350,7 @@ describe('grpc-fallback', () => { assert.strictEqual(err.code, expectedError.code); assert.strictEqual( JSON.stringify(err.statusDetails), - JSON.stringify(expectedError.details) + JSON.stringify(expectedError.details), ); done(); }); @@ -367,7 +367,7 @@ describe('grpc-fallback', () => { arrayBuffer: () => { return Promise.resolve(Buffer.from('')); }, - }) + }), ); gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { echoStub.echo(requestObject, {}, {}, (err?: Error) => { @@ -435,14 +435,14 @@ describe('grpc-fallback', () => { arrayBuffer: () => { return Promise.resolve(Buffer.from(JSON.stringify(serverError))); }, - }) + }), ); gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { echoStub.echo(requestObject, {}, {}, (err?: Error) => { assert(err instanceof GoogleError); assert.strictEqual( JSON.stringify(err.statusDetails?.length), - JSON.stringify(serverError['error']['details'].length) + JSON.stringify(serverError['error']['details'].length), ); assert.strictEqual(err.code, 7); assert.strictEqual(err.message, serverError['error']['message']); @@ -450,7 +450,7 @@ describe('grpc-fallback', () => { assert.strictEqual(err.domain, errorInfo.domain); assert.strictEqual( JSON.stringify(err.errorInfoMetadata), - JSON.stringify(errorInfo.metadata) + JSON.stringify(errorInfo.metadata), ); done(); }); diff --git a/gax/test/unit/grpc.ts b/gax/test/unit/grpc.ts index 084daeb75..cc03e4c86 100644 --- a/gax/test/unit/grpc.ts +++ b/gax/test/unit/grpc.ts @@ -123,7 +123,7 @@ describe('grpc', () => { constructor( public address: {}, public creds: {}, - public options: {[index: string]: string | number | Function} + public options: {[index: string]: string | number | Function}, ) {} } @@ -187,7 +187,7 @@ describe('grpc', () => { assert.rejects( // @ts-ignore grpcClient.createStub(DummyStub, opts), - /configured universe domain/ + /configured universe domain/, ); }); @@ -198,7 +198,7 @@ describe('grpc', () => { assert.rejects( // @ts-ignore grpcClient.createStub(DummyStub, opts), - /configured universe domain/ + /configured universe domain/, ); }); @@ -236,15 +236,15 @@ describe('grpc', () => { const dummyStub = stub as unknown as DummyStub; assert.strictEqual( dummyStub.options['grpc.max_send_message_length'], - 10 * 1024 * 1024 + 10 * 1024 * 1024, ); assert.strictEqual( (dummyStub.options['callInvocationTransformer'] as Function)(), - 42 + 42, ); assert.strictEqual( dummyStub.options['grpc-node.max_session_memory'], - 10 + 10, ); ['servicePath', 'port', 'other_dummy_options'].forEach(k => { assert.strictEqual(stub.options.hasOwnProperty(k), false); @@ -290,7 +290,7 @@ describe('grpc', () => { const dummyStub = stub as unknown as DummyStub; assert.strictEqual( dummyStub.options['grpc.max_receive_message_length'], - 10 * 1024 * 1024 + 10 * 1024 * 1024, ); }); }); @@ -323,14 +323,14 @@ describe('grpc', () => { 'example', 'library', 'v1', - 'library.proto' + 'library.proto', ); const TEST_FILE_NO_DEPS = path.join( 'google', 'example', 'library', 'v1', - 'test.proto' + 'test.proto', ); const TEST_PATH = path.resolve(__dirname, '..', '..', 'test', 'fixtures'); const TEST_JSON = path.resolve( @@ -339,7 +339,7 @@ describe('grpc', () => { '..', 'test', 'fixtures', - 'library.json' + 'library.json', ); it('should load the test file', () => { @@ -349,7 +349,7 @@ describe('grpc', () => { const protos = grpcClient.loadProto(TEST_PATH, TEST_FILE) as any; assert.strictEqual( typeof protos.google.example.library.v1.LibraryService, - 'function' + 'function', ); }); @@ -360,7 +360,7 @@ describe('grpc', () => { const protos = grpcClient.loadProtoJSON(require(TEST_JSON)) as any; assert.strictEqual( typeof protos.google.example.library.v1.LibraryService, - 'function' + 'function', ); }); @@ -368,7 +368,7 @@ describe('grpc', () => { // no-any disabled because if the accessed fields are non-existent, this // test will fail anyway. const protos = grpcClient.loadProto( - path.join(TEST_PATH, TEST_FILE_NO_DEPS) + path.join(TEST_PATH, TEST_FILE_NO_DEPS), // eslint-disable-next-line @typescript-eslint/no-explicit-any ) as any; assert(protos.test.TestMessage); @@ -400,7 +400,7 @@ describe('grpc', () => { ]) as any; assert.strictEqual( typeof protos.google.example.library.v1.LibraryService, - 'function' + 'function', ); assert.strictEqual(typeof protos.google.iam.v1.IAMPolicy, 'function'); }); @@ -409,7 +409,7 @@ describe('grpc', () => { const nonExistentDir = path.join(__dirname, 'nonexistent', 'dir'); const nonExistentFile = 'nonexistent.proto'; assert.throws( - grpcClient.loadProto.bind(null, nonExistentDir, nonExistentFile) + grpcClient.loadProto.bind(null, nonExistentDir, nonExistentFile), ); }); @@ -436,12 +436,12 @@ describe('grpc', () => { const proto1 = grpcClient.loadProto( TEST_PATH, TEST_FILE, - /*ignoreCache:*/ true + /*ignoreCache:*/ true, ); const proto2 = grpcClient.loadProto( TEST_PATH, TEST_FILE, - /*ignoreCache:*/ true + /*ignoreCache:*/ true, ); assert.notStrictEqual(proto1, proto2); }); @@ -449,11 +449,11 @@ describe('grpc', () => { it('should ignore cache if asked for JSON protos', () => { const proto1 = grpcClient.loadProtoJSON( require(TEST_JSON), - /*ignoreCache:*/ true + /*ignoreCache:*/ true, ); const proto2 = grpcClient.loadProtoJSON( require(TEST_JSON), - /*ignoreCache:*/ true + /*ignoreCache:*/ true, ); assert.notStrictEqual(proto1, proto2); }); @@ -473,18 +473,18 @@ describe('grpc', () => { 'google', 'example', 'library', - 'v1' + 'v1', ); const TEST_FILE = path.join(FIXTURES_DIR, 'library.proto'); const NON_EXISTENT_FILE = path.join( __dirname, 'does', 'not', - 'exist.proto' + 'exist.proto', ); const MISSING_INCLUDE_FILE = path.join( FIXTURES_DIR, - 'missing_include.proto' + 'missing_include.proto', ); describe('use with protobufjs load', () => { @@ -495,7 +495,7 @@ describe('grpc', () => { }, () => { done(); - } + }, ); }); @@ -506,7 +506,7 @@ describe('grpc', () => { assert(root instanceof protobuf.Root); assert( root.lookup('google.example.library.v1.LibraryService') instanceof - protobuf.Service + protobuf.Service, ); assert(root.lookup('test.TestMessage') instanceof protobuf.Type); done(); @@ -549,7 +549,7 @@ describe('grpc', () => { assert(root instanceof protobuf.Root); assert( root.lookup('google.example.library.v1.LibraryService') instanceof - protobuf.Service + protobuf.Service, ); assert(root.lookup('test.TestMessage') instanceof protobuf.Type); }); @@ -559,8 +559,8 @@ describe('grpc', () => { protobuf.loadSync.bind( null, NON_EXISTENT_FILE, - new GoogleProtoFilesRoot() - ) + new GoogleProtoFilesRoot(), + ), ); }); @@ -569,8 +569,8 @@ describe('grpc', () => { protobuf.loadSync.bind( null, MISSING_INCLUDE_FILE, - new GoogleProtoFilesRoot() - ) + new GoogleProtoFilesRoot(), + ), ); }); }); @@ -601,7 +601,7 @@ describe('grpc', () => { }).GoogleProtoFilesRoot._findIncludePath; assert.strictEqual( findIncludePath(originPath, includePath), - correctPath + correctPath, ); }); }); @@ -630,7 +630,7 @@ describe('grpc', () => { const servicePath = client._mtlsServicePath( 'https://foo.googleapis.com', false, - true + true, ); assert.strictEqual(servicePath, expected); }); @@ -641,7 +641,7 @@ describe('grpc', () => { const servicePath = client._mtlsServicePath( 'https://foo.googleapis.com', false, - false + false, ); assert.strictEqual(servicePath, expected); }); @@ -700,7 +700,7 @@ dvorak assert.rejects( // @ts-ignore client.createStub(DummyStub, {universeDomain: 'example.com'}), - /configured universe domain/ + /configured universe domain/, ); await fsp.rm(tmpFolder, {recursive: true, force: true}); // Cleanup. }); diff --git a/gax/test/unit/iamService.ts b/gax/test/unit/iamService.ts index bfeec0abc..110a209ac 100644 --- a/gax/test/unit/iamService.ts +++ b/gax/test/unit/iamService.ts @@ -29,7 +29,7 @@ function generateSampleMessage(instance: T) { instance.constructor as typeof protobuf.Message ).toObject(instance as protobuf.Message, {defaults: true}); return (instance.constructor as typeof protobuf.Message).fromObject( - filledObject + filledObject, ) as T; } @@ -41,7 +41,7 @@ function stubSimpleCall(response?: ResponseType, error?: Error) { function stubSimpleCallWithCallback( response?: ResponseType, - error?: Error + error?: Error, ) { return error ? sinon.stub().callsArgWith(2, error) @@ -58,7 +58,7 @@ describe('IAM service', () => { }); client.initialize(); const request = generateSampleMessage( - new protos.google.iam.v1.GetIamPolicyRequest() + new protos.google.iam.v1.GetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -70,7 +70,7 @@ describe('IAM service', () => { }, }; const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.Policy() + new protos.google.iam.v1.Policy(), ); client.innerApiCalls.getIamPolicy = stubSimpleCall(expectedResponse); const response = await client.getIamPolicy(request, expectedOptions); @@ -78,7 +78,7 @@ describe('IAM service', () => { assert( (client.innerApiCalls.getIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); it('invokes getIamPolicy without error using callback', async () => { @@ -89,7 +89,7 @@ describe('IAM service', () => { }); client.initialize(); const request = generateSampleMessage( - new protos.google.iam.v1.GetIamPolicyRequest() + new protos.google.iam.v1.GetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -101,7 +101,7 @@ describe('IAM service', () => { }, }; const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.Policy() + new protos.google.iam.v1.Policy(), ); client.innerApiCalls.getIamPolicy = stubSimpleCallWithCallback(expectedResponse); @@ -115,7 +115,7 @@ describe('IAM service', () => { } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -123,7 +123,7 @@ describe('IAM service', () => { assert( (client.innerApiCalls.getIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions /* callback function above */) + .calledWith(request, expectedOptions /* callback function above */), ); }); it('invokes getIamPolicy with error', async () => { @@ -134,7 +134,7 @@ describe('IAM service', () => { }); client.initialize(); const request = generateSampleMessage( - new protos.google.iam.v1.GetIamPolicyRequest() + new protos.google.iam.v1.GetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -148,7 +148,7 @@ describe('IAM service', () => { const expectedError = new Error('expected'); client.innerApiCalls.getIamPolicy = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(async () => { await client.getIamPolicy(request, expectedOptions); @@ -156,7 +156,7 @@ describe('IAM service', () => { assert( (client.innerApiCalls.getIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); }); @@ -169,7 +169,7 @@ describe('IAM service', () => { }); client.initialize(); const request = generateSampleMessage( - new protos.google.iam.v1.SetIamPolicyRequest() + new protos.google.iam.v1.SetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -181,7 +181,7 @@ describe('IAM service', () => { }, }; const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.Policy() + new protos.google.iam.v1.Policy(), ); client.innerApiCalls.setIamPolicy = stubSimpleCall(expectedResponse); const response = await client.setIamPolicy(request, expectedOptions); @@ -189,7 +189,7 @@ describe('IAM service', () => { assert( (client.innerApiCalls.setIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); it('invokes setIamPolicy without error using callback', async () => { @@ -200,7 +200,7 @@ describe('IAM service', () => { }); client.initialize(); const request = generateSampleMessage( - new protos.google.iam.v1.SetIamPolicyRequest() + new protos.google.iam.v1.SetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -212,7 +212,7 @@ describe('IAM service', () => { }, }; const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.Policy() + new protos.google.iam.v1.Policy(), ); client.innerApiCalls.setIamPolicy = stubSimpleCallWithCallback(expectedResponse); @@ -226,7 +226,7 @@ describe('IAM service', () => { } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -234,7 +234,7 @@ describe('IAM service', () => { assert( (client.innerApiCalls.setIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions /* callback function above */) + .calledWith(request, expectedOptions /* callback function above */), ); }); it('invokes setIamPolicy with error', async () => { @@ -245,7 +245,7 @@ describe('IAM service', () => { }); client.initialize(); const request = generateSampleMessage( - new protos.google.iam.v1.SetIamPolicyRequest() + new protos.google.iam.v1.SetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -259,7 +259,7 @@ describe('IAM service', () => { const expectedError = new Error('expected'); client.innerApiCalls.setIamPolicy = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(async () => { await client.setIamPolicy(request, expectedOptions); @@ -267,7 +267,7 @@ describe('IAM service', () => { assert( (client.innerApiCalls.setIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); }); @@ -280,7 +280,7 @@ describe('IAM service', () => { }); client.initialize(); const request = generateSampleMessage( - new protos.google.iam.v1.TestIamPermissionsRequest() + new protos.google.iam.v1.TestIamPermissionsRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -292,19 +292,19 @@ describe('IAM service', () => { }, }; const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.TestIamPermissionsResponse() + new protos.google.iam.v1.TestIamPermissionsResponse(), ); client.innerApiCalls.testIamPermissions = stubSimpleCall(expectedResponse); const response = await client.testIamPermissions( request, - expectedOptions + expectedOptions, ); assert.deepStrictEqual(response, [expectedResponse]); assert( (client.innerApiCalls.testIamPermissions as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); it('invokes testIamPermissions without error using callback', async () => { @@ -315,7 +315,7 @@ describe('IAM service', () => { }); client.initialize(); const request = generateSampleMessage( - new protos.google.iam.v1.TestIamPermissionsRequest() + new protos.google.iam.v1.TestIamPermissionsRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -327,7 +327,7 @@ describe('IAM service', () => { }, }; const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.TestIamPermissionsResponse() + new protos.google.iam.v1.TestIamPermissionsResponse(), ); client.innerApiCalls.testIamPermissions = stubSimpleCallWithCallback(expectedResponse); @@ -337,14 +337,14 @@ describe('IAM service', () => { expectedOptions, ( err?: Error | null, - result?: protos.google.iam.v1.TestIamPermissionsResponse | null + result?: protos.google.iam.v1.TestIamPermissionsResponse | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -352,7 +352,7 @@ describe('IAM service', () => { assert( (client.innerApiCalls.testIamPermissions as SinonStub) .getCall(0) - .calledWith(request, expectedOptions /* callback function above */) + .calledWith(request, expectedOptions /* callback function above */), ); }); it('invokes testIamPermissions with error', async () => { @@ -363,7 +363,7 @@ describe('IAM service', () => { }); client.initialize(); const request = generateSampleMessage( - new protos.google.iam.v1.TestIamPermissionsRequest() + new protos.google.iam.v1.TestIamPermissionsRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -377,7 +377,7 @@ describe('IAM service', () => { const expectedError = new Error('expected'); client.innerApiCalls.testIamPermissions = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(async () => { await client.testIamPermissions(request, expectedOptions); @@ -385,7 +385,7 @@ describe('IAM service', () => { assert( (client.innerApiCalls.testIamPermissions as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); }); diff --git a/gax/test/unit/locationService.ts b/gax/test/unit/locationService.ts index 8d957cb41..9afab554f 100644 --- a/gax/test/unit/locationService.ts +++ b/gax/test/unit/locationService.ts @@ -27,7 +27,7 @@ function generateSampleMessage(instance: T) { instance.constructor as typeof protobuf.Message ).toObject(instance as protobuf.Message, {defaults: true}); return (instance.constructor as typeof protobuf.Message).fromObject( - filledObject + filledObject, ) as T; } @@ -39,7 +39,7 @@ function stubSimpleCall(response?: ResponseType, error?: Error) { function stubSimpleCallWithCallback( response?: ResponseType, - error?: Error + error?: Error, ) { return error ? sinon.stub().callsArgWith(2, error) @@ -48,7 +48,7 @@ function stubSimpleCallWithCallback( function stubAsyncIterationCall( responses?: ResponseType[], - error?: Error + error?: Error, ) { let counter = 0; const asyncIterable = { @@ -79,7 +79,7 @@ describe('LocationsClient', () => { }); client.initialize(); const request = generateSampleMessage( - new protos.google.cloud.location.GetLocationRequest() + new protos.google.cloud.location.GetLocationRequest(), ); request.name = ''; const expectedHeaderRequestParams = 'name='; @@ -91,7 +91,7 @@ describe('LocationsClient', () => { }, }; const expectedResponse = generateSampleMessage( - new protos.google.cloud.location.Location() + new protos.google.cloud.location.Location(), ); client.innerApiCalls.getLocation = stubSimpleCall(expectedResponse); const response = await client.getLocation(request, expectedOptions); @@ -99,7 +99,7 @@ describe('LocationsClient', () => { assert( (client.innerApiCalls.getLocation as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); @@ -111,7 +111,7 @@ describe('LocationsClient', () => { }); client.initialize(); const request = generateSampleMessage( - new protos.google.cloud.location.GetLocationRequest() + new protos.google.cloud.location.GetLocationRequest(), ); request.name = ''; const expectedHeaderRequestParams = 'name='; @@ -123,7 +123,7 @@ describe('LocationsClient', () => { }, }; const expectedResponse = generateSampleMessage( - new protos.google.cloud.location.Location() + new protos.google.cloud.location.Location(), ); client.innerApiCalls.getLocation = stubSimpleCallWithCallback(expectedResponse); @@ -132,14 +132,14 @@ describe('LocationsClient', () => { request, ( err?: Error | null, - result?: protos.google.cloud.location.ILocation | null + result?: protos.google.cloud.location.ILocation | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -147,7 +147,7 @@ describe('LocationsClient', () => { assert( (client.innerApiCalls.getLocation as SinonStub) .getCall(0) - .calledWith(request, expectedOptions /*, callback defined above */) + .calledWith(request, expectedOptions /*, callback defined above */), ); }); @@ -158,7 +158,7 @@ describe('LocationsClient', () => { }); client.initialize(); const request = generateSampleMessage( - new protos.google.cloud.location.GetLocationRequest() + new protos.google.cloud.location.GetLocationRequest(), ); request.name = ''; const expectedHeaderRequestParams = 'name='; @@ -172,16 +172,16 @@ describe('LocationsClient', () => { const expectedError = new Error('expected'); client.innerApiCalls.getLocation = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects( client.getLocation(request, expectedOptions), - expectedError + expectedError, ); assert( (client.innerApiCalls.getLocation as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); }); @@ -195,7 +195,7 @@ describe('LocationsClient', () => { }); client.initialize(); const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() + new protos.google.cloud.location.ListLocationsRequest(), ); request.name = ''; const expectedHeaderRequestParams = 'name='; @@ -217,7 +217,7 @@ describe('LocationsClient', () => { assert( (client.innerApiCalls.listLocations as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); @@ -229,7 +229,7 @@ describe('LocationsClient', () => { }); client.initialize(); const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() + new protos.google.cloud.location.ListLocationsRequest(), ); request.name = ''; const expectedHeaderRequestParams = 'name='; @@ -252,14 +252,14 @@ describe('LocationsClient', () => { request, ( err?: Error | null, - result?: protos.google.cloud.location.ILocation[] | null + result?: protos.google.cloud.location.ILocation[] | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -267,7 +267,7 @@ describe('LocationsClient', () => { assert( (client.innerApiCalls.listLocations as SinonStub) .getCall(0) - .calledWith(request, expectedOptions /*, callback defined above */) + .calledWith(request, expectedOptions /*, callback defined above */), ); }); @@ -279,7 +279,7 @@ describe('LocationsClient', () => { }); client.initialize(); const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() + new protos.google.cloud.location.ListLocationsRequest(), ); request.name = ''; const expectedHeaderRequestParams = 'name='; @@ -293,16 +293,16 @@ describe('LocationsClient', () => { const expectedError = new Error('expected'); client.innerApiCalls.listLocations = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects( client.listLocations(request, expectedOptions), - expectedError + expectedError, ); assert( (client.innerApiCalls.listLocations as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); @@ -314,7 +314,7 @@ describe('LocationsClient', () => { }); client.initialize(); const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() + new protos.google.cloud.location.ListLocationsRequest(), ); request.name = ''; const expectedHeaderRequestParams = 'name='; @@ -335,13 +335,13 @@ describe('LocationsClient', () => { ( client.descriptors.page.listLocations.asyncIterate as SinonStub ).getCall(0).args[1], - request + request, ); assert.strictEqual( ( client.descriptors.page.listLocations.asyncIterate as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], - expectedHeaderRequestParams + expectedHeaderRequestParams, ); }); @@ -353,7 +353,7 @@ describe('LocationsClient', () => { }); client.initialize(); const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() + new protos.google.cloud.location.ListLocationsRequest(), ); request.name = ''; const expectedHeaderRequestParams = 'name='; @@ -371,13 +371,13 @@ describe('LocationsClient', () => { ( client.descriptors.page.listLocations.asyncIterate as SinonStub ).getCall(0).args[1], - request + request, ); assert.strictEqual( ( client.descriptors.page.listLocations.asyncIterate as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], - expectedHeaderRequestParams + expectedHeaderRequestParams, ); }); }); diff --git a/gax/test/unit/longrunning.ts b/gax/test/unit/longrunning.ts index 0ec804a3c..2dcf43573 100644 --- a/gax/test/unit/longrunning.ts +++ b/gax/test/unit/longrunning.ts @@ -85,7 +85,7 @@ function createApiCall(func: Function, client?: OperationsClient) { const descriptor = new LongrunningDescriptor( client!, mockDecoder as unknown as AnyDecoder, - mockDecoder as unknown as AnyDecoder + mockDecoder as unknown as AnyDecoder, ); return utils.createApiCall(func, {descriptor}) as GaxCallPromise; } @@ -140,7 +140,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -157,19 +157,19 @@ describe('longrunning', () => { assert(operation.hasOwnProperty('backoffSettings')); assert.strictEqual( operation.backoffSettings.initialRetryDelayMillis, - defaultInitialRetryDelayMillis + defaultInitialRetryDelayMillis, ); assert.strictEqual( operation.backoffSettings.retryDelayMultiplier, - defaultRetryDelayMultiplier + defaultRetryDelayMultiplier, ); assert.strictEqual( operation.backoffSettings.maxRetryDelayMillis, - defaultMaxRetryDelayMillis + defaultMaxRetryDelayMillis, ); assert.strictEqual( operation.backoffSettings.totalTimeoutMillis, - defaultTotalTimeoutMillis + defaultTotalTimeoutMillis, ); assert(operation.hasOwnProperty('longrunningDescriptor')); assert.strictEqual(operation.name, OPERATION_NAME); @@ -190,7 +190,7 @@ describe('longrunning', () => { const desc = new LongrunningDescriptor( client as OperationsClient, mockDecoder as unknown as AnyDecoder, - mockDecoder as unknown as AnyDecoder + mockDecoder as unknown as AnyDecoder, ); const initialRetryDelayMillis = 1; const retryDelayMultiplier = 2; @@ -204,30 +204,30 @@ describe('longrunning', () => { unusedRpcValue, unusedRpcValue, unusedRpcValue, - totalTimeoutMillis + totalTimeoutMillis, ); const operation = longrunning.operation( SUCCESSFUL_OP as {} as operationProtos.google.longrunning.Operation, desc, - backoff + backoff, ); assert(operation instanceof Object); assert(operation.hasOwnProperty('backoffSettings')); assert.strictEqual( operation.backoffSettings.initialRetryDelayMillis, - initialRetryDelayMillis + initialRetryDelayMillis, ); assert.strictEqual( operation.backoffSettings.retryDelayMultiplier, - retryDelayMultiplier + retryDelayMultiplier, ); assert.strictEqual( operation.backoffSettings.maxRetryDelayMillis, - maxRetryDelayMillis + maxRetryDelayMillis, ); assert.strictEqual( operation.backoffSettings.totalTimeoutMillis, - totalTimeoutMillis + totalTimeoutMillis, ); assert(operation.hasOwnProperty('longrunningDescriptor')); assert.strictEqual(operation.name, OPERATION_NAME); @@ -247,7 +247,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, SUCCESSFUL_OP); }; @@ -275,7 +275,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -305,7 +305,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -325,7 +325,7 @@ describe('longrunning', () => { assert.strictEqual(client.getOperation.callCount, 1); done(); }), - undefined + undefined, ); }) .catch(error => { @@ -338,7 +338,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -370,7 +370,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, ERROR_OP); }; @@ -397,7 +397,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -428,7 +428,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, SUCCESSFUL_OP); }; @@ -449,7 +449,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -481,7 +481,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -509,7 +509,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -544,7 +544,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -577,7 +577,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -610,7 +610,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -646,7 +646,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -699,7 +699,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -713,7 +713,7 @@ describe('longrunning', () => { {}, { longrunning: gax.createBackoffSettings(1, 1, 1, 0, 0, 0, 1), - } + }, ) .then(responses => { const operation = responses[0] as longrunning.Operation; @@ -725,7 +725,7 @@ describe('longrunning', () => { assert.strictEqual(err!.code, status.DEADLINE_EXCEEDED); assert.strictEqual( err!.message, - 'Total timeout exceeded before ' + 'any response was received' + 'Total timeout exceeded before ' + 'any response was received', ); done(); }); diff --git a/gax/test/unit/operationClient.ts b/gax/test/unit/operationClient.ts index 0d910b8cb..84a01d9cf 100644 --- a/gax/test/unit/operationClient.ts +++ b/gax/test/unit/operationClient.ts @@ -31,7 +31,7 @@ function generateSampleMessage(instance: T) { instance.constructor as typeof protobuf.Message ).toObject(instance as protobuf.Message, {defaults: true}); return (instance.constructor as typeof protobuf.Message).fromObject( - filledObject + filledObject, ) as T; } @@ -43,7 +43,7 @@ function stubSimpleCall(response?: ResponseType, error?: Error) { function stubSimpleCallWithCallback( response?: ResponseType, - error?: Error + error?: Error, ) { return error ? sinon.stub().callsArgWith(2, error) @@ -51,7 +51,7 @@ function stubSimpleCallWithCallback( } function stubPageStreamingCall( responses?: ResponseType[], - error?: Error + error?: Error, ) { const pagingStub = sinon.stub(); if (responses) { @@ -89,7 +89,7 @@ function stubPageStreamingCall( function stubAsyncIterationCall( responses?: ResponseType[], - error?: Error + error?: Error, ) { let counter = 0; const asyncIterable = { @@ -119,14 +119,14 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.GetOperationRequest() + new protos.google.longrunning.GetOperationRequest(), ); const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() + new protos.google.longrunning.Operation(), ); client.innerApiCalls.getOperation = stubSimpleCall(expectedResponse); const response = await client.getOperation(request); @@ -134,7 +134,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.getOperation as SinonStub) .getCall(0) - .calledWith(request) + .calledWith(request), ); }); @@ -145,14 +145,14 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.GetOperationRequest() + new protos.google.longrunning.GetOperationRequest(), ); const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() + new protos.google.longrunning.Operation(), ); client.innerApiCalls.getOperation = stubSimpleCallWithCallback(expectedResponse); @@ -162,14 +162,14 @@ describe('operation client', () => { undefined, ( err?: Error | null, - result?: protos.google.longrunning.Operation | null + result?: protos.google.longrunning.Operation | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -177,7 +177,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.getOperation as SinonStub) .getCall(0) - .calledWith(request /* callback function above */) + .calledWith(request /* callback function above */), ); }); @@ -188,15 +188,15 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.GetOperationRequest() + new protos.google.longrunning.GetOperationRequest(), ); const expectedError = new Error('expected'); client.innerApiCalls.getOperation = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(async () => { await client.getOperation(request); @@ -204,7 +204,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.getOperation as SinonStub) .getCall(0) - .calledWith(request) + .calledWith(request), ); }); }); @@ -216,11 +216,11 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.GetOperationRequest() + new protos.google.longrunning.GetOperationRequest(), ); const expectedResponse: ResultTuple = [ new protos.google.longrunning.Operation(), @@ -233,7 +233,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.getOperation as SinonStub) .getCall(0) - .calledWith(request) + .calledWith(request), ); }); @@ -244,11 +244,11 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.GetOperationRequest() + new protos.google.longrunning.GetOperationRequest(), ); const expectedResponse: ResultTuple = [ new protos.google.longrunning.Operation(), @@ -263,14 +263,14 @@ describe('operation client', () => { undefined, ( err?: Error | null, - result?: protos.google.longrunning.Operation | null + result?: protos.google.longrunning.Operation | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -278,7 +278,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.getOperation as SinonStub) .getCall(0) - .calledWith(request /* callback function above */) + .calledWith(request /* callback function above */), ); }); @@ -289,15 +289,15 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.GetOperationRequest() + new protos.google.longrunning.GetOperationRequest(), ); const expectedError = new Error('expected'); client.innerApiCalls.getOperation = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(async () => { await client.getOperationInternal(request); @@ -305,7 +305,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.getOperation as SinonStub) .getCall(0) - .calledWith(request) + .calledWith(request), ); }); }); @@ -317,14 +317,14 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.ListOperationsRequest() + new protos.google.longrunning.ListOperationsRequest(), ); const expectedResponse = generateSampleMessage( - new protos.google.longrunning.ListOperationsResponse() + new protos.google.longrunning.ListOperationsResponse(), ); client.innerApiCalls.listOperations = stubSimpleCall(expectedResponse); const response = await client.listOperations(request); @@ -332,7 +332,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.listOperations as SinonStub) .getCall(0) - .calledWith(request) + .calledWith(request), ); }); @@ -343,14 +343,14 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.ListOperationsRequest() + new protos.google.longrunning.ListOperationsRequest(), ); const expectedResponse = generateSampleMessage( - new protos.google.longrunning.ListOperationsResponse() + new protos.google.longrunning.ListOperationsResponse(), ); client.innerApiCalls.listOperations = stubSimpleCallWithCallback(expectedResponse); @@ -360,14 +360,14 @@ describe('operation client', () => { undefined, ( err?: Error | null, - result?: protos.google.longrunning.ListOperationsResponse | null + result?: protos.google.longrunning.ListOperationsResponse | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -375,7 +375,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.listOperations as SinonStub) .getCall(0) - .calledWith(request /* callback function above */) + .calledWith(request /* callback function above */), ); }); @@ -386,15 +386,15 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.ListOperationsRequest() + new protos.google.longrunning.ListOperationsRequest(), ); const expectedError = new Error('expected'); client.innerApiCalls.listOperations = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(async () => { await client.listOperations(request); @@ -402,7 +402,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.listOperations as SinonStub) .getCall(0) - .calledWith(request) + .calledWith(request), ); }); @@ -413,11 +413,11 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.ListOperationsRequest() + new protos.google.longrunning.ListOperationsRequest(), ); const expectedResponse = [ generateSampleMessage(new protos.google.longrunning.Operation()), @@ -444,7 +444,7 @@ describe('operation client', () => { assert( (client.descriptor.listOperations.createStream as SinonStub) .getCall(0) - .calledWith(client.innerApiCalls.listOperations, request) + .calledWith(client.innerApiCalls.listOperations, request), ); }); @@ -455,16 +455,16 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.ListOperationsRequest() + new protos.google.longrunning.ListOperationsRequest(), ); const expectedError = new Error('expected'); client.descriptor.listOperations.createStream = stubPageStreamingCall( undefined, - expectedError + expectedError, ); const stream = client.listOperationsStream(request); const promise = new Promise((resolve, reject) => { @@ -485,7 +485,7 @@ describe('operation client', () => { assert( (client.descriptor.listOperations.createStream as SinonStub) .getCall(0) - .calledWith(client.innerApiCalls.listOperations, request) + .calledWith(client.innerApiCalls.listOperations, request), ); }); @@ -496,21 +496,21 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.ListOperationsRequest() + new protos.google.longrunning.ListOperationsRequest(), ); const expectedResponse = [ generateSampleMessage( - new protos.google.longrunning.ListOperationsResponse() + new protos.google.longrunning.ListOperationsResponse(), ), generateSampleMessage( - new protos.google.longrunning.ListOperationsResponse() + new protos.google.longrunning.ListOperationsResponse(), ), generateSampleMessage( - new protos.google.longrunning.ListOperationsResponse() + new protos.google.longrunning.ListOperationsResponse(), ), ]; client.descriptor.listOperations.asyncIterate = @@ -524,7 +524,7 @@ describe('operation client', () => { assert.deepStrictEqual( (client.descriptor.listOperations.asyncIterate as SinonStub).getCall(0) .args[1], - request + request, ); }); @@ -535,15 +535,15 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.ListOperationsRequest() + new protos.google.longrunning.ListOperationsRequest(), ); const expectedError = new Error('expected'); client.descriptor.listOperations.asyncIterate = stubAsyncIterationCall( undefined, - expectedError + expectedError, ); const iterable = client.listOperationsAsync(request); await assert.rejects(async () => { @@ -555,7 +555,7 @@ describe('operation client', () => { }); assert.deepStrictEqual( (client.descriptor.listOperations.asyncIterate as SinonStub).args[0][1], - request + request, ); }); }); @@ -567,14 +567,14 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.CancelOperationRequest() + new protos.google.longrunning.CancelOperationRequest(), ); const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() + new protos.google.protobuf.Empty(), ); client.innerApiCalls.cancelOperation = stubSimpleCall(expectedResponse); const response = await client.cancelOperation(request); @@ -582,7 +582,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.cancelOperation as SinonStub) .getCall(0) - .calledWith(request) + .calledWith(request), ); }); @@ -593,14 +593,14 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.CancelOperationRequest() + new protos.google.longrunning.CancelOperationRequest(), ); const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() + new protos.google.protobuf.Empty(), ); client.innerApiCalls.cancelOperation = stubSimpleCallWithCallback(expectedResponse); @@ -610,14 +610,14 @@ describe('operation client', () => { undefined, ( err?: Error | null, - result?: protos.google.protobuf.Empty | null + result?: protos.google.protobuf.Empty | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -625,7 +625,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.cancelOperation as SinonStub) .getCall(0) - .calledWith(request /* callback function above */) + .calledWith(request /* callback function above */), ); }); @@ -636,15 +636,15 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.CancelOperationRequest() + new protos.google.longrunning.CancelOperationRequest(), ); const expectedError = new Error('expected'); client.innerApiCalls.cancelOperation = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(async () => { await client.cancelOperation(request); @@ -652,7 +652,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.cancelOperation as SinonStub) .getCall(0) - .calledWith(request) + .calledWith(request), ); }); }); @@ -664,14 +664,14 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.DeleteOperationRequest() + new protos.google.longrunning.DeleteOperationRequest(), ); const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() + new protos.google.protobuf.Empty(), ); client.innerApiCalls.deleteOperation = stubSimpleCall(expectedResponse); const response = await client.deleteOperation(request); @@ -679,7 +679,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.deleteOperation as SinonStub) .getCall(0) - .calledWith(request) + .calledWith(request), ); }); @@ -690,14 +690,14 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.DeleteOperationRequest() + new protos.google.longrunning.DeleteOperationRequest(), ); const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() + new protos.google.protobuf.Empty(), ); client.innerApiCalls.deleteOperation = stubSimpleCallWithCallback(expectedResponse); @@ -707,14 +707,14 @@ describe('operation client', () => { undefined, ( err?: Error | null, - result?: protos.google.protobuf.Empty | null + result?: protos.google.protobuf.Empty | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -722,7 +722,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.deleteOperation as SinonStub) .getCall(0) - .calledWith(request /* callback function above */) + .calledWith(request /* callback function above */), ); }); @@ -733,15 +733,15 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.DeleteOperationRequest() + new protos.google.longrunning.DeleteOperationRequest(), ); const expectedError = new Error('expected'); client.innerApiCalls.deleteOperation = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(async () => { await client.deleteOperation(request); @@ -749,7 +749,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.deleteOperation as SinonStub) .getCall(0) - .calledWith(request) + .calledWith(request), ); }); }); diff --git a/gax/test/unit/pagedIteration.ts b/gax/test/unit/pagedIteration.ts index 8399711d2..ff0c7a6fa 100644 --- a/gax/test/unit/pagedIteration.ts +++ b/gax/test/unit/pagedIteration.ts @@ -45,7 +45,7 @@ describe('paged iteration', () => { request: {pageToken?: number}, metadata: {}, options: {}, - callback: APICallback + callback: APICallback, ) { const pageToken = request.pageToken || 0; if (pageToken >= pageSize * pagesToStream) { @@ -76,8 +76,8 @@ describe('paged iteration', () => { warnStub.calledWith( 'autoPaginate true', 'Providing a pageSize without setting autoPaginate to false will still return all results. See https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#auto-pagination for more information on how to configure manual paging', - 'AutopaginateTrueWarning' - ) + 'AutopaginateTrueWarning', + ), ); warnStub.restore(); done(); @@ -154,7 +154,7 @@ describe('paged iteration', () => { err: {}, resources: {}, next: {}, - rawResponse: {nums: {}} + rawResponse: {nums: {}}, ) { if (err) { done(err); @@ -170,7 +170,7 @@ describe('paged iteration', () => { apiCall( next, {autoPaginate: false}, - callback as unknown as APICallback + callback as unknown as APICallback, ); } else { assert.strictEqual(counter, pagesToStream + 1); @@ -186,7 +186,7 @@ describe('paged iteration', () => { request: {}, metadata: {}, options: {}, - callback: APICallback + callback: APICallback, ) { callCount++; if (callCount % 2 === 0) { @@ -244,10 +244,10 @@ describe('paged iteration', () => { } const settings = new gax.CallSettings( - (createOptions && createOptions.settings) || {} + (createOptions && createOptions.settings) || {}, ); const resources = await iterableChecker( - descriptor.asyncIterate(apiCall, {}, settings) + descriptor.asyncIterate(apiCall, {}, settings), ); assert.strictEqual(resources.length, 10); }); @@ -271,11 +271,11 @@ describe('paged iteration', () => { } const settings = new gax.CallSettings( - (createOptions && createOptions.settings) || {} + (createOptions && createOptions.settings) || {}, ); settings.autoPaginate = true; const resources = await iterableChecker( - descriptor.asyncIterate(apiCall, {}, settings) + descriptor.asyncIterate(apiCall, {}, settings), ); assert.strictEqual(resources.length, 10); assert.strictEqual(warnStub.callCount, 1); @@ -283,8 +283,8 @@ describe('paged iteration', () => { warnStub.calledWith( 'autoPaginate true', 'Autopaginate will always be set to false in Async paging methods. See more info at https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#auto-pagination for more information on how to configure paging calls', - 'AutopaginateTrueWarning' - ) + 'AutopaginateTrueWarning', + ), ); warnStub.restore(); }); @@ -293,7 +293,7 @@ describe('paged iteration', () => { request: {pageToken?: number}, metadata: {}, options: {}, - callback: APICallback + callback: APICallback, ) { const responsePages = [ [1, 2, 3], @@ -318,7 +318,7 @@ describe('paged iteration', () => { } const apiCall = util.createApiCall(func, createOptions); const settings = new gax.CallSettings( - (createOptions && createOptions.settings) || {} + (createOptions && createOptions.settings) || {}, ); const iterable = descriptor.asyncIterate(apiCall, {}, settings); const results = []; @@ -342,7 +342,7 @@ describe('paged iteration', () => { stream: Stream, onEnd: Function, done: (...args: string[]) => void, - start: number + start: number, ) { let counter = start; stream @@ -365,7 +365,7 @@ describe('paged iteration', () => { assert.strictEqual(spy.callCount, pagesToStream + 1); }, done, - 0 + 0, ); }); @@ -378,7 +378,7 @@ describe('paged iteration', () => { stream, () => assert.strictEqual(onResponse.callCount, pagesToStream + 1), done, - 0 + 0, ); }); @@ -396,7 +396,7 @@ describe('paged iteration', () => { assert.strictEqual(spy.callCount, 2); }, done, - 0 + 0, ); }); it('ignores autoPaginate options and warns, but respects others', done => { @@ -415,13 +415,13 @@ describe('paged iteration', () => { warnStub.calledWith( 'autoPaginate true', 'Autopaginate will always be set to false in stream paging methods. See more info at https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#auto-pagination for more information on how to configure paging calls', - 'AutopaginateTrueWarning' - ) + 'AutopaginateTrueWarning', + ), ); warnStub.restore(); }, done, - 0 + 0, ); }); it('ignores autoPaginate options but respects others', done => { @@ -435,7 +435,7 @@ describe('paged iteration', () => { assert.strictEqual(spy.callCount, 1); }, done, - 0 + 0, ); }); @@ -454,7 +454,7 @@ describe('paged iteration', () => { assert.strictEqual(onResponse.callCount, spy.callCount); }, done, - 0 + 0, ); }); @@ -469,7 +469,7 @@ describe('paged iteration', () => { assert.strictEqual(spy.callCount, pagesToStream + 1); }, done, - 0 + 0, ); }, 50); }); @@ -520,7 +520,7 @@ describe('paged iteration', () => { request: {pageToken?: number}, metadata: {}, options: {}, - callback: APICallback + callback: APICallback, ) { const pageToken = request.pageToken || 0; if (pageToken >= pageSize * pagesToStream) { @@ -552,7 +552,7 @@ describe('paged iteration', () => { assert.strictEqual(onResponseSpy.callCount, spy.callCount); }, done, - 0 + 0, ); }); }); @@ -596,7 +596,7 @@ describe('REGAPIC Pagination', () => { request: {pageToken?: number}, metadata: {}, options: {}, - callback: APICallback + callback: APICallback, ) { const pageToken = request.pageToken || 0; if (pageToken >= pageSize * pagesToStream) { @@ -628,10 +628,10 @@ describe('REGAPIC Pagination', () => { it('return an tuple iterable, count to 10', async () => { const settings = new gax.CallSettings( - (createOptions && createOptions.settings) || {} + (createOptions && createOptions.settings) || {}, ); const resources = await iterableChecker( - descriptor.asyncIterate(apiCall, {}, settings) + descriptor.asyncIterate(apiCall, {}, settings), ); assert.strictEqual(resources.length, 10); for await (const [key, value] of resources as [string, ResponseType]) { diff --git a/gax/test/unit/pathTemplate.ts b/gax/test/unit/pathTemplate.ts index 8669dada6..babcadaac 100644 --- a/gax/test/unit/pathTemplate.ts +++ b/gax/test/unit/pathTemplate.ts @@ -102,7 +102,7 @@ describe('PathTemplate', () => { const want = {$0: 'hello%2F%2Bworld'}; assert.deepStrictEqual( template.match('buckets/hello%2F%2Bworld/objects'), - want + want, ); }); @@ -111,7 +111,7 @@ describe('PathTemplate', () => { const want = {$0: 'foo', $1: 'bar/baz'}; assert.deepStrictEqual( template.match('buckets/foo/objects/bar/baz'), - want + want, ); }); @@ -123,7 +123,7 @@ describe('PathTemplate', () => { it('should match template with non-slash resource patterns', () => { const template = new PathTemplate( - 'user/{user_id}/blurbs/legacy/{blurb_a}-{blurb_b}~{legacy_user}' + 'user/{user_id}/blurbs/legacy/{blurb_a}-{blurb_b}~{legacy_user}', ); const want = { user_id: 'foo', @@ -133,13 +133,13 @@ describe('PathTemplate', () => { }; assert.deepStrictEqual( template.match('user/foo/blurbs/legacy/bara-barb~user'), - want + want, ); }); it('should not match template with malformed non-slash resource patterns', () => { const template = new PathTemplate( - 'user/{user_id}/blurbs/legacy/{blurb_id}.{legacy_user}' + 'user/{user_id}/blurbs/legacy/{blurb_id}.{legacy_user}', ); assert.throws(() => { template.match('user/foo/blurbs/legacy/bar~user2'); @@ -161,7 +161,7 @@ describe('PathTemplate', () => { }); it('should render atomic resource', () => { const template = new PathTemplate( - 'projects/{project}/metricDescriptors/{metric_descriptor=**}' + 'projects/{project}/metricDescriptors/{metric_descriptor=**}', ); const params = { project: 'project-name', @@ -203,7 +203,7 @@ describe('PathTemplate', () => { it('should accept both strings and numbers as values', () => { const template = new PathTemplate( - 'projects/{project}/sessions/{session}' + 'projects/{project}/sessions/{session}', ); const params = { project: 'testProject', @@ -215,7 +215,7 @@ describe('PathTemplate', () => { it('should render non-slash resource', () => { const template = new PathTemplate( - 'user/{user_id}/blurbs/legacy/{blurb_id}.{legacy_user}/project/{project}' + 'user/{user_id}/blurbs/legacy/{blurb_id}.{legacy_user}/project/{project}', ); const params = { user_id: 'foo', diff --git a/gax/test/unit/regapic.ts b/gax/test/unit/regapic.ts index 6c85e75dd..b06b22605 100644 --- a/gax/test/unit/regapic.ts +++ b/gax/test/unit/regapic.ts @@ -80,7 +80,7 @@ describe('REGAPIC', () => { '..', 'test', 'fixtures', - 'library.json' + 'library.json', ); // eslint-disable-next-line @typescript-eslint/no-var-requires libProtos = gaxGrpc.loadProtoJSON(require(TEST_JSON)); @@ -101,7 +101,7 @@ describe('REGAPIC', () => { arrayBuffer: () => { return Promise.resolve(Buffer.from(JSON.stringify(requestObject))); }, - }) + }), ); gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { @@ -109,7 +109,7 @@ describe('REGAPIC', () => { assert.strictEqual(err, null); assert.strictEqual( requestObject.content, - (result as {content: string}).content + (result as {content: string}).content, ); done(); }); @@ -130,7 +130,7 @@ describe('REGAPIC', () => { Promise.resolve({ ok: true, body: responseStream, - }) + }), ); gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { @@ -138,7 +138,7 @@ describe('REGAPIC', () => { requestObject, {}, {}, - () => {} + () => {}, ) as StreamArrayParser; const results: {}[] = []; stream.on('data', data => { @@ -202,7 +202,7 @@ describe('REGAPIC', () => { arrayBuffer: () => { return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); }, - }) + }), ); gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { @@ -211,11 +211,11 @@ describe('REGAPIC', () => { assert.strictEqual(err, null); assert.strictEqual( 'shelf-name', - (result as {name: {}; theme: {}; type: {}}).name + (result as {name: {}; theme: {}; type: {}}).name, ); assert.strictEqual( 'TYPEONE', - (result as {name: {}; theme: {}; type: {}}).type + (result as {name: {}; theme: {}; type: {}}).type, ); done(); }); @@ -238,7 +238,7 @@ describe('REGAPIC', () => { arrayBuffer: () => { return Promise.resolve(Buffer.from(JSON.stringify(shelf))); }, - }) + }), ); gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { libStub.createShelf(requestObject, {}, {}, (err?: {}) => { @@ -265,7 +265,7 @@ describe('REGAPIC', () => { arrayBuffer: () => { return Promise.resolve(Buffer.from(JSON.stringify(shelf))); }, - }) + }), ); gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { libStub.createShelf(requestObject, {}, {}, (err?: {}) => { @@ -294,7 +294,7 @@ describe('REGAPIC', () => { arrayBuffer: () => { return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); }, - }) + }), ); gaxGrpcNumericEnums @@ -303,16 +303,16 @@ describe('REGAPIC', () => { libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { assert.strictEqual( spy.getCall(0).returnValue?.queryString, - '$alt=json%3Benum-encoding=int' + '$alt=json%3Benum-encoding=int', ); assert.strictEqual(err, null); assert.strictEqual( 'shelf-name', - (result as {name: {}; theme: {}; type: {}}).name + (result as {name: {}; theme: {}; type: {}}).name, ); assert.strictEqual( 100, - (result as {name: {}; theme: {}; type: {}}).type + (result as {name: {}; theme: {}; type: {}}).type, ); done(); }); @@ -335,7 +335,7 @@ describe('REGAPIC', () => { arrayBuffer: () => { return Promise.resolve(Buffer.from(JSON.stringify(shelf))); }, - }) + }), ); gaxGrpcNumericEnums .createStub(libraryService, stubOptions) @@ -343,11 +343,11 @@ describe('REGAPIC', () => { libStub.createShelf(requestObject, {}, {}, (err?: {}) => { assert.strictEqual( 'string', - typeof spy.getCall(0).returnValue?.queryString + typeof spy.getCall(0).returnValue?.queryString, ); assert.match( spy.getCall(0).returnValue?.queryString, - /\$alt=json%3Benum-encoding=int(&.*)?$/ + /\$alt=json%3Benum-encoding=int(&.*)?$/, ); assert.strictEqual(err, null); done(); @@ -374,7 +374,7 @@ describe('REGAPIC', () => { arrayBuffer: () => { return Promise.resolve(Buffer.from(JSON.stringify(shelf))); }, - }) + }), ); gaxGrpcNumericEnums .createStub(libraryService, stubOptions) @@ -382,7 +382,7 @@ describe('REGAPIC', () => { libStub.createShelf(requestObject, {}, {}, (err?: {}) => { assert.strictEqual( spy.getCall(0).returnValue?.queryString, - 'queryStringParameter=must-be-preserved&$alt=json%3Benum-encoding=int' + 'queryStringParameter=must-be-preserved&$alt=json%3Benum-encoding=int', ); assert.strictEqual(err, null); done(); @@ -406,7 +406,7 @@ describe('REGAPIC', () => { arrayBuffer: () => { return Promise.resolve(Buffer.from(JSON.stringify(shelf))); }, - }) + }), ); gaxGrpcNumericEnums .createStub(libraryService, stubOptions) @@ -414,7 +414,7 @@ describe('REGAPIC', () => { libStub.createShelf(requestObject, {}, {}, (err?: {}) => { assert.strictEqual( spy.getCall(0).returnValue?.queryString, - '$alt=json%3Benum-encoding=int' + '$alt=json%3Benum-encoding=int', ); assert.strictEqual(err, null); done(); @@ -441,7 +441,7 @@ describe('REGAPIC', () => { arrayBuffer: () => { return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); }, - }) + }), ); gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { @@ -456,7 +456,7 @@ describe('REGAPIC', () => { read: false; bookId: {}; } - ).name + ).name, ); assert.strictEqual( '9007199254740992', @@ -468,7 +468,7 @@ describe('REGAPIC', () => { read: false; bookId: {}; } - ).bookId + ).bookId, ); done(); }); @@ -492,7 +492,7 @@ describe('REGAPIC', () => { arrayBuffer: () => { return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); }, - }) + }), ); gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { @@ -507,7 +507,7 @@ describe('REGAPIC', () => { read: false; bookId: {}; } - ).name + ).name, ); assert.strictEqual( '42', @@ -519,7 +519,7 @@ describe('REGAPIC', () => { read: false; bookId: {}; } - ).bookId + ).bookId, ); done(); }); @@ -544,7 +544,7 @@ describe('REGAPIC', () => { arrayBuffer: () => { return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); }, - }) + }), ); gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { @@ -559,7 +559,7 @@ describe('REGAPIC', () => { read: false; bookId: {}; } - ).name + ).name, ); assert.strictEqual( bookId.toString(), @@ -571,7 +571,7 @@ describe('REGAPIC', () => { read: false; bookId: {}; } - ).bookId + ).bookId, ); done(); }); @@ -596,7 +596,7 @@ describe('REGAPIC', () => { arrayBuffer: () => { return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); }, - }) + }), ); gaxGrpcMinifyJson @@ -605,20 +605,20 @@ describe('REGAPIC', () => { libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { assert.strictEqual( 'string', - typeof spy.getCall(0).returnValue?.queryString + typeof spy.getCall(0).returnValue?.queryString, ); assert.match( spy.getCall(0).returnValue?.queryString, - /\$prettyPrint=0(&.*)?$/ + /\$prettyPrint=0(&.*)?$/, ); assert.strictEqual(err, null); assert.strictEqual( 'shelf-name', - (result as {name: {}; theme: {}; type: {}}).name + (result as {name: {}; theme: {}; type: {}}).name, ); assert.strictEqual( 100, - (result as {name: {}; theme: {}; type: {}}).type + (result as {name: {}; theme: {}; type: {}}).type, ); done(); }); @@ -641,27 +641,27 @@ describe('REGAPIC', () => { arrayBuffer: () => { return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); }, - }) + }), ); gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { assert.strictEqual( 'string', - typeof spy.getCall(0).returnValue?.queryString + typeof spy.getCall(0).returnValue?.queryString, ); assert.doesNotMatch( spy.getCall(0).returnValue?.queryString, - /prettyPrint/ + /prettyPrint/, ); assert.strictEqual(err, null); assert.strictEqual( 'shelf-name', - (result as {name: {}; theme: {}; type: {}}).name + (result as {name: {}; theme: {}; type: {}}).name, ); assert.strictEqual( 100, - (result as {name: {}; theme: {}; type: {}}).type + (result as {name: {}; theme: {}; type: {}}).type, ); done(); }); diff --git a/gax/test/unit/routingHeader.ts b/gax/test/unit/routingHeader.ts index a1e318830..3acedbbf4 100644 --- a/gax/test/unit/routingHeader.ts +++ b/gax/test/unit/routingHeader.ts @@ -28,7 +28,7 @@ describe('fromParams', () => { const routingHeader = fromParams({screaming: '😱', cyrillic: 'тест'}); assert.strictEqual( routingHeader, - 'screaming=%F0%9F%98%B1&cyrillic=%D1%82%D0%B5%D1%81%D1%82' + 'screaming=%F0%9F%98%B1&cyrillic=%D1%82%D0%B5%D1%81%D1%82', ); }); }); diff --git a/gax/test/unit/status.ts b/gax/test/unit/status.ts index 3007be4dc..c6eb183b1 100644 --- a/gax/test/unit/status.ts +++ b/gax/test/unit/status.ts @@ -26,40 +26,40 @@ describe('status.ts', () => { assert.deepStrictEqual(rpcCodeFromHttpStatusCode(307), Status.UNKNOWN); assert.deepStrictEqual( rpcCodeFromHttpStatusCode(400), - Status.INVALID_ARGUMENT + Status.INVALID_ARGUMENT, ); assert.deepStrictEqual( rpcCodeFromHttpStatusCode(401), - Status.UNAUTHENTICATED + Status.UNAUTHENTICATED, ); assert.deepStrictEqual( rpcCodeFromHttpStatusCode(403), - Status.PERMISSION_DENIED + Status.PERMISSION_DENIED, ); assert.deepStrictEqual(rpcCodeFromHttpStatusCode(404), Status.NOT_FOUND); assert.deepStrictEqual(rpcCodeFromHttpStatusCode(409), Status.ABORTED); assert.deepStrictEqual(rpcCodeFromHttpStatusCode(416), Status.OUT_OF_RANGE); assert.deepStrictEqual( rpcCodeFromHttpStatusCode(429), - Status.RESOURCE_EXHAUSTED + Status.RESOURCE_EXHAUSTED, ); assert.deepStrictEqual(rpcCodeFromHttpStatusCode(499), Status.CANCELLED); assert.deepStrictEqual( rpcCodeFromHttpStatusCode(451), - Status.FAILED_PRECONDITION + Status.FAILED_PRECONDITION, ); assert.deepStrictEqual( rpcCodeFromHttpStatusCode(411), - Status.FAILED_PRECONDITION + Status.FAILED_PRECONDITION, ); assert.deepStrictEqual( rpcCodeFromHttpStatusCode(501), - Status.UNIMPLEMENTED + Status.UNIMPLEMENTED, ); assert.deepStrictEqual(rpcCodeFromHttpStatusCode(503), Status.UNAVAILABLE); assert.deepStrictEqual( rpcCodeFromHttpStatusCode(504), - Status.DEADLINE_EXCEEDED + Status.DEADLINE_EXCEEDED, ); assert.deepStrictEqual(rpcCodeFromHttpStatusCode(505), Status.INTERNAL); assert.deepStrictEqual(rpcCodeFromHttpStatusCode(510), Status.INTERNAL); diff --git a/gax/test/unit/streamArrayParser.ts b/gax/test/unit/streamArrayParser.ts index 61325031b..bc5ecda94 100644 --- a/gax/test/unit/streamArrayParser.ts +++ b/gax/test/unit/streamArrayParser.ts @@ -102,7 +102,7 @@ describe('Parse REST stream array', () => { }, ]; const inStream = createRandomChunkReadableStream( - JSON.stringify(expectedResults) + JSON.stringify(expectedResults), ); inStream.on('data', d => { assert.notEqual(d, undefined); @@ -125,7 +125,7 @@ describe('Parse REST stream array', () => { const expect = toProtobufJSON(User, expectedResults[key]); assert.strictEqual( JSON.stringify(results[key]), - JSON.stringify(expect) + JSON.stringify(expect), ); } done(); @@ -143,7 +143,7 @@ describe('Parse REST stream array', () => { }, ]; const inStream = createRandomChunkReadableStream( - JSON.stringify(expectedResults) + JSON.stringify(expectedResults), ); const streamArrayParser = new StreamArrayParser(streamMethod); pipeline(inStream, streamArrayParser, err => { @@ -165,7 +165,7 @@ describe('Parse REST stream array', () => { it("should listen on error if input stream is not start '['", done => { const expectedResults = {}; const inStream = createRandomChunkReadableStream( - JSON.stringify(expectedResults) + JSON.stringify(expectedResults), ); const streamArrayParser = new StreamArrayParser(streamMethod); pipeline(inStream, streamArrayParser, err => { diff --git a/gax/test/unit/streaming.ts b/gax/test/unit/streaming.ts index 4c291abe9..bcf2941a8 100644 --- a/gax/test/unit/streaming.ts +++ b/gax/test/unit/streaming.ts @@ -47,14 +47,14 @@ function createApiCallStreaming( | sinon.SinonSpy, internal.Transform | StreamArrayParser>, type: streaming.StreamType, rest?: boolean, - gaxStreamingRetries?: boolean + gaxStreamingRetries?: boolean, ) { const settings = new gax.CallSettings(); return createApiCall( //@ts-ignore Promise.resolve(func), settings, - new StreamDescriptor(type, rest, gaxStreamingRetries) + new StreamDescriptor(type, rest, gaxStreamingRetries), ) as GaxCallStream; } @@ -80,7 +80,7 @@ describe('streaming', () => { const apiCall = createApiCallStreaming( spy, - streaming.StreamType.SERVER_STREAMING + streaming.StreamType.SERVER_STREAMING, ); const s = apiCall({}, undefined); const callback = sinon.spy(data => { @@ -119,7 +119,7 @@ describe('streaming', () => { const apiCall = createApiCallStreaming( //@ts-ignore func, - streaming.StreamType.CLIENT_STREAMING + streaming.StreamType.CLIENT_STREAMING, ); const s = apiCall({}, undefined, (err, response) => { assert.strictEqual(err, null); @@ -148,7 +148,7 @@ describe('streaming', () => { const apiCall = createApiCallStreaming( //@ts-ignore func, - streaming.StreamType.BIDI_STREAMING + streaming.StreamType.BIDI_STREAMING, ); const s = apiCall({}, undefined); const arg = {foo: 'bar'}; @@ -191,7 +191,7 @@ describe('streaming', () => { const apiCall = createApiCallStreaming( //@ts-ignore func, - streaming.StreamType.BIDI_STREAMING + streaming.StreamType.BIDI_STREAMING, ); const s = apiCall({}, undefined); let receivedMetadata: {}; @@ -266,7 +266,7 @@ describe('streaming', () => { const apiCall = createApiCallStreaming( //@ts-ignore func, - streaming.StreamType.SERVER_STREAMING + streaming.StreamType.SERVER_STREAMING, ); const s = apiCall( {}, @@ -279,7 +279,7 @@ describe('streaming', () => { maxRpcTimeoutMillis: 3000, maxRetries: 0, }), - } + }, ); let counter = 0; const expectedCount = 5; @@ -331,7 +331,7 @@ describe('streaming', () => { func, streaming.StreamType.SERVER_STREAMING, false, - true // gax native retries + true, // gax native retries ); const s = apiCall( {}, @@ -344,7 +344,7 @@ describe('streaming', () => { maxRpcTimeoutMillis: 3000, maxRetries: 0, }), - } + }, ); let counter = 0; const expectedCount = 5; @@ -393,7 +393,7 @@ describe('streaming', () => { const apiCall = createApiCallStreaming( spy, - streaming.StreamType.SERVER_STREAMING + streaming.StreamType.SERVER_STREAMING, ); const s = apiCall({}, undefined); let receivedMetadata: {}; @@ -473,7 +473,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - true // new gax retries + true, // new gax retries ); const s = apiCall({}, undefined); let receivedMetadata: {}; @@ -547,7 +547,7 @@ describe('streaming', () => { const apiCall = createApiCallStreaming( spy, - streaming.StreamType.SERVER_STREAMING + streaming.StreamType.SERVER_STREAMING, ); const s = apiCall({}, undefined); let receivedStatus: {}; @@ -615,7 +615,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - true // new gax retries + true, // new gax retries ); const s = apiCall({}, undefined); let receivedStatus: {}; @@ -702,7 +702,7 @@ describe('streaming', () => { }); const apiCall = createApiCallStreaming( spy, - streaming.StreamType.SERVER_STREAMING + streaming.StreamType.SERVER_STREAMING, ); const s = apiCall( @@ -716,7 +716,7 @@ describe('streaming', () => { maxRpcTimeoutMillis: 3000, maxRetries: 0, }), - } + }, ); s.on('error', err => { @@ -728,7 +728,7 @@ describe('streaming', () => { assert.strictEqual(err.reason, errorInfoObj.reason); assert.strictEqual( JSON.stringify(err.errorInfoMetadata), - JSON.stringify(errorInfoObj.metadata) + JSON.stringify(errorInfoObj.metadata), ); done(); }); @@ -783,7 +783,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - true // new retry behavior enabled + true, // new retry behavior enabled ); const s = apiCall( @@ -797,7 +797,7 @@ describe('streaming', () => { maxRpcTimeoutMillis: 3000, maxRetries: 0, }), - } + }, ); s.on('error', err => { @@ -809,7 +809,7 @@ describe('streaming', () => { assert.strictEqual(err.reason, errorInfoObj.reason); assert.strictEqual( JSON.stringify(err.errorInfoMetadata), - JSON.stringify(errorInfoObj.metadata) + JSON.stringify(errorInfoObj.metadata), ); done(); }); @@ -865,7 +865,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - true // new retry behavior enabled + true, // new retry behavior enabled ); const s = apiCall( @@ -879,7 +879,7 @@ describe('streaming', () => { maxRpcTimeoutMillis: 3000, maxRetries: 1, // max retries or timeout must be > 0 in order to reach the code we want to test }), - } + }, ); s.on('error', err => { @@ -890,13 +890,13 @@ describe('streaming', () => { assert.deepStrictEqual(err.message, 'test error'); assert.deepStrictEqual( err.note, - 'Exception occurred in retry method that was not classified as transient' + 'Exception occurred in retry method that was not classified as transient', ); assert.strictEqual(err.domain, errorInfoObj.domain); assert.strictEqual(err.reason, errorInfoObj.reason); assert.strictEqual( JSON.stringify(err.errorInfoMetadata), - JSON.stringify(errorInfoObj.metadata) + JSON.stringify(errorInfoObj.metadata), ); done(); }); @@ -950,7 +950,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - true // new retry behavior enabled + true, // new retry behavior enabled ); const s = apiCall( @@ -964,7 +964,7 @@ describe('streaming', () => { maxRpcTimeoutMillis: 3000, // neither maxRetries nor totalTimeoutMillis is defined }), - } + }, ); s.on('error', err => { @@ -975,13 +975,13 @@ describe('streaming', () => { assert.deepStrictEqual(err.message, 'test error'); assert.deepStrictEqual( err.note, - 'Exception occurred in retry method that was not classified as transient' + 'Exception occurred in retry method that was not classified as transient', ); assert.strictEqual(err.domain, errorInfoObj.domain); assert.strictEqual(err.reason, errorInfoObj.reason); assert.strictEqual( JSON.stringify(err.errorInfoMetadata), - JSON.stringify(errorInfoObj.metadata) + JSON.stringify(errorInfoObj.metadata), ); done(); }); @@ -1074,7 +1074,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - true // new retry behavior enabled + true, // new retry behavior enabled ); const s = apiCall( {}, @@ -1087,7 +1087,7 @@ describe('streaming', () => { maxRpcTimeoutMillis: 3000, maxRetries: 2, // max retries or timeout must be > 0 in order to reach the code we want to test }), - } + }, ); s.on('error', err => { @@ -1097,13 +1097,13 @@ describe('streaming', () => { assert.deepStrictEqual(err.message, 'test error 2'); assert.deepStrictEqual( err.note, - 'Exception occurred in retry method that was not classified as transient' + 'Exception occurred in retry method that was not classified as transient', ); assert.strictEqual(err.domain, errorInfoObj.domain); assert.strictEqual(err.reason, errorInfoObj.reason); assert.strictEqual( JSON.stringify(err.errorInfoMetadata), - JSON.stringify(errorInfoObj.metadata) + JSON.stringify(errorInfoObj.metadata), ); done(); }); @@ -1138,7 +1138,7 @@ describe('streaming', () => { counter++; assert.deepStrictEqual( receivedData.join(' '), - 'Hello World testing retries' + 'Hello World testing retries', ); done(); break; @@ -1153,7 +1153,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - true // streaming retries + true, // streaming retries ); const s = apiCall( @@ -1167,7 +1167,7 @@ describe('streaming', () => { maxRpcTimeoutMillis: 3000, maxRetries: 1, }), - } + }, ); s.on('data', data => { receivedData.push(data); @@ -1230,7 +1230,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - true // new retries + true, // new retries ); function shouldRetryFn(error: GoogleError) { @@ -1249,9 +1249,9 @@ describe('streaming', () => { maxRpcTimeoutMillis: 3000, maxRetries: 2, // maxRetries must be > 1 to ensure we hit both checks for a shouldRetry function }, - shouldRetryFn + shouldRetryFn, ), - } + }, ); const finalData: string[] = []; s.on('data', data => { @@ -1334,7 +1334,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - true // new retry behavior enabled + true, // new retry behavior enabled ); // resumption strategy is to pass a different arg to the function const getResumptionRequestFn = sinon.spy((originalRequest: RequestType) => { @@ -1355,9 +1355,9 @@ describe('streaming', () => { maxRetries: 2, // max retries or timeout must be > 0 in order to reach the code we want to test }, undefined, - getResumptionRequestFn + getResumptionRequestFn, ), - } + }, ); s.on('data', data => { receivedData.push(data); @@ -1372,7 +1372,7 @@ describe('streaming', () => { assert.strictEqual(receivedData.length, 4); assert.deepStrictEqual( receivedData.join(' '), - 'Hello World testing retries' + 'Hello World testing retries', ); assert.strictEqual(getResumptionRequestFn.callCount, 1); done(); @@ -1438,7 +1438,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - false // new retry behavior disabled + false, // new retry behavior disabled ); // resumption strategy is to pass a different arg to the function const getResumptionRequestFn = (originalRequest: RequestType) => { @@ -1459,9 +1459,9 @@ describe('streaming', () => { maxRetries: 2, // max retries or timeout must be > 0 in order to reach the code we want to test }, undefined, - getResumptionRequestFn + getResumptionRequestFn, ), - } + }, ); s.on('error', err => { @@ -1469,7 +1469,7 @@ describe('streaming', () => { // stream will continue after retry assert.deepStrictEqual( err.message, - 'getResumptionRequestFn can only be used when gaxStreamingRetries is set to true.' + 'getResumptionRequestFn can only be used when gaxStreamingRetries is set to true.', ); done(); }); @@ -1498,7 +1498,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - true // new retry behavior enabled + true, // new retry behavior enabled ); const s1 = apiCall({}, undefined); @@ -1508,7 +1508,7 @@ describe('streaming', () => { transform: (data, _encoding, callback) => { callback( null, - data.resources.map((element: number) => element + 1) + data.resources.map((element: number) => element + 1), ); }, }); @@ -1526,7 +1526,7 @@ describe('streaming', () => { s2.on('end', () => { assert.strictEqual( JSON.stringify(finalResults), - JSON.stringify([[2, 3]]) + JSON.stringify([[2, 3]]), ); done(); }); @@ -1534,7 +1534,7 @@ describe('streaming', () => { pipeline(s1, transform, s2, err => { if (err) { throw new Error( - 'pipeline in properly emits the end event at the end of a pipeline transformation test failed' + 'pipeline in properly emits the end event at the end of a pipeline transformation test failed', ); } }); @@ -1563,7 +1563,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - true // new retry behavior enabled + true, // new retry behavior enabled ); const s1 = apiCall({}, undefined); @@ -1574,7 +1574,7 @@ describe('streaming', () => { setTimeout(() => { callback( null, - data.resources.map((element: number) => element + 1) + data.resources.map((element: number) => element + 1), ); }, 10); }, @@ -1593,7 +1593,7 @@ describe('streaming', () => { s2.on('end', () => { assert.strictEqual( JSON.stringify(finalResults), - JSON.stringify([[2, 3]]) + JSON.stringify([[2, 3]]), ); done(); }); @@ -1601,7 +1601,7 @@ describe('streaming', () => { pipeline(s1, transform, s2, err => { if (err) { throw new Error( - 'pipeline in properly emits the end event at the end of a pipeline transformation test failed' + 'pipeline in properly emits the end event at the end of a pipeline transformation test failed', ); } }); @@ -1615,7 +1615,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en it('server streaming call retries until exceeding timeout and surfaces underlying error', done => { const retrySpy = sinon.spy( streaming.StreamProxy.prototype, - 'throwIfMaxRetriesOrTotalTimeoutExceeded' + 'throwIfMaxRetriesOrTotalTimeoutExceeded', ); const firstError = Object.assign(new GoogleError('UNAVAILABLE'), { code: 14, @@ -1641,7 +1641,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true + true, ); const call = apiCall( @@ -1655,7 +1655,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en maxRpcTimeoutMillis: 3000, totalTimeoutMillis: 200, // timeout that ensures it should retry at least once }), - } + }, ); call.on('error', err => { @@ -1667,7 +1667,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en assert.notStrictEqual(retrySpy.callCount, 0); // it MUST retry at least once assert.strictEqual( err.message, - 'Total timeout of API exceeded 200 milliseconds retrying error Error: UNAVAILABLE before any response was received.' + 'Total timeout of API exceeded 200 milliseconds retrying error Error: UNAVAILABLE before any response was received.', ); done(); } @@ -1680,7 +1680,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en it('server streaming call retries until exceeding max retries and surfaces underlying error in note', done => { const retrySpy = sinon.spy( streaming.StreamProxy.prototype, - 'throwIfMaxRetriesOrTotalTimeoutExceeded' + 'throwIfMaxRetriesOrTotalTimeoutExceeded', ); const firstError = Object.assign(new GoogleError('UNAVAILABLE'), { code: 14, @@ -1706,7 +1706,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true + true, ); const call = apiCall( @@ -1720,7 +1720,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en maxRpcTimeoutMillis: 3000, maxRetries: 2, }), - } + }, ); call.on('error', err => { @@ -1732,7 +1732,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en assert.strictEqual(retrySpy.callCount, 3); // we pass the first two times assert.strictEqual( err.message, - 'Exceeded maximum number of retries retrying error Error: UNAVAILABLE before any response was received' + 'Exceeded maximum number of retries retrying error Error: UNAVAILABLE before any response was received', ); done(); } @@ -1746,7 +1746,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en // we don't call the timeout/max retry check on non retryable error codes const retrySpy = sinon.spy( streaming.StreamProxy.prototype, - 'throwIfMaxRetriesOrTotalTimeoutExceeded' + 'throwIfMaxRetriesOrTotalTimeoutExceeded', ); const firstError = Object.assign(new GoogleError('UNAVAILABLE'), { code: 14, @@ -1773,7 +1773,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true + true, ); const call = apiCall( @@ -1788,7 +1788,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en maxRpcTimeoutMillis: 3000, maxRetries: 2, }), - } + }, ); call.on('error', err => { @@ -1827,7 +1827,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true + true, ); const call = apiCall( @@ -1841,7 +1841,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en maxRpcTimeoutMillis: 3000, totalTimeoutMillis: 10, }), - } + }, ); call.on('error', err => { @@ -1851,7 +1851,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en assert.strictEqual(err.code, 4); assert.strictEqual( err.message, - 'Total timeout of API exceeded 10 milliseconds retrying error Error: UNAVAILABLE before any response was received.' + 'Total timeout of API exceeded 10 milliseconds retrying error Error: UNAVAILABLE before any response was received.', ); done(); } @@ -1877,7 +1877,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true //gaxStreamingRetries + true, //gaxStreamingRetries ); // anonymous function is a shouldRetryFn @@ -1896,9 +1896,9 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en }, () => { return true; - } + }, ), - } + }, ); }); @@ -1921,7 +1921,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true //gaxStreamingRetries + true, //gaxStreamingRetries ); apiCall( @@ -1935,7 +1935,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en maxRpcTimeoutMillis: 3000, totalTimeoutMillis: 4500, }), - } + }, ); }); @@ -1967,7 +1967,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true //gaxStreamingRetries + true, //gaxStreamingRetries ); // "resumption" strategy is to just return the original request @@ -1989,9 +1989,9 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en totalTimeoutMillis: 4500, }, undefined, - getResumptionRequestFn + getResumptionRequestFn, ), - } + }, ); }); @@ -2025,7 +2025,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true // ensure we're doing the new retries + true, // ensure we're doing the new retries ); // make the call with both options passed at call time @@ -2041,7 +2041,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en totalTimeoutMillis: 4000, maxRetries: 5, }), - } + }, ); call.on('error', err => { assert(err instanceof GoogleError); @@ -2049,7 +2049,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en assert.strictEqual(err.code, 3); assert.strictEqual( err.message, - 'Cannot set both totalTimeoutMillis and maxRetries in backoffSettings.' + 'Cannot set both totalTimeoutMillis and maxRetries in backoffSettings.', ); done(); } @@ -2074,7 +2074,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true // ensure we're doing the new retries + true, // ensure we're doing the new retries ); const passedRetryRequestOptions = { @@ -2103,13 +2103,13 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en maxRpcTimeoutMillis: 3000, totalTimeoutMillis: 4500, }), - } + }, ); } catch (err) { assert(err instanceof Error); assert.strictEqual( err.toString(), - 'Error: Only one of retry or retryRequestOptions may be set' + 'Error: Only one of retry or retryRequestOptions may be set', ); done(); } @@ -2128,16 +2128,16 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en assert(typeof settings.retryRequestOptions === 'undefined'); assert.strictEqual( settings.retry?.backoffSettings.maxRetryDelayMillis, - 70000 + 70000, ); assert.strictEqual( settings.retry?.backoffSettings.retryDelayMultiplier, - 3 + 3, ); // totalTimeout is undefined because maxRetries is passed assert( typeof settings.retry?.backoffSettings.totalTimeoutMillis === - 'undefined' + 'undefined', ); assert.strictEqual(settings.retry?.backoffSettings.maxRetries, 1); @@ -2162,7 +2162,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true // gaxStreamingRetries + true, // gaxStreamingRetries ); const passedRetryRequestOptions = { objectMode: false, @@ -2180,7 +2180,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en {}, { retryRequestOptions: passedRetryRequestOptions, - } + }, ); assert.strictEqual(warnStub.callCount, 4); @@ -2188,29 +2188,29 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en warnStub.calledWith( 'retry_request_options', 'retryRequestOptions will be deprecated in a future release. Please use retryOptions to pass retry options at call time', - 'DeprecationWarning' - ) + 'DeprecationWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'noResponseRetries override is not supported. Please specify retry codes or a function to determine retry eligibility.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'currentRetryAttempt override is not supported. Retry attempts are tracked internally.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'objectMode override is not supported. It is set to true internally by default in gax.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); }); @@ -2227,16 +2227,16 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en assert(typeof settings.retryRequestOptions === 'undefined'); assert.strictEqual( settings.retry?.backoffSettings.maxRetryDelayMillis, - 0 + 0, ); assert.strictEqual( settings.retry?.backoffSettings.retryDelayMultiplier, - 0 + 0, ); // totalTimeout is undefined because maxRetries is passed assert( typeof settings.retry?.backoffSettings.totalTimeoutMillis === - 'undefined' + 'undefined', ); assert.strictEqual(settings.retry?.backoffSettings.maxRetries, 0); @@ -2261,7 +2261,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true // gaxStreamingRetries + true, // gaxStreamingRetries ); const passedRetryRequestOptions = { objectMode: false, @@ -2279,7 +2279,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en {}, { retryRequestOptions: passedRetryRequestOptions, - } + }, ); assert.strictEqual(warnStub.callCount, 4); @@ -2287,29 +2287,29 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en warnStub.calledWith( 'retry_request_options', 'retryRequestOptions will be deprecated in a future release. Please use retryOptions to pass retry options at call time', - 'DeprecationWarning' - ) + 'DeprecationWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'noResponseRetries override is not supported. Please specify retry codes or a function to determine retry eligibility.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'currentRetryAttempt override is not supported. Retry attempts are tracked internally.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'objectMode override is not supported. It is set to true internally by default in gax.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); }); @@ -2326,18 +2326,18 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en assert(typeof settings.retryRequestOptions === 'undefined'); assert.strictEqual( settings.retry?.backoffSettings.maxRetryDelayMillis, - 70000 + 70000, ); assert.strictEqual( settings.retry?.backoffSettings.retryDelayMultiplier, - 3 + 3, ); assert.strictEqual( settings.retry?.backoffSettings.totalTimeoutMillis, - 650000 + 650000, ); assert( - typeof settings.retry?.backoffSettings.maxRetries === 'undefined' + typeof settings.retry?.backoffSettings.maxRetries === 'undefined', ); assert(settings.retry.shouldRetryFn); assert(settings.retry.retryCodes.length === 0); @@ -2360,7 +2360,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true // gaxStreamingRetries + true, // gaxStreamingRetries ); const passedRetryRequestOptions = { objectMode: false, @@ -2377,7 +2377,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en {}, { retryRequestOptions: passedRetryRequestOptions, - } + }, ); assert.strictEqual(warnStub.callCount, 4); @@ -2385,29 +2385,29 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en warnStub.calledWith( 'retry_request_options', 'retryRequestOptions will be deprecated in a future release. Please use retryOptions to pass retry options at call time', - 'DeprecationWarning' - ) + 'DeprecationWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'objectMode override is not supported. It is set to true internally by default in gax.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'noResponseRetries override is not supported. Please specify retry codes or a function to determine retry eligibility.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'currentRetryAttempt override is not supported. Retry attempts are tracked internally.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); }); @@ -2424,18 +2424,18 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en assert(typeof settings.retryRequestOptions === 'undefined'); assert.strictEqual( settings.retry?.backoffSettings.maxRetryDelayMillis, - 0 + 0, ); assert.strictEqual( settings.retry?.backoffSettings.retryDelayMultiplier, - 0 + 0, ); assert.strictEqual( settings.retry?.backoffSettings.totalTimeoutMillis, - 0 + 0, ); assert( - typeof settings.retry?.backoffSettings.maxRetries === 'undefined' + typeof settings.retry?.backoffSettings.maxRetries === 'undefined', ); assert(settings.retry.shouldRetryFn); assert(settings.retry.retryCodes.length === 0); @@ -2458,7 +2458,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true // gaxStreamingRetries + true, // gaxStreamingRetries ); const passedRetryRequestOptions = { objectMode: false, @@ -2475,7 +2475,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en {}, { retryRequestOptions: passedRetryRequestOptions, - } + }, ); assert.strictEqual(warnStub.callCount, 4); @@ -2483,29 +2483,29 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en warnStub.calledWith( 'retry_request_options', 'retryRequestOptions will be deprecated in a future release. Please use retryOptions to pass retry options at call time', - 'DeprecationWarning' - ) + 'DeprecationWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'objectMode override is not supported. It is set to true internally by default in gax.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'noResponseRetries override is not supported. Please specify retry codes or a function to determine retry eligibility.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'currentRetryAttempt override is not supported. Retry attempts are tracked internally.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); }); }); @@ -2535,7 +2535,7 @@ describe('warns/errors about server streaming retry behavior when gaxStreamingRe spy, streaming.StreamType.SERVER_STREAMING, false, - false // ensure we are NOT opted into the new retry behavior + false, // ensure we are NOT opted into the new retry behavior ); // make the call with neither retry option passed at call time @@ -2563,7 +2563,7 @@ describe('REST streaming apiCall return StreamArrayParser', () => { const apiCall = createApiCallStreaming( spy, streaming.StreamType.SERVER_STREAMING, - true + true, ); const s = apiCall({}, undefined); assert.strictEqual(s.readable, true); @@ -2575,7 +2575,7 @@ describe('REST streaming apiCall return StreamArrayParser', () => { s.on('end', () => { assert.strictEqual( JSON.stringify(actualResults), - JSON.stringify([{resources: [1, 2]}, {resources: [3, 4, 5]}]) + JSON.stringify([{resources: [1, 2]}, {resources: [3, 4, 5]}]), ); done(); }); @@ -2593,7 +2593,7 @@ describe('REST streaming apiCall return StreamArrayParser', () => { const apiCall = createApiCallStreaming( spy, streaming.StreamType.SERVER_STREAMING, - true + true, ); const s = apiCall({}, undefined); assert.strictEqual(s.readable, true); diff --git a/gax/test/unit/transcoding.ts b/gax/test/unit/transcoding.ts index 1293ce2ef..431ac5fa6 100644 --- a/gax/test/unit/transcoding.ts +++ b/gax/test/unit/transcoding.ts @@ -85,7 +85,7 @@ describe('gRPC to HTTP transcoding', () => { url: '/v3/projects/project/supportedLanguages', queryString: '', data: '', - } + }, ); assert.deepStrictEqual( @@ -95,46 +95,46 @@ describe('gRPC to HTTP transcoding', () => { url: '/v3/projects/project/supportedLanguages', queryString: 'field=value', data: '', - } + }, ); assert.deepStrictEqual( transcode( {parent: 'projects/project', field: 'value', a: 42}, - parsedOptions + parsedOptions, ), { httpMethod: 'get', url: '/v3/projects/project/supportedLanguages', queryString: 'field=value&a=42', data: '', - } + }, ); assert.deepStrictEqual( transcode( {parent: 'post1/project', field: 'value', a: 42}, - parsedOptions + parsedOptions, ), { httpMethod: 'post', url: '/v3/post1/project/supportedLanguages', queryString: '', data: {field: 'value', a: 42}, - } + }, ); assert.deepStrictEqual( transcode( {parent: 'post2/project', field: 'value', a: 42}, - parsedOptions + parsedOptions, ), { httpMethod: 'post', url: '/v3/post2/project/supportedLanguages', queryString: 'a=42', data: 'value', - } + }, ); assert.deepStrictEqual( @@ -144,7 +144,7 @@ describe('gRPC to HTTP transcoding', () => { url: '/v3/get/project/value/supportedLanguages', queryString: 'a=42', data: '', - } + }, ); // Checking camel-snake-case conversions @@ -155,14 +155,14 @@ describe('gRPC to HTTP transcoding', () => { snakeCaseBody: {snakeCaseField: 42}, fieldName: 'value', }, - parsedOptions + parsedOptions, ), { httpMethod: 'post', url: '/v3/a/first', queryString: 'fieldName=value', data: {snakeCaseField: 42}, - } + }, ); assert.deepStrictEqual( @@ -172,19 +172,19 @@ describe('gRPC to HTTP transcoding', () => { snakeCaseBody: {snakeCaseField: 42}, fieldName: 'value', }, - parsedOptions + parsedOptions, ), { httpMethod: 'post', url: '/v3/b/second', queryString: '', data: {snakeCaseBody: {snakeCaseField: 42}, fieldName: 'value'}, - } + }, ); assert.strictEqual( transcode({unknownField: 'project'}, parsedOptions), - undefined + undefined, ); }); @@ -217,7 +217,7 @@ describe('gRPC to HTTP transcoding', () => { parent: 'post1/project', IPProtocol: 'tcp', }, - parsedOptions + parsedOptions, ), { httpMethod: 'post', @@ -226,7 +226,7 @@ describe('gRPC to HTTP transcoding', () => { data: { IPProtocol: 'tcp', }, - } + }, ); assert.deepStrictEqual( transcode( @@ -235,14 +235,14 @@ describe('gRPC to HTTP transcoding', () => { IPProtocol: 'tcp', field: 'value', }, - parsedOptions + parsedOptions, ), { httpMethod: 'post', queryString: 'IPProtocol=tcp', url: '/v3/post2/project/supportedLanguages', data: 'value', - } + }, ); assert.deepStrictEqual( transcode( @@ -250,7 +250,7 @@ describe('gRPC to HTTP transcoding', () => { parent: 'post1/project', iPProtocol: 'tcp', }, - parsedOptions + parsedOptions, ), { httpMethod: 'post', @@ -259,7 +259,7 @@ describe('gRPC to HTTP transcoding', () => { data: { iPProtocol: 'tcp', }, - } + }, ); }); @@ -290,38 +290,38 @@ describe('gRPC to HTTP transcoding', () => { it('getField', () => { assert.strictEqual( getField({field: 'stringValue'}, 'field'), - 'stringValue' + 'stringValue', ); assert.strictEqual( getField({field: 'stringValue'}, 'nosuchfield'), - undefined + undefined, ); assert.strictEqual( getField({field: 'stringValue'}, 'field.subfield'), - undefined + undefined, ); assert.strictEqual( getField({field: {subfield: 'stringValue'}}, 'field.subfield'), - 'stringValue' + 'stringValue', ); assert.deepStrictEqual( getField({field: {subfield: [1, 2, 3]}}, 'field.subfield'), - [1, 2, 3] + [1, 2, 3], ); assert.strictEqual( getField({field: {subfield: 'stringValue'}}, 'field'), - undefined + undefined, ); assert.strictEqual( getField({field: {subfield: 'stringValue'}}, 'field.nosuchfield'), - undefined + undefined, ); assert.strictEqual( getField( {field: {subfield: {subsubfield: 'stringValue'}}}, - 'field.subfield.subsubfield' + 'field.subfield.subsubfield', ), - 'stringValue' + 'stringValue', ); }); @@ -364,9 +364,9 @@ describe('gRPC to HTTP transcoding', () => { assert.strictEqual(encodeWithSlashes('тест'), '%D1%82%D0%B5%D1%81%D1%82'); assert.strictEqual( encodeWithSlashes( - '_.~0-9abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/ ' + '_.~0-9abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/ ', ), - '_.~0-9abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%2F%20' + '_.~0-9abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%2F%20', ); }); @@ -374,13 +374,13 @@ describe('gRPC to HTTP transcoding', () => { assert.strictEqual(encodeWithoutSlashes('abcd'), 'abcd'); assert.strictEqual( encodeWithoutSlashes('тест'), - '%D1%82%D0%B5%D1%81%D1%82' + '%D1%82%D0%B5%D1%81%D1%82', ); assert.strictEqual( encodeWithoutSlashes( - '_.~0-9abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/ ' + '_.~0-9abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/ ', ), - '_.~0-9abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/%20' + '_.~0-9abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/%20', ); }); @@ -390,24 +390,24 @@ describe('gRPC to HTTP transcoding', () => { assert.strictEqual(applyPattern('fail', 'test'), undefined); assert.strictEqual( applyPattern('projects/*', 'projects/test'), - 'projects/test' + 'projects/test', ); assert.strictEqual( applyPattern('projects/*/locations/*', 'projects/test'), - undefined + undefined, ); assert.strictEqual(applyPattern('locations/*', 'projects/test'), undefined); assert.strictEqual( applyPattern('projects/*/locations/*', 'projects/test/locations/us'), - 'projects/test/locations/us' + 'projects/test/locations/us', ); assert.strictEqual( applyPattern('projects/*/locations/*', 'projects/test/locations/us/q/z'), - undefined + undefined, ); assert.strictEqual( applyPattern('projects/*/locations/**', 'projects/test/locations/us/q/z'), - 'projects/test/locations/us/q/z' + 'projects/test/locations/us/q/z', ); }); @@ -416,7 +416,7 @@ describe('gRPC to HTTP transcoding', () => { assert.deepStrictEqual(flattenObject({field: 'value'}), {field: 'value'}); assert.deepStrictEqual( flattenObject({field: 'value', nested: {subfield: 'subvalue'}}), - {field: 'value', 'nested.subfield': 'subvalue'} + {field: 'value', 'nested.subfield': 'subvalue'}, ); }); @@ -424,46 +424,46 @@ describe('gRPC to HTTP transcoding', () => { assert.deepStrictEqual( match( {parent: 'projects/te st', test: 'value'}, - '/v3/{parent=projects/*}/supportedLanguages' + '/v3/{parent=projects/*}/supportedLanguages', ), { matchedFields: ['parent'], url: '/v3/projects/te%20st/supportedLanguages', - } + }, ); assert.deepStrictEqual( match( {parent: 'projects/te st/locations/location', test: 'value'}, - '/v3/{parent=projects/*}/supportedLanguages' + '/v3/{parent=projects/*}/supportedLanguages', ), - undefined + undefined, ); assert.deepStrictEqual( match( {parent: 'projects/te st/locations/location', test: 'value'}, - '/v3/{parent=projects/*/locations/*}/supportedLanguages' + '/v3/{parent=projects/*/locations/*}/supportedLanguages', ), { matchedFields: ['parent'], url: '/v3/projects/te%20st/locations/location/supportedLanguages', - } + }, ); assert.deepStrictEqual( match( {parent: 'projects/te st', test: 'value'}, - '/v3/{parent=projects/*}/{field=*}/supportedLanguages' + '/v3/{parent=projects/*}/{field=*}/supportedLanguages', ), - undefined + undefined, ); assert.deepStrictEqual( match( {parent: 'projects/te st', test: 'value', field: 42}, - '/v3/{parent=projects/*}/{field=*}/supportedLanguages' + '/v3/{parent=projects/*}/{field=*}/supportedLanguages', ), { matchedFields: ['field', 'parent'], url: '/v3/projects/te%20st/42/supportedLanguages', - } + }, ); assert.deepStrictEqual( match( @@ -473,23 +473,23 @@ describe('gRPC to HTTP transcoding', () => { field: 'fields/field42', path: 'a/b,c/d', }, - '/v3/{parent=projects/*}/{field=fields/*}/{path=**}/supportedLanguages' + '/v3/{parent=projects/*}/{field=fields/*}/{path=**}/supportedLanguages', ), { matchedFields: ['path', 'field', 'parent'], url: '/v3/projects/te%20st/fields/field42/a/b%2Cc/d/supportedLanguages', - } + }, ); assert.deepStrictEqual( match({}, '/v3/{field.subfield}/supportedLanguages'), - undefined + undefined, ); assert.deepStrictEqual( match({field: {subfield: 42}}, '/v3/{field.subfield}/supportedLanguages'), { matchedFields: ['field.subfield'], url: '/v3/42/supportedLanguages', - } + }, ); }); @@ -503,7 +503,7 @@ describe('gRPC to HTTP transcoding', () => { }; const copy = deepCopyWithoutMatchedFields( request as RequestType, - new Set() + new Set(), ); assert.deepStrictEqual(copy, request); request.field.subfield = 43; @@ -532,7 +532,7 @@ describe('gRPC to HTTP transcoding', () => { }; const copy = deepCopyWithoutMatchedFields( request as RequestType, - new Set(['field.subfield']) + new Set(['field.subfield']), ); assert.deepStrictEqual(copy, expected); }); @@ -543,7 +543,7 @@ describe('gRPC to HTTP transcoding', () => { ]); assert.deepStrictEqual( buildQueryStringComponents({field: 'value', a: 42}), - ['field=value', 'a=42'] + ['field=value', 'a=42'], ); assert.deepStrictEqual( buildQueryStringComponents({ @@ -558,7 +558,7 @@ describe('gRPC to HTTP transcoding', () => { 'repeated=z%20z%20z', 'obj.subfield=string', 'obj.y=z', - ] + ], ); }); }); @@ -615,7 +615,7 @@ describe('override the HTTP rules in protoJson', () => { assert.deepStrictEqual(httpOptions.get, rule.get); assert.deepStrictEqual( httpOptions.additional_bindings, - rule.additional_bindings + rule.additional_bindings, ); } } @@ -645,7 +645,7 @@ describe('override the HTTP rules in protoJson', () => { }; assert(originAdditionalBindings()); const expectedAditionalBindings = originAdditionalBindings()!.concat( - httpRules[0].additional_bindings + httpRules[0].additional_bindings, ); overrideHttpRules(httpRules, root); for (const rule of httpRules) { @@ -660,7 +660,7 @@ describe('override the HTTP rules in protoJson', () => { assert.deepStrictEqual(httpOptions.get, rule.get); assert.deepStrictEqual( httpOptions.additional_bindings, - expectedAditionalBindings + expectedAditionalBindings, ); } } diff --git a/gax/test/unit/util.ts b/gax/test/unit/util.ts index 614e1c06f..386243bea 100644 --- a/gax/test/unit/util.ts +++ b/gax/test/unit/util.ts @@ -37,7 +37,7 @@ describe('util.ts', () => { assert.strictEqual(camelToSnakeCase('a.1B'), 'a.1_b'); assert.strictEqual( camelToSnakeCase('somethingABCDEValue`'), - 'something_a_b_c_d_e_value' + 'something_a_b_c_d_e_value', ); }); @@ -53,7 +53,7 @@ describe('util.ts', () => { assert.strictEqual(snakeToCamelCase('a.1_b'), 'a.1B'); assert.strictEqual( snakeToCamelCase('something_abcde_value'), - 'somethingAbcdeValue' + 'somethingAbcdeValue', ); }); @@ -69,15 +69,15 @@ describe('util.ts', () => { assert.strictEqual(toLowerCamelCase('a.1_b'), 'a.1B'); assert.strictEqual( toLowerCamelCase('something_abcde_value'), - 'somethingAbcdeValue' + 'somethingAbcdeValue', ); assert.strictEqual( toLowerCamelCase('PascalCaseString'), - 'pascalCaseString' + 'pascalCaseString', ); assert.strictEqual( toLowerCamelCase('PascalCASEString'), - 'pascalCaseString' + 'pascalCaseString', ); }); diff --git a/gax/test/unit/utils.ts b/gax/test/unit/utils.ts index 24f53d89f..664ec45f9 100644 --- a/gax/test/unit/utils.ts +++ b/gax/test/unit/utils.ts @@ -28,7 +28,7 @@ export function fail( argument: {}, metadata: {}, options: Options, - callback: Function + callback: Function, ) { const error = new GoogleError(); error.code = FAKE_STATUS_CODE_1; @@ -76,7 +76,7 @@ export function createApiCall(func: Function, opts?: Options) { }; }), settings, - descriptor + descriptor, ) as GaxCallPromise; } @@ -87,7 +87,7 @@ export function createRetryOptions( initialRpcTimeoutMillis?: number, rpcTimeoutMultiplier?: number, maxRpcTimeoutMillis?: number, - totalTimeoutMillis?: number + totalTimeoutMillis?: number, ) { const backoff = typeof backoffSettingsOrInitialRetryDelayMillis === 'number' @@ -98,7 +98,7 @@ export function createRetryOptions( initialRpcTimeoutMillis!, rpcTimeoutMultiplier!, maxRpcTimeoutMillis!, - totalTimeoutMillis! + totalTimeoutMillis!, ) : backoffSettingsOrInitialRetryDelayMillis; return gax.createRetryOptions([FAKE_STATUS_CODE_1], backoff); @@ -108,7 +108,7 @@ export function toProtobufJSON(protobufType: protobuf.Type, json: {}) { const message = serializer.fromProto3JSON(protobufType, json); if (!message) { throw new Error( - `Internal Error: fail to convert JSON to protobuf specific JSON, protobuf type: ${protobufType}` + `Internal Error: fail to convert JSON to protobuf specific JSON, protobuf type: ${protobufType}`, ); } return protobufType.toObject(message, defaultToObjectOptions); diff --git a/gax/test/unit/warning.ts b/gax/test/unit/warning.ts index 8453e8105..a79b50587 100644 --- a/gax/test/unit/warning.ts +++ b/gax/test/unit/warning.ts @@ -48,7 +48,7 @@ describe('warnings', () => { assert( stub.calledWith('messageD-1', { type: 'WarningType1', - }) + }), ); stub.restore(); done(); diff --git a/gax/webpack.config.js b/gax/webpack.config.js index 03705217e..83bf18ce5 100644 --- a/gax/webpack.config.js +++ b/gax/webpack.config.js @@ -28,12 +28,12 @@ module.exports = { '../../package.json': path.resolve(__dirname, 'package.json'), '../../protos/operations.json': path.resolve( __dirname, - 'protos/operations.json' + 'protos/operations.json', ), '../../protos/status.json': path.resolve(__dirname, 'protos/status.json'), '../../protos/iam_service.json': path.resolve( __dirname, - 'protos/iam_service.json' + 'protos/iam_service.json', ), }, }, From ebb485f1cd62b0f6b83c85205eace05bc9bab2ba Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Thu, 13 Feb 2025 00:28:44 -0800 Subject: [PATCH 48/64] attempt to fix linting problem --- gax/test/unit/apiCallable.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/gax/test/unit/apiCallable.ts b/gax/test/unit/apiCallable.ts index 1da92da4c..83b41f584 100644 --- a/gax/test/unit/apiCallable.ts +++ b/gax/test/unit/apiCallable.ts @@ -53,7 +53,7 @@ describe('createApiCall', () => { }); }); - it('is customized by call options', done => { + it('is customized by call options', async () => { function func( argument: {}, metadata: {}, @@ -62,14 +62,13 @@ describe('createApiCall', () => { ) { callback(null, options.deadline.getTime()); } - const apiCall = createApiCall(func, {settings: {timeout: 100}}); + const apiCall = await createApiCall(func, {settings: {timeout: 100}}); apiCall({}, {timeout: 200}, (err, resp) => { const now = new Date(); const originalDeadline = now.getTime() + 100; const expectedDeadline = now.getTime() + 200; assert((resp as unknown as number)! > originalDeadline); assert((resp as unknown as number)! <= expectedDeadline); - done(); }); }); From c2eacdedf581b8b731c035d9f0680896d8f637cb Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Thu, 13 Feb 2025 00:41:06 -0800 Subject: [PATCH 49/64] remove floating promises TS error for tests --- gax/test/unit/apiCallable.ts | 6 ++++-- gax/test/unit/bundling.ts | 1 + gax/test/unit/grpc-fallback.ts | 1 + gax/test/unit/grpc.ts | 1 + gax/test/unit/iamService.ts | 2 ++ gax/test/unit/locationService.ts | 1 + gax/test/unit/longrunning.ts | 1 + gax/test/unit/operationClient.ts | 2 ++ gax/test/unit/pagedIteration.ts | 1 + gax/test/unit/regapic.ts | 1 + 10 files changed, 15 insertions(+), 2 deletions(-) diff --git a/gax/test/unit/apiCallable.ts b/gax/test/unit/apiCallable.ts index 83b41f584..99b0fc930 100644 --- a/gax/test/unit/apiCallable.ts +++ b/gax/test/unit/apiCallable.ts @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +/* eslint-disable typescript-eslint/no-floating-promises */ import * as assert from 'assert'; import {status} from '@grpc/grpc-js'; @@ -53,7 +54,7 @@ describe('createApiCall', () => { }); }); - it('is customized by call options', async () => { + it('is customized by call options', done => { function func( argument: {}, metadata: {}, @@ -62,13 +63,14 @@ describe('createApiCall', () => { ) { callback(null, options.deadline.getTime()); } - const apiCall = await createApiCall(func, {settings: {timeout: 100}}); + const apiCall = createApiCall(func, {settings: {timeout: 100}}); apiCall({}, {timeout: 200}, (err, resp) => { const now = new Date(); const originalDeadline = now.getTime() + 100; const expectedDeadline = now.getTime() + 200; assert((resp as unknown as number)! > originalDeadline); assert((resp as unknown as number)! <= expectedDeadline); + done(); }); }); diff --git a/gax/test/unit/bundling.ts b/gax/test/unit/bundling.ts index 27bd077e4..a9fbb4599 100644 --- a/gax/test/unit/bundling.ts +++ b/gax/test/unit/bundling.ts @@ -16,6 +16,7 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ /* eslint-disable no-prototype-builtins */ +/* eslint-disable typescript-eslint/no-floating-promises */ import * as assert from 'assert'; import {status} from '@grpc/grpc-js'; diff --git a/gax/test/unit/grpc-fallback.ts b/gax/test/unit/grpc-fallback.ts index 227e50001..7a8240021 100644 --- a/gax/test/unit/grpc-fallback.ts +++ b/gax/test/unit/grpc-fallback.ts @@ -16,6 +16,7 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ /* eslint-disable no-undef */ +/* eslint-disable typescript-eslint/no-floating-promises */ import * as assert from 'assert'; import {describe, it, beforeEach, afterEach, before, after} from 'mocha'; diff --git a/gax/test/unit/grpc.ts b/gax/test/unit/grpc.ts index cc03e4c86..b29182389 100644 --- a/gax/test/unit/grpc.ts +++ b/gax/test/unit/grpc.ts @@ -17,6 +17,7 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ /* eslint-disable no-prototype-builtins */ /* eslint-disable @typescript-eslint/no-var-requires */ +/* eslint-disable typescript-eslint/no-floating-promises */ import * as assert from 'assert'; import * as os from 'os'; diff --git a/gax/test/unit/iamService.ts b/gax/test/unit/iamService.ts index 110a209ac..fbe50ea67 100644 --- a/gax/test/unit/iamService.ts +++ b/gax/test/unit/iamService.ts @@ -15,6 +15,8 @@ // ** This file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** +/* eslint-disable typescript-eslint/no-floating-promises */ + import * as protos from '../../protos/iam_service'; import * as assert from 'assert'; import * as sinon from 'sinon'; diff --git a/gax/test/unit/locationService.ts b/gax/test/unit/locationService.ts index 9afab554f..166bf473d 100644 --- a/gax/test/unit/locationService.ts +++ b/gax/test/unit/locationService.ts @@ -11,6 +11,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. +/* eslint-disable typescript-eslint/no-floating-promises */ import * as protos from '../../protos/locations'; import * as assert from 'assert'; diff --git a/gax/test/unit/longrunning.ts b/gax/test/unit/longrunning.ts index 2dcf43573..01eb4d265 100644 --- a/gax/test/unit/longrunning.ts +++ b/gax/test/unit/longrunning.ts @@ -15,6 +15,7 @@ */ /* eslint-disable no-prototype-builtins */ +/* eslint-disable typescript-eslint/no-floating-promises */ import * as assert from 'assert'; import {status} from '@grpc/grpc-js'; diff --git a/gax/test/unit/operationClient.ts b/gax/test/unit/operationClient.ts index 84a01d9cf..e3a27b5cc 100644 --- a/gax/test/unit/operationClient.ts +++ b/gax/test/unit/operationClient.ts @@ -15,6 +15,8 @@ // ** This file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** +/* eslint-disable typescript-eslint/no-floating-promises */ + import * as protos from '../../protos/operations'; import * as assert from 'assert'; import * as sinon from 'sinon'; diff --git a/gax/test/unit/pagedIteration.ts b/gax/test/unit/pagedIteration.ts index ff0c7a6fa..476d3e0d0 100644 --- a/gax/test/unit/pagedIteration.ts +++ b/gax/test/unit/pagedIteration.ts @@ -16,6 +16,7 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ /* eslint-disable no-prototype-builtins */ +/* eslint-disable typescript-eslint/no-floating-promises */ import * as assert from 'assert'; import * as pumpify from 'pumpify'; diff --git a/gax/test/unit/regapic.ts b/gax/test/unit/regapic.ts index b06b22605..89f95f1b1 100644 --- a/gax/test/unit/regapic.ts +++ b/gax/test/unit/regapic.ts @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +/* eslint-disable typescript-eslint/no-floating-promises */ import * as assert from 'assert'; import {describe, it, afterEach, before} from 'mocha'; From 93cdeaf4c0c8db1625b06281fbd15b78677730b3 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Thu, 13 Feb 2025 00:55:19 -0800 Subject: [PATCH 50/64] add @ sign to disable linting --- gax/test/unit/apiCallable.ts | 2 +- gax/test/unit/bundling.ts | 2 +- gax/test/unit/grpc-fallback.ts | 2 +- gax/test/unit/grpc.ts | 2 +- gax/test/unit/iamService.ts | 2 +- gax/test/unit/locationService.ts | 2 +- gax/test/unit/longrunning.ts | 2 +- gax/test/unit/operationClient.ts | 2 +- gax/test/unit/pagedIteration.ts | 2 +- gax/test/unit/regapic.ts | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/gax/test/unit/apiCallable.ts b/gax/test/unit/apiCallable.ts index 99b0fc930..20e82cb7d 100644 --- a/gax/test/unit/apiCallable.ts +++ b/gax/test/unit/apiCallable.ts @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* eslint-disable typescript-eslint/no-floating-promises */ +/* eslint-disable @typescript-eslint/no-floating-promises */ import * as assert from 'assert'; import {status} from '@grpc/grpc-js'; diff --git a/gax/test/unit/bundling.ts b/gax/test/unit/bundling.ts index a9fbb4599..878276186 100644 --- a/gax/test/unit/bundling.ts +++ b/gax/test/unit/bundling.ts @@ -16,7 +16,7 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ /* eslint-disable no-prototype-builtins */ -/* eslint-disable typescript-eslint/no-floating-promises */ +/* eslint-disable @typescript-eslint/no-floating-promises */ import * as assert from 'assert'; import {status} from '@grpc/grpc-js'; diff --git a/gax/test/unit/grpc-fallback.ts b/gax/test/unit/grpc-fallback.ts index 7a8240021..bfab76980 100644 --- a/gax/test/unit/grpc-fallback.ts +++ b/gax/test/unit/grpc-fallback.ts @@ -16,7 +16,7 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ /* eslint-disable no-undef */ -/* eslint-disable typescript-eslint/no-floating-promises */ +/* eslint-disable @typescript-eslint/no-floating-promises */ import * as assert from 'assert'; import {describe, it, beforeEach, afterEach, before, after} from 'mocha'; diff --git a/gax/test/unit/grpc.ts b/gax/test/unit/grpc.ts index b29182389..9fcdb1068 100644 --- a/gax/test/unit/grpc.ts +++ b/gax/test/unit/grpc.ts @@ -17,7 +17,7 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ /* eslint-disable no-prototype-builtins */ /* eslint-disable @typescript-eslint/no-var-requires */ -/* eslint-disable typescript-eslint/no-floating-promises */ +/* eslint-disable @typescript-eslint/no-floating-promises */ import * as assert from 'assert'; import * as os from 'os'; diff --git a/gax/test/unit/iamService.ts b/gax/test/unit/iamService.ts index fbe50ea67..d00b11e6a 100644 --- a/gax/test/unit/iamService.ts +++ b/gax/test/unit/iamService.ts @@ -15,7 +15,7 @@ // ** This file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -/* eslint-disable typescript-eslint/no-floating-promises */ +/* eslint-disable @typescript-eslint/no-floating-promises */ import * as protos from '../../protos/iam_service'; import * as assert from 'assert'; diff --git a/gax/test/unit/locationService.ts b/gax/test/unit/locationService.ts index 166bf473d..735d0f721 100644 --- a/gax/test/unit/locationService.ts +++ b/gax/test/unit/locationService.ts @@ -11,7 +11,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -/* eslint-disable typescript-eslint/no-floating-promises */ +/* eslint-disable @typescript-eslint/no-floating-promises */ import * as protos from '../../protos/locations'; import * as assert from 'assert'; diff --git a/gax/test/unit/longrunning.ts b/gax/test/unit/longrunning.ts index 01eb4d265..7bbb02d01 100644 --- a/gax/test/unit/longrunning.ts +++ b/gax/test/unit/longrunning.ts @@ -15,7 +15,7 @@ */ /* eslint-disable no-prototype-builtins */ -/* eslint-disable typescript-eslint/no-floating-promises */ +/* eslint-disable @typescript-eslint/no-floating-promises */ import * as assert from 'assert'; import {status} from '@grpc/grpc-js'; diff --git a/gax/test/unit/operationClient.ts b/gax/test/unit/operationClient.ts index e3a27b5cc..02f623b07 100644 --- a/gax/test/unit/operationClient.ts +++ b/gax/test/unit/operationClient.ts @@ -15,7 +15,7 @@ // ** This file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -/* eslint-disable typescript-eslint/no-floating-promises */ +/* eslint-disable @typescript-eslint/no-floating-promises */ import * as protos from '../../protos/operations'; import * as assert from 'assert'; diff --git a/gax/test/unit/pagedIteration.ts b/gax/test/unit/pagedIteration.ts index 476d3e0d0..b9f4d0054 100644 --- a/gax/test/unit/pagedIteration.ts +++ b/gax/test/unit/pagedIteration.ts @@ -16,7 +16,7 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ /* eslint-disable no-prototype-builtins */ -/* eslint-disable typescript-eslint/no-floating-promises */ +/* eslint-disable @typescript-eslint/no-floating-promises */ import * as assert from 'assert'; import * as pumpify from 'pumpify'; diff --git a/gax/test/unit/regapic.ts b/gax/test/unit/regapic.ts index 89f95f1b1..28a74bbe4 100644 --- a/gax/test/unit/regapic.ts +++ b/gax/test/unit/regapic.ts @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* eslint-disable typescript-eslint/no-floating-promises */ +/* eslint-disable @typescript-eslint/no-floating-promises */ import * as assert from 'assert'; import {describe, it, afterEach, before} from 'mocha'; From fd809ce41f7945ba92efc1c0f174e196b8edda4b Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Thu, 13 Feb 2025 01:06:02 -0800 Subject: [PATCH 51/64] chore: migrate tools to node 18 as well --- gax/src/iamService.ts | 1 + gax/src/locationService.ts | 1 + gax/src/operationsClient.ts | 1 + gax/src/paginationCalls/pageDescriptor.ts | 1 + gax/test/browser-test/webpack.config.js | 2 ++ gax/test/unit/grpc-fallback.ts | 1 + tools/package.json | 38 +++++++++++------------ 7 files changed, 26 insertions(+), 19 deletions(-) diff --git a/gax/src/iamService.ts b/gax/src/iamService.ts index 161b2ceca..dcb3e4717 100644 --- a/gax/src/iamService.ts +++ b/gax/src/iamService.ts @@ -15,6 +15,7 @@ // ** This file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** +/* eslint-disable @typescript-eslint/no-floating-promises */ import * as gax from './gax'; import type {GrpcClient, ClientStubOptions} from './grpc'; diff --git a/gax/src/locationService.ts b/gax/src/locationService.ts index 825c4a3cf..b46ab1832 100644 --- a/gax/src/locationService.ts +++ b/gax/src/locationService.ts @@ -11,6 +11,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. +/* eslint-disable @typescript-eslint/no-floating-promises */ /* global window */ import * as gax from './gax'; diff --git a/gax/src/operationsClient.ts b/gax/src/operationsClient.ts index a9920f911..4ac8ff714 100644 --- a/gax/src/operationsClient.ts +++ b/gax/src/operationsClient.ts @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +/* eslint-disable @typescript-eslint/no-floating-promises */ import type {GoogleAuth, OAuth2Client} from 'google-auth-library'; import {ProjectIdCallback} from 'google-auth-library/build/src/auth/googleauth'; diff --git a/gax/src/paginationCalls/pageDescriptor.ts b/gax/src/paginationCalls/pageDescriptor.ts index 9fc57c55d..ce738892a 100644 --- a/gax/src/paginationCalls/pageDescriptor.ts +++ b/gax/src/paginationCalls/pageDescriptor.ts @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +/* eslint-disable @typescript-eslint/no-floating-promises */ import {PassThrough, Transform} from 'stream'; diff --git a/gax/test/browser-test/webpack.config.js b/gax/test/browser-test/webpack.config.js index 143d71323..448e04819 100644 --- a/gax/test/browser-test/webpack.config.js +++ b/gax/test/browser-test/webpack.config.js @@ -13,6 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +/* eslint-disable n/no-missing-require */ + const webpack = require('webpack'); module.exports = { entry: './build/src/index.js', diff --git a/gax/test/unit/grpc-fallback.ts b/gax/test/unit/grpc-fallback.ts index bfab76980..a8f5099eb 100644 --- a/gax/test/unit/grpc-fallback.ts +++ b/gax/test/unit/grpc-fallback.ts @@ -209,6 +209,7 @@ describe('grpc-fallback', () => { }; if (hasAbortController) { + // eslint-ignore // @ts-ignore AbortController = FakeAbortController; } else { diff --git a/tools/package.json b/tools/package.json index 8b09bf223..1ce88c359 100644 --- a/tools/package.json +++ b/tools/package.json @@ -28,14 +28,14 @@ "author": "Google API Authors", "license": "Apache-2.0", "dependencies": { - "@babel/core": "^7.22.5", - "@babel/traverse": "^7.22.5", - "google-gax": "^4.3.2", + "@babel/core": "^7.26.8", + "@babel/traverse": "^7.26.8", + "google-gax": "^4.4.1", "google-proto-files": "^4.2.0", - "protobufjs-cli": "1.1.3", - "uglify-js": "^3.17.0", - "walk-up-path": "^3.0.1", - "walkdir": "^0.4.0" + "protobufjs-cli": "^1.1.3", + "uglify-js": "^3.19.3", + "walk-up-path": "^4.0.0", + "walkdir": "^0.4.1" }, "repository": { "type": "git", @@ -43,19 +43,19 @@ "directory": "gapic-tools" }, "devDependencies": { - "@babel/cli": "^7.22.5", - "@babel/types": "^7.22.5", - "@types/babel__core": "^7.20.1", - "@types/babel__traverse": "^7.20.1", - "@types/mocha": "^9.0.0", - "@types/ncp": "^2.0.1", - "@types/uglify-js": "^3.17.0", - "c8": "^9.0.0", - "gts": "^5.0.0", - "mocha": "^9.0.0", + "@babel/cli": "^7.26.4", + "@babel/types": "^7.26.8", + "@types/babel__core": "^7.20.5", + "@types/babel__traverse": "^7.20.6", + "@types/mocha": "^10.0.10", + "@types/ncp": "^2.0.8", + "@types/uglify-js": "^3.17.5", + "c8": "^10.1.3", + "gts": "^6.0.2", + "mocha": "^11.1.0", "ncp": "^2.0.0", - "protobufjs": "7.4.0", - "typescript": "^5.1.6" + "protobufjs": "^7.4.0", + "typescript": "^5.7.3" }, "engines": { "node": ">=18" From 3bd82aa204726384f02c47586547d68e18c8de0c Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Thu, 13 Feb 2025 01:17:25 -0800 Subject: [PATCH 52/64] downgrade walkup --- tools/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/package.json b/tools/package.json index 1ce88c359..ebc784307 100644 --- a/tools/package.json +++ b/tools/package.json @@ -34,7 +34,7 @@ "google-proto-files": "^4.2.0", "protobufjs-cli": "^1.1.3", "uglify-js": "^3.19.3", - "walk-up-path": "^4.0.0", + "walk-up-path": "^3.0.0", "walkdir": "^0.4.1" }, "repository": { From 75deabfde506c056cc0b7f741f92fdd966452bdb Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Thu, 13 Feb 2025 01:39:28 -0800 Subject: [PATCH 53/64] run lint --- gax/test/unit/grpc-fallback.ts | 3 +- tools/src/compileProtos.ts | 29 ++++++++-------- tools/src/listProtos.ts | 3 +- tools/src/minify.ts | 5 +-- tools/src/prepublish.ts | 2 +- tools/test/compileProtos.ts | 56 ++++++++++++++++-------------- tools/test/replaceESMMockingLib.ts | 2 +- 7 files changed, 53 insertions(+), 47 deletions(-) diff --git a/gax/test/unit/grpc-fallback.ts b/gax/test/unit/grpc-fallback.ts index a8f5099eb..60828243e 100644 --- a/gax/test/unit/grpc-fallback.ts +++ b/gax/test/unit/grpc-fallback.ts @@ -205,11 +205,11 @@ describe('grpc-fallback', () => { this.abortCalled = true; }; // @ts-ignore + // eslint-disable-next-line no-global-assign createdAbortControllers.push(this); }; if (hasAbortController) { - // eslint-ignore // @ts-ignore AbortController = FakeAbortController; } else { @@ -229,6 +229,7 @@ describe('grpc-fallback', () => { after(() => { if (hasAbortController) { // @ts-ignore + // eslint-disable-next-line no-global-assign AbortController = savedAbortController; } else { // @ts-ignore diff --git a/tools/src/compileProtos.ts b/tools/src/compileProtos.ts index 81c9981be..06e92890f 100644 --- a/tools/src/compileProtos.ts +++ b/tools/src/compileProtos.ts @@ -28,7 +28,7 @@ export const gaxProtos = path.join( require.resolve('google-gax'), '..', '..', - 'protos' + 'protos', ); const readdir = util.promisify(fs.readdir); const readFile = util.promisify(fs.readFile); @@ -95,7 +95,7 @@ function getAllEnums(dts: string): Set { let currentEnum = undefined; for (const line of lines) { const match = line.match( - /^\s*(?:export )?(namespace|class|interface|enum) (\w+) .*{/ + /^\s*(?:export )?(namespace|class|interface|enum) (\w+) .*{/, ); if (match) { const [, keyword, id] = match; @@ -144,7 +144,7 @@ function updateDtsTypes(dts: string, enums: Set): string { // enum: E => E|keyof typeof E to allow all string values replaced = replaced.replace( typeName, - `${typeName}|keyof typeof ${typeName}` + `${typeName}|keyof typeof ${typeName}`, ); } else if (typeName === 'Uint8Array') { // bytes: Uint8Array => Uint8Array|Buffer|string to allow base64-encoded strings @@ -170,14 +170,14 @@ function fixJsFile(js: string): string { // depend on protobufjs, so we re-export it from google-gax js = js.replace( 'import * as $protobuf from "protobufjs/minimal"', - 'import {protobufMinimal as $protobuf} from "google-gax/build/src/protobuf.js"' + 'import {protobufMinimal as $protobuf} from "google-gax/build/src/protobuf.js"', ); // 1. fix protobufjs require: we don't want the libraries to // depend on protobufjs, so we re-export it from google-gax js = js.replace( 'require("protobufjs/minimal")', - 'require("google-gax/build/src/protobuf").protobufMinimal' + 'require("google-gax/build/src/protobuf").protobufMinimal', ); // 2. add Apache license to the generated .js file @@ -192,7 +192,7 @@ function fixDtsFile(dts: string): string { // 1. fix for pbts output to make sure we import Long properly dts = dts.replace( 'import * as Long from "long";', - 'import Long = require("long");' + 'import Long = require("long");', ); if (!dts.match(/import Long = require/)) { dts = 'import Long = require("long");\n' + dts; @@ -202,7 +202,7 @@ function fixDtsFile(dts: string): string { // depend on protobufjs, so we re-export it from google-gax dts = dts.replace( 'import * as $protobuf from "protobufjs"', - 'import type {protobuf as $protobuf} from "google-gax"' + 'import type {protobuf as $protobuf} from "google-gax"', ); // 3. add Apache license to the generated .d.ts file @@ -223,7 +223,7 @@ function fixDtsFile(dts: string): string { */ async function buildListOfProtos( protoJsonFiles: string[], - esm?: boolean + esm?: boolean, ): Promise { const result: string[] = []; for (const file of protoJsonFiles) { @@ -233,7 +233,7 @@ async function buildListOfProtos( // If we're in ESM, we're going to be in a directory level below normal esm ? path.join(directory, '..', normalizePath(filePath)) - : path.join(directory, normalizePath(filePath)) + : path.join(directory, normalizePath(filePath)), ); result.push(...list); } @@ -259,7 +259,7 @@ interface CompileProtosOptions { async function compileProtos( rootName: string, protos: string[], - options: CompileProtosOptions + options: CompileProtosOptions, ): Promise { const extraArgs = []; if (options.keepCase) { @@ -439,16 +439,16 @@ export async function main(parameters: string[]): Promise { */ function usage() { console.log( - `Usage: node ${process.argv[1]} [--skip-json] [--esm] directory ...` + `Usage: node ${process.argv[1]} [--skip-json] [--esm] directory ...`, ); console.log( - `Finds all files matching ${PROTO_LIST_REGEX} in the given directories.` + `Finds all files matching ${PROTO_LIST_REGEX} in the given directories.`, ); console.log( - 'Each of those files should contain a JSON array of proto files used by the' + 'Each of those files should contain a JSON array of proto files used by the', ); console.log( - 'client library. Those proto files will be compiled to JSON using pbjs tool' + 'client library. Those proto files will be compiled to JSON using pbjs tool', ); console.log('from protobufjs.'); } @@ -460,5 +460,6 @@ if (require.main === module) { process.exit(1); } // argv[0] is node.js binary, argv[1] is script path + // eslint-disable-next-line @typescript-eslint/no-floating-promises main(process.argv.slice(2)); } diff --git a/tools/src/listProtos.ts b/tools/src/listProtos.ts index ae797919f..85d79fd8b 100644 --- a/tools/src/listProtos.ts +++ b/tools/src/listProtos.ts @@ -32,7 +32,7 @@ async function main(directory: string) { fs.writeFileSync( outputFile, - JSON.stringify(commonProtoFiles, null, 2) + '\n' + JSON.stringify(commonProtoFiles, null, 2) + '\n', ); } /** @@ -46,5 +46,6 @@ if (require.main === module) { if (process.argv.length < 3 || process.argv[2] === '--help') { usage(); } + // eslint-disable-next-line @typescript-eslint/no-floating-promises main(process.argv[2]); } diff --git a/tools/src/minify.ts b/tools/src/minify.ts index d12931314..08c71f51c 100644 --- a/tools/src/minify.ts +++ b/tools/src/minify.ts @@ -60,10 +60,10 @@ export async function main(directory?: string) { function usage() { console.log(`Usage: node ${process.argv[1]} [directory]`); console.log( - 'Minifies all JSON files in-place in the given directory (non-recursively).' + 'Minifies all JSON files in-place in the given directory (non-recursively).', ); console.log( - 'If no directory is given, minifies JSON files in ./build/protos.' + 'If no directory is given, minifies JSON files in ./build/protos.', ); } @@ -76,5 +76,6 @@ if (require.main === module) { process.exit(1); } + // eslint-disable-next-line @typescript-eslint/no-floating-promises main(process.argv[2]); } diff --git a/tools/src/prepublish.ts b/tools/src/prepublish.ts index 371a9b77e..4f1d750c8 100755 --- a/tools/src/prepublish.ts +++ b/tools/src/prepublish.ts @@ -70,6 +70,6 @@ if (require.main === module) { // eslint-disable-next-line n/no-process-exit process.exit(1); } - + // eslint-disable-next-line @typescript-eslint/no-floating-promises main(process.argv[2]); } diff --git a/tools/test/compileProtos.ts b/tools/test/compileProtos.ts index e5704e8c7..a30ccdcd5 100644 --- a/tools/test/compileProtos.ts +++ b/tools/test/compileProtos.ts @@ -93,12 +93,12 @@ describe('compileProtos tool', () => { assert(js.toString().includes('TestMessage')); assert(js.toString().includes('LibraryService')); assert( - js.toString().includes('http://www.apache.org/licenses/LICENSE-2.0') + js.toString().includes('http://www.apache.org/licenses/LICENSE-2.0'), ); assert( js .toString() - .includes('require("google-gax/build/src/protobuf").protobufMinimal') + .includes('require("google-gax/build/src/protobuf").protobufMinimal'), ); assert(!js.toString().includes('require("protobufjs/minimal")')); @@ -111,12 +111,12 @@ describe('compileProtos tool', () => { assert(ts.toString().includes('import Long = require')); assert(!ts.toString().includes('import * as Long')); assert( - ts.toString().includes('http://www.apache.org/licenses/LICENSE-2.0') + ts.toString().includes('http://www.apache.org/licenses/LICENSE-2.0'), ); assert( ts .toString() - .includes('import type {protobuf as $protobuf} from "google-gax"') + .includes('import type {protobuf as $protobuf} from "google-gax"'), ); assert(!ts.toString().includes('import * as $protobuf from "protobufjs"')); }); @@ -138,12 +138,12 @@ describe('compileProtos tool', () => { assert(cjs.toString().includes('TestMessage')); assert(cjs.toString().includes('LibraryService')); assert( - cjs.toString().includes('http://www.apache.org/licenses/LICENSE-2.0') + cjs.toString().includes('http://www.apache.org/licenses/LICENSE-2.0'), ); assert( cjs .toString() - .includes('require("google-gax/build/src/protobuf").protobufMinimal') + .includes('require("google-gax/build/src/protobuf").protobufMinimal'), ); assert(!cjs.toString().includes('require("protobufjs/minimal")')); @@ -154,18 +154,20 @@ describe('compileProtos tool', () => { assert(js.toString().includes('TestMessage')); assert(js.toString().includes('LibraryService')); assert( - js.toString().includes('http://www.apache.org/licenses/LICENSE-2.0') + js.toString().includes('http://www.apache.org/licenses/LICENSE-2.0'), ); assert( js .toString() .includes( - 'import {protobufMinimal as $protobuf} from "google-gax/build/src/protobuf.js"' - ) + 'import {protobufMinimal as $protobuf} from "google-gax/build/src/protobuf.js"', + ), ); assert(!js.toString().includes('require("protobufjs/minimal")')); assert( - !js.toString().includes('import * as $protobuf from "protobufjs/minimal"') + !js + .toString() + .includes('import * as $protobuf from "protobufjs/minimal"'), ); // check that it uses proper root object; it's taken from fixtures/package.json @@ -177,12 +179,12 @@ describe('compileProtos tool', () => { assert(ts.toString().includes('import Long = require')); assert(!ts.toString().includes('import * as Long')); assert( - ts.toString().includes('http://www.apache.org/licenses/LICENSE-2.0') + ts.toString().includes('http://www.apache.org/licenses/LICENSE-2.0'), ); assert( ts .toString() - .includes('import type {protobuf as $protobuf} from "google-gax"') + .includes('import type {protobuf as $protobuf} from "google-gax"'), ); assert(!ts.toString().includes('import * as $protobuf from "protobufjs"')); }); @@ -198,12 +200,12 @@ describe('compileProtos tool', () => { assert(js.toString().includes('TestMessage')); assert(js.toString().includes('LibraryService')); assert( - js.toString().includes('http://www.apache.org/licenses/LICENSE-2.0') + js.toString().includes('http://www.apache.org/licenses/LICENSE-2.0'), ); assert( js .toString() - .includes('require("google-gax/build/src/protobuf").protobufMinimal') + .includes('require("google-gax/build/src/protobuf").protobufMinimal'), ); assert(!js.toString().includes('require("protobufjs/minimal")')); @@ -216,12 +218,12 @@ describe('compileProtos tool', () => { assert(ts.toString().includes('import Long = require')); assert(!ts.toString().includes('import * as Long')); assert( - ts.toString().includes('http://www.apache.org/licenses/LICENSE-2.0') + ts.toString().includes('http://www.apache.org/licenses/LICENSE-2.0'), ); assert( ts .toString() - .includes('import type {protobuf as $protobuf} from "google-gax"') + .includes('import type {protobuf as $protobuf} from "google-gax"'), ); assert(!ts.toString().includes('import * as $protobuf from "protobufjs"')); }); @@ -239,43 +241,43 @@ describe('compileProtos tool', () => { assert(ts.toString().includes('import Long = require')); assert(!ts.toString().includes('import * as Long')); assert( - ts.toString().includes('http://www.apache.org/licenses/LICENSE-2.0') + ts.toString().includes('http://www.apache.org/licenses/LICENSE-2.0'), ); assert(ts.toString().includes('longField?: (number|Long|string|null);')); assert( - ts.toString().includes('bytesField?: (Uint8Array|Buffer|string|null);') + ts.toString().includes('bytesField?: (Uint8Array|Buffer|string|null);'), ); assert( ts .toString() .includes( - 'enumField?: (google.TestEnum|keyof typeof google.TestEnum|null);' - ) + 'enumField?: (google.TestEnum|keyof typeof google.TestEnum|null);', + ), ); assert( ts .toString() .includes( - '"case"?: (google.TestEnum|keyof typeof google.TestEnum|null);' - ) + '"case"?: (google.TestEnum|keyof typeof google.TestEnum|null);', + ), ); assert(ts.toString().includes('public longField: (number|Long|string);')); assert( - ts.toString().includes('public bytesField: (Uint8Array|Buffer|string);') + ts.toString().includes('public bytesField: (Uint8Array|Buffer|string);'), ); assert( ts .toString() .includes( - 'public enumField: (google.TestEnum|keyof typeof google.TestEnum);' - ) + 'public enumField: (google.TestEnum|keyof typeof google.TestEnum);', + ), ); assert( ts .toString() .includes( - 'public case: (google.TestEnum|keyof typeof google.TestEnum);' - ) + 'public case: (google.TestEnum|keyof typeof google.TestEnum);', + ), ); }); diff --git a/tools/test/replaceESMMockingLib.ts b/tools/test/replaceESMMockingLib.ts index 51aa7d565..cd41a46ec 100644 --- a/tools/test/replaceESMMockingLib.ts +++ b/tools/test/replaceESMMockingLib.ts @@ -101,7 +101,7 @@ describe('replace ESM mocking lib', () => { assert.strictEqual( result?.code?.replace(/(\r\n|\n|\r)/gm, '').replace(' ', ''), - expected + expected, ); }); From 99825f5354632849f0a7cae077e1e22b5c263dfe Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Thu, 13 Feb 2025 01:43:57 -0800 Subject: [PATCH 54/64] fix lint --- gax/test/unit/grpc-fallback.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gax/test/unit/grpc-fallback.ts b/gax/test/unit/grpc-fallback.ts index 60828243e..3d6879e76 100644 --- a/gax/test/unit/grpc-fallback.ts +++ b/gax/test/unit/grpc-fallback.ts @@ -205,12 +205,12 @@ describe('grpc-fallback', () => { this.abortCalled = true; }; // @ts-ignore - // eslint-disable-next-line no-global-assign createdAbortControllers.push(this); }; if (hasAbortController) { // @ts-ignore + // eslint-disable-next-line no-global-assign AbortController = FakeAbortController; } else { // @ts-ignore From 2d48dbb80d6aaa7cebf4bdc241100130399b6e56 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Fri, 14 Feb 2025 17:14:17 -0800 Subject: [PATCH 55/64] attempt to upgrade node-fetch to v3 --- gax/package.json | 2 +- gax/src/fallback.ts | 2 +- gax/src/fallbackServiceStub.ts | 11 +- gax/src/grpc.ts | 4 +- gax/test/system-test/test.clientlibs.ts | 2 +- gax/test/test-application/src/index.ts | 2 +- gax/test/unit/apiCallable.ts | 2 +- gax/test/unit/bundling.ts | 2 +- gax/test/unit/exports.ts | 2 +- gax/test/unit/fallbackError.ts | 2 +- gax/test/unit/gax.ts | 2 +- gax/test/unit/googleError.ts | 2 +- gax/test/unit/grpc-fallback.ts | 191 +++--- gax/test/unit/grpc.ts | 33 +- gax/test/unit/iamService.ts | 2 +- gax/test/unit/locationService.ts | 2 +- gax/test/unit/longrunning.ts | 2 +- gax/test/unit/operationClient.ts | 2 +- gax/test/unit/pagedIteration.ts | 4 +- gax/test/unit/pathTemplate.ts | 2 +- gax/test/unit/regapic.ts | 756 ++++++++++++------------ gax/test/unit/routingHeader.ts | 2 +- gax/test/unit/status.ts | 2 +- gax/test/unit/streamArrayParser.ts | 2 +- gax/test/unit/streaming.ts | 2 +- gax/test/unit/transcoding.ts | 2 +- gax/test/unit/util.ts | 2 +- gax/test/unit/warning.ts | 2 +- gax/tsconfig.json | 6 +- 29 files changed, 553 insertions(+), 496 deletions(-) diff --git a/gax/package.json b/gax/package.json index 65872b542..84c92a6d1 100644 --- a/gax/package.json +++ b/gax/package.json @@ -16,7 +16,7 @@ "abort-controller": "^3.0.0", "duplexify": "^4.1.3", "google-auth-library": "^9.15.1", - "node-fetch": "^2.7.0", + "node-fetch": "^3.3.2", "object-hash": "^3.0.0", "proto3-json-serializer": "^2.0.2", "protobufjs": "^7.4.0", diff --git a/gax/src/fallback.ts b/gax/src/fallback.ts index 5b73d0ceb..0d156c879 100644 --- a/gax/src/fallback.ts +++ b/gax/src/fallback.ts @@ -15,7 +15,7 @@ */ import {OutgoingHttpHeaders} from 'http'; -import * as objectHash from 'object-hash'; +import objectHash from 'object-hash'; import * as protobuf from 'protobufjs'; import * as gax from './gax'; import * as routingHeader from './routingHeader'; diff --git a/gax/src/fallbackServiceStub.ts b/gax/src/fallbackServiceStub.ts index f38b1507c..37ad9e2c0 100644 --- a/gax/src/fallbackServiceStub.ts +++ b/gax/src/fallbackServiceStub.ts @@ -17,17 +17,17 @@ /* global window */ /* global AbortController */ -import nodeFetch from 'node-fetch'; -import {Response as NodeFetchResponse, RequestInit} from 'node-fetch'; +import type {Response as NodeFetchResponse, RequestInit} from 'node-fetch' with {'resolution-mode': 'import'}; import {AbortController as NodeAbortController} from 'abort-controller'; - +import type nodeFetch from 'node-fetch' with {'resolution-mode': 'import'}; import {hasWindowFetch, hasAbortController, isNodeJS} from './featureDetection'; import {AuthClient} from './fallback'; import {StreamArrayParser} from './streamArrayParser'; import {pipeline, PipelineSource} from 'stream'; import type {Agent as HttpAgent} from 'http'; import type {Agent as HttpsAgent} from 'https'; - +const fetchNode = (...args: Parameters) => + import('node-fetch').then(({default: fetch}) => fetch(...args)); interface NodeFetchType { (url: RequestInfo, init?: RequestInit): Promise; } @@ -96,7 +96,7 @@ export function generateServiceStub( ) { const fetch = hasWindowFetch() ? window.fetch - : (nodeFetch as unknown as NodeFetchType); + : (fetchNode as unknown as NodeFetchType); const serviceStub: FallbackServiceStub = { // close method should close all cancel controllers. If this feature request in the future, we can have a cancelControllerFactory that tracks created cancel controllers, and abort them all in close method. @@ -161,7 +161,6 @@ export function generateServiceStub( body: fetchParameters.body as | string | Buffer - | Uint8Array | undefined, method: fetchParameters.method, signal: cancelSignal, diff --git a/gax/src/grpc.ts b/gax/src/grpc.ts index fb828bf0b..37c9a693a 100644 --- a/gax/src/grpc.ts +++ b/gax/src/grpc.ts @@ -24,7 +24,7 @@ import {join} from 'path'; import {OutgoingHttpHeaders} from 'http'; import * as path from 'path'; import * as protobuf from 'protobufjs'; -import * as objectHash from 'object-hash'; +import objectHash from 'object-hash'; import * as gax from './gax'; import {ClientOptions} from '@grpc/grpc-js/build/src/client'; @@ -37,7 +37,7 @@ INCLUDE_DIRS.push(googleProtoFilesDir); // COMMON_PROTO_FILES logic is here for protobufjs loads (see // GoogleProtoFilesRoot below) -import * as commonProtoFiles from './protosList.json'; +import commonProtoFiles from './protosList.json'; import {google} from '../protos/http'; // use the correct path separator for the OS we are running on const COMMON_PROTO_FILES: string[] = commonProtoFiles.map(file => diff --git a/gax/test/system-test/test.clientlibs.ts b/gax/test/system-test/test.clientlibs.ts index e7b4c95b8..56867dbce 100644 --- a/gax/test/system-test/test.clientlibs.ts +++ b/gax/test/system-test/test.clientlibs.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as execa from 'execa'; +import execa from 'execa'; import * as fs from 'fs'; import * as fsp from 'fs/promises'; import * as path from 'path'; diff --git a/gax/test/test-application/src/index.ts b/gax/test/test-application/src/index.ts index 2ea9530e8..4410ac0b7 100644 --- a/gax/test/test-application/src/index.ts +++ b/gax/test/test-application/src/index.ts @@ -17,7 +17,7 @@ 'use strict'; import {EchoClient, SequenceServiceClient, protos} from 'showcase-echo-client'; import {ShowcaseServer} from 'showcase-server'; -import * as assert from 'assert'; +import assert from 'assert'; import {promises as fsp} from 'fs'; import * as path from 'path'; import { diff --git a/gax/test/unit/apiCallable.ts b/gax/test/unit/apiCallable.ts index 20e82cb7d..c756ec8fa 100644 --- a/gax/test/unit/apiCallable.ts +++ b/gax/test/unit/apiCallable.ts @@ -15,7 +15,7 @@ */ /* eslint-disable @typescript-eslint/no-floating-promises */ -import * as assert from 'assert'; +import assert from 'assert'; import {status} from '@grpc/grpc-js'; import {afterEach, describe, it} from 'mocha'; import * as sinon from 'sinon'; diff --git a/gax/test/unit/bundling.ts b/gax/test/unit/bundling.ts index 878276186..d2523dee0 100644 --- a/gax/test/unit/bundling.ts +++ b/gax/test/unit/bundling.ts @@ -18,7 +18,7 @@ /* eslint-disable no-prototype-builtins */ /* eslint-disable @typescript-eslint/no-floating-promises */ -import * as assert from 'assert'; +import assert from 'assert'; import {status} from '@grpc/grpc-js'; import * as sinon from 'sinon'; import {describe, it, beforeEach} from 'mocha'; diff --git a/gax/test/unit/exports.ts b/gax/test/unit/exports.ts index 032ddc574..8132209b4 100644 --- a/gax/test/unit/exports.ts +++ b/gax/test/unit/exports.ts @@ -16,7 +16,7 @@ import * as index from '../../src/index'; import * as fallback from '../../src/fallback'; -import * as assert from 'assert'; +import assert from 'assert'; import {describe, it} from 'mocha'; const version = require('../../../package.json').version; diff --git a/gax/test/unit/fallbackError.ts b/gax/test/unit/fallbackError.ts index c79b5c528..ad2479a55 100644 --- a/gax/test/unit/fallbackError.ts +++ b/gax/test/unit/fallbackError.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import assert from 'assert'; import {describe, it} from 'mocha'; import * as fs from 'fs'; import * as path from 'path'; diff --git a/gax/test/unit/gax.ts b/gax/test/unit/gax.ts index 1dee1c5ea..214b3d07d 100644 --- a/gax/test/unit/gax.ts +++ b/gax/test/unit/gax.ts @@ -22,7 +22,7 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ -import * as assert from 'assert'; +import assert from 'assert'; import {describe, it} from 'mocha'; import * as gax from '../../src/gax'; diff --git a/gax/test/unit/googleError.ts b/gax/test/unit/googleError.ts index 6166177a4..47b8a8523 100644 --- a/gax/test/unit/googleError.ts +++ b/gax/test/unit/googleError.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import assert from 'assert'; import {describe, it} from 'mocha'; import * as fs from 'fs'; import * as util from 'util'; diff --git a/gax/test/unit/grpc-fallback.ts b/gax/test/unit/grpc-fallback.ts index 3d6879e76..5ead3e8bf 100644 --- a/gax/test/unit/grpc-fallback.ts +++ b/gax/test/unit/grpc-fallback.ts @@ -18,15 +18,15 @@ /* eslint-disable no-undef */ /* eslint-disable @typescript-eslint/no-floating-promises */ -import * as assert from 'assert'; +import assert from 'assert'; import {describe, it, beforeEach, afterEach, before, after} from 'mocha'; -import * as nodeFetch from 'node-fetch'; import * as abortController from 'abort-controller'; import * as protobuf from 'protobufjs'; import * as sinon from 'sinon'; import echoProtoJson = require('../fixtures/echo.json'); import {GrpcClient} from '../../src/fallback'; import {GoogleError} from '../../src'; +import proxyquire from 'proxyquire'; // @ts-ignore const hasAbortController = typeof AbortController !== 'undefined'; @@ -277,34 +277,37 @@ describe('grpc-fallback', () => { const headers = metadataBuilder(); assert(headers['x-goog-api-client'][0].match('grpc-web/')); }); - - it('should make a request', done => { + it('should make a request', async () => { const requestObject = {content: 'test-content'}; const responseType = protos.lookupType('EchoResponse'); const response = responseType.create(requestObject); // request === response for EchoService - //@ts-ignore - sinon.stub(nodeFetch, 'Promise').returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(response))); - }, - }), - ); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { - echoStub.echo(requestObject, {}, {}, (err?: Error, result?: {}) => { - assert.strictEqual(err, null); - assert.strictEqual( - requestObject.content, - (result as {content: string}).content, - ); - done(); - }); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(response))); + }, + }); + }, }); + + const gaxGrpcMock = new GrpcClient(); + gaxGrpcMock + .createStub(echoService, stubOptions) + .then((echoStub: {echo: any}) => { + echoStub.echo(requestObject, {}, {}, (err?: Error, result?: {}) => { + assert.strictEqual(err, null); + assert.strictEqual( + requestObject.content, + (result as {content: string}).content + ); + }); + }); }); - it('should handle an API error', done => { + it('should handle an API error', async () => { const requestObject = {content: 'test-content'}; // example of an actual google.rpc.Status error message returned by Language API const expectedMessage = @@ -337,63 +340,51 @@ describe('grpc-fallback', () => { }, ], }; - //@ts-ignore - sinon.stub(nodeFetch, 'Promise').returns( - Promise.resolve({ - ok: false, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(jsonError))); - }, - }), - ); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { + + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(jsonError))); + }, + }); + }, + }); + + const gaxGrpcMock = new GrpcClient(); + + gaxGrpcMock.createStub(echoService, stubOptions).then((echoStub: any) => { echoStub.echo(requestObject, {}, {}, (err?: Error) => { assert(err instanceof GoogleError); assert.strictEqual(err.message, expectedMessage); assert.strictEqual(err.code, expectedError.code); assert.strictEqual( JSON.stringify(err.statusDetails), - JSON.stringify(expectedError.details), + JSON.stringify(expectedError.details) ); - done(); }); }); }); - it('should handle a null response from the API ', done => { + + it('should handle a fetch error', async () => { const requestObject = {content: 'test-content'}; - const expectedMessage = 'Received null response from RPC Echo'; - - //@ts-ignore - sinon.stub(nodeFetch, 'Promise').returns( - Promise.resolve({ - ok: false, - arrayBuffer: () => { - return Promise.resolve(Buffer.from('')); - }, - }), - ); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { - echoStub.echo(requestObject, {}, {}, (err?: Error) => { - assert(err instanceof Error); - assert.strictEqual(err.message, expectedMessage); - done(); - }); + + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.reject(new Error('fetch error')); + }, }); - }); - it('should handle a fetch error', done => { - const requestObject = {content: 'test-content'}; - //@ts-ignore - sinon.stub(nodeFetch, 'Promise').rejects(new Error('fetch error')); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { + const gaxGrpcMock = new GrpcClient(); + gaxGrpcMock.createStub(echoService, stubOptions).then((echoStub: any) => { echoStub.echo(requestObject, {}, {}, (err?: Error) => { assert.strictEqual(err?.message, 'fetch error'); - done(); }); }); }); - it('should promote ErrorInfo if exist in fallback-rest error', done => { + it('should promote ErrorInfo if exist in fallback-rest error', async () => { const requestObject = {content: 'test-content'}; // example of an actual google.rpc.Status error message returned by Translate API const errorInfo = { @@ -429,23 +420,26 @@ describe('grpc-fallback', () => { auth: authStub, fallback: 'rest', }; - // @ts-ignore incomplete options - gaxGrpc = new GrpcClient(opts); - //@ts-ignore - sinon.stub(nodeFetch, 'Promise').returns( - Promise.resolve({ - ok: false, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(serverError))); - }, - }), - ); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { + + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(serverError))); + }, + }); + }, + }); + + const gaxGrpcMock = new GrpcClient(opts); + + gaxGrpcMock.createStub(echoService, stubOptions).then((echoStub: any) => { echoStub.echo(requestObject, {}, {}, (err?: Error) => { assert(err instanceof GoogleError); assert.strictEqual( JSON.stringify(err.statusDetails?.length), - JSON.stringify(serverError['error']['details'].length), + JSON.stringify(serverError['error']['details'].length) ); assert.strictEqual(err.code, 7); assert.strictEqual(err.message, serverError['error']['message']); @@ -453,33 +447,56 @@ describe('grpc-fallback', () => { assert.strictEqual(err.domain, errorInfo.domain); assert.strictEqual( JSON.stringify(err.errorInfoMetadata), - JSON.stringify(errorInfo.metadata), + JSON.stringify(errorInfo.metadata) ); - done(); }); }); }); it('should be able to cancel an API call using AbortController', async () => { - // @ts-ignore - sinon.stub(nodeFetch, 'Promise').returns(Promise.resolve({})); + const opts = { + auth: authStub, + fallback: 'rest', + }; + + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify({}))); + }, + }); + }, + }); + + const gaxGrpcMock = new GrpcClient(opts); + const echoStub = await gaxGrpcMock.createStub(echoService, stubOptions); - const echoStub = await gaxGrpc.createStub(echoService, stubOptions); const request = {content: 'content' + new Date().toString()}; const call = echoStub.echo(request, {}, {}, () => {}); call.cancel(); - // @ts-ignore - assert.strictEqual(createdAbortControllers[0].abortCalled, true); + assert.strictEqual((createdAbortControllers[0] as any).abortCalled, true); }); - it('should have close method', done => { - // @ts-ignore - sinon.stub(nodeFetch, 'Promise').returns(Promise.resolve({})); - gaxGrpc.createStub(echoService, stubOptions).then(stub => { + it('should have close method', async () => { + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve({}); + }, + }); + }, + }); + + const gaxGrpcMock = new GrpcClient(); + + gaxGrpcMock.createStub(echoService, stubOptions).then((stub: any) => { stub.close({}, {}, {}, () => {}); - done(); }); }); -}); +}); \ No newline at end of file diff --git a/gax/test/unit/grpc.ts b/gax/test/unit/grpc.ts index 9fcdb1068..859b219e7 100644 --- a/gax/test/unit/grpc.ts +++ b/gax/test/unit/grpc.ts @@ -19,10 +19,10 @@ /* eslint-disable @typescript-eslint/no-var-requires */ /* eslint-disable @typescript-eslint/no-floating-promises */ -import * as assert from 'assert'; +import assert from 'assert'; import * as os from 'os'; import * as path from 'path'; -import * as proxyquire from 'proxyquire'; +import proxyquire from 'proxyquire'; import * as sinon from 'sinon'; import {mkdirSync, writeFileSync} from 'fs'; import * as fsp from 'fs/promises'; @@ -677,11 +677,17 @@ dvorak mkdirSync(tmpdir, {recursive: true}); const metadataFile = path.join(tmpdir, 'context_aware_metadata.json'); writeFileSync(metadataFile, JSON.stringify(metadataFileContents), 'utf8'); - sandbox.stub(os, 'homedir').returns(tmpFolder); // Create a client and test the certificate detection flow: process.env.GOOGLE_API_USE_CLIENT_CERTIFICATE = 'true'; - const client = gaxGrpc(); - const [cert, key] = await client._detectClientCertificate(); + const {GrpcClient} = await proxyquire('../../src/grpc.js', { + os: { + homedir: () => { + return tmpFolder; + }, + }, + }); + const clientMock = new GrpcClient(); + const [cert, key] = await clientMock._detectClientCertificate(); assert.ok(cert.includes('qwerty')); assert.ok(key.includes('dvorak')); await fsp.rm(tmpFolder, {recursive: true, force: true}); // Cleanup. @@ -694,14 +700,21 @@ dvorak mkdirSync(tmpdir, {recursive: true}); const metadataFile = path.join(tmpdir, 'context_aware_metadata.json'); writeFileSync(metadataFile, JSON.stringify(metadataFileContents), 'utf8'); - sandbox.stub(os, 'homedir').returns(tmpFolder); + + process.env.GOOGLE_API_USE_CLIENT_CERTIFICATE = 'true'; + const {GrpcClient} = await proxyquire('../../src/grpc.js', { + os: { + homedir: () => { + return tmpFolder; + }, + }, + }); // Create a client and test the certificate detection flow: process.env.GOOGLE_API_USE_CLIENT_CERTIFICATE = 'true'; - const client = gaxGrpc(); + const clientMock = new GrpcClient(); assert.rejects( - // @ts-ignore - client.createStub(DummyStub, {universeDomain: 'example.com'}), - /configured universe domain/, + clientMock.createStub(DummyStub, {universeDomain: 'example.com'}), + /configured universe domain/ ); await fsp.rm(tmpFolder, {recursive: true, force: true}); // Cleanup. }); diff --git a/gax/test/unit/iamService.ts b/gax/test/unit/iamService.ts index d00b11e6a..b54e9b59c 100644 --- a/gax/test/unit/iamService.ts +++ b/gax/test/unit/iamService.ts @@ -18,7 +18,7 @@ /* eslint-disable @typescript-eslint/no-floating-promises */ import * as protos from '../../protos/iam_service'; -import * as assert from 'assert'; +import assert from 'assert'; import * as sinon from 'sinon'; import {SinonStub} from 'sinon'; import {describe, it} from 'mocha'; diff --git a/gax/test/unit/locationService.ts b/gax/test/unit/locationService.ts index 735d0f721..31bfefc56 100644 --- a/gax/test/unit/locationService.ts +++ b/gax/test/unit/locationService.ts @@ -14,7 +14,7 @@ /* eslint-disable @typescript-eslint/no-floating-promises */ import * as protos from '../../protos/locations'; -import * as assert from 'assert'; +import assert from 'assert'; import * as sinon from 'sinon'; import {SinonStub} from 'sinon'; import {describe, it} from 'mocha'; diff --git a/gax/test/unit/longrunning.ts b/gax/test/unit/longrunning.ts index 7bbb02d01..7974fc663 100644 --- a/gax/test/unit/longrunning.ts +++ b/gax/test/unit/longrunning.ts @@ -17,7 +17,7 @@ /* eslint-disable no-prototype-builtins */ /* eslint-disable @typescript-eslint/no-floating-promises */ -import * as assert from 'assert'; +import assert from 'assert'; import {status} from '@grpc/grpc-js'; import * as sinon from 'sinon'; import {describe, it} from 'mocha'; diff --git a/gax/test/unit/operationClient.ts b/gax/test/unit/operationClient.ts index 02f623b07..2a1262e70 100644 --- a/gax/test/unit/operationClient.ts +++ b/gax/test/unit/operationClient.ts @@ -18,7 +18,7 @@ /* eslint-disable @typescript-eslint/no-floating-promises */ import * as protos from '../../protos/operations'; -import * as assert from 'assert'; +import assert from 'assert'; import * as sinon from 'sinon'; import {SinonStub} from 'sinon'; import {describe, it} from 'mocha'; diff --git a/gax/test/unit/pagedIteration.ts b/gax/test/unit/pagedIteration.ts index b9f4d0054..6ab543df1 100644 --- a/gax/test/unit/pagedIteration.ts +++ b/gax/test/unit/pagedIteration.ts @@ -18,11 +18,11 @@ /* eslint-disable no-prototype-builtins */ /* eslint-disable @typescript-eslint/no-floating-promises */ -import * as assert from 'assert'; +import assert from 'assert'; import * as pumpify from 'pumpify'; import * as sinon from 'sinon'; import {PassThrough} from 'stream'; -import * as streamEvents from 'stream-events'; +import streamEvents from 'stream-events'; import {PageDescriptor} from '../../src/paginationCalls/pageDescriptor'; import {APICallback, GaxCall, RequestType} from '../../src/apitypes'; import {describe, it, beforeEach} from 'mocha'; diff --git a/gax/test/unit/pathTemplate.ts b/gax/test/unit/pathTemplate.ts index babcadaac..d06092ec6 100644 --- a/gax/test/unit/pathTemplate.ts +++ b/gax/test/unit/pathTemplate.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import assert from 'assert'; import {describe, it} from 'mocha'; import {PathTemplate} from '../../src/pathTemplate'; diff --git a/gax/test/unit/regapic.ts b/gax/test/unit/regapic.ts index 28a74bbe4..ece8e311e 100644 --- a/gax/test/unit/regapic.ts +++ b/gax/test/unit/regapic.ts @@ -15,9 +15,8 @@ */ /* eslint-disable @typescript-eslint/no-floating-promises */ -import * as assert from 'assert'; +import assert from 'assert'; import {describe, it, afterEach, before} from 'mocha'; -import * as nodeFetch from 'node-fetch'; import * as protobuf from 'protobufjs'; import * as path from 'path'; import * as sinon from 'sinon'; @@ -28,6 +27,7 @@ import * as transcoding from '../../src/transcoding'; import {OAuth2Client} from 'google-auth-library'; import {GrpcClientOptions} from '../../src'; import {StreamArrayParser} from '../../src/streamArrayParser'; +import proxyquire from 'proxyquire'; const authClient = { async getRequestHeaders() { @@ -91,33 +91,41 @@ describe('REGAPIC', () => { afterEach(() => { sinon.restore(); }); - - it('should make a request', done => { + it('should make a request', async () => { const requestObject = {content: 'test-content'}; - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(requestObject))); + + const {GrpcClient} = await proxyquire( + '../../src/fallback.js', + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(requestObject)) + ); + }, + }); }, - }), + } ); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { - echoStub.echo(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual(err, null); - assert.strictEqual( - requestObject.content, - (result as {content: string}).content, - ); - done(); + const gaxGrpcMock = new GrpcClient(); + + (await gaxGrpcMock) + .createStub(echoService, stubOptions) + .then((echoStub: any) => { + echoStub.echo(requestObject, {}, {}, (err?: {}, result?: {}) => { + assert.strictEqual(err, null); + assert.strictEqual( + requestObject.content, + (result as {content: string}).content + ); + }); }); - }); }); - it('should make a streaming request', done => { + it('should make a streaming request', async () => { const requestObject = {content: 'test content'}; const responseObject = [{content: 'test'}, {content: 'content'}]; const responseObjectJson = JSON.stringify(responseObject, null, ' '); @@ -127,236 +135,296 @@ describe('REGAPIC', () => { responseStream.push(null); // incomplete types for nodeFetch, so... // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - body: responseStream, - }), + const {GrpcClient} = await proxyquire( + '../../src/fallback.js', + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + body: responseStream, + }); + }, + } ); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { + const gaxGrpcMock = new GrpcClient(); + + gaxGrpcMock.createStub(echoService, stubOptions).then((echoStub: any) => { const stream = echoStub.expand( requestObject, {}, {}, - () => {}, + () => {} ) as StreamArrayParser; const results: {}[] = []; - stream.on('data', data => { + stream.on('data', (data: {}) => { results.push(data); }); - stream.on('error', done); + stream.on('error', () => { + return; + }); stream.on('end', () => { assert.deepStrictEqual(results, responseObject); - done(); }); }); }); - it('should handle fetch failure', done => { + it('should handle fetch failure', async () => { const requestObject = {content: 'test-content'}; - sinon - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - .stub(nodeFetch, 'Promise' as any) - .returns(Promise.reject(new Error('Fetch error'))); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { + const {GrpcClient} = await proxyquire( + '../../src/fallback.js', + { + 'node-fetch': () => { + return Promise.reject(new Error('Fetch error')); + }, + } + ); + + const gaxGrpcMock = new GrpcClient(); + + gaxGrpcMock.createStub(echoService, stubOptions).then((echoStub: any) => { echoStub.echo(requestObject, {}, {}, (err?: {}) => { assert.strictEqual((err as Error).message, 'Fetch error'); - done(); }); }); }); - it('should handle streaming request failure', done => { + it('should handle streaming request failure', async () => { const requestObject = {content: 'test content'}; - sinon - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - .stub(nodeFetch, 'Promise' as any) - .returns(Promise.reject(new Error('Fetch error'))); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { + const {GrpcClient} = await proxyquire( + '../../src/fallback.js', + { + 'node-fetch': () => { + return Promise.reject(new Error('Fetch error')); + }, + } + ); + + const gaxGrpcMock = new GrpcClient(); + gaxGrpc.createStub(echoService, stubOptions).then((echoStub: any) => { const stream = echoStub.expand(requestObject) as StreamArrayParser; - stream.on('error', err => { + stream.on('error', (err: Error) => { assert.strictEqual((err as Error).message, 'Fetch error'); - done(); }); }); }); describe('should support enum conversion in proto message', () => { - it('should support enum conversion in proto message response', done => { + it('should support enum conversion in proto message response', async () => { const requestObject = {name: 'shelves/shelf-name'}; const responseObject = { name: 'shelf-name', theme: 'shelf-theme', type: 1, }; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); + const spy = sinon.spy(); + + const {GrpcClient} = await proxyquire( + '../../src/fallback.js', + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)) + ); + }, + }); }, - }), + '../src/transcoding.js': {transcode: spy}, + } ); - gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { - libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); - assert.strictEqual(err, null); - assert.strictEqual( - 'shelf-name', - (result as {name: {}; theme: {}; type: {}}).name, - ); - assert.strictEqual( - 'TYPEONE', - (result as {name: {}; theme: {}; type: {}}).type, - ); - done(); + const gaxGrpcMock = new GrpcClient(); + + gaxGrpcMock + .createStub(libraryService, stubOptions) + .then((libStub: any) => { + libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { + assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); + assert.strictEqual(err, null); + assert.strictEqual( + 'shelf-name', + (result as {name: {}; theme: {}; type: {}}).name + ); + assert.strictEqual( + 'TYPEONE', + (result as {name: {}; theme: {}; type: {}}).type + ); + }); }); - }, /* catch: */ done); }); - it('should support enum conversion in proto message request using symbolic name', done => { + it('should support enum conversion in proto message request using symbolic name', async () => { const shelf = { name: 'shelf-name', theme: 'shelf-theme', type: 'TYPEONE', }; const requestObject = {shelf: shelf}; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + const spy = sinon.spy(); + + const {GrpcClient} = await proxyquire( + '../../src/fallback.js', + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); }, - }), + '../src/transcoding.js': {transcode: spy}, + } ); - gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { - libStub.createShelf(requestObject, {}, {}, (err?: {}) => { - assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); - assert.strictEqual(err, null); - done(); + + const gaxGrpcMock = new GrpcClient(); + + gaxGrpcMock + .createStub(libraryService, stubOptions) + .then((libStub: any) => { + libStub.createShelf(requestObject, {}, {}, (err?: {}) => { + assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); + assert.strictEqual(err, null); + }); }); - }, /* catch: */ done); }); - it('should support enum conversion in proto message request using type value', done => { + it('should support enum conversion in proto message request using type value', async () => { const shelf = { name: 'shelf-name', theme: 'shelf-theme', type: 1, }; const requestObject = {shelf: shelf}; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + const spy = sinon.spy(); + + const {GrpcClient} = await proxyquire( + '../../src/fallback.js', + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); }, - }), + '../src/transcoding.js': {transcode: spy}, + } ); - gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { - libStub.createShelf(requestObject, {}, {}, (err?: {}) => { - assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); - assert.strictEqual(err, null); - done(); + + const gaxGrpcMock = new GrpcClient(); + gaxGrpcMock + .createStub(libraryService, stubOptions) + .then((libStub: any) => { + libStub.createShelf(requestObject, {}, {}, (err?: {}) => { + assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); + assert.strictEqual(err, null); + }); }); - }, /* catch: */ done); }); }); describe('should support enum conversion in proto message with numeric enums enabled', () => { - it('should support enum conversion in proto message response', done => { + it('should support enum conversion in proto message response', async () => { const requestObject = {name: 'shelves/shelf-name'}; const responseObject = { name: 'shelf-name', theme: 'shelf-theme', type: 100, // unknown enum value }; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); + const spy = sinon.spy(); + + const {GrpcClient} = await proxyquire( + '../../src/fallback.js', + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)) + ); + }, + }); }, - }), + '../src/transcoding.js': {transcode: spy}, + } ); - gaxGrpcNumericEnums + const gaxGrpcNumericEnumsMock = new GrpcClient({ + ...opts, + numericEnums: true, + }); + + gaxGrpcNumericEnumsMock .createStub(libraryService, stubOptions) - .then(libStub => { + .then((libStub: any) => { libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { assert.strictEqual( spy.getCall(0).returnValue?.queryString, - '$alt=json%3Benum-encoding=int', + '$alt=json%3Benum-encoding=int' ); assert.strictEqual(err, null); assert.strictEqual( 'shelf-name', - (result as {name: {}; theme: {}; type: {}}).name, + (result as {name: {}; theme: {}; type: {}}).name ); assert.strictEqual( 100, - (result as {name: {}; theme: {}; type: {}}).type, + (result as {name: {}; theme: {}; type: {}}).type ); - done(); }); - }, /* catch: */ done); + }); }); - it('should request numeric enums if passed as symbolic name', done => { + it('should request numeric enums if passed as symbolic name', async () => { const shelf = { name: 'shelf-name', theme: 'shelf-theme', type: 'TYPEONE', }; const requestObject = {shelf: shelf}; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + const spy = sinon.spy(); + + const {GrpcClient} = await proxyquire( + '../../src/fallback.js', + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); }, - }), + '../src/transcoding.js': {transcode: spy}, + } ); - gaxGrpcNumericEnums + + const gaxGrpcNumericEnumsMock = new GrpcClient({ + ...opts, + numericEnums: true, + }); + gaxGrpcNumericEnumsMock .createStub(libraryService, stubOptions) - .then(libStub => { + .then((libStub: any) => { libStub.createShelf(requestObject, {}, {}, (err?: {}) => { assert.strictEqual( - 'string', - typeof spy.getCall(0).returnValue?.queryString, - ); - assert.match( - spy.getCall(0).returnValue?.queryString, - /\$alt=json%3Benum-encoding=int(&.*)?$/, + spy.getCall(0).returnValue?.queryString, + '$alt=json%3Benum-encoding=int' ); assert.strictEqual(err, null); - done(); }); - }, /* catch: */ done); + }); }); - it('should preserve query string when appending numeric enums parameter', done => { + it('should preserve query string when appending numeric enums parameter', async () => { const shelf = { name: 'shelf-name', theme: 'shelf-theme', @@ -366,66 +434,84 @@ describe('REGAPIC', () => { shelf: shelf, queryStringParameter: 'must-be-preserved', }; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + const spy = sinon.spy(); + + const {GrpcClient} = await proxyquire( + '../../src/fallback.js', + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); }, - }), + '../src/transcoding.js': {transcode: spy}, + } ); - gaxGrpcNumericEnums + + const gaxGrpcNumericEnumsMock = new GrpcClient({ + ...opts, + numericEnums: true, + }); + gaxGrpcNumericEnumsMock .createStub(libraryService, stubOptions) - .then(libStub => { + .then((libStub: any) => { libStub.createShelf(requestObject, {}, {}, (err?: {}) => { assert.strictEqual( spy.getCall(0).returnValue?.queryString, - 'queryStringParameter=must-be-preserved&$alt=json%3Benum-encoding=int', + 'queryStringParameter=must-be-preserved&$alt=json%3Benum-encoding=int' ); assert.strictEqual(err, null); - done(); }); - }, /* catch: */ done); + }); }); - it('should request numeric enums if passed as an unknown number', done => { + it('should request numeric enums if passed as an unknown number', async () => { const shelf = { name: 'shelf-name', theme: 'shelf-theme', type: 100, }; const requestObject = {shelf: shelf}; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + const spy = sinon.spy(); + + const {GrpcClient} = await proxyquire( + '../../src/fallback.js', + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); }, - }), + '../src/transcoding.js': {transcode: spy}, + } ); - gaxGrpcNumericEnums + + const gaxGrpcNumericEnumsMock = new GrpcClient({ + ...opts, + numericEnums: true, + }); + gaxGrpcNumericEnumsMock .createStub(libraryService, stubOptions) - .then(libStub => { + .then((libStub: any) => { libStub.createShelf(requestObject, {}, {}, (err?: {}) => { assert.strictEqual( spy.getCall(0).returnValue?.queryString, - '$alt=json%3Benum-encoding=int', + '$alt=json%3Benum-encoding=int' ); assert.strictEqual(err, null); - done(); }); - }, /* catch: */ done); + }); }); }); describe('should support long data type conversion in proto message', () => { - it('large number long data type conversion in proto message response', done => { + it('large number long data type conversion in proto message response', async () => { const requestObject = {name: 'shelves/shelf-name/books/book-name'}; const responseObject = { name: 'book-name', @@ -434,49 +520,58 @@ describe('REGAPIC', () => { read: true, bookId: 9007199254740992, }; - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); + + const {GrpcClient} = await proxyquire( + '../../src/fallback.js', + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)) + ); + }, + }); }, - }), + } ); - gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { - libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual(err, null); - assert.strictEqual( - 'book-name', - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).name, - ); - assert.strictEqual( - '9007199254740992', - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).bookId, - ); - done(); + + const gaxGrpcMock = new GrpcClient(); + gaxGrpcMock + .createStub(libraryService, stubOptions) + .then((libStub: any) => { + libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { + assert.strictEqual(err, null); + assert.strictEqual( + 'book-name', + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).name + ); + assert.strictEqual( + '9007199254740992', + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).bookId + ); + }); }); - }, /* catch: */ done); }); - it('small number long data type conversion in proto message response', done => { + it('small number long data type conversion in proto message response', async () => { const requestObject = {name: 'shelves/shelf-name/books/book-name'}; const responseObject = { name: 'book-name', @@ -486,48 +581,57 @@ describe('REGAPIC', () => { bookId: 42, }; // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); + const {GrpcClient} = await proxyquire( + '../../src/fallback.js', + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)) + ); + }, + }); }, - }), + } ); - gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { - libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual(err, null); - assert.strictEqual( - 'book-name', - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).name, - ); - assert.strictEqual( - '42', - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).bookId, - ); - done(); + + const gaxGrpcMock = new GrpcClient(); + gaxGrpcMock + .createStub(libraryService, stubOptions) + .then((libStub: any) => { + libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { + assert.strictEqual(err, null); + assert.strictEqual( + 'book-name', + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).name + ); + assert.strictEqual( + '42', + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).bookId + ); + }); }); - }, /* catch: */ done); }); - it('long data type conversion in proto message request', done => { + it('long data type conversion in proto message request', async () => { const bookId = 9007199254740992; const requestObject = {name: `shelves/shelf-name/book_id/${bookId}`}; const responseObject = { @@ -539,134 +643,54 @@ describe('REGAPIC', () => { }; // incomplete types for nodeFetch, so... // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); + const {GrpcClient} = await proxyquire( + '../../src/fallback.js', + { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)) + ); + }, + }); }, - }), - ); - gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { - libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual(err, null); - assert.strictEqual( - 'book-name', - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).name, - ); - assert.strictEqual( - bookId.toString(), - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).bookId, - ); - done(); - }); - }, /* catch: */ done); - }); - }); - - describe('should support json minification', () => { - it('should send prettyPrint=0 when json minification is requested', done => { - const requestObject = {name: 'shelves/shelf-name'}; - const responseObject = { - name: 'shelf-name', - theme: 'shelf-theme', - type: 100, // unknown enum value - }; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); - }, - }), + } ); - gaxGrpcMinifyJson + const gaxGrpcMock = new GrpcClient(); + gaxGrpcMock .createStub(libraryService, stubOptions) - .then(libStub => { - libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual( - 'string', - typeof spy.getCall(0).returnValue?.queryString, - ); - assert.match( - spy.getCall(0).returnValue?.queryString, - /\$prettyPrint=0(&.*)?$/, - ); + .then((libStub: any) => { + libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { assert.strictEqual(err, null); assert.strictEqual( - 'shelf-name', - (result as {name: {}; theme: {}; type: {}}).name, + 'book-name', + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).name ); assert.strictEqual( - 100, - (result as {name: {}; theme: {}; type: {}}).type, + bookId.toString(), + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).bookId ); - done(); }); - }, /* catch: */ done); - }); - - it('should not send prettyPrint setting when json minification is not requested', done => { - const requestObject = {name: 'shelves/shelf-name'}; - const responseObject = { - name: 'shelf-name', - theme: 'shelf-theme', - type: 100, // unknown enum value - }; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); - }, - }), - ); - - gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { - libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual( - 'string', - typeof spy.getCall(0).returnValue?.queryString, - ); - assert.doesNotMatch( - spy.getCall(0).returnValue?.queryString, - /prettyPrint/, - ); - assert.strictEqual(err, null); - assert.strictEqual( - 'shelf-name', - (result as {name: {}; theme: {}; type: {}}).name, - ); - assert.strictEqual( - 100, - (result as {name: {}; theme: {}; type: {}}).type, - ); - done(); }); - }, /* catch: */ done); }); }); -}); +}); \ No newline at end of file diff --git a/gax/test/unit/routingHeader.ts b/gax/test/unit/routingHeader.ts index 3acedbbf4..1e7c77f83 100644 --- a/gax/test/unit/routingHeader.ts +++ b/gax/test/unit/routingHeader.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import assert from 'assert'; import {fromParams} from '../../src/routingHeader'; import {describe, it} from 'mocha'; diff --git a/gax/test/unit/status.ts b/gax/test/unit/status.ts index c6eb183b1..1302e2c28 100644 --- a/gax/test/unit/status.ts +++ b/gax/test/unit/status.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import assert from 'assert'; import {describe, it} from 'mocha'; import {rpcCodeFromHttpStatusCode, Status} from '../../src/status'; diff --git a/gax/test/unit/streamArrayParser.ts b/gax/test/unit/streamArrayParser.ts index bc5ecda94..ca9da211b 100644 --- a/gax/test/unit/streamArrayParser.ts +++ b/gax/test/unit/streamArrayParser.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import assert from 'assert'; import {StreamArrayParser} from '../../src/streamArrayParser'; import {before, describe, it} from 'mocha'; import {pipeline} from 'stream'; diff --git a/gax/test/unit/streaming.ts b/gax/test/unit/streaming.ts index bcf2941a8..5aa3512a1 100644 --- a/gax/test/unit/streaming.ts +++ b/gax/test/unit/streaming.ts @@ -16,7 +16,7 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ -import * as assert from 'assert'; +import assert from 'assert'; import * as sinon from 'sinon'; import {afterEach, describe, it} from 'mocha'; import {PassThrough, Transform, pipeline} from 'stream'; diff --git a/gax/test/unit/transcoding.ts b/gax/test/unit/transcoding.ts index 431ac5fa6..f6c6669c6 100644 --- a/gax/test/unit/transcoding.ts +++ b/gax/test/unit/transcoding.ts @@ -32,7 +32,7 @@ import { buildQueryStringComponents, overrideHttpRules, } from '../../src/transcoding'; -import * as assert from 'assert'; +import assert from 'assert'; import * as protobuf from 'protobufjs'; import echoProtoJson = require('../fixtures/echo.json'); import {google} from '../../protos/http'; diff --git a/gax/test/unit/util.ts b/gax/test/unit/util.ts index 386243bea..e9e882a36 100644 --- a/gax/test/unit/util.ts +++ b/gax/test/unit/util.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import assert from 'assert'; import {describe, it} from 'mocha'; import { toCamelCase as snakeToCamelCase, diff --git a/gax/test/unit/warning.ts b/gax/test/unit/warning.ts index a79b50587..240523321 100644 --- a/gax/test/unit/warning.ts +++ b/gax/test/unit/warning.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import assert from 'assert'; import * as sinon from 'sinon'; import {describe, it} from 'mocha'; diff --git a/gax/tsconfig.json b/gax/tsconfig.json index 9a5a0c4da..d5cda5d87 100644 --- a/gax/tsconfig.json +++ b/gax/tsconfig.json @@ -5,7 +5,11 @@ "rootDir": ".", "outDir": "build", "noImplicitAny": true, - "resolveJsonModule": true + "resolveJsonModule": true, + "moduleResolution": "node16", + "esModuleInterop": true, + "module": "node16", + "skipLibCheck": true }, "include": [ "src/*.ts", From b76905ce815e880db2acdc7c3aa56223f51b520e Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Fri, 14 Feb 2025 17:34:10 -0800 Subject: [PATCH 56/64] run lint --- gax/package.json | 5 +---- gax/src/iamService.ts | 1 - gax/src/locationService.ts | 1 - gax/src/operationsClient.ts | 1 - gax/src/paginationCalls/pageDescriptor.ts | 1 - gax/src/util.ts | 4 ++-- gax/test/test-application/src/index.ts | 2 +- gax/test/unit/apiCallable.ts | 1 - gax/test/unit/bundling.ts | 1 - gax/test/unit/grpc-fallback.ts | 2 -- gax/test/unit/grpc.ts | 1 - gax/test/unit/iamService.ts | 1 - gax/test/unit/locationService.ts | 1 - gax/test/unit/longrunning.ts | 1 - gax/test/unit/operationClient.ts | 1 - gax/test/unit/pagedIteration.ts | 1 - gax/test/unit/regapic.ts | 1 - 17 files changed, 4 insertions(+), 22 deletions(-) diff --git a/gax/package.json b/gax/package.json index 84c92a6d1..fa59ad360 100644 --- a/gax/package.json +++ b/gax/package.json @@ -13,15 +13,13 @@ "@grpc/grpc-js": "^1.12.6", "@grpc/proto-loader": "^0.7.13", "@types/long": "^5.0.0", - "abort-controller": "^3.0.0", "duplexify": "^4.1.3", "google-auth-library": "^9.15.1", "node-fetch": "^3.3.2", "object-hash": "^3.0.0", "proto3-json-serializer": "^2.0.2", "protobufjs": "^7.4.0", - "retry-request": "^7.0.2", - "uuid": "^11.0.5" + "retry-request": "^7.0.2" }, "devDependencies": { "@babel/plugin-proposal-private-methods": "^7.18.6", @@ -34,7 +32,6 @@ "@types/pumpify": "^1.4.4", "@types/sinon": "^17.0.3", "@types/uglify-js": "^3.17.5", - "@types/uuid": "^10.0.0", "assert": "^2.1.0", "c8": "^10.1.3", "cheerio": "^1.0.0", diff --git a/gax/src/iamService.ts b/gax/src/iamService.ts index dcb3e4717..161b2ceca 100644 --- a/gax/src/iamService.ts +++ b/gax/src/iamService.ts @@ -15,7 +15,6 @@ // ** This file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -/* eslint-disable @typescript-eslint/no-floating-promises */ import * as gax from './gax'; import type {GrpcClient, ClientStubOptions} from './grpc'; diff --git a/gax/src/locationService.ts b/gax/src/locationService.ts index b46ab1832..825c4a3cf 100644 --- a/gax/src/locationService.ts +++ b/gax/src/locationService.ts @@ -11,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -/* eslint-disable @typescript-eslint/no-floating-promises */ /* global window */ import * as gax from './gax'; diff --git a/gax/src/operationsClient.ts b/gax/src/operationsClient.ts index 4ac8ff714..a9920f911 100644 --- a/gax/src/operationsClient.ts +++ b/gax/src/operationsClient.ts @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* eslint-disable @typescript-eslint/no-floating-promises */ import type {GoogleAuth, OAuth2Client} from 'google-auth-library'; import {ProjectIdCallback} from 'google-auth-library/build/src/auth/googleauth'; diff --git a/gax/src/paginationCalls/pageDescriptor.ts b/gax/src/paginationCalls/pageDescriptor.ts index ce738892a..9fc57c55d 100644 --- a/gax/src/paginationCalls/pageDescriptor.ts +++ b/gax/src/paginationCalls/pageDescriptor.ts @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* eslint-disable @typescript-eslint/no-floating-promises */ import {PassThrough, Transform} from 'stream'; diff --git a/gax/src/util.ts b/gax/src/util.ts index 7948df28c..01fb85553 100644 --- a/gax/src/util.ts +++ b/gax/src/util.ts @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {v4 as uuidv4} from 'uuid'; +import {randomUUID} from 'crypto'; function words(str: string, normalize = false) { if (normalize) { @@ -110,5 +110,5 @@ export function toLowerCamelCase(str: string) { * in lower case). */ export function makeUUID() { - return uuidv4(); + return randomUUID(); } diff --git a/gax/test/test-application/src/index.ts b/gax/test/test-application/src/index.ts index 4410ac0b7..2ea9530e8 100644 --- a/gax/test/test-application/src/index.ts +++ b/gax/test/test-application/src/index.ts @@ -17,7 +17,7 @@ 'use strict'; import {EchoClient, SequenceServiceClient, protos} from 'showcase-echo-client'; import {ShowcaseServer} from 'showcase-server'; -import assert from 'assert'; +import * as assert from 'assert'; import {promises as fsp} from 'fs'; import * as path from 'path'; import { diff --git a/gax/test/unit/apiCallable.ts b/gax/test/unit/apiCallable.ts index c756ec8fa..5dc17c8b7 100644 --- a/gax/test/unit/apiCallable.ts +++ b/gax/test/unit/apiCallable.ts @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* eslint-disable @typescript-eslint/no-floating-promises */ import assert from 'assert'; import {status} from '@grpc/grpc-js'; diff --git a/gax/test/unit/bundling.ts b/gax/test/unit/bundling.ts index d2523dee0..0ec222b67 100644 --- a/gax/test/unit/bundling.ts +++ b/gax/test/unit/bundling.ts @@ -16,7 +16,6 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ /* eslint-disable no-prototype-builtins */ -/* eslint-disable @typescript-eslint/no-floating-promises */ import assert from 'assert'; import {status} from '@grpc/grpc-js'; diff --git a/gax/test/unit/grpc-fallback.ts b/gax/test/unit/grpc-fallback.ts index 5ead3e8bf..a76823a31 100644 --- a/gax/test/unit/grpc-fallback.ts +++ b/gax/test/unit/grpc-fallback.ts @@ -16,11 +16,9 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ /* eslint-disable no-undef */ -/* eslint-disable @typescript-eslint/no-floating-promises */ import assert from 'assert'; import {describe, it, beforeEach, afterEach, before, after} from 'mocha'; -import * as abortController from 'abort-controller'; import * as protobuf from 'protobufjs'; import * as sinon from 'sinon'; import echoProtoJson = require('../fixtures/echo.json'); diff --git a/gax/test/unit/grpc.ts b/gax/test/unit/grpc.ts index 859b219e7..d3060d82b 100644 --- a/gax/test/unit/grpc.ts +++ b/gax/test/unit/grpc.ts @@ -17,7 +17,6 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ /* eslint-disable no-prototype-builtins */ /* eslint-disable @typescript-eslint/no-var-requires */ -/* eslint-disable @typescript-eslint/no-floating-promises */ import assert from 'assert'; import * as os from 'os'; diff --git a/gax/test/unit/iamService.ts b/gax/test/unit/iamService.ts index b54e9b59c..d88ef23bd 100644 --- a/gax/test/unit/iamService.ts +++ b/gax/test/unit/iamService.ts @@ -15,7 +15,6 @@ // ** This file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -/* eslint-disable @typescript-eslint/no-floating-promises */ import * as protos from '../../protos/iam_service'; import assert from 'assert'; diff --git a/gax/test/unit/locationService.ts b/gax/test/unit/locationService.ts index 31bfefc56..03afd6843 100644 --- a/gax/test/unit/locationService.ts +++ b/gax/test/unit/locationService.ts @@ -11,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -/* eslint-disable @typescript-eslint/no-floating-promises */ import * as protos from '../../protos/locations'; import assert from 'assert'; diff --git a/gax/test/unit/longrunning.ts b/gax/test/unit/longrunning.ts index 7974fc663..acbfb3f90 100644 --- a/gax/test/unit/longrunning.ts +++ b/gax/test/unit/longrunning.ts @@ -15,7 +15,6 @@ */ /* eslint-disable no-prototype-builtins */ -/* eslint-disable @typescript-eslint/no-floating-promises */ import assert from 'assert'; import {status} from '@grpc/grpc-js'; diff --git a/gax/test/unit/operationClient.ts b/gax/test/unit/operationClient.ts index 2a1262e70..63b063392 100644 --- a/gax/test/unit/operationClient.ts +++ b/gax/test/unit/operationClient.ts @@ -15,7 +15,6 @@ // ** This file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -/* eslint-disable @typescript-eslint/no-floating-promises */ import * as protos from '../../protos/operations'; import assert from 'assert'; diff --git a/gax/test/unit/pagedIteration.ts b/gax/test/unit/pagedIteration.ts index 6ab543df1..daf261a9b 100644 --- a/gax/test/unit/pagedIteration.ts +++ b/gax/test/unit/pagedIteration.ts @@ -16,7 +16,6 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ /* eslint-disable no-prototype-builtins */ -/* eslint-disable @typescript-eslint/no-floating-promises */ import assert from 'assert'; import * as pumpify from 'pumpify'; diff --git a/gax/test/unit/regapic.ts b/gax/test/unit/regapic.ts index ece8e311e..06a4862a5 100644 --- a/gax/test/unit/regapic.ts +++ b/gax/test/unit/regapic.ts @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* eslint-disable @typescript-eslint/no-floating-promises */ import assert from 'assert'; import {describe, it, afterEach, before} from 'mocha'; From 0696ae5b96f4270136521a9a28629893f583ddbd Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Fri, 14 Feb 2025 17:37:50 -0800 Subject: [PATCH 57/64] readd abort controller --- gax/package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/gax/package.json b/gax/package.json index fa59ad360..99ede9172 100644 --- a/gax/package.json +++ b/gax/package.json @@ -13,6 +13,7 @@ "@grpc/grpc-js": "^1.12.6", "@grpc/proto-loader": "^0.7.13", "@types/long": "^5.0.0", + "abort-controller": "^3.0.0", "duplexify": "^4.1.3", "google-auth-library": "^9.15.1", "node-fetch": "^3.3.2", From 45fc98fa622e14fe4baee3d496f1265ba24edeb0 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Fri, 14 Feb 2025 17:39:24 -0800 Subject: [PATCH 58/64] readd abort controller in test --- gax/test/unit/grpc-fallback.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/gax/test/unit/grpc-fallback.ts b/gax/test/unit/grpc-fallback.ts index a76823a31..f3eb06e8d 100644 --- a/gax/test/unit/grpc-fallback.ts +++ b/gax/test/unit/grpc-fallback.ts @@ -19,6 +19,7 @@ import assert from 'assert'; import {describe, it, beforeEach, afterEach, before, after} from 'mocha'; +import * as abortController from 'abort-controller'; import * as protobuf from 'protobufjs'; import * as sinon from 'sinon'; import echoProtoJson = require('../fixtures/echo.json'); From d3aa8289ed7754e0a56baa6b83367a3cfacfcf19 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Fri, 14 Feb 2025 18:02:10 -0800 Subject: [PATCH 59/64] run lint --- gax/.eslintignore | 4 + gax/src/fallbackServiceStub.ts | 10 +- gax/src/iamService.ts | 8 +- gax/src/locationService.ts | 8 +- gax/src/operationsClient.ts | 2 +- gax/src/paginationCalls/pageDescriptor.ts | 4 +- gax/src/util.ts | 3 +- gax/test/unit/apiCallable.ts | 80 ++--- gax/test/unit/bundling.ts | 10 +- gax/test/unit/grpc-fallback.ts | 10 +- gax/test/unit/grpc.ts | 2 +- gax/test/unit/regapic.ts | 368 ++++++++++------------ 12 files changed, 225 insertions(+), 284 deletions(-) diff --git a/gax/.eslintignore b/gax/.eslintignore index ea5b04aeb..07a7bd357 100644 --- a/gax/.eslintignore +++ b/gax/.eslintignore @@ -5,3 +5,7 @@ build/ docs/ protos/ samples/generated/ +test/browser-test/ +test/showcase-echo-client/src/ +test/showcase-server/ +test/test-application/src/ \ No newline at end of file diff --git a/gax/src/fallbackServiceStub.ts b/gax/src/fallbackServiceStub.ts index 37ad9e2c0..4fcd1db58 100644 --- a/gax/src/fallbackServiceStub.ts +++ b/gax/src/fallbackServiceStub.ts @@ -17,7 +17,10 @@ /* global window */ /* global AbortController */ -import type {Response as NodeFetchResponse, RequestInit} from 'node-fetch' with {'resolution-mode': 'import'}; +import type { + Response as NodeFetchResponse, + RequestInit, +} from 'node-fetch' with {'resolution-mode': 'import'}; import {AbortController as NodeAbortController} from 'abort-controller'; import type nodeFetch from 'node-fetch' with {'resolution-mode': 'import'}; import {hasWindowFetch, hasAbortController, isNodeJS} from './featureDetection'; @@ -158,10 +161,7 @@ export function generateServiceStub( ...authHeader, ...headers, }, - body: fetchParameters.body as - | string - | Buffer - | undefined, + body: fetchParameters.body as string | Buffer | undefined, method: fetchParameters.method, signal: cancelSignal, }; diff --git a/gax/src/iamService.ts b/gax/src/iamService.ts index 161b2ceca..1ae5539ae 100644 --- a/gax/src/iamService.ts +++ b/gax/src/iamService.ts @@ -255,7 +255,7 @@ export class IamClient { routingHeader.fromParams({ resource: request.resource, }); - this.initialize(); + this.initialize().catch(console.error); return this.innerApiCalls.getIamPolicy(request, options, callback); } @@ -314,7 +314,7 @@ export class IamClient { routingHeader.fromParams({ resource: request.resource, }); - this.initialize(); + this.initialize().catch(console.error); return this.innerApiCalls.setIamPolicy(request, options, callback); } testIamPermissions( @@ -372,7 +372,7 @@ export class IamClient { routingHeader.fromParams({ resource: request.resource, }); - this.initialize(); + this.initialize().catch(console.error); return this.innerApiCalls.testIamPermissions(request, options, callback); } @@ -382,7 +382,7 @@ export class IamClient { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { - this.initialize(); + this.initialize().catch(console.error); if (!this._terminated) { return this.iamPolicyStub!.then(stub => { this._terminated = true; diff --git a/gax/src/locationService.ts b/gax/src/locationService.ts index 825c4a3cf..08ed1b0cd 100644 --- a/gax/src/locationService.ts +++ b/gax/src/locationService.ts @@ -361,7 +361,7 @@ export class LocationsClient { routingHeader.fromParams({ name: request.name || '', }); - this.initialize(); + this.initialize().catch(console.error); return this.innerApiCalls.getLocation(request, options, callback); } @@ -456,7 +456,7 @@ export class LocationsClient { routingHeader.fromParams({ name: request.name || '', }); - this.initialize(); + this.initialize().catch(console.error); return this.innerApiCalls.listLocations(request, options, callback); } @@ -504,7 +504,7 @@ export class LocationsClient { }); options = options || {}; const callSettings = new gax.CallSettings(options); - this.initialize(); + this.initialize().catch(console.error); return this.descriptors.page.listLocations.asyncIterate( this.innerApiCalls['listLocations'] as GaxCall, request as unknown as RequestType, @@ -519,7 +519,7 @@ export class LocationsClient { * @returns {Promise} A promise that resolves when the client is closed. */ close(): Promise { - this.initialize(); + this.initialize().catch(console.error); if (!this._terminated) { return this.locationsStub!.then(stub => { this._terminated = true; diff --git a/gax/src/operationsClient.ts b/gax/src/operationsClient.ts index a9920f911..8cf71527c 100644 --- a/gax/src/operationsClient.ts +++ b/gax/src/operationsClient.ts @@ -148,7 +148,7 @@ export class OperationsClient { /** Closes this operations client. */ close() { - this.operationsStub.then(stub => stub.close()); + this.operationsStub.then(stub => stub.close()).catch(console.error); } /** diff --git a/gax/src/paginationCalls/pageDescriptor.ts b/gax/src/paginationCalls/pageDescriptor.ts index 9fc57c55d..13c3a4636 100644 --- a/gax/src/paginationCalls/pageDescriptor.ts +++ b/gax/src/paginationCalls/pageDescriptor.ts @@ -128,10 +128,10 @@ export class PageDescriptor implements Descriptor { setImmediate(apiCall, next, options, callback as APICallback); } } - stream.on('resume', () => { + stream.on('resume', async () => { if (!started) { started = true; - apiCall(request, options, callback as unknown as APICallback); + await apiCall(request, options, callback as unknown as APICallback); } }); return stream; diff --git a/gax/src/util.ts b/gax/src/util.ts index 01fb85553..7a17eeed4 100644 --- a/gax/src/util.ts +++ b/gax/src/util.ts @@ -13,7 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {randomUUID} from 'crypto'; +const randomUUID = async () => + globalThis.crypto?.randomUUID() || (await import('crypto')).randomUUID(); function words(str: string, normalize = false) { if (normalize) { diff --git a/gax/test/unit/apiCallable.ts b/gax/test/unit/apiCallable.ts index 5dc17c8b7..164dbab2b 100644 --- a/gax/test/unit/apiCallable.ts +++ b/gax/test/unit/apiCallable.ts @@ -34,7 +34,7 @@ describe('createApiCall', () => { afterEach(() => { sinon.restore(); }); - it('calls api call', done => { + it('calls api call', async () => { let deadlineArg: {}; function func( argument: {}, @@ -46,14 +46,13 @@ describe('createApiCall', () => { callback(null, argument); } const apiCall = createApiCall(func); - apiCall(42, undefined, (err, resp) => { + await apiCall(42, undefined, (err, resp) => { assert.strictEqual(resp, 42); assert.ok(deadlineArg); - done(); }); }); - it('is customized by call options', done => { + it('is customized by call options', async () => { function func( argument: {}, metadata: {}, @@ -63,17 +62,16 @@ describe('createApiCall', () => { callback(null, options.deadline.getTime()); } const apiCall = createApiCall(func, {settings: {timeout: 100}}); - apiCall({}, {timeout: 200}, (err, resp) => { + await apiCall({}, {timeout: 200}, (err, resp) => { const now = new Date(); const originalDeadline = now.getTime() + 100; const expectedDeadline = now.getTime() + 200; assert((resp as unknown as number)! > originalDeadline); assert((resp as unknown as number)! <= expectedDeadline); - done(); }); }); - it('chooses the proper timeout', done => { + it('chooses the proper timeout', async () => { function func( argument: {}, metadata: {}, @@ -97,17 +95,16 @@ describe('createApiCall', () => { }); const start = new Date().getTime(); - apiCall({}, undefined, (err, resp) => { + await apiCall({}, undefined, (err, resp) => { // The verifying value is slightly bigger than the expected number // 2000 / 30000, because sometimes runtime can consume some time before // the call starts. assert(Number(resp) - start > 2100); assert(Number(resp) - start <= 30100); - done(); }); }); - it('default to `timeout` for idempotent API calls', done => { + it('default to `timeout` for idempotent API calls', async () => { function func( argument: {}, metadata: {}, @@ -131,31 +128,25 @@ describe('createApiCall', () => { }); const start = new Date().getTime(); - apiCall({}, undefined, (err, resp) => { + await apiCall({}, undefined, (err, resp) => { // The verifying value is slightly bigger than the expected number // 2000 / 30000, because sometimes runtime can consume some time before // the call starts. assert(Number(resp) - start > 2100); assert(Number(resp) - start <= 30100); - done(); }); }); - it('override just custom retry.retryCodes with retry codes', done => { + it('override just custom retry.retryCodes with retry codes', async () => { const initialRetryCodes = [1]; const overrideRetryCodes = [1, 2, 3]; // eslint-disable-next-line @typescript-eslint/no-explicit-any sinon.stub(retries, 'retryable').callsFake((func, retry): any => { - try { assert.strictEqual(retry.retryCodes, overrideRetryCodes); return func; - } catch (err) { - done(err); - } - return func; }); function func() { - done(); + return; } const apiCall = createApiCall(func, { settings: { @@ -170,7 +161,7 @@ describe('createApiCall', () => { }, }); - apiCall( + await apiCall( {}, { retry: { @@ -220,7 +211,7 @@ describe('createApiCall', () => { } }); - it('override just custom retry.backoffSettings', done => { + it('override just custom retry.backoffSettings', async () => { const initialBackoffSettings = gax.createDefaultBackoffSettings(); const overriBackoffSettings = gax.createBackoffSettings( 100, @@ -238,7 +229,7 @@ describe('createApiCall', () => { }); function func() { - done(); + return; } const apiCall = createApiCall(func, { @@ -247,7 +238,7 @@ describe('createApiCall', () => { }, }); - apiCall( + await apiCall( {}, { retry: { @@ -455,7 +446,7 @@ describe('retryable', () => { }); }); - it('retries the API call with promise', done => { + it('retries the API call with promise', async () => { let toAttempt = 3; let deadlineArg: string; function func( @@ -473,15 +464,13 @@ describe('retryable', () => { callback(null, 1729); } const apiCall = createApiCall(func, settings); - apiCall({}, undefined) + await apiCall({}, undefined) .then(resp => { assert.ok(Array.isArray(resp)); assert.strictEqual(resp[0], 1729); assert.strictEqual(toAttempt, 0); assert.ok(deadlineArg); - done(); - }) - .catch(done); + }); }); it('cancels in the middle of retries', done => { @@ -529,12 +518,11 @@ describe('retryable', () => { }); }); - it('aborts retries', done => { + it('aborts retries', async () => { const apiCall = createApiCall(fail, settings); - apiCall({}, undefined, err => { + await apiCall({}, undefined, err => { assert(err instanceof GoogleError); assert.strictEqual(err!.code, status.DEADLINE_EXCEEDED); - done(); }); }); @@ -551,7 +539,7 @@ describe('retryable', () => { }); }); - it('errors on maxRetries and surfaces original error', done => { + it('errors on maxRetries and surfaces original error', async () => { const toAttempt = 5; const backoff = gax.createMaxRetriesBackoffSettings( 0, @@ -569,7 +557,7 @@ describe('retryable', () => { }; const spy = sinon.spy(fail); const apiCall = createApiCall(spy, maxRetrySettings); - apiCall({}, undefined, err => { + await apiCall({}, undefined, err => { assert.ok(err instanceof GoogleError); assert.strictEqual(err!.code, status.DEADLINE_EXCEEDED); assert.strictEqual(spy.callCount, toAttempt); @@ -577,27 +565,25 @@ describe('retryable', () => { err.message, /Exceeded maximum number of retries retrying error Error before any response was received/, ); - done(); }); }); - it('retry fails for exceeding total timeout, surfacing original error', done => { + it('retry fails for exceeding total timeout, surfacing original error', async () => { const spy = sinon.spy(fail); const apiCall = createApiCall(spy, settings); - apiCall({}, undefined, err => { + await apiCall({}, undefined, err => { assert.ok(err instanceof GoogleError); assert.match( err.message, /Total timeout of API TestApi exceeded 100 milliseconds retrying error Error {2}before any response was received/, ); assert.strictEqual(err!.code, status.DEADLINE_EXCEEDED); - done(); }); }); // maxRetries is unsupported, and intended for internal use only or // use with retry-request backwards compatibility - it('errors when totalTimeoutMillis and maxRetries set', done => { + it('errors when totalTimeoutMillis and maxRetries set', async () => { const maxRetries = 5; const backoff = gax.createMaxRetriesBackoffSettings( 0, @@ -615,15 +601,14 @@ describe('retryable', () => { }; const spy = sinon.spy(fail); const apiCall = createApiCall(spy, maxRetrySettings); - apiCall({}, undefined, err => { + await apiCall({}, undefined, err => { assert(err instanceof GoogleError); assert.strictEqual(err!.code, status.INVALID_ARGUMENT); assert.strictEqual(spy.callCount, 0); - done(); }); }); - it('aborts on unexpected exception', done => { + it('aborts on unexpected exception', async () => { function func(argument: {}, metadata: {}, options: {}, callback: Function) { const error = new GoogleError(); error.code = FAKE_STATUS_CODE_2; @@ -631,24 +616,22 @@ describe('retryable', () => { } const spy = sinon.spy(func); const apiCall = createApiCall(spy, settings); - apiCall({}, undefined, err => { + await apiCall({}, undefined, err => { assert(err instanceof Error); assert.strictEqual(err!.code, FAKE_STATUS_CODE_2); assert(err!.note); assert.strictEqual(spy.callCount, 1); - done(); }); }); - it('does not retry even when no responses', done => { + it('does not retry even when no responses', async () => { function func(argument: {}, metadata: {}, options: {}, callback: Function) { callback(null, null); } const apiCall = createApiCall(func, settings); - apiCall({}, undefined, (err, resp) => { + await apiCall({}, undefined, (err, resp) => { assert.strictEqual(err, null); assert.strictEqual(resp, null); - done(); }); }); @@ -725,7 +708,7 @@ describe('retryable', () => { }); }); - it('forwards metadata to builder', done => { + it('forwards metadata to builder', async () => { function func(argument: {}, metadata: {}, options: {}, callback: Function) { callback(null, {}); } @@ -744,10 +727,9 @@ describe('retryable', () => { h1: 'val1', h2: 'val2', }; - apiCall({}, {otherArgs: {headers}}).then(() => { + await apiCall({}, {otherArgs: {headers}}).then(() => { assert.strictEqual(gotHeaders.h1, 'val1'); assert.strictEqual(gotHeaders.h2, 'val2'); - done(); }); }); }); diff --git a/gax/test/unit/bundling.ts b/gax/test/unit/bundling.ts index 0ec222b67..02b5c2a25 100644 --- a/gax/test/unit/bundling.ts +++ b/gax/test/unit/bundling.ts @@ -869,27 +869,25 @@ describe('bundleable', () => { descriptor, }; - it('bundles requests', done => { + it('bundles requests', async () => { const spy = sinon.spy(func); const callback = sinon.spy(obj => { assert(Array.isArray(obj)); assert.deepStrictEqual(obj[0].field1, [1, 2, 3]); if (callback.callCount === 2) { assert.strictEqual(spy.callCount, 1); - done(); } }); const apiCall = createApiCall(spy, settings); - apiCall({field1: [1, 2, 3], field2: 'id'}, undefined, (err, obj) => { + await apiCall({field1: [1, 2, 3], field2: 'id'}, undefined, (err, obj) => { if (err) { - done(err); + return err; } else { callback([obj]); } }); - apiCall({field1: [1, 2, 3], field2: 'id'}, undefined) + await apiCall({field1: [1, 2, 3], field2: 'id'}, undefined) .then(callback) - .catch(done); }); it('does not fail if bundle field is not set', done => { diff --git a/gax/test/unit/grpc-fallback.ts b/gax/test/unit/grpc-fallback.ts index f3eb06e8d..771e57b3d 100644 --- a/gax/test/unit/grpc-fallback.ts +++ b/gax/test/unit/grpc-fallback.ts @@ -300,7 +300,7 @@ describe('grpc-fallback', () => { assert.strictEqual(err, null); assert.strictEqual( requestObject.content, - (result as {content: string}).content + (result as {content: string}).content, ); }); }); @@ -360,7 +360,7 @@ describe('grpc-fallback', () => { assert.strictEqual(err.code, expectedError.code); assert.strictEqual( JSON.stringify(err.statusDetails), - JSON.stringify(expectedError.details) + JSON.stringify(expectedError.details), ); }); }); @@ -438,7 +438,7 @@ describe('grpc-fallback', () => { assert(err instanceof GoogleError); assert.strictEqual( JSON.stringify(err.statusDetails?.length), - JSON.stringify(serverError['error']['details'].length) + JSON.stringify(serverError['error']['details'].length), ); assert.strictEqual(err.code, 7); assert.strictEqual(err.message, serverError['error']['message']); @@ -446,7 +446,7 @@ describe('grpc-fallback', () => { assert.strictEqual(err.domain, errorInfo.domain); assert.strictEqual( JSON.stringify(err.errorInfoMetadata), - JSON.stringify(errorInfo.metadata) + JSON.stringify(errorInfo.metadata), ); }); }); @@ -498,4 +498,4 @@ describe('grpc-fallback', () => { stub.close({}, {}, {}, () => {}); }); }); -}); \ No newline at end of file +}); diff --git a/gax/test/unit/grpc.ts b/gax/test/unit/grpc.ts index d3060d82b..6f8de7c81 100644 --- a/gax/test/unit/grpc.ts +++ b/gax/test/unit/grpc.ts @@ -713,7 +713,7 @@ dvorak const clientMock = new GrpcClient(); assert.rejects( clientMock.createStub(DummyStub, {universeDomain: 'example.com'}), - /configured universe domain/ + /configured universe domain/, ); await fsp.rm(tmpFolder, {recursive: true, force: true}); // Cleanup. }); diff --git a/gax/test/unit/regapic.ts b/gax/test/unit/regapic.ts index 06a4862a5..197ddf2d5 100644 --- a/gax/test/unit/regapic.ts +++ b/gax/test/unit/regapic.ts @@ -93,21 +93,16 @@ describe('REGAPIC', () => { it('should make a request', async () => { const requestObject = {content: 'test-content'}; - const {GrpcClient} = await proxyquire( - '../../src/fallback.js', - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve( - Buffer.from(JSON.stringify(requestObject)) - ); - }, - }); - }, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(requestObject))); + }, + }); + }, + }); const gaxGrpcMock = new GrpcClient(); @@ -118,7 +113,7 @@ describe('REGAPIC', () => { assert.strictEqual(err, null); assert.strictEqual( requestObject.content, - (result as {content: string}).content + (result as {content: string}).content, ); }); }); @@ -134,17 +129,14 @@ describe('REGAPIC', () => { responseStream.push(null); // incomplete types for nodeFetch, so... // eslint-disable-next-line @typescript-eslint/no-explicit-any - const {GrpcClient} = await proxyquire( - '../../src/fallback.js', - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - body: responseStream, - }); - }, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + body: responseStream, + }); + }, + }); const gaxGrpcMock = new GrpcClient(); @@ -153,7 +145,7 @@ describe('REGAPIC', () => { requestObject, {}, {}, - () => {} + () => {}, ) as StreamArrayParser; const results: {}[] = []; stream.on('data', (data: {}) => { @@ -171,14 +163,11 @@ describe('REGAPIC', () => { it('should handle fetch failure', async () => { const requestObject = {content: 'test-content'}; - const {GrpcClient} = await proxyquire( - '../../src/fallback.js', - { - 'node-fetch': () => { - return Promise.reject(new Error('Fetch error')); - }, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.reject(new Error('Fetch error')); + }, + }); const gaxGrpcMock = new GrpcClient(); @@ -192,14 +181,11 @@ describe('REGAPIC', () => { it('should handle streaming request failure', async () => { const requestObject = {content: 'test content'}; - const {GrpcClient} = await proxyquire( - '../../src/fallback.js', - { - 'node-fetch': () => { - return Promise.reject(new Error('Fetch error')); - }, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.reject(new Error('Fetch error')); + }, + }); const gaxGrpcMock = new GrpcClient(); gaxGrpc.createStub(echoService, stubOptions).then((echoStub: any) => { @@ -220,22 +206,19 @@ describe('REGAPIC', () => { }; const spy = sinon.spy(); - const {GrpcClient} = await proxyquire( - '../../src/fallback.js', - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve( - Buffer.from(JSON.stringify(responseObject)) - ); - }, - }); - }, - '../src/transcoding.js': {transcode: spy}, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)), + ); + }, + }); + }, + '../src/transcoding.js': {transcode: spy}, + }); const gaxGrpcMock = new GrpcClient(); @@ -247,11 +230,11 @@ describe('REGAPIC', () => { assert.strictEqual(err, null); assert.strictEqual( 'shelf-name', - (result as {name: {}; theme: {}; type: {}}).name + (result as {name: {}; theme: {}; type: {}}).name, ); assert.strictEqual( 'TYPEONE', - (result as {name: {}; theme: {}; type: {}}).type + (result as {name: {}; theme: {}; type: {}}).type, ); }); }); @@ -266,20 +249,17 @@ describe('REGAPIC', () => { const requestObject = {shelf: shelf}; const spy = sinon.spy(); - const {GrpcClient} = await proxyquire( - '../../src/fallback.js', - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); - }, - }); - }, - '../src/transcoding.js': {transcode: spy}, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); + }, + '../src/transcoding.js': {transcode: spy}, + }); const gaxGrpcMock = new GrpcClient(); @@ -302,20 +282,17 @@ describe('REGAPIC', () => { const requestObject = {shelf: shelf}; const spy = sinon.spy(); - const {GrpcClient} = await proxyquire( - '../../src/fallback.js', - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); - }, - }); - }, - '../src/transcoding.js': {transcode: spy}, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); + }, + '../src/transcoding.js': {transcode: spy}, + }); const gaxGrpcMock = new GrpcClient(); gaxGrpcMock @@ -339,22 +316,19 @@ describe('REGAPIC', () => { }; const spy = sinon.spy(); - const {GrpcClient} = await proxyquire( - '../../src/fallback.js', - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve( - Buffer.from(JSON.stringify(responseObject)) - ); - }, - }); - }, - '../src/transcoding.js': {transcode: spy}, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)), + ); + }, + }); + }, + '../src/transcoding.js': {transcode: spy}, + }); const gaxGrpcNumericEnumsMock = new GrpcClient({ ...opts, @@ -367,16 +341,16 @@ describe('REGAPIC', () => { libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { assert.strictEqual( spy.getCall(0).returnValue?.queryString, - '$alt=json%3Benum-encoding=int' + '$alt=json%3Benum-encoding=int', ); assert.strictEqual(err, null); assert.strictEqual( 'shelf-name', - (result as {name: {}; theme: {}; type: {}}).name + (result as {name: {}; theme: {}; type: {}}).name, ); assert.strictEqual( 100, - (result as {name: {}; theme: {}; type: {}}).type + (result as {name: {}; theme: {}; type: {}}).type, ); }); }); @@ -391,20 +365,17 @@ describe('REGAPIC', () => { const requestObject = {shelf: shelf}; const spy = sinon.spy(); - const {GrpcClient} = await proxyquire( - '../../src/fallback.js', - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); - }, - }); - }, - '../src/transcoding.js': {transcode: spy}, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); + }, + '../src/transcoding.js': {transcode: spy}, + }); const gaxGrpcNumericEnumsMock = new GrpcClient({ ...opts, @@ -416,7 +387,7 @@ describe('REGAPIC', () => { libStub.createShelf(requestObject, {}, {}, (err?: {}) => { assert.strictEqual( spy.getCall(0).returnValue?.queryString, - '$alt=json%3Benum-encoding=int' + '$alt=json%3Benum-encoding=int', ); assert.strictEqual(err, null); }); @@ -435,20 +406,17 @@ describe('REGAPIC', () => { }; const spy = sinon.spy(); - const {GrpcClient} = await proxyquire( - '../../src/fallback.js', - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); - }, - }); - }, - '../src/transcoding.js': {transcode: spy}, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); + }, + '../src/transcoding.js': {transcode: spy}, + }); const gaxGrpcNumericEnumsMock = new GrpcClient({ ...opts, @@ -460,7 +428,7 @@ describe('REGAPIC', () => { libStub.createShelf(requestObject, {}, {}, (err?: {}) => { assert.strictEqual( spy.getCall(0).returnValue?.queryString, - 'queryStringParameter=must-be-preserved&$alt=json%3Benum-encoding=int' + 'queryStringParameter=must-be-preserved&$alt=json%3Benum-encoding=int', ); assert.strictEqual(err, null); }); @@ -476,20 +444,17 @@ describe('REGAPIC', () => { const requestObject = {shelf: shelf}; const spy = sinon.spy(); - const {GrpcClient} = await proxyquire( - '../../src/fallback.js', - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); - }, - }); - }, - '../src/transcoding.js': {transcode: spy}, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); + }, + '../src/transcoding.js': {transcode: spy}, + }); const gaxGrpcNumericEnumsMock = new GrpcClient({ ...opts, @@ -501,7 +466,7 @@ describe('REGAPIC', () => { libStub.createShelf(requestObject, {}, {}, (err?: {}) => { assert.strictEqual( spy.getCall(0).returnValue?.queryString, - '$alt=json%3Benum-encoding=int' + '$alt=json%3Benum-encoding=int', ); assert.strictEqual(err, null); }); @@ -520,21 +485,18 @@ describe('REGAPIC', () => { bookId: 9007199254740992, }; - const {GrpcClient} = await proxyquire( - '../../src/fallback.js', - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve( - Buffer.from(JSON.stringify(responseObject)) - ); - }, - }); - }, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)), + ); + }, + }); + }, + }); const gaxGrpcMock = new GrpcClient(); gaxGrpcMock @@ -552,7 +514,7 @@ describe('REGAPIC', () => { read: false; bookId: {}; } - ).name + ).name, ); assert.strictEqual( '9007199254740992', @@ -564,7 +526,7 @@ describe('REGAPIC', () => { read: false; bookId: {}; } - ).bookId + ).bookId, ); }); }); @@ -580,21 +542,18 @@ describe('REGAPIC', () => { bookId: 42, }; // incomplete types for nodeFetch, so... - const {GrpcClient} = await proxyquire( - '../../src/fallback.js', - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve( - Buffer.from(JSON.stringify(responseObject)) - ); - }, - }); - }, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)), + ); + }, + }); + }, + }); const gaxGrpcMock = new GrpcClient(); gaxGrpcMock @@ -612,7 +571,7 @@ describe('REGAPIC', () => { read: false; bookId: {}; } - ).name + ).name, ); assert.strictEqual( '42', @@ -624,7 +583,7 @@ describe('REGAPIC', () => { read: false; bookId: {}; } - ).bookId + ).bookId, ); }); }); @@ -642,21 +601,18 @@ describe('REGAPIC', () => { }; // incomplete types for nodeFetch, so... // eslint-disable-next-line @typescript-eslint/no-explicit-any - const {GrpcClient} = await proxyquire( - '../../src/fallback.js', - { - 'node-fetch': () => { - return Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve( - Buffer.from(JSON.stringify(responseObject)) - ); - }, - }); - }, - } - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)), + ); + }, + }); + }, + }); const gaxGrpcMock = new GrpcClient(); gaxGrpcMock @@ -674,7 +630,7 @@ describe('REGAPIC', () => { read: false; bookId: {}; } - ).name + ).name, ); assert.strictEqual( bookId.toString(), @@ -686,10 +642,10 @@ describe('REGAPIC', () => { read: false; bookId: {}; } - ).bookId + ).bookId, ); }); }); }); }); -}); \ No newline at end of file +}); From b6f2d8372b8e9cb6177eb93476e0892359438178 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Fri, 14 Feb 2025 18:15:08 -0800 Subject: [PATCH 60/64] run lint --- gax/test/unit/apiCallable.ts | 39 ++++---- gax/test/unit/bundling.ts | 13 ++- gax/test/unit/grpc-fallback.ts | 20 +++-- gax/test/unit/grpc.ts | 34 ++++--- gax/test/unit/iamService.ts | 102 +++++++++++---------- gax/test/unit/locationService.ts | 44 ++++----- gax/test/unit/longrunning.ts | 13 +-- gax/test/unit/operationClient.ts | 150 ++++++++++++++++--------------- gax/test/unit/pagedIteration.ts | 10 ++- gax/test/unit/regapic.ts | 2 +- gax/test/unit/util.ts | 4 +- 11 files changed, 235 insertions(+), 196 deletions(-) diff --git a/gax/test/unit/apiCallable.ts b/gax/test/unit/apiCallable.ts index 164dbab2b..1bb95126d 100644 --- a/gax/test/unit/apiCallable.ts +++ b/gax/test/unit/apiCallable.ts @@ -136,13 +136,13 @@ describe('createApiCall', () => { assert(Number(resp) - start <= 30100); }); }); - it('override just custom retry.retryCodes with retry codes', async () => { + it('override just custom retry.retryCodes with retry codes', () => { const initialRetryCodes = [1]; const overrideRetryCodes = [1, 2, 3]; // eslint-disable-next-line @typescript-eslint/no-explicit-any sinon.stub(retries, 'retryable').callsFake((func, retry): any => { - assert.strictEqual(retry.retryCodes, overrideRetryCodes); - return func; + assert.strictEqual(retry.retryCodes, overrideRetryCodes); + return func; }); function func() { @@ -161,14 +161,14 @@ describe('createApiCall', () => { }, }); - await apiCall( + apiCall( {}, { retry: { retryCodes: overrideRetryCodes, }, }, - ); + ).catch(console.error); }); it('errors when you override custom retry.shouldRetryFn with a function on a non streaming call', async () => { function neverRetry() { @@ -211,7 +211,7 @@ describe('createApiCall', () => { } }); - it('override just custom retry.backoffSettings', async () => { + it('override just custom retry.backoffSettings', () => { const initialBackoffSettings = gax.createDefaultBackoffSettings(); const overriBackoffSettings = gax.createBackoffSettings( 100, @@ -238,14 +238,14 @@ describe('createApiCall', () => { }, }); - await apiCall( + apiCall( {}, { retry: { backoffSettings: overriBackoffSettings, }, }, - ); + ).catch(console.error); }); it('errors when a resumption strategy is passed for a non streaming call', async () => { @@ -265,7 +265,7 @@ describe('createApiCall', () => { }; function func() { - Promise.resolve(); + Promise.resolve().catch(console.error); } const apiCall = createApiCall(func, { settings: { @@ -443,7 +443,7 @@ describe('retryable', () => { assert.strictEqual(toAttempt, 0); assert(deadlineArg); done(); - }); + }).catch(console.error); }); it('retries the API call with promise', async () => { @@ -464,13 +464,12 @@ describe('retryable', () => { callback(null, 1729); } const apiCall = createApiCall(func, settings); - await apiCall({}, undefined) - .then(resp => { - assert.ok(Array.isArray(resp)); - assert.strictEqual(resp[0], 1729); - assert.strictEqual(toAttempt, 0); - assert.ok(deadlineArg); - }); + await apiCall({}, undefined).then(resp => { + assert.ok(Array.isArray(resp)); + assert.strictEqual(resp[0], 1729); + assert.strictEqual(toAttempt, 0); + assert.ok(deadlineArg); + }); }); it('cancels in the middle of retries', done => { @@ -515,7 +514,7 @@ describe('retryable', () => { assert.strictEqual(err!.note, undefined); assert.strictEqual(spy.callCount, 1); done(); - }); + }).catch(console.error); }); it('aborts retries', async () => { @@ -536,7 +535,7 @@ describe('retryable', () => { assert(err!.note); assert.strictEqual(spy.callCount, toAttempt); done(); - }); + }).catch(console.error); }); it('errors on maxRetries and surfaces original error', async () => { @@ -661,7 +660,7 @@ describe('retryable', () => { assert(spy.callCount > callsLowerBound); assert(spy.callCount < callsUpperBound); done(); - }); + }).catch(console.error); }); it.skip('reports A/B testing', () => { diff --git a/gax/test/unit/bundling.ts b/gax/test/unit/bundling.ts index 02b5c2a25..94c512dad 100644 --- a/gax/test/unit/bundling.ts +++ b/gax/test/unit/bundling.ts @@ -881,13 +881,12 @@ describe('bundleable', () => { const apiCall = createApiCall(spy, settings); await apiCall({field1: [1, 2, 3], field2: 'id'}, undefined, (err, obj) => { if (err) { - return err; + throw err; } else { callback([obj]); } }); - await apiCall({field1: [1, 2, 3], field2: 'id'}, undefined) - .then(callback) + await apiCall({field1: [1, 2, 3], field2: 'id'}, undefined).then(callback); }); it('does not fail if bundle field is not set', done => { @@ -1001,27 +1000,27 @@ describe('bundleable', () => { } else { callback(); } - }); + }).catch(console.error); apiCall({data: ['data1'], logName: 'log2'}, undefined, err => { if (err) { done(err); } else { callback(); } - }); + }).catch(console.error); apiCall({data: ['data2'], logName: 'log1'}, undefined, err => { if (err) { done(err); } else { callback(); } - }); + }).catch(console.error); apiCall({data: ['data2'], logName: 'log2'}, undefined, err => { if (err) { done(err); } else { callback(); } - }); + }).catch(console.error); }); }); diff --git a/gax/test/unit/grpc-fallback.ts b/gax/test/unit/grpc-fallback.ts index 771e57b3d..f12fc3801 100644 --- a/gax/test/unit/grpc-fallback.ts +++ b/gax/test/unit/grpc-fallback.ts @@ -138,18 +138,22 @@ describe('createStub', () => { it('validates universe domain if set', async () => { const opts = {...stubOptions, universeDomain: 'example.com'}; - assert.rejects( - gaxGrpc.createStub(echoService, opts), - /configured universe domain/, - ); + assert + .rejects( + gaxGrpc.createStub(echoService, opts), + /configured universe domain/, + ) + .catch(console.error); }); it('validates universe domain if unset', async () => { authClient.universeDomain = 'example.com'; - assert.rejects( - gaxGrpc.createStub(echoService, stubOptions), - /configured universe domain/, - ); + assert + .rejects( + gaxGrpc.createStub(echoService, stubOptions), + /configured universe domain/, + ) + .catch(console.error); // reset to default value authClient.universeDomain = 'googleapis.com'; }); diff --git a/gax/test/unit/grpc.ts b/gax/test/unit/grpc.ts index 6f8de7c81..6d5de2f7f 100644 --- a/gax/test/unit/grpc.ts +++ b/gax/test/unit/grpc.ts @@ -184,22 +184,26 @@ describe('grpc', () => { port: 443, universeDomain: 'example.com', }; - assert.rejects( - // @ts-ignore - grpcClient.createStub(DummyStub, opts), - /configured universe domain/, - ); + assert + .rejects( + // @ts-ignore + grpcClient.createStub(DummyStub, opts), + /configured universe domain/, + ) + .catch(console.error); }); it('validates universe domain if unset', async () => { const opts = {servicePath: 'foo.example.com', port: 443}; stubAuth.getUniverseDomain.reset(); stubAuth.getUniverseDomain.resolves('example.com'); - assert.rejects( - // @ts-ignore - grpcClient.createStub(DummyStub, opts), - /configured universe domain/, - ); + assert + .rejects( + // @ts-ignore + grpcClient.createStub(DummyStub, opts), + /configured universe domain/, + ) + .catch(console.error); }); it('supports optional parameters', () => { @@ -711,10 +715,12 @@ dvorak // Create a client and test the certificate detection flow: process.env.GOOGLE_API_USE_CLIENT_CERTIFICATE = 'true'; const clientMock = new GrpcClient(); - assert.rejects( - clientMock.createStub(DummyStub, {universeDomain: 'example.com'}), - /configured universe domain/, - ); + assert + .rejects( + clientMock.createStub(DummyStub, {universeDomain: 'example.com'}), + /configured universe domain/, + ) + .catch(console.error); await fsp.rm(tmpFolder, {recursive: true, force: true}); // Cleanup. }); }); diff --git a/gax/test/unit/iamService.ts b/gax/test/unit/iamService.ts index d88ef23bd..56c88ddb4 100644 --- a/gax/test/unit/iamService.ts +++ b/gax/test/unit/iamService.ts @@ -57,7 +57,7 @@ describe('IAM service', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( new protos.google.iam.v1.GetIamPolicyRequest(), ); @@ -88,7 +88,7 @@ describe('IAM service', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( new protos.google.iam.v1.GetIamPolicyRequest(), ); @@ -107,17 +107,22 @@ describe('IAM service', () => { client.innerApiCalls.getIamPolicy = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { - client.getIamPolicy( - request, - expectedOptions, - (err?: Error | null, result?: protos.google.iam.v1.Policy | null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }, - ); + client + .getIamPolicy( + request, + expectedOptions, + ( + err?: Error | null, + result?: protos.google.iam.v1.Policy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(console.error); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); @@ -133,7 +138,7 @@ describe('IAM service', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( new protos.google.iam.v1.GetIamPolicyRequest(), ); @@ -168,7 +173,7 @@ describe('IAM service', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( new protos.google.iam.v1.SetIamPolicyRequest(), ); @@ -199,7 +204,7 @@ describe('IAM service', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( new protos.google.iam.v1.SetIamPolicyRequest(), ); @@ -218,17 +223,22 @@ describe('IAM service', () => { client.innerApiCalls.setIamPolicy = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { - client.setIamPolicy( - request, - expectedOptions, - (err?: Error | null, result?: protos.google.iam.v1.Policy | null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }, - ); + client + .setIamPolicy( + request, + expectedOptions, + ( + err?: Error | null, + result?: protos.google.iam.v1.Policy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(console.error); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); @@ -244,7 +254,7 @@ describe('IAM service', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( new protos.google.iam.v1.SetIamPolicyRequest(), ); @@ -279,7 +289,7 @@ describe('IAM service', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( new protos.google.iam.v1.TestIamPermissionsRequest(), ); @@ -314,7 +324,7 @@ describe('IAM service', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( new protos.google.iam.v1.TestIamPermissionsRequest(), ); @@ -333,20 +343,22 @@ describe('IAM service', () => { client.innerApiCalls.testIamPermissions = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { - client.testIamPermissions( - request, - expectedOptions, - ( - err?: Error | null, - result?: protos.google.iam.v1.TestIamPermissionsResponse | null, - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }, - ); + client + .testIamPermissions( + request, + expectedOptions, + ( + err?: Error | null, + result?: protos.google.iam.v1.TestIamPermissionsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(console.error); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); @@ -362,7 +374,7 @@ describe('IAM service', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( new protos.google.iam.v1.TestIamPermissionsRequest(), ); diff --git a/gax/test/unit/locationService.ts b/gax/test/unit/locationService.ts index 03afd6843..cb2119cb5 100644 --- a/gax/test/unit/locationService.ts +++ b/gax/test/unit/locationService.ts @@ -77,7 +77,7 @@ describe('LocationsClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( new protos.google.cloud.location.GetLocationRequest(), ); @@ -109,7 +109,7 @@ describe('LocationsClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( new protos.google.cloud.location.GetLocationRequest(), ); @@ -128,19 +128,21 @@ describe('LocationsClient', () => { client.innerApiCalls.getLocation = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { - client.getLocation( - request, - ( - err?: Error | null, - result?: protos.google.cloud.location.ILocation | null, - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }, - ); + client + .getLocation( + request, + ( + err?: Error | null, + result?: protos.google.cloud.location.ILocation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(console.error); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); @@ -156,7 +158,7 @@ describe('LocationsClient', () => { const client = new LocationsClient(grpcClient, { projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( new protos.google.cloud.location.GetLocationRequest(), ); @@ -193,7 +195,7 @@ describe('LocationsClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( new protos.google.cloud.location.ListLocationsRequest(), ); @@ -227,7 +229,7 @@ describe('LocationsClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( new protos.google.cloud.location.ListLocationsRequest(), ); @@ -277,7 +279,7 @@ describe('LocationsClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( new protos.google.cloud.location.ListLocationsRequest(), ); @@ -312,7 +314,7 @@ describe('LocationsClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( new protos.google.cloud.location.ListLocationsRequest(), ); @@ -351,7 +353,7 @@ describe('LocationsClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( new protos.google.cloud.location.ListLocationsRequest(), ); diff --git a/gax/test/unit/longrunning.ts b/gax/test/unit/longrunning.ts index acbfb3f90..ce48e7854 100644 --- a/gax/test/unit/longrunning.ts +++ b/gax/test/unit/longrunning.ts @@ -522,11 +522,14 @@ describe('longrunning', () => { .then(responses => { const operation = responses[0] as longrunning.Operation; const p = operation.promise(); - operation.cancel().then(() => { - assert.strictEqual(client.cancelOperation.called, true); - assert.strictEqual(client.cancelGetOperationSpy.called, true); - done(); - }); + operation + .cancel() + .then(() => { + assert.strictEqual(client.cancelOperation.called, true); + assert.strictEqual(client.cancelGetOperationSpy.called, true); + done(); + }) + .catch(console.error); return p; }) .then(() => { diff --git a/gax/test/unit/operationClient.ts b/gax/test/unit/operationClient.ts index 63b063392..f3d7a6f7e 100644 --- a/gax/test/unit/operationClient.ts +++ b/gax/test/unit/operationClient.ts @@ -158,20 +158,22 @@ describe('operation client', () => { client.innerApiCalls.getOperation = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { - client.getOperation( - request, - undefined, - ( - err?: Error | null, - result?: protos.google.longrunning.Operation | null, - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }, - ); + client + .getOperation( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.longrunning.Operation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(console.error); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); @@ -259,20 +261,22 @@ describe('operation client', () => { client.innerApiCalls.getOperation = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { - client.getOperationInternal( - request, - undefined, - ( - err?: Error | null, - result?: protos.google.longrunning.Operation | null, - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }, - ); + client + .getOperationInternal( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.longrunning.Operation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(console.error); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); @@ -356,20 +360,22 @@ describe('operation client', () => { client.innerApiCalls.listOperations = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { - client.listOperations( - request, - undefined, - ( - err?: Error | null, - result?: protos.google.longrunning.ListOperationsResponse | null, - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }, - ); + client + .listOperations( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.longrunning.ListOperationsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(console.error); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); @@ -606,20 +612,22 @@ describe('operation client', () => { client.innerApiCalls.cancelOperation = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { - client.cancelOperation( - request, - undefined, - ( - err?: Error | null, - result?: protos.google.protobuf.Empty | null, - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }, - ); + client + .cancelOperation( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.protobuf.Empty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(console.error); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); @@ -703,20 +711,22 @@ describe('operation client', () => { client.innerApiCalls.deleteOperation = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { - client.deleteOperation( - request, - undefined, - ( - err?: Error | null, - result?: protos.google.protobuf.Empty | null, - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }, - ); + client + .deleteOperation( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.protobuf.Empty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(console.error); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); diff --git a/gax/test/unit/pagedIteration.ts b/gax/test/unit/pagedIteration.ts index daf261a9b..301317bd1 100644 --- a/gax/test/unit/pagedIteration.ts +++ b/gax/test/unit/pagedIteration.ts @@ -109,7 +109,7 @@ describe('paged iteration', () => { assert.strictEqual(err, null); assert.deepStrictEqual(results, expected); done(); - }); + }).catch(console.error); }); it('returns a response when autoPaginate is false', done => { @@ -171,13 +171,17 @@ describe('paged iteration', () => { next, {autoPaginate: false}, callback as unknown as APICallback, - ); + ).catch(console.error); } else { assert.strictEqual(counter, pagesToStream + 1); done(); } } - apiCall({}, {autoPaginate: false}, callback as unknown as APICallback); + apiCall( + {}, + {autoPaginate: false}, + callback as unknown as APICallback, + ).catch(console.error); }); it('retries on failure', done => { diff --git a/gax/test/unit/regapic.ts b/gax/test/unit/regapic.ts index 197ddf2d5..0dad7e81a 100644 --- a/gax/test/unit/regapic.ts +++ b/gax/test/unit/regapic.ts @@ -193,7 +193,7 @@ describe('REGAPIC', () => { stream.on('error', (err: Error) => { assert.strictEqual((err as Error).message, 'Fetch error'); }); - }); + }).catch(console.error); }); describe('should support enum conversion in proto message', () => { diff --git a/gax/test/unit/util.ts b/gax/test/unit/util.ts index e9e882a36..1e0f5c745 100644 --- a/gax/test/unit/util.ts +++ b/gax/test/unit/util.ts @@ -81,7 +81,7 @@ describe('util.ts', () => { ); }); - it('returns UUID', () => { - assert.match(makeUUID(), /[a-z0-9-]{36}/); + it('returns UUID', async () => { + assert.match(await makeUUID(), /[a-z0-9-]{36}/); }); }); From 6bdcbd0e4dda615a9c728f805a5eb64b9b7b6b45 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Fri, 14 Feb 2025 18:27:23 -0800 Subject: [PATCH 61/64] fix tests --- gax/test/unit/apiCallable.ts | 14 ++++++-------- gax/test/unit/bundling.ts | 27 +++++++++++++-------------- gax/test/unit/pagedIteration.ts | 27 +++++++++++---------------- 3 files changed, 30 insertions(+), 38 deletions(-) diff --git a/gax/test/unit/apiCallable.ts b/gax/test/unit/apiCallable.ts index 1bb95126d..d31e6c64d 100644 --- a/gax/test/unit/apiCallable.ts +++ b/gax/test/unit/apiCallable.ts @@ -420,7 +420,7 @@ describe('retryable', () => { settings: {timeout: 0, retry: retryOptions, apiName: 'TestApi'}, }; - it('retries the API call', done => { + it('retries the API call', async () => { let toAttempt = 3; let deadlineArg: string; function func( @@ -438,12 +438,11 @@ describe('retryable', () => { callback(null, 1729); } const apiCall = createApiCall(func, settings); - apiCall({}, undefined, (err, resp) => { + await apiCall({}, undefined, (err, resp) => { assert.strictEqual(resp, 1729); assert.strictEqual(toAttempt, 0); assert(deadlineArg); - done(); - }).catch(console.error); + }); }); it('retries the API call with promise', async () => { @@ -500,7 +499,7 @@ describe('retryable', () => { }); }); - it("doesn't retry if no codes", done => { + it("doesn't retry if no codes", async () => { const retryOptions = gax.createRetryOptions( [], gax.createBackoffSettings(1, 2, 3, 4, 5, 6, 7), @@ -508,13 +507,12 @@ describe('retryable', () => { const settings = {settings: {timeout: 0, retry: retryOptions}}; const spy = sinon.spy(fail); const apiCall = createApiCall(spy, settings); - apiCall({}, undefined, err => { + await apiCall({}, undefined, err => { assert.ok(err instanceof Error); assert.strictEqual(err!.code, FAKE_STATUS_CODE_1); assert.strictEqual(err!.note, undefined); assert.strictEqual(spy.callCount, 1); - done(); - }).catch(console.error); + }); }); it('aborts retries', async () => { diff --git a/gax/test/unit/bundling.ts b/gax/test/unit/bundling.ts index 94c512dad..ac16ae0b6 100644 --- a/gax/test/unit/bundling.ts +++ b/gax/test/unit/bundling.ts @@ -975,7 +975,7 @@ describe('bundleable', () => { p.cancel(); }); - it('properly processes camel case fields', done => { + it('properly processes camel case fields', async () => { const descriptor = new BundleDescriptor( 'data', ['log_name'], @@ -990,37 +990,36 @@ describe('bundleable', () => { const callback = sinon.spy(() => { if (callback.callCount === 4) { assert.strictEqual(spy.callCount, 2); // we expect two requests, each has two items - done(); } }); const apiCall = createApiCall(spy, settings); - apiCall({data: ['data1'], logName: 'log1'}, undefined, err => { + await apiCall({data: ['data1'], logName: 'log1'}, undefined, err => { if (err) { - done(err); + throw err; } else { callback(); } - }).catch(console.error); - apiCall({data: ['data1'], logName: 'log2'}, undefined, err => { + }); + await apiCall({data: ['data1'], logName: 'log2'}, undefined, err => { if (err) { - done(err); + throw err; } else { callback(); } - }).catch(console.error); - apiCall({data: ['data2'], logName: 'log1'}, undefined, err => { + }); + await apiCall({data: ['data2'], logName: 'log1'}, undefined, err => { if (err) { - done(err); + throw err; } else { callback(); } - }).catch(console.error); - apiCall({data: ['data2'], logName: 'log2'}, undefined, err => { + }); + await apiCall({data: ['data2'], logName: 'log2'}, undefined, err => { if (err) { - done(err); + throw err; } else { callback(); } - }).catch(console.error); + }); }); }); diff --git a/gax/test/unit/pagedIteration.ts b/gax/test/unit/pagedIteration.ts index 301317bd1..f03f932d2 100644 --- a/gax/test/unit/pagedIteration.ts +++ b/gax/test/unit/pagedIteration.ts @@ -99,17 +99,16 @@ describe('paged iteration', () => { .catch(done); }); - it('calls callback with an Array', done => { + it('calls callback with an Array', async () => { const apiCall = util.createApiCall(func, createOptions); const expected: Array<{}> = []; for (let i = 0; i < pageSize * pagesToStream; ++i) { expected.push(i); } - apiCall({}, undefined, (err, results) => { + await apiCall({}, undefined, (err, results) => { assert.strictEqual(err, null); assert.deepStrictEqual(results, expected); - done(); - }).catch(console.error); + }) }); it('returns a response when autoPaginate is false', done => { @@ -147,17 +146,16 @@ describe('paged iteration', () => { .catch(done); }); - it('sets additional arguments to the callback', done => { + it('sets additional arguments to the callback', async () => { let counter = 0; const apiCall = util.createApiCall(func, createOptions); - function callback( + async function callback( err: {}, resources: {}, next: {}, rawResponse: {nums: {}}, ) { if (err) { - done(err); return; } counter++; @@ -167,24 +165,23 @@ describe('paged iteration', () => { assert(rawResponse.hasOwnProperty('nums')); assert.strictEqual(rawResponse.nums, resources); if (next) { - apiCall( + await apiCall( next, {autoPaginate: false}, callback as unknown as APICallback, - ).catch(console.error); + ) } else { assert.strictEqual(counter, pagesToStream + 1); - done(); } } - apiCall( + await apiCall( {}, {autoPaginate: false}, callback as unknown as APICallback, - ).catch(console.error); + ); }); - it('retries on failure', done => { + it('retries on failure', async () => { let callCount = 0; function failingFunc( request: {}, @@ -200,14 +197,12 @@ describe('paged iteration', () => { } } const apiCall = util.createApiCall(failingFunc, createOptions); - apiCall({}, undefined) + await apiCall({}, undefined) .then(resources => { assert(Array.isArray(resources)); // @ts-ignore response type assert.strictEqual(resources[0].length, pageSize * pagesToStream); - done(); }) - .catch(done); }); it('caps the results by maxResults', () => { From f047cf8ffff1f357524f481920ef16c1446ffe0c Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Fri, 14 Feb 2025 18:35:50 -0800 Subject: [PATCH 62/64] fix tests --- gax/src/util.ts | 4 ++-- gax/test/unit/util.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/gax/src/util.ts b/gax/src/util.ts index 7a17eeed4..e52e241ef 100644 --- a/gax/src/util.ts +++ b/gax/src/util.ts @@ -13,8 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const randomUUID = async () => - globalThis.crypto?.randomUUID() || (await import('crypto')).randomUUID(); +const randomUUID = () => + globalThis.crypto?.randomUUID() || require('crypto').randomUUID(); function words(str: string, normalize = false) { if (normalize) { diff --git a/gax/test/unit/util.ts b/gax/test/unit/util.ts index 1e0f5c745..e9e882a36 100644 --- a/gax/test/unit/util.ts +++ b/gax/test/unit/util.ts @@ -81,7 +81,7 @@ describe('util.ts', () => { ); }); - it('returns UUID', async () => { - assert.match(await makeUUID(), /[a-z0-9-]{36}/); + it('returns UUID', () => { + assert.match(makeUUID(), /[a-z0-9-]{36}/); }); }); From 4ea8b2b23c7f42a86fbc92fddfa5465d19de7a3d Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Fri, 14 Feb 2025 18:41:46 -0800 Subject: [PATCH 63/64] run lint --- gax/test/unit/pagedIteration.ts | 15 +++++++-------- gax/test/unit/regapic.ts | 15 +++++++++------ 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/gax/test/unit/pagedIteration.ts b/gax/test/unit/pagedIteration.ts index f03f932d2..b0556d82c 100644 --- a/gax/test/unit/pagedIteration.ts +++ b/gax/test/unit/pagedIteration.ts @@ -108,7 +108,7 @@ describe('paged iteration', () => { await apiCall({}, undefined, (err, results) => { assert.strictEqual(err, null); assert.deepStrictEqual(results, expected); - }) + }); }); it('returns a response when autoPaginate is false', done => { @@ -169,7 +169,7 @@ describe('paged iteration', () => { next, {autoPaginate: false}, callback as unknown as APICallback, - ) + ); } else { assert.strictEqual(counter, pagesToStream + 1); } @@ -197,12 +197,11 @@ describe('paged iteration', () => { } } const apiCall = util.createApiCall(failingFunc, createOptions); - await apiCall({}, undefined) - .then(resources => { - assert(Array.isArray(resources)); - // @ts-ignore response type - assert.strictEqual(resources[0].length, pageSize * pagesToStream); - }) + await apiCall({}, undefined).then(resources => { + assert(Array.isArray(resources)); + // @ts-ignore response type + assert.strictEqual(resources[0].length, pageSize * pagesToStream); + }); }); it('caps the results by maxResults', () => { diff --git a/gax/test/unit/regapic.ts b/gax/test/unit/regapic.ts index 0dad7e81a..0616d7cb7 100644 --- a/gax/test/unit/regapic.ts +++ b/gax/test/unit/regapic.ts @@ -188,12 +188,15 @@ describe('REGAPIC', () => { }); const gaxGrpcMock = new GrpcClient(); - gaxGrpc.createStub(echoService, stubOptions).then((echoStub: any) => { - const stream = echoStub.expand(requestObject) as StreamArrayParser; - stream.on('error', (err: Error) => { - assert.strictEqual((err as Error).message, 'Fetch error'); - }); - }).catch(console.error); + gaxGrpc + .createStub(echoService, stubOptions) + .then((echoStub: any) => { + const stream = echoStub.expand(requestObject) as StreamArrayParser; + stream.on('error', (err: Error) => { + assert.strictEqual((err as Error).message, 'Fetch error'); + }); + }) + .catch(console.error); }); describe('should support enum conversion in proto message', () => { From c90e5744d38530ddd8bdb6fa61af58b91aadbc3f Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Tue, 18 Feb 2025 16:20:26 -0800 Subject: [PATCH 64/64] upgradependencies --- gax/package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gax/package.json b/gax/package.json index 99ede9172..014e25a12 100644 --- a/gax/package.json +++ b/gax/package.json @@ -18,9 +18,9 @@ "google-auth-library": "^9.15.1", "node-fetch": "^3.3.2", "object-hash": "^3.0.0", - "proto3-json-serializer": "^2.0.2", + "proto3-json-serializer": "^3.0.0", "protobufjs": "^7.4.0", - "retry-request": "^7.0.2" + "retry-request": "^8.0.0" }, "devDependencies": { "@babel/plugin-proposal-private-methods": "^7.18.6",