From 6234521ad7fb1d8a418443f0ea86dbb218e8b435 Mon Sep 17 00:00:00 2001 From: Thiyagu K Date: Wed, 23 Oct 2024 09:12:54 +0000 Subject: [PATCH 01/11] Adds support for the restore token feature --- src/file.ts | 9 ++++++ system-test/storage.ts | 73 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+) diff --git a/src/file.ts b/src/file.ts index e808f5c9a..5e7fb2935 100644 --- a/src/file.ts +++ b/src/file.ts @@ -178,6 +178,7 @@ export interface GetFileMetadataCallback { export interface GetFileOptions extends GetConfig { userProject?: string; generation?: number; + restoreToken?: string; softDeleted?: boolean; } @@ -354,6 +355,7 @@ export interface FileOptions { crc32cGenerator?: CRC32CValidatorGenerator; encryptionKey?: string | Buffer; generation?: number | string; + restoreToken?: string; kmsKeyName?: string; preconditionOpts?: PreconditionOptions; userProject?: string; @@ -450,6 +452,7 @@ export interface SetStorageClassCallback { export interface RestoreOptions extends PreconditionOptions { generation: number; + restoreToken?: string; projection?: 'full' | 'noAcl'; } @@ -471,6 +474,7 @@ export interface FileMetadata extends BaseMetadata { eventBasedHold?: boolean | null; readonly eventBasedHoldReleaseTime?: string; generation?: string | number; + restoreToken?: string; hardDeleteTime?: string; kmsKeyName?: string; md5Hash?: string; @@ -547,6 +551,7 @@ class File extends ServiceObject { name: string; generation?: number; + restoreToken?: string; parent!: Bucket; private encryptionKey?: string | Buffer; @@ -844,6 +849,8 @@ class File extends ServiceObject { * @param {string} [options.userProject] The ID of the project which will be * billed for the request. * @param {number} [options.generation] The generation number to get + * @param {string} [options.restoreToken] If this is a soft-deleted object in an HNS-enabled bucket, returns the restore token which will + * be necessary to restore it if there's a name conflict with another object. * @param {boolean} [options.softDeleted] If true, returns the soft-deleted object. Object `generation` is required if `softDeleted` is set to True. * @param {GetFileCallback} [callback] Callback function. @@ -3707,6 +3714,8 @@ class File extends ServiceObject { * @param {string} [userProject] The ID of the project which will be * billed for the request. * @param {number} [generation] If present, selects a specific revision of this object. + * @param {string} [restoreToken] If this is a soft-deleted object in an HNS-enabled bucket, returns the restore token which will + * be necessary to restore it if there's a name conflict with another object. * @param {string} [projection] Specifies the set of properties to return. If used, must be 'full' or 'noAcl'. * @param {string | number} [ifGenerationMatch] Request proceeds if the generation of the target resource * matches the value used in the precondition. diff --git a/system-test/storage.ts b/system-test/storage.ts index 4b004c830..6c33cf7ac 100644 --- a/system-test/storage.ts +++ b/system-test/storage.ts @@ -792,6 +792,7 @@ describe('storage', function () { describe('soft-delete', () => { let bucket: Bucket; + let hnsBucket: Bucket; const SOFT_DELETE_RETENTION_SECONDS = 7 * 24 * 60 * 60; //7 days in seconds; beforeEach(async () => { @@ -802,11 +803,26 @@ describe('storage', function () { retentionDurationSeconds: SOFT_DELETE_RETENTION_SECONDS, }, }); + + hnsBucket = storage.bucket(generateName()); + await storage.createBucket(hnsBucket.name, { + hierarchicalNamespace: {enabled: true}, + iamConfiguration: { + uniformBucketLevelAccess: { + enabled: true, + }, + }, + softDeletePolicy: { + retentionDurationSeconds: SOFT_DELETE_RETENTION_SECONDS, + }, + }); }); afterEach(async () => { await bucket.deleteFiles({force: true, versions: true}); await bucket.delete(); + await hnsBucket.deleteFiles({force: true, versions: true}); + await hnsBucket.delete(); }); it('should set softDeletePolicy correctly', async () => { @@ -862,6 +878,63 @@ describe('storage', function () { [files] = await bucket.getFiles(); assert.strictEqual(files.length, 1); }); + + it('should LIST soft-deleted files with restore token', async () => { + const f1 = hnsBucket.file('file5a'); + const f2 = hnsBucket.file('file5b'); + await f1.save('file5a'); + await f2.save('file5b'); + await f1.delete(); + await f2.delete(); + const [notSoftDeletedFiles] = await hnsBucket.getFiles(); + assert.strictEqual(notSoftDeletedFiles.length, 0); + const [softDeletedFiles] = await hnsBucket.getFiles({softDeleted: true}); + assert.strictEqual(softDeletedFiles.length, 2); + assert.notStrictEqual( + softDeletedFiles![0].metadata.restoreToken, + undefined + ); + }); + + it('should GET a soft-deleted file with restore token', async () => { + const f1 = hnsBucket.file('file6'); + await f1.save('file6'); + const [metadata] = await f1.getMetadata(); + await f1.delete(); + const [softDeletedFile] = await f1.get({ + softDeleted: true, + generation: parseInt(metadata.generation?.toString() || '0'), + }); + assert(softDeletedFile); + assert.strictEqual( + softDeletedFile.metadata.generation, + metadata.generation + ); + assert.notStrictEqual(softDeletedFile.metadata.restoreToken, undefined); + }); + + it('should restore a soft-deleted file using restoreToken', async () => { + const f1 = hnsBucket.file('file7'); + await f1.save('file7'); + const [metadata] = await f1.getMetadata(); + await f1.delete(); + let [files] = await hnsBucket.getFiles(); + assert.strictEqual(files.length, 0); + const [softDeletedFile] = await f1.get({ + softDeleted: true, + generation: parseInt(metadata.generation?.toString() || '0'), + }); + assert(softDeletedFile); + const restoredFile = await f1.restore({ + generation: parseInt( + softDeletedFile.metadata.generation?.toString() || '0' + ), + restoreToken: softDeletedFile.metadata.restoreToken, + }); + assert(restoredFile); + [files] = await hnsBucket.getFiles(); + assert.strictEqual(files.length, 1); + }); }); describe('dual-region', () => { From 96a7664b151fc93b1c7bbefba0295258cc9ee564 Mon Sep 17 00:00:00 2001 From: Thiyagu K Date: Wed, 23 Oct 2024 10:50:52 +0000 Subject: [PATCH 02/11] description fix --- src/file.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/file.ts b/src/file.ts index 5e7fb2935..d8ff1a216 100644 --- a/src/file.ts +++ b/src/file.ts @@ -3714,8 +3714,8 @@ class File extends ServiceObject { * @param {string} [userProject] The ID of the project which will be * billed for the request. * @param {number} [generation] If present, selects a specific revision of this object. - * @param {string} [restoreToken] If this is a soft-deleted object in an HNS-enabled bucket, returns the restore token which will - * be necessary to restore it if there's a name conflict with another object. + * @param {string} [restoreToken] Returns an option that must be specified when getting a soft-deleted object from an HNS-enabled + * bucket that has a naming and generation conflict with another object in the same bucket. * @param {string} [projection] Specifies the set of properties to return. If used, must be 'full' or 'noAcl'. * @param {string | number} [ifGenerationMatch] Request proceeds if the generation of the target resource * matches the value used in the precondition. From 912b32e53d4377103e8f2f7ac5f2736ecde1eaa6 Mon Sep 17 00:00:00 2001 From: Thiyagu K Date: Fri, 25 Oct 2024 05:54:08 +0000 Subject: [PATCH 03/11] lint fix --- test/transfer-manager.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/test/transfer-manager.ts b/test/transfer-manager.ts index 6280a5c44..c2d0d750c 100644 --- a/test/transfer-manager.ts +++ b/test/transfer-manager.ts @@ -26,7 +26,6 @@ import { MultiPartUploadError, MultiPartUploadHelper, UploadOptions, - UploadManyFilesOptions, TransferManager, Storage, DownloadResponse, From 1f78d9fdca813e8f6ba6ff4d82d642bdf9898a0b Mon Sep 17 00:00:00 2001 From: Thiyagu K Date: Wed, 4 Dec 2024 14:04:29 +0000 Subject: [PATCH 04/11] upgrade to node 18 upgrade to node 18 --- .github/sync-repo-settings.yaml | 3 +-- .github/workflows/ci.yaml | 8 ++++---- .github/workflows/conformance-test.yaml | 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 package.json | 16 +++++++-------- src/file.ts | 2 +- tsconfig.cjs.json | 4 +++- tsconfig.json | 3 ++- 12 files changed, 20 insertions(+), 70 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 diff --git a/.github/sync-repo-settings.yaml b/.github/sync-repo-settings.yaml index 28901a224..556bfc53d 100644 --- a/.github/sync-repo-settings.yaml +++ b/.github/sync-repo-settings.yaml @@ -14,9 +14,8 @@ branchProtectionRules: - "ci/kokoro: System test" - docs - lint - - test (14) - - test (16) - test (18) + - test (20) - cla/google - windows - OwlBot Post Processor diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 4892eb2c5..8babaf86d 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, 18, 20] + node: [18, 20, 22] steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 @@ -32,7 +32,7 @@ jobs: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: - node-version: 14 + node-version: 18 - run: npm install --engine-strict - run: npm test env: @@ -43,7 +43,7 @@ jobs: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: - node-version: 14 + node-version: 18 - run: npm install - run: npm run lint docs: @@ -52,7 +52,7 @@ jobs: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: - node-version: 14 + node-version: 18 - run: npm install - run: npm run docs - uses: JustinBeckwith/linkinator-action@v1 diff --git a/.github/workflows/conformance-test.yaml b/.github/workflows/conformance-test.yaml index dbe15f0ff..803f90710 100644 --- a/.github/workflows/conformance-test.yaml +++ b/.github/workflows/conformance-test.yaml @@ -11,7 +11,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - run: node --version - run: npm install - run: npm run conformance-test diff --git a/.kokoro/continuous/node14/common.cfg b/.kokoro/continuous/node14/common.cfg deleted file mode 100644 index 4ee7584a3..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: "nodejs-storage/.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/nodejs-storage/.kokoro/test.sh" -} diff --git a/.kokoro/continuous/node14/lint.cfg b/.kokoro/continuous/node14/lint.cfg deleted file mode 100644 index 72c4ad241..000000000 --- a/.kokoro/continuous/node14/lint.cfg +++ /dev/null @@ -1,4 +0,0 @@ -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/nodejs-storage/.kokoro/lint.sh" -} diff --git a/.kokoro/continuous/node14/samples-test.cfg b/.kokoro/continuous/node14/samples-test.cfg deleted file mode 100644 index 2137cefc0..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/nodejs-storage/.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 c7c9507a8..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/nodejs-storage/.kokoro/system-test.sh" -} - -env_vars: { - key: "SECRET_MANAGER_KEYS" - value: "long-door-651-kokoro-system-test-service-account,client-library-test-universe-domain-credential" -} \ 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/package.json b/package.json index 1fffeedc4..ae846f34e 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "license": "Apache-2.0", "author": "Google Inc.", "engines": { - "node": ">=14" + "node": ">=18" }, "repository": "googleapis/nodejs-storage", "main": "./build/cjs/src/index.js", @@ -80,7 +80,7 @@ "duplexify": "^4.1.3", "fast-xml-parser": "^4.4.1", "gaxios": "^6.0.2", - "google-auth-library": "^9.6.3", + "google-auth-library": "^9.14.2", "html-entities": "^2.5.2", "mime": "^3.0.0", "p-limit": "^3.0.1", @@ -109,23 +109,23 @@ "@types/yargs": "^17.0.10", "c8": "^9.0.0", "form-data": "^4.0.0", - "gapic-tools": "^0.4.0", - "gts": "^5.0.0", + "gapic-tools": "^0.4.6", + "gts": "^6.0.2", "jsdoc": "^4.0.0", "jsdoc-fresh": "^3.0.0", "jsdoc-region-tag": "^3.0.0", - "linkinator": "^3.0.0", + "linkinator": "^6.1.2", "mocha": "^9.2.2", "mockery": "^2.1.0", + "nise": "6.0.0", "nock": "~13.5.0", "node-fetch": "^2.6.7", "pack-n-play": "^2.0.0", + "path-to-regexp": "6.3.0", "proxyquire": "^2.1.3", "sinon": "^18.0.0", - "nise": "6.0.0", - "path-to-regexp": "6.3.0", "tmp": "^0.2.0", - "typescript": "^5.1.6", + "typescript": "^5.7.2", "yargs": "^17.3.1" } } diff --git a/src/file.ts b/src/file.ts index fbbe60612..6d0bf9ac5 100644 --- a/src/file.ts +++ b/src/file.ts @@ -552,7 +552,7 @@ class File extends ServiceObject { generation?: number; restoreToken?: string; - parent!: Bucket; + declare parent: Bucket; private encryptionKey?: string | Buffer; private encryptionKeyBase64?: string; diff --git a/tsconfig.cjs.json b/tsconfig.cjs.json index d0dbd70c6..f57a7227f 100644 --- a/tsconfig.cjs.json +++ b/tsconfig.cjs.json @@ -14,6 +14,8 @@ "system-test/*.ts", "conformance-test/*.ts", "conformance-test/scenarios/*.ts", - "internal-tooling/*.ts" + "internal-tooling/*.ts", + "src/nodejs-common/*.ts", + "conformance-test/test-data/*.json" ] } diff --git a/tsconfig.json b/tsconfig.json index bf65354d9..4167eb036 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -14,6 +14,7 @@ "src/*.ts", "src/*.cjs", "internal-tooling/*.ts", - "system-test/*.ts" + "system-test/*.ts", + "src/nodejs-common/*.ts" ] } \ No newline at end of file From 5e0a9785ba9614b03a01bf4b7971a188fb16981e Mon Sep 17 00:00:00 2001 From: Thiyagu K Date: Wed, 4 Dec 2024 14:18:09 +0000 Subject: [PATCH 05/11] lint fix phase 1 lint fix phase 1 --- conformance-test/conformanceCommon.ts | 24 +- conformance-test/globalHooks.ts | 2 +- conformance-test/libraryMethods.ts | 60 ++-- conformance-test/scenarios/scenarioFive.ts | 2 +- conformance-test/scenarios/scenarioFour.ts | 2 +- conformance-test/scenarios/scenarioOne.ts | 2 +- conformance-test/scenarios/scenarioSeven.ts | 2 +- conformance-test/scenarios/scenarioSix.ts | 2 +- conformance-test/scenarios/scenarioThree.ts | 2 +- conformance-test/scenarios/scenarioTwo.ts | 2 +- conformance-test/v4SignedUrl.ts | 20 +- .../performApplicationPerformanceTest.ts | 8 +- internal-tooling/performPerformanceTest.ts | 6 +- .../performTransferManagerTest.ts | 8 +- internal-tooling/performanceTest.ts | 6 +- internal-tooling/performanceUtils.ts | 26 +- samples/addBucketConditionalBinding.js | 4 +- samples/addBucketIamMember.js | 4 +- samples/addBucketLabel.js | 2 +- samples/addBucketWebsiteConfiguration.js | 4 +- samples/addFileOwnerAcl.js | 2 +- samples/changeFileCSEKToCMEK.js | 4 +- samples/composeFile.js | 4 +- samples/configureBucketCors.js | 2 +- samples/configureRetries.js | 6 +- samples/copyFile.js | 4 +- samples/copyOldVersionOfFile.js | 4 +- samples/createBucketWithDualRegion.js | 6 +- .../createBucketWithHierarchicalNamespace.js | 2 +- samples/createBucketWithObjectRetention.js | 2 +- ...createBucketWithStorageClassAndLocation.js | 4 +- samples/createBucketWithTurboReplication.js | 2 +- samples/createNotification.js | 2 +- samples/deleteFile.js | 2 +- samples/deleteOldVersionOfFile.js | 2 +- samples/disableRequesterPays.js | 2 +- samples/downloadByteRange.js | 4 +- samples/downloadEncryptedFile.js | 2 +- samples/downloadFile.js | 4 +- ...downloadFileInChunksWithTransferManager.js | 4 +- samples/downloadFileUsingRequesterPays.js | 4 +- samples/downloadFolderWithTransferManager.js | 2 +- samples/downloadIntoMemory.js | 2 +- .../downloadManyFilesWithTransferManager.js | 2 +- samples/downloadPublicFile.js | 4 +- samples/enableBucketLifecycleManagement.js | 2 +- samples/enableDefaultKMSKey.js | 4 +- samples/enableRequesterPays.js | 2 +- samples/fileChangeStorageClass.js | 2 +- samples/fileSetMetadata.js | 6 +- samples/generateV4UploadSignedUrl.js | 2 +- samples/getAutoclass.js | 2 +- samples/getMetadata.js | 6 +- samples/getPublicAccessPrevention.js | 2 +- samples/getRequesterPaysStatus.js | 2 +- samples/getServiceAccount.js | 2 +- samples/getUniformBucketLevelAccess.js | 4 +- samples/hmacKeyActivate.js | 2 +- samples/hmacKeyCreate.js | 2 +- samples/hmacKeyDeactivate.js | 2 +- samples/hmacKeyDelete.js | 4 +- samples/hmacKeyGet.js | 2 +- samples/hmacKeysList.js | 2 +- samples/lockRetentionPolicy.js | 2 +- samples/moveFile.js | 4 +- samples/printFileAclForUser.js | 2 +- samples/releaseEventBasedHold.js | 4 +- samples/releaseTemporaryHold.js | 4 +- samples/removeBucketConditionalBinding.js | 4 +- samples/removeBucketIamMember.js | 8 +- samples/removeFileOwnerAcl.js | 2 +- samples/removeRetentionPolicy.js | 2 +- samples/renameFile.js | 4 +- samples/rotateEncryptionKey.js | 2 +- samples/setAutoclass.js | 4 +- samples/setEventBasedHold.js | 4 +- samples/setObjectRetentionPolicy.js | 6 +- samples/setPublicAccessPreventionEnforced.js | 2 +- samples/setRetentionPolicy.js | 2 +- samples/setTemporaryHold.js | 4 +- samples/streamFileDownload.js | 4 +- samples/streamFileUpload.js | 2 +- samples/system-test/acl.test.js | 26 +- samples/system-test/bucketLifecycle.test.js | 8 +- samples/system-test/bucketLock.test.js | 26 +- samples/system-test/buckets.test.js | 88 +++--- samples/system-test/encryption.test.js | 14 +- samples/system-test/files.test.js | 132 ++++----- samples/system-test/hmacKey.test.js | 18 +- samples/system-test/iam.test.js | 16 +- samples/system-test/notifications.test.js | 6 +- samples/system-test/requesterPays.test.js | 16 +- samples/system-test/storage.test.js | 2 +- samples/system-test/transfer-manager.test.js | 32 +-- samples/uploadDirectory.js | 4 +- samples/uploadEncryptedFile.js | 4 +- samples/uploadFile.js | 2 +- .../uploadFileInChunksWithTransferManager.js | 2 +- samples/uploadFileWithKmsKey.js | 2 +- samples/uploadFromMemory.js | 4 +- samples/uploadManyFilesWithTransferManager.js | 2 +- samples/uploadWithoutAuthentication.js | 2 +- .../uploadWithoutAuthenticationSignedUrl.js | 2 +- src/acl.ts | 34 +-- src/bucket.ts | 206 +++++++------- src/channel.ts | 2 +- src/crc32c.ts | 10 +- src/file.ts | 170 ++++++------ src/hash-stream-validator.ts | 4 +- src/hmacKey.ts | 8 +- src/iam.ts | 32 +-- src/nodejs-common/service-object.ts | 36 +-- src/nodejs-common/service.ts | 8 +- src/nodejs-common/util.ts | 58 ++-- src/notification.ts | 2 +- src/resumable-upload.ts | 30 +- src/signer.ts | 38 +-- src/storage.ts | 56 ++-- src/transfer-manager.ts | 64 ++--- src/util.ts | 10 +- system-test/common.ts | 6 +- system-test/kitchen.ts | 16 +- system-test/storage.ts | 223 +++++++-------- test/acl.ts | 6 +- test/bucket.ts | 178 ++++++------ test/channel.ts | 4 +- test/crc32c.ts | 6 +- test/file.ts | 258 +++++++++--------- test/headers.ts | 8 +- test/iam.ts | 10 +- test/index.ts | 128 ++++----- test/nodejs-common/service-object.ts | 68 ++--- test/nodejs-common/service.ts | 28 +- test/nodejs-common/util.ts | 90 +++--- test/notification.ts | 14 +- test/resumable-upload.ts | 92 +++---- test/signer.ts | 38 +-- test/transfer-manager.ts | 56 ++-- tsconfig.json | 7 +- 139 files changed, 1404 insertions(+), 1390 deletions(-) diff --git a/conformance-test/conformanceCommon.ts b/conformance-test/conformanceCommon.ts index 65da92938..0a012603e 100644 --- a/conformance-test/conformanceCommon.ts +++ b/conformance-test/conformanceCommon.ts @@ -50,7 +50,7 @@ interface ConformanceTestResult { type LibraryMethodsModuleType = typeof import('./libraryMethods'); const methodMap: Map = new Map( - Object.entries(jsonToNodeApiMapping) + Object.entries(jsonToNodeApiMapping), ); const DURATION_SECONDS = 600; // 10 mins. @@ -94,36 +94,36 @@ export function executeScenario(testCase: RetryTestCase) { }); creationResult = await createTestBenchRetryTest( instructionSet.instructions, - jsonMethod?.name.toString() + jsonMethod?.name.toString(), ); if (storageMethodString.includes('InstancePrecondition')) { bucket = await createBucketForTest( storage, testCase.preconditionProvided, - storageMethodString + storageMethodString, ); file = await createFileForTest( testCase.preconditionProvided, storageMethodString, - bucket + bucket, ); } else { bucket = await createBucketForTest( storage, false, - storageMethodString + storageMethodString, ); file = await createFileForTest( false, storageMethodString, - bucket + bucket, ); } notification = bucket.notification(`${TESTS_PREFIX}`); await notification.create(); [hmacKey] = await storage.createHmacKey( - `${TESTS_PREFIX}@email.com` + `${TESTS_PREFIX}@email.com`, ); storage.interceptors.push({ @@ -154,7 +154,7 @@ export function executeScenario(testCase: RetryTestCase) { await assert.rejects(storageMethodObject(methodParameters)); } const testBenchResult = await getTestBenchRetryTest( - creationResult.id + creationResult.id, ); assert.strictEqual(testBenchResult.completed, true); }).timeout(TIMEOUT_FOR_INDIVIDUAL_TEST); @@ -167,7 +167,7 @@ export function executeScenario(testCase: RetryTestCase) { async function createBucketForTest( storage: Storage, preconditionShouldBeOnInstance: boolean, - storageMethodString: String + storageMethodString: String, ) { const name = generateName(storageMethodString, 'bucket'); const bucket = storage.bucket(name); @@ -187,7 +187,7 @@ async function createBucketForTest( async function createFileForTest( preconditionShouldBeOnInstance: boolean, storageMethodString: String, - bucket: Bucket + bucket: Bucket, ) { const name = generateName(storageMethodString, 'file'); const file = bucket.file(name); @@ -209,7 +209,7 @@ function generateName(storageMethodString: String, bucketOrFile: string) { async function createTestBenchRetryTest( instructions: String[], - methodName: string + methodName: string, ): Promise { const requestBody = {instructions: {[methodName]: instructions}}; const response = await fetch(`${TESTBENCH_HOST}retry_test`, { @@ -221,7 +221,7 @@ async function createTestBenchRetryTest( } async function getTestBenchRetryTest( - testId: string + testId: string, ): Promise { const response = await fetch(`${TESTBENCH_HOST}retry_test/${testId}`, { method: 'GET', diff --git a/conformance-test/globalHooks.ts b/conformance-test/globalHooks.ts index 0775b7457..b579e5aae 100644 --- a/conformance-test/globalHooks.ts +++ b/conformance-test/globalHooks.ts @@ -29,7 +29,7 @@ export async function mochaGlobalSetup(this: any) { await getTestBenchDockerImage(); await runTestBenchDockerImage(); await new Promise(resolve => - setTimeout(resolve, TIME_TO_WAIT_FOR_CONTAINER_READY) + setTimeout(resolve, TIME_TO_WAIT_FOR_CONTAINER_READY), ); } diff --git a/conformance-test/libraryMethods.ts b/conformance-test/libraryMethods.ts index 2dd2e586b..45de95eb3 100644 --- a/conformance-test/libraryMethods.ts +++ b/conformance-test/libraryMethods.ts @@ -40,7 +40,7 @@ export interface ConformanceTestOptions { ///////////////////////////////////////////////// export async function addLifecycleRuleInstancePrecondition( - options: ConformanceTestOptions + options: ConformanceTestOptions, ) { await options.bucket!.addLifecycleRule({ action: { @@ -65,7 +65,7 @@ export async function addLifecycleRule(options: ConformanceTestOptions) { }, { ifMetagenerationMatch: 2, - } + }, ); } else { await options.bucket!.addLifecycleRule({ @@ -80,7 +80,7 @@ export async function addLifecycleRule(options: ConformanceTestOptions) { } export async function combineInstancePrecondition( - options: ConformanceTestOptions + options: ConformanceTestOptions, ) { const file1 = options.bucket!.file('file1.txt'); const file2 = options.bucket!.file('file2.txt'); @@ -142,7 +142,7 @@ export async function deleteBucket(options: ConformanceTestOptions) { // Preconditions cannot be implemented with current setup. export async function deleteLabelsInstancePrecondition( - options: ConformanceTestOptions + options: ConformanceTestOptions, ) { await options.bucket!.deleteLabels(); } @@ -158,7 +158,7 @@ export async function deleteLabels(options: ConformanceTestOptions) { } export async function disableRequesterPaysInstancePrecondition( - options: ConformanceTestOptions + options: ConformanceTestOptions, ) { await options.bucket!.disableRequesterPays(); } @@ -174,7 +174,7 @@ export async function disableRequesterPays(options: ConformanceTestOptions) { } export async function enableLoggingInstancePrecondition( - options: ConformanceTestOptions + options: ConformanceTestOptions, ) { const config = { prefix: 'log', @@ -198,7 +198,7 @@ export async function enableLogging(options: ConformanceTestOptions) { } export async function enableRequesterPaysInstancePrecondition( - options: ConformanceTestOptions + options: ConformanceTestOptions, ) { await options.bucket!.enableRequesterPays(); } @@ -249,7 +249,7 @@ export async function lock(options: ConformanceTestOptions) { } export async function bucketMakePrivateInstancePrecondition( - options: ConformanceTestOptions + options: ConformanceTestOptions, ) { await options.bucket!.makePrivate(); } @@ -269,7 +269,7 @@ export async function bucketMakePublic(options: ConformanceTestOptions) { } export async function removeRetentionPeriodInstancePrecondition( - options: ConformanceTestOptions + options: ConformanceTestOptions, ) { await options.bucket!.removeRetentionPeriod(); } @@ -285,7 +285,7 @@ export async function removeRetentionPeriod(options: ConformanceTestOptions) { } export async function setCorsConfigurationInstancePrecondition( - options: ConformanceTestOptions + options: ConformanceTestOptions, ) { const corsConfiguration = [{maxAgeSeconds: 3600}]; // 1 hour await options.bucket!.setCorsConfiguration(corsConfiguration); @@ -303,7 +303,7 @@ export async function setCorsConfiguration(options: ConformanceTestOptions) { } export async function setLabelsInstancePrecondition( - options: ConformanceTestOptions + options: ConformanceTestOptions, ) { const labels = { labelone: 'labelonevalue', @@ -327,7 +327,7 @@ export async function setLabels(options: ConformanceTestOptions) { } export async function bucketSetMetadataInstancePrecondition( - options: ConformanceTestOptions + options: ConformanceTestOptions, ) { const metadata = { website: { @@ -355,7 +355,7 @@ export async function bucketSetMetadata(options: ConformanceTestOptions) { } export async function setRetentionPeriodInstancePrecondition( - options: ConformanceTestOptions + options: ConformanceTestOptions, ) { const DURATION_SECONDS = 15780000; // 6 months. await options.bucket!.setRetentionPeriod(DURATION_SECONDS); @@ -373,7 +373,7 @@ export async function setRetentionPeriod(options: ConformanceTestOptions) { } export async function bucketSetStorageClassInstancePrecondition( - options: ConformanceTestOptions + options: ConformanceTestOptions, ) { await options.bucket!.setStorageClass('nearline'); } @@ -389,11 +389,11 @@ export async function bucketSetStorageClass(options: ConformanceTestOptions) { } export async function bucketUploadResumableInstancePrecondition( - options: ConformanceTestOptions + options: ConformanceTestOptions, ) { const filePath = path.join( getDirName(), - `../conformance-test/test-data/tmp-${uuid.v4()}.txt` + `../conformance-test/test-data/tmp-${uuid.v4()}.txt`, ); createTestFileFromBuffer(FILE_SIZE_BYTES, filePath); if (options.bucket!.instancePreconditionOpts) { @@ -411,7 +411,7 @@ export async function bucketUploadResumableInstancePrecondition( export async function bucketUploadResumable(options: ConformanceTestOptions) { const filePath = path.join( getDirName(), - `../conformance-test/test-data/tmp-${uuid.v4()}.txt` + `../conformance-test/test-data/tmp-${uuid.v4()}.txt`, ); createTestFileFromBuffer(FILE_SIZE_BYTES, filePath); if (options.preconditionRequired) { @@ -432,7 +432,7 @@ export async function bucketUploadResumable(options: ConformanceTestOptions) { } export async function bucketUploadMultipartInstancePrecondition( - options: ConformanceTestOptions + options: ConformanceTestOptions, ) { if (options.bucket!.instancePreconditionOpts) { delete options.bucket!.instancePreconditionOpts.ifMetagenerationMatch; @@ -441,9 +441,9 @@ export async function bucketUploadMultipartInstancePrecondition( await options.bucket!.upload( path.join( getDirName(), - '../../../conformance-test/test-data/retryStrategyTestData.json' + '../../../conformance-test/test-data/retryStrategyTestData.json', ), - {resumable: false} + {resumable: false}, ); } @@ -456,17 +456,17 @@ export async function bucketUploadMultipart(options: ConformanceTestOptions) { await options.bucket!.upload( path.join( getDirName(), - '../../../conformance-test/test-data/retryStrategyTestData.json' + '../../../conformance-test/test-data/retryStrategyTestData.json', ), - {resumable: false, preconditionOpts: {ifGenerationMatch: 0}} + {resumable: false, preconditionOpts: {ifGenerationMatch: 0}}, ); } else { await options.bucket!.upload( path.join( getDirName(), - '../../../conformance-test/test-data/retryStrategyTestData.json' + '../../../conformance-test/test-data/retryStrategyTestData.json', ), - {resumable: false} + {resumable: false}, ); } } @@ -501,7 +501,7 @@ export async function createReadStream(options: ConformanceTestOptions) { } export async function createResumableUploadInstancePrecondition( - options: ConformanceTestOptions + options: ConformanceTestOptions, ) { await options.file!.createResumableUpload(); } @@ -517,7 +517,7 @@ export async function createResumableUpload(options: ConformanceTestOptions) { } export async function fileDeleteInstancePrecondition( - options: ConformanceTestOptions + options: ConformanceTestOptions, ) { await options.file!.delete(); } @@ -557,7 +557,7 @@ export async function isPublic(options: ConformanceTestOptions) { } export async function fileMakePrivateInstancePrecondition( - options: ConformanceTestOptions + options: ConformanceTestOptions, ) { await options.file!.makePrivate(); } @@ -615,7 +615,7 @@ export async function rotateEncryptionKey(options: ConformanceTestOptions) { } export async function saveResumableInstancePrecondition( - options: ConformanceTestOptions + options: ConformanceTestOptions, ) { const buf = createTestBuffer(FILE_SIZE_BYTES); await options.file!.save(buf, { @@ -647,7 +647,7 @@ export async function saveResumable(options: ConformanceTestOptions) { } export async function saveMultipartInstancePrecondition( - options: ConformanceTestOptions + options: ConformanceTestOptions, ) { await options.file!.save('testdata', {resumable: false}); } @@ -668,7 +668,7 @@ export async function saveMultipart(options: ConformanceTestOptions) { } export async function setMetadataInstancePrecondition( - options: ConformanceTestOptions + options: ConformanceTestOptions, ) { const metadata = { contentType: 'application/x-font-ttf', diff --git a/conformance-test/scenarios/scenarioFive.ts b/conformance-test/scenarios/scenarioFive.ts index 9c3a3b572..357e1065f 100644 --- a/conformance-test/scenarios/scenarioFive.ts +++ b/conformance-test/scenarios/scenarioFive.ts @@ -19,7 +19,7 @@ import assert from 'assert'; const SCENARIO_NUMBER_TO_TEST = 5; const retryTestCase: RetryTestCase | undefined = testFile.retryTests.find( - test => test.id === SCENARIO_NUMBER_TO_TEST + test => test.id === SCENARIO_NUMBER_TO_TEST, ); describe(`Scenario ${SCENARIO_NUMBER_TO_TEST}`, () => { diff --git a/conformance-test/scenarios/scenarioFour.ts b/conformance-test/scenarios/scenarioFour.ts index 0072461e4..580c8b794 100644 --- a/conformance-test/scenarios/scenarioFour.ts +++ b/conformance-test/scenarios/scenarioFour.ts @@ -19,7 +19,7 @@ import assert from 'assert'; const SCENARIO_NUMBER_TO_TEST = 4; const retryTestCase: RetryTestCase | undefined = testFile.retryTests.find( - test => test.id === SCENARIO_NUMBER_TO_TEST + test => test.id === SCENARIO_NUMBER_TO_TEST, ); describe(`Scenario ${SCENARIO_NUMBER_TO_TEST}`, () => { diff --git a/conformance-test/scenarios/scenarioOne.ts b/conformance-test/scenarios/scenarioOne.ts index 981da527b..7cfe37caa 100644 --- a/conformance-test/scenarios/scenarioOne.ts +++ b/conformance-test/scenarios/scenarioOne.ts @@ -19,7 +19,7 @@ import assert from 'assert'; const SCENARIO_NUMBER_TO_TEST = 1; const retryTestCase: RetryTestCase | undefined = testFile.retryTests.find( - test => test.id === SCENARIO_NUMBER_TO_TEST + test => test.id === SCENARIO_NUMBER_TO_TEST, ); describe(`Scenario ${SCENARIO_NUMBER_TO_TEST}`, () => { diff --git a/conformance-test/scenarios/scenarioSeven.ts b/conformance-test/scenarios/scenarioSeven.ts index d1204d3b4..8cf6ec0df 100644 --- a/conformance-test/scenarios/scenarioSeven.ts +++ b/conformance-test/scenarios/scenarioSeven.ts @@ -19,7 +19,7 @@ import assert from 'assert'; const SCENARIO_NUMBER_TO_TEST = 7; const retryTestCase: RetryTestCase | undefined = testFile.retryTests.find( - test => test.id === SCENARIO_NUMBER_TO_TEST + test => test.id === SCENARIO_NUMBER_TO_TEST, ); describe(`Scenario ${SCENARIO_NUMBER_TO_TEST}`, () => { diff --git a/conformance-test/scenarios/scenarioSix.ts b/conformance-test/scenarios/scenarioSix.ts index 6d2b452ff..bcc48b601 100644 --- a/conformance-test/scenarios/scenarioSix.ts +++ b/conformance-test/scenarios/scenarioSix.ts @@ -19,7 +19,7 @@ import assert from 'assert'; const SCENARIO_NUMBER_TO_TEST = 6; const retryTestCase: RetryTestCase | undefined = testFile.retryTests.find( - test => test.id === SCENARIO_NUMBER_TO_TEST + test => test.id === SCENARIO_NUMBER_TO_TEST, ); describe(`Scenario ${SCENARIO_NUMBER_TO_TEST}`, () => { diff --git a/conformance-test/scenarios/scenarioThree.ts b/conformance-test/scenarios/scenarioThree.ts index 7b6c90021..d9f98bd5c 100644 --- a/conformance-test/scenarios/scenarioThree.ts +++ b/conformance-test/scenarios/scenarioThree.ts @@ -19,7 +19,7 @@ import assert from 'assert'; const SCENARIO_NUMBER_TO_TEST = 3; const retryTestCase: RetryTestCase | undefined = testFile.retryTests.find( - test => test.id === SCENARIO_NUMBER_TO_TEST + test => test.id === SCENARIO_NUMBER_TO_TEST, ); describe(`Scenario ${SCENARIO_NUMBER_TO_TEST}`, () => { diff --git a/conformance-test/scenarios/scenarioTwo.ts b/conformance-test/scenarios/scenarioTwo.ts index fe2e6fb11..e3caf0730 100644 --- a/conformance-test/scenarios/scenarioTwo.ts +++ b/conformance-test/scenarios/scenarioTwo.ts @@ -19,7 +19,7 @@ import assert from 'assert'; const SCENARIO_NUMBER_TO_TEST = 2; const retryTestCase: RetryTestCase | undefined = testFile.retryTests.find( - test => test.id === SCENARIO_NUMBER_TO_TEST + test => test.id === SCENARIO_NUMBER_TO_TEST, ); describe(`Scenario ${SCENARIO_NUMBER_TO_TEST}`, () => { diff --git a/conformance-test/v4SignedUrl.ts b/conformance-test/v4SignedUrl.ts index ecf378bd7..8f717f8df 100644 --- a/conformance-test/v4SignedUrl.ts +++ b/conformance-test/v4SignedUrl.ts @@ -93,9 +93,9 @@ interface BucketAction { const testFile = fs.readFileSync( path.join( getDirName(), - '../../../conformance-test/test-data/v4SignedUrl.json' + '../../../conformance-test/test-data/v4SignedUrl.json', ), - 'utf-8' + 'utf-8', ); const testCases = JSON.parse(testFile); @@ -105,7 +105,7 @@ const v4SignedPolicyCases: V4SignedPolicyTestCase[] = const SERVICE_ACCOUNT = path.join( getDirName(), - '../../../conformance-test/fixtures/signing-service-account.json' + '../../../conformance-test/fixtures/signing-service-account.json', ); let storage: Storage; @@ -143,7 +143,7 @@ describe('v4 conformance test', () => { const host = testCase.hostname ? new URL( (testCase.scheme ? testCase.scheme + '://' : '') + - testCase.hostname + testCase.hostname, ) : undefined; const origin = testCase.bucketBoundHostname @@ -151,7 +151,7 @@ describe('v4 conformance test', () => { : undefined; const {bucketBoundHostname, virtualHostedStyle} = parseUrlStyle( testCase.urlStyle, - origin + origin, ); const extensionHeaders = testCase.headers; const queryParams = testCase.queryParameters; @@ -204,7 +204,7 @@ describe('v4 conformance test', () => { // Order-insensitive comparison of query params assert.deepStrictEqual( querystring.parse(actual.search), - querystring.parse(expected.search) + querystring.parse(expected.search), ); }); }); @@ -247,7 +247,7 @@ describe('v4 conformance test', () => { : undefined; const {bucketBoundHostname, virtualHostedStyle} = parseUrlStyle( input.urlStyle, - origin + origin, ); options.virtualHostedStyle = virtualHostedStyle; options.bucketBoundHostname = bucketBoundHostname; @@ -260,11 +260,11 @@ describe('v4 conformance test', () => { assert.strictEqual(policy.url, testCase.policyOutput.url); const outputFields = testCase.policyOutput.fields; const decodedPolicy = JSON.parse( - Buffer.from(policy.fields.policy, 'base64').toString() + Buffer.from(policy.fields.policy, 'base64').toString(), ); assert.deepStrictEqual( decodedPolicy, - JSON.parse(testCase.policyOutput.expectedDecodedPolicy) + JSON.parse(testCase.policyOutput.expectedDecodedPolicy), ); assert.deepStrictEqual(policy.fields, outputFields); @@ -275,7 +275,7 @@ describe('v4 conformance test', () => { function parseUrlStyle( style?: keyof typeof UrlStyle, - origin?: string + origin?: string, ): {bucketBoundHostname?: string; virtualHostedStyle?: boolean} { if (style === UrlStyle.BUCKET_BOUND_HOSTNAME) { return {bucketBoundHostname: origin}; diff --git a/internal-tooling/performApplicationPerformanceTest.ts b/internal-tooling/performApplicationPerformanceTest.ts index 99b0f151f..eedcda1f6 100644 --- a/internal-tooling/performApplicationPerformanceTest.ts +++ b/internal-tooling/performApplicationPerformanceTest.ts @@ -56,7 +56,7 @@ async function main() { ({bucket} = await performanceTestSetup( argv.project! as string, - argv.bucket! as string + argv.bucket! as string, )); switch (argv.test_type) { @@ -78,7 +78,7 @@ async function main() { async function uploadInParallel( bucket: Bucket, paths: string[], - options: UploadOptions + options: UploadOptions, ) { const promises: Promise[] = []; for (const index in paths) { @@ -115,7 +115,7 @@ async function performWriteTest(): Promise { argv.num_objects as number, TEST_NAME_STRING, fileSizeRange.low, - fileSizeRange.high + fileSizeRange.high, ); const start = performance.now(); @@ -157,7 +157,7 @@ async function performReadTest(): Promise { argv.num_objects as number, TEST_NAME_STRING, fileSizeRange.low, - fileSizeRange.high + fileSizeRange.high, ); await uploadInParallel(bucket, creationInfo.paths, {validation: checkType}); diff --git a/internal-tooling/performPerformanceTest.ts b/internal-tooling/performPerformanceTest.ts index a23f547c8..82fda1c9f 100644 --- a/internal-tooling/performPerformanceTest.ts +++ b/internal-tooling/performPerformanceTest.ts @@ -54,7 +54,7 @@ async function main() { ({bucket} = await performanceTestSetup( argv.project! as string, - argv.bucket! as string + argv.bucket! as string, )); switch (argv.test_type) { @@ -84,7 +84,7 @@ async function performRangedReadTest(): Promise { fileName, fileSizeRange.low, fileSizeRange.high, - getDirName() + getDirName(), ); const file = bucket.file(`${fileName}`); const destinationFileName = generateRandomFileName(TEST_NAME_STRING); @@ -142,7 +142,7 @@ async function performWriteReadTest(): Promise { fileName, fileSizeRange.low, fileSizeRange.high, - getDirName() + getDirName(), ); for (let j = 0; j < DEFAULT_NUMBER_OF_WRITES; j++) { diff --git a/internal-tooling/performTransferManagerTest.ts b/internal-tooling/performTransferManagerTest.ts index 097e999f7..6e21e7746 100644 --- a/internal-tooling/performTransferManagerTest.ts +++ b/internal-tooling/performTransferManagerTest.ts @@ -56,7 +56,7 @@ async function main() { ({bucket, transferManager} = await performanceTestSetup( argv.project! as string, - argv.bucket! as string + argv.bucket! as string, )); switch (argv.test_type) { @@ -104,7 +104,7 @@ async function performUploadManyFilesTest(): Promise { TEST_NAME_STRING, fileSizeRange.low, fileSizeRange.high, - DIRECTORY_PROBABILITY + DIRECTORY_PROBABILITY, ); const start = performance.now(); @@ -153,7 +153,7 @@ async function performDownloadManyFilesTest(): Promise { TEST_NAME_STRING, fileSizeRange.low, fileSizeRange.high, - DIRECTORY_PROBABILITY + DIRECTORY_PROBABILITY, ); await transferManager.uploadManyFiles(creationInfo.paths, { @@ -210,7 +210,7 @@ async function performChunkUploadDownloadTest(): Promise { fileName, fileSizeRange.low, fileSizeRange.high, - getDirName() + getDirName(), ); const file = bucket.file(`${fileName}`); let result: TestResult = { diff --git a/internal-tooling/performanceTest.ts b/internal-tooling/performanceTest.ts index 995eaf967..02adc10f7 100644 --- a/internal-tooling/performanceTest.ts +++ b/internal-tooling/performanceTest.ts @@ -44,7 +44,7 @@ function main() { if (numThreads > iterationsRemaining) { log( `${numThreads} is greater than number of iterations (${iterationsRemaining}). Using ${iterationsRemaining} threads instead.`, - argv.debug as boolean + argv.debug as boolean, ); numThreads = iterationsRemaining; } @@ -65,7 +65,7 @@ function createWorker() { iterationsRemaining--; log( `Starting new iteration. Current iterations remaining: ${iterationsRemaining}`, - argv.debug as boolean + argv.debug as boolean, ); let testPath = ''; if ( @@ -122,7 +122,7 @@ async function recordResult(results: TestResult[] | TestResult) { : [results]; for await (const outputString of convertToCloudMonitoringFormat( - resultsToAppend + resultsToAppend, )) { argv.file_name ? await appendFile(argv.file_name as string, `${outputString}\n`) diff --git a/internal-tooling/performanceUtils.ts b/internal-tooling/performanceUtils.ts index b0ff2d1d5..b0633bdf1 100644 --- a/internal-tooling/performanceUtils.ts +++ b/internal-tooling/performanceUtils.ts @@ -214,20 +214,20 @@ export function generateRandomFileName(baseName: string): string { export function generateRandomFile( fileName: string, fileSizeLowerBoundBytes: number = getLowHighFileSize( - DEFAULT_OBJECT_RANGE_SIZE_BYTES + DEFAULT_OBJECT_RANGE_SIZE_BYTES, ).low, fileSizeUpperBoundBytes: number = getLowHighFileSize( - DEFAULT_OBJECT_RANGE_SIZE_BYTES + DEFAULT_OBJECT_RANGE_SIZE_BYTES, ).high, - currentDirectory: string = mkdtempSync(randomString()) + currentDirectory: string = mkdtempSync(randomString()), ): number { const fileSizeBytes = randomInteger( fileSizeLowerBoundBytes, - fileSizeUpperBoundBytes + fileSizeUpperBoundBytes, ); execSync( - `head --bytes=${fileSizeBytes} /dev/urandom > ${currentDirectory}/${fileName}` + `head --bytes=${fileSizeBytes} /dev/urandom > ${currentDirectory}/${fileName}`, ); return fileSizeBytes; @@ -247,12 +247,12 @@ export function generateRandomDirectoryStructure( maxObjects: number, baseName: string, fileSizeLowerBoundBytes: number = getLowHighFileSize( - DEFAULT_OBJECT_RANGE_SIZE_BYTES + DEFAULT_OBJECT_RANGE_SIZE_BYTES, ).low, fileSizeUpperBoundBytes: number = getLowHighFileSize( - DEFAULT_OBJECT_RANGE_SIZE_BYTES + DEFAULT_OBJECT_RANGE_SIZE_BYTES, ).high, - directoryProbability: number = DEFAULT_DIRECTORY_PROBABILITY + directoryProbability: number = DEFAULT_DIRECTORY_PROBABILITY, ): RandomDirectoryCreationInformation { let curPath = baseName; const creationInfo: RandomDirectoryCreationInformation = { @@ -272,7 +272,7 @@ export function generateRandomDirectoryStructure( randomName, fileSizeLowerBoundBytes, fileSizeUpperBoundBytes, - curPath + curPath, ); creationInfo.paths.push(path.join(curPath, randomName)); } @@ -288,7 +288,7 @@ export function generateRandomDirectoryStructure( */ export function cleanupFile( fileName: string, - directoryName: string = getDirName() + directoryName: string = getDirName(), ): void { unlinkSync(`${directoryName}/${fileName}`); } @@ -302,7 +302,7 @@ export function cleanupFile( */ export async function performanceTestSetup( projectId: string, - bucketName: string + bucketName: string, ): Promise { const storage = new Storage({projectId}); const bucket = storage.bucket(bucketName, { @@ -346,7 +346,7 @@ export function getValidationType(): 'md5' | 'crc32c' | boolean | undefined { * @returns {AsyncGenerator} A string containing the results of the conversion to cloud monitoring format. */ export async function* convertToCloudMonitoringFormat( - results: TestResult[] + results: TestResult[], ): AsyncGenerator { for (const curResult of results) { const throughput = @@ -384,7 +384,7 @@ export async function* convertToCloudMonitoringFormat( export function log( messageOrError: string | Error, shouldLog: boolean, - isError = false + isError = false, ): void { if (shouldLog) { isError ? console.error(messageOrError) : console.log(messageOrError); diff --git a/samples/addBucketConditionalBinding.js b/samples/addBucketConditionalBinding.js index f5f6754a2..46d01d04d 100644 --- a/samples/addBucketConditionalBinding.js +++ b/samples/addBucketConditionalBinding.js @@ -26,7 +26,7 @@ function main( title = 'match-prefix', description = 'Applies to objects matching a prefix', expression = 'resource.name.startsWith("projects/_/buckets/bucket-name/objects/prefix-a-")', - members = 'user:test@example.com' + members = 'user:test@example.com', ) { members = members.split(','); // [START storage_add_bucket_conditional_iam_binding] @@ -81,7 +81,7 @@ function main( await bucket.iam.setPolicy(policy); console.log( - `Added the following member(s) with role ${roleName} to ${bucketName}:` + `Added the following member(s) with role ${roleName} to ${bucketName}:`, ); members.forEach(member => { diff --git a/samples/addBucketIamMember.js b/samples/addBucketIamMember.js index 9ab6595de..02170c8d6 100644 --- a/samples/addBucketIamMember.js +++ b/samples/addBucketIamMember.js @@ -15,7 +15,7 @@ function main( bucketName = 'my-bucket', roleName = 'roles/storage.objectViewer', - members = 'user:test@example.com' + members = 'user:test@example.com', ) { //including this logic so as to not use yargs members = members.split(','); @@ -59,7 +59,7 @@ function main( await bucket.iam.setPolicy(policy); console.log( - `Added the following member(s) with role ${roleName} to ${bucketName}:` + `Added the following member(s) with role ${roleName} to ${bucketName}:`, ); members.forEach(member => { diff --git a/samples/addBucketLabel.js b/samples/addBucketLabel.js index bb814a831..5964d5ffe 100644 --- a/samples/addBucketLabel.js +++ b/samples/addBucketLabel.js @@ -22,7 +22,7 @@ function main( bucketName = 'my-bucket', labelKey = 'labelone', - labelValue = 'labelonevalue' + labelValue = 'labelonevalue', ) { // [START storage_add_bucket_label] /** diff --git a/samples/addBucketWebsiteConfiguration.js b/samples/addBucketWebsiteConfiguration.js index 75d07a5ea..24d3fa738 100644 --- a/samples/addBucketWebsiteConfiguration.js +++ b/samples/addBucketWebsiteConfiguration.js @@ -22,7 +22,7 @@ function main( bucketName = 'my-bucket', mainPageSuffix = 'http://example.com', - notFoundPage = 'http://example.com/404.html' + notFoundPage = 'http://example.com/404.html', ) { // [START storage_define_bucket_website_configuration] /** @@ -52,7 +52,7 @@ function main( }); console.log( - `Static website bucket ${bucketName} is set up to use ${mainPageSuffix} as the index page and ${notFoundPage} as the 404 page` + `Static website bucket ${bucketName} is set up to use ${mainPageSuffix} as the index page and ${notFoundPage} as the 404 page`, ); } diff --git a/samples/addFileOwnerAcl.js b/samples/addFileOwnerAcl.js index 4029f5692..52cb2cc82 100644 --- a/samples/addFileOwnerAcl.js +++ b/samples/addFileOwnerAcl.js @@ -23,7 +23,7 @@ function main( bucketName = 'my-bucket', fileName = 'test.txt', - userEmail = 'jdobry@google.com' + userEmail = 'jdobry@google.com', ) { // [START storage_add_file_owner] /** diff --git a/samples/changeFileCSEKToCMEK.js b/samples/changeFileCSEKToCMEK.js index 11c886ae5..6b8bc86e6 100644 --- a/samples/changeFileCSEKToCMEK.js +++ b/samples/changeFileCSEKToCMEK.js @@ -24,7 +24,7 @@ function main( fileName = 'test.txt', encryptionKey = 'my-encription-key', kmsKeyName = 'my-kms-key', - generationMatchPrecondition = 0 + generationMatchPrecondition = 0, ) { // [START storage_object_csek_to_cmek] /** @@ -72,7 +72,7 @@ function main( }); console.log( - `file ${fileName} in bucket ${bucketName} is now managed by KMS key ${kmsKeyName} instead of customer-supplied encryption key` + `file ${fileName} in bucket ${bucketName} is now managed by KMS key ${kmsKeyName} instead of customer-supplied encryption key`, ); } diff --git a/samples/composeFile.js b/samples/composeFile.js index 183385e95..3f53c7be1 100644 --- a/samples/composeFile.js +++ b/samples/composeFile.js @@ -24,7 +24,7 @@ function main( firstFileName = 'file-one.txt', secondFileName = 'file-two.txt', destinationFileName = 'file-one-two.txt', - destinationGenerationMatchPrecondition = 0 + destinationGenerationMatchPrecondition = 0, ) { // [START storage_compose_file] /** @@ -65,7 +65,7 @@ function main( await bucket.combine(sources, destinationFileName, combineOptions); console.log( - `New composite file ${destinationFileName} was created by combining ${firstFileName} and ${secondFileName}` + `New composite file ${destinationFileName} was created by combining ${firstFileName} and ${secondFileName}`, ); } diff --git a/samples/configureBucketCors.js b/samples/configureBucketCors.js index cd2893d00..751479cca 100644 --- a/samples/configureBucketCors.js +++ b/samples/configureBucketCors.js @@ -24,7 +24,7 @@ function main( maxAgeSeconds = 3600, method = 'POST', origin = 'http://example.appspot.com', - responseHeader = 'content-type' + responseHeader = 'content-type', ) { // [START storage_cors_configuration] // Imports the Google Cloud client library diff --git a/samples/configureRetries.js b/samples/configureRetries.js index 201fda22a..449662b2c 100644 --- a/samples/configureRetries.js +++ b/samples/configureRetries.js @@ -62,17 +62,17 @@ function main(bucketName = 'my-bucket', fileName = 'test.txt') { }, }); console.log( - 'Functions are customized to be retried according to the following parameters:' + 'Functions are customized to be retried according to the following parameters:', ); console.log(`Auto Retry: ${storage.retryOptions.autoRetry}`); console.log( - `Retry delay multiplier: ${storage.retryOptions.retryDelayMultiplier}` + `Retry delay multiplier: ${storage.retryOptions.retryDelayMultiplier}`, ); console.log(`Total timeout: ${storage.retryOptions.totalTimeout}`); console.log(`Maximum retry delay: ${storage.retryOptions.maxRetryDelay}`); console.log(`Maximum retries: ${storage.retryOptions.maxRetries}`); console.log( - `Idempotency strategy: ${storage.retryOptions.idempotencyStrategy}` + `Idempotency strategy: ${storage.retryOptions.idempotencyStrategy}`, ); async function deleteFileWithCustomizedRetrySetting() { diff --git a/samples/copyFile.js b/samples/copyFile.js index bc41947d8..3260b59c6 100644 --- a/samples/copyFile.js +++ b/samples/copyFile.js @@ -25,7 +25,7 @@ function main( srcFilename = 'test2.txt', destBucketName = 'my-bucket', destFileName = 'test3.txt', - destinationGenerationMatchPrecondition = 0 + destinationGenerationMatchPrecondition = 0, ) { // [START storage_copy_file] /** @@ -72,7 +72,7 @@ function main( .copy(copyDestination, copyOptions); console.log( - `gs://${srcBucketName}/${srcFilename} copied to gs://${destBucketName}/${destFileName}` + `gs://${srcBucketName}/${srcFilename} copied to gs://${destBucketName}/${destFileName}`, ); } diff --git a/samples/copyOldVersionOfFile.js b/samples/copyOldVersionOfFile.js index 780fe0f1a..22291d4fd 100644 --- a/samples/copyOldVersionOfFile.js +++ b/samples/copyOldVersionOfFile.js @@ -25,7 +25,7 @@ function main( destBucketName = 'my-bucket', destFileName = 'test3.txt', generation = 1, - destinationGenerationMatchPrecondition = 0 + destinationGenerationMatchPrecondition = 0, ) { // [START storage_copy_file_archived_generation] /** @@ -76,7 +76,7 @@ function main( .copy(storage.bucket(destBucketName).file(destFileName), copyOptions); console.log( - `Generation ${generation} of file ${srcFilename} in bucket ${srcBucketName} was copied to ${destFileName} in bucket ${destBucketName}` + `Generation ${generation} of file ${srcFilename} in bucket ${srcBucketName} was copied to ${destFileName} in bucket ${destBucketName}`, ); } diff --git a/samples/createBucketWithDualRegion.js b/samples/createBucketWithDualRegion.js index cd145d8e2..8937a6b5c 100644 --- a/samples/createBucketWithDualRegion.js +++ b/samples/createBucketWithDualRegion.js @@ -25,7 +25,7 @@ function main( bucketName = 'my-bucket', location = 'US', region1 = 'US-EAST1', - region2 = 'US-WEST1' + region2 = 'US-WEST1', ) { // [START storage_create_bucket_dual_region] /** @@ -63,8 +63,8 @@ function main( console.log(`- locationType: '${bucket.metadata.locationType}'`); console.log( `- customPlacementConfig: '${JSON.stringify( - bucket.metadata.customPlacementConfig - )}'` + bucket.metadata.customPlacementConfig, + )}'`, ); } diff --git a/samples/createBucketWithHierarchicalNamespace.js b/samples/createBucketWithHierarchicalNamespace.js index 8641cacff..27daab5c3 100644 --- a/samples/createBucketWithHierarchicalNamespace.js +++ b/samples/createBucketWithHierarchicalNamespace.js @@ -50,7 +50,7 @@ function main(bucketName = 'my-bucket') { }); console.log( - `Created '${bucket.name}' with hierarchical namespace enabled.` + `Created '${bucket.name}' with hierarchical namespace enabled.`, ); } diff --git a/samples/createBucketWithObjectRetention.js b/samples/createBucketWithObjectRetention.js index c51ddf7b4..cd290e281 100644 --- a/samples/createBucketWithObjectRetention.js +++ b/samples/createBucketWithObjectRetention.js @@ -41,7 +41,7 @@ function main(bucketName = 'my-bucket') { }); console.log( - `Created '${bucket.name}' with object retention enabled setting: ${bucket.metadata.objectRetention.mode}` + `Created '${bucket.name}' with object retention enabled setting: ${bucket.metadata.objectRetention.mode}`, ); } diff --git a/samples/createBucketWithStorageClassAndLocation.js b/samples/createBucketWithStorageClassAndLocation.js index 27ee7e70a..4d54e7950 100644 --- a/samples/createBucketWithStorageClassAndLocation.js +++ b/samples/createBucketWithStorageClassAndLocation.js @@ -24,7 +24,7 @@ function main( bucketName = 'my-bucket', storageClass = 'coldline', - location = 'ASIA' + location = 'ASIA', ) { // [START storage_create_bucket_class_location] /** @@ -60,7 +60,7 @@ function main( }); console.log( - `${bucket.name} created with ${storageClass} class in ${location}` + `${bucket.name} created with ${storageClass} class in ${location}`, ); } diff --git a/samples/createBucketWithTurboReplication.js b/samples/createBucketWithTurboReplication.js index 566f0c438..0207e648b 100644 --- a/samples/createBucketWithTurboReplication.js +++ b/samples/createBucketWithTurboReplication.js @@ -55,7 +55,7 @@ function main(bucketName = 'my-bucket', location = 'NAM4') { }); console.log( - `${bucket.name} created with the recovery point objective (RPO) set to ${rpo} in ${location}.` + `${bucket.name} created with the recovery point objective (RPO) set to ${rpo} in ${location}.`, ); } diff --git a/samples/createNotification.js b/samples/createNotification.js index 97013ff53..544abbaf9 100644 --- a/samples/createNotification.js +++ b/samples/createNotification.js @@ -23,7 +23,7 @@ const uuid = require('uuid'); function main( bucketName = 'my-bucket', - topic = `nodejs-storage-samples-${uuid.v4()}` + topic = `nodejs-storage-samples-${uuid.v4()}`, ) { // [START storage_create_bucket_notifications] /** diff --git a/samples/deleteFile.js b/samples/deleteFile.js index 4747d3a32..746966442 100644 --- a/samples/deleteFile.js +++ b/samples/deleteFile.js @@ -23,7 +23,7 @@ function main( bucketName = 'my-bucket', fileName = 'test.txt', - generationMatchPrecondition = 0 + generationMatchPrecondition = 0, ) { // [START storage_delete_file] /** diff --git a/samples/deleteOldVersionOfFile.js b/samples/deleteOldVersionOfFile.js index 39434ecd1..db159373e 100644 --- a/samples/deleteOldVersionOfFile.js +++ b/samples/deleteOldVersionOfFile.js @@ -49,7 +49,7 @@ function main(bucketName = 'my-bucket', fileName = 'test.txt', generation = 1) { .delete(); console.log( - `Generation ${generation} of file ${fileName} was deleted from ${bucketName}` + `Generation ${generation} of file ${fileName} was deleted from ${bucketName}`, ); } diff --git a/samples/disableRequesterPays.js b/samples/disableRequesterPays.js index c587615ed..d1850cc0c 100644 --- a/samples/disableRequesterPays.js +++ b/samples/disableRequesterPays.js @@ -40,7 +40,7 @@ function main(bucketName = 'my-bucket') { await storage.bucket(bucketName).disableRequesterPays(); console.log( - `Requester-pays requests have been disabled for bucket ${bucketName}` + `Requester-pays requests have been disabled for bucket ${bucketName}`, ); } diff --git a/samples/downloadByteRange.js b/samples/downloadByteRange.js index bace089b3..81f2abdce 100644 --- a/samples/downloadByteRange.js +++ b/samples/downloadByteRange.js @@ -29,7 +29,7 @@ function main( fileName = 'test.txt', startByte = 0, endByte = 20, - destFileName = path.join(cwd, 'downloaded.txt') + destFileName = path.join(cwd, 'downloaded.txt'), ) { // [START storage_download_byte_range] /** @@ -67,7 +67,7 @@ function main( await storage.bucket(bucketName).file(fileName).download(options); console.log( - `gs://${bucketName}/${fileName} downloaded to ${destFileName} from byte ${startByte} to byte ${endByte}.` + `gs://${bucketName}/${fileName} downloaded to ${destFileName} from byte ${startByte} to byte ${endByte}.`, ); } diff --git a/samples/downloadEncryptedFile.js b/samples/downloadEncryptedFile.js index 76ffa1b96..3043ac58d 100644 --- a/samples/downloadEncryptedFile.js +++ b/samples/downloadEncryptedFile.js @@ -26,7 +26,7 @@ function main( bucketName = 'my-bucket', srcFileName = path.join(__dirname, '../resources', 'test.txt'), destFileName = 'test.txt', - encryptionKey = process.env.GOOGLE_CLOUD_KMS_KEY_US + encryptionKey = process.env.GOOGLE_CLOUD_KMS_KEY_US, ) { // [START storage_download_encrypted_file] /** diff --git a/samples/downloadFile.js b/samples/downloadFile.js index 3ea9d8f31..257f07308 100644 --- a/samples/downloadFile.js +++ b/samples/downloadFile.js @@ -25,7 +25,7 @@ const cwd = path.join(__dirname, '..'); function main( bucketName = 'my-bucket', fileName = 'test.txt', - destFileName = path.join(cwd, 'downloaded.txt') + destFileName = path.join(cwd, 'downloaded.txt'), ) { // [START storage_download_file] /** @@ -55,7 +55,7 @@ function main( await storage.bucket(bucketName).file(fileName).download(options); console.log( - `gs://${bucketName}/${fileName} downloaded to ${destFileName}.` + `gs://${bucketName}/${fileName} downloaded to ${destFileName}.`, ); } diff --git a/samples/downloadFileInChunksWithTransferManager.js b/samples/downloadFileInChunksWithTransferManager.js index 5fe1e64cd..be80892f7 100644 --- a/samples/downloadFileInChunksWithTransferManager.js +++ b/samples/downloadFileInChunksWithTransferManager.js @@ -27,7 +27,7 @@ function main( bucketName = 'my-bucket', fileName = 'file1.txt', destFileName = path.join(cwd, fileName), - chunkSize = 1024 + chunkSize = 1024, ) { // [START storage_transfer_manager_download_chunks_concurrently] /** @@ -62,7 +62,7 @@ function main( }); console.log( - `gs://${bucketName}/${fileName} downloaded to ${destFileName}.` + `gs://${bucketName}/${fileName} downloaded to ${destFileName}.`, ); } diff --git a/samples/downloadFileUsingRequesterPays.js b/samples/downloadFileUsingRequesterPays.js index 8f449e075..035f8764d 100644 --- a/samples/downloadFileUsingRequesterPays.js +++ b/samples/downloadFileUsingRequesterPays.js @@ -27,7 +27,7 @@ function main( projectId = 'cloud-devrel-public-resources', bucketName = `nodejs-storage-samples-${uuid.v4()}`, srcFileName = 'test.txt', - destFileName = path.join(__dirname, `test_${uuid.v4()}.txt`) + destFileName = path.join(__dirname, `test_${uuid.v4()}.txt`), ) { // [START storage_download_file_requester_pays] @@ -62,7 +62,7 @@ function main( await storage.bucket(bucketName).file(srcFileName).download(options); console.log( - `gs://${bucketName}/${srcFileName} downloaded to ${destFileName} using requester-pays requests` + `gs://${bucketName}/${srcFileName} downloaded to ${destFileName} using requester-pays requests`, ); } diff --git a/samples/downloadFolderWithTransferManager.js b/samples/downloadFolderWithTransferManager.js index 9087f1f71..09562a6a2 100644 --- a/samples/downloadFolderWithTransferManager.js +++ b/samples/downloadFolderWithTransferManager.js @@ -45,7 +45,7 @@ function main(bucketName = 'my-bucket', folderName = 'my-folder') { await transferManager.downloadManyFiles(folderName); console.log( - `gs://${bucketName}/${folderName} downloaded to ${folderName}.` + `gs://${bucketName}/${folderName} downloaded to ${folderName}.`, ); } diff --git a/samples/downloadIntoMemory.js b/samples/downloadIntoMemory.js index c80fd9a86..ccda8f56d 100644 --- a/samples/downloadIntoMemory.js +++ b/samples/downloadIntoMemory.js @@ -42,7 +42,7 @@ function main(bucketName = 'my-bucket', fileName = 'test.txt') { const contents = await storage.bucket(bucketName).file(fileName).download(); console.log( - `Contents of gs://${bucketName}/${fileName} are ${contents.toString()}.` + `Contents of gs://${bucketName}/${fileName} are ${contents.toString()}.`, ); } diff --git a/samples/downloadManyFilesWithTransferManager.js b/samples/downloadManyFilesWithTransferManager.js index 7a464ad4c..48f94963a 100644 --- a/samples/downloadManyFilesWithTransferManager.js +++ b/samples/downloadManyFilesWithTransferManager.js @@ -23,7 +23,7 @@ function main( bucketName = 'my-bucket', firstFileName = 'file1.txt', - secondFileName = 'file2.txt' + secondFileName = 'file2.txt', ) { // [START storage_transfer_manager_download_many] /** diff --git a/samples/downloadPublicFile.js b/samples/downloadPublicFile.js index 426b9a7fb..f3971d5cc 100644 --- a/samples/downloadPublicFile.js +++ b/samples/downloadPublicFile.js @@ -25,7 +25,7 @@ const cwd = path.join(__dirname, '..'); function main( bucketName = 'my-bucket', srcFileName = 'test.txt', - destFileName = path.join(cwd, 'downloaded.txt') + destFileName = path.join(cwd, 'downloaded.txt'), ) { // [START storage_download_public_file] /** @@ -55,7 +55,7 @@ function main( await storage.bucket(bucketName).file(srcFileName).download(options); console.log( - `Downloaded public file ${srcFileName} from bucket name ${bucketName} to ${destFileName}` + `Downloaded public file ${srcFileName} from bucket name ${bucketName} to ${destFileName}`, ); } diff --git a/samples/enableBucketLifecycleManagement.js b/samples/enableBucketLifecycleManagement.js index ce1130986..2f023f492 100644 --- a/samples/enableBucketLifecycleManagement.js +++ b/samples/enableBucketLifecycleManagement.js @@ -42,7 +42,7 @@ function main(bucketName = 'my-bucket') { }); console.log( - `Lifecycle management is enabled for bucket ${bucketName} and the rules are:` + `Lifecycle management is enabled for bucket ${bucketName} and the rules are:`, ); console.log(metadata.lifecycle.rule); diff --git a/samples/enableDefaultKMSKey.js b/samples/enableDefaultKMSKey.js index adc3b3505..db86ab056 100644 --- a/samples/enableDefaultKMSKey.js +++ b/samples/enableDefaultKMSKey.js @@ -22,7 +22,7 @@ function main( bucketName = 'my-bucket', - defaultKmsKeyName = process.env.GOOGLE_CLOUD_KMS_KEY_ASIA + defaultKmsKeyName = process.env.GOOGLE_CLOUD_KMS_KEY_ASIA, ) { // [START storage_set_bucket_default_kms_key] /** @@ -48,7 +48,7 @@ function main( }); console.log( - `Default KMS key for ${bucketName} was set to ${defaultKmsKeyName}.` + `Default KMS key for ${bucketName} was set to ${defaultKmsKeyName}.`, ); } diff --git a/samples/enableRequesterPays.js b/samples/enableRequesterPays.js index 4425a1a65..3147cd635 100644 --- a/samples/enableRequesterPays.js +++ b/samples/enableRequesterPays.js @@ -38,7 +38,7 @@ function main(bucketName = 'my-bucket') { await storage.bucket(bucketName).enableRequesterPays(); console.log( - `Requester-pays requests have been enabled for bucket ${bucketName}` + `Requester-pays requests have been enabled for bucket ${bucketName}`, ); } diff --git a/samples/fileChangeStorageClass.js b/samples/fileChangeStorageClass.js index 4677c2a90..79f7aeceb 100644 --- a/samples/fileChangeStorageClass.js +++ b/samples/fileChangeStorageClass.js @@ -23,7 +23,7 @@ function main( bucketName = 'my-bucket', fileName = 'file.txt', storageClass = 'standard', - generationMatchPrecondition = 0 + generationMatchPrecondition = 0, ) { // [START storage_change_file_storage_class] // Imports the Google Cloud client library diff --git a/samples/fileSetMetadata.js b/samples/fileSetMetadata.js index d7f0adf13..07fca93de 100644 --- a/samples/fileSetMetadata.js +++ b/samples/fileSetMetadata.js @@ -22,7 +22,7 @@ function main( bucketName = 'my-bucket', fileName = 'file.txt', - metagenerationMatchPrecondition = 0 + metagenerationMatchPrecondition = 0, ) { // [START storage_set_metadata] // Imports the Google Cloud client library @@ -67,14 +67,14 @@ function main( modified: '1900-01-01', }, }, - options + options, ); console.log( 'Updated metadata for object', fileName, 'in bucket ', - bucketName + bucketName, ); console.log(metadata); } diff --git a/samples/generateV4UploadSignedUrl.js b/samples/generateV4UploadSignedUrl.js index 4b2b4c021..e2b3bd80d 100644 --- a/samples/generateV4UploadSignedUrl.js +++ b/samples/generateV4UploadSignedUrl.js @@ -58,7 +58,7 @@ function main(bucketName = 'my-bucket', fileName = 'test.txt') { console.log('You can use this URL with any user agent, for example:'); console.log( "curl -X PUT -H 'Content-Type: application/octet-stream' " + - `--upload-file my-file '${url}'` + `--upload-file my-file '${url}'`, ); } diff --git a/samples/getAutoclass.js b/samples/getAutoclass.js index 44ae5ff0a..141d32ff7 100644 --- a/samples/getAutoclass.js +++ b/samples/getAutoclass.js @@ -42,7 +42,7 @@ function main(bucketName = 'my-bucket') { } for ${metadata.name} at ${metadata.autoclass.toggleTime}. Autoclass terminal storage class is last updated to ${ metadata.autoclass.terminalStorageClass - } at ${metadata.autoclass.terminalStorageClassUpdateTime}.` + } at ${metadata.autoclass.terminalStorageClassUpdateTime}.`, ); } diff --git a/samples/getMetadata.js b/samples/getMetadata.js index ccaa6b8e3..e51b1da83 100644 --- a/samples/getMetadata.js +++ b/samples/getMetadata.js @@ -67,14 +67,14 @@ function main(bucketName = 'my-bucket', fileName = 'test.txt') { console.log(`Last Metadata Update: ${new Date(metadata.updated)}`); console.log(`TurboReplication: ${metadata.rpo}`); console.log( - `temporaryHold: ${metadata.temporaryHold ? 'enabled' : 'disabled'}` + `temporaryHold: ${metadata.temporaryHold ? 'enabled' : 'disabled'}`, ); console.log( - `eventBasedHold: ${metadata.eventBasedHold ? 'enabled' : 'disabled'}` + `eventBasedHold: ${metadata.eventBasedHold ? 'enabled' : 'disabled'}`, ); if (metadata.retentionExpirationTime) { console.log( - `retentionExpirationTime: ${new Date(metadata.retentionExpirationTime)}` + `retentionExpirationTime: ${new Date(metadata.retentionExpirationTime)}`, ); } if (metadata.metadata) { diff --git a/samples/getPublicAccessPrevention.js b/samples/getPublicAccessPrevention.js index 7a53f7ff2..4d5f92c13 100644 --- a/samples/getPublicAccessPrevention.js +++ b/samples/getPublicAccessPrevention.js @@ -38,7 +38,7 @@ function main(bucketName = 'my-bucket') { // Gets Bucket Metadata and prints publicAccessPrevention value (either 'inherited' or 'enforced'). const [metadata] = await storage.bucket(bucketName).getMetadata(); console.log( - `Public access prevention is ${metadata.iamConfiguration.publicAccessPrevention} for ${bucketName}.` + `Public access prevention is ${metadata.iamConfiguration.publicAccessPrevention} for ${bucketName}.`, ); } diff --git a/samples/getRequesterPaysStatus.js b/samples/getRequesterPaysStatus.js index fea0ad4e7..e4f7dacde 100644 --- a/samples/getRequesterPaysStatus.js +++ b/samples/getRequesterPaysStatus.js @@ -45,7 +45,7 @@ function main(bucketName = 'my-bucket') { status = 'disabled'; } console.log( - `Requester-pays requests are ${status} for bucket ${bucketName}.` + `Requester-pays requests are ${status} for bucket ${bucketName}.`, ); } diff --git a/samples/getServiceAccount.js b/samples/getServiceAccount.js index 6d4a29ba3..e87c4ca04 100644 --- a/samples/getServiceAccount.js +++ b/samples/getServiceAccount.js @@ -38,7 +38,7 @@ function main(projectId = 'serviceAccountProjectId') { async function getServiceAccount() { const [serviceAccount] = await storage.getServiceAccount(); console.log( - `The GCS service account for project ${projectId} is: ${serviceAccount.emailAddress}` + `The GCS service account for project ${projectId} is: ${serviceAccount.emailAddress}`, ); } diff --git a/samples/getUniformBucketLevelAccess.js b/samples/getUniformBucketLevelAccess.js index e6382135e..8651abf0c 100644 --- a/samples/getUniformBucketLevelAccess.js +++ b/samples/getUniformBucketLevelAccess.js @@ -43,11 +43,11 @@ function main(bucketName = 'my-bucket') { metadata.iamConfiguration.uniformBucketLevelAccess; console.log(`Uniform bucket-level access is enabled for ${bucketName}.`); console.log( - `Bucket will be locked on ${uniformBucketLevelAccess.lockedTime}.` + `Bucket will be locked on ${uniformBucketLevelAccess.lockedTime}.`, ); } else { console.log( - `Uniform bucket-level access is not enabled for ${bucketName}.` + `Uniform bucket-level access is not enabled for ${bucketName}.`, ); } } diff --git a/samples/hmacKeyActivate.js b/samples/hmacKeyActivate.js index 6ce8a2dd9..ef5d9b162 100644 --- a/samples/hmacKeyActivate.js +++ b/samples/hmacKeyActivate.js @@ -21,7 +21,7 @@ function main( hmacKeyAccessId = 'GOOG0234230X00', - projectId = 'serviceAccountProjectId' + projectId = 'serviceAccountProjectId', ) { // [START storage_activate_hmac_key] /** diff --git a/samples/hmacKeyCreate.js b/samples/hmacKeyCreate.js index 3fb345680..988da5d1d 100644 --- a/samples/hmacKeyCreate.js +++ b/samples/hmacKeyCreate.js @@ -21,7 +21,7 @@ function main( serviceAccountEmail = 'service-account@example.com', - projectId = 'serviceAccountProjectId' + projectId = 'serviceAccountProjectId', ) { // [START storage_create_hmac_key] /** diff --git a/samples/hmacKeyDeactivate.js b/samples/hmacKeyDeactivate.js index 471bc84ca..730ef2c7d 100644 --- a/samples/hmacKeyDeactivate.js +++ b/samples/hmacKeyDeactivate.js @@ -21,7 +21,7 @@ function main( hmacKeyAccessId = 'GOOG0234230X00', - projectId = 'serviceAccountProjectId' + projectId = 'serviceAccountProjectId', ) { // [START storage_deactivate_hmac_key] /** diff --git a/samples/hmacKeyDelete.js b/samples/hmacKeyDelete.js index 337a273b0..1eee2e704 100644 --- a/samples/hmacKeyDelete.js +++ b/samples/hmacKeyDelete.js @@ -21,7 +21,7 @@ function main( hmacKeyAccessId = 'GOOG0234230X00', - projectId = 'serviceAccountProjectId' + projectId = 'serviceAccountProjectId', ) { // [START storage_delete_hmac_key] /** @@ -45,7 +45,7 @@ function main( await hmacKey.delete(); console.log( - 'The key is deleted, though it may still appear in getHmacKeys() results.' + 'The key is deleted, though it may still appear in getHmacKeys() results.', ); } // [END storage_delete_hmac_key] diff --git a/samples/hmacKeyGet.js b/samples/hmacKeyGet.js index 656036984..e205e6c0b 100644 --- a/samples/hmacKeyGet.js +++ b/samples/hmacKeyGet.js @@ -21,7 +21,7 @@ function main( hmacKeyAccessId = 'GOOG0234230X00', - projectId = 'serviceAccountProjectId' + projectId = 'serviceAccountProjectId', ) { // [START storage_get_hmac_key] /** diff --git a/samples/hmacKeysList.js b/samples/hmacKeysList.js index 6f6acf939..db1a2c276 100644 --- a/samples/hmacKeysList.js +++ b/samples/hmacKeysList.js @@ -40,7 +40,7 @@ function main(projectId = 'serviceAccountProjectId') { // hmacKeys is an array of HmacKey objects. for (const hmacKey of hmacKeys) { console.log( - `Service Account Email: ${hmacKey.metadata.serviceAccountEmail}` + `Service Account Email: ${hmacKey.metadata.serviceAccountEmail}`, ); console.log(`Access Id: ${hmacKey.metadata.accessId}`); } diff --git a/samples/lockRetentionPolicy.js b/samples/lockRetentionPolicy.js index b259fdf7c..3f39d1c2b 100644 --- a/samples/lockRetentionPolicy.js +++ b/samples/lockRetentionPolicy.js @@ -46,7 +46,7 @@ function main(bucketName = 'my-bucket') { .lock(unlockedMetadata.metageneration); console.log(`Retention policy for ${bucketName} is now locked`); console.log( - `Retention policy effective as of ${lockedMetadata.retentionPolicy.effectiveTime}` + `Retention policy effective as of ${lockedMetadata.retentionPolicy.effectiveTime}`, ); return lockedMetadata; diff --git a/samples/moveFile.js b/samples/moveFile.js index 29d62d4e6..2d866a344 100644 --- a/samples/moveFile.js +++ b/samples/moveFile.js @@ -24,7 +24,7 @@ function main( bucketName = 'my-bucket', srcFileName = 'test.txt', destFileName = 'test2.txt', - destinationGenerationMatchPrecondition = 0 + destinationGenerationMatchPrecondition = 0, ) { // [START storage_move_file] /** @@ -66,7 +66,7 @@ function main( .move(destFileName, moveOptions); console.log( - `gs://${bucketName}/${srcFileName} moved to gs://${bucketName}/${destFileName}` + `gs://${bucketName}/${srcFileName} moved to gs://${bucketName}/${destFileName}`, ); } diff --git a/samples/printFileAclForUser.js b/samples/printFileAclForUser.js index f614749c7..030017926 100644 --- a/samples/printFileAclForUser.js +++ b/samples/printFileAclForUser.js @@ -23,7 +23,7 @@ function main( bucketName = 'my-bucket', fileName = 'test.txt', - userEmail = 'jdobry@google.com' + userEmail = 'jdobry@google.com', ) { // [START storage_print_file_acl_for_user] /** diff --git a/samples/releaseEventBasedHold.js b/samples/releaseEventBasedHold.js index cbce58d4b..3ee931c62 100644 --- a/samples/releaseEventBasedHold.js +++ b/samples/releaseEventBasedHold.js @@ -23,7 +23,7 @@ function main( bucketName = 'my-bucket', fileName = 'test.txt', - metagenerationMatchPrecondition = 0 + metagenerationMatchPrecondition = 0, ) { // [START storage_release_event_based_hold] /** @@ -53,7 +53,7 @@ function main( { eventBasedHold: false, }, - options + options, ); console.log(`Event-based hold was released for ${fileName}.`); } diff --git a/samples/releaseTemporaryHold.js b/samples/releaseTemporaryHold.js index 91f6c15b3..3b858c791 100644 --- a/samples/releaseTemporaryHold.js +++ b/samples/releaseTemporaryHold.js @@ -23,7 +23,7 @@ function main( bucketName = 'my-bucket', fileName = 'test.txt', - metagenerationMatchPrecondition = 0 + metagenerationMatchPrecondition = 0, ) { // [START storage_release_temporary_hold] /** @@ -53,7 +53,7 @@ function main( { temporaryHold: false, }, - options + options, ); console.log(`Temporary hold was released for ${fileName}.`); } diff --git a/samples/removeBucketConditionalBinding.js b/samples/removeBucketConditionalBinding.js index 7ba888ea5..a0ed17c1f 100644 --- a/samples/removeBucketConditionalBinding.js +++ b/samples/removeBucketConditionalBinding.js @@ -25,7 +25,7 @@ function main( roleName = 'roles/storage.objectViewer', title = 'match-prefix', description = 'Applies to objects matching a prefix', - expression = 'resource.name.startsWith("projects/_/buckets/bucket-name/objects/prefix-a-")' + expression = 'resource.name.startsWith("projects/_/buckets/bucket-name/objects/prefix-a-")', ) { // [START storage_remove_bucket_conditional_iam_binding] /** @@ -71,7 +71,7 @@ function main( binding.condition && binding.condition.title === title && binding.condition.description === description && - binding.condition.expression === expression + binding.condition.expression === expression, ); const binding = policy.bindings[index]; diff --git a/samples/removeBucketIamMember.js b/samples/removeBucketIamMember.js index fe333a2f4..1dc726bbe 100644 --- a/samples/removeBucketIamMember.js +++ b/samples/removeBucketIamMember.js @@ -15,7 +15,7 @@ function main( bucketName = 'my-bucket', roleName = 'roles/storage.objectViewer', - members = 'user:test@example.com' + members = 'user:test@example.com', ) { members = members.split(','); // [START storage_remove_bucket_iam_member] @@ -50,13 +50,13 @@ function main( // Finds and updates the appropriate role-member group, without a condition. const index = policy.bindings.findIndex( - binding => binding.role === roleName && !binding.condition + binding => binding.role === roleName && !binding.condition, ); const role = policy.bindings[index]; if (role) { role.members = role.members.filter( - member => members.indexOf(member) === -1 + member => members.indexOf(member) === -1, ); // Updates the policy object with the new (or empty) role-member group @@ -74,7 +74,7 @@ function main( } console.log( - `Removed the following member(s) with role ${roleName} from ${bucketName}:` + `Removed the following member(s) with role ${roleName} from ${bucketName}:`, ); members.forEach(member => { console.log(` ${member}`); diff --git a/samples/removeFileOwnerAcl.js b/samples/removeFileOwnerAcl.js index 2a72e1f7e..60fd94ef4 100644 --- a/samples/removeFileOwnerAcl.js +++ b/samples/removeFileOwnerAcl.js @@ -23,7 +23,7 @@ function main( bucketName = 'my-bucket', fileName = 'test.txt', - userEmail = 'jdobry@google.com' + userEmail = 'jdobry@google.com', ) { // [START storage_remove_file_owner] /** diff --git a/samples/removeRetentionPolicy.js b/samples/removeRetentionPolicy.js index f7ec28c7d..d613a3c21 100644 --- a/samples/removeRetentionPolicy.js +++ b/samples/removeRetentionPolicy.js @@ -38,7 +38,7 @@ function main(bucketName = 'my-bucket') { const [metadata] = await storage.bucket(bucketName).getMetadata(); if (metadata.retentionPolicy && metadata.retentionPolicy.isLocked) { console.log( - 'Unable to remove retention period as retention policy is locked.' + 'Unable to remove retention period as retention policy is locked.', ); return null; } else { diff --git a/samples/renameFile.js b/samples/renameFile.js index 0bd53108f..42ac7ce9e 100644 --- a/samples/renameFile.js +++ b/samples/renameFile.js @@ -23,7 +23,7 @@ function main( srcBucketName = 'my-bucket', srcFileName = 'test2.txt', - destFileName = 'test4.txt' + destFileName = 'test4.txt', ) { // [START storage_rename_file] /** @@ -49,7 +49,7 @@ function main( await storage.bucket(srcBucketName).file(srcFileName).rename(destFileName); console.log( - `gs://${srcBucketName}/${srcFileName} renamed to gs://${srcBucketName}/${destFileName}.` + `gs://${srcBucketName}/${srcFileName} renamed to gs://${srcBucketName}/${destFileName}.`, ); } diff --git a/samples/rotateEncryptionKey.js b/samples/rotateEncryptionKey.js index 9bcbd4501..4cb5305aa 100644 --- a/samples/rotateEncryptionKey.js +++ b/samples/rotateEncryptionKey.js @@ -25,7 +25,7 @@ function main( fileName = 'test.txt', oldKey = process.env.GOOGLE_CLOUD_KMS_KEY_US, newKey = process.env.GOOGLE_CLOUD_KMS_KEY_ASIA, - generationMatchPrecondition = 0 + generationMatchPrecondition = 0, ) { // [START storage_rotate_encryption_key] /** diff --git a/samples/setAutoclass.js b/samples/setAutoclass.js index d8c906ac0..72db2e2ba 100644 --- a/samples/setAutoclass.js +++ b/samples/setAutoclass.js @@ -17,7 +17,7 @@ function main( bucketName = 'my-bucket', toggle = true, - terminalStorageClass = 'ARCHIVE' + terminalStorageClass = 'ARCHIVE', ) { // [START storage_set_autoclass] /** @@ -47,7 +47,7 @@ function main( }); console.log( - `Autoclass terminal storage class is ${metadata.autoclass.terminalStorageClass}.` + `Autoclass terminal storage class is ${metadata.autoclass.terminalStorageClass}.`, ); } diff --git a/samples/setEventBasedHold.js b/samples/setEventBasedHold.js index cda14b4c3..af365df55 100644 --- a/samples/setEventBasedHold.js +++ b/samples/setEventBasedHold.js @@ -23,7 +23,7 @@ function main( bucketName = 'my-bucket', fileName = 'test.txt', - metagenerationMatchPrecondition = 0 + metagenerationMatchPrecondition = 0, ) { // [START storage_set_event_based_hold] /** @@ -54,7 +54,7 @@ function main( { eventBasedHold: true, }, - options + options, ); console.log(`Event-based hold was set for ${fileName}.`); } diff --git a/samples/setObjectRetentionPolicy.js b/samples/setObjectRetentionPolicy.js index fc5c2ab1e..2b11b7357 100644 --- a/samples/setObjectRetentionPolicy.js +++ b/samples/setObjectRetentionPolicy.js @@ -22,7 +22,7 @@ function main( bucketName = 'my-bucket', destFileName = 'file.txt', - contents = 'this is the file content' + contents = 'this is the file content', ) { // [START storage_set_object_retention_policy] /** @@ -66,7 +66,7 @@ function main( }); console.log( - `Retention policy for file ${file.name} was set to: ${metadata.retention.mode}` + `Retention policy for file ${file.name} was set to: ${metadata.retention.mode}`, ); // To modify an existing policy on an unlocked file object, pass in the override parameter @@ -78,7 +78,7 @@ function main( }); console.log( - `Retention policy for file ${file.name} was updated to: ${metadata.retention.retainUntilTime}` + `Retention policy for file ${file.name} was updated to: ${metadata.retention.retainUntilTime}`, ); } diff --git a/samples/setPublicAccessPreventionEnforced.js b/samples/setPublicAccessPreventionEnforced.js index 036bf8bec..22bdc6b9c 100644 --- a/samples/setPublicAccessPreventionEnforced.js +++ b/samples/setPublicAccessPreventionEnforced.js @@ -43,7 +43,7 @@ function main(bucketName = 'my-bucket') { }); console.log( - `Public access prevention is set to enforced for ${bucketName}.` + `Public access prevention is set to enforced for ${bucketName}.`, ); } diff --git a/samples/setRetentionPolicy.js b/samples/setRetentionPolicy.js index 21d4d2201..94ba3aed6 100644 --- a/samples/setRetentionPolicy.js +++ b/samples/setRetentionPolicy.js @@ -42,7 +42,7 @@ function main(bucketName = 'my-bucket', retentionPeriod = 5) { .bucket(bucketName) .setRetentionPeriod(retentionPeriod); console.log( - `Bucket ${bucketName} retention period set for ${metadata.retentionPolicy.retentionPeriod} seconds.` + `Bucket ${bucketName} retention period set for ${metadata.retentionPolicy.retentionPeriod} seconds.`, ); } diff --git a/samples/setTemporaryHold.js b/samples/setTemporaryHold.js index db503748a..0c1e78336 100644 --- a/samples/setTemporaryHold.js +++ b/samples/setTemporaryHold.js @@ -23,7 +23,7 @@ function main( bucketName = 'my-bucket', fileName = 'test.txt', - metagenerationMatchPrecondition = 0 + metagenerationMatchPrecondition = 0, ) { // [START storage_set_temporary_hold] /** @@ -53,7 +53,7 @@ function main( { temporaryHold: true, }, - options + options, ); console.log(`Temporary hold was set for ${fileName}.`); } diff --git a/samples/streamFileDownload.js b/samples/streamFileDownload.js index b25aa87f7..420bc7085 100644 --- a/samples/streamFileDownload.js +++ b/samples/streamFileDownload.js @@ -26,7 +26,7 @@ const fs = require('fs'); function main( bucketName = 'my-bucket', fileName = 'test.txt', - destFileName = path.join(cwd, 'downloaded.txt') + destFileName = path.join(cwd, 'downloaded.txt'), ) { // [START storage_stream_file_download] /** @@ -61,7 +61,7 @@ function main( }); console.log( - `gs://${bucketName}/${fileName} downloaded to ${destFileName}.` + `gs://${bucketName}/${fileName} downloaded to ${destFileName}.`, ); } diff --git a/samples/streamFileUpload.js b/samples/streamFileUpload.js index 19c240f60..5aade2e0e 100644 --- a/samples/streamFileUpload.js +++ b/samples/streamFileUpload.js @@ -23,7 +23,7 @@ function main( bucketName = 'my-bucket', destFileName = 'file.txt', - contents = 'this is the file content' + contents = 'this is the file content', ) { // [START storage_stream_file_upload] /** diff --git a/samples/system-test/acl.test.js b/samples/system-test/acl.test.js index 5074b04b7..faf07551b 100644 --- a/samples/system-test/acl.test.js +++ b/samples/system-test/acl.test.js @@ -70,7 +70,7 @@ it('should print acl for a file', () => { it('should print a users acl for a bucket', async () => { await bucket.acl.readers.addUser(userEmail); const out = execSync( - `node printBucketAclForUser.js ${bucketName} ${userEmail}` + `node printBucketAclForUser.js ${bucketName} ${userEmail}`, ); assert.match(out, new RegExp(`READER: user-${userEmail}`)); await bucket.acl.readers.deleteUser(userEmail); @@ -80,44 +80,44 @@ it('should add a user as an owner on a bucket', () => { const out = execSync(`node addBucketOwnerAcl.js ${bucketName} ${userEmail}`); assert.match( out, - new RegExp(`Added user ${userEmail} as an owner on bucket ${bucketName}.`) + new RegExp(`Added user ${userEmail} as an owner on bucket ${bucketName}.`), ); }); it('should remove a user from a bucket', () => { const out = execSync( - `node removeBucketOwnerAcl.js ${bucketName} ${userEmail}` + `node removeBucketOwnerAcl.js ${bucketName} ${userEmail}`, ); assert.match( out, - new RegExp(`Removed user ${userEmail} from bucket ${bucketName}.`) + new RegExp(`Removed user ${userEmail} from bucket ${bucketName}.`), ); }); it('should add a user as a default owner on a bucket', () => { const out = execSync( - `node addBucketDefaultOwnerAcl.js ${bucketName} ${userEmail}` + `node addBucketDefaultOwnerAcl.js ${bucketName} ${userEmail}`, ); assert.match( out, - new RegExp(`Added user ${userEmail} as an owner on bucket ${bucketName}.`) + new RegExp(`Added user ${userEmail} as an owner on bucket ${bucketName}.`), ); }); it('should remove a default user from a bucket', () => { const out = execSync( - `node removeBucketDefaultOwner.js ${bucketName} ${userEmail}` + `node removeBucketDefaultOwner.js ${bucketName} ${userEmail}`, ); assert.match( out, - new RegExp(`Removed user ${userEmail} from bucket ${bucketName}.`) + new RegExp(`Removed user ${userEmail} from bucket ${bucketName}.`), ); }); it('should print a users acl for a file', async () => { await bucket.file(fileName).acl.readers.addUser(userEmail); const out = execSync( - `node printFileAclForUser.js ${bucketName} ${fileName} ${userEmail}` + `node printFileAclForUser.js ${bucketName} ${fileName} ${userEmail}`, ); assert.match(out, new RegExp(`READER: user-${userEmail}`)); await bucket.file(fileName).acl.readers.deleteUser(userEmail); @@ -125,20 +125,20 @@ it('should print a users acl for a file', async () => { it('should add a user as an owner on a bucket', () => { const out = execSync( - `node addFileOwnerAcl.js ${bucketName} ${fileName} ${userEmail}` + `node addFileOwnerAcl.js ${bucketName} ${fileName} ${userEmail}`, ); assert.match( out, - new RegExp(`Added user ${userEmail} as an owner on file ${fileName}.`) + new RegExp(`Added user ${userEmail} as an owner on file ${fileName}.`), ); }); it('should remove a user from a bucket', () => { const out = execSync( - `node removeFileOwnerAcl.js ${bucketName} ${fileName} ${userEmail}` + `node removeFileOwnerAcl.js ${bucketName} ${fileName} ${userEmail}`, ); assert.match( out, - new RegExp(`Removed user ${userEmail} from file ${fileName}.`) + new RegExp(`Removed user ${userEmail} from file ${fileName}.`), ); }); diff --git a/samples/system-test/bucketLifecycle.test.js b/samples/system-test/bucketLifecycle.test.js index 8b1adf9b5..f9cab9bd5 100644 --- a/samples/system-test/bucketLifecycle.test.js +++ b/samples/system-test/bucketLifecycle.test.js @@ -41,11 +41,11 @@ describe('Bucket lifecycle management', () => { it('should add a lifecycle delete rule', async () => { const output = execSync( - `node enableBucketLifecycleManagement.js ${bucketName}` + `node enableBucketLifecycleManagement.js ${bucketName}`, ); assert.include( output, - `Lifecycle management is enabled for bucket ${bucketName} and the rules are:` + `Lifecycle management is enabled for bucket ${bucketName} and the rules are:`, ); const [metadata] = await bucket.getMetadata(); assert.deepStrictEqual(metadata.lifecycle.rule[0], { @@ -68,11 +68,11 @@ describe('Bucket lifecycle management', () => { }); const output = execSync( - `node disableBucketLifecycleManagement.js ${bucketName}` + `node disableBucketLifecycleManagement.js ${bucketName}`, ); assert.include( output, - `Lifecycle management is disabled for bucket ${bucketName}` + `Lifecycle management is disabled for bucket ${bucketName}`, ); const [newMetadata] = await bucket.getMetadata(); assert.isUndefined(newMetadata.lifecycle); diff --git a/samples/system-test/bucketLock.test.js b/samples/system-test/bucketLock.test.js index 7f4693ade..4c32f52c3 100644 --- a/samples/system-test/bucketLock.test.js +++ b/samples/system-test/bucketLock.test.js @@ -52,13 +52,13 @@ after(async () => { it('should set a retention policy on a bucket', () => { const retentionPeriod = 5; const output = execSync( - `node setRetentionPolicy.js ${bucketName} ${retentionPeriod}` + `node setRetentionPolicy.js ${bucketName} ${retentionPeriod}`, ); assert.match( output, new RegExp( - `Bucket ${bucketName} retention period set for ${retentionPeriod} seconds` - ) + `Bucket ${bucketName} retention period set for ${retentionPeriod} seconds`, + ), ); }); @@ -71,7 +71,7 @@ it('should enable default event-based hold on a bucket', () => { const output = execSync(`node enableDefaultEventBasedHold.js ${bucketName}`); assert.match( output, - new RegExp(`Default event-based hold was enabled for ${bucketName}.`) + new RegExp(`Default event-based hold was enabled for ${bucketName}.`), ); }); @@ -84,14 +84,14 @@ it('should disable default event-based hold on a bucket', () => { const output = execSync(`node disableDefaultEventBasedHold.js ${bucketName}`); assert.match( output, - new RegExp(`Default event-based hold was disabled for ${bucketName}`) + new RegExp(`Default event-based hold was disabled for ${bucketName}`), ); }); it('should set an event-based hold on a file', async () => { const [metadata] = await bucket.file(fileName).getMetadata(); const output = execSync( - `node setEventBasedHold.js ${bucketName} ${fileName} ${metadata.metageneration}` + `node setEventBasedHold.js ${bucketName} ${fileName} ${metadata.metageneration}`, ); assert.match(output, new RegExp(`Event-based hold was set for ${fileName}`)); }); @@ -99,11 +99,11 @@ it('should set an event-based hold on a file', async () => { it('should release an event-based hold on a file', async () => { const [metadata] = await bucket.file(fileName).getMetadata(); const output = execSync( - `node releaseEventBasedHold.js ${bucketName} ${fileName} ${metadata.metageneration}` + `node releaseEventBasedHold.js ${bucketName} ${fileName} ${metadata.metageneration}`, ); assert.match( output, - new RegExp(`Event-based hold was released for ${fileName}.`) + new RegExp(`Event-based hold was released for ${fileName}.`), ); }); @@ -111,14 +111,14 @@ it('should remove a retention policy on a bucket', () => { const output = execSync(`node removeRetentionPolicy.js ${bucketName}`); assert.match( output, - new RegExp(`Removed bucket ${bucketName} retention policy.`) + new RegExp(`Removed bucket ${bucketName} retention policy.`), ); }); it('should set an temporary hold on a file', async () => { const [metadata] = await bucket.file(fileName).getMetadata(); const output = execSync( - `node setTemporaryHold.js ${bucketName} ${fileName} ${metadata.metageneration}` + `node setTemporaryHold.js ${bucketName} ${fileName} ${metadata.metageneration}`, ); assert.match(output, new RegExp(`Temporary hold was set for ${fileName}.`)); }); @@ -126,11 +126,11 @@ it('should set an temporary hold on a file', async () => { it('should release an temporary hold on a file', async () => { const [metadata] = await bucket.file(fileName).getMetadata(); const output = execSync( - `node releaseTemporaryHold.js ${bucketName} ${fileName} ${metadata.metageneration}` + `node releaseTemporaryHold.js ${bucketName} ${fileName} ${metadata.metageneration}`, ); assert.match( output, - new RegExp(`Temporary hold was released for ${fileName}.`) + new RegExp(`Temporary hold was released for ${fileName}.`), ); }); @@ -140,6 +140,6 @@ it('should lock a bucket with a retention policy', () => { const output = execSync(`node lockRetentionPolicy.js ${bucketName}`); assert.match( output, - new RegExp(`Retention policy for ${bucketName} is now locked`) + new RegExp(`Retention policy for ${bucketName} is now locked`), ); }); diff --git a/samples/system-test/buckets.test.js b/samples/system-test/buckets.test.js index 01daaa28e..495721908 100644 --- a/samples/system-test/buckets.test.js +++ b/samples/system-test/buckets.test.js @@ -34,7 +34,7 @@ const bucketNameHierarchicalNamespace = `${samplesTestBucketPrefix}-g`; const defaultKmsKeyName = process.env.GOOGLE_CLOUD_KMS_KEY_ASIA; const bucket = storage.bucket(bucketName); const bucketWithClassAndLocation = storage.bucket( - bucketNameWithClassAndLocation + bucketNameWithClassAndLocation, ); const dualRegionBucket = storage.bucket(bucketNameDualRegion); const dualRegionBucketTurbo = storage.bucket(bucketNameDualRegionTurbo); @@ -90,14 +90,14 @@ it('should set autoclass terminal storage class to ARCHIVE', async () => { }, }); const output = execSync( - `node setAutoclass.js ${bucketNameAutoclass} ${true} ARCHIVE` + `node setAutoclass.js ${bucketNameAutoclass} ${true} ARCHIVE`, ); assert.include(output, 'ARCHIVE'); }); it('should disable autoclass', async () => { const output = execSync( - `node setAutoclass.js ${bucketNameAutoclass} ${false}` + `node setAutoclass.js ${bucketNameAutoclass} ${false}`, ); assert.include(output, 'Autoclass'); }); @@ -109,16 +109,16 @@ it('should get autoclass', async () => { it('should set a buckets default KMS key', async () => { const output = execSync( - `node enableDefaultKMSKey.js ${bucketName} ${defaultKmsKeyName}` + `node enableDefaultKMSKey.js ${bucketName} ${defaultKmsKeyName}`, ); assert.include( output, - `Default KMS key for ${bucketName} was set to ${defaultKmsKeyName}` + `Default KMS key for ${bucketName} was set to ${defaultKmsKeyName}`, ); const metadata = await bucket.getMetadata(); assert.strictEqual( metadata[0].encryption.defaultKmsKeyName, - defaultKmsKeyName + defaultKmsKeyName, ); }); @@ -131,17 +131,17 @@ it('should remove a buckets default KMS key', async () => { it("should enable a bucket's uniform bucket-level access", async () => { const output = execSync( - `node enableUniformBucketLevelAccess.js ${bucketName}` + `node enableUniformBucketLevelAccess.js ${bucketName}`, ); assert.match( output, - new RegExp(`Uniform bucket-level access was enabled for ${bucketName}`) + new RegExp(`Uniform bucket-level access was enabled for ${bucketName}`), ); const metadata = await bucket.getMetadata(); assert.strictEqual( metadata[0].iamConfiguration.uniformBucketLevelAccess.enabled, - true + true, ); }); @@ -150,36 +150,36 @@ it("should get a bucket's uniform bucket-level access metadata", async () => { assert.match( output, - new RegExp(`Uniform bucket-level access is enabled for ${bucketName}`) + new RegExp(`Uniform bucket-level access is enabled for ${bucketName}`), ); const [metadata] = await bucket.getMetadata(); assert.ok(metadata.iamConfiguration.uniformBucketLevelAccess.enabled); assert.strictEqual( metadata.iamConfiguration.uniformBucketLevelAccess.lockedTime !== null, - true + true, ); }); it("should disable a bucket's uniform bucket-level access", async () => { const output = execSync( - `node disableUniformBucketLevelAccess.js ${bucketName}` + `node disableUniformBucketLevelAccess.js ${bucketName}`, ); assert.match( output, - new RegExp(`Uniform bucket-level access was disabled for ${bucketName}`) + new RegExp(`Uniform bucket-level access was disabled for ${bucketName}`), ); const metadata = await bucket.getMetadata(); assert.strictEqual( metadata[0].iamConfiguration.uniformBucketLevelAccess.enabled, - false + false, ); }); it('should configure a bucket cors', async () => { execSync( - `node configureBucketCors.js ${bucketName} 3600 POST http://example.appspot.com content-type` + `node configureBucketCors.js ${bucketName} 3600 POST http://example.appspot.com content-type`, ); await bucket.getMetadata(); assert.deepStrictEqual(bucket.metadata.cors[0], { @@ -194,7 +194,7 @@ it('should remove a bucket cors configuration', async () => { const output = execSync(`node removeBucketCors.js ${bucketName}`); assert.include( output, - `Removed CORS configuration from bucket ${bucketName}` + `Removed CORS configuration from bucket ${bucketName}`, ); await bucket.getMetadata(); assert.ok(!bucket.metadata.cors); @@ -202,17 +202,19 @@ it('should remove a bucket cors configuration', async () => { it('should set public access prevention to enforced', async () => { const output = execSync( - `node setPublicAccessPreventionEnforced.js ${bucketName}` + `node setPublicAccessPreventionEnforced.js ${bucketName}`, ); assert.match( output, - new RegExp(`Public access prevention is set to enforced for ${bucketName}.`) + new RegExp( + `Public access prevention is set to enforced for ${bucketName}.`, + ), ); const metadata = await bucket.getMetadata(); assert.strictEqual( metadata[0].iamConfiguration.publicAccessPrevention, - PUBLIC_ACCESS_PREVENTION_ENFORCED + PUBLIC_ACCESS_PREVENTION_ENFORCED, ); }); @@ -227,7 +229,7 @@ it("should get a bucket's public access prevention metadata", async () => { assert.match( output, - new RegExp(`Public access prevention is enforced for ${bucketName}.`) + new RegExp(`Public access prevention is enforced for ${bucketName}.`), ); const [metadata] = await bucket.getMetadata(); @@ -236,23 +238,23 @@ it("should get a bucket's public access prevention metadata", async () => { it('should set public access prevention to inherited', async () => { const output = execSync( - `node setPublicAccessPreventionInherited.js ${bucketName}` + `node setPublicAccessPreventionInherited.js ${bucketName}`, ); assert.match( output, - new RegExp(`Public access prevention is 'inherited' for ${bucketName}.`) + new RegExp(`Public access prevention is 'inherited' for ${bucketName}.`), ); const metadata = await bucket.getMetadata(); assert.strictEqual( metadata[0].iamConfiguration.publicAccessPrevention, - PUBLIC_ACCESS_PREVENTION_INHERITED + PUBLIC_ACCESS_PREVENTION_INHERITED, ); }); it('should create a dual-region bucket', async () => { const output = execSync( - `node createBucketWithDualRegion.js ${bucketNameDualRegion} ${DUAL_REGION.LOCATION} ${DUAL_REGION.REGIONS[0]} ${DUAL_REGION.REGIONS[1]}` + `node createBucketWithDualRegion.js ${bucketNameDualRegion} ${DUAL_REGION.LOCATION} ${DUAL_REGION.REGIONS[0]} ${DUAL_REGION.REGIONS[1]}`, ); // Ensure the sample outputs the desired result @@ -283,13 +285,13 @@ it('should create a dual-region bucket', async () => { it('should create a dual-region bucket with turbo replication enabled', async () => { const output = execSync( - `node createBucketWithTurboReplication.js ${bucketNameDualRegionTurbo}` + `node createBucketWithTurboReplication.js ${bucketNameDualRegionTurbo}`, ); assert.match( output, new RegExp( - `${bucketNameDualRegionTurbo} created with the recovery point objective \\(RPO\\) set to ASYNC_TURBO in NAM4.` - ) + `${bucketNameDualRegionTurbo} created with the recovery point objective \\(RPO\\) set to ASYNC_TURBO in NAM4.`, + ), ); const [exists] = await dualRegionBucketTurbo.exists(); assert.strictEqual(exists, true); @@ -303,7 +305,7 @@ it("should get a bucket's RPO metadata", async () => { const output = execSync(`node getRPO.js ${bucketNameDualRegionTurbo}`); assert.match( output, - new RegExp(`RPO is ASYNC_TURBO for ${bucketNameDualRegionTurbo}.`) + new RegExp(`RPO is ASYNC_TURBO for ${bucketNameDualRegionTurbo}.`), ); const metadata = await dualRegionBucketTurbo.getMetadata(); @@ -312,11 +314,11 @@ it("should get a bucket's RPO metadata", async () => { it("should set a bucket's RPO to ASYNC_TURBO", async () => { const output = execSync( - `node setRPOAsyncTurbo.js ${bucketNameDualRegionTurbo}` + `node setRPOAsyncTurbo.js ${bucketNameDualRegionTurbo}`, ); assert.match( output, - new RegExp(`Turbo replication enabled for ${bucketNameDualRegionTurbo}.`) + new RegExp(`Turbo replication enabled for ${bucketNameDualRegionTurbo}.`), ); const metadata = await dualRegionBucketTurbo.getMetadata(); @@ -327,7 +329,7 @@ it("should set a bucket's RPO to DEFAULT", async () => { const output = execSync(`node setRPODefault.js ${bucketNameDualRegionTurbo}`); assert.match( output, - new RegExp(`Turbo replication disabled for ${bucketNameDualRegionTurbo}.`) + new RegExp(`Turbo replication disabled for ${bucketNameDualRegionTurbo}.`), ); const metadata = await dualRegionBucketTurbo.getMetadata(); @@ -336,13 +338,13 @@ it("should set a bucket's RPO to DEFAULT", async () => { it('should create a hierarchical namespace enabled bucket', async () => { const output = execSync( - `node createBucketWithHierarchicalNamespace.js ${bucketNameHierarchicalNamespace}` + `node createBucketWithHierarchicalNamespace.js ${bucketNameHierarchicalNamespace}`, ); assert.match( output, new RegExp( - `Created '${bucketNameHierarchicalNamespace}' with hierarchical namespace enabled.` - ) + `Created '${bucketNameHierarchicalNamespace}' with hierarchical namespace enabled.`, + ), ); const metadata = await dualRegionBucketTurbo.getMetadata(); @@ -351,12 +353,12 @@ it('should create a hierarchical namespace enabled bucket', async () => { it("should add a bucket's website configuration", async () => { const output = execSync( - `node addBucketWebsiteConfiguration.js ${bucketName} http://example.com http://example.com/404.html` + `node addBucketWebsiteConfiguration.js ${bucketName} http://example.com http://example.com/404.html`, ); assert.include( output, - `Static website bucket ${bucketName} is set up to use http://example.com as the index page and http://example.com/404.html as the 404 page` + `Static website bucket ${bucketName} is set up to use http://example.com as the index page and http://example.com/404.html as the 404 page`, ); const [metadata] = await bucket.getMetadata(); @@ -370,7 +372,7 @@ it('should make bucket publicly readable', async () => { const output = execSync(`node makeBucketPublic.js ${bucketName}`); assert.match( output, - new RegExp(`Bucket ${bucketName} is now publicly readable`) + new RegExp(`Bucket ${bucketName} is now publicly readable`), ); const [policy] = await bucket.iam.getPolicy(); const objectViewerBinding = policy.bindings.filter(binding => { @@ -396,7 +398,7 @@ it("should disable a bucket's versioning", async () => { it('should add label to bucket', async () => { const output = execSync( - `node addBucketLabel.js ${bucketName} labelone labelonevalue` + `node addBucketLabel.js ${bucketName} labelone labelonevalue`, ); assert.include(output, `Added label to bucket ${bucketName}`); const [labels] = await storage.bucket(bucketName).getLabels(); @@ -412,7 +414,7 @@ it('should remove label to bucket', async () => { it("should change a bucket's default storage class", async () => { const output = execSync( - `node changeDefaultStorageClass.js ${bucketName} coldline` + `node changeDefaultStorageClass.js ${bucketName} coldline`, ); assert.include(output, `${bucketName} has been set to coldline`); const [metadata] = await bucket.getMetadata(); @@ -421,11 +423,11 @@ it("should change a bucket's default storage class", async () => { it('should create bucket with storage class and location', async () => { const output = execSync( - `node createBucketWithStorageClassAndLocation.js ${bucketNameWithClassAndLocation} coldline ASIA` + `node createBucketWithStorageClassAndLocation.js ${bucketNameWithClassAndLocation} coldline ASIA`, ); assert.include( output, - `${bucketNameWithClassAndLocation} created with coldline class in ASIA` + `${bucketNameWithClassAndLocation} created with coldline class in ASIA`, ); const [metadata] = await bucketWithClassAndLocation.getMetadata(); assert.strictEqual(metadata.storageClass, 'COLDLINE'); @@ -441,11 +443,11 @@ it('should delete a bucket', async () => { it('should create a bucket with object retention enabled', async () => { const output = execSync( - `node createBucketWithObjectRetention.js ${bucketNameObjectRetention}` + `node createBucketWithObjectRetention.js ${bucketNameObjectRetention}`, ); assert.include( output, - `Created '${bucketNameObjectRetention}' with object retention enabled setting: Enabled` + `Created '${bucketNameObjectRetention}' with object retention enabled setting: Enabled`, ); const [metadata] = await objectRetentionBucket.getMetadata(); assert.strictEqual(metadata.objectRetention.mode, 'Enabled'); diff --git a/samples/system-test/encryption.test.js b/samples/system-test/encryption.test.js index e970df61e..4f1d4f1f4 100644 --- a/samples/system-test/encryption.test.js +++ b/samples/system-test/encryption.test.js @@ -57,11 +57,11 @@ it('should generate a key', () => { it('should upload a file', async () => { const output = execSync( - `node uploadEncryptedFile.js ${bucketName} ${filePath} ${fileName} ${key} ${doesNotExistPrecondition}` + `node uploadEncryptedFile.js ${bucketName} ${filePath} ${fileName} ${key} ${doesNotExistPrecondition}`, ); assert.match( output, - new RegExp(`File ${filePath} uploaded to gs://${bucketName}/${fileName}`) + new RegExp(`File ${filePath} uploaded to gs://${bucketName}/${fileName}`), ); const [exists] = await bucket.file(fileName).exists(); assert.strictEqual(exists, true); @@ -69,11 +69,11 @@ it('should upload a file', async () => { it('should download a file', () => { const output = execSync( - `node downloadEncryptedFile.js ${bucketName} ${fileName} ${downloadFilePath} ${key}` + `node downloadEncryptedFile.js ${bucketName} ${fileName} ${downloadFilePath} ${key}`, ); assert.match( output, - new RegExp(`File ${fileName} downloaded to ${downloadFilePath}`) + new RegExp(`File ${fileName} downloaded to ${downloadFilePath}`), ); fs.statSync(downloadFilePath); }); @@ -85,7 +85,7 @@ it('should rotate keys', async () => { .file(fileName) .getMetadata(); const output = execSync( - `node rotateEncryptionKey.js ${bucketName} ${fileName} ${key} ${newKey} ${metadata.generation}` + `node rotateEncryptionKey.js ${bucketName} ${fileName} ${key} ${newKey} ${metadata.generation}`, ); assert.include(output, 'Encryption key rotated successfully'); }); @@ -101,10 +101,10 @@ it('should convert CSEK to KMS key', async () => { .getMetadata(); await file.save('secret data', {resumable: false}); const output = execSync( - `node changeFileCSEKToCMEK.js ${bucketName} ${encryptedFileName} ${key} ${kmsKeyName} ${metadata.generation}` + `node changeFileCSEKToCMEK.js ${bucketName} ${encryptedFileName} ${key} ${kmsKeyName} ${metadata.generation}`, ); assert.include( output, - `file ${encryptedFileName} in bucket ${bucketName} is now managed by KMS key ${kmsKeyName} instead of customer-supplied encryption key` + `file ${encryptedFileName} in bucket ${bucketName} is now managed by KMS key ${kmsKeyName} instead of customer-supplied encryption key`, ); }); diff --git a/samples/system-test/files.test.js b/samples/system-test/files.test.js index 106c12d1c..91799feea 100644 --- a/samples/system-test/files.test.js +++ b/samples/system-test/files.test.js @@ -64,7 +64,7 @@ describe('file', () => { it('should upload a file', async () => { const output = execSync( - `node uploadFile.js ${bucketName} ${filePath} ${fileName} ${doesNotExistPrecondition}` + `node uploadFile.js ${bucketName} ${filePath} ${fileName} ${doesNotExistPrecondition}`, ); assert.match(output, new RegExp(`${filePath} uploaded to ${bucketName}`)); const [exists] = await bucket.file(fileName).exists(); @@ -73,13 +73,13 @@ describe('file', () => { it('should upload a file from memory', async () => { const output = execSync( - `node uploadFromMemory.js ${bucketName} ${fileContents} ${memoryFileName}` + `node uploadFromMemory.js ${bucketName} ${fileContents} ${memoryFileName}`, ); assert.match( output, new RegExp( - `${memoryFileName} with contents ${fileContents} uploaded to ${bucketName}.` - ) + `${memoryFileName} with contents ${fileContents} uploaded to ${bucketName}.`, + ), ); const [exists] = await bucket.file(memoryFileName).exists(); assert.strictEqual(exists, true); @@ -87,7 +87,7 @@ describe('file', () => { it('should upload a file without authentication', async () => { const output = execSync( - `node uploadWithoutAuthentication.js ${bucketName} ${fileContents} ${fileName} ${doesNotExistPrecondition}` + `node uploadWithoutAuthentication.js ${bucketName} ${fileContents} ${fileName} ${doesNotExistPrecondition}`, ); assert.match(output, new RegExp(`${fileName} uploaded to ${bucketName}`)); const [exists] = await bucket.file(fileName).exists(); @@ -96,7 +96,7 @@ describe('file', () => { it('should upload a file without authentication using signed url strategy', async () => { const output = execSync( - `node uploadWithoutAuthenticationSignedUrl.js ${bucketName} ${fileContents} ${fileName}` + `node uploadWithoutAuthenticationSignedUrl.js ${bucketName} ${fileContents} ${fileName}`, ); assert.match(output, new RegExp(`${fileName} uploaded to ${bucketName}`)); const [exists] = await bucket.file(fileName).exists(); @@ -105,7 +105,7 @@ describe('file', () => { it('should upload a file using a stream', async () => { const output = execSync( - `node streamFileUpload.js ${bucketName} ${fileName} ${fileContents}` + `node streamFileUpload.js ${bucketName} ${fileName} ${fileContents}`, ); assert.match(output, new RegExp(`${fileName} uploaded to ${bucketName}`)); const [exists] = await bucket.file(fileName).exists(); @@ -117,11 +117,11 @@ describe('file', () => { it('should upload a file with a kms key', async () => { const [metadata] = await bucket.file(fileName).getMetadata(); const output = execSync( - `node uploadFileWithKmsKey.js ${bucketName} ${filePath} ${kmsKeyName} ${metadata.generation}` + `node uploadFileWithKmsKey.js ${bucketName} ${filePath} ${kmsKeyName} ${metadata.generation}`, ); assert.include( output, - `${filePath} uploaded to ${bucketName} using ${kmsKeyName}` + `${filePath} uploaded to ${bucketName} using ${kmsKeyName}`, ); const [exists] = await bucket.file(fileName).exists(); assert.strictEqual(exists, true); @@ -129,7 +129,7 @@ describe('file', () => { it('should upload a local directory', done => { const output = execSync( - `node uploadDirectory.js ${bucketName} ${folderPath}` + `node uploadDirectory.js ${bucketName} ${folderPath}`, ); const fileList = []; @@ -151,18 +151,18 @@ describe('file', () => { assert.match( output, new RegExp( - `${fileList.length} files uploaded to ${bucketName} successfully.` - ) + `${fileList.length} files uploaded to ${bucketName} successfully.`, + ), ); Promise.all( fileList.map(file => bucket .file( - path.relative(path.dirname(folderPath), file).replace(/\\/g, '/') + path.relative(path.dirname(folderPath), file).replace(/\\/g, '/'), ) - .exists() - ) + .exists(), + ), ).then(resps => { const ctr = resps.reduce((acc, cur) => { return acc + cur[0]; @@ -174,62 +174,62 @@ describe('file', () => { it('should download a file', () => { const output = execSync( - `node downloadFile.js ${bucketName} ${fileName} ${downloadFilePath}` + `node downloadFile.js ${bucketName} ${fileName} ${downloadFilePath}`, ); assert.match( output, new RegExp( - `gs://${bucketName}/${fileName} downloaded to ${downloadFilePath}.` - ) + `gs://${bucketName}/${fileName} downloaded to ${downloadFilePath}.`, + ), ); fs.statSync(downloadFilePath); }); it('should download a file into memory', () => { const output = execSync( - `node downloadIntoMemory.js ${bucketName} ${memoryFileName}` + `node downloadIntoMemory.js ${bucketName} ${memoryFileName}`, ); assert.match( output, new RegExp( - `Contents of gs://${bucketName}/${memoryFileName} are ${fileContents}.` - ) + `Contents of gs://${bucketName}/${memoryFileName} are ${fileContents}.`, + ), ); }); it('should download a file using a stream', () => { const output = execSync( - `node streamFileDownload.js ${bucketName} ${fileName} ${downloadFilePath}` + `node streamFileDownload.js ${bucketName} ${fileName} ${downloadFilePath}`, ); assert.match( output, new RegExp( - `gs://${bucketName}/${fileName} downloaded to ${downloadFilePath}.` - ) + `gs://${bucketName}/${fileName} downloaded to ${downloadFilePath}.`, + ), ); fs.statSync(downloadFilePath); }); it('should download a file using a given byte range', () => { const output = execSync( - `node downloadByteRange.js ${bucketName} ${fileName} ${startByte} ${endByte} ${downloadFilePath}` + `node downloadByteRange.js ${bucketName} ${fileName} ${startByte} ${endByte} ${downloadFilePath}`, ); assert.match( output, new RegExp( - `gs://${bucketName}/${fileName} downloaded to ${downloadFilePath} from byte ${startByte} to byte ${endByte}.` - ) + `gs://${bucketName}/${fileName} downloaded to ${downloadFilePath} from byte ${startByte} to byte ${endByte}.`, + ), ); fs.statSync(downloadFilePath); }); it('should move a file', async () => { const output = execSync( - `node moveFile.js ${bucketName} ${fileName} ${movedFileName} ${doesNotExistPrecondition}` + `node moveFile.js ${bucketName} ${fileName} ${movedFileName} ${doesNotExistPrecondition}`, ); assert.include( output, - `gs://${bucketName}/${fileName} moved to gs://${bucketName}/${movedFileName}` + `gs://${bucketName}/${fileName} moved to gs://${bucketName}/${movedFileName}`, ); const [exists] = await bucket.file(movedFileName).exists(); assert.strictEqual(exists, true); @@ -237,11 +237,11 @@ describe('file', () => { it('should copy a file', async () => { const output = execSync( - `node copyFile.js ${bucketName} ${movedFileName} ${bucketName} ${copiedFileName} ${doesNotExistPrecondition}` + `node copyFile.js ${bucketName} ${movedFileName} ${bucketName} ${copiedFileName} ${doesNotExistPrecondition}`, ); assert.include( output, - `gs://${bucketName}/${movedFileName} copied to gs://${bucketName}/${copiedFileName}` + `gs://${bucketName}/${movedFileName} copied to gs://${bucketName}/${copiedFileName}`, ); const [exists] = await bucket.file(copiedFileName).exists(); assert.strictEqual(exists, true); @@ -275,13 +275,13 @@ describe('file', () => { it('should rename a file', async () => { const output = execSync( - `node renameFile.js ${bucketName} ${movedFileName} ${renamedFileName}` + `node renameFile.js ${bucketName} ${movedFileName} ${renamedFileName}`, ); assert.match( output, new RegExp( - `gs://${bucketName}/${movedFileName} renamed to gs://${bucketName}/${renamedFileName}.` - ) + `gs://${bucketName}/${movedFileName} renamed to gs://${bucketName}/${renamedFileName}.`, + ), ); const [exists] = await bucket.file(renamedFileName).exists(); assert.strictEqual(exists, true); @@ -315,21 +315,21 @@ describe('file', () => { it('should make a file public', () => { const output = execSync( - `node makePublic.js ${bucketName} ${publicFileName}` + `node makePublic.js ${bucketName} ${publicFileName}`, ); assert.match( output, - new RegExp(`gs://${bucketName}/${publicFileName} is now public`) + new RegExp(`gs://${bucketName}/${publicFileName} is now public`), ); }); it('should download public file', () => { const output = execSync( - `node downloadPublicFile.js ${bucketName} ${publicFileName} ${downloadPublicFilePath}` + `node downloadPublicFile.js ${bucketName} ${publicFileName} ${downloadPublicFilePath}`, ); assert.include( output, - `Downloaded public file ${publicFileName} from bucket name ${bucketName} to ${downloadPublicFilePath}` + `Downloaded public file ${publicFileName} from bucket name ${bucketName} to ${downloadPublicFilePath}`, ); fs.statSync(downloadPublicFilePath); }); @@ -337,17 +337,17 @@ describe('file', () => { it('should generate a v2 signed URL for a file', async () => { const output = await execSync( - `node generateSignedUrl ${bucketName} ${copiedFileName}` + `node generateSignedUrl ${bucketName} ${copiedFileName}`, ); assert.match( output, - new RegExp(`The signed url for ${copiedFileName} is `) + new RegExp(`The signed url for ${copiedFileName} is `), ); }); it('should generate a v4 signed URL and read a file', async () => { const output = await execSync( - `node generateV4ReadSignedUrl.js ${bucketName} ${copiedFileName}` + `node generateV4ReadSignedUrl.js ${bucketName} ${copiedFileName}`, ); const expected = /URL:\n([^\s]+)/; @@ -361,7 +361,7 @@ describe('file', () => { it('should generate a v4 signed URL and upload a file', async () => { const output = execSync( - `node generateV4UploadSignedUrl.js ${bucketName} ${signedFileName}` + `node generateV4UploadSignedUrl.js ${bucketName} ${signedFileName}`, ); const expected = /URL:\n([^\s]+)/; @@ -383,7 +383,7 @@ describe('file', () => { .on('response', res => { assert.strictEqual( res.headers['content-type'], - 'application/octet-stream' + 'application/octet-stream', ); }) .on('data', buf => (remoteContent += buf.toString())) @@ -397,12 +397,12 @@ describe('file', () => { it('should generate a v4 signed policy', async () => { const output = execSync( - `node generateV4SignedPolicy.js ${bucketName} ${signedFileName}` + `node generateV4SignedPolicy.js ${bucketName} ${signedFileName}`, ); assert.include( output, - `
{ assert.include(output, ' { it('should get metadata for a file', () => { const output = execSync( - `node getMetadata.js ${bucketName} ${copiedFileName}` + `node getMetadata.js ${bucketName} ${copiedFileName}`, ); assert.include(output, `Bucket: ${bucketName}`); assert.include(output, `Name: ${copiedFileName}`); @@ -434,19 +434,19 @@ describe('file', () => { modified: '1900-01-01', }; const output = execSync( - `node fileSetMetadata.js ${bucketName} ${copiedFileName} ${metadata.metageneration} ` + `node fileSetMetadata.js ${bucketName} ${copiedFileName} ${metadata.metageneration} `, ); assert.match( output, - new RegExp(`description: '${userMetadata.description}'`) + new RegExp(`description: '${userMetadata.description}'`), ); assert.match(output, new RegExp(`modified: '${userMetadata.modified}'`)); }); it('should set storage class for a file', async () => { const output = execSync( - `node fileChangeStorageClass.js ${bucketName} ${copiedFileName} standard ${doesNotExistPrecondition}` + `node fileChangeStorageClass.js ${bucketName} ${copiedFileName} standard ${doesNotExistPrecondition}`, ); assert.include(output, `${copiedFileName} has been set to standard`); const [metadata] = await storage @@ -470,28 +470,28 @@ describe('file', () => { const destinationFile = bucket.file(destinationFileName); const output = execSync( - `node composeFile.js ${bucketName} ${firstFileName} ${secondFileName} ${destinationFileName}` + `node composeFile.js ${bucketName} ${firstFileName} ${secondFileName} ${destinationFileName}`, ); assert.include( output, - `New composite file ${destinationFileName} was created by combining ${firstFileName} and ${secondFileName}` + `New composite file ${destinationFileName} was created by combining ${firstFileName} and ${secondFileName}`, ); const [contents] = await destinationFile.download(); assert.strictEqual( contents.toString(), - files.map(x => x.contents).join('') + files.map(x => x.contents).join(''), ); }); it('should delete a file', async () => { const [metadata] = await bucket.file(copiedFileName).getMetadata(); const output = execSync( - `node deleteFile.js ${bucketName} ${copiedFileName} ${metadata.generation}` + `node deleteFile.js ${bucketName} ${copiedFileName} ${metadata.generation}`, ); assert.match( output, - new RegExp(`gs://${bucketName}/${copiedFileName} deleted`) + new RegExp(`gs://${bucketName}/${copiedFileName} deleted`), ); const [exists] = await bucket.file(copiedFileName).exists(); assert.strictEqual(exists, false); @@ -526,7 +526,7 @@ describe('file', () => { it('should list file with old versions', async () => { const output = execSync( - `node listFilesWithOldVersions.js ${bucketNameWithVersioning}` + `node listFilesWithOldVersions.js ${bucketNameWithVersioning}`, ); assert.notEqual(output.indexOf(fileName), output.lastIndexOf(fileName)); }); @@ -536,13 +536,13 @@ describe('file', () => { const [files] = await bucketWithVersioning.getFiles({versions: true}); const generation = files[0].metadata.generation; const output = execSync( - `node copyOldVersionOfFile.js ${bucketNameWithVersioning} ${fileName} ${bucketNameWithVersioning} ${destFileName} ${generation}` + `node copyOldVersionOfFile.js ${bucketNameWithVersioning} ${fileName} ${bucketNameWithVersioning} ${destFileName} ${generation}`, ); assert.match( output, new RegExp( - `Generation ${generation} of file ${fileName} in bucket ${bucketNameWithVersioning} was copied to ${destFileName} in bucket ${bucketNameWithVersioning}` - ) + `Generation ${generation} of file ${fileName} in bucket ${bucketNameWithVersioning} was copied to ${destFileName} in bucket ${bucketNameWithVersioning}`, + ), ); const [exists] = await bucketWithVersioning.file(destFileName).exists(); assert.strictEqual(exists, true); @@ -550,11 +550,13 @@ describe('file', () => { it('should delete a file with customized retry settings', () => { const output = execSync( - `node configureRetries.js ${bucketName} ${fileName}` + `node configureRetries.js ${bucketName} ${fileName}`, ); assert.match( output, - new RegExp(`File ${fileName} deleted with a customized retry strategy.`) + new RegExp( + `File ${fileName} deleted with a customized retry strategy.`, + ), ); }); @@ -562,13 +564,13 @@ describe('file', () => { const [files] = await bucketWithVersioning.getFiles({versions: true}); const generation = files[0].metadata.generation; const output = execSync( - `node deleteOldVersionOfFile.js ${bucketNameWithVersioning} ${fileName} ${generation}` + `node deleteOldVersionOfFile.js ${bucketNameWithVersioning} ${fileName} ${generation}`, ); assert.match( output, new RegExp( - `Generation ${generation} of file ${fileName} was deleted from ${bucketNameWithVersioning}` - ) + `Generation ${generation} of file ${fileName} was deleted from ${bucketNameWithVersioning}`, + ), ); const [exists] = await bucketWithVersioning .file(fileName, { @@ -588,7 +590,7 @@ describe('file', () => { it('should create a file with unlocked retention and then override it', async () => { const output = execSync( - `node setObjectRetentionPolicy.js ${objectRetentionBucketName} ${fileName} ${fileContent}` + `node setObjectRetentionPolicy.js ${objectRetentionBucketName} ${fileName} ${fileContent}`, ); assert.include(output, 'Retention policy for file'); const file = objectRetentionBucket.file(fileName); diff --git a/samples/system-test/hmacKey.test.js b/samples/system-test/hmacKey.test.js index 20c4e149b..38dfe6ee8 100644 --- a/samples/system-test/hmacKey.test.js +++ b/samples/system-test/hmacKey.test.js @@ -41,7 +41,7 @@ describe('HMAC SA Key samples', () => { it('should create an HMAC Key', async () => { const output = execSync( - `node hmacKeyCreate.js ${SERVICE_ACCOUNT_EMAIL} ${SERVICE_ACCOUNT_PROJECT}` + `node hmacKeyCreate.js ${SERVICE_ACCOUNT_EMAIL} ${SERVICE_ACCOUNT_PROJECT}`, ); assert.include(output, 'The base64 encoded secret is:'); }); @@ -53,21 +53,21 @@ describe('HMAC SA Key samples', () => { it('should get HMAC Key', async () => { const output = execSync( - `node hmacKeyGet.js ${hmacKey.metadata.accessId} ${SERVICE_ACCOUNT_PROJECT}` + `node hmacKeyGet.js ${hmacKey.metadata.accessId} ${SERVICE_ACCOUNT_PROJECT}`, ); assert.include(output, 'The HMAC key metadata is:'); }); it('should deactivate HMAC Key', async () => { const output = execSync( - `node hmacKeyDeactivate.js ${hmacKey.metadata.accessId} ${SERVICE_ACCOUNT_PROJECT}` + `node hmacKeyDeactivate.js ${hmacKey.metadata.accessId} ${SERVICE_ACCOUNT_PROJECT}`, ); assert.include(output, 'The HMAC key is now inactive.'); }); it('should activate HMAC Key', async () => { const output = execSync( - `node hmacKeyActivate.js ${hmacKey.metadata.accessId} ${SERVICE_ACCOUNT_PROJECT}` + `node hmacKeyActivate.js ${hmacKey.metadata.accessId} ${SERVICE_ACCOUNT_PROJECT}`, ); assert.include(output, 'The HMAC key is now active.'); }); @@ -75,14 +75,14 @@ describe('HMAC SA Key samples', () => { it('should delete HMAC key', async () => { // Deactivate then delete execSync( - `node hmacKeyDeactivate.js ${hmacKey.metadata.accessId} ${SERVICE_ACCOUNT_PROJECT}` + `node hmacKeyDeactivate.js ${hmacKey.metadata.accessId} ${SERVICE_ACCOUNT_PROJECT}`, ); const output = execSync( - `node hmacKeyDelete.js ${hmacKey.metadata.accessId} ${SERVICE_ACCOUNT_PROJECT}` + `node hmacKeyDelete.js ${hmacKey.metadata.accessId} ${SERVICE_ACCOUNT_PROJECT}`, ); assert.include( output, - 'The key is deleted, though it may still appear in getHmacKeys() results.' + 'The key is deleted, though it may still appear in getHmacKeys() results.', ); }); }); @@ -110,7 +110,7 @@ async function deleteStaleHmacKeys(serviceAccountEmail, projectId) { limit(async () => { await hmacKey.setMetadata({state: 'INACTIVE'}); await hmacKey.delete(); - }) - ) + }), + ), ); } diff --git a/samples/system-test/iam.test.js b/samples/system-test/iam.test.js index 22da024e1..593366447 100644 --- a/samples/system-test/iam.test.js +++ b/samples/system-test/iam.test.js @@ -52,22 +52,22 @@ after(async () => { it('should add multiple members to a role on a bucket', async () => { const output = execSync( - `node addBucketIamMember.js ${bucketName} ${roleName} "user:${userEmail}"` + `node addBucketIamMember.js ${bucketName} ${roleName} "user:${userEmail}"`, ); assert.include( output, - `Added the following member(s) with role ${roleName} to ${bucketName}:` + `Added the following member(s) with role ${roleName} to ${bucketName}:`, ); assert.match(output, new RegExp(`user:${userEmail}`)); }); it('should add conditional binding to a bucket', async () => { const output = execSync( - `node addBucketConditionalBinding.js ${bucketName} ${roleName} '${title}' '${description}' '${expression}' "user:${userEmail}"` + `node addBucketConditionalBinding.js ${bucketName} ${roleName} '${title}' '${description}' '${expression}' "user:${userEmail}"`, ); assert.include( output, - `Added the following member(s) with role ${roleName} to ${bucketName}:` + `Added the following member(s) with role ${roleName} to ${bucketName}:`, ); assert.include(output, 'with condition:'); assert.include(output, `Title: ${title}`); @@ -85,19 +85,19 @@ it('should list members of a role on a bucket', async () => { it('should remove multiple members from a role on a bucket', async () => { const output = execSync( - `node removeBucketIamMember.js ${bucketName} ${roleName} "user:${userEmail}"` + `node removeBucketIamMember.js ${bucketName} ${roleName} "user:${userEmail}"`, ); assert.ok( output.includes( - `Removed the following member(s) with role ${roleName} from ${bucketName}:` - ) + `Removed the following member(s) with role ${roleName} from ${bucketName}:`, + ), ); assert.match(output, new RegExp(`user:${userEmail}`)); }); it('should remove conditional binding to a bucket', async () => { const output = execSync( - `node removeBucketConditionalBinding.js ${bucketName} ${roleName} '${title}' '${description}' '${expression}'` + `node removeBucketConditionalBinding.js ${bucketName} ${roleName} '${title}' '${description}' '${expression}'`, ); assert.include(output, 'Conditional Binding was removed'); }); diff --git a/samples/system-test/notifications.test.js b/samples/system-test/notifications.test.js index ef88d8b07..c86c7a782 100644 --- a/samples/system-test/notifications.test.js +++ b/samples/system-test/notifications.test.js @@ -52,7 +52,7 @@ after(async () => { it('should create a notification', async () => { const output = execSync( - `node createNotification.js ${bucketName} ${topicName}` + `node createNotification.js ${bucketName} ${topicName}`, ); assert.match(output, /Notification subscription created./); const [exists] = await notification.exists(); @@ -68,7 +68,7 @@ it('should list notifications', async () => { it('should get metadata', async () => { const metadata = await notification.getMetadata(); const output = execSync( - `node getMetadataNotifications.js ${bucketName} ${notificationId}` + `node getMetadataNotifications.js ${bucketName} ${notificationId}`, ); assert.match(output, /ID:/); assert.match(output, new RegExp(metadata.id)); @@ -91,7 +91,7 @@ it('should get metadata', async () => { it('should delete a notification', async () => { const output = execSync( - `node deleteNotification.js ${bucketName} ${notificationId}` + `node deleteNotification.js ${bucketName} ${notificationId}`, ); assert.match(output, new RegExp(`Notification ${notificationId} deleted.`)); const [exists] = await notification.exists(); diff --git a/samples/system-test/requesterPays.test.js b/samples/system-test/requesterPays.test.js index 76611db16..031a78541 100644 --- a/samples/system-test/requesterPays.test.js +++ b/samples/system-test/requesterPays.test.js @@ -51,12 +51,12 @@ after(async () => { it.skip('should error on requester-pays requests if they are disabled', () => { const result = execSync( - `node downloadFileUsingRequesterPays.js ${projectId} ${bucketName} ${fileName} ${downloadFilePath}` + `node downloadFileUsingRequesterPays.js ${projectId} ${bucketName} ${fileName} ${downloadFilePath}`, ); assert.ok(result.stderr); assert.match( result.stderr, - /User project prohibited for non requester pays bucket/ + /User project prohibited for non requester pays bucket/, ); }); @@ -64,7 +64,7 @@ it('should fetch requester-pays status on a default bucket', () => { const out = execSync(`node getRequesterPaysStatus.js ${bucketName}`); assert.include( out, - `Requester-pays requests are disabled for bucket ${bucketName}` + `Requester-pays requests are disabled for bucket ${bucketName}`, ); }); @@ -72,7 +72,7 @@ it('should enable requester-pays requests', () => { const out = execSync(`node enableRequesterPays.js ${bucketName}`); assert.include( out, - `Requester-pays requests have been enabled for bucket ${bucketName}` + `Requester-pays requests have been enabled for bucket ${bucketName}`, ); }); @@ -80,17 +80,17 @@ it('should fetch requester-pays status on a modified bucket', () => { const out = execSync(`node getRequesterPaysStatus.js ${bucketName}`); assert.include( out, - `Requester-pays requests are enabled for bucket ${bucketName}.` + `Requester-pays requests are enabled for bucket ${bucketName}.`, ); }); it('should download a file using requester-pays requests', () => { const out = execSync( - `node downloadFileUsingRequesterPays.js ${projectId} ${bucketName} ${fileName} ${downloadFilePath}` + `node downloadFileUsingRequesterPays.js ${projectId} ${bucketName} ${fileName} ${downloadFilePath}`, ); assert.include( out, - `gs://${bucketName}/${fileName} downloaded to ${downloadFilePath} using requester-pays requests` + `gs://${bucketName}/${fileName} downloaded to ${downloadFilePath} using requester-pays requests`, ); fs.statSync(downloadFilePath); }); @@ -99,7 +99,7 @@ it('should disable requester-pays requests', () => { const out = execSync(`node disableRequesterPays.js ${bucketName}`); assert.include( out, - `Requester-pays requests have been disabled for bucket ${bucketName}` + `Requester-pays requests have been disabled for bucket ${bucketName}`, ); }); diff --git a/samples/system-test/storage.test.js b/samples/system-test/storage.test.js index 9aacf774b..e4e074e01 100644 --- a/samples/system-test/storage.test.js +++ b/samples/system-test/storage.test.js @@ -25,6 +25,6 @@ it('should intialize storage with a custom api endpoint', async () => { const output = execSync(`node setClientEndpoint.js ${apiEndpoint}`); assert.match( output, - new RegExp(`Client initiated with endpoint: ${apiEndpoint}.`) + new RegExp(`Client initiated with endpoint: ${apiEndpoint}.`), ); }); diff --git a/samples/system-test/transfer-manager.test.js b/samples/system-test/transfer-manager.test.js index f6180bed3..56b7b9645 100644 --- a/samples/system-test/transfer-manager.test.js +++ b/samples/system-test/transfer-manager.test.js @@ -46,69 +46,69 @@ describe('transfer manager', () => { it('should upload multiple files', async () => { const output = execSync( - `node uploadManyFilesWithTransferManager.js ${bucketName} ${firstFilePath} ${secondFilePath}` + `node uploadManyFilesWithTransferManager.js ${bucketName} ${firstFilePath} ${secondFilePath}`, ); assert.match( output, new RegExp( - `${firstFilePath} uploaded to ${bucketName}.\n${secondFilePath} uploaded to ${bucketName}` - ) + `${firstFilePath} uploaded to ${bucketName}.\n${secondFilePath} uploaded to ${bucketName}`, + ), ); }); it('should download mulitple files', async () => { const output = execSync( - `node downloadManyFilesWithTransferManager.js ${bucketName} ${firstFilePath} ${secondFilePath}` + `node downloadManyFilesWithTransferManager.js ${bucketName} ${firstFilePath} ${secondFilePath}`, ); assert.match( output, new RegExp( - `gs://${bucketName}/${firstFilePath} downloaded to ${firstFilePath}.\ngs://${bucketName}/${secondFilePath} downloaded to ${secondFilePath}.` - ) + `gs://${bucketName}/${firstFilePath} downloaded to ${firstFilePath}.\ngs://${bucketName}/${secondFilePath} downloaded to ${secondFilePath}.`, + ), ); }); it('should download a file utilizing chunked download', async () => { const output = execSync( - `node downloadFileInChunksWithTransferManager.js ${bucketName} ${firstFilePath} ${downloadFilePath} ${chunkSize}` + `node downloadFileInChunksWithTransferManager.js ${bucketName} ${firstFilePath} ${downloadFilePath} ${chunkSize}`, ); assert.match( output, new RegExp( - `gs://${bucketName}/${firstFilePath} downloaded to ${downloadFilePath}.` - ) + `gs://${bucketName}/${firstFilePath} downloaded to ${downloadFilePath}.`, + ), ); }); it('should upload a file utilizing chunked upload', async () => { const output = execSync( - `node uploadFileInChunksWithTransferManager.js ${bucketName} ${firstFilePath} ${chunkSize}` + `node uploadFileInChunksWithTransferManager.js ${bucketName} ${firstFilePath} ${chunkSize}`, ); assert.match( output, - new RegExp(`${firstFilePath} uploaded to ${bucketName}.`) + new RegExp(`${firstFilePath} uploaded to ${bucketName}.`), ); }); it('should upload a directory', async () => { const output = execSync( - `node uploadDirectoryWithTransferManager.js ${bucketName} ${resourcesPath}` + `node uploadDirectoryWithTransferManager.js ${bucketName} ${resourcesPath}`, ); assert.match( output, - new RegExp(`${resourcesPath} uploaded to ${bucketName}.`) + new RegExp(`${resourcesPath} uploaded to ${bucketName}.`), ); }); it('should download a directory', async () => { const output = execSync( - `node downloadFolderWithTransferManager.js ${bucketName} ${resourcesPath}` + `node downloadFolderWithTransferManager.js ${bucketName} ${resourcesPath}`, ); assert.match( output, new RegExp( - `gs://${bucketName}/${resourcesPath} downloaded to ${resourcesPath}.` - ) + `gs://${bucketName}/${resourcesPath} downloaded to ${resourcesPath}.`, + ), ); }); }); diff --git a/samples/uploadDirectory.js b/samples/uploadDirectory.js index 62ff62279..fe6c6f925 100644 --- a/samples/uploadDirectory.js +++ b/samples/uploadDirectory.js @@ -21,7 +21,7 @@ function main( bucketName = 'your-unique-bucket-name', - directoryPath = './local/path/to/directory' + directoryPath = './local/path/to/directory', ) { // [START upload_directory] /** @@ -80,7 +80,7 @@ function main( } console.log( - `${successfulUploads} files uploaded to ${bucketName} successfully.` + `${successfulUploads} files uploaded to ${bucketName} successfully.`, ); } diff --git a/samples/uploadEncryptedFile.js b/samples/uploadEncryptedFile.js index 8dd156cc0..7221a7f03 100644 --- a/samples/uploadEncryptedFile.js +++ b/samples/uploadEncryptedFile.js @@ -18,7 +18,7 @@ function main( filePath = path.join(__dirname, '../resources', 'test.txt'), destFileName = 'test.txt', key = process.env.GOOGLE_CLOUD_KMS_KEY_US, - generationMatchPrecondition = 0 + generationMatchPrecondition = 0, ) { // [START storage_upload_encrypted_file] /** @@ -60,7 +60,7 @@ function main( await storage.bucket(bucketName).upload(filePath, options); console.log( - `File ${filePath} uploaded to gs://${bucketName}/${destFileName}` + `File ${filePath} uploaded to gs://${bucketName}/${destFileName}`, ); } diff --git a/samples/uploadFile.js b/samples/uploadFile.js index 1538e4ff1..9c4989bf7 100644 --- a/samples/uploadFile.js +++ b/samples/uploadFile.js @@ -16,7 +16,7 @@ function main( bucketName = 'my-bucket', filePath = './local/path/to/file.txt', destFileName = 'file.txt', - generationMatchPrecondition = 0 + generationMatchPrecondition = 0, ) { // [START storage_upload_file] /** diff --git a/samples/uploadFileInChunksWithTransferManager.js b/samples/uploadFileInChunksWithTransferManager.js index 02e843784..56006153d 100644 --- a/samples/uploadFileInChunksWithTransferManager.js +++ b/samples/uploadFileInChunksWithTransferManager.js @@ -23,7 +23,7 @@ function main( bucketName = 'my-bucket', filePath = './local/path/to/file.txt', - chunkSize = 32 * 1024 * 1024 + chunkSize = 32 * 1024 * 1024, ) { // [START storage_transfer_manager_upload_chunks_concurrently] /** diff --git a/samples/uploadFileWithKmsKey.js b/samples/uploadFileWithKmsKey.js index 771638abc..9350e6c12 100644 --- a/samples/uploadFileWithKmsKey.js +++ b/samples/uploadFileWithKmsKey.js @@ -24,7 +24,7 @@ function main( bucketName = 'my-bucket', filePath = 'test.txt', kmsKeyName = process.env.GOOGLE_CLOUD_KMS_KEY_US, - generationMatchPrecondition = 0 + generationMatchPrecondition = 0, ) { // [START storage_upload_with_kms_key] /** diff --git a/samples/uploadFromMemory.js b/samples/uploadFromMemory.js index cd6ec5166..a10b66bd1 100644 --- a/samples/uploadFromMemory.js +++ b/samples/uploadFromMemory.js @@ -15,7 +15,7 @@ function main( bucketName = 'my-bucket', contents = 'these are my file contents', - destFileName = 'file.txt' + destFileName = 'file.txt', ) { // [START storage_file_upload_from_memory] /** @@ -40,7 +40,7 @@ function main( await storage.bucket(bucketName).file(destFileName).save(contents); console.log( - `${destFileName} with contents ${contents} uploaded to ${bucketName}.` + `${destFileName} with contents ${contents} uploaded to ${bucketName}.`, ); } diff --git a/samples/uploadManyFilesWithTransferManager.js b/samples/uploadManyFilesWithTransferManager.js index cc0019f50..306716d2c 100644 --- a/samples/uploadManyFilesWithTransferManager.js +++ b/samples/uploadManyFilesWithTransferManager.js @@ -23,7 +23,7 @@ function main( bucketName = 'my-bucket', firstFilePath = './local/path/to/file1.txt', - secondFilePath = './local/path/to/file2.txt' + secondFilePath = './local/path/to/file2.txt', ) { // [START storage_transfer_manager_upload_many] /** diff --git a/samples/uploadWithoutAuthentication.js b/samples/uploadWithoutAuthentication.js index f51e56940..2b99ac817 100644 --- a/samples/uploadWithoutAuthentication.js +++ b/samples/uploadWithoutAuthentication.js @@ -16,7 +16,7 @@ function main( bucketName = 'my-bucket', contents = 'these are my file contents', destFileName = 'file.txt', - generationMatchPrecondition = 0 + generationMatchPrecondition = 0, ) { // [START storage_upload_without_authentication] /** diff --git a/samples/uploadWithoutAuthenticationSignedUrl.js b/samples/uploadWithoutAuthenticationSignedUrl.js index 4be8def3b..799a34f8c 100644 --- a/samples/uploadWithoutAuthenticationSignedUrl.js +++ b/samples/uploadWithoutAuthenticationSignedUrl.js @@ -15,7 +15,7 @@ function main( bucketName = 'my-bucket', contents = 'these are my file contents', - destFileName = 'file.txt' + destFileName = 'file.txt', ) { // [START storage_upload_without_authentication_signed_url] /** diff --git a/src/acl.ts b/src/acl.ts index 9776b0340..ecd02bb7a 100644 --- a/src/acl.ts +++ b/src/acl.ts @@ -23,7 +23,7 @@ export interface AclOptions { pathPrefix: string; request: ( reqOpts: DecorateRequestOptions, - callback: BodyResponseCallback + callback: BodyResponseCallback, ) => void; } @@ -35,7 +35,7 @@ export interface GetAclCallback { ( err: Error | null, acl?: AccessControlObject | AccessControlObject[] | null, - apiResponse?: AclMetadata + apiResponse?: AclMetadata, ): void; } export interface GetAclOptions { @@ -55,7 +55,7 @@ export interface UpdateAclCallback { ( err: Error | null, acl?: AccessControlObject | null, - apiResponse?: AclMetadata + apiResponse?: AclMetadata, ): void; } @@ -70,7 +70,7 @@ export interface AddAclCallback { ( err: Error | null, acl?: AccessControlObject | null, - apiResponse?: AclMetadata + apiResponse?: AclMetadata, ): void; } export type RemoveAclResponse = [AclMetadata]; @@ -331,7 +331,7 @@ class AclRoleAccessorMethods { (acc as any)[method] = ( entityId: string, options: {}, - callback: Function | {} + callback: Function | {}, ) => { let apiEntity; @@ -355,7 +355,7 @@ class AclRoleAccessorMethods { entity: apiEntity, role, }, - options + options, ); const args = [options]; @@ -420,7 +420,7 @@ class Acl extends AclRoleAccessorMethods { pathPrefix: string; request_: ( reqOpts: DecorateRequestOptions, - callback: BodyResponseCallback + callback: BodyResponseCallback, ) => void; constructor(options: AclOptions) { @@ -508,7 +508,7 @@ class Acl extends AclRoleAccessorMethods { */ add( options: AddAclOptions, - callback?: AddAclCallback + callback?: AddAclCallback, ): void | Promise { const query = {} as AclQuery; @@ -538,7 +538,7 @@ class Acl extends AclRoleAccessorMethods { } callback!(null, this.makeAclObject_(resp), resp); - } + }, ); } @@ -608,7 +608,7 @@ class Acl extends AclRoleAccessorMethods { */ delete( options: RemoveAclOptions, - callback?: RemoveAclCallback + callback?: RemoveAclCallback, ): void | Promise { const query = {} as AclQuery; @@ -628,7 +628,7 @@ class Acl extends AclRoleAccessorMethods { }, (err, resp) => { callback!(err, resp); - } + }, ); } @@ -722,7 +722,7 @@ class Acl extends AclRoleAccessorMethods { */ get( optionsOrCallback?: GetAclOptions | GetAclCallback, - cb?: GetAclCallback + cb?: GetAclCallback, ): void | Promise { const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : null; @@ -763,7 +763,7 @@ class Acl extends AclRoleAccessorMethods { } callback!(null, results, resp); - } + }, ); } @@ -830,7 +830,7 @@ class Acl extends AclRoleAccessorMethods { */ update( options: UpdateAclOptions, - callback?: UpdateAclCallback + callback?: UpdateAclCallback, ): void | Promise { const query = {} as AclQuery; @@ -858,7 +858,7 @@ class Acl extends AclRoleAccessorMethods { } callback!(null, this.makeAclObject_(resp), resp); - } + }, ); } @@ -868,7 +868,7 @@ class Acl extends AclRoleAccessorMethods { * @private */ makeAclObject_( - accessControlObject: AccessControlObject + accessControlObject: AccessControlObject, ): AccessControlObject { const obj = { entity: accessControlObject.entity, @@ -895,7 +895,7 @@ class Acl extends AclRoleAccessorMethods { */ request( reqOpts: DecorateRequestOptions, - callback: BodyResponseCallback + callback: BodyResponseCallback, ): void { reqOpts.uri = this.pathPrefix + reqOpts.uri; this.request_(reqOpts, callback); diff --git a/src/bucket.ts b/src/bucket.ts index 73df3374d..df3b8dba1 100644 --- a/src/bucket.ts +++ b/src/bucket.ts @@ -97,7 +97,7 @@ export interface GetFilesCallback { err: Error | null, files?: File[], nextQuery?: {}, - apiResponse?: unknown + apiResponse?: unknown, ): void; } @@ -217,7 +217,7 @@ export interface CreateNotificationCallback { ( err: Error | null, notification: Notification | null, - apiResponse: unknown + apiResponse: unknown, ): void; } @@ -373,7 +373,7 @@ export interface GetBucketMetadataCallback { ( err: ApiError | null, metadata: BucketMetadata | null, - apiResponse: unknown + apiResponse: unknown, ): void; } @@ -409,7 +409,7 @@ export interface GetNotificationsCallback { ( err: Error | null, notifications: Notification[] | null, - apiResponse: unknown + apiResponse: unknown, ): void; } @@ -1266,16 +1266,16 @@ class Bucket extends ServiceObject { addLifecycleRule( rule: LifecycleRule | LifecycleRule[], - options?: AddLifecycleRuleOptions + options?: AddLifecycleRuleOptions, ): Promise; addLifecycleRule( rule: LifecycleRule | LifecycleRule[], options: AddLifecycleRuleOptions, - callback: SetBucketMetadataCallback + callback: SetBucketMetadataCallback, ): void; addLifecycleRule( rule: LifecycleRule | LifecycleRule[], - callback: SetBucketMetadataCallback + callback: SetBucketMetadataCallback, ): void; /** * @typedef {object} AddLifecycleRuleOptions Configuration options for Bucket#addLifecycleRule(). @@ -1448,7 +1448,7 @@ class Bucket extends ServiceObject { addLifecycleRule( rule: LifecycleRule | LifecycleRule[], optionsOrCallback?: AddLifecycleRuleOptions | SetBucketMetadataCallback, - callback?: SetBucketMetadataCallback + callback?: SetBucketMetadataCallback, ): Promise | void { let options: AddLifecycleRuleOptions = {}; @@ -1502,7 +1502,7 @@ class Bucket extends ServiceObject { lifecycle: {rule: currentLifecycleRules!.concat(rules)}, }, options as AddLifecycleRuleOptions, - callback! + callback!, ); }); } @@ -1510,18 +1510,18 @@ class Bucket extends ServiceObject { combine( sources: string[] | File[], destination: string | File, - options?: CombineOptions + options?: CombineOptions, ): Promise; combine( sources: string[] | File[], destination: string | File, options: CombineOptions, - callback: CombineCallback + callback: CombineCallback, ): void; combine( sources: string[] | File[], destination: string | File, - callback: CombineCallback + callback: CombineCallback, ): void; /** * @typedef {object} CombineOptions @@ -1597,7 +1597,7 @@ class Bucket extends ServiceObject { sources: string[] | File[], destination: string | File, optionsOrCallback?: CombineOptions | CombineCallback, - callback?: CombineCallback + callback?: CombineCallback, ): Promise | void { if (!Array.isArray(sources) || sources.length === 0) { throw new Error(BucketExceptionMessages.PROVIDE_SOURCE_FILE); @@ -1617,7 +1617,7 @@ class Bucket extends ServiceObject { this.disableAutoRetryConditionallyIdempotent_( this.methods.setMetadata, // Not relevant but param is required AvailableServiceObjectMethods.setMetadata, // Same as above - options + options, ); const convertToFile = (file: string | File): File => { @@ -1676,7 +1676,7 @@ class Bucket extends ServiceObject { if (source.metadata && source.metadata.generation) { sourceObject.generation = parseInt( - source.metadata.generation.toString() + source.metadata.generation.toString(), ); } @@ -1693,25 +1693,25 @@ class Bucket extends ServiceObject { } callback!(null, destinationFile, resp); - } + }, ); } createChannel( id: string, config: CreateChannelConfig, - options?: CreateChannelOptions + options?: CreateChannelOptions, ): Promise; createChannel( id: string, config: CreateChannelConfig, - callback: CreateChannelCallback + callback: CreateChannelCallback, ): void; createChannel( id: string, config: CreateChannelConfig, options: CreateChannelOptions, - callback: CreateChannelCallback + callback: CreateChannelCallback, ): void; /** * See a {@link https://cloud.google.com/storage/docs/json_api/v1/objects/watchAll| Objects: watchAll request body}. @@ -1808,7 +1808,7 @@ class Bucket extends ServiceObject { id: string, config: CreateChannelConfig, optionsOrCallback?: CreateChannelOptions | CreateChannelCallback, - callback?: CreateChannelCallback + callback?: CreateChannelCallback, ): Promise | void { if (typeof id !== 'string') { throw new Error(BucketExceptionMessages.CHANNEL_ID_REQUIRED); @@ -1830,7 +1830,7 @@ class Bucket extends ServiceObject { id, type: 'web_hook', }, - config + config, ), qs: options, }, @@ -1846,18 +1846,18 @@ class Bucket extends ServiceObject { channel.metadata = apiResponse; callback!(null, channel, apiResponse); - } + }, ); } createNotification( topic: string, - options?: CreateNotificationOptions + options?: CreateNotificationOptions, ): Promise; createNotification( topic: string, options: CreateNotificationOptions, - callback: CreateNotificationCallback + callback: CreateNotificationCallback, ): void; createNotification(topic: string, callback: CreateNotificationCallback): void; /** @@ -1967,7 +1967,7 @@ class Bucket extends ServiceObject { createNotification( topic: string, optionsOrCallback?: CreateNotificationOptions | CreateNotificationCallback, - callback?: CreateNotificationCallback + callback?: CreateNotificationCallback, ): Promise | void { let options: CreateNotificationOptions = {}; if (typeof optionsOrCallback === 'function') { @@ -2024,7 +2024,7 @@ class Bucket extends ServiceObject { notification.metadata = apiResponse; callback!(null, notification, apiResponse); - } + }, ); } @@ -2113,7 +2113,7 @@ class Bucket extends ServiceObject { */ deleteFiles( queryOrCallback?: DeleteFilesOptions | DeleteFilesCallback, - callback?: DeleteFilesCallback + callback?: DeleteFilesCallback, ): Promise | void { let query: DeleteFilesOptions = {}; if (typeof queryOrCallback === 'function') { @@ -2150,7 +2150,7 @@ class Bucket extends ServiceObject { limit(() => deleteFile(curFile)).catch(e => { filesStream.destroy(); throw e; - }) + }), ); } @@ -2168,13 +2168,13 @@ class Bucket extends ServiceObject { deleteLabels(callback: DeleteLabelsCallback): void; deleteLabels( labels: string | string[], - options: DeleteLabelsOptions + options: DeleteLabelsOptions, ): Promise; deleteLabels(labels: string | string[], callback: DeleteLabelsCallback): void; deleteLabels( labels: string | string[], options: DeleteLabelsOptions, - callback: DeleteLabelsCallback + callback: DeleteLabelsCallback, ): void; /** * @deprecated @@ -2236,7 +2236,7 @@ class Bucket extends ServiceObject { | DeleteLabelsCallback | DeleteLabelsOptions, optionsOrCallback?: DeleteLabelsCallback | DeleteLabelsOptions, - callback?: DeleteLabelsCallback + callback?: DeleteLabelsCallback, ): Promise | void { let labels = new Array(); let options: DeleteLabelsOptions = {}; @@ -2284,12 +2284,12 @@ class Bucket extends ServiceObject { } disableRequesterPays( - options?: DisableRequesterPaysOptions + options?: DisableRequesterPaysOptions, ): Promise; disableRequesterPays(callback: DisableRequesterPaysCallback): void; disableRequesterPays( options: DisableRequesterPaysOptions, - callback: DisableRequesterPaysCallback + callback: DisableRequesterPaysCallback, ): void; /** * @typedef {array} DisableRequesterPaysResponse @@ -2342,7 +2342,7 @@ class Bucket extends ServiceObject { optionsOrCallback?: | DisableRequesterPaysOptions | DisableRequesterPaysCallback, - callback?: DisableRequesterPaysCallback + callback?: DisableRequesterPaysCallback, ): Promise | void { let options: DisableRequesterPaysOptions = {}; if (typeof optionsOrCallback === 'function') { @@ -2358,16 +2358,16 @@ class Bucket extends ServiceObject { }, }, options, - callback! + callback!, ); } enableLogging( - config: EnableLoggingOptions + config: EnableLoggingOptions, ): Promise; enableLogging( config: EnableLoggingOptions, - callback: SetBucketMetadataCallback + callback: SetBucketMetadataCallback, ): void; /** * Configuration object for enabling logging. @@ -2427,7 +2427,7 @@ class Bucket extends ServiceObject { */ enableLogging( config: EnableLoggingOptions, - callback?: SetBucketMetadataCallback + callback?: SetBucketMetadataCallback, ): Promise | void { if ( !config || @@ -2435,7 +2435,7 @@ class Bucket extends ServiceObject { typeof config.prefix === 'undefined' ) { throw new Error( - BucketExceptionMessages.CONFIGURATION_OBJECT_PREFIX_REQUIRED + BucketExceptionMessages.CONFIGURATION_OBJECT_PREFIX_REQUIRED, ); } @@ -2469,7 +2469,7 @@ class Bucket extends ServiceObject { }, }, options, - callback! + callback!, ); } catch (e) { callback!(e as Error); @@ -2479,12 +2479,12 @@ class Bucket extends ServiceObject { } enableRequesterPays( - options?: EnableRequesterPaysOptions + options?: EnableRequesterPaysOptions, ): Promise; enableRequesterPays(callback: EnableRequesterPaysCallback): void; enableRequesterPays( options: EnableRequesterPaysOptions, - callback: EnableRequesterPaysCallback + callback: EnableRequesterPaysCallback, ): void; /** @@ -2540,7 +2540,7 @@ class Bucket extends ServiceObject { optionsOrCallback?: | EnableRequesterPaysCallback | EnableRequesterPaysOptions, - cb?: EnableRequesterPaysCallback + cb?: EnableRequesterPaysCallback, ): Promise | void { let options: EnableRequesterPaysOptions = {}; if (typeof optionsOrCallback === 'function') { @@ -2556,7 +2556,7 @@ class Bucket extends ServiceObject { }, }, options, - cb! + cb!, ); } @@ -2802,7 +2802,7 @@ class Bucket extends ServiceObject { */ getFiles( queryOrCallback?: GetFilesOptions | GetFilesCallback, - callback?: GetFilesCallback + callback?: GetFilesCallback, ): void | Promise { let query = typeof queryOrCallback === 'object' ? queryOrCallback : {}; if (!callback) { @@ -2853,7 +2853,7 @@ class Bucket extends ServiceObject { } // eslint-disable-next-line @typescript-eslint/no-explicit-any (callback as any)(null, files, nextQuery, resp); - } + }, ); } @@ -2914,7 +2914,7 @@ class Bucket extends ServiceObject { */ getLabels( optionsOrCallback?: GetLabelsOptions | GetLabelsCallback, - callback?: GetLabelsCallback + callback?: GetLabelsCallback, ): Promise | void { let options: GetLabelsOptions = {}; if (typeof optionsOrCallback === 'function') { @@ -2932,17 +2932,17 @@ class Bucket extends ServiceObject { } callback!(null, metadata?.labels || {}); - } + }, ); } getNotifications( - options?: GetNotificationsOptions + options?: GetNotificationsOptions, ): Promise; getNotifications(callback: GetNotificationsCallback): void; getNotifications( options: GetNotificationsOptions, - callback: GetNotificationsCallback + callback: GetNotificationsCallback, ): void; /** * @typedef {object} GetNotificationsOptions Configuration options for Bucket#getNotification(). @@ -2999,7 +2999,7 @@ class Bucket extends ServiceObject { */ getNotifications( optionsOrCallback?: GetNotificationsOptions | GetNotificationsCallback, - callback?: GetNotificationsCallback + callback?: GetNotificationsCallback, ): Promise | void { let options: GetNotificationsOptions = {}; if (typeof optionsOrCallback === 'function') { @@ -3024,18 +3024,18 @@ class Bucket extends ServiceObject { const notificationInstance = this.notification(notification.id!); notificationInstance.metadata = notification; return notificationInstance; - } + }, ); callback!(null, notifications, resp); - } + }, ); } getSignedUrl(cfg: GetBucketSignedUrlConfig): Promise; getSignedUrl( cfg: GetBucketSignedUrlConfig, - callback: GetSignedUrlCallback + callback: GetSignedUrlCallback, ): void; /** * @typedef {array} GetSignedUrlResponse @@ -3165,7 +3165,7 @@ class Bucket extends ServiceObject { */ getSignedUrl( cfg: GetBucketSignedUrlConfig, - callback?: GetSignedUrlCallback + callback?: GetSignedUrlCallback, ): void | Promise { const method = BucketActionToHTTPMethod[cfg.action]; @@ -3185,7 +3185,7 @@ class Bucket extends ServiceObject { this.storage.authClient, this, undefined, - this.storage + this.storage, ); } @@ -3231,7 +3231,7 @@ class Bucket extends ServiceObject { */ lock( metageneration: number | string, - callback?: BucketLockCallback + callback?: BucketLockCallback, ): Promise | void { const metatype = typeof metageneration; if (metatype !== 'number' && metatype !== 'string') { @@ -3246,17 +3246,17 @@ class Bucket extends ServiceObject { ifMetagenerationMatch: metageneration, }, }, - callback! + callback!, ); } makePrivate( - options?: MakeBucketPrivateOptions + options?: MakeBucketPrivateOptions, ): Promise; makePrivate(callback: MakeBucketPrivateCallback): void; makePrivate( options: MakeBucketPrivateOptions, - callback: MakeBucketPrivateCallback + callback: MakeBucketPrivateCallback, ): void; /** * @typedef {array} MakeBucketPrivateResponse @@ -3361,7 +3361,7 @@ class Bucket extends ServiceObject { */ makePrivate( optionsOrCallback?: MakeBucketPrivateOptions | MakeBucketPrivateCallback, - callback?: MakeBucketPrivateCallback + callback?: MakeBucketPrivateCallback, ): Promise | void { const options: MakeBucketPrivateRequest = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; @@ -3408,7 +3408,7 @@ class Bucket extends ServiceObject { const internalCall = () => { if (options.includeFiles) { return promisify( - this.makeAllFilesPublicPrivate_ + this.makeAllFilesPublicPrivate_, ).call(this, options); } return Promise.resolve([] as File[]); @@ -3420,12 +3420,12 @@ class Bucket extends ServiceObject { } makePublic( - options?: MakeBucketPublicOptions + options?: MakeBucketPublicOptions, ): Promise; makePublic(callback: MakeBucketPublicCallback): void; makePublic( options: MakeBucketPublicOptions, - callback: MakeBucketPublicCallback + callback: MakeBucketPublicCallback, ): void; /** * @typedef {object} MakeBucketPublicOptions @@ -3522,7 +3522,7 @@ class Bucket extends ServiceObject { */ makePublic( optionsOrCallback?: MakeBucketPublicOptions | MakeBucketPublicCallback, - callback?: MakeBucketPublicCallback + callback?: MakeBucketPublicCallback, ): Promise | void { const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; @@ -3545,7 +3545,7 @@ class Bucket extends ServiceObject { .then(() => { if (req.includeFiles) { return promisify( - this.makeAllFilesPublicPrivate_ + this.makeAllFilesPublicPrivate_, ).call(this, req); } return []; @@ -3577,12 +3577,12 @@ class Bucket extends ServiceObject { } removeRetentionPeriod( - options?: SetBucketMetadataOptions + options?: SetBucketMetadataOptions, ): Promise; removeRetentionPeriod(callback: SetBucketMetadataCallback): void; removeRetentionPeriod( options: SetBucketMetadataOptions, - callback: SetBucketMetadataCallback + callback: SetBucketMetadataCallback, ): void; /** * Remove an already-existing retention policy from this bucket, if it is not @@ -3609,7 +3609,7 @@ class Bucket extends ServiceObject { */ removeRetentionPeriod( optionsOrCallback?: SetBucketMetadataOptions | SetBucketMetadataCallback, - callback?: SetBucketMetadataCallback + callback?: SetBucketMetadataCallback, ): Promise | void { const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; @@ -3621,14 +3621,14 @@ class Bucket extends ServiceObject { retentionPolicy: null, }, options, - callback! + callback!, ); } request(reqOpts: DecorateRequestOptions): Promise; request( reqOpts: DecorateRequestOptions, - callback: BodyResponseCallback + callback: BodyResponseCallback, ): void; /** * Makes request and applies userProject query parameter if necessary. @@ -3640,7 +3640,7 @@ class Bucket extends ServiceObject { */ request( reqOpts: DecorateRequestOptions, - callback?: BodyResponseCallback + callback?: BodyResponseCallback, ): void | Promise { if (this.userProject && (!reqOpts.qs || !reqOpts.qs.userProject)) { reqOpts.qs = {...reqOpts.qs, userProject: this.userProject}; @@ -3650,13 +3650,13 @@ class Bucket extends ServiceObject { setLabels( labels: Labels, - options?: SetLabelsOptions + options?: SetLabelsOptions, ): Promise; setLabels(labels: Labels, callback: SetLabelsCallback): void; setLabels( labels: Labels, options: SetLabelsOptions, - callback: SetLabelsCallback + callback: SetLabelsCallback, ): void; /** * @deprecated @@ -3718,7 +3718,7 @@ class Bucket extends ServiceObject { setLabels( labels: Labels, optionsOrCallback?: SetLabelsOptions | SetLabelsCallback, - callback?: SetLabelsCallback + callback?: SetLabelsCallback, ): Promise | void { const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; @@ -3732,21 +3732,21 @@ class Bucket extends ServiceObject { setMetadata( metadata: BucketMetadata, - options?: SetMetadataOptions + options?: SetMetadataOptions, ): Promise>; setMetadata( metadata: BucketMetadata, - callback: MetadataCallback + callback: MetadataCallback, ): void; setMetadata( metadata: BucketMetadata, options: SetMetadataOptions, - callback: MetadataCallback + callback: MetadataCallback, ): void; setMetadata( metadata: BucketMetadata, optionsOrCallback: SetMetadataOptions | MetadataCallback, - cb?: MetadataCallback + cb?: MetadataCallback, ): Promise> | void { const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; @@ -3758,7 +3758,7 @@ class Bucket extends ServiceObject { this.disableAutoRetryConditionallyIdempotent_( this.methods.setMetadata, AvailableServiceObjectMethods.setMetadata, - options + options, ); super @@ -3772,16 +3772,16 @@ class Bucket extends ServiceObject { setRetentionPeriod( duration: number, - options?: SetBucketMetadataOptions + options?: SetBucketMetadataOptions, ): Promise; setRetentionPeriod( duration: number, - callback: SetBucketMetadataCallback + callback: SetBucketMetadataCallback, ): void; setRetentionPeriod( duration: number, options: SetBucketMetadataOptions, - callback: SetBucketMetadataCallback + callback: SetBucketMetadataCallback, ): void; /** * Lock all objects contained in the bucket, based on their creation time. Any @@ -3824,7 +3824,7 @@ class Bucket extends ServiceObject { setRetentionPeriod( duration: number, optionsOrCallback?: SetBucketMetadataOptions | SetBucketMetadataCallback, - callback?: SetBucketMetadataCallback + callback?: SetBucketMetadataCallback, ): Promise | void { const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; @@ -3837,22 +3837,22 @@ class Bucket extends ServiceObject { }, }, options, - callback! + callback!, ); } setCorsConfiguration( corsConfiguration: Cors[], - options?: SetBucketMetadataOptions + options?: SetBucketMetadataOptions, ): Promise; setCorsConfiguration( corsConfiguration: Cors[], - callback: SetBucketMetadataCallback + callback: SetBucketMetadataCallback, ): void; setCorsConfiguration( corsConfiguration: Cors[], options: SetBucketMetadataOptions, - callback: SetBucketMetadataCallback + callback: SetBucketMetadataCallback, ): void; /** * @@ -3903,7 +3903,7 @@ class Bucket extends ServiceObject { setCorsConfiguration( corsConfiguration: Cors[], optionsOrCallback?: SetBucketMetadataOptions | SetBucketMetadataCallback, - callback?: SetBucketMetadataCallback + callback?: SetBucketMetadataCallback, ): Promise | void { const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; @@ -3914,22 +3914,22 @@ class Bucket extends ServiceObject { cors: corsConfiguration, }, options, - callback! + callback!, ); } setStorageClass( storageClass: string, - options?: SetBucketStorageClassOptions + options?: SetBucketStorageClassOptions, ): Promise; setStorageClass( storageClass: string, - callback: SetBucketStorageClassCallback + callback: SetBucketStorageClassCallback, ): void; setStorageClass( storageClass: string, options: SetBucketStorageClassOptions, - callback: SetBucketStorageClassCallback + callback: SetBucketStorageClassCallback, ): void; /** * @typedef {object} SetBucketStorageClassOptions @@ -3981,7 +3981,7 @@ class Bucket extends ServiceObject { optionsOrCallback?: | SetBucketStorageClassOptions | SetBucketStorageClassCallback, - callback?: SetBucketStorageClassCallback + callback?: SetBucketStorageClassCallback, ): Promise | void { const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; @@ -4043,7 +4043,7 @@ class Bucket extends ServiceObject { upload( pathString: string, options: UploadOptions, - callback: UploadCallback + callback: UploadCallback, ): void; upload(pathString: string, callback: UploadCallback): void; /** @@ -4303,7 +4303,7 @@ class Bucket extends ServiceObject { upload( pathString: string, optionsOrCallback?: UploadOptions | UploadCallback, - callback?: UploadCallback + callback?: UploadCallback, ): Promise | void { const upload = (numberOfRetries: number | undefined) => { const returnValue = AsyncRetry( @@ -4342,7 +4342,7 @@ class Bucket extends ServiceObject { factor: this.storage.retryOptions.retryDelayMultiplier, maxTimeout: this.storage.retryOptions.maxRetryDelay! * 1000, //convert to milliseconds maxRetryTime: this.storage.retryOptions.totalTimeout! * 1000, //convert to milliseconds - } + }, ); if (!callback) { @@ -4372,7 +4372,7 @@ class Bucket extends ServiceObject { { metadata: {}, }, - options + options, ); // Do not retry if precondition option ifGenerationMatch is not set @@ -4416,12 +4416,12 @@ class Bucket extends ServiceObject { } makeAllFilesPublicPrivate_( - options?: MakeAllFilesPublicPrivateOptions + options?: MakeAllFilesPublicPrivateOptions, ): Promise; makeAllFilesPublicPrivate_(callback: MakeAllFilesPublicPrivateCallback): void; makeAllFilesPublicPrivate_( options: MakeAllFilesPublicPrivateOptions, - callback: MakeAllFilesPublicPrivateCallback + callback: MakeAllFilesPublicPrivateCallback, ): void; /** * @private @@ -4471,7 +4471,7 @@ class Bucket extends ServiceObject { optionsOrCallback?: | MakeAllFilesPublicPrivateOptions | MakeAllFilesPublicPrivateCallback, - callback?: MakeAllFilesPublicPrivateCallback + callback?: MakeAllFilesPublicPrivateCallback, ): Promise | void { const MAX_PARALLEL_LIMIT = 10; const errors = [] as Error[]; @@ -4504,7 +4504,7 @@ class Bucket extends ServiceObject { }) .then( () => callback!(errors.length > 0 ? errors : null, updatedFiles), - err => callback!(err, updatedFiles) + err => callback!(err, updatedFiles), ); } @@ -4517,7 +4517,7 @@ class Bucket extends ServiceObject { coreOpts: any, // eslint-disable-next-line @typescript-eslint/no-explicit-any methodType: AvailableServiceObjectMethods, - localPreconditionOptions?: PreconditionOptions + localPreconditionOptions?: PreconditionOptions, ): void { if ( typeof coreOpts === 'object' && diff --git a/src/channel.ts b/src/channel.ts index ee0c10984..eccb27071 100644 --- a/src/channel.ts +++ b/src/channel.ts @@ -106,7 +106,7 @@ class Channel extends ServiceObject { }, (err, apiResponse) => { callback!(err, apiResponse); - } + }, ); } } diff --git a/src/crc32c.ts b/src/crc32c.ts index 4d11d26f5..c8c0e10f7 100644 --- a/src/crc32c.ts +++ b/src/crc32c.ts @@ -231,7 +231,7 @@ class CRC32C implements CRC32CValidator { * @param value 4-byte `ArrayBufferView`/`Buffer`/`TypedArray` */ private static fromBuffer( - value: ArrayBuffer | ArrayBufferView | Buffer + value: ArrayBuffer | ArrayBufferView | Buffer, ): CRC32C { let buffer: Buffer; @@ -247,7 +247,7 @@ class CRC32C implements CRC32CValidator { if (buffer.byteLength !== 4) { throw new RangeError( - CRC32C_EXCEPTION_MESSAGES.INVALID_INIT_BUFFER_LENGTH(buffer.byteLength) + CRC32C_EXCEPTION_MESSAGES.INVALID_INIT_BUFFER_LENGTH(buffer.byteLength), ); } @@ -277,7 +277,7 @@ class CRC32C implements CRC32CValidator { if (buffer.byteLength !== 4) { throw new RangeError( - CRC32C_EXCEPTION_MESSAGES.INVALID_INIT_BASE64_RANGE(buffer.byteLength) + CRC32C_EXCEPTION_MESSAGES.INVALID_INIT_BASE64_RANGE(buffer.byteLength), ); } @@ -292,7 +292,7 @@ class CRC32C implements CRC32CValidator { private static fromNumber(value: number): CRC32C { if (!Number.isSafeInteger(value) || value > 2 ** 32 || value < -(2 ** 32)) { throw new RangeError( - CRC32C_EXCEPTION_MESSAGES.INVALID_INIT_INTEGER(value) + CRC32C_EXCEPTION_MESSAGES.INVALID_INIT_INTEGER(value), ); } @@ -306,7 +306,7 @@ class CRC32C implements CRC32CValidator { * @param value A number, 4-byte `ArrayBufferView`/`Buffer`/`TypedArray`, or 4-byte base64-encoded data (string) */ static from( - value: ArrayBuffer | ArrayBufferView | CRC32CValidator | string | number + value: ArrayBuffer | ArrayBufferView | CRC32CValidator | string | number, ): CRC32C { if (typeof value === 'number') { return this.fromNumber(value); diff --git a/src/file.ts b/src/file.ts index 6d0bf9ac5..6fdfe2059 100644 --- a/src/file.ts +++ b/src/file.ts @@ -83,7 +83,7 @@ export interface GetExpirationDateCallback { ( err: Error | null, expirationDate?: Date | null, - apiResponse?: unknown + apiResponse?: unknown, ): void; } @@ -288,7 +288,7 @@ export interface MoveCallback { ( err: Error | null, destinationFile?: File | null, - apiResponse?: unknown + apiResponse?: unknown, ): void; } @@ -348,7 +348,7 @@ const COMPRESSIBLE_MIME_REGEX = new RegExp( ] .map(r => r.source) .join(''), - 'i' + 'i', ); export interface FileOptions { @@ -386,7 +386,7 @@ export type DownloadResponse = [Buffer]; export type DownloadCallback = ( err: RequestError | null, - contents: Buffer + contents: Buffer, ) => void; export interface DownloadOptions extends CreateReadStreamOptions { @@ -1105,7 +1105,7 @@ class File extends ServiceObject { * - if `idempotencyStrategy` is set to `RetryNever` */ private shouldRetryBasedOnPreconditionAndIdempotencyStrat( - options?: PreconditionOptions + options?: PreconditionOptions, ): boolean { return !( (options?.ifGenerationMatch === undefined && @@ -1119,13 +1119,13 @@ class File extends ServiceObject { copy( destination: string | Bucket | File, - options?: CopyOptions + options?: CopyOptions, ): Promise; copy(destination: string | Bucket | File, callback: CopyCallback): void; copy( destination: string | Bucket | File, options: CopyOptions, - callback: CopyCallback + callback: CopyCallback, ): void; /** * @typedef {array} CopyResponse @@ -1262,10 +1262,10 @@ class File extends ServiceObject { copy( destination: string | Bucket | File, optionsOrCallback?: CopyOptions | CopyCallback, - callback?: CopyCallback + callback?: CopyCallback, ): Promise | void { const noDestinationError = new Error( - FileExceptionMessages.DESTINATION_NO_NAME + FileExceptionMessages.DESTINATION_NO_NAME, ); if (!destination) { @@ -1345,7 +1345,7 @@ class File extends ServiceObject { this.kmsKeyName = query.destinationKmsKeyName; const keyIndex = this.interceptors.indexOf( - this.encryptionKeyInterceptor! + this.encryptionKeyInterceptor!, ); if (keyIndex > -1) { this.interceptors.splice(keyIndex, 1); @@ -1354,7 +1354,7 @@ class File extends ServiceObject { if ( !this.shouldRetryBasedOnPreconditionAndIdempotencyStrat( - options?.preconditionOpts + options?.preconditionOpts, ) ) { this.storage.retryOptions.autoRetry = false; @@ -1369,7 +1369,7 @@ class File extends ServiceObject { { method: 'POST', uri: `/rewriteTo/b/${destBucket.name}/o/${encodeURIComponent( - newFile.name + newFile.name, )}`, qs: query, json: options, @@ -1400,7 +1400,7 @@ class File extends ServiceObject { } callback!(null, newFile, resp); - } + }, ); } @@ -1555,7 +1555,7 @@ class File extends ServiceObject { const onResponse = ( err: Error | null, _body: ResponseBody, - rawResponseStream: unknown + rawResponseStream: unknown, ) => { if (err) { // Get error message from the body. @@ -1607,7 +1607,7 @@ class File extends ServiceObject { if (md5 && !hashes.md5) { const hashError = new RequestError( - FileExceptionMessages.MD5_NOT_AVAILABLE + FileExceptionMessages.MD5_NOT_AVAILABLE, ); hashError.code = 'MD5_NOT_AVAILABLE'; throughStream.destroy(hashError); @@ -1626,7 +1626,7 @@ class File extends ServiceObject { rawResponseStream as Readable, ...(transformStreams as [Transform]), throughStream, - onComplete + onComplete, ); }; @@ -1685,11 +1685,11 @@ class File extends ServiceObject { } createResumableUpload( - options?: CreateResumableUploadOptions + options?: CreateResumableUploadOptions, ): Promise; createResumableUpload( options: CreateResumableUploadOptions, - callback: CreateResumableUploadCallback + callback: CreateResumableUploadCallback, ): void; createResumableUpload(callback: CreateResumableUploadCallback): void; /** @@ -1780,7 +1780,7 @@ class File extends ServiceObject { optionsOrCallback?: | CreateResumableUploadOptions | CreateResumableUploadCallback, - callback?: CreateResumableUploadCallback + callback?: CreateResumableUploadCallback, ): void | Promise { const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; @@ -1806,7 +1806,7 @@ class File extends ServiceObject { bucket: this.bucket.name, customRequestOptions: this.getRequestInterceptors().reduce( (reqOpts, interceptorFn) => interceptorFn(reqOpts), - {} + {}, ), file: this.name, generation: this.generation, @@ -1824,7 +1824,7 @@ class File extends ServiceObject { universeDomain: this.bucket.storage.universeDomain, [GCCL_GCS_CMD_KEY]: options[GCCL_GCS_CMD_KEY], }, - callback! + callback!, ); this.storage.retryOptions.autoRetry = this.instanceRetryValue; } @@ -2039,7 +2039,7 @@ class File extends ServiceObject { if (crc32c && !options.isPartialUpload && !options.resumeCRC32C) { throw new RangeError( - FileExceptionMessages.MISSING_RESUME_CRC32C_FINAL_UPLOAD + FileExceptionMessages.MISSING_RESUME_CRC32C_FINAL_UPLOAD, ); } } @@ -2169,7 +2169,7 @@ class File extends ServiceObject { } catch (e) { pipelineCallback(e as Error); } - } + }, ); }); @@ -2188,7 +2188,7 @@ class File extends ServiceObject { delete(callback: DeleteCallback): void; delete( optionsOrCallback?: DeleteOptions | DeleteCallback, - cb?: DeleteCallback + cb?: DeleteCallback, ): Promise<[r.Response]> | void { const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; @@ -2197,7 +2197,7 @@ class File extends ServiceObject { this.disableAutoRetryConditionallyIdempotent_( this.methods.delete, AvailableServiceObjectMethods.delete, - options + options, ); super @@ -2278,7 +2278,7 @@ class File extends ServiceObject { */ download( optionsOrCallback?: DownloadOptions | DownloadCallback, - cb?: DownloadCallback + cb?: DownloadCallback, ): Promise | void { let options: DownloadOptions; if (typeof optionsOrCallback === 'function') { @@ -2381,7 +2381,7 @@ class File extends ServiceObject { setEncryptionKey(encryptionKey: string | Buffer) { this.encryptionKey = encryptionKey; this.encryptionKeyBase64 = Buffer.from(encryptionKey as string).toString( - 'base64' + 'base64', ); this.encryptionKeyHash = crypto .createHash('sha256') @@ -2416,7 +2416,7 @@ class File extends ServiceObject { static from( publicUrlOrGsUrl: string, storageInstance: Storage, - options?: FileOptions + options?: FileOptions, ): File { const gsMatches = [...publicUrlOrGsUrl.matchAll(GS_UTIL_URL_REGEX)]; const httpsMatches = [...publicUrlOrGsUrl.matchAll(HTTPS_PUBLIC_URL_REGEX)]; @@ -2429,7 +2429,7 @@ class File extends ServiceObject { return new File(bucket, httpsMatches[0][4], options); } else { throw new Error( - 'URL string must be of format gs://bucket/file or https://storage.googleapis.com/bucket/file' + 'URL string must be of format gs://bucket/file or https://storage.googleapis.com/bucket/file', ); } } @@ -2439,7 +2439,7 @@ class File extends ServiceObject { get(options: GetFileOptions, callback: InstanceResponseCallback): void; get( optionsOrCallback?: GetFileOptions | InstanceResponseCallback, - cb?: InstanceResponseCallback + cb?: InstanceResponseCallback, ): Promise> | void { // eslint-disable-next-line @typescript-eslint/no-explicit-any const options: any = @@ -2488,7 +2488,7 @@ class File extends ServiceObject { * ``` */ getExpirationDate( - callback?: GetExpirationDateCallback + callback?: GetExpirationDateCallback, ): void | Promise { this.getMetadata( (err: ApiError | null, metadata: FileMetadata, apiResponse: unknown) => { @@ -2506,21 +2506,21 @@ class File extends ServiceObject { callback!( null, new Date(metadata.retentionExpirationTime), - apiResponse + apiResponse, ); - } + }, ); } generateSignedPostPolicyV2( - options: GenerateSignedPostPolicyV2Options + options: GenerateSignedPostPolicyV2Options, ): Promise; generateSignedPostPolicyV2( options: GenerateSignedPostPolicyV2Options, - callback: GenerateSignedPostPolicyV2Callback + callback: GenerateSignedPostPolicyV2Callback, ): void; generateSignedPostPolicyV2( - callback: GenerateSignedPostPolicyV2Callback + callback: GenerateSignedPostPolicyV2Callback, ): void; /** * @typedef {array} GenerateSignedPostPolicyV2Response @@ -2615,16 +2615,16 @@ class File extends ServiceObject { optionsOrCallback?: | GenerateSignedPostPolicyV2Options | GenerateSignedPostPolicyV2Callback, - cb?: GenerateSignedPostPolicyV2Callback + cb?: GenerateSignedPostPolicyV2Callback, ): void | Promise { const args = normalize( optionsOrCallback, - cb + cb, ); let options = args.options; const callback = args.callback; const expires = new Date( - (options as GenerateSignedPostPolicyV2Options).expires + (options as GenerateSignedPostPolicyV2Options).expires, ); if (isNaN(expires.getTime())) { @@ -2713,19 +2713,19 @@ class File extends ServiceObject { }, err => { callback(new SigningError(err.message)); - } + }, ); } generateSignedPostPolicyV4( - options: GenerateSignedPostPolicyV4Options + options: GenerateSignedPostPolicyV4Options, ): Promise; generateSignedPostPolicyV4( options: GenerateSignedPostPolicyV4Options, - callback: GenerateSignedPostPolicyV4Callback + callback: GenerateSignedPostPolicyV4Callback, ): void; generateSignedPostPolicyV4( - callback: GenerateSignedPostPolicyV4Callback + callback: GenerateSignedPostPolicyV4Callback, ): void; /** * @typedef {object} SignedPostPolicyV4Output @@ -2819,7 +2819,7 @@ class File extends ServiceObject { optionsOrCallback?: | GenerateSignedPostPolicyV4Options | GenerateSignedPostPolicyV4Callback, - cb?: GenerateSignedPostPolicyV4Callback + cb?: GenerateSignedPostPolicyV4Callback, ): void | Promise { const args = normalize< GenerateSignedPostPolicyV4Options, @@ -2828,7 +2828,7 @@ class File extends ServiceObject { let options = args.options; const callback = args.callback; const expires = new Date( - (options as GenerateSignedPostPolicyV4Options).expires + (options as GenerateSignedPostPolicyV4Options).expires, ); if (isNaN(expires.getTime())) { @@ -2841,7 +2841,7 @@ class File extends ServiceObject { if (expires.valueOf() - Date.now() > SEVEN_DAYS * 1000) { throw new Error( - `Max allowed expiration is seven days (${SEVEN_DAYS} seconds).` + `Max allowed expiration is seven days (${SEVEN_DAYS} seconds).`, ); } @@ -2888,7 +2888,7 @@ class File extends ServiceObject { try { const signature = await this.storage.authClient.sign( policyBase64, - options.signingEndpoint + options.signingEndpoint, ); const signatureHex = Buffer.from(signature, 'base64').toString('hex'); const universe = this.parent.storage.universeDomain; @@ -3096,7 +3096,7 @@ class File extends ServiceObject { */ getSignedUrl( cfg: GetSignedUrlConfig, - callback?: GetSignedUrlCallback + callback?: GetSignedUrlCallback, ): void | Promise { const method = ActionToHTTPMethod[cfg.action]; const extensionHeaders = objectKeyToLowercase(cfg.extensionHeaders || {}); @@ -3147,7 +3147,7 @@ class File extends ServiceObject { this.storage.authClient, this.bucket, this, - this.storage + this.storage, ); } @@ -3245,17 +3245,17 @@ class File extends ServiceObject { } else { callback!(null, true); } - } + }, ); } makePrivate( - options?: MakeFilePrivateOptions + options?: MakeFilePrivateOptions, ): Promise; makePrivate(callback: MakeFilePrivateCallback): void; makePrivate( options: MakeFilePrivateOptions, - callback: MakeFilePrivateCallback + callback: MakeFilePrivateCallback, ): void; /** * @typedef {object} MakeFilePrivateOptions Configuration options for File#makePrivate(). @@ -3313,7 +3313,7 @@ class File extends ServiceObject { */ makePrivate( optionsOrCallback?: MakeFilePrivateOptions | MakeFilePrivateCallback, - callback?: MakeFilePrivateCallback + callback?: MakeFilePrivateCallback, ): Promise | void { const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; @@ -3385,7 +3385,7 @@ class File extends ServiceObject { * Another example: */ makePublic( - callback?: MakeFilePublicCallback + callback?: MakeFilePublicCallback, ): Promise | void { callback = callback || util.noop; this.acl.add( @@ -3395,7 +3395,7 @@ class File extends ServiceObject { }, (err, acl, resp) => { callback!(err, resp); - } + }, ); } @@ -3424,13 +3424,13 @@ class File extends ServiceObject { move( destination: string | Bucket | File, - options?: MoveOptions + options?: MoveOptions, ): Promise; move(destination: string | Bucket | File, callback: MoveCallback): void; move( destination: string | Bucket | File, options: MoveOptions, - callback: MoveCallback + callback: MoveCallback, ): void; /** * @typedef {array} MoveResponse @@ -3565,7 +3565,7 @@ class File extends ServiceObject { move( destination: string | Bucket | File, optionsOrCallback?: MoveOptions | MoveCallback, - callback?: MoveCallback + callback?: MoveCallback, ): Promise | void { const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; @@ -3601,13 +3601,13 @@ class File extends ServiceObject { rename( destinationFile: string | File, - options?: RenameOptions + options?: RenameOptions, ): Promise; rename(destinationFile: string | File, callback: RenameCallback): void; rename( destinationFile: string | File, options: RenameOptions, - callback: RenameCallback + callback: RenameCallback, ): void; /** * @typedef {array} RenameResponse @@ -3696,7 +3696,7 @@ class File extends ServiceObject { rename( destinationFile: string | File, optionsOrCallback?: RenameOptions | RenameCallback, - callback?: RenameCallback + callback?: RenameCallback, ): Promise | void { const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; @@ -3746,7 +3746,7 @@ class File extends ServiceObject { request(reqOpts: DecorateRequestOptions): Promise; request( reqOpts: DecorateRequestOptions, - callback: BodyResponseCallback + callback: BodyResponseCallback, ): void; /** * Makes request and applies userProject query parameter if necessary. @@ -3758,18 +3758,18 @@ class File extends ServiceObject { */ request( reqOpts: DecorateRequestOptions, - callback?: BodyResponseCallback + callback?: BodyResponseCallback, ): void | Promise { return this.parent.request.call(this, reqOpts, callback!); } rotateEncryptionKey( - options?: RotateEncryptionKeyOptions + options?: RotateEncryptionKeyOptions, ): Promise; rotateEncryptionKey(callback: RotateEncryptionKeyCallback): void; rotateEncryptionKey( options: RotateEncryptionKeyOptions, - callback: RotateEncryptionKeyCallback + callback: RotateEncryptionKeyCallback, ): void; /** * @callback RotateEncryptionKeyCallback @@ -3807,7 +3807,7 @@ class File extends ServiceObject { optionsOrCallback?: | RotateEncryptionKeyOptions | RotateEncryptionKeyCallback, - callback?: RotateEncryptionKeyCallback + callback?: RotateEncryptionKeyCallback, ): Promise | void { callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; @@ -3890,7 +3890,7 @@ class File extends ServiceObject { save( data: SaveData, optionsOrCallback?: SaveOptions | SaveCallback, - callback?: SaveCallback + callback?: SaveCallback, ): Promise | void { // tslint:enable:no-any callback = @@ -3901,7 +3901,7 @@ class File extends ServiceObject { let maxRetries = this.storage.retryOptions.maxRetries; if ( !this.shouldRetryBasedOnPreconditionAndIdempotencyStrat( - options?.preconditionOpts + options?.preconditionOpts, ) ) { maxRetries = 0; @@ -3960,7 +3960,7 @@ class File extends ServiceObject { factor: this.storage.retryOptions.retryDelayMultiplier, maxTimeout: this.storage.retryOptions.maxRetryDelay! * 1000, //convert to milliseconds maxRetryTime: this.storage.retryOptions.totalTimeout! * 1000, //convert to milliseconds - } + }, ); if (!callback) { return returnValue; @@ -3977,21 +3977,21 @@ class File extends ServiceObject { setMetadata( metadata: FileMetadata, - options?: SetMetadataOptions + options?: SetMetadataOptions, ): Promise>; setMetadata( metadata: FileMetadata, - callback: MetadataCallback + callback: MetadataCallback, ): void; setMetadata( metadata: FileMetadata, options: SetMetadataOptions, - callback: MetadataCallback + callback: MetadataCallback, ): void; setMetadata( metadata: FileMetadata, optionsOrCallback: SetMetadataOptions | MetadataCallback, - cb?: MetadataCallback + cb?: MetadataCallback, ): Promise> | void { // eslint-disable-next-line @typescript-eslint/no-explicit-any const options: any = @@ -4004,7 +4004,7 @@ class File extends ServiceObject { this.disableAutoRetryConditionallyIdempotent_( this.methods.setMetadata, AvailableServiceObjectMethods.setMetadata, - options + options, ); super @@ -4018,16 +4018,16 @@ class File extends ServiceObject { setStorageClass( storageClass: string, - options?: SetStorageClassOptions + options?: SetStorageClassOptions, ): Promise; setStorageClass( storageClass: string, options: SetStorageClassOptions, - callback: SetStorageClassCallback + callback: SetStorageClassCallback, ): void; setStorageClass( storageClass: string, - callback?: SetStorageClassCallback + callback?: SetStorageClassCallback, ): void; /** * @typedef {array} SetStorageClassResponse @@ -4078,7 +4078,7 @@ class File extends ServiceObject { setStorageClass( storageClass: string, optionsOrCallback?: SetStorageClassOptions | SetStorageClassCallback, - callback?: SetStorageClassCallback + callback?: SetStorageClassCallback, ): Promise | void { callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; @@ -4138,14 +4138,14 @@ class File extends ServiceObject { */ startResumableUpload_( dup: Duplexify, - options: CreateResumableUploadOptions = {} + options: CreateResumableUploadOptions = {}, ): void { options.metadata ??= {}; const retryOptions = this.storage.retryOptions; if ( !this.shouldRetryBasedOnPreconditionAndIdempotencyStrat( - options.preconditionOpts + options.preconditionOpts, ) ) { retryOptions.autoRetry = false; @@ -4156,7 +4156,7 @@ class File extends ServiceObject { bucket: this.bucket.name, customRequestOptions: this.getRequestInterceptors().reduce( (reqOpts, interceptorFn) => interceptorFn(reqOpts), - {} + {}, ), file: this.name, generation: this.generation, @@ -4220,7 +4220,7 @@ class File extends ServiceObject { */ startSimpleUpload_( dup: Duplexify, - options: CreateWriteStreamOptions = {} + options: CreateWriteStreamOptions = {}, ): void { options.metadata ??= {}; @@ -4263,7 +4263,7 @@ class File extends ServiceObject { Object.assign( reqOpts.qs, this.instancePreconditionOpts, - options.preconditionOpts + options.preconditionOpts, ); util.makeWritableStream(dup, { @@ -4289,7 +4289,7 @@ class File extends ServiceObject { // eslint-disable-next-line @typescript-eslint/no-explicit-any coreOpts: any, methodType: AvailableServiceObjectMethods, - localPreconditionOptions?: PreconditionOptions + localPreconditionOptions?: PreconditionOptions, ): void { if ( (typeof coreOpts === 'object' && @@ -4335,7 +4335,7 @@ class File extends ServiceObject { */ async #validateIntegrity( hashCalculatingStream: HashStreamValidator, - verify: {crc32c?: boolean; md5?: boolean} = {} + verify: {crc32c?: boolean; md5?: boolean} = {}, ) { const metadata = this.metadata; diff --git a/src/hash-stream-validator.ts b/src/hash-stream-validator.ts index 5f4a10e4e..5f1f8c740 100644 --- a/src/hash-stream-validator.ts +++ b/src/hash-stream-validator.ts @@ -108,7 +108,7 @@ class HashStreamValidator extends Transform { if (failed) { const mismatchError = new RequestError( - FileExceptionMessages.DOWNLOAD_MISMATCH + FileExceptionMessages.DOWNLOAD_MISMATCH, ); mismatchError.code = 'CONTENT_DOWNLOAD_MISMATCH'; @@ -121,7 +121,7 @@ class HashStreamValidator extends Transform { _transform( chunk: Buffer, encoding: BufferEncoding, - callback: (e?: Error) => void + callback: (e?: Error) => void, ) { this.push(chunk, encoding); diff --git a/src/hmacKey.ts b/src/hmacKey.ts index 9b79daa5e..4f7373733 100644 --- a/src/hmacKey.ts +++ b/src/hmacKey.ts @@ -371,21 +371,21 @@ export class HmacKey extends ServiceObject { */ setMetadata( metadata: HmacKeyMetadata, - options?: SetMetadataOptions + options?: SetMetadataOptions, ): Promise>; setMetadata( metadata: HmacKeyMetadata, - callback: MetadataCallback + callback: MetadataCallback, ): void; setMetadata( metadata: HmacKeyMetadata, options: SetMetadataOptions, - callback: MetadataCallback + callback: MetadataCallback, ): void; setMetadata( metadata: HmacKeyMetadata, optionsOrCallback: SetMetadataOptions | MetadataCallback, - cb?: MetadataCallback + cb?: MetadataCallback, ): Promise> | void { // ETag preconditions are not currently supported. Retries should be disabled if the idempotency strategy is not set to RetryAlways if ( diff --git a/src/iam.ts b/src/iam.ts index 8f6ee5d76..7a90a1b36 100644 --- a/src/iam.ts +++ b/src/iam.ts @@ -99,7 +99,7 @@ export interface TestIamPermissionsCallback { ( err?: Error | null, acl?: {[key: string]: boolean} | null, - apiResponse?: unknown + apiResponse?: unknown, ): void; } @@ -143,7 +143,7 @@ export enum IAMExceptionMessages { class Iam { private request_: ( reqOpts: DecorateRequestOptions, - callback: BodyResponseCallback + callback: BodyResponseCallback, ) => void; private resourceId_: string; @@ -242,7 +242,7 @@ class Iam { */ getPolicy( optionsOrCallback?: GetPolicyOptions | GetPolicyCallback, - callback?: GetPolicyCallback + callback?: GetPolicyCallback, ): Promise | void { const {options, callback: cb} = normalize< GetPolicyOptions, @@ -266,19 +266,19 @@ class Iam { uri: '/iam', qs, }, - cb! + cb!, ); } setPolicy( policy: Policy, - options?: SetPolicyOptions + options?: SetPolicyOptions, ): Promise; setPolicy(policy: Policy, callback: SetPolicyCallback): void; setPolicy( policy: Policy, options: SetPolicyOptions, - callback: SetPolicyCallback + callback: SetPolicyCallback, ): void; /** * Set the IAM policy. @@ -331,7 +331,7 @@ class Iam { setPolicy( policy: Policy, optionsOrCallback?: SetPolicyOptions | SetPolicyCallback, - callback?: SetPolicyCallback + callback?: SetPolicyCallback, ): Promise | void { if (policy === null || typeof policy !== 'object') { throw new Error(IAMExceptionMessages.POLICY_OBJECT_REQUIRED); @@ -356,26 +356,26 @@ class Iam { { resourceId: this.resourceId_, }, - policy + policy, ), qs: options, }, - cb + cb, ); } testPermissions( permissions: string | string[], - options?: TestIamPermissionsOptions + options?: TestIamPermissionsOptions, ): Promise; testPermissions( permissions: string | string[], - callback: TestIamPermissionsCallback + callback: TestIamPermissionsCallback, ): void; testPermissions( permissions: string | string[], options: TestIamPermissionsOptions, - callback: TestIamPermissionsCallback + callback: TestIamPermissionsCallback, ): void; /** * Test a set of permissions for a resource. @@ -435,7 +435,7 @@ class Iam { testPermissions( permissions: string | string[], optionsOrCallback?: TestIamPermissionsOptions | TestIamPermissionsCallback, - callback?: TestIamPermissionsCallback + callback?: TestIamPermissionsCallback, ): Promise | void { if (!Array.isArray(permissions) && typeof permissions !== 'string') { throw new Error(IAMExceptionMessages.PERMISSIONS_REQUIRED); @@ -454,7 +454,7 @@ class Iam { { permissions: permissionsArray, }, - options + options, ); this.request_( @@ -478,11 +478,11 @@ class Iam { acc[permission] = availablePermissions.indexOf(permission) > -1; return acc; }, - {} + {}, ); cb!(null, permissionsHash, resp); - } + }, ); } } diff --git a/src/nodejs-common/service-object.ts b/src/nodejs-common/service-object.ts index a4e369a3f..4f83189d5 100644 --- a/src/nodejs-common/service-object.ts +++ b/src/nodejs-common/service-object.ts @@ -34,7 +34,7 @@ export interface ServiceObjectParent { requestStream(reqOpts: DecorateRequestOptions): r.Request; request( reqOpts: DecorateRequestOptions, - callback: BodyResponseCallback + callback: BodyResponseCallback, ): void; } @@ -48,7 +48,7 @@ export type MetadataResponse = [K, r.Response]; export type MetadataCallback = ( err: Error | null, metadata?: K, - apiResponse?: r.Response + apiResponse?: r.Response, ) => void; export type ExistsOptions = object; @@ -237,7 +237,7 @@ class ServiceObject extends EventEmitter { create(callback: CreateCallback): void; create( optionsOrCallback?: CreateOptions | CreateCallback, - callback?: CreateCallback + callback?: CreateCallback, ): void | Promise> { // eslint-disable-next-line @typescript-eslint/no-this-alias const self = this; @@ -282,7 +282,7 @@ class ServiceObject extends EventEmitter { delete(callback: DeleteCallback): void; delete( optionsOrCallback?: DeleteOptions | DeleteCallback, - cb?: DeleteCallback + cb?: DeleteCallback, ): Promise<[r.Response]> | void { const [options, callback] = util.maybeOptionsOrCallback< DeleteOptions, @@ -317,7 +317,7 @@ class ServiceObject extends EventEmitter { } } callback(err, res); - } + }, ); } @@ -333,7 +333,7 @@ class ServiceObject extends EventEmitter { exists(callback: ExistsCallback): void; exists( optionsOrCallback?: ExistsOptions | ExistsCallback, - cb?: ExistsCallback + cb?: ExistsCallback, ): void | Promise<[boolean]> { const [options, callback] = util.maybeOptionsOrCallback< ExistsOptions, @@ -370,7 +370,7 @@ class ServiceObject extends EventEmitter { get(options: GetOrCreateOptions, callback: InstanceResponseCallback): void; get( optionsOrCallback?: GetOrCreateOptions | InstanceResponseCallback, - cb?: InstanceResponseCallback + cb?: InstanceResponseCallback, ): Promise> | void { // eslint-disable-next-line @typescript-eslint/no-this-alias const self = this; @@ -387,7 +387,7 @@ class ServiceObject extends EventEmitter { function onCreate( err: ApiError | null, instance: T, - apiResponse: r.Response + apiResponse: r.Response, ) { if (err) { if (err.code === 409) { @@ -431,7 +431,7 @@ class ServiceObject extends EventEmitter { getMetadata(callback: MetadataCallback): void; getMetadata( optionsOrCallback: GetMetadataOptions | MetadataCallback, - cb?: MetadataCallback + cb?: MetadataCallback, ): Promise> | void { const [options, callback] = util.maybeOptionsOrCallback< GetMetadataOptions, @@ -459,7 +459,7 @@ class ServiceObject extends EventEmitter { (err: Error | null, body?: ResponseBody, res?: r.Response) => { this.metadata = body; callback!(err, this.metadata, res); - } + }, ); } @@ -485,18 +485,18 @@ class ServiceObject extends EventEmitter { */ setMetadata( metadata: K, - options?: SetMetadataOptions + options?: SetMetadataOptions, ): Promise>; setMetadata(metadata: K, callback: MetadataCallback): void; setMetadata( metadata: K, options: SetMetadataOptions, - callback: MetadataCallback + callback: MetadataCallback, ): void; setMetadata( metadata: K, optionsOrCallback: SetMetadataOptions | MetadataCallback, - cb?: MetadataCallback + cb?: MetadataCallback, ): Promise> | void { const [options, callback] = util.maybeOptionsOrCallback< SetMetadataOptions, @@ -529,7 +529,7 @@ class ServiceObject extends EventEmitter { (err: Error | null, body?: ResponseBody, res?: r.Response) => { this.metadata = body; callback!(err, this.metadata, res); - } + }, ); } @@ -545,11 +545,11 @@ class ServiceObject extends EventEmitter { private request_(reqOpts: StreamRequestOptions): r.Request; private request_( reqOpts: DecorateRequestOptions, - callback: BodyResponseCallback + callback: BodyResponseCallback, ): void; private request_( reqOpts: DecorateRequestOptions | StreamRequestOptions, - callback?: BodyResponseCallback + callback?: BodyResponseCallback, ): void | r.Request { reqOpts = {...reqOpts}; @@ -595,11 +595,11 @@ class ServiceObject extends EventEmitter { request(reqOpts: DecorateRequestOptions): Promise; request( reqOpts: DecorateRequestOptions, - callback: BodyResponseCallback + callback: BodyResponseCallback, ): void; request( reqOpts: DecorateRequestOptions, - callback?: BodyResponseCallback + callback?: BodyResponseCallback, ): void | Promise { this.request_(reqOpts, callback!); } diff --git a/src/nodejs-common/service.ts b/src/nodejs-common/service.ts index 8156cd176..f415420e5 100644 --- a/src/nodejs-common/service.ts +++ b/src/nodejs-common/service.ts @@ -176,7 +176,7 @@ export class Service { getProjectId(): Promise; getProjectId(callback: (err: Error | null, projectId?: string) => void): void; getProjectId( - callback?: (err: Error | null, projectId?: string) => void + callback?: (err: Error | null, projectId?: string) => void, ): Promise | void { if (!callback) { return this.getProjectIdAsync(); @@ -204,11 +204,11 @@ export class Service { private request_(reqOpts: StreamRequestOptions): r.Request; private request_( reqOpts: DecorateRequestOptions, - callback: BodyResponseCallback + callback: BodyResponseCallback, ): void; private request_( reqOpts: DecorateRequestOptions | StreamRequestOptions, - callback?: BodyResponseCallback + callback?: BodyResponseCallback, ): void | r.Request { reqOpts = {...reqOpts, timeout: this.timeout}; const isAbsoluteUrl = reqOpts.uri.indexOf('http') === 0; @@ -291,7 +291,7 @@ export class Service { */ request( reqOpts: DecorateRequestOptions, - callback: BodyResponseCallback + callback: BodyResponseCallback, ): void { Service.prototype.request_.call(this, reqOpts, callback); } diff --git a/src/nodejs-common/util.ts b/src/nodejs-common/util.ts index aec0b2f50..9ba3051ad 100644 --- a/src/nodejs-common/util.ts +++ b/src/nodejs-common/util.ts @@ -96,17 +96,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; } @@ -119,18 +119,18 @@ export interface MakeAuthenticatedRequest { (reqOpts: DecorateRequestOptions): Duplexify; ( reqOpts: DecorateRequestOptions, - options?: MakeAuthenticatedRequestOptions + options?: MakeAuthenticatedRequestOptions, ): void | Abortable; ( reqOpts: DecorateRequestOptions, - callback?: BodyResponseCallback + callback?: BodyResponseCallback, ): void | Abortable; ( reqOpts: DecorateRequestOptions, - optionsOrCallback?: MakeAuthenticatedRequestOptions | BodyResponseCallback + optionsOrCallback?: MakeAuthenticatedRequestOptions | BodyResponseCallback, ): void | Abortable | Duplexify; getCredentials: ( - callback: (err?: Error | null, credentials?: CredentialBody) => void + callback: (err?: Error | null, credentials?: CredentialBody) => void, ) => void; authClient: GoogleAuth; } @@ -233,9 +233,9 @@ export interface MakeWritableStreamOptions { fnobj: { onAuthenticated( err: Error | null, - authenticatedReqOpts?: r.Options + authenticatedReqOpts?: r.Options, ): void; - } + }, ): void; } @@ -300,7 +300,7 @@ export class ApiError extends Error { */ static createMultiErrorMessage( err: GoogleErrorBody, - errors?: GoogleInnerError[] + errors?: GoogleInnerError[], ): string { const messages: Set = new Set(); @@ -321,7 +321,7 @@ export class ApiError extends Error { if (messageArr.length > 1) { messageArr = messageArr.map((message, i) => ` ${i + 1}. ${message}`); messageArr.unshift( - 'Multiple errors occurred during the request. Please see the `errors` array for complete details.\n' + 'Multiple errors occurred during the request. Please see the `errors` array for complete details.\n', ); messageArr.push('\n'); } @@ -412,7 +412,7 @@ export class Util { err: Error | null, resp?: r.Response | null, body?: ResponseBody, - callback?: BodyResponseCallback + callback?: BodyResponseCallback, ) { callback = callback || util.noop; @@ -510,7 +510,7 @@ export class Util { makeWritableStream( dup: Duplexify, options: MakeWritableStreamOptions, - onComplete?: Function + onComplete?: Function, ) { onComplete = onComplete || util.noop; @@ -558,7 +558,7 @@ export class Util { } requestDefaults.headers = util._getDefaultHeaders( - reqOpts[GCCL_GCS_CMD_KEY] + reqOpts[GCCL_GCS_CMD_KEY], ); const request = teenyRequest.defaults(requestDefaults); request(authenticatedReqOpts!, (err, resp, body) => { @@ -625,7 +625,7 @@ export class Util { * @param {array} config.scopes - Array of scopes required for the API. */ makeAuthenticatedRequestFactory( - config: MakeAuthenticatedRequestFactoryConfig + config: MakeAuthenticatedRequestFactoryConfig, ) { const googleAutoAuthConfig = {...config}; if (googleAutoAuthConfig.projectId === DEFAULT_PROJECT_ID_TOKEN) { @@ -656,19 +656,21 @@ export class Util { * authenticated request options. */ function makeAuthenticatedRequest( - reqOpts: DecorateRequestOptions + reqOpts: DecorateRequestOptions, ): Duplexify; function makeAuthenticatedRequest( reqOpts: DecorateRequestOptions, - options?: MakeAuthenticatedRequestOptions + options?: MakeAuthenticatedRequestOptions, ): void | Abortable; function makeAuthenticatedRequest( reqOpts: DecorateRequestOptions, - callback?: BodyResponseCallback + callback?: BodyResponseCallback, ): void | Abortable; function makeAuthenticatedRequest( reqOpts: DecorateRequestOptions, - optionsOrCallback?: MakeAuthenticatedRequestOptions | BodyResponseCallback + optionsOrCallback?: + | MakeAuthenticatedRequestOptions + | BodyResponseCallback, ): void | Abortable | Duplexify { let stream: Duplexify; let projectId: string; @@ -691,7 +693,7 @@ export class Util { const onAuthenticated = async ( err: Error | null, - authenticatedReqOpts?: DecorateRequestOptions + authenticatedReqOpts?: DecorateRequestOptions, ) => { const authLibraryError = err; const autoAuthFailed = @@ -710,7 +712,7 @@ export class Util { // Try with existing `projectId` value authenticatedReqOpts = util.decorateRequest( authenticatedReqOpts!, - projectId + projectId, ); err = null; @@ -723,7 +725,7 @@ export class Util { authenticatedReqOpts = util.decorateRequest( authenticatedReqOpts!, - projectId + projectId, ); err = null; @@ -769,7 +771,7 @@ export class Util { apiResponseError = authLibraryError; } callback!(apiResponseError, ...params); - } + }, ); } }; @@ -818,7 +820,7 @@ export class Util { return onAuthenticated( null, - authorizedReqOpts as DecorateRequestOptions + authorizedReqOpts as DecorateRequestOptions, ); } catch (e) { return onAuthenticated(e as Error); @@ -866,7 +868,7 @@ export class Util { makeRequest( reqOpts: DecorateRequestOptions, config: MakeRequestConfig, - callback: BodyResponseCallback + callback: BodyResponseCallback, ): void | Abortable { let autoRetryValue = AUTO_RETRY_DEFAULT; if (config.autoRetry !== undefined) { @@ -883,7 +885,7 @@ export class Util { } requestDefaults.headers = this._getDefaultHeaders( - reqOpts[GCCL_GCS_CMD_KEY] + reqOpts[GCCL_GCS_CMD_KEY], ); const options = { request: teenyRequest.defaults(requestDefaults), @@ -913,7 +915,7 @@ export class Util { // eslint-disable-next-line @typescript-eslint/no-explicit-any (err: Error | null, response: {}, body: any) => { util.handleResp(err, response as {} as r.Response, body, callback!); - } + }, ); } const dup = config.stream as AbortableDuplex; @@ -1014,7 +1016,7 @@ export class Util { */ maybeOptionsOrCallback void>( optionsOrCallback?: T | C, - cb?: C + cb?: C, ): [T, C] { return typeof optionsOrCallback === 'function' ? [{} as T, optionsOrCallback as C] diff --git a/src/notification.ts b/src/notification.ts index 6d63a899f..95b2e0811 100644 --- a/src/notification.ts +++ b/src/notification.ts @@ -72,7 +72,7 @@ export interface GetNotificationCallback { ( err: Error | null, notification?: Notification | null, - apiResponse?: unknown + apiResponse?: unknown, ): void; } diff --git a/src/resumable-upload.ts b/src/resumable-upload.ts index b12c27f09..f20a337b5 100644 --- a/src/resumable-upload.ts +++ b/src/resumable-upload.ts @@ -108,7 +108,7 @@ export interface UploadConfig extends Pick { */ authClient?: { request: ( - opts: GaxiosOptions + opts: GaxiosOptions, ) => Promise> | GaxiosPromise; }; @@ -292,7 +292,7 @@ export class Upload extends Writable { */ authClient: { request: ( - opts: GaxiosOptions + opts: GaxiosOptions, ) => Promise> | GaxiosPromise; }; cacheKey: string; @@ -349,13 +349,13 @@ export class Upload extends Writable { if (cfg.offset && !cfg.uri) { throw new RangeError( - 'Cannot provide an `offset` without providing a `uri`' + 'Cannot provide an `offset` without providing a `uri`', ); } if (cfg.isPartialUpload && !cfg.chunkSize) { throw new RangeError( - 'Cannot set `isPartialUpload` without providing a `chunkSize`' + 'Cannot set `isPartialUpload` without providing a `chunkSize`', ); } @@ -497,13 +497,13 @@ export class Upload extends Writable { _write( chunk: Buffer | string, encoding: BufferEncoding, - readCallback = () => {} + readCallback = () => {}, ) { // Backwards-compatible event this.emit('writing'); this.writeBuffers.push( - typeof chunk === 'string' ? Buffer.from(chunk, encoding) : chunk + typeof chunk === 'string' ? Buffer.from(chunk, encoding) : chunk, ); this.once('readFromChunkBuffer', readCallback); @@ -709,7 +709,7 @@ export class Upload extends Writable { name: this.file, uploadType: 'resumable', }, - this.params + this.params, ), data: metadata, headers: { @@ -777,7 +777,7 @@ export class Upload extends Writable { factor: this.retryOptions.retryDelayMultiplier, maxTimeout: this.retryOptions.maxRetryDelay! * 1000, //convert to milliseconds maxRetryTime: this.retryOptions.totalTimeout! * 1000, //convert to milliseconds - } + }, ); this.uri = uri; @@ -1052,7 +1052,7 @@ export class Upload extends Writable { * @returns the current upload status */ async checkUploadStatus( - config: CheckUploadStatusConfig = {} + config: CheckUploadStatusConfig = {}, ): Promise> { let googAPIClient = `${getRuntimeTrackingString()} gccl/${ packageJson.version @@ -1161,7 +1161,7 @@ export class Upload extends Writable { }; const res = await this.authClient.request<{error?: object}>( - combinedReqOpts + combinedReqOpts, ); if (res.data && res.data.error) { throw res.data.error; @@ -1232,8 +1232,8 @@ export class Upload extends Writable { if (retryDelay <= 0) { this.destroy( new Error( - `Retry total time limit exceeded - ${JSON.stringify(resp.data)}` - ) + `Retry total time limit exceeded - ${JSON.stringify(resp.data)}`, + ), ); return; } @@ -1255,7 +1255,7 @@ export class Upload extends Writable { this.numRetries++; } else { this.destroy( - new Error(`Retry limit exceeded - ${JSON.stringify(resp.data)}`) + new Error(`Retry limit exceeded - ${JSON.stringify(resp.data)}`), ); } } @@ -1309,7 +1309,7 @@ export function createURI(cfg: UploadConfig): Promise; export function createURI(cfg: UploadConfig, callback: CreateUriCallback): void; export function createURI( cfg: UploadConfig, - callback?: CreateUriCallback + callback?: CreateUriCallback, ): void | Promise { const up = new Upload(cfg); if (!callback) { @@ -1325,7 +1325,7 @@ export function createURI( * @returns the current upload status */ export function checkUploadStatus( - cfg: UploadConfig & Required> + cfg: UploadConfig & Required>, ) { const up = new Upload(cfg); diff --git a/src/signer.ts b/src/signer.ts index 879bc4d2a..a657cef61 100644 --- a/src/signer.ts +++ b/src/signer.ts @@ -152,11 +152,11 @@ export class URLSigner { * move it before optional properties. In the next major we should refactor the * constructor of this class to only accept a config object. */ - private storage: Storage = new Storage() + private storage: Storage = new Storage(), ) {} getSignedUrl( - cfg: SignerGetSignedUrlConfig + cfg: SignerGetSignedUrlConfig, ): Promise { const expiresInSeconds = this.parseExpires(cfg.expires); const method = cfg.method; @@ -164,7 +164,7 @@ export class URLSigner { if (expiresInSeconds < accessibleAtInSeconds) { throw new Error( - SignerExceptionMessages.EXPIRATION_BEFORE_ACCESSIBLE_DATE + SignerExceptionMessages.EXPIRATION_BEFORE_ACCESSIBLE_DATE, ); } @@ -200,7 +200,7 @@ export class URLSigner { promise = this.getSignedUrlV4(config); } else { throw new Error( - `Invalid signed URL version: ${version}. Supported versions are 'v2' and 'v4'.` + `Invalid signed URL version: ${version}. Supported versions are 'v2' and 'v4'.`, ); } @@ -208,13 +208,13 @@ export class URLSigner { query = Object.assign(query, cfg.queryParams); const signedUrl = new url.URL( - cfg.host?.toString() || config.cname || this.storage.apiEndpoint + cfg.host?.toString() || config.cname || this.storage.apiEndpoint, ); signedUrl.pathname = this.getResourcePath( !!config.cname, this.bucket.name, - config.file + config.file, ); // eslint-disable-next-line @typescript-eslint/no-explicit-any signedUrl.search = qsStringify(query as any); @@ -223,15 +223,15 @@ export class URLSigner { } private getSignedUrlV2( - config: GetSignedUrlConfigInternal + config: GetSignedUrlConfigInternal, ): Promise { const canonicalHeadersString = this.getCanonicalHeaders( - config.extensionHeaders || {} + config.extensionHeaders || {}, ); const resourcePath = this.getResourcePath( false, config.bucket, - config.file + config.file, ); const blobToSign = [ @@ -247,7 +247,7 @@ export class URLSigner { try { const signature = await auth.sign( blobToSign, - config.signingEndpoint?.toString() + config.signingEndpoint?.toString(), ); const credentials = await auth.getCredentials(); @@ -267,7 +267,7 @@ export class URLSigner { } private getSignedUrlV4( - config: GetSignedUrlConfigInternal + config: GetSignedUrlConfigInternal, ): Promise { config.accessibleAt = config.accessibleAt ? config.accessibleAt @@ -279,13 +279,13 @@ export class URLSigner { // v4 limit expiration to be 7 days maximum if (expiresPeriodInSeconds > SEVEN_DAYS) { throw new Error( - `Max allowed expiration is seven days (${SEVEN_DAYS} seconds).` + `Max allowed expiration is seven days (${SEVEN_DAYS} seconds).`, ); } const extensionHeaders = Object.assign({}, config.extensionHeaders); const fqdn = new url.URL( - config.host?.toString() || config.cname || this.storage.apiEndpoint + config.host?.toString() || config.cname || this.storage.apiEndpoint, ); extensionHeaders.host = fqdn.hostname; if (config.contentMd5) { @@ -322,7 +322,7 @@ export class URLSigner { const credential = `${credentials.client_email}/${credentialScope}`; const dateISO = formatAsUTCISO( config.accessibleAt ? config.accessibleAt : new Date(), - true + true, ); const queryParams: Query = { 'X-Goog-Algorithm': 'GOOG4-RSA-SHA256', @@ -342,7 +342,7 @@ export class URLSigner { canonicalQueryParams, extensionHeadersString, signedHeaders, - contentSha256 + contentSha256, ); const hash = crypto @@ -360,7 +360,7 @@ export class URLSigner { try { const signature = await this.auth.sign( blobToSign, - config.signingEndpoint?.toString() + config.signingEndpoint?.toString(), ); const signatureHex = Buffer.from(signature, 'base64').toString('hex'); const signedQuery: Query = Object.assign({}, queryParams, { @@ -421,7 +421,7 @@ export class URLSigner { query: string, headers: string, signedHeaders: string, - contentSha256?: string + contentSha256?: string, ) { return [ method, @@ -453,7 +453,7 @@ export class URLSigner { parseExpires( expires: string | number | Date, - current: Date = new Date() + current: Date = new Date(), ): number { const expiresInMSeconds = new Date(expires).valueOf(); @@ -470,7 +470,7 @@ export class URLSigner { parseAccessibleAt(accessibleAt?: string | number | Date): number { const accessibleAtInMSeconds = new Date( - accessibleAt || new Date() + accessibleAt || new Date(), ).valueOf(); if (isNaN(accessibleAtInMSeconds)) { diff --git a/src/storage.ts b/src/storage.ts index 6bd9f37a8..9b9e8e2df 100644 --- a/src/storage.ts +++ b/src/storage.ts @@ -43,7 +43,7 @@ export interface GetServiceAccountCallback { ( err: Error | null, serviceAccount?: ServiceAccount, - apiResponse?: unknown + apiResponse?: unknown, ): void; } @@ -174,7 +174,7 @@ export interface GetBucketsCallback { err: Error | null, buckets: Bucket[], nextQuery?: {}, - apiResponse?: unknown + apiResponse?: unknown, ): void; } export interface GetBucketsRequest { @@ -204,7 +204,7 @@ export interface CreateHmacKeyCallback { err: Error | null, hmacKey?: HmacKey | null, secret?: string | null, - apiResponse?: HmacKeyResourceResponse + apiResponse?: HmacKeyResourceResponse, ): void; } @@ -224,7 +224,7 @@ export interface GetHmacKeysCallback { err: Error | null, hmacKeys: HmacKey[] | null, nextQuery?: {}, - apiResponse?: unknown + apiResponse?: unknown, ): void; } @@ -853,18 +853,18 @@ export class Storage extends Service { createBucket( name: string, - metadata?: CreateBucketRequest + metadata?: CreateBucketRequest, ): Promise; createBucket(name: string, callback: BucketCallback): void; createBucket( name: string, metadata: CreateBucketRequest, - callback: BucketCallback + callback: BucketCallback, ): void; createBucket( name: string, metadata: CreateBucketRequest, - callback: BucketCallback + callback: BucketCallback, ): void; /** * @typedef {array} CreateBucketResponse @@ -994,7 +994,7 @@ export class Storage extends Service { createBucket( name: string, metadataOrCallback?: BucketCallback | CreateBucketRequest, - callback?: BucketCallback + callback?: BucketCallback, ): Promise | void { if (!name) { throw new Error(StorageExceptionMessages.BUCKET_NAME_REQUIRED_CREATE); @@ -1023,14 +1023,14 @@ export class Storage extends Service { standard: 'STANDARD', } as const; const storageClassKeys = Object.keys( - storageClasses + storageClasses, ) as (keyof typeof storageClasses)[]; for (const storageClass of storageClassKeys) { if (body[storageClass]) { if (metadata.storageClass && metadata.storageClass !== storageClass) { throw new Error( - `Both \`${storageClass}\` and \`storageClass\` were provided.` + `Both \`${storageClass}\` and \`storageClass\` were provided.`, ); } body.storageClass = storageClasses[storageClass]; @@ -1091,22 +1091,22 @@ export class Storage extends Service { bucket.metadata = resp; callback!(null, bucket, resp); - } + }, ); } createHmacKey( serviceAccountEmail: string, - options?: CreateHmacKeyOptions + options?: CreateHmacKeyOptions, ): Promise; createHmacKey( serviceAccountEmail: string, - callback: CreateHmacKeyCallback + callback: CreateHmacKeyCallback, ): void; createHmacKey( serviceAccountEmail: string, options: CreateHmacKeyOptions, - callback: CreateHmacKeyCallback + callback: CreateHmacKeyCallback, ): void; /** * @typedef {object} CreateHmacKeyOptions @@ -1184,7 +1184,7 @@ export class Storage extends Service { createHmacKey( serviceAccountEmail: string, optionsOrCb?: CreateHmacKeyOptions | CreateHmacKeyCallback, - cb?: CreateHmacKeyCallback + cb?: CreateHmacKeyCallback, ): Promise | void { if (typeof serviceAccountEmail !== 'string') { throw new Error(StorageExceptionMessages.HMAC_SERVICE_ACCOUNT); @@ -1218,7 +1218,7 @@ export class Storage extends Service { hmacKey.metadata = resp.metadata; callback!(null, hmacKey, resp.secret, resp); - } + }, ); } @@ -1312,11 +1312,11 @@ export class Storage extends Service { */ getBuckets( optionsOrCallback?: GetBucketsRequest | GetBucketsCallback, - cb?: GetBucketsCallback + cb?: GetBucketsCallback, ): void | Promise { const {options, callback} = normalize( optionsOrCallback, - cb + cb, ); options.project = options.project || this.projectId; @@ -1343,7 +1343,7 @@ export class Storage extends Service { : null; callback(null, buckets, nextQuery, resp); - } + }, ); } @@ -1435,7 +1435,7 @@ export class Storage extends Service { getHmacKeys(options: GetHmacKeysOptions, callback: GetHmacKeysCallback): void; getHmacKeys( optionsOrCb?: GetHmacKeysOptions | GetHmacKeysCallback, - cb?: GetHmacKeysCallback + cb?: GetHmacKeysCallback, ): Promise | void { const {options, callback} = normalize(optionsOrCb, cb); const query = Object.assign({}, options); @@ -1467,19 +1467,19 @@ export class Storage extends Service { : null; callback(null, hmacKeys, nextQuery, resp); - } + }, ); } getServiceAccount( - options?: GetServiceAccountOptions + options?: GetServiceAccountOptions, ): Promise; getServiceAccount( - options?: GetServiceAccountOptions + options?: GetServiceAccountOptions, ): Promise; getServiceAccount( options: GetServiceAccountOptions, - callback: GetServiceAccountCallback + callback: GetServiceAccountCallback, ): void; getServiceAccount(callback: GetServiceAccountCallback): void; /** @@ -1532,11 +1532,11 @@ export class Storage extends Service { */ getServiceAccount( optionsOrCallback?: GetServiceAccountOptions | GetServiceAccountCallback, - cb?: GetServiceAccountCallback + cb?: GetServiceAccountCallback, ): void | Promise { const {options, callback} = normalize( optionsOrCallback, - cb + cb, ); this.request( { @@ -1555,14 +1555,14 @@ export class Storage extends Service { // eslint-disable-next-line no-prototype-builtins if (resp.hasOwnProperty(prop)) { const camelCaseProp = prop.replace(/_(\w)/g, (_, match) => - match.toUpperCase() + match.toUpperCase(), ); camelCaseResponse[camelCaseProp] = resp[prop]; } } callback(null, camelCaseResponse, resp); - } + }, ); } diff --git a/src/transfer-manager.ts b/src/transfer-manager.ts index 234824d77..c487c7749 100644 --- a/src/transfer-manager.ts +++ b/src/transfer-manager.ts @@ -96,7 +96,7 @@ export interface UploadManyFilesOptions { concurrencyLimit?: number; customDestinationBuilder?( path: string, - options: UploadManyFilesOptions + options: UploadManyFilesOptions, ): string; skipIfExists?: boolean; prefix?: string; @@ -140,7 +140,7 @@ export interface MultiPartUploadHelper { uploadPart( partNumber: number, chunk: Buffer, - validation?: 'md5' | false + validation?: 'md5' | false, ): Promise; completeUpload(): Promise; abortUpload(): Promise; @@ -150,14 +150,14 @@ export type MultiPartHelperGenerator = ( bucket: Bucket, fileName: string, uploadId?: string, - partsMap?: Map + partsMap?: Map, ) => MultiPartUploadHelper; const defaultMultiPartGenerator: MultiPartHelperGenerator = ( bucket, fileName, uploadId, - partsMap + partsMap, ) => { return new XMLMultiPartUploadHelper(bucket, fileName, uploadId, partsMap); }; @@ -169,7 +169,7 @@ export class MultiPartUploadError extends Error { constructor( message: string, uploadId: string, - partsMap: Map + partsMap: Map, ) { super(message); this.uploadId = uploadId; @@ -198,7 +198,7 @@ class XMLMultiPartUploadHelper implements MultiPartUploadHelper { bucket: Bucket, fileName: string, uploadId?: string, - partsMap?: Map + partsMap?: Map, ) { this.authClient = bucket.storage.authClient || new GoogleAuth(); this.uploadId = uploadId || ''; @@ -289,7 +289,7 @@ class XMLMultiPartUploadHelper implements MultiPartUploadHelper { async uploadPart( partNumber: number, chunk: Buffer, - validation?: 'md5' | false + validation?: 'md5' | false, ): Promise { const url = `${this.baseUrl}?partNumber=${partNumber}&uploadId=${this.uploadId}`; let headers: Headers = this.#setGoogApiClientHeaders(); @@ -327,14 +327,14 @@ class XMLMultiPartUploadHelper implements MultiPartUploadHelper { async completeUpload(): Promise { const url = `${this.baseUrl}?uploadId=${this.uploadId}`; const sortedMap = new Map( - [...this.partsMap.entries()].sort((a, b) => a[0] - b[0]) + [...this.partsMap.entries()].sort((a, b) => a[0] - b[0]), ); const parts: {}[] = []; for (const entry of sortedMap.entries()) { parts.push({PartNumber: entry[0], ETag: entry[1]}); } const body = `${this.xmlBuilder.build( - parts + parts, )}`; return AsyncRetry(async bail => { try { @@ -456,7 +456,7 @@ export class TransferManager { */ async uploadManyFiles( filePathsOrDirectory: string[] | string, - options: UploadManyFilesOptions = {} + options: UploadManyFilesOptions = {}, ): Promise { if (options.skipIfExists && options.passthroughOptions?.preconditionOpts) { options.passthroughOptions.preconditionOpts.ifGenerationMatch = 0; @@ -472,13 +472,13 @@ export class TransferManager { } const limit = pLimit( - options.concurrencyLimit || DEFAULT_PARALLEL_UPLOAD_LIMIT + options.concurrencyLimit || DEFAULT_PARALLEL_UPLOAD_LIMIT, ); const promises: Promise[] = []; let allPaths: string[] = []; if (!Array.isArray(filePathsOrDirectory)) { for await (const curPath of this.getPathsFromDirectory( - filePathsOrDirectory + filePathsOrDirectory, )) { allPaths.push(curPath); } @@ -503,14 +503,14 @@ export class TransferManager { if (options.prefix) { passThroughOptionsCopy.destination = path.posix.join( ...options.prefix.split(path.sep), - passThroughOptionsCopy.destination + passThroughOptionsCopy.destination, ); } promises.push( limit(() => - this.bucket.upload(filePath, passThroughOptionsCopy as UploadOptions) - ) + this.bucket.upload(filePath, passThroughOptionsCopy as UploadOptions), + ), ); } @@ -565,10 +565,10 @@ export class TransferManager { */ async downloadManyFiles( filesOrFolder: File[] | string[] | string, - options: DownloadManyFilesOptions = {} + options: DownloadManyFilesOptions = {}, ): Promise { const limit = pLimit( - options.concurrencyLimit || DEFAULT_PARALLEL_DOWNLOAD_LIMIT + options.concurrencyLimit || DEFAULT_PARALLEL_DOWNLOAD_LIMIT, ); const promises: Promise[] = []; let files: File[] = []; @@ -602,7 +602,7 @@ export class TransferManager { passThroughOptionsCopy.destination = path.join( options.prefix || '', passThroughOptionsCopy.destination || '', - file.name + file.name, ); } if (options.stripPrefix) { @@ -626,7 +626,7 @@ export class TransferManager { } return file.download(passThroughOptionsCopy); - }) + }), ); } @@ -668,12 +668,12 @@ export class TransferManager { */ async downloadFileInChunks( fileOrName: File | string, - options: DownloadFileInChunksOptions = {} + options: DownloadFileInChunksOptions = {}, ): Promise { let chunkSize = options.chunkSizeBytes || DOWNLOAD_IN_CHUNKS_DEFAULT_CHUNK_SIZE; let limit = pLimit( - options.concurrencyLimit || DEFAULT_PARALLEL_CHUNKED_DOWNLOAD_LIMIT + options.concurrencyLimit || DEFAULT_PARALLEL_CHUNKED_DOWNLOAD_LIMIT, ); const noReturnData = Boolean(options.noReturnData); const promises: Promise[] = []; @@ -708,11 +708,11 @@ export class TransferManager { resp[0], 0, resp[0].length, - chunkStart + chunkStart, ); if (noReturnData) return; return result.buffer; - }) + }), ); start += chunkSize; @@ -729,7 +729,7 @@ export class TransferManager { const downloadedCrc32C = await CRC32C.fromFile(filePath); if (!downloadedCrc32C.validate(fileInfo[0].metadata.crc32c)) { const mismatchError = new RequestError( - FileExceptionMessages.DOWNLOAD_MISMATCH + FileExceptionMessages.DOWNLOAD_MISMATCH, ); mismatchError.code = 'CONTENT_DOWNLOAD_MISMATCH'; throw mismatchError; @@ -786,12 +786,12 @@ export class TransferManager { async uploadFileInChunks( filePath: string, options: UploadFileInChunksOptions = {}, - generator: MultiPartHelperGenerator = defaultMultiPartGenerator + generator: MultiPartHelperGenerator = defaultMultiPartGenerator, ): Promise { const chunkSize = options.chunkSizeBytes || UPLOAD_IN_CHUNKS_DEFAULT_CHUNK_SIZE; const limit = pLimit( - options.concurrencyLimit || DEFAULT_PARALLEL_CHUNKED_UPLOAD_LIMIT + options.concurrencyLimit || DEFAULT_PARALLEL_CHUNKED_UPLOAD_LIMIT, ); const maxQueueSize = options.maxQueueSize || @@ -802,7 +802,7 @@ export class TransferManager { this.bucket, fileName, options.uploadId, - options.partsMap + options.partsMap, ); let partNumber = 1; let promises: Promise[] = []; @@ -824,8 +824,8 @@ export class TransferManager { } promises.push( limit(() => - mpuHelper.uploadPart(partNumber++, curChunk, options.validation) - ) + mpuHelper.uploadPart(partNumber++, curChunk, options.validation), + ), ); } await Promise.all(promises); @@ -842,20 +842,20 @@ export class TransferManager { throw new MultiPartUploadError( (e as Error).message, mpuHelper.uploadId!, - mpuHelper.partsMap! + mpuHelper.partsMap!, ); } } throw new MultiPartUploadError( (e as Error).message, mpuHelper.uploadId!, - mpuHelper.partsMap! + mpuHelper.partsMap!, ); } } private async *getPathsFromDirectory( - directory: string + directory: string, ): AsyncGenerator { const filesAndSubdirectories = await fsp.readdir(directory, { withFileTypes: true, diff --git a/src/util.ts b/src/util.ts index 896edc586..b4a4999f3 100644 --- a/src/util.ts +++ b/src/util.ts @@ -26,7 +26,7 @@ const isEsm = true; export function normalize( optionsOrCallback?: T | U, - cb?: U + cb?: U, ) { const options = ( typeof optionsOrCallback === 'object' ? optionsOrCallback : {} @@ -58,7 +58,7 @@ export function objectEntries(obj: {[key: string]: T}): Array<[string, T]> { export function fixedEncodeURIComponent(str: string): string { return encodeURIComponent(str).replace( /[!'()*]/g, - c => '%' + c.charCodeAt(0).toString(16).toUpperCase() + c => '%' + c.charCodeAt(0).toString(16).toUpperCase(), ); } @@ -110,7 +110,7 @@ export function unicodeJSONStringify(obj: object) { return JSON.stringify(obj).replace( /[\u0080-\uFFFF]/g, (char: string) => - '\\u' + ('0000' + char.charCodeAt(0).toString(16)).slice(-4) + '\\u' + ('0000' + char.charCodeAt(0).toString(16)).slice(-4), ); } @@ -154,7 +154,7 @@ export function formatAsUTCISO( dateTimeToFormat: Date, includeTime = false, dateDelimiter = '', - timeDelimiter = '' + timeDelimiter = '', ): string { const year = dateTimeToFormat.getUTCFullYear(); const month = dateTimeToFormat.getUTCMonth() + 1; @@ -246,7 +246,7 @@ export class PassThroughShim extends PassThrough { _write( chunk: never, encoding: BufferEncoding, - callback: (error?: Error | null | undefined) => void + callback: (error?: Error | null | undefined) => void, ): void { if (this.shouldEmitWriting) { this.emit('writing'); diff --git a/system-test/common.ts b/system-test/common.ts index 0288143c6..6831f58cb 100644 --- a/system-test/common.ts +++ b/system-test/common.ts @@ -52,7 +52,7 @@ describe('Common', () => { assert.ifError(err); assert.strictEqual(resp, mockResponse); mockServer.close(done); - } + }, ); }); @@ -77,7 +77,7 @@ describe('Common', () => { assert.strictEqual((err! as common.ApiError).code, 408); assert.strictEqual(numRequestAttempts, 4); mockServer.close(done); - } + }, ); }); @@ -105,7 +105,7 @@ describe('Common', () => { assert(err?.message.includes('ECONNREFUSED')); const timeResponse = Date.now(); assert(timeResponse - timeRequest > minExpectedResponseTime); - } + }, ); done(); }); diff --git a/system-test/kitchen.ts b/system-test/kitchen.ts index fbdd139d1..5ec6659a3 100644 --- a/system-test/kitchen.ts +++ b/system-test/kitchen.ts @@ -109,7 +109,7 @@ describe('resumable-upload', () => { file: filePath, retryOptions: retryOptions, metadata: {contentType: 'image/jpg'}, - }) + }), ) .on('error', done) .on('response', resp => { @@ -137,7 +137,7 @@ describe('resumable-upload', () => { type DoUploadCallback = (...args: any[]) => void; const doUpload = ( opts: {interrupt?: boolean}, - callback: DoUploadCallback + callback: DoUploadCallback, ) => { let sizeStreamed = 0; let destroyed = false; @@ -182,7 +182,7 @@ describe('resumable-upload', () => { assert.strictEqual(metadata.size, size); assert.strictEqual(typeof metadata.size, 'number'); done(); - } + }, ); }); }); @@ -222,7 +222,7 @@ describe('resumable-upload', () => { file: filePath, metadata, retryOptions: retryOptions, - }) + }), ) .on('error', (err: ErrorWithCode) => { assert.strictEqual(err.status, 400); @@ -243,8 +243,8 @@ describe('resumable-upload', () => { file.createWriteStream({ chunkSize, }), - e => (e ? reject(e) : resolve()) - ) + e => (e ? reject(e) : resolve()), + ), ); const [results] = await file.getMetadata(); @@ -290,7 +290,7 @@ describe('resumable-upload', () => { }); await new Promise((resolve, reject) => - pipeline(readable, writable, e => (e ? reject(e) : resolve())) + pipeline(readable, writable, e => (e ? reject(e) : resolve())), ); } @@ -301,7 +301,7 @@ describe('resumable-upload', () => { assert.equal( crc32cGenerated, count, - 'crc32c should be generated on each upload' + 'crc32c should be generated on each upload', ); assert.equal(results.size, FILE_SIZE); }); diff --git a/system-test/storage.ts b/system-test/storage.ts index 6c33cf7ac..db388dac6 100644 --- a/system-test/storage.ts +++ b/system-test/storage.ts @@ -92,20 +92,20 @@ describe('storage', function () { logo: { path: path.join( getDirName(), - '../../../system-test/data/CloudPlatform_128px_Retina.png' + '../../../system-test/data/CloudPlatform_128px_Retina.png', ), }, big: { path: path.join( getDirName(), - '../../../system-test/data/three-mb-file.tif' + '../../../system-test/data/three-mb-file.tif', ), hash: undefined, }, html: { path: path.join( getDirName(), - '../../../system-test/data/long-html-file.html' + '../../../system-test/data/long-html-file.html', ), }, empty: { @@ -205,7 +205,7 @@ describe('storage', function () { await assert.rejects( file.download(), (err: Error) => - err.message.indexOf('does not have storage.objects.get') > -1 + err.message.indexOf('does not have storage.objects.get') > -1, ); }); @@ -218,7 +218,7 @@ describe('storage', function () { /does not have storage\.objects\.create access/, ]; assert( - allowedErrorMessages.some(msg => msg.test((e as Error).message)) + allowedErrorMessages.some(msg => msg.test((e as Error).message)), ); } }); @@ -231,7 +231,7 @@ describe('storage', function () { // Introduce a delay between tests to avoid getting an error. beforeEach(async () => { await new Promise(resolve => - setTimeout(resolve, BUCKET_METADATA_UPDATE_WAIT_TIME) + setTimeout(resolve, BUCKET_METADATA_UPDATE_WAIT_TIME), ); }); @@ -270,7 +270,7 @@ describe('storage', function () { const [accessControlGet] = await bucket.acl.get(opts); assert.strictEqual( (accessControlGet as AccessControlObject).role, - storage.acl.OWNER_ROLE + storage.acl.OWNER_ROLE, ); await bucket.acl.delete(opts); }); @@ -297,20 +297,20 @@ describe('storage', function () { role: 'READER', }); await new Promise(resolve => - setTimeout(resolve, BUCKET_METADATA_UPDATE_WAIT_TIME) + setTimeout(resolve, BUCKET_METADATA_UPDATE_WAIT_TIME), ); await bucket.acl.delete({entity: 'allUsers'}); }); it('should make files public', async () => { await Promise.all( - ['a', 'b', 'c'].map(text => createFileWithContentPromise(text)) + ['a', 'b', 'c'].map(text => createFileWithContentPromise(text)), ); await bucket.makePublic({includeFiles: true}); const [files] = await bucket.getFiles(); const resps = await Promise.all( - files.map(file => isFilePublicAsync(file)) + files.map(file => isFilePublicAsync(file)), ); resps.forEach(resp => assert.strictEqual(resp, true)); await Promise.all([ @@ -323,7 +323,7 @@ describe('storage', function () { try { await bucket.makePublic(); await new Promise(resolve => - setTimeout(resolve, BUCKET_METADATA_UPDATE_WAIT_TIME) + setTimeout(resolve, BUCKET_METADATA_UPDATE_WAIT_TIME), ); await bucket.makePrivate(); assert.rejects(bucket.acl.get({entity: 'allUsers'}), err => { @@ -337,13 +337,13 @@ describe('storage', function () { it('should make files private', async () => { await Promise.all( - ['a', 'b', 'c'].map(text => createFileWithContentPromise(text)) + ['a', 'b', 'c'].map(text => createFileWithContentPromise(text)), ); await bucket.makePrivate({includeFiles: true}); const [files] = await bucket.getFiles(); const resps = await Promise.all( - files.map(file => isFilePublicAsync(file)) + files.map(file => isFilePublicAsync(file)), ); resps.forEach(resp => { assert.strictEqual(resp, false); @@ -385,7 +385,7 @@ describe('storage', function () { const [accessControlGet] = await file.acl.get({entity: USER_ACCOUNT}); assert.strictEqual( (accessControlGet as AccessControlObject).role, - storage.acl.OWNER_ROLE + storage.acl.OWNER_ROLE, ); await file.acl.delete({entity: USER_ACCOUNT}); }); @@ -424,7 +424,7 @@ describe('storage', function () { assert.doesNotReject(file.makePrivate()); assert.rejects( file.acl.get({entity: 'allUsers'}), - validateMakeFilePrivateRejects + validateMakeFilePrivateRejects, ); }); @@ -487,11 +487,11 @@ describe('storage', function () { bucket.upload(FILES.big.path, { resumable: true, private: true, - }) + }), ); assert.rejects( file.acl.get({entity: 'allUsers'}), - validateMakeFilePrivateRejects + validateMakeFilePrivateRejects, ); }); }); @@ -539,7 +539,7 @@ describe('storage', function () { const legacyBucketReaderBinding = newPolicy!.bindings.filter( binding => { return binding.role === 'roles/storage.legacyBucketReader'; - } + }, )[0]; assert(legacyBucketReaderBinding.members.includes('allUsers')); }); @@ -606,7 +606,7 @@ describe('storage', function () { const setPublicAccessPrevention = ( bucket: Bucket, - configuration: string + configuration: string, ) => { return bucket.setMetadata({ iamConfiguration: { @@ -616,14 +616,14 @@ describe('storage', function () { }; const validateUnexpectedPublicAccessPreventionValueError = ( - err: ApiError + err: ApiError, ) => { assert.strictEqual(err.code, 400); return true; }; const validateConfiguringPublicAccessWhenPAPEnforcedError = ( - err: ApiError + err: ApiError, ) => { assert.strictEqual(err.code, 412); return true; @@ -634,14 +634,14 @@ describe('storage', function () { it('inserts a bucket with enforced public access prevention', async () => { await setPublicAccessPrevention( bucket, - PUBLIC_ACCESS_PREVENTION_ENFORCED + PUBLIC_ACCESS_PREVENTION_ENFORCED, ); const [bucketMetadata] = await bucket.getMetadata(); const publicAccessPreventionStatus = bucketMetadata!.iamConfiguration!.publicAccessPrevention; return assert.strictEqual( publicAccessPreventionStatus, - PUBLIC_ACCESS_PREVENTION_ENFORCED + PUBLIC_ACCESS_PREVENTION_ENFORCED, ); }); @@ -661,21 +661,21 @@ describe('storage', function () { await setPublicAccessPrevention( bucket, - PUBLIC_ACCESS_PREVENTION_ENFORCED + PUBLIC_ACCESS_PREVENTION_ENFORCED, ); }); it('bucket cannot be made public', async () => { return assert.rejects( () => bucket.makePublic(), - validateConfiguringPublicAccessWhenPAPEnforcedError + validateConfiguringPublicAccessWhenPAPEnforcedError, ); }); it('object cannot be made public via ACL', async () => { return assert.rejects( () => file.makePublic(), - validateConfiguringPublicAccessWhenPAPEnforcedError + validateConfiguringPublicAccessWhenPAPEnforcedError, ); }); }); @@ -683,21 +683,21 @@ describe('storage', function () { it('inserts a bucket with inherited public access prevention', async () => { await setPublicAccessPrevention( bucket, - PUBLIC_ACCESS_PREVENTION_INHERITED + PUBLIC_ACCESS_PREVENTION_INHERITED, ); const [bucketMetadata] = await bucket.getMetadata(); const publicAccessPreventionStatus = bucketMetadata!.iamConfiguration!.publicAccessPrevention; return assert.strictEqual( publicAccessPreventionStatus, - PUBLIC_ACCESS_PREVENTION_INHERITED + PUBLIC_ACCESS_PREVENTION_INHERITED, ); }); it('makes public a bucket with inherited public access prevention', async () => { await setPublicAccessPrevention( bucket, - PUBLIC_ACCESS_PREVENTION_INHERITED + PUBLIC_ACCESS_PREVENTION_INHERITED, ); return assert.ok(() => bucket.makePublic()); }); @@ -705,7 +705,7 @@ describe('storage', function () { it('should fail to insert a bucket with unexpected public access prevention value', async () => { await assert.rejects( () => setPublicAccessPrevention(bucket, 'unexpected value'), - validateUnexpectedPublicAccessPreventionValueError + validateUnexpectedPublicAccessPreventionValueError, ); }); @@ -723,7 +723,7 @@ describe('storage', function () { const [updatedBucketMetadata] = await bucket.getMetadata(); return assert.strictEqual( updatedBucketMetadata!.iamConfiguration!.publicAccessPrevention, - publicAccessPreventionStatus + publicAccessPreventionStatus, ); }); @@ -740,13 +740,13 @@ describe('storage', function () { bucketMetadata!.iamConfiguration!.uniformBucketLevelAccess!.enabled; await setPublicAccessPrevention( bucket, - PUBLIC_ACCESS_PREVENTION_INHERITED + PUBLIC_ACCESS_PREVENTION_INHERITED, ); const [updatedBucketMetadata] = await bucket.getMetadata(); return assert.strictEqual( updatedBucketMetadata!.iamConfiguration!.uniformBucketLevelAccess! .enabled, - ublaSetting + ublaSetting, ); }); }); @@ -764,7 +764,7 @@ describe('storage', function () { const setTurboReplication = ( bucket: Bucket, - turboReplicationConfiguration: string + turboReplicationConfiguration: string, ) => { return bucket.setMetadata({ rpo: turboReplicationConfiguration, @@ -831,7 +831,7 @@ describe('storage', function () { assert(metadata[0].softDeletePolicy.effectiveTime); assert.deepStrictEqual( metadata[0].softDeletePolicy.retentionDurationSeconds, - SOFT_DELETE_RETENTION_SECONDS.toString() + SOFT_DELETE_RETENTION_SECONDS.toString(), ); }); @@ -860,7 +860,7 @@ describe('storage', function () { assert(softDeletedFile); assert.strictEqual( softDeletedFile.metadata.generation, - metadata.generation + metadata.generation, ); }); @@ -892,7 +892,7 @@ describe('storage', function () { assert.strictEqual(softDeletedFiles.length, 2); assert.notStrictEqual( softDeletedFiles![0].metadata.restoreToken, - undefined + undefined, ); }); @@ -908,7 +908,7 @@ describe('storage', function () { assert(softDeletedFile); assert.strictEqual( softDeletedFile.metadata.generation, - metadata.generation + metadata.generation, ); assert.notStrictEqual(softDeletedFile.metadata.restoreToken, undefined); }); @@ -927,7 +927,7 @@ describe('storage', function () { assert(softDeletedFile); const restoredFile = await f1.restore({ generation: parseInt( - softDeletedFile.metadata.generation?.toString() || '0' + softDeletedFile.metadata.generation?.toString() || '0', ), restoreToken: softDeletedFile.metadata.restoreToken, }); @@ -1032,7 +1032,7 @@ describe('storage', function () { await new Promise(res => setTimeout(res, UNIFORM_ACCESS_WAIT_TIME)); } catch (err) { assert( - validateUniformBucketLevelAccessEnabledError(err as ApiError) + validateUniformBucketLevelAccessEnabledError(err as ApiError), ); break; } @@ -1047,7 +1047,7 @@ describe('storage', function () { await new Promise(res => setTimeout(res, UNIFORM_ACCESS_WAIT_TIME)); } catch (err) { assert( - validateUniformBucketLevelAccessEnabledError(err as ApiError) + validateUniformBucketLevelAccessEnabledError(err as ApiError), ); break; } @@ -1164,7 +1164,7 @@ describe('storage', function () { after(async () => { await Promise.all( - bucketsToCreate.map(bucket => storage.bucket(bucket).delete()) + bucketsToCreate.map(bucket => storage.bucket(bucket).delete()), ); }); @@ -1307,7 +1307,7 @@ describe('storage', function () { const [metadata] = await bucket.getMetadata(); assert.deepStrictEqual( metadata.labels, - Object.assign({}, LABELS, newLabels) + Object.assign({}, LABELS, newLabels), ); }); @@ -1394,7 +1394,7 @@ describe('storage', function () { }); assert.strictEqual( bucket.metadata.lifecycle!.rule!.length, - numExistingRules + 2 + numExistingRules + 2, ); }); @@ -1415,8 +1415,8 @@ describe('storage', function () { rule.action.type === 'Delete' && typeof rule.condition.matchesPrefix === 'object' && (rule.condition.matchesPrefix as string[]).length === 1 && - Array.isArray(rule.condition.matchesPrefix) - ) + Array.isArray(rule.condition.matchesPrefix), + ), ); }); @@ -1435,8 +1435,8 @@ describe('storage', function () { (rule: LifecycleRule) => typeof rule.action === 'object' && rule.action.type === 'Delete' && - Array.isArray(rule.condition.matchesPrefix) - ) + Array.isArray(rule.condition.matchesPrefix), + ), ); }); @@ -1479,8 +1479,8 @@ describe('storage', function () { typeof rule.action === 'object' && rule.action.type === 'Delete' && rule.condition.noncurrentTimeBefore === NONCURRENT_TIME_BEFORE && - rule.condition.daysSinceNoncurrentTime === 100 - ) + rule.condition.daysSinceNoncurrentTime === 100, + ), ); }); @@ -1503,8 +1503,8 @@ describe('storage', function () { typeof rule.action === 'object' && rule.action.type === 'Delete' && rule.condition.customTimeBefore === CUSTOM_TIME_BEFORE && - rule.condition.daysSinceCustomTime === 100 - ) + rule.condition.daysSinceCustomTime === 100, + ), ); }); @@ -1604,7 +1604,7 @@ describe('storage', function () { await storage.createBucket(bucket.name); const [metadata] = await bucket.getMetadata(); assert( - [undefined, false].includes(metadata?.hierarchicalNamespace?.enabled) + [undefined, false].includes(metadata?.hierarchicalNamespace?.enabled), ); }); @@ -1614,7 +1614,7 @@ describe('storage', function () { }); const [metadata] = await bucket.getMetadata(); assert( - [undefined, false].includes(metadata?.hierarchicalNamespace?.enabled) + [undefined, false].includes(metadata?.hierarchicalNamespace?.enabled), ); }); @@ -1645,7 +1645,7 @@ describe('storage', function () { await bucket.getMetadata(); assert.strictEqual( bucket.metadata!.retentionPolicy!.retentionPeriod, - `${RETENTION_DURATION_SECONDS}` + `${RETENTION_DURATION_SECONDS}`, ); }); @@ -1656,7 +1656,7 @@ describe('storage', function () { await bucket.getMetadata(); assert.strictEqual( bucket.metadata!.retentionPolicy!.retentionPeriod, - `${RETENTION_DURATION_SECONDS}` + `${RETENTION_DURATION_SECONDS}`, ); }); @@ -1671,7 +1671,7 @@ describe('storage', function () { bucket.setRetentionPeriod(RETENTION_DURATION_SECONDS / 2), (err: ApiError) => { return err.code === 403; - } + }, ); }); @@ -1682,7 +1682,7 @@ describe('storage', function () { await bucket.getMetadata(); assert.strictEqual( bucket.metadata!.retentionPolicy!.retentionPeriod, - `${RETENTION_DURATION_SECONDS}` + `${RETENTION_DURATION_SECONDS}`, ); await bucket.removeRetentionPeriod(); @@ -1756,12 +1756,12 @@ describe('storage', function () { after(async () => { await new Promise(resolve => - setTimeout(resolve, RETENTION_PERIOD_SECONDS * 1000) + setTimeout(resolve, RETENTION_PERIOD_SECONDS * 1000), ); await Promise.all( FILES.map(async file => { return file.delete(); - }) + }), ); }); @@ -1849,7 +1849,7 @@ describe('storage', function () { const file = new File(objectRetentionBucket, fileName); const [metadata] = await file.setMetadata( {retention: null}, - {overrideUnlockedRetention: true} + {overrideUnlockedRetention: true}, ); assert.strictEqual(metadata.retention, undefined); }); @@ -1950,7 +1950,7 @@ describe('storage', function () { // Get the service account for the "second" account (the // one that will read the requester pays file). const clientEmail = JSON.parse( - fs.readFileSync(key2!, 'utf-8') + fs.readFileSync(key2!, 'utf-8'), ).client_email; policy.bindings.push({ role: 'roles/storage.admin', @@ -1999,7 +1999,7 @@ describe('storage', function () { * @returns The result of the successful request pays operation. */ async function requesterPaysDoubleTest( - testFunction: F + testFunction: F, ): Promise> { const failureMessage = 'Bucket is a requester pays bucket but no user project provided.'; @@ -2009,7 +2009,7 @@ describe('storage', function () { (err as Error).message.includes(failureMessage), `Expected '${ (err as Error).message - }' to include '${failureMessage}'` + }' to include '${failureMessage}'`, ); return true; }); @@ -2032,14 +2032,14 @@ describe('storage', function () { await bucketNonAllowList.combine( sourceFiles, destinationFile, - USER_PROJECT_OPTIONS + USER_PROJECT_OPTIONS, ); // eslint-disable-next-line @typescript-eslint/no-explicit-any function createFileAsync(fileObject: any) { return fileObject.file.save( fileObject.contents, - USER_PROJECT_OPTIONS + USER_PROJECT_OPTIONS, ); } }); @@ -2092,7 +2092,7 @@ describe('storage', function () { await requesterPaysDoubleTest(async options => { return bucketNonAllowList.setStorageClass( 'multi-regional', - options + options, ); }); }); @@ -2301,7 +2301,7 @@ describe('storage', function () { .on('end', () => { file.hash = hash.digest('base64'); resolve(); - }) + }), ); } await Promise.all(Object.keys(FILES).map(key => setHash(key))); @@ -2367,7 +2367,7 @@ describe('storage', function () { }, }, }), - /Metadata part is too large/ + /Metadata part is too large/, ); }); @@ -2440,7 +2440,7 @@ describe('storage', function () { }); assert.strictEqual( String(fileContents).slice(0, 20), - String(remoteContents) + String(remoteContents), ); }); @@ -2511,7 +2511,7 @@ describe('storage', function () { .on('response', raw => { assert.strictEqual( raw.toJSON().headers['content-encoding'], - undefined + undefined, ); }) .pipe(fs.createWriteStream(tmpFilePath)) @@ -2664,8 +2664,8 @@ describe('storage', function () { [ 'The target object is encrypted by a', 'customer-supplied encryption key.', - ].join(' ') - ) > -1 + ].join(' '), + ) > -1, ); }); }); @@ -2772,7 +2772,7 @@ describe('storage', function () { const projectIdRegExp = /^.+\/locations/; const actualKmsKeyName = metadata!.kmsKeyName!.replace( projectIdRegExp, - '' + '', ); let expectedKmsKeyName = kmsKeyName.replace(projectIdRegExp, ''); @@ -2792,7 +2792,7 @@ describe('storage', function () { const projectIdRegExp = /^.+\/locations/; const actualKmsKeyName = metadata!.kmsKeyName!.replace( projectIdRegExp, - '' + '', ); let expectedKmsKeyName = kmsKeyName.replace(projectIdRegExp, ''); @@ -2832,7 +2832,7 @@ describe('storage', function () { beforeEach(async () => { await new Promise(res => - setTimeout(res, BUCKET_METADATA_UPDATE_WAIT_TIME) + setTimeout(res, BUCKET_METADATA_UPDATE_WAIT_TIME), ); await bucket.setMetadata({ encryption: { @@ -2843,7 +2843,7 @@ describe('storage', function () { afterEach(async () => { await new Promise(res => - setTimeout(res, BUCKET_METADATA_UPDATE_WAIT_TIME) + setTimeout(res, BUCKET_METADATA_UPDATE_WAIT_TIME), ); await bucket.setMetadata({ encryption: null, @@ -2858,7 +2858,7 @@ describe('storage', function () { const actualKmsKeyName = metadata!.encryption!.defaultKmsKeyName!.replace( projectIdRegExp, - '' + '', ); const expectedKmsKeyName = kmsKeyName.replace(projectIdRegExp, ''); assert.strictEqual(actualKmsKeyName, expectedKmsKeyName); @@ -2870,7 +2870,7 @@ describe('storage', function () { await createCryptoKeyAsync(cryptoKeyId); await new Promise(res => - setTimeout(res, BUCKET_METADATA_UPDATE_WAIT_TIME) + setTimeout(res, BUCKET_METADATA_UPDATE_WAIT_TIME), ); await bucket.setMetadata({ encryption: { @@ -2887,7 +2887,7 @@ describe('storage', function () { assert.strictEqual( fileMetadata.kmsKeyName, - `${metadata!.encryption!.defaultKmsKeyName}/cryptoKeyVersions/1` + `${metadata!.encryption!.defaultKmsKeyName}/cryptoKeyVersions/1`, ); }); }); @@ -2915,7 +2915,7 @@ describe('storage', function () { const [metadata] = await copiedFile.getMetadata(); assert.strictEqual( typeof metadata!.metadata!.originalProperty, - 'undefined' + 'undefined', ); assert.strictEqual(metadata!.metadata!.newProperty, 'true'); await Promise.all([file.delete, copiedFile.delete()]); @@ -3003,7 +3003,7 @@ describe('storage', function () { async function uploadAndVerify( file: File, - options: Omit + options: Omit, ) { await bucket.upload(filePath, { destination: file, @@ -3126,11 +3126,13 @@ describe('storage', function () { const [contents] = await destinationFile.download(); assert.strictEqual( contents.toString(), - files.map(x => x.contents).join('') + files.map(x => x.contents).join(''), ); await Promise.all( - sourceFiles.concat([destinationFile]).map(file => deleteFileAsync(file)) + sourceFiles + .concat([destinationFile]) + .map(file => deleteFileAsync(file)), ); }); }); @@ -3156,7 +3158,7 @@ describe('storage', function () { const ms = Math.pow(2, retries) * 1000 + Math.random() * 1000; return new Promise(done => { console.info( - `retrying "${test.title}" with accessId ${accessId} in ${ms}ms` + `retrying "${test.title}" with accessId ${accessId} in ${ms}ms`, ); setTimeout(done, ms); }); @@ -3198,7 +3200,7 @@ describe('storage', function () { assert(hmacKeys.length > 0); assert( hmacKeys.some(hmacKey => hmacKey.id === accessId), - 'created HMAC key not found from getHmacKeys result' + 'created HMAC key not found from getHmacKeys result', ); }); @@ -3227,7 +3229,7 @@ describe('storage', function () { assert(Array.isArray(hmacKeys)); assert( !hmacKeys.some(hmacKey => hmacKey.id === accessId), - 'deleted HMAC key is found from getHmacKeys result' + 'deleted HMAC key is found from getHmacKeys result', ); }); @@ -3262,16 +3264,17 @@ describe('storage', function () { const [hmacKeys] = await storage.getHmacKeys({projectId: HMAC_PROJECT}); assert( hmacKeys.some( - hmacKey => hmacKey.metadata!.serviceAccountEmail === SERVICE_ACCOUNT + hmacKey => + hmacKey.metadata!.serviceAccountEmail === SERVICE_ACCOUNT, ), - `Expected at least 1 key for service account: ${SERVICE_ACCOUNT}` + `Expected at least 1 key for service account: ${SERVICE_ACCOUNT}`, ); assert( hmacKeys.some( hmacKey => - hmacKey.metadata!.serviceAccountEmail === SECOND_SERVICE_ACCOUNT + hmacKey.metadata!.serviceAccountEmail === SECOND_SERVICE_ACCOUNT, ), - `Expected at least 1 key for service account: ${SECOND_SERVICE_ACCOUNT}` + `Expected at least 1 key for service account: ${SECOND_SERVICE_ACCOUNT}`, ); }); @@ -3283,9 +3286,9 @@ describe('storage', function () { assert( hmacKeys.every( hmacKey => - hmacKey.metadata!.serviceAccountEmail === SECOND_SERVICE_ACCOUNT + hmacKey.metadata!.serviceAccountEmail === SECOND_SERVICE_ACCOUNT, ), - 'HMAC key belonging to other service accounts unexpected' + 'HMAC key belonging to other service accounts unexpected', ); }); }); @@ -3346,7 +3349,7 @@ describe('storage', function () { assert.deepStrictEqual( (result as {prefixes: string[]}).prefixes, - expected + expected, ); }); @@ -3487,7 +3490,7 @@ describe('storage', function () { assert.strictEqual(files![0].name, files![1].name); assert.notStrictEqual( files![0].metadata.generation, - files![1].metadata.generation + files![1].metadata.generation, ); }); @@ -3503,7 +3506,7 @@ describe('storage', function () { assert.strictEqual(err.code, 412); assert.strictEqual(err.errors![0].reason, 'conditionNotMet'); return true; - } + }, ); await bucketWithVersioning .file(fileName) @@ -3564,7 +3567,7 @@ describe('storage', function () { await fetch(signedDeleteUrl, {method: 'DELETE'}); assert.rejects( () => file.getMetadata(), - (err: ApiError) => err.code === 404 + (err: ApiError) => err.code === 404, ); }); }); @@ -3638,10 +3641,10 @@ describe('storage', function () { assert(err instanceof Error); assert.strictEqual( err.message, - `Max allowed expiration is seven days (${SEVEN_DAYS_IN_SECONDS.toString()} seconds).` + `Max allowed expiration is seven days (${SEVEN_DAYS_IN_SECONDS.toString()} seconds).`, ); return true; - } + }, ); }); @@ -3824,7 +3827,7 @@ describe('storage', function () { topic.name, { eventTypes: ['OBJECT_FINALIZE'], - } + }, ); notification = createNotificationData[0]; subscription = topic.subscription(generateName()); @@ -3949,10 +3952,10 @@ describe('storage', function () { const TEST_UNIVERSE_DOMAIN = isNullOrUndefined('TEST_UNIVERSE_DOMAIN'); const TEST_PROJECT_ID = isNullOrUndefined('TEST_UNIVERSE_PROJECT_ID'); const TEST_UNIVERSE_LOCATION = isNullOrUndefined( - 'TEST_UNIVERSE_LOCATION' + 'TEST_UNIVERSE_LOCATION', ); const CREDENTIAL_PATH = isNullOrUndefined( - 'TEST_UNIVERSE_DOMAIN_CREDENTIAL' + 'TEST_UNIVERSE_DOMAIN_CREDENTIAL', ); // Create a client with universe domain credentials universeDomainStorage = new Storage({ @@ -4019,13 +4022,13 @@ describe('storage', function () { function deleteBucket( bucket: Bucket, options: {}, - callback: DeleteBucketCallback + callback: DeleteBucketCallback, ): void; function deleteBucket(bucket: Bucket, callback: DeleteBucketCallback): void; function deleteBucket( bucket: Bucket, optsOrCb: {} | DeleteBucketCallback, - callback?: DeleteBucketCallback + callback?: DeleteBucketCallback, ) { let options = typeof optsOrCb === 'object' ? optsOrCb : {}; callback = @@ -4075,10 +4078,10 @@ describe('storage', function () { const [buckets] = await storage.getBuckets({prefix: TESTS_PREFIX}); const limit = pLimit(10); await new Promise(resolve => - setTimeout(resolve, RETENTION_DURATION_SECONDS * 1000) + setTimeout(resolve, RETENTION_DURATION_SECONDS * 1000), ); return Promise.all( - buckets.map(bucket => limit(() => deleteBucketAsync(bucket))) + buckets.map(bucket => limit(() => deleteBucketAsync(bucket))), ); } @@ -4090,7 +4093,7 @@ describe('storage', function () { }); const limit = pLimit(10); return Promise.all( - filteredTopics.map(topic => limit(() => deleteTopicAsync(topic))) + filteredTopics.map(topic => limit(() => deleteTopicAsync(topic))), ); } @@ -4117,7 +4120,7 @@ describe('storage', function () { async function deleteStaleHmacKeys( serviceAccountEmail: string, - projectId: string + projectId: string, ) { const old = new Date(); old.setHours(old.getHours() - 1); @@ -4137,8 +4140,8 @@ describe('storage', function () { limit(async () => { await hmacKey.setMetadata({state: 'INACTIVE'}); await hmacKey.delete(); - }) - ) + }), + ), ); } diff --git a/test/acl.ts b/test/acl.ts index 5c1d73e25..975e786d9 100644 --- a/test/acl.ts +++ b/test/acl.ts @@ -149,7 +149,7 @@ describe('storage/acl', () => { (err: Error, acls: {}, apiResponse: unknown) => { assert.deepStrictEqual(resp, apiResponse); done(); - } + }, ); }); }); @@ -443,7 +443,7 @@ describe('storage/acl', () => { (err: Error, acls: Array<{}>, apiResponse: unknown) => { assert.deepStrictEqual(resp, apiResponse); done(); - } + }, ); }); }); @@ -594,7 +594,7 @@ describe('storage/AclRoleAccessorMethods', () => { entity: 'user-' + fakeUser, role: fakeRole, }, - fakeOptions + fakeOptions, ); aclEntity.add = (options: {}) => { diff --git a/test/bucket.ts b/test/bucket.ts index 3935f9b72..a5ea54811 100644 --- a/test/bucket.ts +++ b/test/bucket.ts @@ -361,7 +361,7 @@ describe('Bucket', () => { }); assert.deepStrictEqual( bucket.instancePreconditionOpts, - options.preconditionOpts + options.preconditionOpts, ); }); @@ -381,7 +381,7 @@ describe('Bucket', () => { }); assert.deepStrictEqual( bucket.instancePreconditionOpts, - options.preconditionOpts + options.preconditionOpts, ); }); @@ -401,7 +401,7 @@ describe('Bucket', () => { }); assert.deepStrictEqual( bucket.instancePreconditionOpts, - options.preconditionOpts + options.preconditionOpts, ); }); @@ -421,7 +421,7 @@ describe('Bucket', () => { }); assert.deepStrictEqual( bucket.instancePreconditionOpts, - options.preconditionOpts + options.preconditionOpts, ); }); @@ -704,7 +704,7 @@ describe('Bucket', () => { destination.request = (reqOpts: DecorateRequestOptions) => { assert.strictEqual( reqOpts.json.destination.contentType, - mime.getType(destination.name) + mime.getType(destination.name), ); done(); @@ -720,7 +720,7 @@ describe('Bucket', () => { destination.request = (reqOpts: DecorateRequestOptions) => { assert.strictEqual( reqOpts.json.destination.contentType, - destination.metadata.contentType + destination.metadata.contentType, ); done(); @@ -735,7 +735,7 @@ describe('Bucket', () => { destination.request = (reqOpts: DecorateRequestOptions) => { assert.strictEqual( reqOpts.json.destination.contentType, - mime.getType(destination.name) + mime.getType(destination.name), ); done(); @@ -825,19 +825,19 @@ describe('Bucket', () => { destination.request = (reqOpts: DecorateRequestOptions) => { assert.strictEqual( reqOpts.qs.ifGenerationMatch, - options.ifGenerationMatch + options.ifGenerationMatch, ); assert.strictEqual( reqOpts.qs.ifGenerationNotMatch, - options.ifGenerationNotMatch + options.ifGenerationNotMatch, ); assert.strictEqual( reqOpts.qs.ifMetagenerationMatch, - options.ifMetagenerationMatch + options.ifMetagenerationMatch, ); assert.strictEqual( reqOpts.qs.ifMetagenerationNotMatch, - options.ifMetagenerationNotMatch + options.ifMetagenerationNotMatch, ); done(); }; @@ -851,7 +851,7 @@ describe('Bucket', () => { destination.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(); }; @@ -867,7 +867,7 @@ describe('Bucket', () => { destination.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(error); }; @@ -885,7 +885,7 @@ describe('Bucket', () => { destination.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, resp); }; @@ -896,7 +896,7 @@ describe('Bucket', () => { (err: Error, obj: {}, apiResponse: {}) => { assert.strictEqual(resp, apiResponse); done(); - } + }, ); }); @@ -906,7 +906,7 @@ describe('Bucket', () => { destination.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { assert.strictEqual(reqOpts.maxRetries, 0); callback(); @@ -972,7 +972,7 @@ describe('Bucket', () => { beforeEach(() => { bucket.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(error, apiResponse); }; @@ -988,7 +988,7 @@ describe('Bucket', () => { assert.strictEqual(apiResponse_, apiResponse); done(); - } + }, ); }); }); @@ -1001,7 +1001,7 @@ describe('Bucket', () => { beforeEach(() => { bucket.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, apiResponse); }; @@ -1025,7 +1025,7 @@ describe('Bucket', () => { assert.strictEqual(channel_.metadata, apiResponse); assert.strictEqual(apiResponse_, apiResponse); done(); - } + }, ); }); }); @@ -1061,7 +1061,7 @@ describe('Bucket', () => { const expectedTopic = PUBSUB_SERVICE_PATH + topic; const expectedJson = Object.assign( {topic: expectedTopic}, - convertObjKeysToSnakeCase(options) + convertObjKeysToSnakeCase(options), ); bucket.request = (reqOpts: DecorateRequestOptions) => { @@ -1144,7 +1144,7 @@ describe('Bucket', () => { bucket.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(error, response); }; @@ -1156,7 +1156,7 @@ describe('Bucket', () => { assert.strictEqual(notification, null); assert.strictEqual(resp, response); done(); - } + }, ); }); @@ -1167,7 +1167,7 @@ describe('Bucket', () => { bucket.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, response); }; @@ -1185,7 +1185,7 @@ describe('Bucket', () => { assert.strictEqual(notification.metadata, response); assert.strictEqual(resp, response); done(); - } + }, ); }); }); @@ -1485,7 +1485,7 @@ describe('Bucket', () => { bucket.setMetadata = ( metadata: {}, _optionsOrCallback: {}, - callback: Function + callback: Function, ) => { assert.deepStrictEqual(metadata, { billing: { @@ -1502,7 +1502,7 @@ describe('Bucket', () => { bucket.setMetadata = ( metadata: {}, optionsOrCallback: {}, - callback: Function + callback: Function, ) => { assert.strictEqual(callback, undefined); done(); @@ -1553,7 +1553,7 @@ describe('Bucket', () => { { bucket: 'bucket-name', }, - assert.ifError + assert.ifError, ), BucketExceptionMessages.CONFIGURATION_OBJECT_PREFIX_REQUIRED; }); @@ -1635,7 +1635,7 @@ describe('Bucket', () => { prefix: PREFIX, bucket: bucketName, }, - assert.ifError + assert.ifError, ); }); @@ -1645,7 +1645,7 @@ describe('Bucket', () => { bucket.setMetadata = (metadata: BucketMetadata) => { assert.deepStrictEqual( metadata!.logging!.logBucket, - bucketForLogging.id + bucketForLogging.id, ); setImmediate(done); return Promise.resolve([]); @@ -1656,7 +1656,7 @@ describe('Bucket', () => { prefix: PREFIX, bucket: bucketForLogging, }, - assert.ifError + assert.ifError, ); }); @@ -1666,10 +1666,10 @@ describe('Bucket', () => { bucket.setMetadata = ( metadata: {}, optionsOrCallback: {}, - callback: Function + callback: Function, ) => { Promise.resolve([setMetadataResponse]).then(resp => - callback(null, ...resp) + callback(null, ...resp), ); }; @@ -1679,7 +1679,7 @@ describe('Bucket', () => { assert.ifError(err); assert.strictEqual(response, setMetadataResponse); done(); - } + }, ); }); @@ -1702,7 +1702,7 @@ describe('Bucket', () => { bucket.setMetadata = ( metadata: {}, optionsOrCallback: {}, - callback: Function + callback: Function, ) => { assert.deepStrictEqual(metadata, { billing: { @@ -1719,7 +1719,7 @@ describe('Bucket', () => { bucket.setMetadata = ( metadata: {}, optionsOrCallback: {}, - callback: Function + callback: Function, ) => { assert.equal(callback, undefined); done(); @@ -1792,7 +1792,7 @@ describe('Bucket', () => { delimiter: '/', autoPaginate: false, }, - util.noop + util.noop, ); }); @@ -1800,7 +1800,7 @@ describe('Bucket', () => { const token = 'next-page-token'; bucket.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, {nextPageToken: token, items: []}); }; @@ -1809,14 +1809,14 @@ describe('Bucket', () => { (err: Error, results: {}, nextQuery: GetFilesOptions) => { assert.strictEqual(nextQuery.pageToken, token); assert.strictEqual(nextQuery.maxResults, 5); - } + }, ); }); it('should return null nextQuery if there are no more results', () => { bucket.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, {items: []}); }; @@ -1824,14 +1824,14 @@ describe('Bucket', () => { {maxResults: 5}, (err: Error, results: {}, nextQuery: {}) => { assert.strictEqual(nextQuery, null); - } + }, ); }); it('should return File objects', done => { bucket.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, { items: [{name: 'fake-file-name', generation: 1}], @@ -1842,7 +1842,7 @@ describe('Bucket', () => { assert(files[0] instanceof FakeFile); assert.strictEqual( typeof files[0].calledWith_[2].generation, - 'undefined' + 'undefined', ); done(); }); @@ -1851,7 +1851,7 @@ describe('Bucket', () => { it('should return versioned Files if queried for versions', done => { bucket.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, { items: [{name: 'fake-file-name', generation: 1}], @@ -1869,7 +1869,7 @@ describe('Bucket', () => { it('should return Files with specified values if queried for fields', done => { bucket.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, { items: [{name: 'fake-file-name'}], @@ -1882,7 +1882,7 @@ describe('Bucket', () => { assert.ifError(err); assert.strictEqual(files[0].name, 'fake-file-name'); done(); - } + }, ); }); @@ -1890,7 +1890,7 @@ describe('Bucket', () => { const softDeletedTime = new Date('1/1/2024').toISOString(); bucket.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, { items: [{name: 'fake-file-name', generation: 1, softDeletedTime}], @@ -1910,7 +1910,7 @@ describe('Bucket', () => { bucket.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, { items: [{name: 'fake-file-name', kmsKeyName}], @@ -1928,7 +1928,7 @@ describe('Bucket', () => { const resp = {items: [{name: 'fake-file-name'}]}; bucket.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, resp); }; @@ -1936,7 +1936,7 @@ describe('Bucket', () => { (err: Error, files: Array<{}>, nextQuery: {}, apiResponse: {}) => { assert.deepStrictEqual(resp, apiResponse); done(); - } + }, ); }); @@ -1946,7 +1946,7 @@ describe('Bucket', () => { bucket.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(error, apiResponse); }; @@ -1959,7 +1959,7 @@ describe('Bucket', () => { assert.strictEqual(apiResponse_, apiResponse); done(); - } + }, ); }); @@ -1973,7 +1973,7 @@ describe('Bucket', () => { }; bucket.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, {items: [fileMetadata]}); }; @@ -2079,7 +2079,7 @@ describe('Bucket', () => { bucket.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(error, response); }; @@ -2090,7 +2090,7 @@ describe('Bucket', () => { assert.strictEqual(notifications, null); assert.strictEqual(resp, response); done(); - } + }, ); }); @@ -2100,7 +2100,7 @@ describe('Bucket', () => { bucket.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, response); }; @@ -2123,7 +2123,7 @@ describe('Bucket', () => { }); assert.strictEqual(resp, response); done(); - } + }, ); }); }); @@ -2149,7 +2149,7 @@ describe('Bucket', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any urlSignerStub = (sandbox.stub as any)(fakeSigner, 'URLSigner').returns( - signer + signer, ); SIGNED_URL_CONFIG = { @@ -2188,7 +2188,7 @@ describe('Bucket', () => { signingEndpoint: undefined, }); done(); - } + }, ); }); }); @@ -2206,7 +2206,7 @@ describe('Bucket', () => { bucket.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { assert.deepStrictEqual(reqOpts, { method: 'POST', @@ -2242,7 +2242,7 @@ describe('Bucket', () => { bucket.makeAllFilesPublicPrivate_ = ( opts: MakeAllFilesPublicPrivateOptions, - callback: Function + callback: Function, ) => { assert.strictEqual(opts.private, true); assert.strictEqual(opts.force, true); @@ -2288,7 +2288,7 @@ describe('Bucket', () => { it('should not make files private by default', done => { bucket.parent.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(); }; @@ -2305,7 +2305,7 @@ describe('Bucket', () => { bucket.parent.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(error); }; @@ -2321,7 +2321,7 @@ describe('Bucket', () => { beforeEach(() => { bucket.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(); }; @@ -2348,7 +2348,7 @@ describe('Bucket', () => { bucket.makeAllFilesPublicPrivate_ = ( opts: MakeAllFilesPublicPrivateOptions, - callback: Function + callback: Function, ) => { assert.strictEqual(opts.public, true); assert.strictEqual(opts.force, true); @@ -2367,7 +2367,7 @@ describe('Bucket', () => { assert(didSetDefaultAcl); assert(didMakeFilesPublic); done(); - } + }, ); }); @@ -2412,7 +2412,7 @@ describe('Bucket', () => { bucket.setMetadata = ( metadata: {}, _optionsOrCallback: {}, - callback: Function + callback: Function, ) => { assert.deepStrictEqual(metadata, { retentionPolicy: null, @@ -2434,7 +2434,7 @@ describe('Bucket', () => { it('should set the userProject if qs is undefined', done => { FakeServiceObject.prototype.request = (( - reqOpts: DecorateRequestOptions + reqOpts: DecorateRequestOptions, ) => { assert.strictEqual(reqOpts.qs.userProject, USER_PROJECT); done(); @@ -2452,7 +2452,7 @@ describe('Bucket', () => { }; FakeServiceObject.prototype.request = (( - reqOpts: DecorateRequestOptions + reqOpts: DecorateRequestOptions, ) => { assert.strictEqual(reqOpts.qs.userProject, USER_PROJECT); assert.strictEqual(reqOpts.qs, options.qs); @@ -2472,7 +2472,7 @@ describe('Bucket', () => { }; FakeServiceObject.prototype.request = (( - reqOpts: DecorateRequestOptions + reqOpts: DecorateRequestOptions, ) => { assert.strictEqual(reqOpts.qs.userProject, fakeUserProject); done(); @@ -2503,7 +2503,7 @@ describe('Bucket', () => { bucket.setMetadata = ( metadata: BucketMetadata, _callbackOrOptions: {}, - callback: Function + callback: Function, ) => { assert.strictEqual(metadata.labels, labels); Promise.resolve([]).then(resp => callback(null, ...resp)); @@ -2529,7 +2529,7 @@ describe('Bucket', () => { bucket.setMetadata = ( metadata: {}, _callbackOrOptions: {}, - callback: Function + callback: Function, ) => { assert.deepStrictEqual(metadata, { retentionPolicy: { @@ -2551,7 +2551,7 @@ describe('Bucket', () => { bucket.setMetadata = ( metadata: {}, _callbackOrOptions: {}, - callback: Function + callback: Function, ) => { assert.deepStrictEqual(metadata, { cors: corsConfiguration, @@ -2591,7 +2591,7 @@ describe('Bucket', () => { bucket.setMetadata = ( metadata: BucketMetadata, options: {}, - callback: Function + callback: Function, ) => { assert.deepStrictEqual(metadata, {storageClass: STORAGE_CLASS}); assert.strictEqual(options, OPTIONS); @@ -2622,14 +2622,14 @@ describe('Bucket', () => { methods.forEach(method => { assert.strictEqual( bucket.methods[method].reqOpts.qs.userProject, - undefined + undefined, ); }); bucket.setUserProject(USER_PROJECT); methods.forEach(method => { assert.strictEqual( bucket.methods[method].reqOpts.qs.userProject, - USER_PROJECT + USER_PROJECT, ); }); }); @@ -2639,12 +2639,12 @@ describe('Bucket', () => { const basename = 'testfile.json'; const filepath = path.join( getDirName(), - '../../../test/testdata/' + basename + '../../../test/testdata/' + basename, ); const nonExistentFilePath = path.join( getDirName(), '../../../test/testdata/', - 'non-existent-file' + 'non-existent-file', ); const metadata = { metadata: { @@ -2805,7 +2805,7 @@ describe('Bucket', () => { _transform( chunk: string | Buffer, _encoding: string, - done: Function + done: Function, ) { this.push(chunk); setTimeout(() => { @@ -2886,7 +2886,7 @@ describe('Bucket', () => { _transform( chunk: string | Buffer, _encoding: string, - done: Function + done: Function, ) { this.push(chunk); setTimeout(() => { @@ -2933,7 +2933,7 @@ describe('Bucket', () => { _transform( chunk: string | Buffer, _encoding: string, - done: Function + done: Function, ) { this.push(chunk); setTimeout(() => { @@ -2991,7 +2991,7 @@ describe('Bucket', () => { setImmediate(() => { assert.strictEqual( options!.metadata!.contentType, - metadata.contentType + metadata.contentType, ); done(); }); @@ -3059,7 +3059,7 @@ describe('Bucket', () => { assert.strictEqual(file, fakeFile); assert.strictEqual(apiResponse, metadata); done(); - } + }, ); }); @@ -3169,7 +3169,7 @@ describe('Bucket', () => { (errs: Error[]) => { assert.deepStrictEqual(errs, [error, error]); done(); - } + }, ); }); @@ -3198,7 +3198,7 @@ describe('Bucket', () => { assert.deepStrictEqual(errs, [error, error]); assert.deepStrictEqual(files, successFiles); done(); - } + }, ); }); }); @@ -3212,7 +3212,7 @@ describe('Bucket', () => { it('should set autoRetry to false when ifMetagenerationMatch is undefined (setMetadata)', done => { bucket.disableAutoRetryConditionallyIdempotent_( bucket.methods.setMetadata, - AvailableServiceObjectMethods.setMetadata + AvailableServiceObjectMethods.setMetadata, ); assert.strictEqual(bucket.storage.retryOptions.autoRetry, false); done(); @@ -3221,7 +3221,7 @@ describe('Bucket', () => { it('should set autoRetry to false when ifMetagenerationMatch is undefined (delete)', done => { bucket.disableAutoRetryConditionallyIdempotent_( bucket.methods.delete, - AvailableServiceObjectMethods.delete + AvailableServiceObjectMethods.delete, ); assert.strictEqual(bucket.storage.retryOptions.autoRetry, false); done(); @@ -3236,7 +3236,7 @@ describe('Bucket', () => { }); bucket.disableAutoRetryConditionallyIdempotent_( bucket.methods.delete, - AvailableServiceObjectMethods.delete + AvailableServiceObjectMethods.delete, ); assert.strictEqual(bucket.storage.retryOptions.autoRetry, false); done(); @@ -3250,7 +3250,7 @@ describe('Bucket', () => { }); bucket.disableAutoRetryConditionallyIdempotent_( bucket.methods.delete, - AvailableServiceObjectMethods.delete + AvailableServiceObjectMethods.delete, ); assert.strictEqual(bucket.storage.retryOptions.autoRetry, true); done(); diff --git a/test/channel.ts b/test/channel.ts index e70272f20..b0ef1204d 100644 --- a/test/channel.ts +++ b/test/channel.ts @@ -112,7 +112,7 @@ describe('Channel', () => { channel.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(error, apiResponse); }; @@ -127,7 +127,7 @@ describe('Channel', () => { it('should not require a callback', done => { channel.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { assert.doesNotThrow(() => callback()); done(); diff --git a/test/crc32c.ts b/test/crc32c.ts index 4a14af96b..83a909abe 100644 --- a/test/crc32c.ts +++ b/test/crc32c.ts @@ -67,7 +67,7 @@ describe('CRC32C', () => { assert.equal( result, expected, - `Expected '${input}' to produce \`${expected}\` - not \`${result}\`` + `Expected '${input}' to produce \`${expected}\` - not \`${result}\``, ); } }); @@ -87,7 +87,7 @@ describe('CRC32C', () => { assert.equal( result, expected, - `Expected '${input}' to produce \`${expected}\` - not \`${result}\`` + `Expected '${input}' to produce \`${expected}\` - not \`${result}\``, ); } }); @@ -324,7 +324,7 @@ describe('CRC32C', () => { assert.throws( () => CRC32C.from(arrayBufferView.buffer), - expectedError + expectedError, ); } }); diff --git a/test/file.ts b/test/file.ts index cfbb46597..0890fabc0 100644 --- a/test/file.ts +++ b/test/file.ts @@ -83,7 +83,7 @@ const fakeUtil = Object.assign({}, util, { makeRequest( reqOpts: DecorateRequestOptions, config: object, - callback: BodyResponseCallback + callback: BodyResponseCallback, ) { callback(null); }, @@ -195,7 +195,7 @@ describe('File', () => { // crc32c hash of `zlib.gzipSync(Buffer.from(DATA), {level: 9})` const GZIPPED_DATA = Buffer.from( 'H4sIAAAAAAACEytJLS5RSEksSQQAsq4I0wkAAAA=', - 'base64' + 'base64', ); //crc32c hash of `GZIPPED_DATA` const CRC32C_HASH_GZIP = '64jygg=='; @@ -285,7 +285,7 @@ describe('File', () => { it('should set instanceRetryValue to the storage insance retryOptions.autoRetry value', () => { assert.strictEqual( file.instanceRetryValue, - STORAGE.retryOptions.autoRetry + STORAGE.retryOptions.autoRetry, ); }); @@ -369,7 +369,7 @@ describe('File', () => { }); assert.deepStrictEqual( file.instancePreconditionOpts, - options.preconditionOpts + options.preconditionOpts, ); }); @@ -388,7 +388,7 @@ describe('File', () => { }); assert.deepStrictEqual( file.instancePreconditionOpts, - options.preconditionOpts + options.preconditionOpts, ); }); @@ -407,7 +407,7 @@ describe('File', () => { }); assert.deepStrictEqual( file.instancePreconditionOpts, - options.preconditionOpts + options.preconditionOpts, ); }); @@ -426,7 +426,7 @@ describe('File', () => { }); assert.deepStrictEqual( file.instancePreconditionOpts, - options.preconditionOpts + options.preconditionOpts, ); }); @@ -618,7 +618,7 @@ describe('File', () => { file.request = (reqOpts: DecorateRequestOptions) => { assert.strictEqual( reqOpts.qs.destinationKmsKeyName, - newFile.kmsKeyName + newFile.kmsKeyName, ); assert.strictEqual(file.kmsKeyName, newFile.kmsKeyName); done(); @@ -634,7 +634,7 @@ describe('File', () => { file.request = (reqOpts: DecorateRequestOptions) => { assert.strictEqual( reqOpts.qs.destinationKmsKeyName, - destinationKmsKeyName + destinationKmsKeyName, ); assert.strictEqual(file.kmsKeyName, destinationKmsKeyName); done(); @@ -651,7 +651,7 @@ describe('File', () => { file.request = (reqOpts: DecorateRequestOptions) => { assert.strictEqual( reqOpts.qs.destinationPredefinedAcl, - options.predefinedAcl + options.predefinedAcl, ); assert.strictEqual(reqOpts.json.destinationPredefinedAcl, undefined); done(); @@ -668,7 +668,7 @@ describe('File', () => { file.request = (reqOpts: DecorateRequestOptions) => { assert.strictEqual( reqOpts.qs.destinationKmsKeyName, - destinationKmsKeyName + destinationKmsKeyName, ); assert.strictEqual(file.kmsKeyName, destinationKmsKeyName); done(); @@ -698,7 +698,7 @@ describe('File', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any file: any, expectedPath: string, - callback: Function + callback: Function, ) { file.request = (reqOpts: DecorateRequestOptions) => { assert.strictEqual(reqOpts.uri, expectedPath); @@ -760,7 +760,7 @@ describe('File', () => { beforeEach(() => { file.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, apiResponse); }; @@ -771,7 +771,7 @@ describe('File', () => { file.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { file.copy = (newFile_: {}, options: {}, callback: Function) => { assert.strictEqual(newFile_, newFile); @@ -793,7 +793,7 @@ describe('File', () => { file.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any file.copy = (newFile_: {}, options: any) => { @@ -816,13 +816,13 @@ describe('File', () => { file.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any file.copy = (newFile_: {}, options: any) => { assert.strictEqual( options.destinationKmsKeyName, - fakeOptions.destinationKmsKeyName + fakeOptions.destinationKmsKeyName, ); done(); }; @@ -850,7 +850,7 @@ describe('File', () => { const resp = {success: true}; file.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, resp); }; @@ -974,7 +974,7 @@ describe('File', () => { err: Error, res: {}, body: {}, - callback: Function + callback: Function, ) => { const rawResponseStream = new PassThrough(); Object.assign(rawResponseStream, { @@ -1184,7 +1184,7 @@ describe('File', () => { err: Error, res: {}, body: {}, - callback: Function + callback: Function, ) => { callback(ERROR, null, res); setImmediate(() => { @@ -1222,7 +1222,7 @@ describe('File', () => { err: Error, res: {}, body: {}, - callback: Function + callback: Function, ) => { callback(null, null, rawResponseStream); setImmediate(() => { @@ -1259,7 +1259,7 @@ describe('File', () => { err: Error, res: {}, body: {}, - callback: Function + callback: Function, ) => { callback(null, null, rawResponseStream); setImmediate(() => { @@ -1295,7 +1295,7 @@ describe('File', () => { err: Error, res: {}, body: {}, - callback: Function + callback: Function, ) => { const rawResponseStream = new PassThrough(); Object.assign(rawResponseStream, { @@ -1334,7 +1334,7 @@ describe('File', () => { assert.equal( Buffer.compare(Buffer.concat(collection), GZIPPED_DATA), - 0 + 0, ); }); @@ -1393,7 +1393,7 @@ describe('File', () => { err: Error, res: {}, body: {}, - callback: Function + callback: Function, ) => { const rawResponseStream = new PassThrough(); Object.assign(rawResponseStream, { @@ -1436,7 +1436,7 @@ describe('File', () => { err: Error, res: {}, body: {}, - callback: Function + callback: Function, ) => { const rawResponseStream = new PassThrough(); Object.assign(rawResponseStream, { @@ -1469,7 +1469,7 @@ describe('File', () => { err: Error, res: {}, body: {}, - callback: Function + callback: Function, ) => { const rawResponseStream = new PassThrough(); Object.assign(rawResponseStream, { @@ -1614,7 +1614,7 @@ describe('File', () => { err: Error, res: {}, body: {}, - callback: Function + callback: Function, ) => { const rawResponseStream = new PassThrough(); Object.assign(rawResponseStream, { @@ -1657,7 +1657,7 @@ describe('File', () => { err: Error, res: {}, body: {}, - callback: Function + callback: Function, ) => { const rawResponseStream = new PassThrough(); Object.assign(rawResponseStream, { @@ -1694,7 +1694,7 @@ describe('File', () => { setImmediate(() => { assert.strictEqual( opts.headers!.Range, - 'bytes=' + startOffset + '-' + 'bytes=' + startOffset + '-', ); done(); }); @@ -1849,23 +1849,23 @@ describe('File', () => { assert.strictEqual(opts.userProject, options.userProject); assert.strictEqual( opts.retryOptions.autoRetry, - options.retryOptions.autoRetry + options.retryOptions.autoRetry, ); assert.strictEqual( opts.retryOptions.maxRetries, - options.retryOptions.maxRetries + options.retryOptions.maxRetries, ); assert.strictEqual( opts.retryOptions.maxRetryDelay, - options.retryOptions.maxRetryDelay + options.retryOptions.maxRetryDelay, ); assert.strictEqual( opts.retryOptions.retryDelayMultipier, - options.retryOptions.retryDelayMultipier + options.retryOptions.retryDelayMultipier, ); assert.strictEqual( opts.retryOptions.totalTimeout, - options.retryOptions.totalTimeout + options.retryOptions.totalTimeout, ); assert.strictEqual(opts.params, options.preconditionOpts); @@ -1928,23 +1928,23 @@ describe('File', () => { assert.strictEqual(opts.userProject, options.userProject); assert.strictEqual( opts.retryOptions.autoRetry, - options.retryOptions.autoRetry + options.retryOptions.autoRetry, ); assert.strictEqual( opts.retryOptions.maxRetries, - options.retryOptions.maxRetries + options.retryOptions.maxRetries, ); assert.strictEqual( opts.retryOptions.maxRetryDelay, - options.retryOptions.maxRetryDelay + options.retryOptions.maxRetryDelay, ); assert.strictEqual( opts.retryOptions.retryDelayMultipier, - options.retryOptions.retryDelayMultipier + options.retryOptions.retryDelayMultipier, ); assert.strictEqual( opts.retryOptions.totalTimeout, - options.retryOptions.totalTimeout + options.retryOptions.totalTimeout, ); assert.strictEqual(opts.params, file.instancePreconditionOpts); @@ -1993,7 +1993,7 @@ describe('File', () => { it('should emit RangeError', done => { const error = new RangeError( - 'Cannot provide an `offset` without providing a `uri`' + 'Cannot provide an `offset` without providing a `uri`', ); const opitons = { @@ -2203,7 +2203,7 @@ describe('File', () => { file.startResumableUpload_ = (stream: {}, options: any) => { assert.strictEqual( options.preconditionOpts.ifMetagenerationNotMatch, - 100 + 100, ); done(); }; @@ -2645,7 +2645,7 @@ describe('File', () => { assert.ifError(err); assert.strictEqual( fileContents + fileContents, - tmpFileContents.toString() + tmpFileContents.toString(), ); done(); }); @@ -2769,7 +2769,7 @@ describe('File', () => { assert.strictEqual(expirationDate, null); assert.strictEqual(apiResponse_, apiResponse); done(); - } + }, ); }); @@ -2784,12 +2784,12 @@ describe('File', () => { (err: Error, expirationDate: {}, apiResponse_: {}) => { assert.strictEqual( err.message, - FileExceptionMessages.EXPIRATION_TIME_NA + FileExceptionMessages.EXPIRATION_TIME_NA, ); assert.strictEqual(expirationDate, null); assert.strictEqual(apiResponse_, apiResponse); done(); - } + }, ); }); @@ -2810,7 +2810,7 @@ describe('File', () => { assert.deepStrictEqual(expirationDate, expirationTime); assert.strictEqual(apiResponse_, apiResponse); done(); - } + }, ); }); }); @@ -2846,7 +2846,7 @@ describe('File', () => { assert.strictEqual(typeof signedPolicy.base64, 'string'); assert.strictEqual(typeof signedPolicy.signature, 'string'); done(); - } + }, ); }); @@ -2882,7 +2882,7 @@ describe('File', () => { assert.ifError(err); assert(signedPolicy.string.indexOf(conditionString) > -1); done(); - } + }, ); }); @@ -2897,7 +2897,7 @@ describe('File', () => { assert.ifError(err); assert(signedPolicy.string.indexOf(conditionString) > -1); done(); - } + }, ); }); @@ -2918,11 +2918,11 @@ describe('File', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any policy.conditions.some((condition: any) => { return condition.success_action_redirect === redirectUrl; - }) + }), ); done(); - } + }, ); }); @@ -2943,11 +2943,11 @@ describe('File', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any policy.conditions.some((condition: any) => { return condition.success_action_status === successStatus; - }) + }), ); done(); - } + }, ); }); @@ -2964,7 +2964,7 @@ describe('File', () => { const expires_ = JSON.parse(policy.string).expiration; assert.strictEqual(expires_, expires.toISOString()); done(); - } + }, ); }); @@ -2980,7 +2980,7 @@ describe('File', () => { const expires_ = JSON.parse(policy.string).expiration; assert.strictEqual(expires_, new Date(expires).toISOString()); done(); - } + }, ); }); @@ -2996,7 +2996,7 @@ describe('File', () => { const expires_ = JSON.parse(policy.string).expiration; assert.strictEqual(expires_, new Date(expires).toISOString()); done(); - } + }, ); }); @@ -3008,7 +3008,7 @@ describe('File', () => { { expires, }, - () => {} + () => {}, ), ExceptionMessages.EXPIRATION_DATE_INVALID; }); @@ -3022,7 +3022,7 @@ describe('File', () => { { expires, }, - () => {} + () => {}, ), ExceptionMessages.EXPIRATION_DATE_PAST; }); @@ -3041,7 +3041,7 @@ describe('File', () => { assert.ifError(err); assert(signedPolicy.string.indexOf(conditionString) > -1); done(); - } + }, ); }); @@ -3056,7 +3056,7 @@ describe('File', () => { assert.ifError(err); assert(signedPolicy.string.indexOf(conditionString) > -1); done(); - } + }, ); }); @@ -3067,7 +3067,7 @@ describe('File', () => { expires: Date.now() + 2000, equals: [{}], }, - () => {} + () => {}, ), FileExceptionMessages.EQUALS_CONDITION_TWO_ELEMENTS; }); @@ -3080,7 +3080,7 @@ describe('File', () => { expires: Date.now() + 2000, equals: [['1', '2', '3']], }, - () => {} + () => {}, ), FileExceptionMessages.EQUALS_CONDITION_TWO_ELEMENTS; }); @@ -3099,7 +3099,7 @@ describe('File', () => { assert.ifError(err); assert(signedPolicy.string.indexOf(conditionString) > -1); done(); - } + }, ); }); @@ -3114,7 +3114,7 @@ describe('File', () => { assert.ifError(err); assert(signedPolicy.string.indexOf(conditionString) > -1); done(); - } + }, ); }); @@ -3125,7 +3125,7 @@ describe('File', () => { expires: Date.now() + 2000, startsWith: [{}], }, - () => {} + () => {}, ), FileExceptionMessages.STARTS_WITH_TWO_ELEMENTS; }); @@ -3138,7 +3138,7 @@ describe('File', () => { expires: Date.now() + 2000, startsWith: [['1', '2', '3']], }, - () => {} + () => {}, ), FileExceptionMessages.STARTS_WITH_TWO_ELEMENTS; }); @@ -3157,7 +3157,7 @@ describe('File', () => { assert.ifError(err); assert(signedPolicy.string.indexOf(conditionString) > -1); done(); - } + }, ); }); @@ -3168,7 +3168,7 @@ describe('File', () => { expires: Date.now() + 2000, contentLengthRange: [{max: 1}], }, - () => {} + () => {}, ), FileExceptionMessages.CONTENT_LENGTH_RANGE_MIN_MAX; }); @@ -3181,7 +3181,7 @@ describe('File', () => { expires: Date.now() + 2000, contentLengthRange: [{min: 0}], }, - () => {} + () => {}, ), FileExceptionMessages.CONTENT_LENGTH_RANGE_MIN_MAX; }); @@ -3244,7 +3244,7 @@ describe('File', () => { const policyString = JSON.stringify(policy); const EXPECTED_POLICY = Buffer.from(policyString).toString('base64'); const EXPECTED_SIGNATURE = Buffer.from(SIGNATURE, 'base64').toString( - 'hex' + 'hex', ); const EXPECTED_FIELDS = { ...CONFIG.fields, @@ -3265,11 +3265,11 @@ describe('File', () => { const signStub = BUCKET.storage.authClient.sign; assert.deepStrictEqual( Buffer.from(signStub.getCall(0).args[0], 'base64').toString(), - policyString + policyString, ); done(); - } + }, ); }); @@ -3306,10 +3306,10 @@ describe('File', () => { assert( Buffer.from(res.fields.policy, 'base64') .toString('utf-8') - .includes(EXPECTED_POLICY_ELEMENT) + .includes(EXPECTED_POLICY_ELEMENT), ); done(); - } + }, ); }); @@ -3330,11 +3330,11 @@ describe('File', () => { assert.strictEqual(res.fields['x-goog-meta-foo'], 'bar'); const decodedPolicy = Buffer.from( res.fields.policy, - 'base64' + 'base64', ).toString('utf-8'); assert(decodedPolicy.includes(expectedConditionString)); done(); - } + }, ); }); @@ -3354,11 +3354,11 @@ describe('File', () => { assert.strictEqual(res.fields['x-goog-meta-foo'], 'bår'); const decodedPolicy = Buffer.from( res.fields.policy, - 'base64' + 'base64', ).toString('utf-8'); assert(decodedPolicy.includes('"x-goog-meta-foo":"b\\u00e5r"')); done(); - } + }, ); }); @@ -3379,14 +3379,14 @@ describe('File', () => { assert.strictEqual(res.fields['x-ignore-foo'], 'bar'); const decodedPolicy = Buffer.from( res.fields.policy, - 'base64' + 'base64', ).toString('utf-8'); assert(!decodedPolicy.includes(expectedConditionString)); const signStub = BUCKET.storage.authClient.sign; assert(!signStub.getCall(0).args[0].includes('x-ignore-foo')); done(); - } + }, ); }); @@ -3404,16 +3404,16 @@ describe('File', () => { const expectedConditionString = JSON.stringify(CONFIG.conditions); const decodedPolicy = Buffer.from( res.fields.policy, - 'base64' + 'base64', ).toString('utf-8'); assert(decodedPolicy.includes(expectedConditionString)); const signStub = BUCKET.storage.authClient.sign; assert( - !signStub.getCall(0).args[0].includes(expectedConditionString) + !signStub.getCall(0).args[0].includes(expectedConditionString), ); done(); - } + }, ); }); @@ -3426,7 +3426,7 @@ describe('File', () => { assert.ifError(err); assert(res.url, CONFIG.bucketBoundHostname); done(); - } + }, ); }); @@ -3439,7 +3439,7 @@ describe('File', () => { assert.ifError(err); assert(res.url, `https://${BUCKET.name}.storage.googleapis.com/`); done(); - } + }, ); }); @@ -3458,7 +3458,7 @@ describe('File', () => { assert.ifError(err); assert(res.url, `https://${BUCKET.name}.storage.googleapis.com/`); done(); - } + }, ); }); @@ -3473,14 +3473,14 @@ describe('File', () => { (err: Error, response: SignedPostPolicyV4Output) => { assert.ifError(err); const policy = JSON.parse( - Buffer.from(response.fields.policy, 'base64').toString() + Buffer.from(response.fields.policy, 'base64').toString(), ); assert.strictEqual( policy.expiration, - formatAsUTCISO(expires, true, '-', ':') + formatAsUTCISO(expires, true, '-', ':'), ); done(); - } + }, ); }); @@ -3494,14 +3494,14 @@ describe('File', () => { (err: Error, response: SignedPostPolicyV4Output) => { assert.ifError(err); const policy = JSON.parse( - Buffer.from(response.fields.policy, 'base64').toString() + Buffer.from(response.fields.policy, 'base64').toString(), ); assert.strictEqual( policy.expiration, - formatAsUTCISO(new Date(expires), true, '-', ':') + formatAsUTCISO(new Date(expires), true, '-', ':'), ); done(); - } + }, ); }); @@ -3509,7 +3509,7 @@ describe('File', () => { const expires = formatAsUTCISO( new Date(Date.now() + 2 * 24 * 60 * 60 * 1000), false, - '-' + '-', ); file.generateSignedPostPolicyV4( @@ -3519,14 +3519,14 @@ describe('File', () => { (err: Error, response: SignedPostPolicyV4Output) => { assert.ifError(err); const policy = JSON.parse( - Buffer.from(response.fields.policy, 'base64').toString() + Buffer.from(response.fields.policy, 'base64').toString(), ); assert.strictEqual( policy.expiration, - formatAsUTCISO(new Date(expires), true, '-', ':') + formatAsUTCISO(new Date(expires), true, '-', ':'), ); done(); - } + }, ); }); @@ -3538,7 +3538,7 @@ describe('File', () => { { expires, }, - () => {} + () => {}, ), ExceptionMessages.EXPIRATION_DATE_INVALID; }); @@ -3552,7 +3552,7 @@ describe('File', () => { { expires, }, - () => {} + () => {}, ), ExceptionMessages.EXPIRATION_DATE_PAST; }); @@ -3566,7 +3566,7 @@ describe('File', () => { { expires, }, - () => {} + () => {}, ), {message: 'Max allowed expiration is seven days (604800 seconds).'}; }); @@ -3595,7 +3595,7 @@ describe('File', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any urlSignerStub = (sandbox.stub as any)(fakeSigner, 'URLSigner').returns( - signer + signer, ); SIGNED_URL_CONFIG = { @@ -3741,7 +3741,7 @@ describe('File', () => { file.setMetadata = ( metadata: FileMetadata, optionsOrCallback: SetMetadataOptions | MetadataCallback, - cb: MetadataCallback + cb: MetadataCallback, ) => { Promise.resolve([apiResponse]).then(resp => cb(null, ...resp)); }; @@ -3828,7 +3828,7 @@ describe('File', () => { const file = new File(BUCKET, NAME); assert.strictEqual( file.publicUrl(), - `https://storage.googleapis.com/bucket-name/${encodeURIComponent(NAME)}` + `https://storage.googleapis.com/bucket-name/${encodeURIComponent(NAME)}`, ); done(); }); @@ -3838,7 +3838,7 @@ describe('File', () => { const file = new File(BUCKET, NAME); assert.strictEqual( file.publicUrl(), - `https://storage.googleapis.com/bucket-name/${encodeURIComponent(NAME)}` + `https://storage.googleapis.com/bucket-name/${encodeURIComponent(NAME)}`, ); done(); }); @@ -3848,7 +3848,7 @@ describe('File', () => { const file = new File(BUCKET, NAME); assert.strictEqual( file.publicUrl(), - `https://storage.googleapis.com/bucket-name/${encodeURIComponent(NAME)}` + `https://storage.googleapis.com/bucket-name/${encodeURIComponent(NAME)}`, ); done(); }); @@ -3858,7 +3858,7 @@ describe('File', () => { const file = new File(BUCKET, NAME); assert.strictEqual( file.publicUrl(), - `https://storage.googleapis.com/bucket-name/${encodeURIComponent(NAME)}` + `https://storage.googleapis.com/bucket-name/${encodeURIComponent(NAME)}`, ); done(); }); @@ -3868,7 +3868,7 @@ describe('File', () => { const file = new File(BUCKET, NAME); assert.strictEqual( file.publicUrl(), - `https://storage.googleapis.com/bucket-name/${encodeURIComponent(NAME)}` + `https://storage.googleapis.com/bucket-name/${encodeURIComponent(NAME)}`, ); done(); }); @@ -3891,7 +3891,7 @@ describe('File', () => { fakeUtil.makeRequest = function ( reqOpts: DecorateRequestOptions, config: object, - callback: BodyResponseCallback + callback: BodyResponseCallback, ) { const error = new ApiError('Permission Denied.'); error.code = 403; @@ -3910,7 +3910,7 @@ describe('File', () => { fakeUtil.makeRequest = function ( reqOpts: DecorateRequestOptions, config: object, - callback: BodyResponseCallback + callback: BodyResponseCallback, ) { callback(error); }; @@ -3924,7 +3924,7 @@ describe('File', () => { fakeUtil.makeRequest = function ( reqOpts: DecorateRequestOptions, config: object, - callback: BodyResponseCallback + callback: BodyResponseCallback, ) { assert.strictEqual(reqOpts.method, 'GET'); callback(null); @@ -3944,7 +3944,7 @@ describe('File', () => { fakeUtil.makeRequest = function ( reqOpts: DecorateRequestOptions, config: object, - callback: BodyResponseCallback + callback: BodyResponseCallback, ) { assert.strictEqual(reqOpts.uri, expectedURL); callback(null); @@ -3959,7 +3959,7 @@ describe('File', () => { fakeUtil.makeRequest = function ( reqOpts: DecorateRequestOptions, config: object, - callback: BodyResponseCallback + callback: BodyResponseCallback, ) { assert.deepStrictEqual(reqOpts.headers, {}); callback(null); @@ -3984,7 +3984,7 @@ describe('File', () => { fakeUtil.makeRequest = function ( reqOpts: DecorateRequestOptions, config: object, - callback: BodyResponseCallback + callback: BodyResponseCallback, ) { assert.deepStrictEqual(reqOpts.headers, expectedHeader); callback(null); @@ -4002,7 +4002,7 @@ describe('File', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any file: any, expectedDestination: string, - callback: Function + callback: Function, ) { file.copy = (destination: string) => { assert.strictEqual(destination, expectedDestination); @@ -4049,7 +4049,7 @@ describe('File', () => { assert.strictEqual(err, error); assert.strictEqual( err.message, - `file#copy failed with an error - ${originalErrorMessage}` + `file#copy failed with an error - ${originalErrorMessage}`, ); done(); }); @@ -4074,7 +4074,7 @@ describe('File', () => { assert.strictEqual(destinationFile, newFile); assert.strictEqual(apiResponse, copyApiResponse); done(); - } + }, ); }); @@ -4158,7 +4158,7 @@ describe('File', () => { assert.strictEqual(err, error); assert.strictEqual( err.message, - `file#delete failed with an error - ${originalErrorMessage}` + `file#delete failed with an error - ${originalErrorMessage}`, ); done(); }); @@ -4204,7 +4204,7 @@ describe('File', () => { it('should pass options to underlying request call', async () => { file.parent.request = function ( reqOpts: DecorateRequestOptions, - callback_: Function + callback_: Function, ) { assert.strictEqual(this, file); assert.deepStrictEqual(reqOpts, { @@ -4228,7 +4228,7 @@ describe('File', () => { file.parent.request = function ( reqOpts: DecorateRequestOptions, - callback_: Function + callback_: Function, ) { assert.strictEqual(this, file); assert.strictEqual(reqOpts, options); @@ -4286,7 +4286,7 @@ describe('File', () => { file.copy = ( destination: string, options: object, - callback: Function + callback: Function, ) => { assert.strictEqual(destination, newFile); assert.deepStrictEqual(options, {}); @@ -4301,7 +4301,7 @@ describe('File', () => { const DATA = 'Data!'; const BUFFER_DATA = Buffer.from(DATA, 'utf8'); const UINT8_ARRAY_DATA = Uint8Array.from( - Array.from(DATA).map(l => l.charCodeAt(0)) + Array.from(DATA).map(l => l.charCodeAt(0)), ); class DelayedStreamNoError extends Transform { @@ -4378,7 +4378,7 @@ describe('File', () => { _transform( chunk: string | Buffer, _encoding: string, - done: Function + done: Function, ) { this.push(chunk); setTimeout(() => { @@ -4508,7 +4508,7 @@ describe('File', () => { transform( chunk: string | Buffer, _encoding: string, - done: Function + done: Function, ) { this.push(chunk); setTimeout(() => { @@ -4728,7 +4728,7 @@ describe('File', () => { newFile.setMetadata( {retention: null}, {overrideUnlockedRetention: true}, - assert.ifError + assert.ifError, ); }); }); @@ -4882,11 +4882,11 @@ describe('File', () => { assert.deepStrictEqual( file.interceptors[0].request({}), - expectedInterceptor + expectedInterceptor, ); assert.deepStrictEqual( file.encryptionKeyInterceptor.request({}), - expectedInterceptor + expectedInterceptor, ); done(); @@ -5184,7 +5184,7 @@ describe('File', () => { makeWritableStreamOverride = (stream: {}, options_: any) => { assert.strictEqual( options_.request.qs.userProject, - options.userProject + options.userProject, ); done(); }; @@ -5199,7 +5199,7 @@ describe('File', () => { beforeEach(() => { file.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(error); }; @@ -5226,7 +5226,7 @@ describe('File', () => { beforeEach(() => { file.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, body, resp); }; diff --git a/test/headers.ts b/test/headers.ts index 9ccc68581..61c5f2ced 100644 --- a/test/headers.ts +++ b/test/headers.ts @@ -67,8 +67,8 @@ describe('headers', () => { } assert.ok( /^gl-node\/(?[^W]+) gccl\/(?[^W]+) gccl-invocation-id\/(?[^W]+)$/.test( - requests[0].headers['x-goog-api-client'] - ) + requests[0].headers['x-goog-api-client'], + ), ); }); @@ -89,8 +89,8 @@ describe('headers', () => { } assert.ok( /^gl-deno\/0.00.0 gccl\/(?[^W]+) gccl-invocation-id\/(?[^W]+)$/.test( - requests[1].headers['x-goog-api-client'] - ) + requests[1].headers['x-goog-api-client'], + ), ); }); }); diff --git a/test/iam.ts b/test/iam.ts index 92327daa6..0fc35be6c 100644 --- a/test/iam.ts +++ b/test/iam.ts @@ -140,7 +140,7 @@ describe('storage/iam', () => { { resourceId: iam.resourceId_, }, - policy + policy, ), qs: {}, }); @@ -211,7 +211,7 @@ describe('storage/iam', () => { assert.strictEqual(permissions, null); assert.strictEqual(apiResp, apiResponse); done(); - } + }, ); }); @@ -236,7 +236,7 @@ describe('storage/iam', () => { assert.strictEqual(apiResp, apiResponse); done(); - } + }, ); }); @@ -258,7 +258,7 @@ describe('storage/iam', () => { assert.strictEqual(apiResp, apiResponse); done(); - } + }, ); }); @@ -272,7 +272,7 @@ describe('storage/iam', () => { { permissions, }, - options + options, ); iam.request_ = (reqOpts: DecorateRequestOptions) => { diff --git a/test/index.ts b/test/index.ts index 6d10c02a3..332373708 100644 --- a/test/index.ts +++ b/test/index.ts @@ -145,7 +145,7 @@ describe('Storage', () => { assert.deepStrictEqual( calledWith.packageJson, // eslint-disable-next-line @typescript-eslint/no-var-requires - getPackageJSON() + getPackageJSON(), ); }); @@ -231,7 +231,7 @@ describe('Storage', () => { const calledWith = storage.calledWith_[0]; assert.strictEqual( calledWith.retryOptions.retryDelayMultiplier, - retryDelayMultiplier + retryDelayMultiplier, ); }); @@ -269,15 +269,15 @@ describe('Storage', () => { assert.strictEqual(calledWith.retryOptions.maxRetries, maxRetryDefault); assert.strictEqual( calledWith.retryOptions.retryDelayMultiplier, - retryDelayMultiplierDefault + retryDelayMultiplierDefault, ); assert.strictEqual( calledWith.retryOptions.totalTimeout, - totalTimeoutDefault + totalTimeoutDefault, ); assert.strictEqual( calledWith.retryOptions.maxRetryDelay, - maxRetryDelayDefault + maxRetryDelayDefault, ); }); @@ -317,7 +317,7 @@ describe('Storage', () => { const error = undefined; assert.strictEqual( calledWith.retryOptions.retryableErrorFn(error), - false + false, ); }); @@ -376,7 +376,7 @@ describe('Storage', () => { error.code = 0; assert.strictEqual( calledWith.retryOptions.retryableErrorFn(error), - false + false, ); }); @@ -393,7 +393,7 @@ describe('Storage', () => { ]; assert.strictEqual( calledWith.retryOptions.retryableErrorFn(error), - false + false, ); }); @@ -435,11 +435,11 @@ describe('Storage', () => { const calledWith = storage.calledWith_[0]; assert.strictEqual( calledWith.baseUrl, - `https://${protocollessApiEndpoint}/storage/v1` + `https://${protocollessApiEndpoint}/storage/v1`, ); assert.strictEqual( calledWith.apiEndpoint, - `https://${protocollessApiEndpoint}` + `https://${protocollessApiEndpoint}`, ); }); @@ -464,7 +464,7 @@ describe('Storage', () => { it('should use `CRC32C_DEFAULT_VALIDATOR_GENERATOR` by default', () => { assert.strictEqual( storage.crc32cGenerator, - CRC32C_DEFAULT_VALIDATOR_GENERATOR + CRC32C_DEFAULT_VALIDATOR_GENERATOR, ); }); @@ -496,7 +496,7 @@ describe('Storage', () => { assert.strictEqual(calledWith.baseUrl, EMULATOR_HOST); assert.strictEqual( calledWith.apiEndpoint, - 'https://internal.benchmark.com/path' + 'https://internal.benchmark.com/path', ); }); @@ -523,7 +523,7 @@ describe('Storage', () => { assert.strictEqual(calledWith.baseUrl, EMULATOR_HOST); assert.strictEqual( calledWith.apiEndpoint, - 'https://internal.benchmark.com/path' + 'https://internal.benchmark.com/path', ); }); @@ -636,16 +636,16 @@ describe('Storage', () => { it('should make correct API request', done => { storage.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { assert.strictEqual(reqOpts.method, 'POST'); assert.strictEqual( reqOpts.uri, - `/projects/${storage.projectId}/hmacKeys` + `/projects/${storage.projectId}/hmacKeys`, ); assert.strictEqual( reqOpts.qs.serviceAccountEmail, - SERVICE_ACCOUNT_EMAIL + SERVICE_ACCOUNT_EMAIL, ); callback(null, response); @@ -712,7 +712,7 @@ describe('Storage', () => { ]); assert.strictEqual(hmacKey.metadata, metadataResponse); done(); - } + }, ); }); @@ -727,12 +727,12 @@ describe('Storage', () => { err: Error, _hmacKey: HmacKey, _secret: string, - apiResponse: HmacKeyResourceResponse + apiResponse: HmacKeyResourceResponse, ) => { assert.ifError(err); assert.strictEqual(apiResponse, response); done(); - } + }, ); }); @@ -749,7 +749,7 @@ describe('Storage', () => { assert.strictEqual(err, error); assert.strictEqual(apiResponse, response); done(); - } + }, ); }); }); @@ -762,7 +762,7 @@ describe('Storage', () => { it('should make correct API request', done => { storage.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { assert.strictEqual(reqOpts.method, 'POST'); assert.strictEqual(reqOpts.uri, '/b'); @@ -778,11 +778,11 @@ describe('Storage', () => { it('should accept a name, metadata, and callback', done => { storage.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { assert.deepStrictEqual( reqOpts.json, - Object.assign(METADATA, {name: BUCKET_NAME}) + Object.assign(METADATA, {name: BUCKET_NAME}), ); callback(null, METADATA); }; @@ -799,7 +799,7 @@ describe('Storage', () => { it('should accept a name and callback only', done => { storage.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(); }; @@ -832,7 +832,7 @@ describe('Storage', () => { }; storage.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, METADATA); }; @@ -848,7 +848,7 @@ describe('Storage', () => { const error = new Error('Error.'); storage.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(error); }; @@ -862,7 +862,7 @@ describe('Storage', () => { const resp = {success: true}; storage.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, resp); }; @@ -871,7 +871,7 @@ describe('Storage', () => { (err: Error, bucket: Bucket, apiResponse: unknown) => { assert.strictEqual(resp, apiResponse); done(); - } + }, ); }); @@ -879,7 +879,7 @@ describe('Storage', () => { const storageClass = 'nearline'; storage.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { assert.strictEqual(reqOpts.json.storageClass, storageClass); callback(); // done @@ -891,11 +891,11 @@ describe('Storage', () => { const storageClass = 'coldline'; storage.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { assert.strictEqual( reqOpts.json.storageClass, - storageClass.toUpperCase() + storageClass.toUpperCase(), ); callback(); // done }; @@ -904,7 +904,7 @@ describe('Storage', () => { storage.createBucket( BUCKET_NAME, {storageClass, [storageClass]: true}, - done + done, ); }); }); @@ -914,7 +914,7 @@ describe('Storage', () => { const rpo = 'ASYNC_TURBO'; storage.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { assert.strictEqual(reqOpts.json.location, location); assert.strictEqual(reqOpts.json.rpo, rpo); @@ -931,7 +931,7 @@ describe('Storage', () => { storageClass: 'nearline', coldline: true, }, - assert.ifError + assert.ifError, ); }, /Both `coldline` and `storageClass` were provided./); }); @@ -939,7 +939,7 @@ describe('Storage', () => { it('should allow enabling object retention', done => { storage.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { assert.strictEqual(reqOpts.qs.enableObjectRetention, true); callback(); @@ -950,7 +950,7 @@ describe('Storage', () => { it('should allow enabling hierarchical namespace', done => { storage.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { assert.strictEqual(reqOpts.json.hierarchicalNamespace.enabled, true); callback(); @@ -958,7 +958,7 @@ describe('Storage', () => { storage.createBucket( BUCKET_NAME, {hierarchicalNamespace: {enabled: true}}, - done + done, ); }); @@ -1002,7 +1002,7 @@ describe('Storage', () => { { multiRegional: true, }, - assert.ifError + assert.ifError, ); }); @@ -1078,7 +1078,7 @@ describe('Storage', () => { storage.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(error, apiResponse); }; @@ -1091,7 +1091,7 @@ describe('Storage', () => { assert.strictEqual(nextQuery, null); assert.strictEqual(resp, apiResponse); done(); - } + }, ); }); @@ -1099,7 +1099,7 @@ describe('Storage', () => { const token = 'next-page-token'; storage.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, {nextPageToken: token, items: []}); }; @@ -1108,14 +1108,14 @@ describe('Storage', () => { (err: Error, results: {}, nextQuery: GetFilesOptions) => { assert.strictEqual(nextQuery.pageToken, token); assert.strictEqual(nextQuery.maxResults, 5); - } + }, ); }); it('should return null nextQuery if there are no more results', () => { storage.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, {items: []}); }; @@ -1123,14 +1123,14 @@ describe('Storage', () => { {maxResults: 5}, (err: Error, results: {}, nextQuery: {}) => { assert.strictEqual(nextQuery, null); - } + }, ); }); it('should return Bucket objects', done => { storage.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, {items: [{id: 'fake-bucket-name'}]}); }; @@ -1145,7 +1145,7 @@ describe('Storage', () => { const resp = {items: [{id: 'fake-bucket-name'}]}; storage.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, resp); }; @@ -1153,7 +1153,7 @@ describe('Storage', () => { (err: Error, buckets: Bucket[], nextQuery: {}, apiResponse: {}) => { assert.deepStrictEqual(resp, apiResponse); done(); - } + }, ); }); @@ -1167,7 +1167,7 @@ describe('Storage', () => { }; storage.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, {items: [bucketMetadata]}); }; @@ -1216,7 +1216,7 @@ describe('Storage', () => { const firstArg = storage.request.firstCall.args[0]; assert.strictEqual( firstArg.uri, - `/projects/${storage.projectId}/hmacKeys` + `/projects/${storage.projectId}/hmacKeys`, ); assert.deepStrictEqual(firstArg.qs, {}); done(); @@ -1235,7 +1235,7 @@ describe('Storage', () => { const firstArg = storage.request.firstCall.args[0]; assert.strictEqual( firstArg.uri, - `/projects/${storage.projectId}/hmacKeys` + `/projects/${storage.projectId}/hmacKeys`, ); assert.deepStrictEqual(firstArg.qs, query); done(); @@ -1258,7 +1258,7 @@ describe('Storage', () => { assert.strictEqual(nextQuery, null); assert.strictEqual(resp, apiResponse); done(); - } + }, ); }); @@ -1280,7 +1280,7 @@ describe('Storage', () => { assert.ifError(err); assert.deepStrictEqual(nextQuery, expectedNextQuery); done(); - } + }, ); }); @@ -1307,7 +1307,7 @@ describe('Storage', () => { assert.ifError(err); assert.deepStrictEqual(resp, apiResponse); done(); - } + }, ); }); @@ -1334,7 +1334,7 @@ describe('Storage', () => { storage.request = (reqOpts: DecorateRequestOptions) => { assert.strictEqual( reqOpts.uri, - `/projects/${storage.projectId}/serviceAccount` + `/projects/${storage.projectId}/serviceAccount`, ); assert.deepStrictEqual(reqOpts.qs, {}); done(); @@ -1364,7 +1364,7 @@ describe('Storage', () => { beforeEach(() => { storage.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(ERROR, API_RESPONSE); }; @@ -1377,7 +1377,7 @@ describe('Storage', () => { assert.strictEqual(serviceAccount, null); assert.strictEqual(apiResponse, API_RESPONSE); done(); - } + }, ); }); }); @@ -1388,7 +1388,7 @@ describe('Storage', () => { beforeEach(() => { storage.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, API_RESPONSE); }; @@ -1401,7 +1401,7 @@ describe('Storage', () => { storage.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, apiResponse); }; @@ -1409,16 +1409,16 @@ describe('Storage', () => { storage.getServiceAccount( ( err: Error, - serviceAccount: {[index: string]: string | undefined} + serviceAccount: {[index: string]: string | undefined}, ) => { assert.ifError(err); assert.strictEqual( serviceAccount.snakeCase, - apiResponse.snake_case + apiResponse.snake_case, ); assert.strictEqual(serviceAccount.snake_case, undefined); done(); - } + }, ); }); @@ -1429,7 +1429,7 @@ describe('Storage', () => { assert.deepStrictEqual(serviceAccount, {}); assert.strictEqual(apiResponse, API_RESPONSE); done(); - } + }, ); }); }); @@ -1442,7 +1442,7 @@ describe('Storage', () => { it('should default protocol to https', () => { const endpoint = Storage.sanitizeEndpoint( - USER_DEFINED_SHORT_API_ENDPOINT + USER_DEFINED_SHORT_API_ENDPOINT, ); assert.strictEqual(endpoint.match(PROTOCOL_REGEX)![1], 'https'); }); @@ -1451,7 +1451,7 @@ describe('Storage', () => { const endpoint = Storage.sanitizeEndpoint(USER_DEFINED_FULL_API_ENDPOINT); assert.strictEqual( endpoint.match(PROTOCOL_REGEX)![1], - USER_DEFINED_PROTOCOL + USER_DEFINED_PROTOCOL, ); }); diff --git a/test/nodejs-common/service-object.ts b/test/nodejs-common/service-object.ts index b9dc994c1..af1945ad9 100644 --- a/test/nodejs-common/service-object.ts +++ b/test/nodejs-common/service-object.ts @@ -55,7 +55,7 @@ type FakeServiceObject = any; interface InternalServiceObject { request_: ( reqOpts: DecorateRequestOptions, - callback?: BodyResponseCallback + callback?: BodyResponseCallback, ) => void | r.Request; createMethod?: Function; methods: SO.Methods; @@ -63,7 +63,7 @@ interface InternalServiceObject { } function asInternal( - serviceObject: SO.ServiceObject + serviceObject: SO.ServiceObject, ) { return serviceObject as {} as InternalServiceObject; } @@ -112,7 +112,7 @@ describe('ServiceObject', () => { it('should localize the createMethod', () => { assert.strictEqual( asInternal(serviceObject).createMethod, - CONFIG.createMethod + CONFIG.createMethod, ); }); @@ -152,7 +152,7 @@ describe('ServiceObject', () => { const serviceObject = new ServiceObject(config); assert.strictEqual( typeof serviceObject.getRequestInterceptors, - 'function' + 'function', ); }); }); @@ -165,7 +165,7 @@ describe('ServiceObject', () => { function createMethod( id: string, options_: {}, - callback: (err: Error | null, a: {}, b: {}) => void + callback: (err: Error | null, a: {}, b: {}) => void, ) { assert.strictEqual(id, config.id); assert.strictEqual(options_, options); @@ -197,7 +197,7 @@ describe('ServiceObject', () => { function createMethod( id: string, options_: {}, - callback: (err: Error | null, a: {}, b: {}) => void + callback: (err: Error | null, a: {}, b: {}) => void, ) { assert.strictEqual(id, config.id); assert.strictEqual(options_, options); @@ -227,7 +227,7 @@ describe('ServiceObject', () => { assert.strictEqual(instance, null); assert.strictEqual(apiResponse_, apiResponse); done(); - } + }, ); }); @@ -324,7 +324,7 @@ describe('ServiceObject', () => { const cb = callback as BodyResponseCallback; assert.deepStrictEqual( serviceObject.methods.delete, - cachedMethodConfig + cachedMethodConfig, ); assert.deepStrictEqual(opts.uri, 'v2'); assert.deepStrictEqual(opts.method, 'PATCH'); @@ -392,7 +392,7 @@ describe('ServiceObject', () => { const cb = callback as BodyResponseCallback; assert.deepStrictEqual( serviceObject.methods.delete, - cachedMethodConfig + cachedMethodConfig, ); assert.deepStrictEqual(opts.qs, { defaultProperty: true, @@ -499,7 +499,7 @@ describe('ServiceObject', () => { (options_: SO.GetMetadataOptions): void => { assert.deepStrictEqual(options, options_); done(); - } + }, ); serviceObject.exists(options, assert.ifError); }); @@ -518,10 +518,10 @@ describe('ServiceObject', () => { serviceObject.getMetadata = promisify( ( options: SO.GetMetadataOptions, - callback: SO.MetadataCallback + callback: SO.MetadataCallback, ) => { callback(error, metadata); - } + }, ); serviceObject.get((err, instance, metadata_) => { @@ -539,10 +539,10 @@ describe('ServiceObject', () => { serviceObject.getMetadata = promisify( ( options: SO.GetMetadataOptions, - callback: SO.MetadataCallback + callback: SO.MetadataCallback, ) => { callback(null, metadata); - } + }, ); serviceObject.get((err, instance, metadata_) => { @@ -570,10 +570,10 @@ describe('ServiceObject', () => { serviceObject.getMetadata = promisify( ( options: SO.GetMetadataOptions, - callback: SO.MetadataCallback + callback: SO.MetadataCallback, ) => { callback(ERROR, METADATA); - } + }, ); }); @@ -622,7 +622,7 @@ describe('ServiceObject', () => { callback!(null); // done() }); callback!(error, null, apiResponse); - } + }, ); serviceObject.get(AUTO_CREATE_CONFIG, (err, instance, resp) => { @@ -656,7 +656,7 @@ describe('ServiceObject', () => { sandbox.stub(ServiceObject.prototype, 'request').callsFake(function ( this: SO.ServiceObject, reqOpts, - callback + callback, ) { const opts = reqOpts as r.OptionsWithUri; const cb = callback as BodyResponseCallback; @@ -698,7 +698,7 @@ describe('ServiceObject', () => { const cb = callback as BodyResponseCallback; assert.deepStrictEqual( serviceObject.methods.getMetadata, - cachedMethodConfig + cachedMethodConfig, ); assert.deepStrictEqual(opts.uri, 'v2'); done(); @@ -729,7 +729,7 @@ describe('ServiceObject', () => { const cb = callback as BodyResponseCallback; assert.deepStrictEqual( serviceObject.methods.getMetadata, - cachedMethodConfig + cachedMethodConfig, ); assert.deepStrictEqual(opts.qs, { defaultProperty: true, @@ -820,7 +820,7 @@ describe('ServiceObject', () => { serviceObject.parent.getRequestInterceptors = () => { return serviceObject.parent.interceptors.map( - interceptor => interceptor.request + interceptor => interceptor.request, ); }; @@ -841,21 +841,21 @@ describe('ServiceObject', () => { serviceObject.interceptors = [{request}]; const originalParentInterceptors = [].slice.call( - serviceObject.parent.interceptors + serviceObject.parent.interceptors, ); const originalLocalInterceptors = [].slice.call( - serviceObject.interceptors + serviceObject.interceptors, ); serviceObject.getRequestInterceptors(); assert.deepStrictEqual( serviceObject.parent.interceptors, - originalParentInterceptors + originalParentInterceptors, ); assert.deepStrictEqual( serviceObject.interceptors, - originalLocalInterceptors + originalLocalInterceptors, ); }); @@ -882,7 +882,7 @@ describe('ServiceObject', () => { sandbox.stub(ServiceObject.prototype, 'request').callsFake(function ( this: SO.ServiceObject, reqOpts, - callback + callback, ) { const opts = reqOpts as r.OptionsWithUri; const cb = callback as BodyResponseCallback; @@ -927,7 +927,7 @@ describe('ServiceObject', () => { const cb = callback as BodyResponseCallback; assert.deepStrictEqual( serviceObject.methods.setMetadata, - cachedMethodConfig + cachedMethodConfig, ); assert.deepStrictEqual(opts.uri, 'v2'); assert.deepStrictEqual(opts.method, 'PUT'); @@ -958,7 +958,7 @@ describe('ServiceObject', () => { const cb = callback as BodyResponseCallback; assert.deepStrictEqual( serviceObject.methods.setMetadata, - cachedMethodConfig + cachedMethodConfig, ); assert.deepStrictEqual(opts.qs, { defaultProperty: true, @@ -976,7 +976,7 @@ describe('ServiceObject', () => { { optionalProperty: true, thisPropertyWasOverridden: true, - } + }, ); }); @@ -1080,7 +1080,7 @@ describe('ServiceObject', () => { uri: '//1/2//', }; const expectedUri = [serviceObject.baseUrl, serviceObject.id, '1/2'].join( - '/' + '/', ); serviceObject.parent.request = (reqOpts_, callback) => { assert.strictEqual(reqOpts_.uri, expectedUri); @@ -1113,20 +1113,20 @@ describe('ServiceObject', () => { sandbox .stub( parent.parent as SO.ServiceObject, - 'request' + 'request', ) .callsFake((reqOpts, callback) => { assert.deepStrictEqual( reqOpts.interceptors_![0].request({} as DecorateRequestOptions), { child: true, - } + }, ); assert.deepStrictEqual( reqOpts.interceptors_![1].request({} as DecorateRequestOptions), { parent: true, - } + }, ); callback(null, null, {} as r.Response); }); @@ -1148,7 +1148,7 @@ describe('ServiceObject', () => { asInternal(serviceObject).interceptors; assert.deepStrictEqual( reqOpts.interceptors_, - serviceObjectInterceptors + serviceObjectInterceptors, ); assert.notStrictEqual(reqOpts.interceptors_, serviceObjectInterceptors); callback(null, null, {} as r.Response); diff --git a/test/nodejs-common/service.ts b/test/nodejs-common/service.ts index 502c4e541..7d379da8d 100644 --- a/test/nodejs-common/service.ts +++ b/test/nodejs-common/service.ts @@ -45,12 +45,12 @@ const makeAuthRequestFactoryCache = util.makeAuthenticatedRequestFactory; let makeAuthenticatedRequestFactoryOverride: | null | (( - config: MakeAuthenticatedRequestFactoryConfig + config: MakeAuthenticatedRequestFactoryConfig, ) => MakeAuthenticatedRequest); util.makeAuthenticatedRequestFactory = function ( this: Util, - config: MakeAuthenticatedRequestFactoryConfig + config: MakeAuthenticatedRequestFactoryConfig, ) { if (makeAuthenticatedRequestFactoryOverride) { return makeAuthenticatedRequestFactoryOverride.call(this, config); @@ -101,7 +101,7 @@ describe('Service', () => { const authenticatedRequest = {} as MakeAuthenticatedRequest; makeAuthenticatedRequestFactoryOverride = ( - config: MakeAuthenticatedRequestFactoryConfig + config: MakeAuthenticatedRequestFactoryConfig, ) => { const expectedConfig = { ...CONFIG, @@ -296,7 +296,7 @@ describe('Service', () => { service.interceptors = [{request}]; const originalGlobalInterceptors = [].slice.call( - service.globalInterceptors + service.globalInterceptors, ); const originalLocalInterceptors = [].slice.call(service.interceptors); @@ -304,7 +304,7 @@ describe('Service', () => { assert.deepStrictEqual( service.globalInterceptors, - originalGlobalInterceptors + originalGlobalInterceptors, ); assert.deepStrictEqual(service.interceptors, originalLocalInterceptors); }); @@ -390,7 +390,7 @@ describe('Service', () => { const expectedUri = [service.baseUrl, reqOpts.uri].join('/'); service.makeAuthenticatedRequest = ( reqOpts_: DecorateRequestOptions, - callback: BodyResponseCallback + callback: BodyResponseCallback, ) => { assert.notStrictEqual(reqOpts_, reqOpts); assert.strictEqual(reqOpts_.uri, expectedUri); @@ -464,7 +464,7 @@ describe('Service', () => { service.makeAuthenticatedRequest = (reqOpts: DecorateRequestOptions) => { assert.strictEqual( reqOpts.headers!['User-Agent'], - getUserAgentString() + getUserAgentString(), ); done(); }; @@ -478,7 +478,7 @@ describe('Service', () => { const r = new RegExp( `^gl-node/${process.versions.node} gccl/${ pkg.version - }-${getModuleFormat()} gccl-invocation-id/(?[^W]+)$` + }-${getModuleFormat()} gccl-invocation-id/(?[^W]+)$`, ); assert.ok(r.test(reqOpts.headers!['x-goog-api-client'])); done(); @@ -494,7 +494,7 @@ describe('Service', () => { const r = new RegExp( `^gl-node/${process.versions.node} gccl/${ pkg.version - }-${getModuleFormat()} gccl-invocation-id/(?[^W]+) gccl-gcs-cmd/${expected}$` + }-${getModuleFormat()} gccl-invocation-id/(?[^W]+) gccl-gcs-cmd/${expected}$`, ); assert.ok(r.test(reqOpts.headers!['x-goog-api-client'])); done(); @@ -502,7 +502,7 @@ describe('Service', () => { service.request_( {...reqOpts, [GCCL_GCS_CMD_KEY]: expected}, - assert.ifError + assert.ifError, ); }); @@ -515,7 +515,7 @@ describe('Service', () => { const expectedUri = [service.baseUrl, reqOpts.uri].join('/'); service.makeAuthenticatedRequest = ( - reqOpts_: DecorateRequestOptions + reqOpts_: DecorateRequestOptions, ) => { assert.strictEqual(reqOpts_.uri, expectedUri); @@ -539,7 +539,7 @@ describe('Service', () => { ].join('/'); service.makeAuthenticatedRequest = ( - reqOpts_: DecorateRequestOptions + reqOpts_: DecorateRequestOptions, ) => { assert.strictEqual(reqOpts_.uri, expectedUri); @@ -564,7 +564,7 @@ describe('Service', () => { ].join('/'); service.makeAuthenticatedRequest = ( - reqOpts_: DecorateRequestOptions + reqOpts_: DecorateRequestOptions, ) => { assert.strictEqual(reqOpts_.uri, expectedUri); @@ -676,7 +676,7 @@ describe('Service', () => { const response = {body: {abc: '123'}, statusCode: 200}; Service.prototype.request_ = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { assert.strictEqual(reqOpts, fakeOpts); callback(null, response.body, response); diff --git a/test/nodejs-common/util.ts b/test/nodejs-common/util.ts index 48d5fd0f1..c723abf41 100644 --- a/test/nodejs-common/util.ts +++ b/test/nodejs-common/util.ts @@ -79,8 +79,8 @@ function fakeRequest() { fakeRequest.defaults = (defaults: r.CoreOptions) => { assert.ok( /^gl-node\/(?[^W]+) gccl\/(?[^W]+) gccl-invocation-id\/(?[^W]+)$/.test( - defaults.headers!['x-goog-api-client'] - ) + defaults.headers!['x-goog-api-client'], + ), ); return fakeRequest; }; @@ -97,7 +97,7 @@ function fakeReplaceProjectIdToken() { return (replaceProjectIdTokenOverride || replaceProjectIdToken).apply( null, // eslint-disable-next-line prefer-spread, prefer-rest-params - arguments + arguments, ); } @@ -116,7 +116,7 @@ describe('common/util', () => { errors = errors.map((error, i) => ` ${i + 1}. ${error}`); errors.unshift( - 'Multiple errors occurred during the request. Please see the `errors` array for complete details.\n' + 'Multiple errors occurred during the request. Please see the `errors` array for complete details.\n', ); errors.push('\n'); @@ -371,7 +371,7 @@ describe('common/util', () => { assert.deepStrictEqual(body, fakeResponse.body); assert.deepStrictEqual(resp, fakeResponse); done(); - } + }, ); }); @@ -441,7 +441,7 @@ describe('common/util', () => { } done(); - } + }, ); }); }); @@ -514,20 +514,20 @@ describe('common/util', () => { assert.strictEqual( // eslint-disable-next-line @typescript-eslint/no-explicit-any (mp[0] as any)['Content-Type'], - 'application/json' + 'application/json', ); assert.strictEqual(mp[0].body, JSON.stringify(metadata)); assert.strictEqual( // eslint-disable-next-line @typescript-eslint/no-explicit-any (mp[1] as any)['Content-Type'], - 'application/octet-stream' + 'application/octet-stream', ); // (is a writable stream:) assert.strictEqual( // eslint-disable-next-line @typescript-eslint/no-explicit-any typeof (mp[1].body as any)._writableState, - 'object' + 'object', ); done(); @@ -622,7 +622,7 @@ describe('common/util', () => { requestOverride = ( reqOpts: DecorateRequestOptions, - callback: (err: Error) => void + callback: (err: Error) => void, ) => { callback(error); }; @@ -657,7 +657,7 @@ describe('common/util', () => { requestOverride = ( reqOpts: DecorateRequestOptions, - callback: (err: Error | null, res: r.Response) => void + callback: (err: Error | null, res: r.Response) => void, ) => { callback(null, fakeResponse); }; @@ -692,7 +692,7 @@ describe('common/util', () => { requestOverride = ( reqOpts: DecorateRequestOptions, - callback: () => void + callback: () => void, ) => { callback(); }; @@ -790,7 +790,7 @@ describe('common/util', () => { it('should return a function', () => { assert.strictEqual( typeof util.makeAuthenticatedRequestFactory({}), - 'function' + 'function', ); }); @@ -834,7 +834,7 @@ describe('common/util', () => { makeAuthenticatedRequest(fakeReqOpts, { onAuthenticated( err: Error, - authenticatedReqOpts: DecorateRequestOptions + authenticatedReqOpts: DecorateRequestOptions, ) { assert.ifError(err); assert.strictEqual(authenticatedReqOpts, decoratedRequest); @@ -861,7 +861,7 @@ describe('common/util', () => { makeAuthenticatedRequest(reqOpts, { onAuthenticated( err: Error, - authenticatedReqOpts: DecorateRequestOptions + authenticatedReqOpts: DecorateRequestOptions, ) { assert.ifError(err); assert.deepStrictEqual(reqOpts, authenticatedReqOpts); @@ -955,7 +955,7 @@ describe('common/util', () => { }); const makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory( - {customEndpoint: true} + {customEndpoint: true}, ); makeAuthenticatedRequest(reqOpts, { @@ -1056,7 +1056,7 @@ describe('common/util', () => { it('should attempt request anyway', done => { sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient); const makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory( - {} + {}, ); const correctReqOpts = {} as DecorateRequestOptions; @@ -1078,7 +1078,7 @@ describe('common/util', () => { it('should block 401 API errors', done => { const authClientError = new Error( - 'Could not load the default credentials' + 'Could not load the default credentials', ); authClient.authorizeRequest = async () => { throw authClientError; @@ -1094,7 +1094,7 @@ describe('common/util', () => { }); const makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory( - {} + {}, ); makeAuthenticatedRequest( {} as DecorateRequestOptions, @@ -1103,7 +1103,7 @@ describe('common/util', () => { assert.strictEqual(arg2, makeRequestArg2); assert.strictEqual(arg3, makeRequestArg3); done(); - } + }, ); }); @@ -1122,7 +1122,7 @@ describe('common/util', () => { }); const makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory( - {} + {}, ); makeAuthenticatedRequest( {} as DecorateRequestOptions, @@ -1131,7 +1131,7 @@ describe('common/util', () => { assert.strictEqual(arg2, makeRequestArg2); assert.strictEqual(arg3, makeRequestArg3); done(); - } + }, ); }); @@ -1143,7 +1143,7 @@ describe('common/util', () => { }); const makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory( - {} + {}, ); makeAuthenticatedRequest(fakeReqOpts, { onAuthenticated(err) { @@ -1250,7 +1250,7 @@ describe('common/util', () => { const mar = util.makeAuthenticatedRequestFactory({}); const authenticatedRequest = mar( reqOpts, - assert.ifError + assert.ifError, ) as Abortable; authenticatedRequest.abort(); // done() @@ -1392,7 +1392,7 @@ describe('common/util', () => { function testNoRetryRequestConfig(done: () => void) { return ( reqOpts: DecorateRequestOptions, - config: retryRequest.Options + config: retryRequest.Options, ) => { assert.strictEqual(config.retries, 0); done(); @@ -1411,27 +1411,27 @@ describe('common/util', () => { function testRetryOptions(done: () => void) { return ( reqOpts: DecorateRequestOptions, - config: retryRequest.Options + config: retryRequest.Options, ) => { assert.strictEqual( config.retries, - 0 //autoRetry was set to false, so shouldn't retry + 0, //autoRetry was set to false, so shouldn't retry ); assert.strictEqual( config.noResponseRetries, - 0 //autoRetry was set to false, so shouldn't retry + 0, //autoRetry was set to false, so shouldn't retry ); assert.strictEqual( config.retryDelayMultiplier, - retryOptionsConfig.retryOptions.retryDelayMultiplier + retryOptionsConfig.retryOptions.retryDelayMultiplier, ); assert.strictEqual( config.totalTimeout, - retryOptionsConfig.retryOptions.totalTimeout + retryOptionsConfig.retryOptions.totalTimeout, ); assert.strictEqual( config.maxRetryDelay, - retryOptionsConfig.retryOptions.maxRetryDelay + retryOptionsConfig.retryOptions.maxRetryDelay, ); done(); }; @@ -1547,7 +1547,7 @@ describe('common/util', () => { util.makeRequest( {method: 'POST'} as DecorateRequestOptions, {stream: userStream}, - util.noop + util.noop, ); }); @@ -1560,7 +1560,7 @@ describe('common/util', () => { requestStream.abort = done; return requestStream; }, - {defaults: () => requestOverride} + {defaults: () => requestOverride}, ); util.makeRequest(reqOpts, {stream: userStream}, util.noop); @@ -1576,7 +1576,7 @@ describe('common/util', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any reqOpts, {}, - assert.ifError + assert.ifError, ); }); @@ -1585,7 +1585,7 @@ describe('common/util', () => { util.makeRequest( reqOpts, customRetryRequestFunctionConfig, - assert.ifError + assert.ifError, ); }); @@ -1613,7 +1613,7 @@ describe('common/util', () => { util.makeRequest( reqOptsWithRetrySettings, noRetryRequestConfig, - assert.ifError + assert.ifError, ); }); @@ -1633,7 +1633,7 @@ describe('common/util', () => { retryRequestOverride = ( rOpts: DecorateRequestOptions, opts: MakeRequestConfig, - callback: r.RequestCallback + callback: r.RequestCallback, ) => { callback(error, fakeResponse, body); }; @@ -1657,7 +1657,7 @@ describe('common/util', () => { { autoPaginate: true, } as DecorateRequestOptions, - projectId + projectId, ); assert.strictEqual(decoratedReqOpts.autoPaginate, undefined); @@ -1668,7 +1668,7 @@ describe('common/util', () => { { autoPaginateVal: true, } as DecorateRequestOptions, - projectId + projectId, ); assert.strictEqual(decoratedReqOpts.autoPaginateVal, undefined); @@ -1679,7 +1679,7 @@ describe('common/util', () => { { objectMode: true, } as DecorateRequestOptions, - projectId + projectId, ); assert.strictEqual(decoratedReqOpts.objectMode, undefined); @@ -1692,7 +1692,7 @@ describe('common/util', () => { autoPaginate: true, }, } as DecorateRequestOptions, - projectId + projectId, ); assert.strictEqual(decoratedReqOpts.qs.autoPaginate, undefined); @@ -1705,7 +1705,7 @@ describe('common/util', () => { autoPaginateVal: true, }, } as DecorateRequestOptions, - projectId + projectId, ); assert.strictEqual(decoratedReqOpts.qs.autoPaginateVal, undefined); @@ -1718,7 +1718,7 @@ describe('common/util', () => { autoPaginate: true, }, } as DecorateRequestOptions, - projectId + projectId, ); assert.strictEqual(decoratedReqOpts.json.autoPaginate, undefined); @@ -1731,7 +1731,7 @@ describe('common/util', () => { autoPaginateVal: true, }, } as DecorateRequestOptions, - projectId + projectId, ); assert.strictEqual(decoratedReqOpts.json.autoPaginateVal, undefined); @@ -1884,7 +1884,7 @@ describe('common/util', () => { const callback = () => {}; const [opts, cb] = util.maybeOptionsOrCallback( optionsOrCallback, - callback + callback, ); assert.strictEqual(opts, optionsOrCallback); assert.strictEqual(cb, callback); diff --git a/test/notification.ts b/test/notification.ts index fe396dcb5..3cb0e2bd1 100644 --- a/test/notification.ts +++ b/test/notification.ts @@ -140,7 +140,7 @@ describe('Notification', () => { BUCKET.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { assert.strictEqual(reqOpts.method, 'DELETE'); assert.strictEqual(reqOpts.uri, 'notificationConfigs/123'); @@ -154,7 +154,7 @@ describe('Notification', () => { it('should optionally accept options', done => { BUCKET.request = ( reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { assert.deepStrictEqual(reqOpts.qs, {}); callback(); // the done fn @@ -166,7 +166,7 @@ describe('Notification', () => { it('should optionally accept a callback', done => { BUCKET.request = ( _reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(); // the done fn }; @@ -250,7 +250,7 @@ describe('Notification', () => { {}, { maxResults: 5, - } + }, ); notification.get = (config_: {}) => { @@ -290,7 +290,7 @@ describe('Notification', () => { assert.strictEqual(instance, null); assert.strictEqual(resp, apiResponse); done(); - } + }, ); }); @@ -342,7 +342,7 @@ describe('Notification', () => { BUCKET.request = ( _reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(error, response, response); }; @@ -360,7 +360,7 @@ describe('Notification', () => { BUCKET.request = ( _reqOpts: DecorateRequestOptions, - callback: Function + callback: Function, ) => { callback(null, response, response); }; diff --git a/test/resumable-upload.ts b/test/resumable-upload.ts index 0080767e0..625c3f341 100644 --- a/test/resumable-upload.ts +++ b/test/resumable-upload.ts @@ -60,7 +60,7 @@ function mockAuthorizeRequest( code = 200, data: {} | string = { access_token: 'abc123', - } + }, ) { return nock('https://www.googleapis.com') .post('/oauth2/v4/token') @@ -176,7 +176,7 @@ describe('resumable-upload', () => { }); assert.strictEqual( upWithZeroGeneration.cacheKey, - [BUCKET, FILE, 0].join('/') + [BUCKET, FILE, 0].join('/'), ); }); @@ -525,7 +525,7 @@ describe('resumable-upload', () => { assert.equal( Buffer.compare(Buffer.concat(up.writeBuffers), Buffer.from('abcdef')), - 0 + 0, ); }); @@ -576,7 +576,7 @@ describe('resumable-upload', () => { it('should keep the desired last few bytes', () => { up.localWriteCache = [Buffer.from('123'), Buffer.from('456')]; up.localWriteCacheByteLength = up.localWriteCache.reduce( - (a: Buffer, b: number) => a.byteLength + b + (a: Buffer, b: number) => a.byteLength + b, ); up.writeBuffers = [Buffer.from('789')]; @@ -1071,7 +1071,7 @@ describe('resumable-upload', () => { assert.equal(data.contentLength, 24); done(); - } + }, ); up.makeRequestStream = async (reqOpts: GaxiosOptions) => { @@ -1160,10 +1160,10 @@ describe('resumable-upload', () => { assert(reqOpts.headers); assert.equal( reqOpts.headers['Content-Range'], - `bytes ${OFFSET}-*/${CONTENT_LENGTH}` + `bytes ${OFFSET}-*/${CONTENT_LENGTH}`, ); assert.ok( - X_GOOG_API_HEADER_REGEX.test(reqOpts.headers['x-goog-api-client']) + X_GOOG_API_HEADER_REGEX.test(reqOpts.headers['x-goog-api-client']), ); assert.ok(USER_AGENT_REGEX.test(reqOpts.headers['User-Agent'])); @@ -1180,7 +1180,7 @@ describe('resumable-upload', () => { assert(reqOpts.headers); assert.equal(reqOpts.headers['Content-Range'], 'bytes 0-*/*'); assert.ok( - X_GOOG_API_HEADER_REGEX.test(reqOpts.headers['x-goog-api-client']) + X_GOOG_API_HEADER_REGEX.test(reqOpts.headers['x-goog-api-client']), ); assert.ok(USER_AGENT_REGEX.test(reqOpts.headers['User-Agent'])); @@ -1211,10 +1211,10 @@ describe('resumable-upload', () => { assert.equal(reqOpts.headers['Content-Length'], CHUNK_SIZE); assert.equal( reqOpts.headers['Content-Range'], - `bytes ${OFFSET}-${endByte}/${CONTENT_LENGTH}` + `bytes ${OFFSET}-${endByte}/${CONTENT_LENGTH}`, ); assert.ok( - X_GOOG_API_HEADER_REGEX.test(reqOpts.headers['x-goog-api-client']) + X_GOOG_API_HEADER_REGEX.test(reqOpts.headers['x-goog-api-client']), ); assert.ok(USER_AGENT_REGEX.test(reqOpts.headers['User-Agent'])); @@ -1227,7 +1227,7 @@ describe('resumable-upload', () => { const OFFSET = 100; const EXPECTED_STREAM_AMOUNT = Math.min( UPSTREAM_BUFFER_SIZE - OFFSET, - CHUNK_SIZE + CHUNK_SIZE, ); const ENDING_BYTE = EXPECTED_STREAM_AMOUNT + OFFSET - 1; @@ -1239,14 +1239,14 @@ describe('resumable-upload', () => { assert(reqOpts.headers); assert.equal( reqOpts.headers['Content-Length'], - EXPECTED_STREAM_AMOUNT + EXPECTED_STREAM_AMOUNT, ); assert.equal( reqOpts.headers['Content-Range'], - `bytes ${OFFSET}-${ENDING_BYTE}/*` + `bytes ${OFFSET}-${ENDING_BYTE}/*`, ); assert.ok( - X_GOOG_API_HEADER_REGEX.test(reqOpts.headers['x-goog-api-client']) + X_GOOG_API_HEADER_REGEX.test(reqOpts.headers['x-goog-api-client']), ); assert.ok(USER_AGENT_REGEX.test(reqOpts.headers['User-Agent'])); @@ -1270,14 +1270,14 @@ describe('resumable-upload', () => { assert(reqOpts.headers); assert.equal( reqOpts.headers['Content-Length'], - CONTENT_LENGTH - NUM_BYTES_WRITTEN + CONTENT_LENGTH - NUM_BYTES_WRITTEN, ); assert.equal( reqOpts.headers['Content-Range'], - `bytes ${OFFSET}-${endByte}/${CONTENT_LENGTH}` + `bytes ${OFFSET}-${endByte}/${CONTENT_LENGTH}`, ); assert.ok( - X_GOOG_API_HEADER_REGEX.test(reqOpts.headers['x-goog-api-client']) + X_GOOG_API_HEADER_REGEX.test(reqOpts.headers['x-goog-api-client']), ); assert.ok(USER_AGENT_REGEX.test(reqOpts.headers['User-Agent'])); const data = await getAllDataFromRequest(); @@ -1435,13 +1435,13 @@ describe('resumable-upload', () => { assert.equal(up.offset, lastByteReceived + 1); assert.equal( Buffer.concat(up.writeBuffers).byteLength, - UPSTREAM_BUFFER_LENGTH + expectedUnshiftAmount + UPSTREAM_BUFFER_LENGTH + expectedUnshiftAmount, ); assert.equal( Buffer.concat(up.writeBuffers) .subarray(0, expectedUnshiftAmount) .toString(), - 'a'.repeat(expectedUnshiftAmount) + 'a'.repeat(expectedUnshiftAmount), ); // we should discard part of the last chunk, as we know what the server @@ -1485,7 +1485,7 @@ describe('resumable-upload', () => { await up.getAndSetOffset(); assert.notEqual( beforeCallInvocationId, - up.currentInvocationId.checkUploadStatus + up.currentInvocationId.checkUploadStatus, ); }); @@ -1494,7 +1494,7 @@ describe('resumable-upload', () => { up.destroy = () => { assert.equal( beforeCallInvocationId, - up.currentInvocationId.checkUploadStatus + up.currentInvocationId.checkUploadStatus, ); done(); }; @@ -1519,7 +1519,7 @@ describe('resumable-upload', () => { assert.equal(reqOpts.headers['Content-Length'], 0); assert.equal(reqOpts.headers['Content-Range'], 'bytes */*'); assert.ok( - X_GOOG_API_HEADER_REGEX.test(reqOpts.headers['x-goog-api-client']) + X_GOOG_API_HEADER_REGEX.test(reqOpts.headers['x-goog-api-client']), ); assert.ok(USER_AGENT_REGEX.test(reqOpts.headers['User-Agent'])); done(); @@ -1580,7 +1580,7 @@ describe('resumable-upload', () => { assert.strictEqual(headers['x-goog-encryption-key'], up.encryption.key); assert.strictEqual( headers['x-goog-encryption-key-sha256'], - up.encryption.hash + up.encryption.hash, ); }); @@ -1874,7 +1874,7 @@ describe('resumable-upload', () => { up.destroy = (err: Error) => { assert.strictEqual( err.message, - `Retry limit exceeded - ${JSON.stringify(RESP.data)}` + `Retry limit exceeded - ${JSON.stringify(RESP.data)}`, ); done(); }; @@ -1915,7 +1915,7 @@ describe('resumable-upload', () => { assert.strictEqual(up.numRetries, 3); assert.strictEqual( err.message, - `Retry limit exceeded - ${JSON.stringify(RESP.data)}` + `Retry limit exceeded - ${JSON.stringify(RESP.data)}`, ); done(); }); @@ -2010,7 +2010,7 @@ describe('resumable-upload', () => { assert.equal(up.localWriteCache.length, 0); assert.equal( Buffer.concat(up.writeBuffers).toString(), - 'a'.repeat(12) + 'b'.repeat(10) + 'a'.repeat(12) + 'b'.repeat(10), ); assert.equal(up.offset, undefined); @@ -2091,7 +2091,7 @@ describe('resumable-upload', () => { assert.strictEqual( url.input.match(PROTOCOL_REGEX) && url.input.match(PROTOCOL_REGEX)![1], - url.match + url.match, ); } }); @@ -2111,7 +2111,7 @@ describe('resumable-upload', () => { const endpoint = up.sanitizeEndpoint(USER_DEFINED_FULL_API_ENDPOINT); assert.strictEqual( endpoint.match(PROTOCOL_REGEX)![1], - USER_DEFINED_PROTOCOL + USER_DEFINED_PROTOCOL, ); }); @@ -2183,7 +2183,7 @@ describe('resumable-upload', () => { up.contentLength = CHUNK_SIZE_MULTIPLE * 8; up.createURI = ( - callback: (error: Error | null, uri: string) => void + callback: (error: Error | null, uri: string) => void, ) => { up.uri = uri; up.offset = 0; @@ -2301,12 +2301,12 @@ describe('resumable-upload', () => { assert(request.opts.headers); assert.equal( request.opts.headers['Content-Range'], - `bytes 0-*/${CONTENT_LENGTH}` + `bytes 0-*/${CONTENT_LENGTH}`, ); assert.ok( X_GOOG_API_HEADER_REGEX.test( - request.opts.headers['x-goog-api-client'] - ) + request.opts.headers['x-goog-api-client'], + ), ); assert.ok(USER_AGENT_REGEX.test(request.opts.headers['User-Agent'])); @@ -2327,7 +2327,7 @@ describe('resumable-upload', () => { up.chunkSize = CHUNK_SIZE_MULTIPLE; up.contentLength = CHUNK_SIZE_MULTIPLE * 8; up.createURI = ( - callback: (error: Error | null, uri: string) => void + callback: (error: Error | null, uri: string) => void, ) => { up.uri = uri; up.offset = 0; @@ -2469,19 +2469,19 @@ describe('resumable-upload', () => { assert(request.opts.headers); assert.equal( request.opts.headers['Content-Length'], - LAST_REQUEST_SIZE + LAST_REQUEST_SIZE, ); assert.equal( request.opts.headers['Content-Range'], - `bytes ${offset}-${endByte}/${CONTENT_LENGTH}` + `bytes ${offset}-${endByte}/${CONTENT_LENGTH}`, ); assert.ok( X_GOOG_API_HEADER_REGEX.test( - request.opts.headers['x-goog-api-client'] - ) + request.opts.headers['x-goog-api-client'], + ), ); assert.ok( - USER_AGENT_REGEX.test(request.opts.headers['User-Agent']) + USER_AGENT_REGEX.test(request.opts.headers['User-Agent']), ); } else { // The preceding chunks @@ -2492,15 +2492,15 @@ describe('resumable-upload', () => { assert.equal(request.opts.headers['Content-Length'], CHUNK_SIZE); assert.equal( request.opts.headers['Content-Range'], - `bytes ${offset}-${endByte}/${CONTENT_LENGTH}` + `bytes ${offset}-${endByte}/${CONTENT_LENGTH}`, ); assert.ok( X_GOOG_API_HEADER_REGEX.test( - request.opts.headers['x-goog-api-client'] - ) + request.opts.headers['x-goog-api-client'], + ), ); assert.ok( - USER_AGENT_REGEX.test(request.opts.headers['User-Agent']) + USER_AGENT_REGEX.test(request.opts.headers['User-Agent']), ); } } @@ -2521,7 +2521,7 @@ describe('resumable-upload', () => { up.contentLength = 0; up.createURI = ( - callback: (error: Error | null, uri: string) => void + callback: (error: Error | null, uri: string) => void, ) => { up.uri = uri; up.offset = 0; @@ -2593,12 +2593,12 @@ describe('resumable-upload', () => { assert.equal( request.opts.headers['Content-Range'], - `bytes 0-*/${CONTENT_LENGTH}` + `bytes 0-*/${CONTENT_LENGTH}`, ); assert.ok( X_GOOG_API_HEADER_REGEX.test( - request.opts.headers['x-goog-api-client'] - ) + request.opts.headers['x-goog-api-client'], + ), ); assert.ok(USER_AGENT_REGEX.test(request.opts.headers['User-Agent'])); diff --git a/test/signer.ts b/test/signer.ts index 7d729af15..07f9b47c5 100644 --- a/test/signer.ts +++ b/test/signer.ts @@ -141,7 +141,7 @@ describe('signer', () => { assert.strictEqual(v2arg.contentType, CONFIG.contentType); assert.deepStrictEqual( v2arg.extensionHeaders, - CONFIG.extensionHeaders + CONFIG.extensionHeaders, ); }); @@ -169,7 +169,7 @@ describe('signer', () => { assert.strictEqual(v4arg.contentType, CONFIG.contentType); assert.deepStrictEqual( v4arg.extensionHeaders, - CONFIG.extensionHeaders + CONFIG.extensionHeaders, ); }); @@ -179,7 +179,7 @@ describe('signer', () => { assert.throws( () => signer.getSignedUrl(CONFIG), - /Invalid signed URL version: v42\. Supported versions are 'v2' and 'v4'\./ + /Invalid signed URL version: v42\. Supported versions are 'v2' and 'v4'\./, ); }); }); @@ -290,7 +290,7 @@ describe('signer', () => { assert( (v2.getCall(0).args[0] as SignedUrlArgs).expiration, - expiresInSeconds + expiresInSeconds, ); }); }); @@ -381,8 +381,8 @@ describe('signer', () => { qsStringify({ ...query, ...CONFIG.queryParams, - }) - ) + }), + ), ); }); }); @@ -420,8 +420,8 @@ describe('signer', () => { const signedUrl = await signer.getSignedUrl(CONFIG); assert( signedUrl.startsWith( - `https://${bucket.name}.storage.googleapis.com/${file.name}` - ) + `https://${bucket.name}.storage.googleapis.com/${file.name}`, + ), ); }); @@ -551,7 +551,7 @@ describe('signer', () => { '', CONFIG.expiration, 'canonical-headers' + '/resource/path', - ].join('\n') + ].join('\n'), ); }); }); @@ -601,7 +601,7 @@ describe('signer', () => { }, { message: `Max allowed expiration is seven days (${SEVEN_DAYS} seconds).`, - } + }, ); }); @@ -622,10 +622,10 @@ describe('signer', () => { assert(err instanceof Error); assert.strictEqual( err.message, - `Max allowed expiration is seven days (${SEVEN_DAYS_IN_SECONDS.toString()} seconds).` + `Max allowed expiration is seven days (${SEVEN_DAYS_IN_SECONDS.toString()} seconds).`, ); return true; - } + }, ); }); @@ -639,7 +639,7 @@ describe('signer', () => { const arg = getCanonicalHeaders.getCall(0).args[0]; assert.strictEqual( arg.host, - PATH_STYLED_HOST.replace('https://', '') + PATH_STYLED_HOST.replace('https://', ''), ); }); @@ -786,11 +786,11 @@ describe('signer', () => { assert.strictEqual( arg['X-Goog-SignedHeaders'], - 'host;x-foo;x-goog-acl' + 'host;x-foo;x-goog-acl', ); assert.strictEqual( query['X-Goog-SignedHeaders'], - 'host;x-foo;x-goog-acl' + 'host;x-foo;x-goog-acl', ); }); @@ -880,8 +880,8 @@ describe('signer', () => { assert( blobToSign.startsWith( - ['GOOG4-RSA-SHA256', dateISO, credentialScope].join('\n') - ) + ['GOOG4-RSA-SHA256', dateISO, credentialScope].join('\n'), + ), ); }); @@ -904,7 +904,7 @@ describe('signer', () => { const query = (await signer['getSignedUrlV4'](CONFIG)) as Query; const signatureInHex = Buffer.from('signature', 'base64').toString( - 'hex' + 'hex', ); assert.strictEqual(query['X-Goog-Signature'], signatureInHex); }); @@ -978,7 +978,7 @@ describe('signer', () => { 'query', 'headers', 'signedHeaders', - SHA + SHA, ); const EXPECTED = [ diff --git a/test/transfer-manager.ts b/test/transfer-manager.ts index c2d0d750c..6ae0bf294 100644 --- a/test/transfer-manager.ts +++ b/test/transfer-manager.ts @@ -57,7 +57,7 @@ describe('Transfer Manager', () => { }, idempotencyStrategy: IdempotencyStrategy.RetryConditional, }, - }) + }), ); let sandbox: sinon.SinonSandbox; let transferManager: TransferManager; @@ -108,7 +108,7 @@ describe('Transfer Manager', () => { sandbox.stub(bucket, 'upload').callsFake((path, options) => { assert.strictEqual( (options as UploadOptions).preconditionOpts?.ifGenerationMatch, - 0 + 0, ); }); @@ -128,7 +128,7 @@ describe('Transfer Manager', () => { sandbox.stub(bucket, 'upload').callsFake((path, options) => { assert.strictEqual( (options as UploadOptions).destination, - expectedDestination + expectedDestination, ); }); @@ -147,7 +147,7 @@ describe('Transfer Manager', () => { const result = await transferManager.uploadManyFiles(paths); assert.strictEqual( result[0][0].name, - paths[0].split(path.sep).join(path.posix.sep) + paths[0].split(path.sep).join(path.posix.sep), ); }); @@ -157,7 +157,7 @@ describe('Transfer Manager', () => { sandbox.stub(bucket, 'upload').callsFake(async (_path, options) => { assert.strictEqual( (options as UploadOptions)[GCCL_GCS_CMD_KEY], - 'tm.upload_many' + 'tm.upload_many', ); }); @@ -224,7 +224,7 @@ describe('Transfer Manager', () => { sandbox.stub(file, 'download').callsFake(options => { assert.strictEqual( (options as DownloadOptions).destination, - expectedDestination + expectedDestination, ); }); await transferManager.downloadManyFiles([file], {prefix}); @@ -239,7 +239,7 @@ describe('Transfer Manager', () => { sandbox.stub(file, 'download').callsFake(options => { assert.strictEqual( (options as DownloadOptions).destination, - expectedDestination + expectedDestination, ); }); await transferManager.downloadManyFiles([file], {stripPrefix}); @@ -251,7 +251,7 @@ describe('Transfer Manager', () => { sandbox.stub(file, 'download').callsFake(async options => { assert.strictEqual( (options as DownloadOptions)[GCCL_GCS_CMD_KEY], - 'tm.download_many' + 'tm.download_many', ); }); @@ -264,7 +264,7 @@ describe('Transfer Manager', () => { }; const filename = 'first.txt'; const expectedDestination = path.normalize( - `${passthroughOptions.destination}/${filename}` + `${passthroughOptions.destination}/${filename}`, ); const download = (optionsOrCb?: DownloadOptions | DownloadCallback) => { if (typeof optionsOrCb === 'function') { @@ -285,14 +285,14 @@ describe('Transfer Manager', () => { sandbox.stub(firstFile, 'download').callsFake(options => { assert.strictEqual( (options as DownloadManyFilesOptions).skipIfExists, - 0 + 0, ); }); const secondFile = new File(bucket, 'second.txt'); sandbox.stub(secondFile, 'download').callsFake(options => { assert.strictEqual( (options as DownloadManyFilesOptions).skipIfExists, - 0 + 0, ); }); @@ -347,7 +347,7 @@ describe('Transfer Manager', () => { mkdirSpy.calledOnceWith(expectedDir, { recursive: true, }), - true + true, ); }); }); @@ -429,7 +429,7 @@ describe('Transfer Manager', () => { transferManager.downloadFileInChunks(file, {validation: 'crc32c'}), { code: 'CONTENT_DOWNLOAD_MISMATCH', - } + }, ); }); @@ -437,7 +437,7 @@ describe('Transfer Manager', () => { sandbox.stub(file, 'download').callsFake(async options => { assert.strictEqual( (options as DownloadOptions)[GCCL_GCS_CMD_KEY], - 'tm.download_sharded' + 'tm.download_sharded', ); return [Buffer.alloc(100)]; }); @@ -478,7 +478,7 @@ describe('Transfer Manager', () => { before(async () => { directory = await fsp.mkdtemp( - path.join(tmpdir(), 'tm-uploadFileInChunks-') + path.join(tmpdir(), 'tm-uploadFileInChunks-'), ); filePath = path.join(directory, 't.txt'); @@ -508,7 +508,7 @@ describe('Transfer Manager', () => { await transferManager.uploadFileInChunks( filePath, {}, - mockGeneratorFunction + mockGeneratorFunction, ); assert.strictEqual(fakeHelper.initiateUpload.calledOnce, true); assert.strictEqual(fakeHelper.uploadPart.calledOnce, true); @@ -523,7 +523,7 @@ describe('Transfer Manager', () => { { chunkSizeBytes: 32 * 1024 * 1024, }, - mockGeneratorFunction + mockGeneratorFunction, ); assert.strictEqual(readStreamSpy.calledOnceWith(filePath, options), true); @@ -545,7 +545,7 @@ describe('Transfer Manager', () => { ]), chunkSizeBytes: 32 * 1024 * 1024, }, - mockGeneratorFunction + mockGeneratorFunction, ); assert.strictEqual(readStreamSpy.calledOnceWith(filePath, options), true); @@ -561,7 +561,7 @@ describe('Transfer Manager', () => { [2, '321'], ]), }, - mockGeneratorFunction + mockGeneratorFunction, ); assert.strictEqual(fakeHelper.uploadId, '123'); @@ -572,7 +572,7 @@ describe('Transfer Manager', () => { const expectedErr = new MultiPartUploadError( 'Hello World', '', - new Map() + new Map(), ); mockGeneratorFunction = (bucket, fileName, uploadId, partsMap) => { fakeHelper = sandbox.createStubInstance(FakeXMLHelper); @@ -588,9 +588,9 @@ describe('Transfer Manager', () => { transferManager.uploadFileInChunks( filePath, {autoAbortFailure: false}, - mockGeneratorFunction + mockGeneratorFunction, ), - expectedErr + expectedErr, ); }); @@ -618,7 +618,7 @@ describe('Transfer Manager', () => { await transferManager.uploadFileInChunks( filePath, {headers: headersToAdd}, - mockGeneratorFunction + mockGeneratorFunction, ); }); @@ -626,7 +626,7 @@ describe('Transfer Manager', () => { const expectedErr = new MultiPartUploadError( 'Hello World', '', - new Map() + new Map(), ); const fakeId = '123'; @@ -648,7 +648,7 @@ describe('Transfer Manager', () => { }; assert.doesNotThrow(() => - transferManager.uploadFileInChunks(filePath, {}, mockGeneratorFunction) + transferManager.uploadFileInChunks(filePath, {}, mockGeneratorFunction), ); }); @@ -670,14 +670,14 @@ describe('Transfer Manager', () => { assert('x-goog-api-client' in opts.headers); assert.match( opts.headers['x-goog-api-client'], - /gccl-gcs-cmd\/tm.upload_sharded/ + /gccl-gcs-cmd\/tm.upload_sharded/, ); return { data: Buffer.from( ` 1 - ` + `, ), headers: {}, } as GaxiosResponse; @@ -715,7 +715,7 @@ describe('Transfer Manager', () => { data: Buffer.from( ` 1 - ` + `, ), headers: {}, } as GaxiosResponse; diff --git a/tsconfig.json b/tsconfig.json index 4167eb036..834dd78ce 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -13,8 +13,13 @@ "include": [ "src/*.ts", "src/*.cjs", + "test/*.ts", "internal-tooling/*.ts", "system-test/*.ts", - "src/nodejs-common/*.ts" + "src/nodejs-common/*.ts", + "test/nodejs-common/*.ts", + "conformance-test/*.ts", + "conformance-test/scenarios/*.ts", + "conformance-test/test-data/*.json" ] } \ No newline at end of file From 57691021cdd9af7f0bda88acdd659a0262cb9267 Mon Sep 17 00:00:00 2001 From: Thiyagu K Date: Wed, 4 Dec 2024 15:05:57 +0000 Subject: [PATCH 06/11] lint fix phase 2 lint fix phase 2 --- conformance-test/libraryMethods.ts | 2 +- .../performApplicationPerformanceTest.ts | 2 +- internal-tooling/performPerformanceTest.ts | 2 +- .../performTransferManagerTest.ts | 6 +-- internal-tooling/performanceTest.ts | 4 +- src/bucket.ts | 24 ++++----- src/file.ts | 18 ++++--- src/nodejs-common/service-object.ts | 4 +- src/nodejs-common/util.ts | 6 +-- src/resumable-upload.ts | 26 +++++----- system-test/storage.ts | 32 ++++++------ test/bucket.ts | 40 +++++++++----- test/file.ts | 4 +- test/hmacKey.ts | 4 +- test/nodejs-common/service-object.ts | 52 +++++++++---------- test/signer.ts | 24 ++++----- test/transfer-manager.ts | 2 +- 17 files changed, 137 insertions(+), 115 deletions(-) diff --git a/conformance-test/libraryMethods.ts b/conformance-test/libraryMethods.ts index 45de95eb3..d58924b83 100644 --- a/conformance-test/libraryMethods.ts +++ b/conformance-test/libraryMethods.ts @@ -797,7 +797,7 @@ export async function createBucket(options: ConformanceTestOptions) { const bucket = options.storage!.bucket('test-creating-bucket'); const [exists] = await bucket.exists(); if (exists) { - bucket.delete(); + await bucket.delete(); } await options.storage!.createBucket('test-creating-bucket'); } diff --git a/internal-tooling/performApplicationPerformanceTest.ts b/internal-tooling/performApplicationPerformanceTest.ts index eedcda1f6..59d3b40d5 100644 --- a/internal-tooling/performApplicationPerformanceTest.ts +++ b/internal-tooling/performApplicationPerformanceTest.ts @@ -188,4 +188,4 @@ async function performReadTest(): Promise { return result; } -main(); +void main(); diff --git a/internal-tooling/performPerformanceTest.ts b/internal-tooling/performPerformanceTest.ts index 82fda1c9f..5a6d9bcdb 100644 --- a/internal-tooling/performPerformanceTest.ts +++ b/internal-tooling/performPerformanceTest.ts @@ -214,4 +214,4 @@ async function performWriteReadTest(): Promise { return results; } -main(); +void main(); diff --git a/internal-tooling/performTransferManagerTest.ts b/internal-tooling/performTransferManagerTest.ts index 6e21e7746..4c1a3d6b1 100644 --- a/internal-tooling/performTransferManagerTest.ts +++ b/internal-tooling/performTransferManagerTest.ts @@ -82,12 +82,12 @@ async function performTestCleanup(fileOrFiles: File[] | File | string[]) { const filesToDelete = Array.isArray(fileOrFiles) ? fileOrFiles : [fileOrFiles]; - const promises = filesToDelete.map(f => { + const promises = filesToDelete.map(async f => { let fileToDelete = f; if (typeof f === 'string') { fileToDelete = bucket.file(f); } - (fileToDelete as File).delete({ignoreNotFound: true}); + await (fileToDelete as File).delete({ignoreNotFound: true}); }); return Promise.all(promises); } @@ -276,4 +276,4 @@ async function performChunkUploadDownloadTest(): Promise { return results; } -main(); +void main(); diff --git a/internal-tooling/performanceTest.ts b/internal-tooling/performanceTest.ts index 02adc10f7..ca7cf7ed3 100644 --- a/internal-tooling/performanceTest.ts +++ b/internal-tooling/performanceTest.ts @@ -96,9 +96,9 @@ function createWorker() { argv: process.argv.slice(2), }); - w.on('message', data => { + w.on('message', async data => { log('Successfully completed iteration.', argv.debug as boolean); - recordResult(data); + await recordResult(data); if (iterationsRemaining > 0) { createWorker(); } diff --git a/src/bucket.ts b/src/bucket.ts index df3b8dba1..a446e5948 100644 --- a/src/bucket.ts +++ b/src/bucket.ts @@ -1445,11 +1445,11 @@ class Bucket extends ServiceObject { * }, function(err, apiResponse) {}); * ``` */ - addLifecycleRule( + async addLifecycleRule( rule: LifecycleRule | LifecycleRule[], optionsOrCallback?: AddLifecycleRuleOptions | SetBucketMetadataCallback, callback?: SetBucketMetadataCallback, - ): Promise | void { + ): Promise | void> { let options: AddLifecycleRuleOptions = {}; if (typeof optionsOrCallback === 'function') { @@ -1487,7 +1487,7 @@ class Bucket extends ServiceObject { // The default behavior appends the previously-defined lifecycle rules with // the new ones just passed in by the user. - this.getMetadata((err: ApiError | null, metadata: BucketMetadata) => { + await this.getMetadata((err: ApiError | null, metadata: BucketMetadata) => { if (err) { callback!(err); return; @@ -2111,10 +2111,10 @@ class Bucket extends ServiceObject { * bucket.deleteFiles().then(function() {}); * ``` */ - deleteFiles( + async deleteFiles( queryOrCallback?: DeleteFilesOptions | DeleteFilesCallback, callback?: DeleteFilesCallback, - ): Promise | void { + ): Promise | void> { let query: DeleteFilesOptions = {}; if (typeof queryOrCallback === 'function') { callback = queryOrCallback; @@ -2135,7 +2135,7 @@ class Bucket extends ServiceObject { }); }; - (async () => { + await (async () => { try { let promises = []; const limit = pLimit(MAX_PARALLEL_LIMIT); @@ -2425,10 +2425,10 @@ class Bucket extends ServiceObject { * }); * ``` */ - enableLogging( + async enableLogging( config: EnableLoggingOptions, callback?: SetBucketMetadataCallback, - ): Promise | void { + ): Promise | void> { if ( !config || typeof config === 'function' || @@ -2453,7 +2453,7 @@ class Bucket extends ServiceObject { if (config?.ifMetagenerationNotMatch) { options.ifMetagenerationNotMatch = config.ifMetagenerationNotMatch; } - (async () => { + await (async () => { try { const [policy] = await this.iam.getPolicy(); policy.bindings.push({ @@ -4300,11 +4300,11 @@ class Bucket extends ServiceObject { * region_tag:storage_upload_encrypted_file * Example of uploading an encrypted file: */ - upload( + async upload( pathString: string, optionsOrCallback?: UploadOptions | UploadCallback, callback?: UploadCallback, - ): Promise | void { + ): Promise | void> { const upload = (numberOfRetries: number | undefined) => { const returnValue = AsyncRetry( async (bail: (err: Error) => void) => { @@ -4412,7 +4412,7 @@ class Bucket extends ServiceObject { }); } - upload(maxRetries); + await upload(maxRetries); } makeAllFilesPublicPrivate_( diff --git a/src/file.ts b/src/file.ts index 6fdfe2059..99fc93f38 100644 --- a/src/file.ts +++ b/src/file.ts @@ -1552,17 +1552,19 @@ class File extends ServiceObject { // which will return the bytes from the source without decompressing // gzip'd content. We then send it through decompressed, if // applicable, to the user. - const onResponse = ( + const onResponse = async ( err: Error | null, _body: ResponseBody, rawResponseStream: unknown, ) => { if (err) { // Get error message from the body. - this.getBufferFromReadable(rawResponseStream as Readable).then(body => { - err.message = body.toString('utf8'); - throughStream.destroy(err); - }); + await this.getBufferFromReadable(rawResponseStream as Readable).then( + body => { + err.message = body.toString('utf8'); + throughStream.destroy(err); + }, + ); return; } @@ -2487,10 +2489,10 @@ class File extends ServiceObject { * }); * ``` */ - getExpirationDate( + async getExpirationDate( callback?: GetExpirationDateCallback, - ): void | Promise { - this.getMetadata( + ): Promise> { + await this.getMetadata( (err: ApiError | null, metadata: FileMetadata, apiResponse: unknown) => { if (err) { callback!(err, null, apiResponse); diff --git a/src/nodejs-common/service-object.ts b/src/nodejs-common/service-object.ts index 4f83189d5..9953ce17e 100644 --- a/src/nodejs-common/service-object.ts +++ b/src/nodejs-common/service-object.ts @@ -400,7 +400,7 @@ class ServiceObject extends EventEmitter { callback!(null, instance, apiResponse); } - this.getMetadata(options, (err: ApiError | null, metadata) => { + this.getMetadata(options, async (err: ApiError | null, metadata) => { if (err) { if (err.code === 404 && autoCreate) { const args: Array = []; @@ -408,7 +408,7 @@ class ServiceObject extends EventEmitter { args.push(options); } args.push(onCreate); - self.create(...args); + await self.create(...args); return; } callback!(err, null, metadata as unknown as r.Response); diff --git a/src/nodejs-common/util.ts b/src/nodejs-common/util.ts index 9ba3051ad..f67856075 100644 --- a/src/nodejs-common/util.ts +++ b/src/nodejs-common/util.ts @@ -666,12 +666,12 @@ export class Util { reqOpts: DecorateRequestOptions, callback?: BodyResponseCallback, ): void | Abortable; - function makeAuthenticatedRequest( + async function makeAuthenticatedRequest( reqOpts: DecorateRequestOptions, optionsOrCallback?: | MakeAuthenticatedRequestOptions | BodyResponseCallback, - ): void | Abortable | Duplexify { + ): Promise { let stream: Duplexify; let projectId: string; const reqConfig = {...config}; @@ -827,7 +827,7 @@ export class Util { } }; - prepareRequest(); + await prepareRequest(); if (stream!) { return stream!; diff --git a/src/resumable-upload.ts b/src/resumable-upload.ts index f20a337b5..d05000b03 100644 --- a/src/resumable-upload.ts +++ b/src/resumable-upload.ts @@ -455,15 +455,15 @@ export class Upload extends Writable { this.#gcclGcsCmd = cfg[GCCL_GCS_CMD_KEY]; - this.once('writing', () => { + this.once('writing', async () => { if (this.uri) { - this.continueUploading(); + await this.continueUploading(); } else { - this.createURI(err => { + this.createURI(async err => { if (err) { return this.destroy(err); } - this.startUploading(); + await this.startUploading(); return; }); } @@ -956,7 +956,7 @@ export class Upload extends Writable { const err = e as ApiError; if (this.retryOptions.retryableErrorFn!(err)) { - this.attemptDelayedRetry({ + await this.attemptDelayedRetry({ status: NaN, data: err, }); @@ -1017,7 +1017,7 @@ export class Upload extends Writable { } // continue uploading next chunk - this.continueUploading(); + await this.continueUploading(); } else if ( !this.isSuccessfulResponse(resp.status) && !shouldContinueUploadInAnotherRequest @@ -1119,7 +1119,7 @@ export class Upload extends Writable { const err = e as ApiError; if (this.retryOptions.retryableErrorFn!(err)) { - this.attemptDelayedRetry({ + await this.attemptDelayedRetry({ status: NaN, data: err, }); @@ -1190,7 +1190,7 @@ export class Upload extends Writable { }, }; const res = await this.authClient.request(combinedReqOpts); - const successfulRequest = this.onResponse(res); + const successfulRequest = await this.onResponse(res); this.removeListener('error', errorCallback); return successfulRequest ? res : null; @@ -1199,7 +1199,7 @@ export class Upload extends Writable { /** * @return {bool} is the request good? */ - private onResponse(resp: GaxiosResponse) { + private async onResponse(resp: GaxiosResponse) { if ( resp.status !== 200 && this.retryOptions.retryableErrorFn!({ @@ -1208,7 +1208,7 @@ export class Upload extends Writable { name: resp.statusText, }) ) { - this.attemptDelayedRetry(resp); + await this.attemptDelayedRetry(resp); return false; } @@ -1219,13 +1219,15 @@ export class Upload extends Writable { /** * @param resp GaxiosResponse object from previous attempt */ - private attemptDelayedRetry(resp: Pick) { + private async attemptDelayedRetry( + resp: Pick, + ) { if (this.numRetries < this.retryOptions.maxRetries!) { if ( resp.status === NOT_FOUND_STATUS_CODE && this.numChunksReadInRequest === 0 ) { - this.startUploading(); + await this.startUploading(); } else { const retryDelay = this.getRetryDelay(); diff --git a/system-test/storage.ts b/system-test/storage.ts index db388dac6..4c44b103c 100644 --- a/system-test/storage.ts +++ b/system-test/storage.ts @@ -186,7 +186,7 @@ describe('storage', function () { const file = files[0]; const [isPublic] = await file.isPublic(); assert.strictEqual(isPublic, true); - assert.doesNotReject(file.download()); + await assert.doesNotReject(file.download()); }); }); @@ -326,7 +326,7 @@ describe('storage', function () { setTimeout(resolve, BUCKET_METADATA_UPDATE_WAIT_TIME), ); await bucket.makePrivate(); - assert.rejects(bucket.acl.get({entity: 'allUsers'}), err => { + await assert.rejects(bucket.acl.get({entity: 'allUsers'}), err => { assert.strictEqual((err as ApiError).code, 404); assert.strictEqual((err as ApiError).errors![0].reason, 'notFound'); }); @@ -420,9 +420,9 @@ describe('storage', function () { assert.strictEqual(err!.errors![0].reason, 'notFound'); return true; }; - assert.doesNotReject(file.makePublic()); - assert.doesNotReject(file.makePrivate()); - assert.rejects( + await assert.doesNotReject(file.makePublic()); + await assert.doesNotReject(file.makePrivate()); + await assert.rejects( file.acl.get({entity: 'allUsers'}), validateMakeFilePrivateRejects, ); @@ -483,13 +483,13 @@ describe('storage', function () { assert.strictEqual((err as ApiError).errors![0].reason, 'notFound'); return true; }; - assert.doesNotReject( + await assert.doesNotReject( bucket.upload(FILES.big.path, { resumable: true, private: true, }), ); - assert.rejects( + await assert.rejects( file.acl.get({entity: 'allUsers'}), validateMakeFilePrivateRejects, ); @@ -1767,14 +1767,14 @@ describe('storage', function () { it('should block an overwrite request', async () => { const file = await createFile(); - assert.rejects(file.save('new data'), (err: ApiError) => { + await assert.rejects(file.save('new data'), (err: ApiError) => { assert.strictEqual(err.code, 403); }); }); it('should block a delete request', async () => { const file = await createFile(); - assert.rejects(file.delete(), (err: ApiError) => { + await assert.rejects(file.delete(), (err: ApiError) => { assert.strictEqual(err.code, 403); }); }); @@ -2446,7 +2446,7 @@ describe('storage', function () { it('should handle non-network errors', async () => { const file = bucket.file('hi.jpg'); - assert.rejects(file.download(), (err: ApiError) => { + await assert.rejects(file.download(), (err: ApiError) => { assert.strictEqual((err as ApiError).code, 404); }); }); @@ -2620,8 +2620,8 @@ describe('storage', function () { .on('error', done) .pipe(fs.createWriteStream(tmpFilePath)) .on('error', done) - .on('finish', () => { - file.delete((err: ApiError | null) => { + .on('finish', async () => { + await file.delete((err: ApiError | null) => { assert.ifError(err); fs.readFile(tmpFilePath, (err, data) => { @@ -2658,7 +2658,7 @@ describe('storage', function () { }); it('should not download from the unencrypted file', async () => { - assert.rejects(unencryptedFile.download(), (err: ApiError) => { + await assert.rejects(unencryptedFile.download(), (err: ApiError) => { assert( err!.message.indexOf( [ @@ -3103,7 +3103,7 @@ describe('storage', function () { // We can't actually create a channel. But we can test to see that we're // reaching the right endpoint with the API request. const channel = storage.channel('id', 'resource-id'); - assert.rejects(channel.stop(), (err: ApiError) => { + await assert.rejects(channel.stop(), (err: ApiError) => { assert.strictEqual((err as ApiError).code, 404); assert.strictEqual(err!.message.indexOf("Channel 'id' not found"), 0); }); @@ -3189,7 +3189,7 @@ describe('storage', function () { }); it('should get metadata for an HMAC key', async function () { - delay(this, accessId); + await delay(this, accessId); const hmacKey = storage.hmacKey(accessId, {projectId: HMAC_PROJECT}); const [metadata] = await hmacKey.getMetadata(); assert.strictEqual(metadata.accessId, accessId); @@ -3565,7 +3565,7 @@ describe('storage', function () { }); await fetch(signedDeleteUrl, {method: 'DELETE'}); - assert.rejects( + await assert.rejects( () => file.getMetadata(), (err: ApiError) => err.code === 404, ); diff --git a/test/bucket.ts b/test/bucket.ts index a5ea54811..457ee912a 100644 --- a/test/bucket.ts +++ b/test/bucket.ts @@ -1492,7 +1492,9 @@ describe('Bucket', () => { requesterPays: false, }, }); - Promise.resolve([]).then(resp => callback(null, ...resp)); + Promise.resolve([]) + .then(resp => callback(null, ...resp)) + .catch(() => {}); }; bucket.disableRequesterPays(done); @@ -1513,10 +1515,12 @@ describe('Bucket', () => { it('should set autoRetry to false when ifMetagenerationMatch is undefined', done => { bucket.setMetadata = () => { - Promise.resolve().then(() => { - assert.strictEqual(bucket.storage.retryOptions.autoRetry, false); - done(); - }); + Promise.resolve() + .then(() => { + assert.strictEqual(bucket.storage.retryOptions.autoRetry, false); + done(); + }) + .catch(() => {}); }; bucket.disableRequesterPays(); }); @@ -1668,9 +1672,9 @@ describe('Bucket', () => { optionsOrCallback: {}, callback: Function, ) => { - Promise.resolve([setMetadataResponse]).then(resp => - callback(null, ...resp), - ); + Promise.resolve([setMetadataResponse]) + .then(resp => callback(null, ...resp)) + .catch(() => {}); }; bucket.enableLogging( @@ -1709,7 +1713,9 @@ describe('Bucket', () => { requesterPays: true, }, }); - Promise.resolve([]).then(resp => callback(null, ...resp)); + Promise.resolve([]) + .then(resp => callback(null, ...resp)) + .catch(() => {}); }; bucket.enableRequesterPays(done); @@ -2418,7 +2424,9 @@ describe('Bucket', () => { retentionPolicy: null, }); - Promise.resolve([]).then(resp => callback(null, ...resp)); + Promise.resolve([]) + .then(resp => callback(null, ...resp)) + .catch(() => {}); }; bucket.removeRetentionPeriod(done); @@ -2506,7 +2514,9 @@ describe('Bucket', () => { callback: Function, ) => { assert.strictEqual(metadata.labels, labels); - Promise.resolve([]).then(resp => callback(null, ...resp)); + Promise.resolve([]) + .then(resp => callback(null, ...resp)) + .catch(() => {}); }; bucket.setLabels(labels, done); }); @@ -2537,7 +2547,9 @@ describe('Bucket', () => { }, }); - Promise.resolve([]).then(resp => callback(null, ...resp)); + Promise.resolve([]) + .then(resp => callback(null, ...resp)) + .catch(() => {}); }; bucket.setRetentionPeriod(duration, done); @@ -2595,7 +2607,9 @@ describe('Bucket', () => { ) => { assert.deepStrictEqual(metadata, {storageClass: STORAGE_CLASS}); assert.strictEqual(options, OPTIONS); - Promise.resolve([]).then(resp => callback(null, ...resp)); + Promise.resolve([]) + .then(resp => callback(null, ...resp)) + .catch(() => {}); }; bucket.setStorageClass(STORAGE_CLASS, OPTIONS, CALLBACK); diff --git a/test/file.ts b/test/file.ts index 0890fabc0..e61e126f0 100644 --- a/test/file.ts +++ b/test/file.ts @@ -3743,7 +3743,9 @@ describe('File', () => { optionsOrCallback: SetMetadataOptions | MetadataCallback, cb: MetadataCallback, ) => { - Promise.resolve([apiResponse]).then(resp => cb(null, ...resp)); + Promise.resolve([apiResponse]) + .then(resp => cb(null, ...resp)) + .catch(() => {}); }; file.makePrivate((err: Error, apiResponse_: {}) => { diff --git a/test/hmacKey.ts b/test/hmacKey.ts index fc8e858f4..b0217c4a6 100644 --- a/test/hmacKey.ts +++ b/test/hmacKey.ts @@ -100,7 +100,9 @@ describe('HmacKey', () => { it('should correctly call setMetadata', done => { hmacKey.setMetadata = (metadata: HmacKeyMetadata, callback: Function) => { assert.deepStrictEqual(metadata.accessId, ACCESS_ID); - Promise.resolve([]).then(resp => callback(null, ...resp)); + Promise.resolve([]) + .then(resp => callback(null, ...resp)) + .catch(() => {}); }; hmacKey.setMetadata({accessId: ACCESS_ID}, done); diff --git a/test/nodejs-common/service-object.ts b/test/nodejs-common/service-object.ts index af1945ad9..2b2508590 100644 --- a/test/nodejs-common/service-object.ts +++ b/test/nodejs-common/service-object.ts @@ -415,8 +415,8 @@ describe('ServiceObject', () => { sandbox .stub(ServiceObject.prototype, 'request') .callsArgWith(1, null, null, {}); - assert.doesNotThrow(() => { - serviceObject.delete(); + assert.doesNotThrow(async () => { + await serviceObject.delete(); }); }); @@ -433,9 +433,9 @@ describe('ServiceObject', () => { }); describe('exists', () => { - it('should call get', done => { + it('should call get', async done => { sandbox.stub(serviceObject, 'get').callsFake(() => done()); - serviceObject.exists(() => {}); + await serviceObject.exists(() => {}); }); it('should accept options', done => { @@ -452,31 +452,31 @@ describe('ServiceObject', () => { serviceObject.exists(options, assert.ifError); }); - it('should execute callback with false if 404', done => { + it('should execute callback with false if 404', async done => { const error = new ApiError(''); error.code = 404; sandbox.stub(serviceObject, 'get').callsArgWith(1, error); - serviceObject.exists((err: Error, exists: boolean) => { + await serviceObject.exists((err: Error, exists: boolean) => { assert.ifError(err); assert.strictEqual(exists, false); done(); }); }); - it('should execute callback with error if not 404', done => { + it('should execute callback with error if not 404', async done => { const error = new ApiError(''); error.code = 500; sandbox.stub(serviceObject, 'get').callsArgWith(1, error); - serviceObject.exists((err: Error, exists: boolean) => { + await serviceObject.exists((err: Error, exists: boolean) => { assert.strictEqual(err, error); assert.strictEqual(exists, undefined); done(); }); }); - it('should execute callback with true if no error', done => { + it('should execute callback with true if no error', async done => { sandbox.stub(serviceObject, 'get').callsArgWith(1, null); - serviceObject.exists((err: Error, exists: boolean) => { + await serviceObject.exists((err: Error, exists: boolean) => { assert.ifError(err); assert.strictEqual(exists, true); done(); @@ -652,7 +652,7 @@ describe('ServiceObject', () => { }); describe('getMetadata', () => { - it('should make the correct request', done => { + it('should make the correct request', async done => { sandbox.stub(ServiceObject.prototype, 'request').callsFake(function ( this: SO.ServiceObject, reqOpts, @@ -665,7 +665,7 @@ describe('ServiceObject', () => { done(); cb(null, null, {} as r.Response); }); - serviceObject.getMetadata(() => {}); + await serviceObject.getMetadata(() => {}); }); it('should accept options', done => { @@ -748,35 +748,35 @@ describe('ServiceObject', () => { }); }); - it('should execute callback with error & apiResponse', done => { + it('should execute callback with error & apiResponse', async done => { const error = new Error('ಠ_ಠ'); sandbox.stub(ServiceObject.prototype, 'request').callsArgWith(1, error); - serviceObject.getMetadata((err: Error, metadata: {}) => { + await serviceObject.getMetadata((err: Error, metadata: {}) => { assert.strictEqual(err, error); assert.strictEqual(metadata, undefined); done(); }); }); - it('should update metadata', done => { + it('should update metadata', async done => { const apiResponse = {}; sandbox .stub(ServiceObject.prototype, 'request') .callsArgWith(1, null, {}, apiResponse); - serviceObject.getMetadata((err: Error) => { + await serviceObject.getMetadata((err: Error) => { assert.ifError(err); assert.deepStrictEqual(serviceObject.metadata, apiResponse); done(); }); }); - it('should execute callback with metadata & API response', done => { + it('should execute callback with metadata & API response', async done => { const apiResponse = {}; const requestResponse = {body: apiResponse}; sandbox .stub(ServiceObject.prototype, 'request') .callsArgWith(1, null, apiResponse, requestResponse); - serviceObject.getMetadata((err: Error, metadata: {}) => { + await serviceObject.getMetadata((err: Error, metadata: {}) => { assert.ifError(err); assert.strictEqual(metadata, apiResponse); done(); @@ -877,7 +877,7 @@ describe('ServiceObject', () => { }); describe('setMetadata', () => { - it('should make the correct request', done => { + it('should make the correct request', async done => { const metadata = {metadataProperty: true}; sandbox.stub(ServiceObject.prototype, 'request').callsFake(function ( this: SO.ServiceObject, @@ -893,7 +893,7 @@ describe('ServiceObject', () => { done(); cb(null, null, {} as r.Response); }); - serviceObject.setMetadata(metadata, () => {}); + await serviceObject.setMetadata(metadata, () => {}); }); it('should accept options', done => { @@ -980,35 +980,35 @@ describe('ServiceObject', () => { ); }); - it('should execute callback with error & apiResponse', done => { + it('should execute callback with error & apiResponse', async done => { const error = new Error('Error.'); sandbox.stub(ServiceObject.prototype, 'request').callsArgWith(1, error); - serviceObject.setMetadata({}, (err: Error, apiResponse_: {}) => { + await serviceObject.setMetadata({}, (err: Error, apiResponse_: {}) => { assert.strictEqual(err, error); assert.strictEqual(apiResponse_, undefined); done(); }); }); - it('should update metadata', done => { + it('should update metadata', async done => { const apiResponse = {}; sandbox .stub(ServiceObject.prototype, 'request') .callsArgWith(1, undefined, apiResponse); - serviceObject.setMetadata({}, (err: Error) => { + await serviceObject.setMetadata({}, (err: Error) => { assert.ifError(err); assert.strictEqual(serviceObject.metadata, apiResponse); done(); }); }); - it('should execute callback with metadata & API response', done => { + it('should execute callback with metadata & API response', async done => { const body = {}; const apiResponse = {body}; sandbox .stub(ServiceObject.prototype, 'request') .callsArgWith(1, null, body, apiResponse); - serviceObject.setMetadata({}, (err: Error, metadata: {}) => { + await serviceObject.setMetadata({}, (err: Error, metadata: {}) => { assert.ifError(err); assert.strictEqual(metadata, body); done(); diff --git a/test/signer.ts b/test/signer.ts index 07f9b47c5..c7f504d2f 100644 --- a/test/signer.ts +++ b/test/signer.ts @@ -208,8 +208,8 @@ describe('signer', () => { const accessibleAt = accessibleAtNumber; const expires = accessibleAt - 86400000; - assert.throws(() => { - signer.getSignedUrl({ + assert.throws(async () => { + await signer.getSignedUrl({ version: 'v4', method: 'GET', accessibleAt, @@ -260,8 +260,8 @@ describe('signer', () => { it('should throw if a date is invalid', () => { const accessibleAt = new Date('31-12-2019'); - assert.throws(() => { - signer.getSignedUrl({ + assert.throws(async () => { + await signer.getSignedUrl({ version: 'v4', method: 'GET', accessibleAt, @@ -565,12 +565,12 @@ describe('signer', () => { }); }); - it('rejects with SigningError on signing Error', () => { + it('rejects with SigningError on signing Error', async () => { const err = new Error('my-err'); err.stack = 'some-stack-trace'; sandbox.stub(authClient, 'sign').rejects(err); - assert.rejects(() => signer['getSignedUrlV2'](CONFIG), { + await assert.rejects(() => signer['getSignedUrlV2'](CONFIG), { name: 'SigningError', message: 'my-err', stack: 'some-stack-trace', @@ -596,8 +596,8 @@ describe('signer', () => { const SEVEN_DAYS = 7 * 24 * 60 * 60; assert.throws( - () => { - signer['getSignedUrlV4'](CONFIG); + async () => { + await signer['getSignedUrlV4'](CONFIG); }, { message: `Max allowed expiration is seven days (${SEVEN_DAYS} seconds).`, @@ -722,8 +722,8 @@ describe('signer', () => { ...CONFIG, }; - assert.throws(() => { - signer['getSignedUrlV4'](CONFIG), + assert.throws(async () => { + await signer['getSignedUrlV4'](CONFIG), SignerExceptionMessages.X_GOOG_CONTENT_SHA256; }); }); @@ -885,12 +885,12 @@ describe('signer', () => { ); }); - it('rejects with SigningError on signing Error', () => { + it('rejects with SigningError on signing Error', async () => { const err = new Error('my-err'); err.stack = 'some-stack-trace'; sinon.stub(authClient, 'sign').rejects(err); - assert.rejects(() => signer['getSignedUrlV4'](CONFIG), { + await assert.rejects(() => signer['getSignedUrlV4'](CONFIG), { name: 'SigningError', message: 'my-err', stack: 'some-stack-trace', diff --git a/test/transfer-manager.ts b/test/transfer-manager.ts index 6ae0bf294..810346bd0 100644 --- a/test/transfer-manager.ts +++ b/test/transfer-manager.ts @@ -584,7 +584,7 @@ describe('Transfer Manager', () => { fakeHelper.abortUpload.resolves(); return fakeHelper; }; - assert.rejects( + await assert.rejects( transferManager.uploadFileInChunks( filePath, {autoAbortFailure: false}, From 3c1b5de02c6a70bfb516d34d4701f0291bcc2f51 Mon Sep 17 00:00:00 2001 From: Thiyagu K Date: Wed, 4 Dec 2024 18:03:06 +0000 Subject: [PATCH 07/11] bug fix --- src/bucket.ts | 28 ++++++++++++++++------------ src/file.ts | 7 ++++--- src/nodejs-common/util.ts | 7 ++++--- 3 files changed, 24 insertions(+), 18 deletions(-) diff --git a/src/bucket.ts b/src/bucket.ts index a446e5948..e5d7ef00c 100644 --- a/src/bucket.ts +++ b/src/bucket.ts @@ -1445,11 +1445,11 @@ class Bucket extends ServiceObject { * }, function(err, apiResponse) {}); * ``` */ - async addLifecycleRule( + addLifecycleRule( rule: LifecycleRule | LifecycleRule[], optionsOrCallback?: AddLifecycleRuleOptions | SetBucketMetadataCallback, callback?: SetBucketMetadataCallback, - ): Promise | void> { + ): Promise | void { let options: AddLifecycleRuleOptions = {}; if (typeof optionsOrCallback === 'function') { @@ -1487,7 +1487,8 @@ class Bucket extends ServiceObject { // The default behavior appends the previously-defined lifecycle rules with // the new ones just passed in by the user. - await this.getMetadata((err: ApiError | null, metadata: BucketMetadata) => { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.getMetadata((err: ApiError | null, metadata: BucketMetadata) => { if (err) { callback!(err); return; @@ -2111,10 +2112,10 @@ class Bucket extends ServiceObject { * bucket.deleteFiles().then(function() {}); * ``` */ - async deleteFiles( + deleteFiles( queryOrCallback?: DeleteFilesOptions | DeleteFilesCallback, callback?: DeleteFilesCallback, - ): Promise | void> { + ): Promise | void { let query: DeleteFilesOptions = {}; if (typeof queryOrCallback === 'function') { callback = queryOrCallback; @@ -2135,7 +2136,8 @@ class Bucket extends ServiceObject { }); }; - await (async () => { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + (async () => { try { let promises = []; const limit = pLimit(MAX_PARALLEL_LIMIT); @@ -2425,10 +2427,10 @@ class Bucket extends ServiceObject { * }); * ``` */ - async enableLogging( + enableLogging( config: EnableLoggingOptions, callback?: SetBucketMetadataCallback, - ): Promise | void> { + ): Promise | void { if ( !config || typeof config === 'function' || @@ -2453,7 +2455,8 @@ class Bucket extends ServiceObject { if (config?.ifMetagenerationNotMatch) { options.ifMetagenerationNotMatch = config.ifMetagenerationNotMatch; } - await (async () => { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + (async () => { try { const [policy] = await this.iam.getPolicy(); policy.bindings.push({ @@ -4300,11 +4303,11 @@ class Bucket extends ServiceObject { * region_tag:storage_upload_encrypted_file * Example of uploading an encrypted file: */ - async upload( + upload( pathString: string, optionsOrCallback?: UploadOptions | UploadCallback, callback?: UploadCallback, - ): Promise | void> { + ): Promise | void { const upload = (numberOfRetries: number | undefined) => { const returnValue = AsyncRetry( async (bail: (err: Error) => void) => { @@ -4412,7 +4415,8 @@ class Bucket extends ServiceObject { }); } - await upload(maxRetries); + // eslint-disable-next-line @typescript-eslint/no-floating-promises + upload(maxRetries); } makeAllFilesPublicPrivate_( diff --git a/src/file.ts b/src/file.ts index 99fc93f38..297872841 100644 --- a/src/file.ts +++ b/src/file.ts @@ -2489,10 +2489,11 @@ class File extends ServiceObject { * }); * ``` */ - async getExpirationDate( + getExpirationDate( callback?: GetExpirationDateCallback, - ): Promise> { - await this.getMetadata( + ): void | Promise { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.getMetadata( (err: ApiError | null, metadata: FileMetadata, apiResponse: unknown) => { if (err) { callback!(err, null, apiResponse); diff --git a/src/nodejs-common/util.ts b/src/nodejs-common/util.ts index f67856075..6ec55f1d4 100644 --- a/src/nodejs-common/util.ts +++ b/src/nodejs-common/util.ts @@ -666,12 +666,12 @@ export class Util { reqOpts: DecorateRequestOptions, callback?: BodyResponseCallback, ): void | Abortable; - async function makeAuthenticatedRequest( + function makeAuthenticatedRequest( reqOpts: DecorateRequestOptions, optionsOrCallback?: | MakeAuthenticatedRequestOptions | BodyResponseCallback, - ): Promise { + ): void | Abortable | Duplexify { let stream: Duplexify; let projectId: string; const reqConfig = {...config}; @@ -827,7 +827,8 @@ export class Util { } }; - await prepareRequest(); + // eslint-disable-next-line @typescript-eslint/no-floating-promises + prepareRequest(); if (stream!) { return stream!; From 515c7ffc3b6a4042efbc14ebf5b0703722e0aaa1 Mon Sep 17 00:00:00 2001 From: Thiyagu K Date: Wed, 4 Dec 2024 18:54:06 +0000 Subject: [PATCH 08/11] test case error fix --- test/signer.ts | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/test/signer.ts b/test/signer.ts index c7f504d2f..41d1b4451 100644 --- a/test/signer.ts +++ b/test/signer.ts @@ -208,8 +208,9 @@ describe('signer', () => { const accessibleAt = accessibleAtNumber; const expires = accessibleAt - 86400000; - assert.throws(async () => { - await signer.getSignedUrl({ + assert.throws(() => { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + signer.getSignedUrl({ version: 'v4', method: 'GET', accessibleAt, @@ -260,8 +261,9 @@ describe('signer', () => { it('should throw if a date is invalid', () => { const accessibleAt = new Date('31-12-2019'); - assert.throws(async () => { - await signer.getSignedUrl({ + assert.throws(() => { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + signer.getSignedUrl({ version: 'v4', method: 'GET', accessibleAt, @@ -596,8 +598,9 @@ describe('signer', () => { const SEVEN_DAYS = 7 * 24 * 60 * 60; assert.throws( - async () => { - await signer['getSignedUrlV4'](CONFIG); + () => { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + signer['getSignedUrlV4'](CONFIG); }, { message: `Max allowed expiration is seven days (${SEVEN_DAYS} seconds).`, @@ -722,8 +725,9 @@ describe('signer', () => { ...CONFIG, }; - assert.throws(async () => { - await signer['getSignedUrlV4'](CONFIG), + assert.throws(() => { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + signer['getSignedUrlV4'](CONFIG), SignerExceptionMessages.X_GOOG_CONTENT_SHA256; }); }); From 258a38e71e9e07dfbe546a769223bc673defbfdf Mon Sep 17 00:00:00 2001 From: Thiyagu K Date: Thu, 5 Dec 2024 10:27:29 +0000 Subject: [PATCH 09/11] test case error fix --- src/resumable-upload.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/resumable-upload.ts b/src/resumable-upload.ts index d05000b03..8a91a098d 100644 --- a/src/resumable-upload.ts +++ b/src/resumable-upload.ts @@ -1199,7 +1199,7 @@ export class Upload extends Writable { /** * @return {bool} is the request good? */ - private async onResponse(resp: GaxiosResponse) { + private onResponse(resp: GaxiosResponse) { if ( resp.status !== 200 && this.retryOptions.retryableErrorFn!({ @@ -1208,7 +1208,7 @@ export class Upload extends Writable { name: resp.statusText, }) ) { - await this.attemptDelayedRetry(resp); + void this.attemptDelayedRetry(resp); return false; } From 2af55984f75edfef407fd9f82bd86db69a461a93 Mon Sep 17 00:00:00 2001 From: Thiyagu K Date: Tue, 10 Dec 2024 05:22:27 +0000 Subject: [PATCH 10/11] chore: upgrade to Node 18 chore: upgrade to Node 18 --- .kokoro/common.cfg | 2 +- .kokoro/continuous/node18/common.cfg | 24 +++++++++++++++++++ .kokoro/continuous/node18/lint.cfg | 4 ++++ .../node18}/samples-test.cfg | 0 .../node18}/system-test.cfg | 0 .../node14 => continuous/node18}/test.cfg | 0 .../presubmit/{node14 => node18}/common.cfg | 2 +- .kokoro/presubmit/node18/samples-test.cfg | 12 ++++++++++ .kokoro/presubmit/node18/system-test.cfg | 12 ++++++++++ .kokoro/presubmit/node18/test.cfg | 0 .kokoro/release/docs-devsite.cfg | 2 +- .kokoro/release/docs.cfg | 2 +- .kokoro/release/publish.cfg | 2 +- .kokoro/samples-test.sh | 2 +- .kokoro/system-test.sh | 2 +- .kokoro/test.sh | 2 +- owlbot.py | 4 ++-- 17 files changed, 62 insertions(+), 10 deletions(-) create mode 100644 .kokoro/continuous/node18/common.cfg create mode 100644 .kokoro/continuous/node18/lint.cfg rename .kokoro/{presubmit/node14 => continuous/node18}/samples-test.cfg (100%) rename .kokoro/{presubmit/node14 => continuous/node18}/system-test.cfg (100%) rename .kokoro/{presubmit/node14 => continuous/node18}/test.cfg (100%) rename .kokoro/presubmit/{node14 => node18}/common.cfg (89%) create mode 100644 .kokoro/presubmit/node18/samples-test.cfg create mode 100644 .kokoro/presubmit/node18/system-test.cfg create mode 100644 .kokoro/presubmit/node18/test.cfg diff --git a/.kokoro/common.cfg b/.kokoro/common.cfg index 4ee7584a3..713afb2ec 100644 --- a/.kokoro/common.cfg +++ b/.kokoro/common.cfg @@ -16,7 +16,7 @@ build_file: "nodejs-storage/.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/node18/common.cfg b/.kokoro/continuous/node18/common.cfg new file mode 100644 index 000000000..807992318 --- /dev/null +++ b/.kokoro/continuous/node18/common.cfg @@ -0,0 +1,24 @@ +# 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: "nodejs-storage/.kokoro/trampoline_v2.sh" + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" +} +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-storage/.kokoro/test.sh" +} \ No newline at end of file diff --git a/.kokoro/continuous/node18/lint.cfg b/.kokoro/continuous/node18/lint.cfg new file mode 100644 index 000000000..6b291575e --- /dev/null +++ b/.kokoro/continuous/node18/lint.cfg @@ -0,0 +1,4 @@ +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-storage/.kokoro/lint.sh" +} \ No newline at end of file diff --git a/.kokoro/presubmit/node14/samples-test.cfg b/.kokoro/continuous/node18/samples-test.cfg similarity index 100% rename from .kokoro/presubmit/node14/samples-test.cfg rename to .kokoro/continuous/node18/samples-test.cfg diff --git a/.kokoro/presubmit/node14/system-test.cfg b/.kokoro/continuous/node18/system-test.cfg similarity index 100% rename from .kokoro/presubmit/node14/system-test.cfg rename to .kokoro/continuous/node18/system-test.cfg diff --git a/.kokoro/presubmit/node14/test.cfg b/.kokoro/continuous/node18/test.cfg similarity index 100% rename from .kokoro/presubmit/node14/test.cfg rename to .kokoro/continuous/node18/test.cfg diff --git a/.kokoro/presubmit/node14/common.cfg b/.kokoro/presubmit/node18/common.cfg similarity index 89% rename from .kokoro/presubmit/node14/common.cfg rename to .kokoro/presubmit/node18/common.cfg index 4ee7584a3..713afb2ec 100644 --- a/.kokoro/presubmit/node14/common.cfg +++ b/.kokoro/presubmit/node18/common.cfg @@ -16,7 +16,7 @@ build_file: "nodejs-storage/.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/presubmit/node18/samples-test.cfg b/.kokoro/presubmit/node18/samples-test.cfg new file mode 100644 index 000000000..2137cefc0 --- /dev/null +++ b/.kokoro/presubmit/node18/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/nodejs-storage/.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/node18/system-test.cfg b/.kokoro/presubmit/node18/system-test.cfg new file mode 100644 index 000000000..c7c9507a8 --- /dev/null +++ b/.kokoro/presubmit/node18/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/nodejs-storage/.kokoro/system-test.sh" +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "long-door-651-kokoro-system-test-service-account,client-library-test-universe-domain-credential" +} \ No newline at end of file diff --git a/.kokoro/presubmit/node18/test.cfg b/.kokoro/presubmit/node18/test.cfg new file mode 100644 index 000000000..e69de29bb diff --git a/.kokoro/release/docs-devsite.cfg b/.kokoro/release/docs-devsite.cfg index eea22f239..c98f038de 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.cfg b/.kokoro/release/docs.cfg index 25c377eef..71c80e6b0 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 019cc24a5..85aa13842 100644 --- a/.kokoro/release/publish.cfg +++ b/.kokoro/release/publish.cfg @@ -30,7 +30,7 @@ build_file: "nodejs-storage/.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 e219954ae..6b69337ef 100755 --- a/.kokoro/system-test.sh +++ b/.kokoro/system-test.sh @@ -55,7 +55,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.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/owlbot.py b/owlbot.py index 8e2e3b940..4768d85c8 100644 --- a/owlbot.py +++ b/owlbot.py @@ -26,8 +26,8 @@ '.github/sync-repo-settings.yaml', '.prettierrc.js', '.mocharc.js', - '.kokoro/continuous/node14/system-test.cfg', - '.kokoro/presubmit/node14/system-test.cfg', + '.kokoro/continuous/node18/system-test.cfg', + '.kokoro/presubmit/node18/system-test.cfg', '.kokoro/release/publish.cfg', '.kokoro/system-test.sh' ]) From f9dc145a019f1e7f29fab2a25b6dd786ba52925e Mon Sep 17 00:00:00 2001 From: Thiyagu K Date: Thu, 12 Dec 2024 07:09:33 +0000 Subject: [PATCH 11/11] Removed unnecessary dependency. Removed unnecessary dependency. --- package.json | 2 -- 1 file changed, 2 deletions(-) diff --git a/package.json b/package.json index ae846f34e..48e788a43 100644 --- a/package.json +++ b/package.json @@ -117,11 +117,9 @@ "linkinator": "^6.1.2", "mocha": "^9.2.2", "mockery": "^2.1.0", - "nise": "6.0.0", "nock": "~13.5.0", "node-fetch": "^2.6.7", "pack-n-play": "^2.0.0", - "path-to-regexp": "6.3.0", "proxyquire": "^2.1.3", "sinon": "^18.0.0", "tmp": "^0.2.0",