diff --git a/sdk/storage/storage-blob/.prettierignore b/sdk/storage/storage-blob/.prettierignore new file mode 100644 index 000000000000..3fd7f651ed5f --- /dev/null +++ b/sdk/storage/storage-blob/.prettierignore @@ -0,0 +1,2 @@ +src/generated/**/*.ts +package-lock.json diff --git a/sdk/storage/storage-blob/.prettierrc.json b/sdk/storage/storage-blob/.prettierrc.json deleted file mode 100644 index 1ca87ab7d8af..000000000000 --- a/sdk/storage/storage-blob/.prettierrc.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "singleQuote": false -} diff --git a/sdk/storage/storage-blob/gulpfile.js b/sdk/storage/storage-blob/gulpfile.js index a99dc6ee1dbd..c66aa821e000 100644 --- a/sdk/storage/storage-blob/gulpfile.js +++ b/sdk/storage/storage-blob/gulpfile.js @@ -6,11 +6,7 @@ const zipFileName = `azurestoragejs.blob-${version}.zip`; gulp.task("zip", function(callback) { gulp - .src([ - "browser/azure-storage.blob.js", - "browser/azure-storage.blob.min.js", - "browser/*.txt" - ]) + .src(["browser/azure-storage.blob.js", "browser/azure-storage.blob.min.js", "browser/*.txt"]) .pipe(zip(zipFileName)) .pipe(gulp.dest("browser")) .on("end", callback); diff --git a/sdk/storage/storage-blob/karma.conf.js b/sdk/storage/storage-blob/karma.conf.js index bf041dcb0346..77093d5f6b7b 100644 --- a/sdk/storage/storage-blob/karma.conf.js +++ b/sdk/storage/storage-blob/karma.conf.js @@ -1,6 +1,6 @@ // https://github.com/karma-runner/karma-chrome-launcher process.env.CHROME_BIN = require("puppeteer").executablePath(); -require("dotenv").config({path:"../.env"}); +require("dotenv").config({ path: "../.env" }); module.exports = function(config) { config.set({ diff --git a/sdk/storage/storage-blob/package.json b/sdk/storage/storage-blob/package.json index 667b565f9824..c180b3a101c9 100644 --- a/sdk/storage/storage-blob/package.json +++ b/sdk/storage/storage-blob/package.json @@ -73,10 +73,10 @@ "build:nodebrowser": "rollup -c 2>&1", "build:test": "npm run build:es6 && rollup -c rollup.test.config.js 2>&1", "build": "npm run build:es6 && npm run build:nodebrowser && npm run build:browserzip", - "check-format": "prettier --list-different --config .prettierrc.json \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", + "check-format": "prettier --list-different --config ../../.prettierrc.json \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", "clean": "rimraf dist dist-esm dist-test typings temp browser/*.js* browser/*.zip statistics.html coverage coverage-browser .nyc_output *.tgz *.log test*.xml TEST*.xml", "extract-api": "tsc -p . && api-extractor run --local", - "format": "prettier --write --config .prettierrc.json \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", + "format": "prettier --write --config ../../.prettierrc.json \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", "integration-test:browser": "karma start --single-run", "integration-test:node": "cross-env TS_NODE_COMPILER_OPTIONS=\"{\\\"module\\\": \\\"commonjs\\\"}\" nyc mocha --compilers ts-node/register --require source-map-support/register --reporter mocha-multi --reporter-options spec=-,mocha-junit-reporter=- --full-trace --no-timeouts test/*.test.ts test/node/*.test.ts", "integration-test": "npm run integration-test:node && npm run integration-test:browser", diff --git a/sdk/storage/storage-blob/rollup.config.js b/sdk/storage/storage-blob/rollup.config.js index 16b60c8e772c..f79a86d0e405 100644 --- a/sdk/storage/storage-blob/rollup.config.js +++ b/sdk/storage/storage-blob/rollup.config.js @@ -27,7 +27,7 @@ const nodeRollupConfigFactory = () => { }; }; -const browserRollupConfigFactory = isProduction => { +const browserRollupConfigFactory = (isProduction) => { const browserRollupConfig = { input: "dist-esm/src/index.browser.js", output: { @@ -57,20 +57,13 @@ const browserRollupConfigFactory = isProduction => { ` }), nodeResolve({ - mainFields: ['module', 'browser'], + mainFields: ["module", "browser"], preferBuiltins: false }), commonjs({ namedExports: { events: ["EventEmitter"], - assert: [ - "ok", - "deepEqual", - "equal", - "fail", - "deepStrictEqual", - "notDeepEqual" - ] + assert: ["ok", "deepEqual", "equal", "fail", "deepStrictEqual", "notDeepEqual"] } }) ] diff --git a/sdk/storage/storage-blob/src/Aborter.ts b/sdk/storage/storage-blob/src/Aborter.ts index 4e3c1c46bf0d..f4048e0cd6c1 100644 --- a/sdk/storage/storage-blob/src/Aborter.ts +++ b/sdk/storage/storage-blob/src/Aborter.ts @@ -83,16 +83,14 @@ export class Aborter implements AbortSignalLike { * * @memberof Aborter */ - public onabort?: ((ev?: Event) => any); + public onabort?: (ev?: Event) => any; // tslint:disable-next-line:variable-name private _aborted: boolean = false; private timer?: any; private readonly parent?: Aborter; private readonly children: Aborter[] = []; // When child object calls dispose(), remove child from here - private readonly abortEventListeners: Array< - (this: AbortSignalLike, ev?: any) => any - > = []; + private readonly abortEventListeners: Array<(this: AbortSignalLike, ev?: any) => any> = []; // Pipeline proxies need to use "abortSignal as Aborter" in order to access non AbortSignalLike methods // immutable primitive types private readonly key?: string; @@ -164,10 +162,7 @@ export class Aborter implements AbortSignalLike { * @returns {Aborter} * @memberof Aborter */ - public withValue( - key: string, - value?: string | number | boolean | null - ): Aborter { + public withValue(key: string, value?: string | number | boolean | null): Aborter { const childCancelContext = new Aborter(this, 0, key, value); this.children.push(childCancelContext); return childCancelContext; @@ -184,11 +179,7 @@ export class Aborter implements AbortSignalLike { * @memberof Aborter */ public getValue(key: string): string | number | boolean | null | undefined { - for ( - let parent: Aborter | undefined = this; - parent; - parent = parent.parent - ) { + for (let parent: Aborter | undefined = this; parent; parent = parent.parent) { if (parent.key === key) { return parent.value; } @@ -216,11 +207,11 @@ export class Aborter implements AbortSignalLike { this.onabort.call(this); } - this.abortEventListeners.forEach(listener => { + this.abortEventListeners.forEach((listener) => { listener.call(this); }); - this.children.forEach(child => child.cancelByParent()); + this.children.forEach((child) => child.cancelByParent()); this._aborted = true; } diff --git a/sdk/storage/storage-blob/src/AppendBlobURL.ts b/sdk/storage/storage-blob/src/AppendBlobURL.ts index ebf663786be3..2965e9620ab9 100644 --- a/sdk/storage/storage-blob/src/AppendBlobURL.ts +++ b/sdk/storage/storage-blob/src/AppendBlobURL.ts @@ -5,11 +5,7 @@ import { Aborter } from "./Aborter"; import { BlobURL } from "./BlobURL"; import { ContainerURL } from "./ContainerURL"; import { AppendBlob } from "./generated/lib/operations"; -import { - IAppendBlobAccessConditions, - IBlobAccessConditions, - IMetadata -} from "./models"; +import { IAppendBlobAccessConditions, IBlobAccessConditions, IMetadata } from "./models"; import { Pipeline } from "./Pipeline"; import { URLConstants } from "./utils/constants"; import { appendToURLPath, setURLParameter } from "./utils/utils.common"; @@ -43,10 +39,7 @@ export class AppendBlobURL extends BlobURL { * @returns {AppendBlobURL} * @memberof AppendBlobURL */ - public static fromContainerURL( - containerURL: ContainerURL, - blobName: string - ): AppendBlobURL { + public static fromContainerURL(containerURL: ContainerURL, blobName: string): AppendBlobURL { return new AppendBlobURL( appendToURLPath(containerURL.url, encodeURIComponent(blobName)), containerURL.pipeline @@ -149,8 +142,7 @@ export class AppendBlobURL extends BlobURL { blobHTTPHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.accessConditions.leaseAccessConditions, metadata: options.metadata, - modifiedAccessConditions: - options.accessConditions.modifiedAccessConditions + modifiedAccessConditions: options.accessConditions.modifiedAccessConditions }); } @@ -175,11 +167,9 @@ export class AppendBlobURL extends BlobURL { options.accessConditions = options.accessConditions || {}; return this.appendBlobContext.appendBlock(body, contentLength, { abortSignal: aborter, - appendPositionAccessConditions: - options.accessConditions.appendPositionAccessConditions, + appendPositionAccessConditions: options.accessConditions.appendPositionAccessConditions, leaseAccessConditions: options.accessConditions.leaseAccessConditions, - modifiedAccessConditions: - options.accessConditions.modifiedAccessConditions, + modifiedAccessConditions: options.accessConditions.modifiedAccessConditions, onUploadProgress: options.progress, transactionalContentMD5: options.transactionalContentMD5 }); diff --git a/sdk/storage/storage-blob/src/BlobDownloadResponse.ts b/sdk/storage/storage-blob/src/BlobDownloadResponse.ts index 94f83926ce98..0a62dc183f4c 100644 --- a/sdk/storage/storage-blob/src/BlobDownloadResponse.ts +++ b/sdk/storage/storage-blob/src/BlobDownloadResponse.ts @@ -4,10 +4,7 @@ import { Aborter } from "./Aborter"; import * as Models from "./generated/lib/models"; import { IMetadata } from "./models"; import { IRetriableReadableStreamOptions } from "./utils/RetriableReadableStream"; -import { - ReadableStreamGetter, - RetriableReadableStream -} from "./utils/RetriableReadableStream"; +import { ReadableStreamGetter, RetriableReadableStream } from "./utils/RetriableReadableStream"; /** * ONLY AVAILABLE IN NODE.JS RUNTIME. diff --git a/sdk/storage/storage-blob/src/BlobURL.ts b/sdk/storage/storage-blob/src/BlobURL.ts index 9f87c1ad324c..469de7fe1d74 100644 --- a/sdk/storage/storage-blob/src/BlobURL.ts +++ b/sdk/storage/storage-blob/src/BlobURL.ts @@ -9,10 +9,7 @@ import { rangeToString } from "./IRange"; import { IBlobAccessConditions, IMetadata } from "./models"; import { Pipeline } from "./Pipeline"; import { StorageURL } from "./StorageURL"; -import { - DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS, - URLConstants -} from "./utils/constants"; +import { DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS, URLConstants } from "./utils/constants"; import { appendToURLPath, setURLParameter } from "./utils/utils.common"; export interface IBlobDownloadOptions { @@ -213,11 +210,9 @@ export class BlobURL extends StorageURL { const res = await this.blobContext.download({ abortSignal: aborter, leaseAccessConditions: options.blobAccessConditions.leaseAccessConditions, - modifiedAccessConditions: - options.blobAccessConditions.modifiedAccessConditions, + modifiedAccessConditions: options.blobAccessConditions.modifiedAccessConditions, onDownloadProgress: isNode ? undefined : options.progress, - range: - offset === 0 && !count ? undefined : rangeToString({ offset, count }), + range: offset === 0 && !count ? undefined : rangeToString({ offset, count }), rangeGetContentMD5: options.rangeGetContentMD5, snapshot: options.snapshot }); @@ -232,24 +227,17 @@ export class BlobURL extends StorageURL { // bundlers may try to bundle following code and "FileReadResponse.ts". // In this case, "FileDownloadResponse.browser.ts" will be used as a shim of "FileDownloadResponse.ts" // The config is in package.json "browser" field - if ( - options.maxRetryRequests === undefined || - options.maxRetryRequests < 0 - ) { + if (options.maxRetryRequests === undefined || options.maxRetryRequests < 0) { // TODO: Default value or make it a required parameter? options.maxRetryRequests = DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS; } if (res.contentLength === undefined) { - throw new RangeError( - `File download response doesn't contain valid content length header` - ); + throw new RangeError(`File download response doesn't contain valid content length header`); } if (!res.eTag) { - throw new RangeError( - `File download response doesn't contain valid etag header` - ); + throw new RangeError(`File download response doesn't contain valid etag header`); } return new BlobDownloadResponse( @@ -257,18 +245,14 @@ export class BlobURL extends StorageURL { res, async (start: number): Promise => { const updatedOptions: Models.BlobDownloadOptionalParams = { - leaseAccessConditions: options.blobAccessConditions! - .leaseAccessConditions, + leaseAccessConditions: options.blobAccessConditions!.leaseAccessConditions, modifiedAccessConditions: { - ifMatch: - options.blobAccessConditions!.modifiedAccessConditions!.ifMatch || - res.eTag, - ifModifiedSince: options.blobAccessConditions! - .modifiedAccessConditions!.ifModifiedSince, - ifNoneMatch: options.blobAccessConditions!.modifiedAccessConditions! - .ifNoneMatch, - ifUnmodifiedSince: options.blobAccessConditions! - .modifiedAccessConditions!.ifUnmodifiedSince + ifMatch: options.blobAccessConditions!.modifiedAccessConditions!.ifMatch || res.eTag, + ifModifiedSince: options.blobAccessConditions!.modifiedAccessConditions! + .ifModifiedSince, + ifNoneMatch: options.blobAccessConditions!.modifiedAccessConditions!.ifNoneMatch, + ifUnmodifiedSince: options.blobAccessConditions!.modifiedAccessConditions! + .ifUnmodifiedSince }, range: rangeToString({ count: offset + res.contentLength! - start, @@ -317,8 +301,7 @@ export class BlobURL extends StorageURL { return this.blobContext.getProperties({ abortSignal: aborter, leaseAccessConditions: options.blobAccessConditions.leaseAccessConditions, - modifiedAccessConditions: - options.blobAccessConditions.modifiedAccessConditions + modifiedAccessConditions: options.blobAccessConditions.modifiedAccessConditions }); } @@ -344,8 +327,7 @@ export class BlobURL extends StorageURL { abortSignal: aborter, deleteSnapshots: options.deleteSnapshots, leaseAccessConditions: options.blobAccessConditions.leaseAccessConditions, - modifiedAccessConditions: - options.blobAccessConditions.modifiedAccessConditions + modifiedAccessConditions: options.blobAccessConditions.modifiedAccessConditions }); } @@ -360,9 +342,7 @@ export class BlobURL extends StorageURL { * @returns {Promise} * @memberof BlobURL */ - public async undelete( - aborter: Aborter - ): Promise { + public async undelete(aborter: Aborter): Promise { return this.blobContext.undelete({ abortSignal: aborter }); @@ -394,8 +374,7 @@ export class BlobURL extends StorageURL { abortSignal: aborter, blobHTTPHeaders, leaseAccessConditions: options.blobAccessConditions.leaseAccessConditions, - modifiedAccessConditions: - options.blobAccessConditions.modifiedAccessConditions + modifiedAccessConditions: options.blobAccessConditions.modifiedAccessConditions }); } @@ -424,8 +403,7 @@ export class BlobURL extends StorageURL { abortSignal: aborter, leaseAccessConditions: options.blobAccessConditions.leaseAccessConditions, metadata, - modifiedAccessConditions: - options.blobAccessConditions.modifiedAccessConditions + modifiedAccessConditions: options.blobAccessConditions.modifiedAccessConditions }); } @@ -569,8 +547,7 @@ export class BlobURL extends StorageURL { abortSignal: aborter, leaseAccessConditions: options.blobAccessConditions.leaseAccessConditions, metadata: options.metadata, - modifiedAccessConditions: - options.blobAccessConditions.modifiedAccessConditions + modifiedAccessConditions: options.blobAccessConditions.modifiedAccessConditions }); } @@ -597,22 +574,18 @@ export class BlobURL extends StorageURL { options: IBlobStartCopyFromURLOptions = {} ): Promise { options.blobAccessConditions = options.blobAccessConditions || {}; - options.sourceModifiedAccessConditions = - options.sourceModifiedAccessConditions || {}; + options.sourceModifiedAccessConditions = options.sourceModifiedAccessConditions || {}; return this.blobContext.startCopyFromURL(copySource, { abortSignal: aborter, leaseAccessConditions: options.blobAccessConditions.leaseAccessConditions, metadata: options.metadata, - modifiedAccessConditions: - options.blobAccessConditions.modifiedAccessConditions, + modifiedAccessConditions: options.blobAccessConditions.modifiedAccessConditions, sourceModifiedAccessConditions: { sourceIfMatch: options.sourceModifiedAccessConditions.ifMatch, - sourceIfModifiedSince: - options.sourceModifiedAccessConditions.ifModifiedSince, + sourceIfModifiedSince: options.sourceModifiedAccessConditions.ifModifiedSince, sourceIfNoneMatch: options.sourceModifiedAccessConditions.ifNoneMatch, - sourceIfUnmodifiedSince: - options.sourceModifiedAccessConditions.ifUnmodifiedSince + sourceIfUnmodifiedSince: options.sourceModifiedAccessConditions.ifUnmodifiedSince } }); } diff --git a/sdk/storage/storage-blob/src/BlockBlobURL.ts b/sdk/storage/storage-blob/src/BlockBlobURL.ts index db811a17ceb1..d8a2c09d3475 100644 --- a/sdk/storage/storage-blob/src/BlockBlobURL.ts +++ b/sdk/storage/storage-blob/src/BlockBlobURL.ts @@ -57,10 +57,7 @@ export class BlockBlobURL extends BlobURL { * @returns {BlockBlobURL} * @memberof BlockBlobURL */ - public static fromContainerURL( - containerURL: ContainerURL, - blobName: string - ): BlockBlobURL { + public static fromContainerURL(containerURL: ContainerURL, blobName: string): BlockBlobURL { return new BlockBlobURL( appendToURLPath(containerURL.url, encodeURIComponent(blobName)), containerURL.pipeline @@ -178,8 +175,7 @@ export class BlockBlobURL extends BlobURL { blobHTTPHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.accessConditions.leaseAccessConditions, metadata: options.metadata, - modifiedAccessConditions: - options.accessConditions.modifiedAccessConditions, + modifiedAccessConditions: options.accessConditions.modifiedAccessConditions, onUploadProgress: options.progress }); } @@ -249,8 +245,7 @@ export class BlockBlobURL extends BlobURL { abortSignal: aborter, leaseAccessConditions: options.leaseAccessConditions, sourceContentMD5: options.sourceContentMD5, - sourceRange: - offset === 0 && !count ? undefined : rangeToString({ offset, count }) + sourceRange: offset === 0 && !count ? undefined : rangeToString({ offset, count }) }); } @@ -282,8 +277,7 @@ export class BlockBlobURL extends BlobURL { blobHTTPHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.accessConditions.leaseAccessConditions, metadata: options.metadata, - modifiedAccessConditions: - options.accessConditions.modifiedAccessConditions + modifiedAccessConditions: options.accessConditions.modifiedAccessConditions } ); } diff --git a/sdk/storage/storage-blob/src/BrowserPolicyFactory.ts b/sdk/storage/storage-blob/src/BrowserPolicyFactory.ts index 095475fb00ce..786d6d8e8137 100644 --- a/sdk/storage/storage-blob/src/BrowserPolicyFactory.ts +++ b/sdk/storage/storage-blob/src/BrowserPolicyFactory.ts @@ -1,8 +1,4 @@ -import { - RequestPolicy, - RequestPolicyFactory, - RequestPolicyOptions -} from "@azure/ms-rest-js"; +import { RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "@azure/ms-rest-js"; import { BrowserPolicy } from "./policies/BrowserPolicy"; @@ -14,10 +10,7 @@ import { BrowserPolicy } from "./policies/BrowserPolicy"; * @implements {RequestPolicyFactory} */ export class BrowserPolicyFactory implements RequestPolicyFactory { - public create( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions - ): BrowserPolicy { + public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): BrowserPolicy { return new BrowserPolicy(nextPolicy, options); } } diff --git a/sdk/storage/storage-blob/src/ContainerURL.ts b/sdk/storage/storage-blob/src/ContainerURL.ts index f1d47c8a94af..8d6b4a2b6ae9 100644 --- a/sdk/storage/storage-blob/src/ContainerURL.ts +++ b/sdk/storage/storage-blob/src/ContainerURL.ts @@ -138,10 +138,7 @@ export class ContainerURL extends StorageURL { * @param serviceURL A ServiceURL object * @param containerName A container name */ - public static fromServiceURL( - serviceURL: ServiceURL, - containerName: string - ): ContainerURL { + public static fromServiceURL(serviceURL: ServiceURL, containerName: string): ContainerURL { return new ContainerURL( appendToURLPath(serviceURL.url, encodeURIComponent(containerName)), serviceURL.pipeline @@ -261,11 +258,9 @@ export class ContainerURL extends StorageURL { if ( (options.containerAccessConditions.modifiedAccessConditions.ifMatch && - options.containerAccessConditions.modifiedAccessConditions.ifMatch !== - ETagNone) || + options.containerAccessConditions.modifiedAccessConditions.ifMatch !== ETagNone) || (options.containerAccessConditions.modifiedAccessConditions.ifNoneMatch && - options.containerAccessConditions.modifiedAccessConditions - .ifNoneMatch !== ETagNone) + options.containerAccessConditions.modifiedAccessConditions.ifNoneMatch !== ETagNone) ) { throw new RangeError( "the IfMatch and IfNoneMatch access conditions must have their default\ @@ -275,10 +270,8 @@ export class ContainerURL extends StorageURL { return this.containerContext.deleteMethod({ abortSignal: aborter, - leaseAccessConditions: - options.containerAccessConditions.leaseAccessConditions, - modifiedAccessConditions: - options.containerAccessConditions.modifiedAccessConditions + leaseAccessConditions: options.containerAccessConditions.leaseAccessConditions, + modifiedAccessConditions: options.containerAccessConditions.modifiedAccessConditions }); } @@ -316,14 +309,11 @@ export class ContainerURL extends StorageURL { } if ( - options.containerAccessConditions.modifiedAccessConditions - .ifUnmodifiedSince || + options.containerAccessConditions.modifiedAccessConditions.ifUnmodifiedSince || (options.containerAccessConditions.modifiedAccessConditions.ifMatch && - options.containerAccessConditions.modifiedAccessConditions.ifMatch !== - ETagNone) || + options.containerAccessConditions.modifiedAccessConditions.ifMatch !== ETagNone) || (options.containerAccessConditions.modifiedAccessConditions.ifNoneMatch && - options.containerAccessConditions.modifiedAccessConditions - .ifNoneMatch !== ETagNone) + options.containerAccessConditions.modifiedAccessConditions.ifNoneMatch !== ETagNone) ) { throw new RangeError( "the IfUnmodifiedSince, IfMatch, and IfNoneMatch must have their default values\ @@ -333,11 +323,9 @@ export class ContainerURL extends StorageURL { return this.containerContext.setMetadata({ abortSignal: aborter, - leaseAccessConditions: - options.containerAccessConditions.leaseAccessConditions, + leaseAccessConditions: options.containerAccessConditions.leaseAccessConditions, metadata, - modifiedAccessConditions: - options.containerAccessConditions.modifiedAccessConditions + modifiedAccessConditions: options.containerAccessConditions.modifiedAccessConditions }); } @@ -435,10 +423,8 @@ export class ContainerURL extends StorageURL { abortSignal: aborter, access, containerAcl: acl, - leaseAccessConditions: - options.containerAccessConditions.leaseAccessConditions, - modifiedAccessConditions: - options.containerAccessConditions.modifiedAccessConditions + leaseAccessConditions: options.containerAccessConditions.leaseAccessConditions, + modifiedAccessConditions: options.containerAccessConditions.modifiedAccessConditions }); } diff --git a/sdk/storage/storage-blob/src/IAccountSASSignatureValues.ts b/sdk/storage/storage-blob/src/IAccountSASSignatureValues.ts index c18b9114cb54..e438caf5ceaf 100644 --- a/sdk/storage/storage-blob/src/IAccountSASSignatureValues.ts +++ b/sdk/storage/storage-blob/src/IAccountSASSignatureValues.ts @@ -117,9 +117,7 @@ export function generateAccountSASQueryParameters( const parsedPermissions = AccountSASPermissions.parse( accountSASSignatureValues.permissions ).toString(); - const parsedServices = AccountSASServices.parse( - accountSASSignatureValues.services - ).toString(); + const parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString(); const parsedResourceTypes = AccountSASResourceTypes.parse( accountSASSignatureValues.resourceTypes ).toString(); @@ -133,12 +131,8 @@ export function generateAccountSASQueryParameters( ? truncatedISO8061Date(accountSASSignatureValues.startTime, false) : "", truncatedISO8061Date(accountSASSignatureValues.expiryTime, false), - accountSASSignatureValues.ipRange - ? ipRangeToString(accountSASSignatureValues.ipRange) - : "", - accountSASSignatureValues.protocol - ? accountSASSignatureValues.protocol - : "", + accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", + accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", version, "" // Account SAS requires an additional newline character ].join("\n"); diff --git a/sdk/storage/storage-blob/src/IBlobSASSignatureValues.ts b/sdk/storage/storage-blob/src/IBlobSASSignatureValues.ts index 8e556ed78122..204bc86fa21b 100644 --- a/sdk/storage/storage-blob/src/IBlobSASSignatureValues.ts +++ b/sdk/storage/storage-blob/src/IBlobSASSignatureValues.ts @@ -164,18 +164,14 @@ export function generateBlobSASQueryParameters( ); } - const version = blobSASSignatureValues.version - ? blobSASSignatureValues.version - : SERVICE_VERSION; + const version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; let resource: string = "c"; let verifiedPermissions: string | undefined; // Calling parse and toString guarantees the proper ordering and throws on invalid characters. if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions.parse( - blobSASSignatureValues.permissions - ).toString(); + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions).toString(); resource = "b"; } else { verifiedPermissions = ContainerSASPermissions.parse( @@ -199,23 +195,13 @@ export function generateBlobSASQueryParameters( blobSASSignatureValues.blobName ), blobSASSignatureValues.identifier, - blobSASSignatureValues.ipRange - ? ipRangeToString(blobSASSignatureValues.ipRange) - : "", + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", version, - blobSASSignatureValues.cacheControl - ? blobSASSignatureValues.cacheControl - : "", - blobSASSignatureValues.contentDisposition - ? blobSASSignatureValues.contentDisposition - : "", - blobSASSignatureValues.contentEncoding - ? blobSASSignatureValues.contentEncoding - : "", - blobSASSignatureValues.contentLanguage - ? blobSASSignatureValues.contentLanguage - : "", + blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", + blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", + blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", + blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" ].join("\n"); @@ -241,11 +227,7 @@ export function generateBlobSASQueryParameters( ); } -function getCanonicalName( - accountName: string, - containerName: string, - blobName?: string -): string { +function getCanonicalName(accountName: string, containerName: string, blobName?: string): string { // Container: "/blob/account/containerName" // Blob: "/blob/account/containerName/blobName" const elements: string[] = [`/blob/${accountName}/${containerName}`]; diff --git a/sdk/storage/storage-blob/src/LoggingPolicyFactory.ts b/sdk/storage/storage-blob/src/LoggingPolicyFactory.ts index 29b9081d157d..d6f1057480b4 100644 --- a/sdk/storage/storage-blob/src/LoggingPolicyFactory.ts +++ b/sdk/storage/storage-blob/src/LoggingPolicyFactory.ts @@ -1,8 +1,4 @@ -import { - RequestPolicy, - RequestPolicyFactory, - RequestPolicyOptions -} from "@azure/ms-rest-js"; +import { RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "@azure/ms-rest-js"; import { LoggingPolicy } from "./policies/LoggingPolicy"; @@ -36,10 +32,7 @@ export class LoggingPolicyFactory implements RequestPolicyFactory { this.loggingOptions = loggingOptions; } - public create( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions - ): LoggingPolicy { + public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): LoggingPolicy { return new LoggingPolicy(nextPolicy, options, this.loggingOptions); } } diff --git a/sdk/storage/storage-blob/src/PageBlobURL.ts b/sdk/storage/storage-blob/src/PageBlobURL.ts index 13e975eaafd4..78888dc9409d 100644 --- a/sdk/storage/storage-blob/src/PageBlobURL.ts +++ b/sdk/storage/storage-blob/src/PageBlobURL.ts @@ -6,11 +6,7 @@ import { BlobURL } from "./BlobURL"; import { ContainerURL } from "./ContainerURL"; import { PageBlob } from "./generated/lib/operations"; import { rangeToString } from "./IRange"; -import { - IBlobAccessConditions, - IMetadata, - IPageBlobAccessConditions -} from "./models"; +import { IBlobAccessConditions, IMetadata, IPageBlobAccessConditions } from "./models"; import { Pipeline } from "./Pipeline"; import { URLConstants } from "./utils/constants"; import { appendToURLPath, setURLParameter } from "./utils/utils.common"; @@ -70,10 +66,7 @@ export class PageBlobURL extends BlobURL { * @returns {PageBlobURL} * @memberof PageBlobURL */ - public static fromContainerURL( - containerURL: ContainerURL, - blobName: string - ): PageBlobURL { + public static fromContainerURL(containerURL: ContainerURL, blobName: string): PageBlobURL { return new PageBlobURL( appendToURLPath(containerURL.url, encodeURIComponent(blobName)), containerURL.pipeline @@ -180,8 +173,7 @@ export class PageBlobURL extends BlobURL { blobSequenceNumber: options.blobSequenceNumber, leaseAccessConditions: options.accessConditions.leaseAccessConditions, metadata: options.metadata, - modifiedAccessConditions: - options.accessConditions.modifiedAccessConditions + modifiedAccessConditions: options.accessConditions.modifiedAccessConditions }); } @@ -209,12 +201,10 @@ export class PageBlobURL extends BlobURL { return this.pageBlobContext.uploadPages(body, count, { abortSignal: aborter, leaseAccessConditions: options.accessConditions.leaseAccessConditions, - modifiedAccessConditions: - options.accessConditions.modifiedAccessConditions, + modifiedAccessConditions: options.accessConditions.modifiedAccessConditions, onUploadProgress: options.progress, range: rangeToString({ offset, count }), - sequenceNumberAccessConditions: - options.accessConditions.sequenceNumberAccessConditions, + sequenceNumberAccessConditions: options.accessConditions.sequenceNumberAccessConditions, transactionalContentMD5: options.transactionalContentMD5 }); } @@ -241,11 +231,9 @@ export class PageBlobURL extends BlobURL { return this.pageBlobContext.clearPages(0, { abortSignal: aborter, leaseAccessConditions: options.accessConditions.leaseAccessConditions, - modifiedAccessConditions: - options.accessConditions.modifiedAccessConditions, + modifiedAccessConditions: options.accessConditions.modifiedAccessConditions, range: rangeToString({ offset, count }), - sequenceNumberAccessConditions: - options.accessConditions.sequenceNumberAccessConditions + sequenceNumberAccessConditions: options.accessConditions.sequenceNumberAccessConditions }); } @@ -271,8 +259,7 @@ export class PageBlobURL extends BlobURL { return this.pageBlobContext.getPageRanges({ abortSignal: aborter, leaseAccessConditions: options.accessConditions.leaseAccessConditions, - modifiedAccessConditions: - options.accessConditions.modifiedAccessConditions, + modifiedAccessConditions: options.accessConditions.modifiedAccessConditions, range: rangeToString({ offset, count }) }); } @@ -301,8 +288,7 @@ export class PageBlobURL extends BlobURL { return this.pageBlobContext.getPageRangesDiff({ abortSignal: aborter, leaseAccessConditions: options.accessConditions.leaseAccessConditions, - modifiedAccessConditions: - options.accessConditions.modifiedAccessConditions, + modifiedAccessConditions: options.accessConditions.modifiedAccessConditions, prevsnapshot: prevSnapshot, range: rangeToString({ offset, count }) }); @@ -328,8 +314,7 @@ export class PageBlobURL extends BlobURL { return this.pageBlobContext.resize(size, { abortSignal: aborter, leaseAccessConditions: options.accessConditions.leaseAccessConditions, - modifiedAccessConditions: - options.accessConditions.modifiedAccessConditions + modifiedAccessConditions: options.accessConditions.modifiedAccessConditions }); } @@ -356,8 +341,7 @@ export class PageBlobURL extends BlobURL { abortSignal: aborter, blobSequenceNumber: sequenceNumber, leaseAccessConditions: options.accessConditions.leaseAccessConditions, - modifiedAccessConditions: - options.accessConditions.modifiedAccessConditions + modifiedAccessConditions: options.accessConditions.modifiedAccessConditions }); } diff --git a/sdk/storage/storage-blob/src/Pipeline.ts b/sdk/storage/storage-blob/src/Pipeline.ts index 4d5262d1d0a6..eada177ac894 100644 --- a/sdk/storage/storage-blob/src/Pipeline.ts +++ b/sdk/storage/storage-blob/src/Pipeline.ts @@ -61,10 +61,7 @@ export class Pipeline { * @param {IPipelineOptions} [options={}] * @memberof Pipeline */ - constructor( - factories: RequestPolicyFactory[], - options: IPipelineOptions = {} - ) { + constructor(factories: RequestPolicyFactory[], options: IPipelineOptions = {}) { this.factories = factories; this.options = options; } diff --git a/sdk/storage/storage-blob/src/RetryPolicyFactory.ts b/sdk/storage/storage-blob/src/RetryPolicyFactory.ts index faac1ef057a7..1918e1cdf405 100644 --- a/sdk/storage/storage-blob/src/RetryPolicyFactory.ts +++ b/sdk/storage/storage-blob/src/RetryPolicyFactory.ts @@ -1,8 +1,4 @@ -import { - RequestPolicy, - RequestPolicyFactory, - RequestPolicyOptions -} from "@azure/ms-rest-js"; +import { RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "@azure/ms-rest-js"; import { RetryPolicy, RetryPolicyType } from "./policies/RetryPolicy"; @@ -95,10 +91,7 @@ export class RetryPolicyFactory implements RequestPolicyFactory { this.retryOptions = retryOptions; } - public create( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions - ): RetryPolicy { + public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): RetryPolicy { return new RetryPolicy(nextPolicy, options, this.retryOptions); } } diff --git a/sdk/storage/storage-blob/src/SASQueryParameters.ts b/sdk/storage/storage-blob/src/SASQueryParameters.ts index b2973c5df54c..5b73e1db9131 100644 --- a/sdk/storage/storage-blob/src/SASQueryParameters.ts +++ b/sdk/storage/storage-blob/src/SASQueryParameters.ts @@ -286,18 +286,14 @@ export class SASQueryParameters { this.tryAppendQueryParameter( queries, param, - this.startTime - ? truncatedISO8061Date(this.startTime, false) - : undefined + this.startTime ? truncatedISO8061Date(this.startTime, false) : undefined ); break; case "se": this.tryAppendQueryParameter( queries, param, - this.expiryTime - ? truncatedISO8061Date(this.expiryTime, false) - : undefined + this.expiryTime ? truncatedISO8061Date(this.expiryTime, false) : undefined ); break; case "sip": @@ -349,11 +345,7 @@ export class SASQueryParameters { * @returns {void} * @memberof SASQueryParameters */ - private tryAppendQueryParameter( - queries: string[], - key: string, - value?: string - ): void { + private tryAppendQueryParameter(queries: string[], key: string, value?: string): void { if (!value) { return; } diff --git a/sdk/storage/storage-blob/src/ServiceURL.ts b/sdk/storage/storage-blob/src/ServiceURL.ts index a1d32daf1c1f..e484136589a6 100644 --- a/sdk/storage/storage-blob/src/ServiceURL.ts +++ b/sdk/storage/storage-blob/src/ServiceURL.ts @@ -84,9 +84,7 @@ export class ServiceURL extends StorageURL { * @returns {Promise} * @memberof ServiceURL */ - public async getProperties( - aborter: Aborter - ): Promise { + public async getProperties(aborter: Aborter): Promise { return this.serviceContext.getProperties({ abortSignal: aborter }); @@ -123,9 +121,7 @@ export class ServiceURL extends StorageURL { * @returns {Promise} * @memberof ServiceURL */ - public async getStatistics( - aborter: Aborter - ): Promise { + public async getStatistics(aborter: Aborter): Promise { return this.serviceContext.getStatistics({ abortSignal: aborter }); @@ -143,9 +139,7 @@ export class ServiceURL extends StorageURL { * @returns {Promise} * @memberof ServiceURL */ - public async getAccountInfo( - aborter: Aborter - ): Promise { + public async getAccountInfo(aborter: Aborter): Promise { return this.serviceContext.getAccountInfo({ abortSignal: aborter }); diff --git a/sdk/storage/storage-blob/src/StorageURL.ts b/sdk/storage/storage-blob/src/StorageURL.ts index 51e46d20fb64..394574a06ce6 100644 --- a/sdk/storage/storage-blob/src/StorageURL.ts +++ b/sdk/storage/storage-blob/src/StorageURL.ts @@ -6,10 +6,7 @@ import { StorageClientContext } from "./generated/lib/storageClientContext"; import { LoggingPolicyFactory } from "./LoggingPolicyFactory"; import { IHttpClient, IHttpPipelineLogger, Pipeline } from "./Pipeline"; import { IRetryOptions, RetryPolicyFactory } from "./RetryPolicyFactory"; -import { - ITelemetryOptions, - TelemetryPolicyFactory -} from "./TelemetryPolicyFactory"; +import { ITelemetryOptions, TelemetryPolicyFactory } from "./TelemetryPolicyFactory"; import { UniqueRequestIDPolicyFactory } from "./UniqueRequestIDPolicyFactory"; import { escapeURLPath } from "./utils/utils.common"; diff --git a/sdk/storage/storage-blob/src/TelemetryPolicyFactory.ts b/sdk/storage/storage-blob/src/TelemetryPolicyFactory.ts index 5d53fc5a876a..a75dad719028 100644 --- a/sdk/storage/storage-blob/src/TelemetryPolicyFactory.ts +++ b/sdk/storage/storage-blob/src/TelemetryPolicyFactory.ts @@ -40,10 +40,7 @@ export class TelemetryPolicyFactory implements RequestPolicyFactory { if (isNode) { if (telemetry) { const telemetryString = telemetry.value; - if ( - telemetryString.length > 0 && - userAgentInfo.indexOf(telemetryString) === -1 - ) { + if (telemetryString.length > 0 && userAgentInfo.indexOf(telemetryString) === -1) { userAgentInfo.push(telemetryString); } } @@ -55,9 +52,7 @@ export class TelemetryPolicyFactory implements RequestPolicyFactory { } // e.g. (NODE-VERSION 4.9.1; Windows_NT 10.0.16299) - const runtimeInfo = `(NODE-VERSION ${ - process.version - }; ${os.type()} ${os.release()})`; + const runtimeInfo = `(NODE-VERSION ${process.version}; ${os.type()} ${os.release()})`; if (userAgentInfo.indexOf(runtimeInfo) === -1) { userAgentInfo.push(runtimeInfo); } @@ -66,10 +61,7 @@ export class TelemetryPolicyFactory implements RequestPolicyFactory { this.telemetryString = userAgentInfo.join(" "); } - public create( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions - ): TelemetryPolicy { + public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): TelemetryPolicy { return new TelemetryPolicy(nextPolicy, options, this.telemetryString); } } diff --git a/sdk/storage/storage-blob/src/UniqueRequestIDPolicyFactory.ts b/sdk/storage/storage-blob/src/UniqueRequestIDPolicyFactory.ts index d586a6fa8fc6..6610c6ff3b53 100644 --- a/sdk/storage/storage-blob/src/UniqueRequestIDPolicyFactory.ts +++ b/sdk/storage/storage-blob/src/UniqueRequestIDPolicyFactory.ts @@ -1,8 +1,4 @@ -import { - RequestPolicy, - RequestPolicyFactory, - RequestPolicyOptions -} from "@azure/ms-rest-js"; +import { RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "@azure/ms-rest-js"; import { UniqueRequestIDPolicy } from "./policies/UniqueRequestIDPolicy"; @@ -14,10 +10,7 @@ import { UniqueRequestIDPolicy } from "./policies/UniqueRequestIDPolicy"; * @implements {RequestPolicyFactory} */ export class UniqueRequestIDPolicyFactory implements RequestPolicyFactory { - public create( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions - ): UniqueRequestIDPolicy { + public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): UniqueRequestIDPolicy { return new UniqueRequestIDPolicy(nextPolicy, options); } } diff --git a/sdk/storage/storage-blob/src/credentials/Credential.ts b/sdk/storage/storage-blob/src/credentials/Credential.ts index d87d71befb84..ba47b60f6d5d 100644 --- a/sdk/storage/storage-blob/src/credentials/Credential.ts +++ b/sdk/storage/storage-blob/src/credentials/Credential.ts @@ -1,8 +1,4 @@ -import { - RequestPolicy, - RequestPolicyFactory, - RequestPolicyOptions -} from "@azure/ms-rest-js"; +import { RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "@azure/ms-rest-js"; import { CredentialPolicy } from "../policies/CredentialPolicy"; diff --git a/sdk/storage/storage-blob/src/credentials/TokenCredential.ts b/sdk/storage/storage-blob/src/credentials/TokenCredential.ts index c56a3dfc8d3e..eb3715bc25c0 100644 --- a/sdk/storage/storage-blob/src/credentials/TokenCredential.ts +++ b/sdk/storage/storage-blob/src/credentials/TokenCredential.ts @@ -56,10 +56,7 @@ export class TokenCredential extends Credential { * @returns {TokenCredentialPolicy} * @memberof TokenCredential */ - public create( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions - ): TokenCredentialPolicy { + public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): TokenCredentialPolicy { return new TokenCredentialPolicy(nextPolicy, options, this); } } diff --git a/sdk/storage/storage-blob/src/highlevel.browser.ts b/sdk/storage/storage-blob/src/highlevel.browser.ts index 3a3796e0b006..664866779f63 100644 --- a/sdk/storage/storage-blob/src/highlevel.browser.ts +++ b/sdk/storage/storage-blob/src/highlevel.browser.ts @@ -2,10 +2,7 @@ import { generateUuid } from "@azure/ms-rest-js"; import { Aborter } from "./Aborter"; import { BlockBlobURL } from "./BlockBlobURL"; -import { - BlobUploadCommonResponse, - IUploadToBlockBlobOptions -} from "./highlevel.common"; +import { BlobUploadCommonResponse, IUploadToBlockBlobOptions } from "./highlevel.common"; import { Batch } from "./utils/Batch"; import { BLOCK_BLOB_MAX_BLOCKS, @@ -78,10 +75,7 @@ async function UploadSeekableBlobToBlockBlob( if (!options.blockSize) { options.blockSize = 0; } - if ( - options.blockSize < 0 || - options.blockSize > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES - ) { + if (options.blockSize < 0 || options.blockSize > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES) { throw new RangeError( `blockSize option must be >= 0 and <= ${BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES}` ); @@ -148,8 +142,7 @@ async function UploadSeekableBlobToBlockBlob( blobFactory(start, contentLength), contentLength, { - leaseAccessConditions: options.blobAccessConditions! - .leaseAccessConditions + leaseAccessConditions: options.blobAccessConditions!.leaseAccessConditions } ); // Update progress after block is successfully uploaded to server, in case of block trying diff --git a/sdk/storage/storage-blob/src/highlevel.node.ts b/sdk/storage/storage-blob/src/highlevel.node.ts index 3062e0ef7048..d2f34fa8dd08 100644 --- a/sdk/storage/storage-blob/src/highlevel.node.ts +++ b/sdk/storage/storage-blob/src/highlevel.node.ts @@ -92,10 +92,7 @@ async function uploadResetableStreamToBlockBlob( if (!options.blockSize) { options.blockSize = 0; } - if ( - options.blockSize < 0 || - options.blockSize > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES - ) { + if (options.blockSize < 0 || options.blockSize > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES) { throw new RangeError( `blockSize option must be >= 0 and <= ${BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES}` ); @@ -162,8 +159,7 @@ async function uploadResetableStreamToBlockBlob( () => streamFactory(start, contentLength), contentLength, { - leaseAccessConditions: options.blobAccessConditions! - .leaseAccessConditions + leaseAccessConditions: options.blobAccessConditions!.leaseAccessConditions } ); // Update progress after block is successfully uploaded to server, in case of block trying @@ -246,17 +242,11 @@ export async function downloadBlobToBuffer( const batch = new Batch(options.parallelism); for (let off = offset; off < offset + count; off = off + options.blockSize) { batch.addOperation(async () => { - const chunkEnd = - off + options.blockSize! < count! ? off + options.blockSize! : count!; - const response = await blobURL.download( - aborter, - off, - chunkEnd - off + 1, - { - blobAccessConditions: options.blobAccessConditions, - maxRetryRequests: options.maxRetryRequestsPerBlock - } - ); + const chunkEnd = off + options.blockSize! < count! ? off + options.blockSize! : count!; + const response = await blobURL.download(aborter, off, chunkEnd - off + 1, { + blobAccessConditions: options.blobAccessConditions, + maxRetryRequests: options.maxRetryRequestsPerBlock + }); const stream = response.readableStreamBody!; await streamToBuffer(stream, buffer, off - offset, chunkEnd - offset); // Update progress after block is downloaded, in case of block trying diff --git a/sdk/storage/storage-blob/src/policies/BrowserPolicy.ts b/sdk/storage/storage-blob/src/policies/BrowserPolicy.ts index 054a67c29f13..da28a835c088 100644 --- a/sdk/storage/storage-blob/src/policies/BrowserPolicy.ts +++ b/sdk/storage/storage-blob/src/policies/BrowserPolicy.ts @@ -42,17 +42,12 @@ export class BrowserPolicy extends BaseRequestPolicy { * @returns {Promise} * @memberof BrowserPolicy */ - public async sendRequest( - request: WebResource - ): Promise { + public async sendRequest(request: WebResource): Promise { if (isNode) { return this._nextPolicy.sendRequest(request); } - if ( - request.method.toUpperCase() === "GET" || - request.method.toUpperCase() === "HEAD" - ) { + if (request.method.toUpperCase() === "GET" || request.method.toUpperCase() === "HEAD") { request.url = setURLParameter( request.url, URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, diff --git a/sdk/storage/storage-blob/src/policies/CredentialPolicy.ts b/sdk/storage/storage-blob/src/policies/CredentialPolicy.ts index ee09c0e002b9..9a25c8b94b2a 100644 --- a/sdk/storage/storage-blob/src/policies/CredentialPolicy.ts +++ b/sdk/storage/storage-blob/src/policies/CredentialPolicy.ts @@ -1,8 +1,4 @@ -import { - BaseRequestPolicy, - HttpOperationResponse, - WebResource -} from "@azure/ms-rest-js"; +import { BaseRequestPolicy, HttpOperationResponse, WebResource } from "@azure/ms-rest-js"; /** * Credential policy used to sign HTTP(S) requests before sending. This is an diff --git a/sdk/storage/storage-blob/src/policies/LoggingPolicy.ts b/sdk/storage/storage-blob/src/policies/LoggingPolicy.ts index 51fdb8307f64..0d1fa108a316 100644 --- a/sdk/storage/storage-blob/src/policies/LoggingPolicy.ts +++ b/sdk/storage/storage-blob/src/policies/LoggingPolicy.ts @@ -52,9 +52,7 @@ export class LoggingPolicy extends BaseRequestPolicy { * @returns {Promise} * @memberof LoggingPolicy */ - public async sendRequest( - request: WebResource - ): Promise { + public async sendRequest(request: WebResource): Promise { this.tryCount++; this.requestStartTime = new Date(); if (this.tryCount === 1) { @@ -63,11 +61,7 @@ export class LoggingPolicy extends BaseRequestPolicy { let safeURL: string = request.url; if (getURLParameter(safeURL, URLConstants.Parameters.SIGNATURE)) { - safeURL = setURLParameter( - safeURL, - URLConstants.Parameters.SIGNATURE, - "*****" - ); + safeURL = setURLParameter(safeURL, URLConstants.Parameters.SIGNATURE, "*****"); } this.log( HttpPipelineLogLevel.INFO, @@ -78,10 +72,8 @@ export class LoggingPolicy extends BaseRequestPolicy { const response = await this._nextPolicy.sendRequest(request); const requestEndTime = new Date(); - const requestCompletionTime = - requestEndTime.getTime() - this.requestStartTime.getTime(); - const operationDuration = - requestEndTime.getTime() - this.operationStartTime.getTime(); + const requestCompletionTime = requestEndTime.getTime() - this.requestStartTime.getTime(); + const operationDuration = requestEndTime.getTime() - this.operationStartTime.getTime(); let currentLevel: HttpPipelineLogLevel = HttpPipelineLogLevel.INFO; let logMessage: string = ""; @@ -91,10 +83,7 @@ export class LoggingPolicy extends BaseRequestPolicy { } // If the response took too long, we'll upgrade to warning. - if ( - requestCompletionTime >= - this.loggingOptions.logWarningIfTryOverThreshold - ) { + if (requestCompletionTime >= this.loggingOptions.logWarningIfTryOverThreshold) { // Log a warning if the try duration exceeded the specified threshold. if (this.shouldLog(HttpPipelineLogLevel.WARNING)) { currentLevel = HttpPipelineLogLevel.WARNING; @@ -110,8 +99,7 @@ export class LoggingPolicy extends BaseRequestPolicy { (response.status !== HTTPURLConnection.HTTP_NOT_FOUND && response.status !== HTTPURLConnection.HTTP_CONFLICT && response.status !== HTTPURLConnection.HTTP_PRECON_FAILED && - response.status !== - HTTPURLConnection.HTTP_RANGE_NOT_SATISFIABLE)) || + response.status !== HTTPURLConnection.HTTP_RANGE_NOT_SATISFIABLE)) || (response.status >= 500 && response.status <= 509) ) { const errorString = `REQUEST ERROR: HTTP request failed with status code: ${ @@ -131,9 +119,7 @@ export class LoggingPolicy extends BaseRequestPolicy { } catch (err) { this.log( HttpPipelineLogLevel.ERROR, - `Unexpected failure attempting to make request. Error message: ${ - err.message - }` + `Unexpected failure attempting to make request. Error message: ${err.message}` ); throw err; } diff --git a/sdk/storage/storage-blob/src/policies/RetryPolicy.ts b/sdk/storage/storage-blob/src/policies/RetryPolicy.ts index f2b96da29e9d..66252204f092 100644 --- a/sdk/storage/storage-blob/src/policies/RetryPolicy.ts +++ b/sdk/storage/storage-blob/src/policies/RetryPolicy.ts @@ -21,14 +21,9 @@ import { setURLHost, setURLParameter } from "../utils/utils.common"; * @param {IRetryOptions} retryOptions * @returns */ -export function NewRetryPolicyFactory( - retryOptions?: IRetryOptions -): RequestPolicyFactory { +export function NewRetryPolicyFactory(retryOptions?: IRetryOptions): RequestPolicyFactory { return { - create: ( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions - ): RetryPolicy => { + create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions): RetryPolicy => { return new RetryPolicy(nextPolicy, options, retryOptions); } }; @@ -136,9 +131,7 @@ export class RetryPolicy extends BaseRequestPolicy { * @returns {Promise} * @memberof RetryPolicy */ - public async sendRequest( - request: WebResource - ): Promise { + public async sendRequest(request: WebResource): Promise { return this.attemptSendRequest(request, false, 1); } @@ -166,18 +159,11 @@ export class RetryPolicy extends BaseRequestPolicy { const isPrimaryRetry = secondaryHas404 || !this.retryOptions.secondaryHost || - !( - request.method === "GET" || - request.method === "HEAD" || - request.method === "OPTIONS" - ) || + !(request.method === "GET" || request.method === "HEAD" || request.method === "OPTIONS") || attempt % 2 === 1; if (!isPrimaryRetry) { - newRequest.url = setURLHost( - newRequest.url, - this.retryOptions.secondaryHost! - ); + newRequest.url = setURLHost(newRequest.url, this.retryOptions.secondaryHost!); } // Set the server-side timeout query parameter "timeout=[seconds]" @@ -193,17 +179,14 @@ export class RetryPolicy extends BaseRequestPolicy { try { this.logf( HttpPipelineLogLevel.INFO, - `RetryPolicy: =====> Try=${attempt} ${ - isPrimaryRetry ? "Primary" : "Secondary" - }` + `RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}` ); response = await this._nextPolicy.sendRequest(newRequest); if (!this.shouldRetry(isPrimaryRetry, attempt, response)) { return response; } - secondaryHas404 = - secondaryHas404 || (!isPrimaryRetry && response.status === 404); + secondaryHas404 = secondaryHas404 || (!isPrimaryRetry && response.status === 404); } catch (err) { this.logf( HttpPipelineLogLevel.ERROR, @@ -278,10 +261,7 @@ export class RetryPolicy extends BaseRequestPolicy { if (response || err) { const statusCode = response ? response.status : err ? err.statusCode : 0; if (!isPrimaryRetry && statusCode === 404) { - this.logf( - HttpPipelineLogLevel.INFO, - `RetryPolicy: Secondary access with 404, will retry.` - ); + this.logf(HttpPipelineLogLevel.INFO, `RetryPolicy: Secondary access with 404, will retry.`); return true; } @@ -340,10 +320,7 @@ export class RetryPolicy extends BaseRequestPolicy { delayTimeInMs = Math.random() * 1000; } - this.logf( - HttpPipelineLogLevel.INFO, - `RetryPolicy: Delay for ${delayTimeInMs}ms` - ); + this.logf(HttpPipelineLogLevel.INFO, `RetryPolicy: Delay for ${delayTimeInMs}ms`); return delay(delayTimeInMs); } } diff --git a/sdk/storage/storage-blob/src/policies/SharedKeyCredentialPolicy.ts b/sdk/storage/storage-blob/src/policies/SharedKeyCredentialPolicy.ts index a6ba9318a771..141a9bfcdcde 100644 --- a/sdk/storage/storage-blob/src/policies/SharedKeyCredentialPolicy.ts +++ b/sdk/storage/storage-blob/src/policies/SharedKeyCredentialPolicy.ts @@ -1,8 +1,4 @@ -import { - RequestPolicy, - RequestPolicyOptions, - WebResource -} from "@azure/ms-rest-js"; +import { RequestPolicy, RequestPolicyOptions, WebResource } from "@azure/ms-rest-js"; import { SharedKeyCredential } from "../credentials/SharedKeyCredential"; import { HeaderConstants } from "../utils/constants"; import { getURLPath, getURLQueries } from "../utils/utils.common"; @@ -51,15 +47,8 @@ export class SharedKeyCredentialPolicy extends CredentialPolicy { protected signRequest(request: WebResource): WebResource { request.headers.set(HeaderConstants.X_MS_DATE, new Date().toUTCString()); - if ( - request.body && - typeof request.body === "string" && - request.body.length > 0 - ) { - request.headers.set( - HeaderConstants.CONTENT_LENGTH, - Buffer.byteLength(request.body) - ); + if (request.body && typeof request.body === "string" && request.body.length > 0) { + request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); } const stringToSign: string = @@ -104,10 +93,7 @@ export class SharedKeyCredentialPolicy extends CredentialPolicy { * @returns {string} * @memberof SharedKeyCredentialPolicy */ - private getHeaderValueToSign( - request: WebResource, - headerName: string - ): string { + private getHeaderValueToSign(request: WebResource, headerName: string): string { const value = request.headers.get(headerName); if (!value) { @@ -141,10 +127,8 @@ export class SharedKeyCredentialPolicy extends CredentialPolicy { * @memberof SharedKeyCredentialPolicy */ private getCanonicalizedHeadersString(request: WebResource): string { - let headersArray = request.headers.headersArray().filter(value => { - return value.name - .toLowerCase() - .startsWith(HeaderConstants.PREFIX_FOR_STORAGE); + let headersArray = request.headers.headersArray().filter((value) => { + return value.name.toLowerCase().startsWith(HeaderConstants.PREFIX_FOR_STORAGE); }); headersArray.sort( @@ -155,17 +139,14 @@ export class SharedKeyCredentialPolicy extends CredentialPolicy { // Remove duplicate headers headersArray = headersArray.filter((value, index, array) => { - if ( - index > 0 && - value.name.toLowerCase() === array[index - 1].name.toLowerCase() - ) { + if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) { return false; } return true; }); let canonicalizedHeadersStringToSign: string = ""; - headersArray.forEach(header => { + headersArray.forEach((header) => { canonicalizedHeadersStringToSign += `${header.name .toLowerCase() .trimRight()}:${header.value.trimLeft()}\n`; @@ -202,9 +183,7 @@ export class SharedKeyCredentialPolicy extends CredentialPolicy { queryKeys.sort(); for (const key of queryKeys) { - canonicalizedResourceString += `\n${key}:${decodeURIComponent( - lowercaseQueries[key] - )}`; + canonicalizedResourceString += `\n${key}:${decodeURIComponent(lowercaseQueries[key])}`; } } diff --git a/sdk/storage/storage-blob/src/policies/TelemetryPolicy.ts b/sdk/storage/storage-blob/src/policies/TelemetryPolicy.ts index fedf88f4a524..cedefe68fde4 100644 --- a/sdk/storage/storage-blob/src/policies/TelemetryPolicy.ts +++ b/sdk/storage/storage-blob/src/policies/TelemetryPolicy.ts @@ -32,11 +32,7 @@ export class TelemetryPolicy extends BaseRequestPolicy { * @param {ITelemetryOptions} [telemetry] * @memberof TelemetryPolicy */ - constructor( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions, - telemetry: string - ) { + constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, telemetry: string) { super(nextPolicy, options); this.telemetry = telemetry; } @@ -48,9 +44,7 @@ export class TelemetryPolicy extends BaseRequestPolicy { * @returns {Promise} * @memberof TelemetryPolicy */ - public async sendRequest( - request: WebResource - ): Promise { + public async sendRequest(request: WebResource): Promise { if (isNode) { if (!request.headers) { request.headers = new HttpHeaders(); diff --git a/sdk/storage/storage-blob/src/policies/TokenCredentialPolicy.ts b/sdk/storage/storage-blob/src/policies/TokenCredentialPolicy.ts index a92a04d39bfc..fc1b4d8610c5 100644 --- a/sdk/storage/storage-blob/src/policies/TokenCredentialPolicy.ts +++ b/sdk/storage/storage-blob/src/policies/TokenCredentialPolicy.ts @@ -1,9 +1,4 @@ -import { - HttpHeaders, - RequestPolicy, - RequestPolicyOptions, - WebResource -} from "@azure/ms-rest-js"; +import { HttpHeaders, RequestPolicy, RequestPolicyOptions, WebResource } from "@azure/ms-rest-js"; import { TokenCredential } from "../credentials/TokenCredential"; import { HeaderConstants } from "../utils/constants"; diff --git a/sdk/storage/storage-blob/src/policies/UniqueRequestIDPolicy.ts b/sdk/storage/storage-blob/src/policies/UniqueRequestIDPolicy.ts index b4ff96983f9c..3e4e4e9dd17b 100644 --- a/sdk/storage/storage-blob/src/policies/UniqueRequestIDPolicy.ts +++ b/sdk/storage/storage-blob/src/policies/UniqueRequestIDPolicy.ts @@ -33,14 +33,9 @@ export class UniqueRequestIDPolicy extends BaseRequestPolicy { * @returns {Promise} * @memberof UniqueRequestIDPolicy */ - public async sendRequest( - request: WebResource - ): Promise { + public async sendRequest(request: WebResource): Promise { if (!request.headers.contains(HeaderConstants.X_MS_CLIENT_REQUEST_ID)) { - request.headers.set( - HeaderConstants.X_MS_CLIENT_REQUEST_ID, - generateUuid() - ); + request.headers.set(HeaderConstants.X_MS_CLIENT_REQUEST_ID, generateUuid()); } return this._nextPolicy.sendRequest(request); diff --git a/sdk/storage/storage-blob/src/utils/Batch.ts b/sdk/storage/storage-blob/src/utils/Batch.ts index e4917f1c0edf..87a185ddeb3d 100644 --- a/sdk/storage/storage-blob/src/utils/Batch.ts +++ b/sdk/storage/storage-blob/src/utils/Batch.ts @@ -134,7 +134,7 @@ export class Batch { return new Promise((resolve, reject) => { this.emitter.on("finish", resolve); - this.emitter.on("error", error => { + this.emitter.on("error", (error) => { this.state = BatchStates.Error; reject(error); }); diff --git a/sdk/storage/storage-blob/src/utils/BufferScheduler.ts b/sdk/storage/storage-blob/src/utils/BufferScheduler.ts index 21a91c5bca43..81ed82f64a21 100644 --- a/sdk/storage/storage-blob/src/utils/BufferScheduler.ts +++ b/sdk/storage/storage-blob/src/utils/BufferScheduler.ts @@ -4,10 +4,7 @@ import { Readable } from "stream"; /** * OutgoingHandler is an async function triggered by BufferScheduler. */ -export declare type OutgoingHandler = ( - buffer: Buffer, - offset?: number -) => Promise; +export declare type OutgoingHandler = (buffer: Buffer, offset?: number) => Promise; /** * This class accepts a Node.js Readable stream as input, and keeps reading data @@ -206,21 +203,15 @@ export class BufferScheduler { encoding?: string ) { if (bufferSize <= 0) { - throw new RangeError( - `bufferSize must be larger than 0, current is ${bufferSize}` - ); + throw new RangeError(`bufferSize must be larger than 0, current is ${bufferSize}`); } if (maxBuffers <= 0) { - throw new RangeError( - `maxBuffers must be larger than 0, current is ${maxBuffers}` - ); + throw new RangeError(`maxBuffers must be larger than 0, current is ${maxBuffers}`); } if (parallelism <= 0) { - throw new RangeError( - `parallelism must be larger than 0, current is ${parallelism}` - ); + throw new RangeError(`parallelism must be larger than 0, current is ${parallelism}`); } this.bufferSize = bufferSize; @@ -240,9 +231,8 @@ export class BufferScheduler { */ public async do(): Promise { return new Promise((resolve, reject) => { - this.readable.on("data", data => { - data = - typeof data === "string" ? Buffer.from(data, this.encoding) : data; + this.readable.on("data", (data) => { + data = typeof data === "string" ? Buffer.from(data, this.encoding) : data; this.appendUnresolvedData(data); if (!this.resolveData()) { @@ -250,7 +240,7 @@ export class BufferScheduler { } }); - this.readable.on("error", err => { + this.readable.on("error", (err) => { this.emitter.emit("error", err); }); @@ -259,7 +249,7 @@ export class BufferScheduler { this.emitter.emit("checkEnd"); }); - this.emitter.on("error", err => { + this.emitter.on("error", (err) => { this.isError = true; this.readable.pause(); reject(err); @@ -272,14 +262,8 @@ export class BufferScheduler { } if (this.isStreamEnd && this.executingOutgoingHandlers === 0) { - if ( - this.unresolvedLength > 0 && - this.unresolvedLength < this.bufferSize - ) { - this.outgoingHandler( - this.shiftBufferFromUnresolvedDataArray(), - this.offset - ) + if (this.unresolvedLength > 0 && this.unresolvedLength < this.bufferSize) { + this.outgoingHandler(this.shiftBufferFromUnresolvedDataArray(), this.offset) .then(resolve) .catch(reject); } else if (this.unresolvedLength >= this.bufferSize) { @@ -320,20 +304,14 @@ export class BufferScheduler { } // Lazy concat because Buffer.concat highly drops performance - let merged = Buffer.concat( - this.unresolvedDataArray, - this.unresolvedLength - ); + let merged = Buffer.concat(this.unresolvedDataArray, this.unresolvedLength); const buffer = merged.slice(0, this.bufferSize); merged = merged.slice(this.bufferSize); this.unresolvedDataArray = [merged]; this.unresolvedLength -= buffer.length; return buffer; } else if (this.unresolvedLength > 0) { - const merged = Buffer.concat( - this.unresolvedDataArray, - this.unresolvedLength - ); + const merged = Buffer.concat(this.unresolvedDataArray, this.unresolvedLength); this.unresolvedDataArray = []; this.unresolvedLength = 0; return merged; diff --git a/sdk/storage/storage-blob/src/utils/RetriableReadableStream.ts b/sdk/storage/storage-blob/src/utils/RetriableReadableStream.ts index 69f70ded63a6..5bf8bec65096 100644 --- a/sdk/storage/storage-blob/src/utils/RetriableReadableStream.ts +++ b/sdk/storage/storage-blob/src/utils/RetriableReadableStream.ts @@ -3,9 +3,7 @@ import { Readable } from "stream"; import { Aborter } from "../Aborter"; -export type ReadableStreamGetter = ( - offset: number -) => Promise; +export type ReadableStreamGetter = (offset: number) => Promise; export interface IRetriableReadableStreamOptions { /** @@ -87,21 +85,13 @@ export class RetriableReadableStream extends Readable { this.offset = offset; this.end = offset + count - 1; this.maxRetryRequests = - options.maxRetryRequests && options.maxRetryRequests >= 0 - ? options.maxRetryRequests - : 0; + options.maxRetryRequests && options.maxRetryRequests >= 0 ? options.maxRetryRequests : 0; this.progress = options.progress; this.options = options; aborter.addEventListener("abort", () => { this.source.pause(); - this.emit( - "error", - new RestError( - "The request was aborted", - RestError.REQUEST_ABORTED_ERROR - ) - ); + this.emit("error", new RestError("The request was aborted", RestError.REQUEST_ABORTED_ERROR)); }); this.setSourceDataHandler(); @@ -154,13 +144,13 @@ export class RetriableReadableStream extends Readable { if (this.retries < this.maxRetryRequests) { this.retries += 1; this.getter(this.offset) - .then(newSource => { + .then((newSource) => { this.source = newSource; this.setSourceDataHandler(); this.setSourceEndHandler(); this.setSourceErrorHandler(); }) - .catch(error => { + .catch((error) => { this.emit("error", error); }); } else { @@ -189,7 +179,7 @@ export class RetriableReadableStream extends Readable { } private setSourceErrorHandler() { - this.source.on("error", error => { + this.source.on("error", (error) => { this.emit("error", error); }); } diff --git a/sdk/storage/storage-blob/src/utils/utils.common.ts b/sdk/storage/storage-blob/src/utils/utils.common.ts index 014c17a693ec..6ecb8cec24f0 100644 --- a/sdk/storage/storage-blob/src/utils/utils.common.ts +++ b/sdk/storage/storage-blob/src/utils/utils.common.ts @@ -93,11 +93,7 @@ export function appendToURLPath(url: string, name: string): string { const urlParsed = URLBuilder.parse(url); let path = urlParsed.getPath(); - path = path - ? path.endsWith("/") - ? `${path}${name}` - : `${path}/${name}` - : name; + path = path ? (path.endsWith("/") ? `${path}${name}` : `${path}/${name}`) : name; urlParsed.setPath(path); return urlParsed.toString(); @@ -113,11 +109,7 @@ export function appendToURLPath(url: string, name: string): string { * @param {string} [value] Parameter value * @returns {string} An updated URL string */ -export function setURLParameter( - url: string, - name: string, - value?: string -): string { +export function setURLParameter(url: string, name: string, value?: string): string { const urlParsed = URLBuilder.parse(url); urlParsed.setQueryParameter(name, value); return urlParsed.toString(); @@ -131,10 +123,7 @@ export function setURLParameter( * @param {string} name * @returns {(string | string[] | undefined)} */ -export function getURLParameter( - url: string, - name: string -): string | string[] | undefined { +export function getURLParameter(url: string, name: string): string | string[] | undefined { const urlParsed = URLBuilder.parse(url); return urlParsed.getQueryParameterValue(name); } @@ -179,18 +168,14 @@ export function getURLQueries(url: string): { [key: string]: string } { } queryString = queryString.trim(); - queryString = queryString.startsWith("?") - ? queryString.substr(1) - : queryString; + queryString = queryString.startsWith("?") ? queryString.substr(1) : queryString; let querySubStrings: string[] = queryString.split("&"); querySubStrings = querySubStrings.filter((value: string) => { const indexOfEqual = value.indexOf("="); const lastIndexOfEqual = value.lastIndexOf("="); return ( - indexOfEqual > 0 && - indexOfEqual === lastIndexOfEqual && - lastIndexOfEqual < value.length - 1 + indexOfEqual > 0 && indexOfEqual === lastIndexOfEqual && lastIndexOfEqual < value.length - 1 ); }); @@ -214,10 +199,7 @@ export function getURLQueries(url: string): { [key: string]: string } { * If false, YYYY-MM-DDThh:mm:ssZ will be returned. * @returns {string} Date string in ISO8061 format, with or without 7 milliseconds component */ -export function truncatedISO8061Date( - date: Date, - withMilliseconds: boolean = true -): string { +export function truncatedISO8061Date(date: Date, withMilliseconds: boolean = true): string { // Date.toISOString() will return like "2018-10-29T06:34:36.139Z" const dateString = date.toISOString(); @@ -245,9 +227,7 @@ export function base64encode(content: string): string { * @returns {string} */ export function base64decode(encodedString: string): string { - return !isNode - ? atob(encodedString) - : Buffer.from(encodedString, "base64").toString(); + return !isNode ? atob(encodedString) : Buffer.from(encodedString, "base64").toString(); } /** @@ -257,29 +237,21 @@ export function base64decode(encodedString: string): string { * @param {number} blockIndex * @returns {string} */ -export function generateBlockID( - blockIDPrefix: string, - blockIndex: number -): string { +export function generateBlockID(blockIDPrefix: string, blockIndex: number): string { // To generate a 64 bytes base64 string, source string should be 48 const maxSourceStringLength = 48; // A blob can have a maximum of 100,000 uncommitted blocks at any given time const maxBlockIndexLength = 6; - const maxAllowedBlockIDPrefixLength = - maxSourceStringLength - maxBlockIndexLength; + const maxAllowedBlockIDPrefixLength = maxSourceStringLength - maxBlockIndexLength; if (blockIDPrefix.length > maxAllowedBlockIDPrefixLength) { blockIDPrefix = blockIDPrefix.slice(0, maxAllowedBlockIDPrefixLength); } const res = blockIDPrefix + - padStart( - blockIndex.toString(), - maxSourceStringLength - blockIDPrefix.length, - "0" - ); + padStart(blockIndex.toString(), maxSourceStringLength - blockIDPrefix.length, "0"); return base64encode(res); } diff --git a/sdk/storage/storage-blob/src/utils/utils.node.ts b/sdk/storage/storage-blob/src/utils/utils.node.ts index 74f04f0a7094..394fed9f40f6 100644 --- a/sdk/storage/storage-blob/src/utils/utils.node.ts +++ b/sdk/storage/storage-blob/src/utils/utils.node.ts @@ -35,14 +35,9 @@ export async function streamToBuffer( } // How much data needed in this chunk - const chunkLength = - pos + chunk.length > count ? count - pos : chunk.length; + const chunkLength = pos + chunk.length > count ? count - pos : chunk.length; - buffer.fill( - chunk.slice(0, chunkLength), - offset + pos, - offset + pos + chunkLength - ); + buffer.fill(chunk.slice(0, chunkLength), offset + pos, offset + pos + chunkLength); pos += chunkLength; }); diff --git a/sdk/storage/storage-blob/test/aborter.test.ts b/sdk/storage/storage-blob/test/aborter.test.ts index f749b8ac02d9..057adb6c2daf 100644 --- a/sdk/storage/storage-blob/test/aborter.test.ts +++ b/sdk/storage/storage-blob/test/aborter.test.ts @@ -4,7 +4,7 @@ import { Aborter } from "../src/Aborter"; import { ContainerURL } from "../src/ContainerURL"; import { getBSU, getUniqueName } from "./utils"; import * as dotenv from "dotenv"; -dotenv.config({path:"../.env"}); +dotenv.config({ path: "../.env" }); // tslint:disable:no-empty describe("Aborter", () => { diff --git a/sdk/storage/storage-blob/test/appendbloburl.test.ts b/sdk/storage/storage-blob/test/appendbloburl.test.ts index 462351eb6989..f67884618f38 100644 --- a/sdk/storage/storage-blob/test/appendbloburl.test.ts +++ b/sdk/storage/storage-blob/test/appendbloburl.test.ts @@ -5,7 +5,7 @@ import { AppendBlobURL } from "../src/AppendBlobURL"; import { ContainerURL } from "../src/ContainerURL"; import { bodyToString, getBSU, getUniqueName } from "./utils"; import * as dotenv from "dotenv"; -dotenv.config({path:"../.env"}); +dotenv.config({ path: "../.env" }); describe("AppendBlobURL", () => { const serviceURL = getBSU(); @@ -47,26 +47,11 @@ describe("AppendBlobURL", () => { }; await appendBlobURL.create(Aborter.none, options); const properties = await appendBlobURL.getProperties(Aborter.none); - assert.equal( - properties.cacheControl, - options.blobHTTPHeaders.blobCacheControl - ); - assert.equal( - properties.contentDisposition, - options.blobHTTPHeaders.blobContentDisposition - ); - assert.equal( - properties.contentEncoding, - options.blobHTTPHeaders.blobContentEncoding - ); - assert.equal( - properties.contentLanguage, - options.blobHTTPHeaders.blobContentLanguage - ); - assert.equal( - properties.contentType, - options.blobHTTPHeaders.blobContentType - ); + assert.equal(properties.cacheControl, options.blobHTTPHeaders.blobCacheControl); + assert.equal(properties.contentDisposition, options.blobHTTPHeaders.blobContentDisposition); + assert.equal(properties.contentEncoding, options.blobHTTPHeaders.blobContentEncoding); + assert.equal(properties.contentLanguage, options.blobHTTPHeaders.blobContentLanguage); + assert.equal(properties.contentType, options.blobHTTPHeaders.blobContentType); assert.equal(properties.metadata!.key1, options.metadata.key1); assert.equal(properties.metadata!.key2, options.metadata.key2); }); diff --git a/sdk/storage/storage-blob/test/bloburl.test.ts b/sdk/storage/storage-blob/test/bloburl.test.ts index 9f449486e4fb..852764137b14 100644 --- a/sdk/storage/storage-blob/test/bloburl.test.ts +++ b/sdk/storage/storage-blob/test/bloburl.test.ts @@ -88,9 +88,7 @@ describe("BlobURL", () => { blobContentDisposition: "blobContentDisposition", blobContentEncoding: "blobContentEncoding", blobContentLanguage: "blobContentLanguage", - blobContentMD5: isNode - ? Buffer.from([1, 2, 3, 4]) - : new Uint8Array([1, 2, 3, 4]), + blobContentMD5: isNode ? Buffer.from([1, 2, 3, 4]) : new Uint8Array([1, 2, 3, 4]), blobContentType: "blobContentType" }; await blobURL.setHTTPHeaders(Aborter.none, headers); @@ -104,10 +102,7 @@ describe("BlobURL", () => { assert.deepStrictEqual(result.contentMD5, headers.blobContentMD5); assert.deepStrictEqual(result.contentEncoding, headers.blobContentEncoding); assert.deepStrictEqual(result.contentLanguage, headers.blobContentLanguage); - assert.deepStrictEqual( - result.contentDisposition, - headers.blobContentDisposition - ); + assert.deepStrictEqual(result.contentDisposition, headers.blobContentDisposition); }); it("acquireLease", async () => { @@ -219,13 +214,9 @@ describe("BlobURL", () => { await blobSnapshotURL.delete(Aborter.none); await blobURL.delete(Aborter.none); - const result2 = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - include: ["snapshots"] - } - ); + const result2 = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + include: ["snapshots"] + }); // Verify that the snapshot is deleted assert.equal(result2.segment.blobItems!.length, 0); @@ -238,13 +229,9 @@ describe("BlobURL", () => { const blobSnapshotURL = blobURL.withSnapshot(result.snapshot!); await blobSnapshotURL.getProperties(Aborter.none); - const result3 = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - include: ["snapshots"] - } - ); + const result3 = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + include: ["snapshots"] + }); // As a snapshot doesn't have leaseStatus and leaseState properties but origin blob has, // let assign them to undefined both for other properties' easy comparison @@ -261,10 +248,7 @@ describe("BlobURL", () => { result3.segment.blobItems![0].properties, result3.segment.blobItems![1].properties ); - assert.ok( - result3.segment.blobItems![0].snapshot || - result3.segment.blobItems![1].snapshot - ); + assert.ok(result3.segment.blobItems![0].snapshot || result3.segment.blobItems![1].snapshot); }); it("undelete", async () => { @@ -281,31 +265,20 @@ describe("BlobURL", () => { await blobURL.delete(Aborter.none); - const result = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - include: ["deleted"] - } - ); + const result = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + include: ["deleted"] + }); assert.ok(result.segment.blobItems![0].deleted); await blobURL.undelete(Aborter.none); - const result2 = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - include: ["deleted"] - } - ); + const result2 = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + include: ["deleted"] + }); assert.ok(!result2.segment.blobItems![0].deleted); }); it("startCopyFromURL", async () => { - const newBlobURL = BlobURL.fromContainerURL( - containerURL, - getUniqueName("copiedblob") - ); + const newBlobURL = BlobURL.fromContainerURL(containerURL, getUniqueName("copiedblob")); const result = await newBlobURL.startCopyFromURL(Aborter.none, blobURL.url); assert.ok(result.copyId); @@ -317,10 +290,7 @@ describe("BlobURL", () => { }); it("abortCopyFromURL should failed for a completed copy operation", async () => { - const newBlobURL = BlobURL.fromContainerURL( - containerURL, - getUniqueName("copiedblob") - ); + const newBlobURL = BlobURL.fromContainerURL(containerURL, getUniqueName("copiedblob")); const result = await newBlobURL.startCopyFromURL(Aborter.none, blobURL.url); assert.ok(result.copyId); sleep(1 * 1000); @@ -349,10 +319,7 @@ describe("BlobURL", () => { await blockBlobURL.setTier(Aborter.none, "Hot"); properties = await blockBlobURL.getProperties(Aborter.none); if (properties.archiveStatus) { - assert.equal( - properties.archiveStatus.toLowerCase(), - "rehydrate-pending-to-hot" - ); + assert.equal(properties.archiveStatus.toLowerCase(), "rehydrate-pending-to-hot"); } }); }); diff --git a/sdk/storage/storage-blob/test/blockbloburl.test.ts b/sdk/storage/storage-blob/test/blockbloburl.test.ts index 7310d2f33949..003e59cc4f68 100644 --- a/sdk/storage/storage-blob/test/blockbloburl.test.ts +++ b/sdk/storage/storage-blob/test/blockbloburl.test.ts @@ -6,7 +6,7 @@ import { BlockBlobURL } from "../src/BlockBlobURL"; import { ContainerURL } from "../src/ContainerURL"; import { base64encode, bodyToString, getBSU, getUniqueName } from "./utils"; import * as dotenv from "dotenv"; -dotenv.config({path:"../.env"}); +dotenv.config({ path: "../.env" }); describe("BlockBlobURL", () => { const serviceURL = getBSU(); @@ -56,10 +56,7 @@ describe("BlockBlobURL", () => { const result = await blobURL.download(Aborter.none, 0); assert.deepStrictEqual(await bodyToString(result, body.length), body); assert.deepStrictEqual(result.cacheControl, options.blobCacheControl); - assert.deepStrictEqual( - result.contentDisposition, - options.blobContentDisposition - ); + assert.deepStrictEqual(result.contentDisposition, options.blobContentDisposition); assert.deepStrictEqual(result.contentEncoding, options.blobContentEncoding); assert.deepStrictEqual(result.contentLanguage, options.blobContentLanguage); assert.deepStrictEqual(result.contentType, options.blobContentType); @@ -68,22 +65,9 @@ describe("BlockBlobURL", () => { it("stageBlock", async () => { const body = "HelloWorld"; - await blockBlobURL.stageBlock( - Aborter.none, - base64encode("1"), - body, - body.length - ); - await blockBlobURL.stageBlock( - Aborter.none, - base64encode("2"), - body, - body.length - ); - const listResponse = await blockBlobURL.getBlockList( - Aborter.none, - "uncommitted" - ); + await blockBlobURL.stageBlock(Aborter.none, base64encode("1"), body, body.length); + await blockBlobURL.stageBlock(Aborter.none, base64encode("2"), body, body.length); + const listResponse = await blockBlobURL.getBlockList(Aborter.none, "uncommitted"); assert.equal(listResponse.uncommittedBlocks!.length, 2); assert.equal(listResponse.uncommittedBlocks![0].name, base64encode("1")); assert.equal(listResponse.uncommittedBlocks![0].size, body.length); @@ -106,17 +90,9 @@ describe("BlockBlobURL", () => { containerURL, getUniqueName("newblockblob") ); - await newBlockBlobURL.stageBlockFromURL( - Aborter.none, - base64encode("1"), - blockBlobURL.url, - 0 - ); + await newBlockBlobURL.stageBlockFromURL(Aborter.none, base64encode("1"), blockBlobURL.url, 0); - const listResponse = await newBlockBlobURL.getBlockList( - Aborter.none, - "uncommitted" - ); + const listResponse = await newBlockBlobURL.getBlockList(Aborter.none, "uncommitted"); assert.equal(listResponse.uncommittedBlocks!.length, 1); assert.equal(listResponse.uncommittedBlocks![0].name, base64encode("1")); assert.equal(listResponse.uncommittedBlocks![0].size, body.length); @@ -159,10 +135,7 @@ describe("BlockBlobURL", () => { 2 ); - const listResponse = await newBlockBlobURL.getBlockList( - Aborter.none, - "uncommitted" - ); + const listResponse = await newBlockBlobURL.getBlockList(Aborter.none, "uncommitted"); assert.equal(listResponse.uncommittedBlocks!.length, 3); assert.equal(listResponse.uncommittedBlocks![0].name, base64encode("1")); assert.equal(listResponse.uncommittedBlocks![0].size, 4); @@ -183,26 +156,10 @@ describe("BlockBlobURL", () => { it("commitBlockList", async () => { const body = "HelloWorld"; - await blockBlobURL.stageBlock( - Aborter.none, - base64encode("1"), - body, - body.length - ); - await blockBlobURL.stageBlock( - Aborter.none, - base64encode("2"), - body, - body.length - ); - await blockBlobURL.commitBlockList(Aborter.none, [ - base64encode("1"), - base64encode("2") - ]); - const listResponse = await blockBlobURL.getBlockList( - Aborter.none, - "committed" - ); + await blockBlobURL.stageBlock(Aborter.none, base64encode("1"), body, body.length); + await blockBlobURL.stageBlock(Aborter.none, base64encode("2"), body, body.length); + await blockBlobURL.commitBlockList(Aborter.none, [base64encode("1"), base64encode("2")]); + const listResponse = await blockBlobURL.getBlockList(Aborter.none, "committed"); assert.equal(listResponse.committedBlocks!.length, 2); assert.equal(listResponse.committedBlocks![0].name, base64encode("1")); assert.equal(listResponse.committedBlocks![0].size, body.length); @@ -212,18 +169,8 @@ describe("BlockBlobURL", () => { it("commitBlockList with all parameters set", async () => { const body = "HelloWorld"; - await blockBlobURL.stageBlock( - Aborter.none, - base64encode("1"), - body, - body.length - ); - await blockBlobURL.stageBlock( - Aborter.none, - base64encode("2"), - body, - body.length - ); + await blockBlobURL.stageBlock(Aborter.none, base64encode("1"), body, body.length); + await blockBlobURL.stageBlock(Aborter.none, base64encode("2"), body, body.length); const options = { blobCacheControl: "blobCacheControl", @@ -236,19 +183,12 @@ describe("BlockBlobURL", () => { keyb: "valb" } }; - await blockBlobURL.commitBlockList( - Aborter.none, - [base64encode("1"), base64encode("2")], - { - blobHTTPHeaders: options, - metadata: options.metadata - } - ); + await blockBlobURL.commitBlockList(Aborter.none, [base64encode("1"), base64encode("2")], { + blobHTTPHeaders: options, + metadata: options.metadata + }); - const listResponse = await blockBlobURL.getBlockList( - Aborter.none, - "committed" - ); + const listResponse = await blockBlobURL.getBlockList(Aborter.none, "committed"); assert.equal(listResponse.committedBlocks!.length, 2); assert.equal(listResponse.committedBlocks![0].name, base64encode("1")); assert.equal(listResponse.committedBlocks![0].size, body.length); @@ -256,15 +196,9 @@ describe("BlockBlobURL", () => { assert.equal(listResponse.committedBlocks![1].size, body.length); const result = await blobURL.download(Aborter.none, 0); - assert.deepStrictEqual( - await bodyToString(result, body.repeat(2).length), - body.repeat(2) - ); + assert.deepStrictEqual(await bodyToString(result, body.repeat(2).length), body.repeat(2)); assert.deepStrictEqual(result.cacheControl, options.blobCacheControl); - assert.deepStrictEqual( - result.contentDisposition, - options.blobContentDisposition - ); + assert.deepStrictEqual(result.contentDisposition, options.blobContentDisposition); assert.deepStrictEqual(result.contentEncoding, options.blobContentEncoding); assert.deepStrictEqual(result.contentLanguage, options.blobContentLanguage); assert.deepStrictEqual(result.contentType, options.blobContentType); @@ -273,18 +207,8 @@ describe("BlockBlobURL", () => { it("getBlockList", async () => { const body = "HelloWorld"; - await blockBlobURL.stageBlock( - Aborter.none, - base64encode("1"), - body, - body.length - ); - await blockBlobURL.stageBlock( - Aborter.none, - base64encode("2"), - body, - body.length - ); + await blockBlobURL.stageBlock(Aborter.none, base64encode("1"), body, body.length); + await blockBlobURL.stageBlock(Aborter.none, base64encode("2"), body, body.length); await blockBlobURL.commitBlockList(Aborter.none, [base64encode("2")]); const listResponse = await blockBlobURL.getBlockList(Aborter.none, "all"); assert.equal(listResponse.committedBlocks!.length, 1); diff --git a/sdk/storage/storage-blob/test/browser/highlevel.browser.test.ts b/sdk/storage/storage-blob/test/browser/highlevel.browser.test.ts index 0a57e8f17219..3d9cae9b2a15 100644 --- a/sdk/storage/storage-blob/test/browser/highlevel.browser.test.ts +++ b/sdk/storage/storage-blob/test/browser/highlevel.browser.test.ts @@ -82,7 +82,7 @@ describe("Highelvel", () => { await uploadBrowserDataToBlockBlob(aborter, tempFile1, blockBlobURL, { blockSize: 4 * 1024 * 1024, parallelism: 2, - progress: ev => { + progress: (ev) => { assert.ok(ev.loadedBytes); eventTriggered = true; aborter.abort(); @@ -100,7 +100,7 @@ describe("Highelvel", () => { await uploadBrowserDataToBlockBlob(aborter, tempFile2, blockBlobURL, { blockSize: 4 * 1024 * 1024, parallelism: 2, - progress: ev => { + progress: (ev) => { assert.ok(ev.loadedBytes); eventTriggered = true; aborter.abort(); diff --git a/sdk/storage/storage-blob/test/containerurl.test.ts b/sdk/storage/storage-blob/test/containerurl.test.ts index 24dd7860129c..d95bfd74bfe5 100644 --- a/sdk/storage/storage-blob/test/containerurl.test.ts +++ b/sdk/storage/storage-blob/test/containerurl.test.ts @@ -6,7 +6,7 @@ import { BlockBlobURL } from "../src/BlockBlobURL"; import { ContainerURL } from "../src/ContainerURL"; import { getBSU, getUniqueName, sleep } from "./utils"; import * as dotenv from "dotenv"; -dotenv.config({path:"../.env"}); +dotenv.config({ path: "../.env" }); describe("ContainerURL", () => { const serviceURL = getBSU(); @@ -48,16 +48,13 @@ describe("ContainerURL", () => { assert.ok(!result.blobPublicAccess); }); - it("create with default parameters", done => { + it("create with default parameters", (done) => { // create() with default parameters has been tested in beforeEach done(); }); it("create with all parameters configured", async () => { - const cURL = ContainerURL.fromServiceURL( - serviceURL, - getUniqueName(containerName) - ); + const cURL = ContainerURL.fromServiceURL(serviceURL, getUniqueName(containerName)); const metadata = { key: "value" }; const access = "container"; await cURL.create(Aborter.none, { metadata, access }); @@ -66,7 +63,7 @@ describe("ContainerURL", () => { assert.deepEqual(result.metadata, metadata); }); - it("delete", done => { + it("delete", (done) => { // delete() with default parameters has been tested in afterEach done(); }); @@ -167,10 +164,7 @@ describe("ContainerURL", () => { it("listBlobFlatSegment with default parameters", async () => { const blobURLs = []; for (let i = 0; i < 3; i++) { - const blobURL = BlobURL.fromContainerURL( - containerURL, - getUniqueName(`blockblob/${i}`) - ); + const blobURL = BlobURL.fromContainerURL(containerURL, getUniqueName(`blockblob/${i}`)); const blockBlobURL = BlockBlobURL.fromBlobURL(blobURL); await blockBlobURL.upload(Aborter.none, "", 0); blobURLs.push(blobURL); @@ -196,10 +190,7 @@ describe("ContainerURL", () => { keyb: "c" }; for (let i = 0; i < 2; i++) { - const blobURL = BlobURL.fromContainerURL( - containerURL, - getUniqueName(`${prefix}/${i}`) - ); + const blobURL = BlobURL.fromContainerURL(containerURL, getUniqueName(`${prefix}/${i}`)); const blockBlobURL = BlockBlobURL.fromBlobURL(blobURL); await blockBlobURL.upload(Aborter.none, "", 0, { metadata @@ -207,42 +198,22 @@ describe("ContainerURL", () => { blobURLs.push(blobURL); } - const result = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - include: [ - "snapshots", - "metadata", - "uncommittedblobs", - "copy", - "deleted" - ], - maxresults: 1, - prefix - } - ); + const result = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + include: ["snapshots", "metadata", "uncommittedblobs", "copy", "deleted"], + maxresults: 1, + prefix + }); assert.ok(result.serviceEndpoint.length > 0); assert.ok(containerURL.url.indexOf(result.containerName)); assert.deepStrictEqual(result.segment.blobItems!.length, 1); assert.ok(blobURLs[0].url.indexOf(result.segment.blobItems![0].name)); assert.deepStrictEqual(result.segment.blobItems![0].metadata, metadata); - const result2 = await containerURL.listBlobFlatSegment( - Aborter.none, - result.nextMarker, - { - include: [ - "snapshots", - "metadata", - "uncommittedblobs", - "copy", - "deleted" - ], - maxresults: 2, - prefix - } - ); + const result2 = await containerURL.listBlobFlatSegment(Aborter.none, result.nextMarker, { + include: ["snapshots", "metadata", "uncommittedblobs", "copy", "deleted"], + maxresults: 2, + prefix + }); assert.ok(result2.serviceEndpoint.length > 0); assert.ok(containerURL.url.indexOf(result2.containerName)); @@ -258,28 +229,19 @@ describe("ContainerURL", () => { it("listBlobHierarchySegment with default parameters", async () => { const blobURLs = []; for (let i = 0; i < 3; i++) { - const blobURL = BlobURL.fromContainerURL( - containerURL, - getUniqueName(`blockblob${i}/${i}`) - ); + const blobURL = BlobURL.fromContainerURL(containerURL, getUniqueName(`blockblob${i}/${i}`)); const blockBlobURL = BlockBlobURL.fromBlobURL(blobURL); await blockBlobURL.upload(Aborter.none, "", 0); blobURLs.push(blobURL); } const delimiter = "/"; - const result = await containerURL.listBlobHierarchySegment( - Aborter.none, - delimiter - ); + const result = await containerURL.listBlobHierarchySegment(Aborter.none, delimiter); assert.ok(result.serviceEndpoint.length > 0); assert.ok(containerURL.url.indexOf(result.containerName)); assert.deepStrictEqual(result.nextMarker, ""); assert.deepStrictEqual(result.delimiter, delimiter); - assert.deepStrictEqual( - result.segment.blobPrefixes!.length, - blobURLs.length - ); + assert.deepStrictEqual(result.segment.blobPrefixes!.length, blobURLs.length); for (const blob of blobURLs) { let i = 0; @@ -311,16 +273,11 @@ describe("ContainerURL", () => { blobURLs.push(blobURL); } - const result = await containerURL.listBlobHierarchySegment( - Aborter.none, - delimiter, - undefined, - { - include: ["metadata", "uncommittedblobs", "copy", "deleted"], - maxresults: 1, - prefix - } - ); + const result = await containerURL.listBlobHierarchySegment(Aborter.none, delimiter, undefined, { + include: ["metadata", "uncommittedblobs", "copy", "deleted"], + maxresults: 1, + prefix + }); assert.ok(result.serviceEndpoint.length > 0); assert.ok(containerURL.url.indexOf(result.containerName)); assert.deepStrictEqual(result.segment.blobPrefixes!.length, 1); diff --git a/sdk/storage/storage-blob/test/node/blockbloburl.test.ts b/sdk/storage/storage-blob/test/node/blockbloburl.test.ts index caa0198821e0..23dcb33e2fe4 100644 --- a/sdk/storage/storage-blob/test/node/blockbloburl.test.ts +++ b/sdk/storage/storage-blob/test/node/blockbloburl.test.ts @@ -52,9 +52,6 @@ describe("BlockBlobURL Node.js only", () => { const body: string = getUniqueName("randomstring你好"); await blockBlobURL.upload(Aborter.none, body, Buffer.byteLength(body)); const result = await blobURL.download(Aborter.none, 0); - assert.deepStrictEqual( - await bodyToString(result, Buffer.byteLength(body)), - body - ); + assert.deepStrictEqual(await bodyToString(result, Buffer.byteLength(body)), body); }); }); diff --git a/sdk/storage/storage-blob/test/node/highlevel.node.test.ts b/sdk/storage/storage-blob/test/node/highlevel.node.test.ts index 94f82d12ab98..840dc21b4e88 100644 --- a/sdk/storage/storage-blob/test/node/highlevel.node.test.ts +++ b/sdk/storage/storage-blob/test/node/highlevel.node.test.ts @@ -11,12 +11,7 @@ import { uploadStreamToBlockBlob } from "../../src/highlevel.node"; import { IRetriableReadableStreamOptions } from "../../src/utils/RetriableReadableStream"; -import { - createRandomLocalFile, - getBSU, - getUniqueName, - readStreamToLocalFile -} from "../utils"; +import { createRandomLocalFile, getBSU, getUniqueName, readStreamToLocalFile } from "../utils"; // tslint:disable:no-empty describe("Highlevel", () => { @@ -49,17 +44,9 @@ describe("Highlevel", () => { if (!fs.existsSync(tempFolderPath)) { fs.mkdirSync(tempFolderPath); } - tempFileLarge = await createRandomLocalFile( - tempFolderPath, - 257, - 1024 * 1024 - ); + tempFileLarge = await createRandomLocalFile(tempFolderPath, 257, 1024 * 1024); tempFileLargeLength = 257 * 1024 * 1024; - tempFileSmall = await createRandomLocalFile( - tempFolderPath, - 15, - 1024 * 1024 - ); + tempFileSmall = await createRandomLocalFile(tempFolderPath, 15, 1024 * 1024); tempFileSmallLength = 15 * 1024 * 1024; }); @@ -75,14 +62,8 @@ describe("Highlevel", () => { }); const downloadResponse = await blockBlobURL.download(Aborter.none, 0); - const downloadedFile = path.join( - tempFolderPath, - getUniqueName("downloadfile.") - ); - await readStreamToLocalFile( - downloadResponse.readableStreamBody!, - downloadedFile - ); + const downloadedFile = path.join(tempFolderPath, getUniqueName("downloadfile.")); + await readStreamToLocalFile(downloadResponse.readableStreamBody!, downloadedFile); const downloadedData = await fs.readFileSync(downloadedFile); const uploadedData = await fs.readFileSync(tempFileLarge); @@ -98,14 +79,8 @@ describe("Highlevel", () => { }); const downloadResponse = await blockBlobURL.download(Aborter.none, 0); - const downloadedFile = path.join( - tempFolderPath, - getUniqueName("downloadfile.") - ); - await readStreamToLocalFile( - downloadResponse.readableStreamBody!, - downloadedFile - ); + const downloadedFile = path.join(tempFolderPath, getUniqueName("downloadfile.")); + await readStreamToLocalFile(downloadResponse.readableStreamBody!, downloadedFile); const downloadedData = await fs.readFileSync(downloadedFile); const uploadedData = await fs.readFileSync(tempFileSmall); @@ -120,14 +95,8 @@ describe("Highlevel", () => { }); const downloadResponse = await blockBlobURL.download(Aborter.none, 0); - const downloadedFile = path.join( - tempFolderPath, - getUniqueName("downloadfile.") - ); - await readStreamToLocalFile( - downloadResponse.readableStreamBody!, - downloadedFile - ); + const downloadedFile = path.join(tempFolderPath, getUniqueName("downloadfile.")); + await readStreamToLocalFile(downloadResponse.readableStreamBody!, downloadedFile); const downloadedData = await fs.readFileSync(downloadedFile); const uploadedData = await fs.readFileSync(tempFileSmall); @@ -172,7 +141,7 @@ describe("Highlevel", () => { await uploadFileToBlockBlob(aborter, tempFileLarge, blockBlobURL, { blockSize: 4 * 1024 * 1024, parallelism: 20, - progress: ev => { + progress: (ev) => { assert.ok(ev.loadedBytes); eventTriggered = true; aborter.abort(); @@ -190,7 +159,7 @@ describe("Highlevel", () => { await uploadFileToBlockBlob(aborter, tempFileSmall, blockBlobURL, { blockSize: 4 * 1024 * 1024, parallelism: 20, - progress: ev => { + progress: (ev) => { assert.ok(ev.loadedBytes); eventTriggered = true; aborter.abort(); @@ -202,24 +171,12 @@ describe("Highlevel", () => { it("uploadStreamToBlockBlob should success", async () => { const rs = fs.createReadStream(tempFileLarge); - await uploadStreamToBlockBlob( - Aborter.none, - rs, - blockBlobURL, - 4 * 1024 * 1024, - 20 - ); + await uploadStreamToBlockBlob(Aborter.none, rs, blockBlobURL, 4 * 1024 * 1024, 20); const downloadResponse = await blockBlobURL.download(Aborter.none, 0); - const downloadFilePath = path.join( - tempFolderPath, - getUniqueName("downloadFile") - ); - await readStreamToLocalFile( - downloadResponse.readableStreamBody!, - downloadFilePath - ); + const downloadFilePath = path.join(tempFolderPath, getUniqueName("downloadFile")); + await readStreamToLocalFile(downloadResponse.readableStreamBody!, downloadFilePath); const downloadedBuffer = fs.readFileSync(downloadFilePath); const uploadedBuffer = fs.readFileSync(tempFileLarge); @@ -233,24 +190,12 @@ describe("Highlevel", () => { const bufferStream = new PassThrough(); bufferStream.end(buf); - await uploadStreamToBlockBlob( - Aborter.none, - bufferStream, - blockBlobURL, - 4 * 1024 * 1024, - 20 - ); + await uploadStreamToBlockBlob(Aborter.none, bufferStream, blockBlobURL, 4 * 1024 * 1024, 20); const downloadResponse = await blockBlobURL.download(Aborter.none, 0); - const downloadFilePath = path.join( - tempFolderPath, - getUniqueName("downloadFile") - ); - await readStreamToLocalFile( - downloadResponse.readableStreamBody!, - downloadFilePath - ); + const downloadFilePath = path.join(tempFolderPath, getUniqueName("downloadFile")); + await readStreamToLocalFile(downloadResponse.readableStreamBody!, downloadFilePath); const downloadedBuffer = fs.readFileSync(downloadFilePath); assert.ok(buf.equals(downloadedBuffer)); @@ -263,13 +208,7 @@ describe("Highlevel", () => { const aborter = Aborter.timeout(1); try { - await uploadStreamToBlockBlob( - aborter, - rs, - blockBlobURL, - 4 * 1024 * 1024, - 20 - ); + await uploadStreamToBlockBlob(aborter, rs, blockBlobURL, 4 * 1024 * 1024, 20); assert.fail(); } catch (err) { assert.ok((err.code as string).toLowerCase().includes("abort")); @@ -280,31 +219,18 @@ describe("Highlevel", () => { const rs = fs.createReadStream(tempFileLarge); let eventTriggered = false; - await uploadStreamToBlockBlob( - Aborter.none, - rs, - blockBlobURL, - 4 * 1024 * 1024, - 20, - { - progress: ev => { - assert.ok(ev.loadedBytes); - eventTriggered = true; - } + await uploadStreamToBlockBlob(Aborter.none, rs, blockBlobURL, 4 * 1024 * 1024, 20, { + progress: (ev) => { + assert.ok(ev.loadedBytes); + eventTriggered = true; } - ); + }); assert.ok(eventTriggered); }); it("downloadBlobToBuffer should success", async () => { const rs = fs.createReadStream(tempFileLarge); - await uploadStreamToBlockBlob( - Aborter.none, - rs, - blockBlobURL, - 4 * 1024 * 1024, - 20 - ); + await uploadStreamToBlockBlob(Aborter.none, rs, blockBlobURL, 4 * 1024 * 1024, 20); const buf = Buffer.alloc(tempFileLargeLength); await downloadBlobToBuffer(Aborter.none, buf, blockBlobURL, 0, undefined, { @@ -319,28 +245,15 @@ describe("Highlevel", () => { it("downloadBlobToBuffer should abort", async () => { const rs = fs.createReadStream(tempFileLarge); - await uploadStreamToBlockBlob( - Aborter.none, - rs, - blockBlobURL, - 4 * 1024 * 1024, - 20 - ); + await uploadStreamToBlockBlob(Aborter.none, rs, blockBlobURL, 4 * 1024 * 1024, 20); try { const buf = Buffer.alloc(tempFileLargeLength); - await downloadBlobToBuffer( - Aborter.timeout(1), - buf, - blockBlobURL, - 0, - undefined, - { - blockSize: 4 * 1024 * 1024, - maxRetryRequestsPerBlock: 5, - parallelism: 20 - } - ); + await downloadBlobToBuffer(Aborter.timeout(1), buf, blockBlobURL, 0, undefined, { + blockSize: 4 * 1024 * 1024, + maxRetryRequestsPerBlock: 5, + parallelism: 20 + }); assert.fail(); } catch (err) { assert.ok((err.code as string).toLowerCase().includes("abort")); @@ -349,13 +262,7 @@ describe("Highlevel", () => { it("downloadBlobToBuffer should update progress event", async () => { const rs = fs.createReadStream(tempFileSmall); - await uploadStreamToBlockBlob( - Aborter.none, - rs, - blockBlobURL, - 4 * 1024 * 1024, - 10 - ); + await uploadStreamToBlockBlob(Aborter.none, rs, blockBlobURL, 4 * 1024 * 1024, 10); let eventTriggered = false; const buf = Buffer.alloc(tempFileSmallLength); @@ -375,47 +282,30 @@ describe("Highlevel", () => { }); it("bloburl.download should success when internal stream unexcepted ends at the stream end", async () => { - const uploadResponse = await uploadFileToBlockBlob( - Aborter.none, - tempFileSmall, - blockBlobURL, - { - blockSize: 4 * 1024 * 1024, - parallelism: 20 - } - ); + const uploadResponse = await uploadFileToBlockBlob(Aborter.none, tempFileSmall, blockBlobURL, { + blockSize: 4 * 1024 * 1024, + parallelism: 20 + }); let retirableReadableStreamOptions: IRetriableReadableStreamOptions; - const downloadResponse = await blockBlobURL.download( - Aborter.none, - 0, - undefined, - { - blobAccessConditions: { - modifiedAccessConditions: { - ifMatch: uploadResponse.eTag - } - }, - maxRetryRequests: 1, - progress: ev => { - if (ev.loadedBytes >= tempFileSmallLength) { - retirableReadableStreamOptions.doInjectErrorOnce = true; - } + const downloadResponse = await blockBlobURL.download(Aborter.none, 0, undefined, { + blobAccessConditions: { + modifiedAccessConditions: { + ifMatch: uploadResponse.eTag + } + }, + maxRetryRequests: 1, + progress: (ev) => { + if (ev.loadedBytes >= tempFileSmallLength) { + retirableReadableStreamOptions.doInjectErrorOnce = true; } } - ); + }); - retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any) - .options; + retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any).options; - const downloadedFile = path.join( - tempFolderPath, - getUniqueName("downloadfile.") - ); - await readStreamToLocalFile( - downloadResponse.readableStreamBody!, - downloadedFile - ); + const downloadedFile = path.join(tempFolderPath, getUniqueName("downloadfile.")); + await readStreamToLocalFile(downloadResponse.readableStreamBody!, downloadedFile); const downloadedData = await fs.readFileSync(downloadedFile); const uploadedData = await fs.readFileSync(tempFileSmall); @@ -425,48 +315,31 @@ describe("Highlevel", () => { }); it("bloburl.download should download full data successfully when internal stream unexcepted ends", async () => { - const uploadResponse = await uploadFileToBlockBlob( - Aborter.none, - tempFileSmall, - blockBlobURL, - { - blockSize: 4 * 1024 * 1024, - parallelism: 20 - } - ); + const uploadResponse = await uploadFileToBlockBlob(Aborter.none, tempFileSmall, blockBlobURL, { + blockSize: 4 * 1024 * 1024, + parallelism: 20 + }); let retirableReadableStreamOptions: IRetriableReadableStreamOptions; let injectedErrors = 0; - const downloadResponse = await blockBlobURL.download( - Aborter.none, - 0, - undefined, - { - blobAccessConditions: { - modifiedAccessConditions: { - ifMatch: uploadResponse.eTag - } - }, - maxRetryRequests: 3, - progress: () => { - if (injectedErrors++ < 3) { - retirableReadableStreamOptions.doInjectErrorOnce = true; - } + const downloadResponse = await blockBlobURL.download(Aborter.none, 0, undefined, { + blobAccessConditions: { + modifiedAccessConditions: { + ifMatch: uploadResponse.eTag + } + }, + maxRetryRequests: 3, + progress: () => { + if (injectedErrors++ < 3) { + retirableReadableStreamOptions.doInjectErrorOnce = true; } } - ); + }); - retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any) - .options; + retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any).options; - const downloadedFile = path.join( - tempFolderPath, - getUniqueName("downloadfile.") - ); - await readStreamToLocalFile( - downloadResponse.readableStreamBody!, - downloadedFile - ); + const downloadedFile = path.join(tempFolderPath, getUniqueName("downloadfile.")); + await readStreamToLocalFile(downloadResponse.readableStreamBody!, downloadedFile); const downloadedData = await fs.readFileSync(downloadedFile); const uploadedData = await fs.readFileSync(tempFileSmall); @@ -476,107 +349,69 @@ describe("Highlevel", () => { }); it("bloburl.download should download partial data when internal stream unexcepted ends", async () => { - const uploadResponse = await uploadFileToBlockBlob( - Aborter.none, - tempFileSmall, - blockBlobURL, - { - blockSize: 4 * 1024 * 1024, - parallelism: 20 - } - ); + const uploadResponse = await uploadFileToBlockBlob(Aborter.none, tempFileSmall, blockBlobURL, { + blockSize: 4 * 1024 * 1024, + parallelism: 20 + }); const partialSize = 500 * 1024; let retirableReadableStreamOptions: IRetriableReadableStreamOptions; let injectedErrors = 0; - const downloadResponse = await blockBlobURL.download( - Aborter.none, - 0, - partialSize, - { - blobAccessConditions: { - modifiedAccessConditions: { - ifMatch: uploadResponse.eTag - } - }, - maxRetryRequests: 3, - progress: () => { - if (injectedErrors++ < 3) { - retirableReadableStreamOptions.doInjectErrorOnce = true; - } + const downloadResponse = await blockBlobURL.download(Aborter.none, 0, partialSize, { + blobAccessConditions: { + modifiedAccessConditions: { + ifMatch: uploadResponse.eTag + } + }, + maxRetryRequests: 3, + progress: () => { + if (injectedErrors++ < 3) { + retirableReadableStreamOptions.doInjectErrorOnce = true; } } - ); + }); - retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any) - .options; + retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any).options; - const downloadedFile = path.join( - tempFolderPath, - getUniqueName("downloadfile.") - ); - await readStreamToLocalFile( - downloadResponse.readableStreamBody!, - downloadedFile - ); + const downloadedFile = path.join(tempFolderPath, getUniqueName("downloadfile.")); + await readStreamToLocalFile(downloadResponse.readableStreamBody!, downloadedFile); const downloadedData = await fs.readFileSync(downloadedFile); const uploadedData = await fs.readFileSync(tempFileSmall); fs.unlinkSync(downloadedFile); - assert.ok( - downloadedData - .slice(0, partialSize) - .equals(uploadedData.slice(0, partialSize)) - ); + assert.ok(downloadedData.slice(0, partialSize).equals(uploadedData.slice(0, partialSize))); }); it("bloburl.download should download data failed when exceeding max stream retry requests", async () => { - const uploadResponse = await uploadFileToBlockBlob( - Aborter.none, - tempFileSmall, - blockBlobURL, - { - blockSize: 4 * 1024 * 1024, - parallelism: 20 - } - ); + const uploadResponse = await uploadFileToBlockBlob(Aborter.none, tempFileSmall, blockBlobURL, { + blockSize: 4 * 1024 * 1024, + parallelism: 20 + }); - const downloadedFile = path.join( - tempFolderPath, - getUniqueName("downloadfile.") - ); + const downloadedFile = path.join(tempFolderPath, getUniqueName("downloadfile.")); let retirableReadableStreamOptions: IRetriableReadableStreamOptions; let injectedErrors = 0; let expectedError = false; try { - const downloadResponse = await blockBlobURL.download( - Aborter.none, - 0, - undefined, - { - blobAccessConditions: { - modifiedAccessConditions: { - ifMatch: uploadResponse.eTag - } - }, - maxRetryRequests: 0, - progress: () => { - if (injectedErrors++ < 1) { - retirableReadableStreamOptions.doInjectErrorOnce = true; - } + const downloadResponse = await blockBlobURL.download(Aborter.none, 0, undefined, { + blobAccessConditions: { + modifiedAccessConditions: { + ifMatch: uploadResponse.eTag + } + }, + maxRetryRequests: 0, + progress: () => { + if (injectedErrors++ < 1) { + retirableReadableStreamOptions.doInjectErrorOnce = true; } } - ); - retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any) - .options; - await readStreamToLocalFile( - downloadResponse.readableStreamBody!, - downloadedFile - ); + }); + retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any).options; + await readStreamToLocalFile(downloadResponse.readableStreamBody!, downloadedFile); } catch (error) { expectedError = true; } @@ -586,20 +421,12 @@ describe("Highlevel", () => { }); it("bloburl.download should abort after retrys", async () => { - const uploadResponse = await uploadFileToBlockBlob( - Aborter.none, - tempFileSmall, - blockBlobURL, - { - blockSize: 4 * 1024 * 1024, - parallelism: 20 - } - ); + const uploadResponse = await uploadFileToBlockBlob(Aborter.none, tempFileSmall, blockBlobURL, { + blockSize: 4 * 1024 * 1024, + parallelism: 20 + }); - const downloadedFile = path.join( - tempFolderPath, - getUniqueName("downloadfile.") - ); + const downloadedFile = path.join(tempFolderPath, getUniqueName("downloadfile.")); let retirableReadableStreamOptions: IRetriableReadableStreamOptions; let injectedErrors = 0; @@ -607,34 +434,25 @@ describe("Highlevel", () => { try { const aborter = Aborter.none; - const downloadResponse = await blockBlobURL.download( - aborter, - 0, - undefined, - { - blobAccessConditions: { - modifiedAccessConditions: { - ifMatch: uploadResponse.eTag - } - }, - maxRetryRequests: 3, - progress: () => { - if (injectedErrors++ < 2) { - // Triger 2 times of retry - retirableReadableStreamOptions.doInjectErrorOnce = true; - } else { - // Trigger aborter - aborter.abort(); - } + const downloadResponse = await blockBlobURL.download(aborter, 0, undefined, { + blobAccessConditions: { + modifiedAccessConditions: { + ifMatch: uploadResponse.eTag + } + }, + maxRetryRequests: 3, + progress: () => { + if (injectedErrors++ < 2) { + // Triger 2 times of retry + retirableReadableStreamOptions.doInjectErrorOnce = true; + } else { + // Trigger aborter + aborter.abort(); } } - ); - retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any) - .options; - await readStreamToLocalFile( - downloadResponse.readableStreamBody!, - downloadedFile - ); + }); + retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any).options; + await readStreamToLocalFile(downloadResponse.readableStreamBody!, downloadedFile); } catch (error) { expectedError = true; } diff --git a/sdk/storage/storage-blob/test/node/pagebloburl.test.ts b/sdk/storage/storage-blob/test/node/pagebloburl.test.ts index 12b3a1d9118f..75464294e997 100644 --- a/sdk/storage/storage-blob/test/node/pagebloburl.test.ts +++ b/sdk/storage/storage-blob/test/node/pagebloburl.test.ts @@ -38,20 +38,14 @@ describe("PageBlobURL", () => { let snapshotResult = await pageBlobURL.createSnapshot(Aborter.none); assert.ok(snapshotResult.snapshot); - const destPageBlobURL = PageBlobURL.fromContainerURL( - containerURL, - getUniqueName("page") - ); + const destPageBlobURL = PageBlobURL.fromContainerURL(containerURL, getUniqueName("page")); await containerURL.setAccessPolicy(Aborter.none, "container"); await sleep(5 * 1000); let copySource = pageBlobURL.withSnapshot(snapshotResult.snapshot!).url; - let copyResponse = await destPageBlobURL.startCopyIncremental( - Aborter.none, - copySource - ); + let copyResponse = await destPageBlobURL.startCopyIncremental(Aborter.none, copySource); async function waitForCopy(retries = 0) { if (retries >= 30) { @@ -77,13 +71,9 @@ describe("PageBlobURL", () => { await waitForCopy(); - let listBlobResponse = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - include: ["copy", "snapshots"] - } - ); + let listBlobResponse = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + include: ["copy", "snapshots"] + }); assert.equal(listBlobResponse.segment.blobItems.length, 4); @@ -91,26 +81,17 @@ describe("PageBlobURL", () => { snapshotResult = await pageBlobURL.createSnapshot(Aborter.none); assert.ok(snapshotResult.snapshot); copySource = pageBlobURL.withSnapshot(snapshotResult.snapshot!).url; - copyResponse = await destPageBlobURL.startCopyIncremental( - Aborter.none, - copySource - ); + copyResponse = await destPageBlobURL.startCopyIncremental(Aborter.none, copySource); await waitForCopy(); - listBlobResponse = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - include: ["copy", "snapshots"] - } - ); + listBlobResponse = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + include: ["copy", "snapshots"] + }); assert.equal(listBlobResponse.segment.blobItems.length, 6); - const pageBlobProperties = await destPageBlobURL.getProperties( - Aborter.none - ); + const pageBlobProperties = await destPageBlobURL.getProperties(Aborter.none); assert.equal(pageBlobProperties.metadata!.sourcemeta, "val"); }); }); diff --git a/sdk/storage/storage-blob/test/pagebloburl.test.ts b/sdk/storage/storage-blob/test/pagebloburl.test.ts index 3cef7acd3d3f..9be65303de95 100644 --- a/sdk/storage/storage-blob/test/pagebloburl.test.ts +++ b/sdk/storage/storage-blob/test/pagebloburl.test.ts @@ -6,7 +6,7 @@ import { BlobURL } from "../src/BlobURL"; import { ContainerURL } from "../src/ContainerURL"; import { PageBlobURL } from "../src/PageBlobURL"; import * as dotenv from "dotenv"; -dotenv.config({path:"../.env"}); +dotenv.config({ path: "../.env" }); describe("PageBlobURL", () => { const serviceURL = getBSU(); @@ -33,10 +33,7 @@ describe("PageBlobURL", () => { await pageBlobURL.create(Aborter.none, 512); const result = await blobURL.download(Aborter.none, 0); - assert.deepStrictEqual( - await bodyToString(result, 512), - "\u0000".repeat(512) - ); + assert.deepStrictEqual(await bodyToString(result, 512), "\u0000".repeat(512)); }); it("create with all parameters set", async () => { @@ -56,32 +53,14 @@ describe("PageBlobURL", () => { await pageBlobURL.create(Aborter.none, 512, options); const result = await blobURL.download(Aborter.none, 0); - assert.deepStrictEqual( - await bodyToString(result, 512), - "\u0000".repeat(512) - ); + assert.deepStrictEqual(await bodyToString(result, 512), "\u0000".repeat(512)); const properties = await blobURL.getProperties(Aborter.none); - assert.equal( - properties.cacheControl, - options.blobHTTPHeaders.blobCacheControl - ); - assert.equal( - properties.contentDisposition, - options.blobHTTPHeaders.blobContentDisposition - ); - assert.equal( - properties.contentEncoding, - options.blobHTTPHeaders.blobContentEncoding - ); - assert.equal( - properties.contentLanguage, - options.blobHTTPHeaders.blobContentLanguage - ); - assert.equal( - properties.contentType, - options.blobHTTPHeaders.blobContentType - ); + assert.equal(properties.cacheControl, options.blobHTTPHeaders.blobCacheControl); + assert.equal(properties.contentDisposition, options.blobHTTPHeaders.blobContentDisposition); + assert.equal(properties.contentEncoding, options.blobHTTPHeaders.blobContentEncoding); + assert.equal(properties.contentLanguage, options.blobHTTPHeaders.blobContentLanguage); + assert.equal(properties.contentType, options.blobHTTPHeaders.blobContentType); assert.equal(properties.metadata!.key1, options.metadata.key1); assert.equal(properties.metadata!.key2, options.metadata.key2); }); @@ -105,10 +84,7 @@ describe("PageBlobURL", () => { it("clearPages", async () => { await pageBlobURL.create(Aborter.none, 1024); let result = await blobURL.download(Aborter.none, 0); - assert.deepStrictEqual( - await bodyToString(result, 1024), - "\u0000".repeat(1024) - ); + assert.deepStrictEqual(await bodyToString(result, 1024), "\u0000".repeat(1024)); await pageBlobURL.uploadPages(Aborter.none, "a".repeat(1024), 0, 1024); result = await pageBlobURL.download(Aborter.none, 0, 1024); @@ -116,20 +92,14 @@ describe("PageBlobURL", () => { await pageBlobURL.clearPages(Aborter.none, 0, 512); result = await pageBlobURL.download(Aborter.none, 0, 512); - assert.deepStrictEqual( - await bodyToString(result, 512), - "\u0000".repeat(512) - ); + assert.deepStrictEqual(await bodyToString(result, 512), "\u0000".repeat(512)); }); it("getPageRanges", async () => { await pageBlobURL.create(Aborter.none, 1024); const result = await blobURL.download(Aborter.none, 0); - assert.deepStrictEqual( - await bodyToString(result, 1024), - "\u0000".repeat(1024) - ); + assert.deepStrictEqual(await bodyToString(result, 1024), "\u0000".repeat(1024)); await pageBlobURL.uploadPages(Aborter.none, "a".repeat(512), 0, 512); await pageBlobURL.uploadPages(Aborter.none, "b".repeat(512), 512, 512); @@ -145,10 +115,7 @@ describe("PageBlobURL", () => { await pageBlobURL.create(Aborter.none, 1024); const result = await blobURL.download(Aborter.none, 0); - assert.deepStrictEqual( - await bodyToString(result, 1024), - "\u0000".repeat(1024) - ); + assert.deepStrictEqual(await bodyToString(result, 1024), "\u0000".repeat(1024)); await pageBlobURL.uploadPages(Aborter.none, "b".repeat(1024), 0, 1024); diff --git a/sdk/storage/storage-blob/test/retrypolicy.test.ts b/sdk/storage/storage-blob/test/retrypolicy.test.ts index 260304f43fcc..cb08c6c1252e 100644 --- a/sdk/storage/storage-blob/test/retrypolicy.test.ts +++ b/sdk/storage/storage-blob/test/retrypolicy.test.ts @@ -8,7 +8,7 @@ import { Pipeline } from "../src/Pipeline"; import { getBSU, getUniqueName } from "./utils"; import { InjectorPolicyFactory } from "./utils/InjectorPolicyFactory"; import * as dotenv from "dotenv"; -dotenv.config({path:"../.env"}); +dotenv.config({ path: "../.env" }); describe("RetryPolicy", () => { const serviceURL = getBSU(); @@ -30,11 +30,7 @@ describe("RetryPolicy", () => { const injector = new InjectorPolicyFactory(() => { if (injectCounter === 0) { injectCounter++; - return new RestError( - "Server Internal Error", - "ServerInternalError", - 500 - ); + return new RestError("Server Internal Error", "ServerInternalError", 500); } }); const factories = containerURL.pipeline.factories.slice(); // clone factories array @@ -58,10 +54,7 @@ describe("RetryPolicy", () => { return new RestError("Server Internal Error", "ServerInternalError", 500); }); - const credential = - containerURL.pipeline.factories[ - containerURL.pipeline.factories.length - 1 - ]; + const credential = containerURL.pipeline.factories[containerURL.pipeline.factories.length - 1]; const factories = StorageURL.newPipeline(credential, { retryOptions: { maxTries: 3 } }).factories; @@ -87,11 +80,7 @@ describe("RetryPolicy", () => { let injectCounter = 0; const injector = new InjectorPolicyFactory(() => { if (injectCounter++ < 1) { - return new RestError( - "Server Internal Error", - "ServerInternalError", - 500 - ); + return new RestError("Server Internal Error", "ServerInternalError", 500); } }); @@ -104,10 +93,7 @@ describe("RetryPolicy", () => { hostParts.unshift(secondaryAccount); const secondaryHost = hostParts.join("."); - const credential = - containerURL.pipeline.factories[ - containerURL.pipeline.factories.length - 1 - ]; + const credential = containerURL.pipeline.factories[containerURL.pipeline.factories.length - 1]; const factories = StorageURL.newPipeline(credential, { retryOptions: { maxTries: 2, secondaryHost } }).factories; @@ -123,9 +109,6 @@ describe("RetryPolicy", () => { finalRequestURL = err.request ? err.request.url : ""; } - assert.deepStrictEqual( - URLBuilder.parse(finalRequestURL).getHost(), - secondaryHost - ); + assert.deepStrictEqual(URLBuilder.parse(finalRequestURL).getHost(), secondaryHost); }); }); diff --git a/sdk/storage/storage-blob/test/serviceurl.test.ts b/sdk/storage/storage-blob/test/serviceurl.test.ts index cc0d6623dcf9..4646ebd71839 100644 --- a/sdk/storage/storage-blob/test/serviceurl.test.ts +++ b/sdk/storage/storage-blob/test/serviceurl.test.ts @@ -5,7 +5,7 @@ import { ContainerURL } from "../src/ContainerURL"; import { ServiceURL } from "../src/ServiceURL"; import { getAlternateBSU, getBSU, getUniqueName, wait } from "./utils"; import * as dotenv from "dotenv"; -dotenv.config({path:"../.env"}); +dotenv.config({ path: "../.env" }); describe("ServiceURL", () => { it("ListContainers with default parameters", async () => { @@ -33,26 +33,16 @@ describe("ServiceURL", () => { const containerNamePrefix = getUniqueName("container"); const containerName1 = `${containerNamePrefix}x1`; const containerName2 = `${containerNamePrefix}x2`; - const containerURL1 = ContainerURL.fromServiceURL( - serviceURL, - containerName1 - ); - const containerURL2 = ContainerURL.fromServiceURL( - serviceURL, - containerName2 - ); + const containerURL1 = ContainerURL.fromServiceURL(serviceURL, containerName1); + const containerURL2 = ContainerURL.fromServiceURL(serviceURL, containerName2); await containerURL1.create(Aborter.none, { metadata: { key: "val" } }); await containerURL2.create(Aborter.none, { metadata: { key: "val" } }); - const result1 = await serviceURL.listContainersSegment( - Aborter.none, - undefined, - { - include: "metadata", - maxresults: 1, - prefix: containerNamePrefix - } - ); + const result1 = await serviceURL.listContainersSegment(Aborter.none, undefined, { + include: "metadata", + maxresults: 1, + prefix: containerNamePrefix + }); assert.ok(result1.nextMarker); assert.equal(result1.containerItems!.length, 1); @@ -61,25 +51,15 @@ describe("ServiceURL", () => { assert.ok(result1.containerItems![0].properties.lastModified); assert.ok(!result1.containerItems![0].properties.leaseDuration); assert.ok(!result1.containerItems![0].properties.publicAccess); - assert.deepEqual( - result1.containerItems![0].properties.leaseState, - "available" - ); - assert.deepEqual( - result1.containerItems![0].properties.leaseStatus, - "unlocked" - ); + assert.deepEqual(result1.containerItems![0].properties.leaseState, "available"); + assert.deepEqual(result1.containerItems![0].properties.leaseStatus, "unlocked"); assert.deepEqual(result1.containerItems![0].metadata!.key, "val"); - const result2 = await serviceURL.listContainersSegment( - Aborter.none, - result1.nextMarker, - { - include: "metadata", - maxresults: 1, - prefix: containerNamePrefix - } - ); + const result2 = await serviceURL.listContainersSegment(Aborter.none, result1.nextMarker, { + include: "metadata", + maxresults: 1, + prefix: containerNamePrefix + }); assert.ok(!result2.nextMarker); assert.equal(result2.containerItems!.length, 1); @@ -88,14 +68,8 @@ describe("ServiceURL", () => { assert.ok(result2.containerItems![0].properties.lastModified); assert.ok(!result2.containerItems![0].properties.leaseDuration); assert.ok(!result2.containerItems![0].properties.publicAccess); - assert.deepEqual( - result2.containerItems![0].properties.leaseState, - "available" - ); - assert.deepEqual( - result2.containerItems![0].properties.leaseStatus, - "unlocked" - ); + assert.deepEqual(result2.containerItems![0].properties.leaseState, "available"); + assert.deepEqual(result2.containerItems![0].properties.leaseStatus, "unlocked"); assert.deepEqual(result2.containerItems![0].metadata!.key, "val"); await containerURL1.delete(Aborter.none); @@ -187,7 +161,7 @@ describe("ServiceURL", () => { assert.deepEqual(result.hourMetrics, serviceProperties.hourMetrics); }); - it("getStatistics", done => { + it("getStatistics", (done) => { let serviceURL: ServiceURL | undefined; try { serviceURL = getAlternateBSU(); @@ -198,7 +172,7 @@ describe("ServiceURL", () => { serviceURL! .getStatistics(Aborter.none) - .then(result => { + .then((result) => { assert.ok(result.geoReplication!.lastSyncTime); done(); }) diff --git a/sdk/storage/storage-blob/test/specialnaming.test.ts b/sdk/storage/storage-blob/test/specialnaming.test.ts index f44444a9a557..81fa50114351 100644 --- a/sdk/storage/storage-blob/test/specialnaming.test.ts +++ b/sdk/storage/storage-blob/test/specialnaming.test.ts @@ -5,7 +5,7 @@ import { getBSU, getUniqueName } from "./utils/index"; import * as assert from "assert"; import { appendToURLPath } from "../src/utils/utils.common"; import * as dotenv from "dotenv"; -dotenv.config({path:"../.env"}); +dotenv.config({ path: "../.env" }); describe("Special Naming Tests", () => { const serviceURL = getBSU(); @@ -25,13 +25,9 @@ describe("Special Naming Tests", () => { const blockBlobURL = BlockBlobURL.fromContainerURL(containerURL, blobName); await blockBlobURL.upload(Aborter.none, "A", 1); - const response = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - prefix: blobName - } - ); + const response = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + prefix: blobName + }); assert.notDeepEqual(response.segment.blobItems.length, 0); }); @@ -43,13 +39,9 @@ describe("Special Naming Tests", () => { ); await blockBlobURL.upload(Aborter.none, "A", 1); - const response = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - prefix: blobName - } - ); + const response = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + prefix: blobName + }); assert.notDeepEqual(response.segment.blobItems.length, 0); }); @@ -59,13 +51,9 @@ describe("Special Naming Tests", () => { await blockBlobURL.upload(Aborter.none, "A", 1); await blockBlobURL.getProperties(Aborter.none); - const response = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - prefix: blobName - } - ); + const response = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + prefix: blobName + }); assert.notDeepEqual(response.segment.blobItems.length, 0); }); @@ -78,13 +66,9 @@ describe("Special Naming Tests", () => { await blockBlobURL.upload(Aborter.none, "A", 1); await blockBlobURL.getProperties(Aborter.none); - const response = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - prefix: blobName - } - ); + const response = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + prefix: blobName + }); assert.notDeepEqual(response.segment.blobItems.length, 0); }); @@ -94,13 +78,9 @@ describe("Special Naming Tests", () => { await blockBlobURL.upload(Aborter.none, "A", 1); await blockBlobURL.getProperties(Aborter.none); - const response = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - prefix: blobName - } - ); + const response = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + prefix: blobName + }); assert.notDeepEqual(response.segment.blobItems.length, 0); }); @@ -113,38 +93,26 @@ describe("Special Naming Tests", () => { await blockBlobURL.upload(Aborter.none, "A", 1); await blockBlobURL.getProperties(Aborter.none); - const response = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - prefix: blobName - } - ); + const response = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + prefix: blobName + }); assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob names Chinese characters", async () => { - const blobName: string = getUniqueName( - "////Upper/blob/empty /another 汉字" - ); + const blobName: string = getUniqueName("////Upper/blob/empty /another 汉字"); const blockBlobURL = BlockBlobURL.fromContainerURL(containerURL, blobName); await blockBlobURL.upload(Aborter.none, "A", 1); await blockBlobURL.getProperties(Aborter.none); - const response = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - prefix: blobName - } - ); + const response = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + prefix: blobName + }); assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob names Chinese characters in URL string", async () => { - const blobName: string = getUniqueName( - "////Upper/blob/empty /another 汉字" - ); + const blobName: string = getUniqueName("////Upper/blob/empty /another 汉字"); const blockBlobURL = new BlockBlobURL( appendToURLPath(containerURL.url, blobName), containerURL.pipeline @@ -152,13 +120,9 @@ describe("Special Naming Tests", () => { await blockBlobURL.upload(Aborter.none, "A", 1); await blockBlobURL.getProperties(Aborter.none); - const response = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - prefix: blobName - } - ); + const response = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + prefix: blobName + }); assert.notDeepEqual(response.segment.blobItems.length, 0); }); @@ -170,14 +134,10 @@ describe("Special Naming Tests", () => { await blockBlobURL.upload(Aborter.none, "A", 1); await blockBlobURL.getProperties(Aborter.none); - const response = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - // NOTICE: Azure Storage Server will replace "\" with "/" in the blob names - prefix: blobName.replace(/\\/g, "/") - } - ); + const response = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + // NOTICE: Azure Storage Server will replace "\" with "/" in the blob names + prefix: blobName.replace(/\\/g, "/") + }); assert.notDeepEqual(response.segment.blobItems.length, 0); }); @@ -189,43 +149,29 @@ describe("Special Naming Tests", () => { // There are 2 special cases for a URL string: // Escape "%" when creating XXXURL object with URL strings // Escape "?" otherwise string after "?" will be treated as URL parameters - appendToURLPath( - containerURL.url, - blobName.replace(/%/g, "%25").replace(/\?/g, "%3F") - ), + appendToURLPath(containerURL.url, blobName.replace(/%/g, "%25").replace(/\?/g, "%3F")), containerURL.pipeline ); await blockBlobURL.upload(Aborter.none, "A", 1); await blockBlobURL.getProperties(Aborter.none); - const response = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - // NOTICE: Azure Storage Server will replace "\" with "/" in the blob names - prefix: blobName.replace(/\\/g, "/") - } - ); + const response = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + // NOTICE: Azure Storage Server will replace "\" with "/" in the blob names + prefix: blobName.replace(/\\/g, "/") + }); assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name Russian URI encoded", async () => { const blobName: string = getUniqueName("ру́сский язы́к"); const blobNameEncoded: string = encodeURIComponent(blobName); - const blockBlobURL = BlockBlobURL.fromContainerURL( - containerURL, - blobNameEncoded - ); + const blockBlobURL = BlockBlobURL.fromContainerURL(containerURL, blobNameEncoded); await blockBlobURL.upload(Aborter.none, "A", 1); await blockBlobURL.getProperties(Aborter.none); - const response = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - prefix: blobNameEncoded - } - ); + const response = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + prefix: blobNameEncoded + }); assert.notDeepEqual(response.segment.blobItems.length, 0); }); @@ -235,13 +181,9 @@ describe("Special Naming Tests", () => { await blockBlobURL.upload(Aborter.none, "A", 1); await blockBlobURL.getProperties(Aborter.none); - const response = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - prefix: blobName - } - ); + const response = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + prefix: blobName + }); assert.notDeepEqual(response.segment.blobItems.length, 0); }); @@ -254,33 +196,22 @@ describe("Special Naming Tests", () => { await blockBlobURL.upload(Aborter.none, "A", 1); await blockBlobURL.getProperties(Aborter.none); - const response = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - prefix: blobName - } - ); + const response = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + prefix: blobName + }); assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name Arabic URI encoded", async () => { const blobName: string = getUniqueName("عربي/عربى"); const blobNameEncoded: string = encodeURIComponent(blobName); - const blockBlobURL = BlockBlobURL.fromContainerURL( - containerURL, - blobNameEncoded - ); + const blockBlobURL = BlockBlobURL.fromContainerURL(containerURL, blobNameEncoded); await blockBlobURL.upload(Aborter.none, "A", 1); await blockBlobURL.getProperties(Aborter.none); - const response = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - prefix: blobNameEncoded - } - ); + const response = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + prefix: blobNameEncoded + }); assert.notDeepEqual(response.segment.blobItems.length, 0); }); @@ -290,13 +221,9 @@ describe("Special Naming Tests", () => { await blockBlobURL.upload(Aborter.none, "A", 1); await blockBlobURL.getProperties(Aborter.none); - const response = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - prefix: blobName - } - ); + const response = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + prefix: blobName + }); assert.notDeepEqual(response.segment.blobItems.length, 0); }); @@ -309,33 +236,22 @@ describe("Special Naming Tests", () => { await blockBlobURL.upload(Aborter.none, "A", 1); await blockBlobURL.getProperties(Aborter.none); - const response = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - prefix: blobName - } - ); + const response = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + prefix: blobName + }); assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name Japanese URI encoded", async () => { const blobName: string = getUniqueName("にっぽんご/にほんご"); const blobNameEncoded: string = encodeURIComponent(blobName); - const blockBlobURL = BlockBlobURL.fromContainerURL( - containerURL, - blobNameEncoded - ); + const blockBlobURL = BlockBlobURL.fromContainerURL(containerURL, blobNameEncoded); await blockBlobURL.upload(Aborter.none, "A", 1); await blockBlobURL.getProperties(Aborter.none); - const response = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - prefix: blobNameEncoded - } - ); + const response = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + prefix: blobNameEncoded + }); assert.notDeepEqual(response.segment.blobItems.length, 0); }); @@ -345,13 +261,9 @@ describe("Special Naming Tests", () => { await blockBlobURL.upload(Aborter.none, "A", 1); await blockBlobURL.getProperties(Aborter.none); - const response = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - prefix: blobName - } - ); + const response = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + prefix: blobName + }); assert.notDeepEqual(response.segment.blobItems.length, 0); }); @@ -364,13 +276,9 @@ describe("Special Naming Tests", () => { await blockBlobURL.upload(Aborter.none, "A", 1); await blockBlobURL.getProperties(Aborter.none); - const response = await containerURL.listBlobFlatSegment( - Aborter.none, - undefined, - { - prefix: blobName - } - ); + const response = await containerURL.listBlobFlatSegment(Aborter.none, undefined, { + prefix: blobName + }); assert.notDeepEqual(response.segment.blobItems.length, 0); }); }); diff --git a/sdk/storage/storage-blob/test/utils/InjectorPolicy.ts b/sdk/storage/storage-blob/test/utils/InjectorPolicy.ts index 87dcc133dcf9..3d41732dcddb 100644 --- a/sdk/storage/storage-blob/test/utils/InjectorPolicy.ts +++ b/sdk/storage/storage-blob/test/utils/InjectorPolicy.ts @@ -27,11 +27,7 @@ export class InjectorPolicy extends BaseRequestPolicy { * @param {RequestPolicyOptions} options * @memberof InjectorPolicy */ - public constructor( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions, - injector: Injector - ) { + public constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, injector: Injector) { super(nextPolicy, options); this.injector = injector; } @@ -43,9 +39,7 @@ export class InjectorPolicy extends BaseRequestPolicy { * @returns {Promise} * @memberof InjectorPolicy */ - public async sendRequest( - request: WebResource - ): Promise { + public async sendRequest(request: WebResource): Promise { const error = this.injector(); if (error) { throw error; diff --git a/sdk/storage/storage-blob/test/utils/InjectorPolicyFactory.ts b/sdk/storage/storage-blob/test/utils/InjectorPolicyFactory.ts index c1f478b9b226..ebd5412e76d5 100644 --- a/sdk/storage/storage-blob/test/utils/InjectorPolicyFactory.ts +++ b/sdk/storage/storage-blob/test/utils/InjectorPolicyFactory.ts @@ -1,8 +1,4 @@ -import { - RequestPolicy, - RequestPolicyFactory, - RequestPolicyOptions -} from "../../src"; +import { RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "../../src"; import { InjectorPolicy, Injector } from "./InjectorPolicy"; /** @@ -19,10 +15,7 @@ export class InjectorPolicyFactory implements RequestPolicyFactory { this.injector = injector; } - public create( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions - ): InjectorPolicy { + public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): InjectorPolicy { return new InjectorPolicy(nextPolicy, options, this.injector); } } diff --git a/sdk/storage/storage-blob/test/utils/index.browser.ts b/sdk/storage/storage-blob/test/utils/index.browser.ts index 00ee2b84d2c2..295c36993a0c 100644 --- a/sdk/storage/storage-blob/test/utils/index.browser.ts +++ b/sdk/storage/storage-blob/test/utils/index.browser.ts @@ -4,10 +4,7 @@ import { StorageURL } from "../../src/StorageURL"; export * from "./testutils.common"; -export function getGenericBSU( - accountType: string, - accountNameSuffix: string = "" -): ServiceURL { +export function getGenericBSU(accountType: string, accountNameSuffix: string = ""): ServiceURL { const accountNameEnvVar = `${accountType}ACCOUNT_NAME`; const accountSASEnvVar = `${accountType}ACCOUNT_SAS`; @@ -84,10 +81,7 @@ export async function blobToArrayBuffer(blob: Blob): Promise { }); } -export function arrayBufferEqual( - buf1: ArrayBuffer, - buf2: ArrayBuffer -): boolean { +export function arrayBufferEqual(buf1: ArrayBuffer, buf2: ArrayBuffer): boolean { if (buf1.byteLength !== buf2.byteLength) { return false; } diff --git a/sdk/storage/storage-blob/test/utils/index.ts b/sdk/storage/storage-blob/test/utils/index.ts index 10de427fdd45..69ed28382461 100644 --- a/sdk/storage/storage-blob/test/utils/index.ts +++ b/sdk/storage/storage-blob/test/utils/index.ts @@ -9,10 +9,7 @@ import { getUniqueName } from "./testutils.common"; export * from "./testutils.common"; -export function getGenericBSU( - accountType: string, - accountNameSuffix: string = "" -): ServiceURL { +export function getGenericBSU(accountType: string, accountNameSuffix: string = ""): ServiceURL { const accountNameEnvVar = `${accountType}ACCOUNT_NAME`; const accountKeyEnvVar = `${accountType}ACCOUNT_KEY`; @@ -112,10 +109,7 @@ export async function createRandomLocalFile( // Returns a Promise which is completed after the file handle is closed. // If Promise is rejected, the reason will be set to the first error raised by either the // ReadableStream or the fs.WriteStream. -export async function readStreamToLocalFile( - rs: NodeJS.ReadableStream, - file: string -) { +export async function readStreamToLocalFile(rs: NodeJS.ReadableStream, file: string) { return new Promise((resolve, reject) => { const ws = fs.createWriteStream(file); @@ -131,10 +125,10 @@ export async function readStreamToLocalFile( ws.on("error", () => console.log("ws.error")); ws.on("finish", () => console.log("ws.finish")); ws.on("pipe", () => console.log("ws.pipe")); - ws.on("unpipe", () => console.log("ws.unpipe")); + ws.on("unpipe", () => console.log("ws.unpipe")); } - let error : Error; + let error: Error; rs.on("error", (err: Error) => { // First error wins diff --git a/sdk/storage/storage-blob/test/utils/testutils.common.ts b/sdk/storage/storage-blob/test/utils/testutils.common.ts index 4ec999c08633..de4d969696c9 100644 --- a/sdk/storage/storage-blob/test/utils/testutils.common.ts +++ b/sdk/storage/storage-blob/test/utils/testutils.common.ts @@ -14,7 +14,7 @@ export function getUniqueName(prefix: string): string { } export async function sleep(time: number): Promise { - return new Promise(resolve => { + return new Promise((resolve) => { setTimeout(resolve, time); }); } @@ -24,17 +24,13 @@ export function base64encode(content: string): string { } export function base64decode(encodedString: string): string { - return isBrowser() - ? atob(encodedString) - : Buffer.from(encodedString, "base64").toString(); + return isBrowser() ? atob(encodedString) : Buffer.from(encodedString, "base64").toString(); } export class ConsoleHttpPipelineLogger implements IHttpPipelineLogger { constructor(public minimumLogLevel: HttpPipelineLogLevel) {} public log(logLevel: HttpPipelineLogLevel, message: string): void { - const logMessage = `${new Date().toISOString()} ${ - HttpPipelineLogLevel[logLevel] - }: ${message}`; + const logMessage = `${new Date().toISOString()} ${HttpPipelineLogLevel[logLevel]}: ${message}`; switch (logLevel) { case HttpPipelineLogLevel.ERROR: // tslint:disable-next-line:no-console @@ -53,7 +49,7 @@ export class ConsoleHttpPipelineLogger implements IHttpPipelineLogger { } export async function wait(time: number): Promise { - return new Promise(resolve => { + return new Promise((resolve) => { setTimeout(resolve, time); }); } diff --git a/sdk/storage/storage-blob/tsconfig.json b/sdk/storage/storage-blob/tsconfig.json index 61885eb2e18c..e271ee388662 100644 --- a/sdk/storage/storage-blob/tsconfig.json +++ b/sdk/storage/storage-blob/tsconfig.json @@ -22,4 +22,4 @@ "compileOnSave": true, "exclude": ["node_modules", "./samples/*"], "include": ["./src/**/*.ts", "./test/**/*.ts"] -} \ No newline at end of file +} diff --git a/sdk/storage/storage-file/.prettierignore b/sdk/storage/storage-file/.prettierignore new file mode 100644 index 000000000000..3fd7f651ed5f --- /dev/null +++ b/sdk/storage/storage-file/.prettierignore @@ -0,0 +1,2 @@ +src/generated/**/*.ts +package-lock.json diff --git a/sdk/storage/storage-file/.prettierrc.json b/sdk/storage/storage-file/.prettierrc.json deleted file mode 100644 index 1ca87ab7d8af..000000000000 --- a/sdk/storage/storage-file/.prettierrc.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "singleQuote": false -} diff --git a/sdk/storage/storage-file/gulpfile.js b/sdk/storage/storage-file/gulpfile.js index 340cdcd3418d..5587922cff17 100644 --- a/sdk/storage/storage-file/gulpfile.js +++ b/sdk/storage/storage-file/gulpfile.js @@ -6,11 +6,7 @@ const zipFileName = `azurestoragejs.file-${version}.zip`; gulp.task("zip", function(callback) { gulp - .src([ - "browser/azure-storage.file.js", - "browser/azure-storage.file.min.js", - "browser/*.txt" - ]) + .src(["browser/azure-storage.file.js", "browser/azure-storage.file.min.js", "browser/*.txt"]) .pipe(zip(zipFileName)) .pipe(gulp.dest("browser")) .on("end", callback); diff --git a/sdk/storage/storage-file/karma.conf.js b/sdk/storage/storage-file/karma.conf.js index bf041dcb0346..77093d5f6b7b 100644 --- a/sdk/storage/storage-file/karma.conf.js +++ b/sdk/storage/storage-file/karma.conf.js @@ -1,6 +1,6 @@ // https://github.com/karma-runner/karma-chrome-launcher process.env.CHROME_BIN = require("puppeteer").executablePath(); -require("dotenv").config({path:"../.env"}); +require("dotenv").config({ path: "../.env" }); module.exports = function(config) { config.set({ diff --git a/sdk/storage/storage-file/package.json b/sdk/storage/storage-file/package.json index bf40db7dc60b..cbb73a69ce11 100644 --- a/sdk/storage/storage-file/package.json +++ b/sdk/storage/storage-file/package.json @@ -73,10 +73,10 @@ "build:nodebrowser": "rollup -c 2>&1", "build:test": "npm run build:es6 && rollup -c rollup.test.config.js 2>&1", "build": "npm run build:es6 && npm run build:nodebrowser && npm run build:browserzip", - "check-format": "prettier --list-different --config .prettierrc.json \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", + "check-format": "prettier --list-different --config ../../.prettierrc.json \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", "clean": "rimraf dist dist-esm dist-test typings temp browser/*.js* browser/*.zip statistics.html coverage coverage-browser .nyc_output *.tgz *.log test*.xml TEST*.xml", "extract-api": "tsc -p . && api-extractor run --local", - "format": "prettier --write --config .prettierrc.json \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", + "format": "prettier --write --config ../../.prettierrc.json \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", "integration-test:browser": "karma start --single-run", "integration-test:node": "cross-env TS_NODE_COMPILER_OPTIONS=\"{\\\"module\\\": \\\"commonjs\\\"}\" nyc mocha --compilers ts-node/register --require source-map-support/register --reporter mocha-multi --reporter-options spec=-,mocha-junit-reporter=- --full-trace --no-timeouts test/*.test.ts test/node/*.test.ts", "integration-test": "npm run integration-test:node && npm run integration-test:browser", diff --git a/sdk/storage/storage-file/rollup.config.js b/sdk/storage/storage-file/rollup.config.js index a39ef73e03bf..8e94e4f9bfcb 100644 --- a/sdk/storage/storage-file/rollup.config.js +++ b/sdk/storage/storage-file/rollup.config.js @@ -27,7 +27,7 @@ const nodeRollupConfigFactory = () => { }; }; -const browserRollupConfigFactory = isProduction => { +const browserRollupConfigFactory = (isProduction) => { const browserRollupConfig = { input: "dist-esm/src/index.browser.js", output: { @@ -57,7 +57,7 @@ const browserRollupConfigFactory = isProduction => { ` }), nodeResolve({ - mainFields: ['module', 'browser'], + mainFields: ["module", "browser"], preferBuiltins: false }), commonjs({ diff --git a/sdk/storage/storage-file/src/Aborter.ts b/sdk/storage/storage-file/src/Aborter.ts index a4f0ef07d9ad..1782949bdbaf 100644 --- a/sdk/storage/storage-file/src/Aborter.ts +++ b/sdk/storage/storage-file/src/Aborter.ts @@ -83,16 +83,14 @@ export class Aborter implements AbortSignalLike { * * @memberof Aborter */ - public onabort?: ((ev?: Event) => any); + public onabort?: (ev?: Event) => any; // tslint:disable-next-line:variable-name private _aborted: boolean = false; private timer?: any; private readonly parent?: Aborter; private readonly children: Aborter[] = []; // When child object calls dispose(), remove child from here - private readonly abortEventListeners: Array< - (this: AbortSignalLike, ev?: any) => any - > = []; + private readonly abortEventListeners: Array<(this: AbortSignalLike, ev?: any) => any> = []; // Pipeline proxies need to use "abortSignal as Aborter" in order to access non AbortSignalLike methods // immutable primitive types private readonly key?: string; @@ -164,10 +162,7 @@ export class Aborter implements AbortSignalLike { * @returns {Aborter} * @memberof Aborter */ - public withValue( - key: string, - value?: string | number | boolean | null - ): Aborter { + public withValue(key: string, value?: string | number | boolean | null): Aborter { const childCancelContext = new Aborter(this, 0, key, value); this.children.push(childCancelContext); return childCancelContext; @@ -184,11 +179,7 @@ export class Aborter implements AbortSignalLike { * @memberof Aborter */ public getValue(key: string): string | number | boolean | null | undefined { - for ( - let parent: Aborter | undefined = this; - parent; - parent = parent.parent - ) { + for (let parent: Aborter | undefined = this; parent; parent = parent.parent) { if (parent.key === key) { return parent.value; } @@ -216,11 +207,11 @@ export class Aborter implements AbortSignalLike { this.onabort.call(this); } - this.abortEventListeners.forEach(listener => { + this.abortEventListeners.forEach((listener) => { listener.call(this); }); - this.children.forEach(child => child.cancelByParent()); + this.children.forEach((child) => child.cancelByParent()); this._aborted = true; } diff --git a/sdk/storage/storage-file/src/BrowserPolicyFactory.ts b/sdk/storage/storage-file/src/BrowserPolicyFactory.ts index 095475fb00ce..786d6d8e8137 100644 --- a/sdk/storage/storage-file/src/BrowserPolicyFactory.ts +++ b/sdk/storage/storage-file/src/BrowserPolicyFactory.ts @@ -1,8 +1,4 @@ -import { - RequestPolicy, - RequestPolicyFactory, - RequestPolicyOptions -} from "@azure/ms-rest-js"; +import { RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "@azure/ms-rest-js"; import { BrowserPolicy } from "./policies/BrowserPolicy"; @@ -14,10 +10,7 @@ import { BrowserPolicy } from "./policies/BrowserPolicy"; * @implements {RequestPolicyFactory} */ export class BrowserPolicyFactory implements RequestPolicyFactory { - public create( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions - ): BrowserPolicy { + public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): BrowserPolicy { return new BrowserPolicy(nextPolicy, options); } } diff --git a/sdk/storage/storage-file/src/DirectoryURL.ts b/sdk/storage/storage-file/src/DirectoryURL.ts index 3e43d601ee0e..160b257c5073 100644 --- a/sdk/storage/storage-file/src/DirectoryURL.ts +++ b/sdk/storage/storage-file/src/DirectoryURL.ts @@ -53,10 +53,7 @@ export class DirectoryURL extends StorageURL { * @param shareURL A ShareURL object * @param directoryName A directory name */ - public static fromShareURL( - shareURL: ShareURL, - directoryName: string - ): DirectoryURL { + public static fromShareURL(shareURL: ShareURL, directoryName: string): DirectoryURL { return new DirectoryURL( appendToURLPath(shareURL.url, encodeURIComponent(directoryName)), shareURL.pipeline @@ -69,10 +66,7 @@ export class DirectoryURL extends StorageURL { * @param directoryURL A DirectoryURL object * @param directoryName A subdirectory name */ - public static fromDirectoryURL( - directoryURL: DirectoryURL, - directoryName: string - ): DirectoryURL { + public static fromDirectoryURL(directoryURL: DirectoryURL, directoryName: string): DirectoryURL { return new DirectoryURL( appendToURLPath(directoryURL.url, encodeURIComponent(directoryName)), directoryURL.pipeline @@ -151,9 +145,7 @@ export class DirectoryURL extends StorageURL { * @returns {Promise} * @memberof DirectoryURL */ - public async getProperties( - aborter: Aborter - ): Promise { + public async getProperties(aborter: Aborter): Promise { return this.context.getProperties({ abortSignal: aborter }); @@ -169,9 +161,7 @@ export class DirectoryURL extends StorageURL { * @returns {Promise} * @memberof DirectoryURL */ - public async delete( - aborter: Aborter - ): Promise { + public async delete(aborter: Aborter): Promise { return this.context.deleteMethod({ abortSignal: aborter }); diff --git a/sdk/storage/storage-file/src/FileURL.ts b/sdk/storage/storage-file/src/FileURL.ts index eac2d380ff70..a98a1d4ff658 100644 --- a/sdk/storage/storage-file/src/FileURL.ts +++ b/sdk/storage/storage-file/src/FileURL.ts @@ -1,9 +1,4 @@ -import { - HttpRequestBody, - HttpResponse, - isNode, - TransferProgressEvent -} from "@azure/ms-rest-js"; +import { HttpRequestBody, HttpResponse, isNode, TransferProgressEvent } from "@azure/ms-rest-js"; import { Aborter } from "./Aborter"; import { DirectoryURL } from "./DirectoryURL"; import { FileDownloadResponse } from "./FileDownloadResponse"; @@ -264,9 +259,7 @@ export class FileURL extends StorageURL { options: IFileDownloadOptions = {} ): Promise { if (options.rangeGetContentMD5 && offset === 0 && count === undefined) { - throw new RangeError( - `rangeGetContentMD5 only works with partial data downloading` - ); + throw new RangeError(`rangeGetContentMD5 only works with partial data downloading`); } const downloadFullFile = offset === 0 && !count; @@ -287,18 +280,13 @@ export class FileURL extends StorageURL { // bundlers may try to bundle following code and "FileReadResponse.ts". // In this case, "FileDownloadResponse.browser.ts" will be used as a shim of "FileDownloadResponse.ts" // The config is in package.json "browser" field - if ( - options.maxRetryRequests === undefined || - options.maxRetryRequests < 0 - ) { + if (options.maxRetryRequests === undefined || options.maxRetryRequests < 0) { // TODO: Default value or make it a required parameter? options.maxRetryRequests = DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS; } if (res.contentLength === undefined) { - throw new RangeError( - `File download response doesn't contain valid content length header` - ); + throw new RangeError(`File download response doesn't contain valid content length header`); } return new FileDownloadResponse( @@ -343,9 +331,7 @@ export class FileURL extends StorageURL { * @returns {Promise} * @memberof FileURL */ - public async getProperties( - aborter: Aborter - ): Promise { + public async getProperties(aborter: Aborter): Promise { return this.context.getProperties({ abortSignal: aborter }); @@ -476,9 +462,7 @@ export class FileURL extends StorageURL { } if (contentLength > FILE_RANGE_MAX_SIZE_BYTES) { - throw new RangeError( - `offset must be < ${FILE_RANGE_MAX_SIZE_BYTES} bytes` - ); + throw new RangeError(`offset must be < ${FILE_RANGE_MAX_SIZE_BYTES} bytes`); } return this.context.uploadRange( @@ -514,14 +498,9 @@ export class FileURL extends StorageURL { throw new RangeError(`offset must >= 0 and contentLength must be > 0`); } - return this.context.uploadRange( - rangeToString({ count: contentLength, offset }), - "clear", - 0, - { - abortSignal: aborter - } - ); + return this.context.uploadRange(rangeToString({ count: contentLength, offset }), "clear", 0, { + abortSignal: aborter + }); } /** diff --git a/sdk/storage/storage-file/src/IAccountSASSignatureValues.ts b/sdk/storage/storage-file/src/IAccountSASSignatureValues.ts index 5d446c1aa3a5..8e440b0a1341 100644 --- a/sdk/storage/storage-file/src/IAccountSASSignatureValues.ts +++ b/sdk/storage/storage-file/src/IAccountSASSignatureValues.ts @@ -117,9 +117,7 @@ export function generateAccountSASQueryParameters( const parsedPermissions = AccountSASPermissions.parse( accountSASSignatureValues.permissions ).toString(); - const parsedServices = AccountSASServices.parse( - accountSASSignatureValues.services - ).toString(); + const parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString(); const parsedResourceTypes = AccountSASResourceTypes.parse( accountSASSignatureValues.resourceTypes ).toString(); @@ -133,12 +131,8 @@ export function generateAccountSASQueryParameters( ? truncatedISO8061Date(accountSASSignatureValues.startTime, false) : "", truncatedISO8061Date(accountSASSignatureValues.expiryTime, false), - accountSASSignatureValues.ipRange - ? ipRangeToString(accountSASSignatureValues.ipRange) - : "", - accountSASSignatureValues.protocol - ? accountSASSignatureValues.protocol - : "", + accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", + accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", version, "" // Account SAS requires an additional newline character ].join("\n"); diff --git a/sdk/storage/storage-file/src/IFileSASSignatureValues.ts b/sdk/storage/storage-file/src/IFileSASSignatureValues.ts index 05ca0c66f659..68254b24f022 100644 --- a/sdk/storage/storage-file/src/IFileSASSignatureValues.ts +++ b/sdk/storage/storage-file/src/IFileSASSignatureValues.ts @@ -164,18 +164,14 @@ export function generateFileSASQueryParameters( ); } - const version = fileSASSignatureValues.version - ? fileSASSignatureValues.version - : SERVICE_VERSION; + const version = fileSASSignatureValues.version ? fileSASSignatureValues.version : SERVICE_VERSION; let resource: string = "s"; let verifiedPermissions: string | undefined; // Calling parse and toString guarantees the proper ordering and throws on invalid characters. if (fileSASSignatureValues.permissions) { if (fileSASSignatureValues.filePath) { - verifiedPermissions = FileSASPermissions.parse( - fileSASSignatureValues.permissions - ).toString(); + verifiedPermissions = FileSASPermissions.parse(fileSASSignatureValues.permissions).toString(); resource = "f"; } else { verifiedPermissions = ShareSASPermissions.parse( @@ -199,9 +195,7 @@ export function generateFileSASQueryParameters( fileSASSignatureValues.filePath ), fileSASSignatureValues.identifier, - fileSASSignatureValues.ipRange - ? ipRangeToString(fileSASSignatureValues.ipRange) - : "", + fileSASSignatureValues.ipRange ? ipRangeToString(fileSASSignatureValues.ipRange) : "", fileSASSignatureValues.protocol, version, fileSASSignatureValues.cacheControl, @@ -233,11 +227,7 @@ export function generateFileSASQueryParameters( ); } -function getCanonicalName( - accountName: string, - shareName: string, - filePath?: string -): string { +function getCanonicalName(accountName: string, shareName: string, filePath?: string): string { // Share: "/file/account/sharename" // File: "/file/account/sharename/filename" // File: "/file/account/sharename/directoryname/filename" diff --git a/sdk/storage/storage-file/src/LoggingPolicyFactory.ts b/sdk/storage/storage-file/src/LoggingPolicyFactory.ts index 29b9081d157d..d6f1057480b4 100644 --- a/sdk/storage/storage-file/src/LoggingPolicyFactory.ts +++ b/sdk/storage/storage-file/src/LoggingPolicyFactory.ts @@ -1,8 +1,4 @@ -import { - RequestPolicy, - RequestPolicyFactory, - RequestPolicyOptions -} from "@azure/ms-rest-js"; +import { RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "@azure/ms-rest-js"; import { LoggingPolicy } from "./policies/LoggingPolicy"; @@ -36,10 +32,7 @@ export class LoggingPolicyFactory implements RequestPolicyFactory { this.loggingOptions = loggingOptions; } - public create( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions - ): LoggingPolicy { + public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): LoggingPolicy { return new LoggingPolicy(nextPolicy, options, this.loggingOptions); } } diff --git a/sdk/storage/storage-file/src/Pipeline.ts b/sdk/storage/storage-file/src/Pipeline.ts index fd3af1c23ed5..01c05b7a8ec7 100644 --- a/sdk/storage/storage-file/src/Pipeline.ts +++ b/sdk/storage/storage-file/src/Pipeline.ts @@ -61,10 +61,7 @@ export class Pipeline { * @param {IPipelineOptions} [options={}] * @memberof Pipeline */ - constructor( - factories: RequestPolicyFactory[], - options: IPipelineOptions = {} - ) { + constructor(factories: RequestPolicyFactory[], options: IPipelineOptions = {}) { this.factories = factories; this.options = options; } diff --git a/sdk/storage/storage-file/src/RetryPolicyFactory.ts b/sdk/storage/storage-file/src/RetryPolicyFactory.ts index 21c14949e995..64b9b7d7c1f1 100644 --- a/sdk/storage/storage-file/src/RetryPolicyFactory.ts +++ b/sdk/storage/storage-file/src/RetryPolicyFactory.ts @@ -1,8 +1,4 @@ -import { - RequestPolicy, - RequestPolicyFactory, - RequestPolicyOptions -} from "@azure/ms-rest-js"; +import { RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "@azure/ms-rest-js"; import { RetryPolicy, RetryPolicyType } from "./policies/RetryPolicy"; @@ -84,10 +80,7 @@ export class RetryPolicyFactory implements RequestPolicyFactory { this.retryOptions = retryOptions; } - public create( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions - ): RetryPolicy { + public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): RetryPolicy { return new RetryPolicy(nextPolicy, options, this.retryOptions); } } diff --git a/sdk/storage/storage-file/src/SASQueryParameters.ts b/sdk/storage/storage-file/src/SASQueryParameters.ts index 2320a0b96319..c116438b9050 100644 --- a/sdk/storage/storage-file/src/SASQueryParameters.ts +++ b/sdk/storage/storage-file/src/SASQueryParameters.ts @@ -286,18 +286,14 @@ export class SASQueryParameters { this.tryAppendQueryParameter( queries, param, - this.startTime - ? truncatedISO8061Date(this.startTime, false) - : undefined + this.startTime ? truncatedISO8061Date(this.startTime, false) : undefined ); break; case "se": this.tryAppendQueryParameter( queries, param, - this.expiryTime - ? truncatedISO8061Date(this.expiryTime, false) - : undefined + this.expiryTime ? truncatedISO8061Date(this.expiryTime, false) : undefined ); break; case "sip": @@ -349,11 +345,7 @@ export class SASQueryParameters { * @returns {void} * @memberof SASQueryParameters */ - private tryAppendQueryParameter( - queries: string[], - key: string, - value?: string - ): void { + private tryAppendQueryParameter(queries: string[], key: string, value?: string): void { if (!value) { return; } diff --git a/sdk/storage/storage-file/src/ServiceURL.ts b/sdk/storage/storage-file/src/ServiceURL.ts index a9974a08b121..6b270adc24d8 100644 --- a/sdk/storage/storage-file/src/ServiceURL.ts +++ b/sdk/storage/storage-file/src/ServiceURL.ts @@ -89,9 +89,7 @@ export class ServiceURL extends StorageURL { * @returns {Promise} * @memberof ServiceURL */ - public async getProperties( - aborter: Aborter - ): Promise { + public async getProperties(aborter: Aborter): Promise { return this.serviceContext.getProperties({ abortSignal: aborter }); diff --git a/sdk/storage/storage-file/src/ShareURL.ts b/sdk/storage/storage-file/src/ShareURL.ts index 7e20760b71df..e5a011e0c115 100644 --- a/sdk/storage/storage-file/src/ShareURL.ts +++ b/sdk/storage/storage-file/src/ShareURL.ts @@ -8,11 +8,7 @@ import { Pipeline } from "./Pipeline"; import { ServiceURL } from "./ServiceURL"; import { StorageURL } from "./StorageURL"; import { URLConstants } from "./utils/constants"; -import { - appendToURLPath, - setURLParameter, - truncatedISO8061Date -} from "./utils/utils.common"; +import { appendToURLPath, setURLParameter, truncatedISO8061Date } from "./utils/utils.common"; export interface IShareCreateOptions { /** @@ -116,14 +112,8 @@ export class ShareURL extends StorageURL { * @param serviceURL * @param shareName */ - public static fromServiceURL( - serviceURL: ServiceURL, - shareName: string - ): ShareURL { - return new ShareURL( - appendToURLPath(serviceURL.url, shareName), - serviceURL.pipeline - ); + public static fromServiceURL(serviceURL: ServiceURL, shareName: string): ShareURL { + return new ShareURL(appendToURLPath(serviceURL.url, shareName), serviceURL.pipeline); } /** @@ -213,9 +203,7 @@ export class ShareURL extends StorageURL { * @returns {Promise} * @memberof ShareURL */ - public async getProperties( - aborter: Aborter - ): Promise { + public async getProperties(aborter: Aborter): Promise { return this.context.getProperties({ abortSignal: aborter }); @@ -279,9 +267,7 @@ export class ShareURL extends StorageURL { * @returns {Promise} * @memberof ShareURL */ - public async getAccessPolicy( - aborter: Aborter - ): Promise { + public async getAccessPolicy(aborter: Aborter): Promise { const response = await this.context.getAccessPolicy({ abortSignal: aborter }); @@ -398,9 +384,7 @@ export class ShareURL extends StorageURL { * @returns {Promise} * @memberof ShareURL */ - public async getStatistics( - aborter: Aborter - ): Promise { + public async getStatistics(aborter: Aborter): Promise { return this.context.getStatistics({ abortSignal: aborter }); diff --git a/sdk/storage/storage-file/src/StorageURL.ts b/sdk/storage/storage-file/src/StorageURL.ts index 5fae3242c2ec..fc2501d958fb 100644 --- a/sdk/storage/storage-file/src/StorageURL.ts +++ b/sdk/storage/storage-file/src/StorageURL.ts @@ -6,10 +6,7 @@ import { StorageClientContext } from "./generated/lib/storageClientContext"; import { LoggingPolicyFactory } from "./LoggingPolicyFactory"; import { IHttpClient, IHttpPipelineLogger, Pipeline } from "./Pipeline"; import { IRetryOptions, RetryPolicyFactory } from "./RetryPolicyFactory"; -import { - ITelemetryOptions, - TelemetryPolicyFactory -} from "./TelemetryPolicyFactory"; +import { ITelemetryOptions, TelemetryPolicyFactory } from "./TelemetryPolicyFactory"; import { UniqueRequestIDPolicyFactory } from "./UniqueRequestIDPolicyFactory"; import { escapeURLPath } from "./utils/utils.common"; diff --git a/sdk/storage/storage-file/src/TelemetryPolicyFactory.ts b/sdk/storage/storage-file/src/TelemetryPolicyFactory.ts index 5d53fc5a876a..a75dad719028 100644 --- a/sdk/storage/storage-file/src/TelemetryPolicyFactory.ts +++ b/sdk/storage/storage-file/src/TelemetryPolicyFactory.ts @@ -40,10 +40,7 @@ export class TelemetryPolicyFactory implements RequestPolicyFactory { if (isNode) { if (telemetry) { const telemetryString = telemetry.value; - if ( - telemetryString.length > 0 && - userAgentInfo.indexOf(telemetryString) === -1 - ) { + if (telemetryString.length > 0 && userAgentInfo.indexOf(telemetryString) === -1) { userAgentInfo.push(telemetryString); } } @@ -55,9 +52,7 @@ export class TelemetryPolicyFactory implements RequestPolicyFactory { } // e.g. (NODE-VERSION 4.9.1; Windows_NT 10.0.16299) - const runtimeInfo = `(NODE-VERSION ${ - process.version - }; ${os.type()} ${os.release()})`; + const runtimeInfo = `(NODE-VERSION ${process.version}; ${os.type()} ${os.release()})`; if (userAgentInfo.indexOf(runtimeInfo) === -1) { userAgentInfo.push(runtimeInfo); } @@ -66,10 +61,7 @@ export class TelemetryPolicyFactory implements RequestPolicyFactory { this.telemetryString = userAgentInfo.join(" "); } - public create( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions - ): TelemetryPolicy { + public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): TelemetryPolicy { return new TelemetryPolicy(nextPolicy, options, this.telemetryString); } } diff --git a/sdk/storage/storage-file/src/UniqueRequestIDPolicyFactory.ts b/sdk/storage/storage-file/src/UniqueRequestIDPolicyFactory.ts index 825c7df26edd..6610c6ff3b53 100644 --- a/sdk/storage/storage-file/src/UniqueRequestIDPolicyFactory.ts +++ b/sdk/storage/storage-file/src/UniqueRequestIDPolicyFactory.ts @@ -10,10 +10,7 @@ import { UniqueRequestIDPolicy } from "./policies/UniqueRequestIDPolicy"; * @implements {RequestPolicyFactory} */ export class UniqueRequestIDPolicyFactory implements RequestPolicyFactory { - public create( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions - ): UniqueRequestIDPolicy { + public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): UniqueRequestIDPolicy { return new UniqueRequestIDPolicy(nextPolicy, options); } } diff --git a/sdk/storage/storage-file/src/credentials/Credential.ts b/sdk/storage/storage-file/src/credentials/Credential.ts index d87d71befb84..ba47b60f6d5d 100644 --- a/sdk/storage/storage-file/src/credentials/Credential.ts +++ b/sdk/storage/storage-file/src/credentials/Credential.ts @@ -1,8 +1,4 @@ -import { - RequestPolicy, - RequestPolicyFactory, - RequestPolicyOptions -} from "@azure/ms-rest-js"; +import { RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "@azure/ms-rest-js"; import { CredentialPolicy } from "../policies/CredentialPolicy"; diff --git a/sdk/storage/storage-file/src/highlevel.browser.ts b/sdk/storage/storage-file/src/highlevel.browser.ts index 0f006e3bd72a..efaf0652e5f9 100644 --- a/sdk/storage/storage-file/src/highlevel.browser.ts +++ b/sdk/storage/storage-file/src/highlevel.browser.ts @@ -2,10 +2,7 @@ import { Aborter } from "./Aborter"; import { FileURL } from "./FileURL"; import { IUploadToAzureFileOptions } from "./highlevel.common"; import { Batch } from "./utils/Batch"; -import { - FILE_RANGE_MAX_SIZE_BYTES, - DEFAULT_HIGH_LEVEL_PARALLELISM -} from "./utils/constants"; +import { FILE_RANGE_MAX_SIZE_BYTES, DEFAULT_HIGH_LEVEL_PARALLELISM } from "./utils/constants"; /** * ONLY AVAILABLE IN BROWSERS. @@ -63,9 +60,7 @@ async function UploadSeekableBlobToAzureFile( options.rangeSize = FILE_RANGE_MAX_SIZE_BYTES; } if (options.rangeSize < 0 || options.rangeSize > FILE_RANGE_MAX_SIZE_BYTES) { - throw new RangeError( - `options.rangeSize must be > 0 and <= ${FILE_RANGE_MAX_SIZE_BYTES}` - ); + throw new RangeError(`options.rangeSize must be > 0 and <= ${FILE_RANGE_MAX_SIZE_BYTES}`); } if (!options.fileHTTPHeaders) { @@ -95,12 +90,7 @@ async function UploadSeekableBlobToAzureFile( const start = options.rangeSize! * i; const end = i === numBlocks - 1 ? size : start + options.rangeSize!; const contentLength = end - start; - await fileURL.uploadRange( - aborter, - blobFactory(start, contentLength), - start, - contentLength - ); + await fileURL.uploadRange(aborter, blobFactory(start, contentLength), start, contentLength); // Update progress after block is successfully uploaded to server, in case of block trying // TODO: Hook with convenience layer progress event in finer level transferProgress += contentLength; diff --git a/sdk/storage/storage-file/src/highlevel.node.ts b/sdk/storage/storage-file/src/highlevel.node.ts index 9679eeb76d6e..2c97e45e57db 100644 --- a/sdk/storage/storage-file/src/highlevel.node.ts +++ b/sdk/storage/storage-file/src/highlevel.node.ts @@ -3,17 +3,11 @@ import { TransferProgressEvent } from "@azure/ms-rest-js"; import { Readable } from "stream"; import { Aborter } from "./Aborter"; import { FileURL } from "./FileURL"; -import { - IDownloadFromAzureFileOptions, - IUploadToAzureFileOptions -} from "./highlevel.common"; +import { IDownloadFromAzureFileOptions, IUploadToAzureFileOptions } from "./highlevel.common"; import { IFileHTTPHeaders, IMetadata } from "./models"; import { Batch } from "./utils/Batch"; import { BufferScheduler } from "./utils/BufferScheduler"; -import { - DEFAULT_HIGH_LEVEL_PARALLELISM, - FILE_RANGE_MAX_SIZE_BYTES -} from "./utils/constants"; +import { DEFAULT_HIGH_LEVEL_PARALLELISM, FILE_RANGE_MAX_SIZE_BYTES } from "./utils/constants"; import { streamToBuffer } from "./utils/utils.node"; /** @@ -78,9 +72,7 @@ async function uploadResetableStreamToAzureFile( options.rangeSize = FILE_RANGE_MAX_SIZE_BYTES; } if (options.rangeSize < 0 || options.rangeSize > FILE_RANGE_MAX_SIZE_BYTES) { - throw new RangeError( - `options.rangeSize must be > 0 and <= ${FILE_RANGE_MAX_SIZE_BYTES}` - ); + throw new RangeError(`options.rangeSize must be > 0 and <= ${FILE_RANGE_MAX_SIZE_BYTES}`); } if (!options.fileHTTPHeaders) { @@ -194,16 +186,10 @@ export async function downloadAzureFileToBuffer( const batch = new Batch(options.parallelism); for (let off = offset; off < offset + count; off = off + options.rangeSize) { batch.addOperation(async () => { - const chunkEnd = - off + options.rangeSize! < count! ? off + options.rangeSize! : count!; - const response = await fileURL.download( - aborter, - off, - chunkEnd - off + 1, - { - maxRetryRequests: options.maxRetryRequestsPerRange - } - ); + const chunkEnd = off + options.rangeSize! < count! ? off + options.rangeSize! : count!; + const response = await fileURL.download(aborter, off, chunkEnd - off + 1, { + maxRetryRequests: options.maxRetryRequestsPerRange + }); const stream = response.readableStreamBody!; await streamToBuffer(stream, buffer, off - offset, chunkEnd - offset); // Update progress after block is downloaded, in case of block trying @@ -289,9 +275,7 @@ export async function uploadStreamToAzureFile( } if (bufferSize <= 0 || bufferSize > FILE_RANGE_MAX_SIZE_BYTES) { - throw new RangeError( - `bufferSize must be > 0 and <= ${FILE_RANGE_MAX_SIZE_BYTES}` - ); + throw new RangeError(`bufferSize must be > 0 and <= ${FILE_RANGE_MAX_SIZE_BYTES}`); } if (maxBuffers < 0) { diff --git a/sdk/storage/storage-file/src/policies/BrowserPolicy.ts b/sdk/storage/storage-file/src/policies/BrowserPolicy.ts index 054a67c29f13..da28a835c088 100644 --- a/sdk/storage/storage-file/src/policies/BrowserPolicy.ts +++ b/sdk/storage/storage-file/src/policies/BrowserPolicy.ts @@ -42,17 +42,12 @@ export class BrowserPolicy extends BaseRequestPolicy { * @returns {Promise} * @memberof BrowserPolicy */ - public async sendRequest( - request: WebResource - ): Promise { + public async sendRequest(request: WebResource): Promise { if (isNode) { return this._nextPolicy.sendRequest(request); } - if ( - request.method.toUpperCase() === "GET" || - request.method.toUpperCase() === "HEAD" - ) { + if (request.method.toUpperCase() === "GET" || request.method.toUpperCase() === "HEAD") { request.url = setURLParameter( request.url, URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, diff --git a/sdk/storage/storage-file/src/policies/CredentialPolicy.ts b/sdk/storage/storage-file/src/policies/CredentialPolicy.ts index ee09c0e002b9..9a25c8b94b2a 100644 --- a/sdk/storage/storage-file/src/policies/CredentialPolicy.ts +++ b/sdk/storage/storage-file/src/policies/CredentialPolicy.ts @@ -1,8 +1,4 @@ -import { - BaseRequestPolicy, - HttpOperationResponse, - WebResource -} from "@azure/ms-rest-js"; +import { BaseRequestPolicy, HttpOperationResponse, WebResource } from "@azure/ms-rest-js"; /** * Credential policy used to sign HTTP(S) requests before sending. This is an diff --git a/sdk/storage/storage-file/src/policies/LoggingPolicy.ts b/sdk/storage/storage-file/src/policies/LoggingPolicy.ts index 51fdb8307f64..0d1fa108a316 100644 --- a/sdk/storage/storage-file/src/policies/LoggingPolicy.ts +++ b/sdk/storage/storage-file/src/policies/LoggingPolicy.ts @@ -52,9 +52,7 @@ export class LoggingPolicy extends BaseRequestPolicy { * @returns {Promise} * @memberof LoggingPolicy */ - public async sendRequest( - request: WebResource - ): Promise { + public async sendRequest(request: WebResource): Promise { this.tryCount++; this.requestStartTime = new Date(); if (this.tryCount === 1) { @@ -63,11 +61,7 @@ export class LoggingPolicy extends BaseRequestPolicy { let safeURL: string = request.url; if (getURLParameter(safeURL, URLConstants.Parameters.SIGNATURE)) { - safeURL = setURLParameter( - safeURL, - URLConstants.Parameters.SIGNATURE, - "*****" - ); + safeURL = setURLParameter(safeURL, URLConstants.Parameters.SIGNATURE, "*****"); } this.log( HttpPipelineLogLevel.INFO, @@ -78,10 +72,8 @@ export class LoggingPolicy extends BaseRequestPolicy { const response = await this._nextPolicy.sendRequest(request); const requestEndTime = new Date(); - const requestCompletionTime = - requestEndTime.getTime() - this.requestStartTime.getTime(); - const operationDuration = - requestEndTime.getTime() - this.operationStartTime.getTime(); + const requestCompletionTime = requestEndTime.getTime() - this.requestStartTime.getTime(); + const operationDuration = requestEndTime.getTime() - this.operationStartTime.getTime(); let currentLevel: HttpPipelineLogLevel = HttpPipelineLogLevel.INFO; let logMessage: string = ""; @@ -91,10 +83,7 @@ export class LoggingPolicy extends BaseRequestPolicy { } // If the response took too long, we'll upgrade to warning. - if ( - requestCompletionTime >= - this.loggingOptions.logWarningIfTryOverThreshold - ) { + if (requestCompletionTime >= this.loggingOptions.logWarningIfTryOverThreshold) { // Log a warning if the try duration exceeded the specified threshold. if (this.shouldLog(HttpPipelineLogLevel.WARNING)) { currentLevel = HttpPipelineLogLevel.WARNING; @@ -110,8 +99,7 @@ export class LoggingPolicy extends BaseRequestPolicy { (response.status !== HTTPURLConnection.HTTP_NOT_FOUND && response.status !== HTTPURLConnection.HTTP_CONFLICT && response.status !== HTTPURLConnection.HTTP_PRECON_FAILED && - response.status !== - HTTPURLConnection.HTTP_RANGE_NOT_SATISFIABLE)) || + response.status !== HTTPURLConnection.HTTP_RANGE_NOT_SATISFIABLE)) || (response.status >= 500 && response.status <= 509) ) { const errorString = `REQUEST ERROR: HTTP request failed with status code: ${ @@ -131,9 +119,7 @@ export class LoggingPolicy extends BaseRequestPolicy { } catch (err) { this.log( HttpPipelineLogLevel.ERROR, - `Unexpected failure attempting to make request. Error message: ${ - err.message - }` + `Unexpected failure attempting to make request. Error message: ${err.message}` ); throw err; } diff --git a/sdk/storage/storage-file/src/policies/RetryPolicy.ts b/sdk/storage/storage-file/src/policies/RetryPolicy.ts index a1b884b4854e..d5252cbc0a54 100644 --- a/sdk/storage/storage-file/src/policies/RetryPolicy.ts +++ b/sdk/storage/storage-file/src/policies/RetryPolicy.ts @@ -21,14 +21,9 @@ import { setURLParameter } from "../utils/utils.common"; * @param {IRetryOptions} retryOptions * @returns */ -export function NewRetryPolicyFactory( - retryOptions?: IRetryOptions -): RequestPolicyFactory { +export function NewRetryPolicyFactory(retryOptions?: IRetryOptions): RequestPolicyFactory { return { - create: ( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions - ): RetryPolicy => { + create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions): RetryPolicy => { return new RetryPolicy(nextPolicy, options, retryOptions); } }; @@ -131,9 +126,7 @@ export class RetryPolicy extends BaseRequestPolicy { * @returns {Promise} * @memberof RetryPolicy */ - public async sendRequest( - request: WebResource - ): Promise { + public async sendRequest(request: WebResource): Promise { return this.attemptSendRequest(request, false, 1); } @@ -173,17 +166,14 @@ export class RetryPolicy extends BaseRequestPolicy { try { this.logf( HttpPipelineLogLevel.INFO, - `RetryPolicy: =====> Try=${attempt} ${ - isPrimaryRetry ? "Primary" : "Secondary" - }` + `RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}` ); response = await this._nextPolicy.sendRequest(newRequest); if (!this.shouldRetry(isPrimaryRetry, attempt, response)) { return response; } - secondaryHas404 = - secondaryHas404 || (!isPrimaryRetry && response.status === 404); + secondaryHas404 = secondaryHas404 || (!isPrimaryRetry && response.status === 404); } catch (err) { this.logf( HttpPipelineLogLevel.ERROR, @@ -258,10 +248,7 @@ export class RetryPolicy extends BaseRequestPolicy { if (response || err) { const statusCode = response ? response.status : err ? err.statusCode : 0; if (!isPrimaryRetry && statusCode === 404) { - this.logf( - HttpPipelineLogLevel.INFO, - `RetryPolicy: Secondary access with 404, will retry.` - ); + this.logf(HttpPipelineLogLevel.INFO, `RetryPolicy: Secondary access with 404, will retry.`); return true; } @@ -320,10 +307,7 @@ export class RetryPolicy extends BaseRequestPolicy { delayTimeInMs = Math.random() * 1000; } - this.logf( - HttpPipelineLogLevel.INFO, - `RetryPolicy: Delay for ${delayTimeInMs}ms` - ); + this.logf(HttpPipelineLogLevel.INFO, `RetryPolicy: Delay for ${delayTimeInMs}ms`); return delay(delayTimeInMs); } } diff --git a/sdk/storage/storage-file/src/policies/SharedKeyCredentialPolicy.ts b/sdk/storage/storage-file/src/policies/SharedKeyCredentialPolicy.ts index a6ba9318a771..141a9bfcdcde 100644 --- a/sdk/storage/storage-file/src/policies/SharedKeyCredentialPolicy.ts +++ b/sdk/storage/storage-file/src/policies/SharedKeyCredentialPolicy.ts @@ -1,8 +1,4 @@ -import { - RequestPolicy, - RequestPolicyOptions, - WebResource -} from "@azure/ms-rest-js"; +import { RequestPolicy, RequestPolicyOptions, WebResource } from "@azure/ms-rest-js"; import { SharedKeyCredential } from "../credentials/SharedKeyCredential"; import { HeaderConstants } from "../utils/constants"; import { getURLPath, getURLQueries } from "../utils/utils.common"; @@ -51,15 +47,8 @@ export class SharedKeyCredentialPolicy extends CredentialPolicy { protected signRequest(request: WebResource): WebResource { request.headers.set(HeaderConstants.X_MS_DATE, new Date().toUTCString()); - if ( - request.body && - typeof request.body === "string" && - request.body.length > 0 - ) { - request.headers.set( - HeaderConstants.CONTENT_LENGTH, - Buffer.byteLength(request.body) - ); + if (request.body && typeof request.body === "string" && request.body.length > 0) { + request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); } const stringToSign: string = @@ -104,10 +93,7 @@ export class SharedKeyCredentialPolicy extends CredentialPolicy { * @returns {string} * @memberof SharedKeyCredentialPolicy */ - private getHeaderValueToSign( - request: WebResource, - headerName: string - ): string { + private getHeaderValueToSign(request: WebResource, headerName: string): string { const value = request.headers.get(headerName); if (!value) { @@ -141,10 +127,8 @@ export class SharedKeyCredentialPolicy extends CredentialPolicy { * @memberof SharedKeyCredentialPolicy */ private getCanonicalizedHeadersString(request: WebResource): string { - let headersArray = request.headers.headersArray().filter(value => { - return value.name - .toLowerCase() - .startsWith(HeaderConstants.PREFIX_FOR_STORAGE); + let headersArray = request.headers.headersArray().filter((value) => { + return value.name.toLowerCase().startsWith(HeaderConstants.PREFIX_FOR_STORAGE); }); headersArray.sort( @@ -155,17 +139,14 @@ export class SharedKeyCredentialPolicy extends CredentialPolicy { // Remove duplicate headers headersArray = headersArray.filter((value, index, array) => { - if ( - index > 0 && - value.name.toLowerCase() === array[index - 1].name.toLowerCase() - ) { + if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) { return false; } return true; }); let canonicalizedHeadersStringToSign: string = ""; - headersArray.forEach(header => { + headersArray.forEach((header) => { canonicalizedHeadersStringToSign += `${header.name .toLowerCase() .trimRight()}:${header.value.trimLeft()}\n`; @@ -202,9 +183,7 @@ export class SharedKeyCredentialPolicy extends CredentialPolicy { queryKeys.sort(); for (const key of queryKeys) { - canonicalizedResourceString += `\n${key}:${decodeURIComponent( - lowercaseQueries[key] - )}`; + canonicalizedResourceString += `\n${key}:${decodeURIComponent(lowercaseQueries[key])}`; } } diff --git a/sdk/storage/storage-file/src/policies/TelemetryPolicy.ts b/sdk/storage/storage-file/src/policies/TelemetryPolicy.ts index fedf88f4a524..cedefe68fde4 100644 --- a/sdk/storage/storage-file/src/policies/TelemetryPolicy.ts +++ b/sdk/storage/storage-file/src/policies/TelemetryPolicy.ts @@ -32,11 +32,7 @@ export class TelemetryPolicy extends BaseRequestPolicy { * @param {ITelemetryOptions} [telemetry] * @memberof TelemetryPolicy */ - constructor( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions, - telemetry: string - ) { + constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, telemetry: string) { super(nextPolicy, options); this.telemetry = telemetry; } @@ -48,9 +44,7 @@ export class TelemetryPolicy extends BaseRequestPolicy { * @returns {Promise} * @memberof TelemetryPolicy */ - public async sendRequest( - request: WebResource - ): Promise { + public async sendRequest(request: WebResource): Promise { if (isNode) { if (!request.headers) { request.headers = new HttpHeaders(); diff --git a/sdk/storage/storage-file/src/policies/UniqueRequestIDPolicy.ts b/sdk/storage/storage-file/src/policies/UniqueRequestIDPolicy.ts index b4ff96983f9c..3e4e4e9dd17b 100644 --- a/sdk/storage/storage-file/src/policies/UniqueRequestIDPolicy.ts +++ b/sdk/storage/storage-file/src/policies/UniqueRequestIDPolicy.ts @@ -33,14 +33,9 @@ export class UniqueRequestIDPolicy extends BaseRequestPolicy { * @returns {Promise} * @memberof UniqueRequestIDPolicy */ - public async sendRequest( - request: WebResource - ): Promise { + public async sendRequest(request: WebResource): Promise { if (!request.headers.contains(HeaderConstants.X_MS_CLIENT_REQUEST_ID)) { - request.headers.set( - HeaderConstants.X_MS_CLIENT_REQUEST_ID, - generateUuid() - ); + request.headers.set(HeaderConstants.X_MS_CLIENT_REQUEST_ID, generateUuid()); } return this._nextPolicy.sendRequest(request); diff --git a/sdk/storage/storage-file/src/utils/Batch.ts b/sdk/storage/storage-file/src/utils/Batch.ts index e4917f1c0edf..87a185ddeb3d 100644 --- a/sdk/storage/storage-file/src/utils/Batch.ts +++ b/sdk/storage/storage-file/src/utils/Batch.ts @@ -134,7 +134,7 @@ export class Batch { return new Promise((resolve, reject) => { this.emitter.on("finish", resolve); - this.emitter.on("error", error => { + this.emitter.on("error", (error) => { this.state = BatchStates.Error; reject(error); }); diff --git a/sdk/storage/storage-file/src/utils/BufferScheduler.ts b/sdk/storage/storage-file/src/utils/BufferScheduler.ts index 21a91c5bca43..81ed82f64a21 100644 --- a/sdk/storage/storage-file/src/utils/BufferScheduler.ts +++ b/sdk/storage/storage-file/src/utils/BufferScheduler.ts @@ -4,10 +4,7 @@ import { Readable } from "stream"; /** * OutgoingHandler is an async function triggered by BufferScheduler. */ -export declare type OutgoingHandler = ( - buffer: Buffer, - offset?: number -) => Promise; +export declare type OutgoingHandler = (buffer: Buffer, offset?: number) => Promise; /** * This class accepts a Node.js Readable stream as input, and keeps reading data @@ -206,21 +203,15 @@ export class BufferScheduler { encoding?: string ) { if (bufferSize <= 0) { - throw new RangeError( - `bufferSize must be larger than 0, current is ${bufferSize}` - ); + throw new RangeError(`bufferSize must be larger than 0, current is ${bufferSize}`); } if (maxBuffers <= 0) { - throw new RangeError( - `maxBuffers must be larger than 0, current is ${maxBuffers}` - ); + throw new RangeError(`maxBuffers must be larger than 0, current is ${maxBuffers}`); } if (parallelism <= 0) { - throw new RangeError( - `parallelism must be larger than 0, current is ${parallelism}` - ); + throw new RangeError(`parallelism must be larger than 0, current is ${parallelism}`); } this.bufferSize = bufferSize; @@ -240,9 +231,8 @@ export class BufferScheduler { */ public async do(): Promise { return new Promise((resolve, reject) => { - this.readable.on("data", data => { - data = - typeof data === "string" ? Buffer.from(data, this.encoding) : data; + this.readable.on("data", (data) => { + data = typeof data === "string" ? Buffer.from(data, this.encoding) : data; this.appendUnresolvedData(data); if (!this.resolveData()) { @@ -250,7 +240,7 @@ export class BufferScheduler { } }); - this.readable.on("error", err => { + this.readable.on("error", (err) => { this.emitter.emit("error", err); }); @@ -259,7 +249,7 @@ export class BufferScheduler { this.emitter.emit("checkEnd"); }); - this.emitter.on("error", err => { + this.emitter.on("error", (err) => { this.isError = true; this.readable.pause(); reject(err); @@ -272,14 +262,8 @@ export class BufferScheduler { } if (this.isStreamEnd && this.executingOutgoingHandlers === 0) { - if ( - this.unresolvedLength > 0 && - this.unresolvedLength < this.bufferSize - ) { - this.outgoingHandler( - this.shiftBufferFromUnresolvedDataArray(), - this.offset - ) + if (this.unresolvedLength > 0 && this.unresolvedLength < this.bufferSize) { + this.outgoingHandler(this.shiftBufferFromUnresolvedDataArray(), this.offset) .then(resolve) .catch(reject); } else if (this.unresolvedLength >= this.bufferSize) { @@ -320,20 +304,14 @@ export class BufferScheduler { } // Lazy concat because Buffer.concat highly drops performance - let merged = Buffer.concat( - this.unresolvedDataArray, - this.unresolvedLength - ); + let merged = Buffer.concat(this.unresolvedDataArray, this.unresolvedLength); const buffer = merged.slice(0, this.bufferSize); merged = merged.slice(this.bufferSize); this.unresolvedDataArray = [merged]; this.unresolvedLength -= buffer.length; return buffer; } else if (this.unresolvedLength > 0) { - const merged = Buffer.concat( - this.unresolvedDataArray, - this.unresolvedLength - ); + const merged = Buffer.concat(this.unresolvedDataArray, this.unresolvedLength); this.unresolvedDataArray = []; this.unresolvedLength = 0; return merged; diff --git a/sdk/storage/storage-file/src/utils/RetriableReadableStream.ts b/sdk/storage/storage-file/src/utils/RetriableReadableStream.ts index 7eef43545d63..2469955d3220 100644 --- a/sdk/storage/storage-file/src/utils/RetriableReadableStream.ts +++ b/sdk/storage/storage-file/src/utils/RetriableReadableStream.ts @@ -2,9 +2,7 @@ import { RestError, TransferProgressEvent } from "@azure/ms-rest-js"; import { Readable } from "stream"; import { Aborter } from "../Aborter"; -export type ReadableStreamGetter = ( - offset: number -) => Promise; +export type ReadableStreamGetter = (offset: number) => Promise; export interface IRetriableReadableStreamOptions { /** @@ -86,21 +84,13 @@ export class RetriableReadableStream extends Readable { this.offset = offset; this.end = offset + count - 1; this.maxRetryRequests = - options.maxRetryRequests && options.maxRetryRequests >= 0 - ? options.maxRetryRequests - : 0; + options.maxRetryRequests && options.maxRetryRequests >= 0 ? options.maxRetryRequests : 0; this.progress = options.progress; this.options = options; aborter.addEventListener("abort", () => { this.source.pause(); - this.emit( - "error", - new RestError( - "The request was aborted", - RestError.REQUEST_ABORTED_ERROR - ) - ); + this.emit("error", new RestError("The request was aborted", RestError.REQUEST_ABORTED_ERROR)); }); this.setSourceDataHandler(); @@ -153,13 +143,13 @@ export class RetriableReadableStream extends Readable { if (this.retries < this.maxRetryRequests) { this.retries += 1; this.getter(this.offset) - .then(newSource => { + .then((newSource) => { this.source = newSource; this.setSourceDataHandler(); this.setSourceEndHandler(); this.setSourceErrorHandler(); }) - .catch(error => { + .catch((error) => { this.emit("error", error); }); } else { @@ -188,7 +178,7 @@ export class RetriableReadableStream extends Readable { } private setSourceErrorHandler() { - this.source.on("error", error => { + this.source.on("error", (error) => { this.emit("error", error); }); } diff --git a/sdk/storage/storage-file/src/utils/utils.common.ts b/sdk/storage/storage-file/src/utils/utils.common.ts index d906f46d9d36..4c163d91defe 100644 --- a/sdk/storage/storage-file/src/utils/utils.common.ts +++ b/sdk/storage/storage-file/src/utils/utils.common.ts @@ -93,11 +93,7 @@ export function appendToURLPath(url: string, name: string): string { const urlParsed = URLBuilder.parse(url); let path = urlParsed.getPath(); - path = path - ? path.endsWith("/") - ? `${path}${name}` - : `${path}/${name}` - : name; + path = path ? (path.endsWith("/") ? `${path}${name}` : `${path}/${name}`) : name; urlParsed.setPath(path); return urlParsed.toString(); @@ -113,11 +109,7 @@ export function appendToURLPath(url: string, name: string): string { * @param {string} [value] Parameter value * @returns {string} An updated URL string */ -export function setURLParameter( - url: string, - name: string, - value?: string -): string { +export function setURLParameter(url: string, name: string, value?: string): string { const urlParsed = URLBuilder.parse(url); urlParsed.setQueryParameter(name, value); return urlParsed.toString(); @@ -131,10 +123,7 @@ export function setURLParameter( * @param {string} name * @returns {(string | string[] | undefined)} */ -export function getURLParameter( - url: string, - name: string -): string | string[] | undefined { +export function getURLParameter(url: string, name: string): string | string[] | undefined { const urlParsed = URLBuilder.parse(url); return urlParsed.getQueryParameterValue(name); } @@ -179,18 +168,14 @@ export function getURLQueries(url: string): { [key: string]: string } { } queryString = queryString.trim(); - queryString = queryString.startsWith("?") - ? queryString.substr(1) - : queryString; + queryString = queryString.startsWith("?") ? queryString.substr(1) : queryString; let querySubStrings: string[] = queryString.split("&"); querySubStrings = querySubStrings.filter((value: string) => { const indexOfEqual = value.indexOf("="); const lastIndexOfEqual = value.lastIndexOf("="); return ( - indexOfEqual > 0 && - indexOfEqual === lastIndexOfEqual && - lastIndexOfEqual < value.length - 1 + indexOfEqual > 0 && indexOfEqual === lastIndexOfEqual && lastIndexOfEqual < value.length - 1 ); }); @@ -214,10 +199,7 @@ export function getURLQueries(url: string): { [key: string]: string } { * If false, YYYY-MM-DDThh:mm:ssZ will be returned. * @returns {string} Date string in ISO8061 format, with or without 7 milliseconds component */ -export function truncatedISO8061Date( - date: Date, - withMilliseconds: boolean = true -): string { +export function truncatedISO8061Date(date: Date, withMilliseconds: boolean = true): string { // Date.toISOString() will return like "2018-10-29T06:34:36.139Z" const dateString = date.toISOString(); @@ -245,9 +227,7 @@ export function base64encode(content: string): string { * @returns {string} */ export function base64decode(encodedString: string): string { - return !isNode - ? atob(encodedString) - : Buffer.from(encodedString, "base64").toString(); + return !isNode ? atob(encodedString) : Buffer.from(encodedString, "base64").toString(); } /** diff --git a/sdk/storage/storage-file/src/utils/utils.node.ts b/sdk/storage/storage-file/src/utils/utils.node.ts index 74f04f0a7094..394fed9f40f6 100644 --- a/sdk/storage/storage-file/src/utils/utils.node.ts +++ b/sdk/storage/storage-file/src/utils/utils.node.ts @@ -35,14 +35,9 @@ export async function streamToBuffer( } // How much data needed in this chunk - const chunkLength = - pos + chunk.length > count ? count - pos : chunk.length; + const chunkLength = pos + chunk.length > count ? count - pos : chunk.length; - buffer.fill( - chunk.slice(0, chunkLength), - offset + pos, - offset + pos + chunkLength - ); + buffer.fill(chunk.slice(0, chunkLength), offset + pos, offset + pos + chunkLength); pos += chunkLength; }); diff --git a/sdk/storage/storage-file/test/aborter.test.ts b/sdk/storage/storage-file/test/aborter.test.ts index 6f8def20c25f..02f0ca54ba8e 100644 --- a/sdk/storage/storage-file/test/aborter.test.ts +++ b/sdk/storage/storage-file/test/aborter.test.ts @@ -4,7 +4,7 @@ import { Aborter } from "../src/Aborter"; import { ShareURL } from "../src/ShareURL"; import { getBSU, getUniqueName } from "./utils"; import * as dotenv from "dotenv"; -dotenv.config({path:"../.env"}); +dotenv.config({ path: "../.env" }); // tslint:disable:no-empty describe("Aborter", () => { diff --git a/sdk/storage/storage-file/test/directoryurl.test.ts b/sdk/storage/storage-file/test/directoryurl.test.ts index 5a4c7330ea73..a1fa824f0239 100644 --- a/sdk/storage/storage-file/test/directoryurl.test.ts +++ b/sdk/storage/storage-file/test/directoryurl.test.ts @@ -6,7 +6,7 @@ import { FileURL } from "../src/FileURL"; import { ShareURL } from "../src/ShareURL"; import { getBSU, getUniqueName } from "./utils"; import * as dotenv from "dotenv"; -dotenv.config({path:"../.env"}); +dotenv.config({ path: "../.env" }); describe("DirectoryURL", () => { const serviceURL = getBSU(); @@ -55,7 +55,7 @@ describe("DirectoryURL", () => { assert.ok(result.date); }); - it("create with default parameters", done => { + it("create with default parameters", (done) => { // create() with default parameters has been tested in beforeEach done(); }); @@ -68,7 +68,7 @@ describe("DirectoryURL", () => { assert.deepStrictEqual(result.metadata, metadata); }); - it("delete", done => { + it("delete", (done) => { // delete() with default parameters has been tested in afterEach done(); }); @@ -89,26 +89,18 @@ describe("DirectoryURL", () => { const subFileURLs = []; for (let i = 0; i < 3; i++) { - const subFileURL = FileURL.fromDirectoryURL( - rootDirURL, - getUniqueName(`${prefix}file${i}`) - ); + const subFileURL = FileURL.fromDirectoryURL(rootDirURL, getUniqueName(`${prefix}file${i}`)); await subFileURL.create(Aborter.none, 1024); subFileURLs.push(subFileURL); } - const result = await rootDirURL.listFilesAndDirectoriesSegment( - Aborter.none, - undefined, - { prefix } - ); + const result = await rootDirURL.listFilesAndDirectoriesSegment(Aborter.none, undefined, { + prefix + }); assert.ok(result.serviceEndpoint.length > 0); assert.ok(shareURL.url.indexOf(result.shareName)); assert.deepStrictEqual(result.nextMarker, ""); - assert.deepStrictEqual( - result.segment.directoryItems.length, - subDirURLs.length - ); + assert.deepStrictEqual(result.segment.directoryItems.length, subDirURLs.length); assert.deepStrictEqual(result.segment.fileItems.length, subFileURLs.length); let i = 0; @@ -145,29 +137,21 @@ describe("DirectoryURL", () => { const subFileURLs = []; for (let i = 0; i < 3; i++) { - const subFileURL = FileURL.fromDirectoryURL( - rootDirURL, - getUniqueName(`${prefix}file${i}`) - ); + const subFileURL = FileURL.fromDirectoryURL(rootDirURL, getUniqueName(`${prefix}file${i}`)); await subFileURL.create(Aborter.none, 1024); subFileURLs.push(subFileURL); } - const firstRequestSize = Math.ceil( - (subDirURLs.length + subFileURLs.length) / 2 - ); - const secondRequestSize = - subDirURLs.length + subFileURLs.length - firstRequestSize; + const firstRequestSize = Math.ceil((subDirURLs.length + subFileURLs.length) / 2); + const secondRequestSize = subDirURLs.length + subFileURLs.length - firstRequestSize; - const firstResult = await rootDirURL.listFilesAndDirectoriesSegment( - Aborter.none, - undefined, - { prefix, maxresults: firstRequestSize } - ); + const firstResult = await rootDirURL.listFilesAndDirectoriesSegment(Aborter.none, undefined, { + prefix, + maxresults: firstRequestSize + }); assert.deepStrictEqual( - firstResult.segment.directoryItems.length + - firstResult.segment.fileItems.length, + firstResult.segment.directoryItems.length + firstResult.segment.fileItems.length, firstRequestSize ); assert.notDeepEqual(firstResult.nextMarker, undefined); @@ -178,8 +162,7 @@ describe("DirectoryURL", () => { { prefix, maxresults: firstRequestSize + secondRequestSize } ); assert.deepStrictEqual( - secondResult.segment.directoryItems.length + - secondResult.segment.fileItems.length, + secondResult.segment.directoryItems.length + secondResult.segment.fileItems.length, secondRequestSize ); diff --git a/sdk/storage/storage-file/test/fileurl.test.ts b/sdk/storage/storage-file/test/fileurl.test.ts index a59963d1eb22..853d9d3a2988 100644 --- a/sdk/storage/storage-file/test/fileurl.test.ts +++ b/sdk/storage/storage-file/test/fileurl.test.ts @@ -7,7 +7,7 @@ import { FileURL } from "../src/FileURL"; import { ShareURL } from "../src/ShareURL"; import { bodyToString, getBSU, getUniqueName, sleep } from "./utils"; import * as dotenv from "dotenv"; -dotenv.config({path:"../.env"}); +dotenv.config({ path: "../.env" }); describe("FileURL", () => { const serviceURL = getBSU(); @@ -62,32 +62,14 @@ describe("FileURL", () => { await fileURL.create(Aborter.none, 512, options); const result = await fileURL.download(Aborter.none, 0); - assert.deepStrictEqual( - await bodyToString(result, 512), - "\u0000".repeat(512) - ); + assert.deepStrictEqual(await bodyToString(result, 512), "\u0000".repeat(512)); const properties = await fileURL.getProperties(Aborter.none); - assert.equal( - properties.cacheControl, - options.fileHTTPHeaders.fileCacheControl - ); - assert.equal( - properties.contentDisposition, - options.fileHTTPHeaders.fileContentDisposition - ); - assert.equal( - properties.contentEncoding, - options.fileHTTPHeaders.fileContentEncoding - ); - assert.equal( - properties.contentLanguage, - options.fileHTTPHeaders.fileContentLanguage - ); - assert.equal( - properties.contentType, - options.fileHTTPHeaders.fileContentType - ); + assert.equal(properties.cacheControl, options.fileHTTPHeaders.fileCacheControl); + assert.equal(properties.contentDisposition, options.fileHTTPHeaders.fileContentDisposition); + assert.equal(properties.contentEncoding, options.fileHTTPHeaders.fileContentEncoding); + assert.equal(properties.contentLanguage, options.fileHTTPHeaders.fileContentLanguage); + assert.equal(properties.contentType, options.fileHTTPHeaders.fileContentType); assert.equal(properties.metadata!.key1, options.metadata.key1); assert.equal(properties.metadata!.key2, options.metadata.key2); }); @@ -140,9 +122,7 @@ describe("FileURL", () => { fileContentDisposition: "fileContentDisposition", fileContentEncoding: "fileContentEncoding", fileContentLanguage: "fileContentLanguage", - fileContentMD5: isNode - ? Buffer.from([1, 2, 3, 4]) - : new Uint8Array([1, 2, 3, 4]), + fileContentMD5: isNode ? Buffer.from([1, 2, 3, 4]) : new Uint8Array([1, 2, 3, 4]), fileContentType: "fileContentType" }; await fileURL.setHTTPHeaders(Aborter.none, headers); @@ -154,10 +134,7 @@ describe("FileURL", () => { assert.deepStrictEqual(result.contentMD5, headers.fileContentMD5); assert.deepStrictEqual(result.contentEncoding, headers.fileContentEncoding); assert.deepStrictEqual(result.contentLanguage, headers.fileContentLanguage); - assert.deepStrictEqual( - result.contentDisposition, - headers.fileContentDisposition - ); + assert.deepStrictEqual(result.contentDisposition, headers.fileContentDisposition); }); it("delete", async () => { @@ -167,10 +144,7 @@ describe("FileURL", () => { it("startCopyFromURL", async () => { await fileURL.create(Aborter.none, 1024); - const newFileURL = FileURL.fromDirectoryURL( - dirURL, - getUniqueName("copiedfile") - ); + const newFileURL = FileURL.fromDirectoryURL(dirURL, getUniqueName("copiedfile")); const result = await newFileURL.startCopyFromURL(Aborter.none, fileURL.url); assert.ok(result.copyId); @@ -183,10 +157,7 @@ describe("FileURL", () => { it("abortCopyFromURL should failed for a completed copy operation", async () => { await fileURL.create(Aborter.none, content.length); - const newFileURL = FileURL.fromDirectoryURL( - dirURL, - getUniqueName("copiedfile") - ); + const newFileURL = FileURL.fromDirectoryURL(dirURL, getUniqueName("copiedfile")); const result = await newFileURL.startCopyFromURL(Aborter.none, fileURL.url); assert.ok(result.copyId); sleep(1 * 1000); @@ -264,10 +235,7 @@ describe("FileURL", () => { await fileURL.clearRange(Aborter.none, 1, 8); const result = await fileURL.download(Aborter.none, 0); - assert.deepStrictEqual( - await bodyToString(result, 10), - "H" + "\u0000".repeat(8) + "d" - ); + assert.deepStrictEqual(await bodyToString(result, 10), "H" + "\u0000".repeat(8) + "d"); }); it("getRangeList", async () => { diff --git a/sdk/storage/storage-file/test/node/highlevel.node.test.ts b/sdk/storage/storage-file/test/node/highlevel.node.test.ts index 9be923eb83a6..f208e9ac3ebb 100644 --- a/sdk/storage/storage-file/test/node/highlevel.node.test.ts +++ b/sdk/storage/storage-file/test/node/highlevel.node.test.ts @@ -10,12 +10,7 @@ import { uploadFileToAzureFile, uploadStreamToAzureFile } from "../../src/highlevel.node"; -import { - createRandomLocalFile, - getBSU, - getUniqueName, - readStreamToLocalFile -} from "../utils"; +import { createRandomLocalFile, getBSU, getUniqueName, readStreamToLocalFile } from "../utils"; import { IRetriableReadableStreamOptions } from "../../src/utils/RetriableReadableStream"; // tslint:disable:no-empty @@ -52,17 +47,9 @@ describe("Highlevel", () => { if (!fs.existsSync(tempFolderPath)) { fs.mkdirSync(tempFolderPath); } - tempFileLarge = await createRandomLocalFile( - tempFolderPath, - 257, - 1024 * 1024 - ); + tempFileLarge = await createRandomLocalFile(tempFolderPath, 257, 1024 * 1024); tempFileLargeLength = 257 * 1024 * 1024; - tempFileSmall = await createRandomLocalFile( - tempFolderPath, - 15, - 1024 * 1024 - ); + tempFileSmall = await createRandomLocalFile(tempFolderPath, 15, 1024 * 1024); tempFileSmallLength = 15 * 1024 * 1024; }); @@ -78,14 +65,8 @@ describe("Highlevel", () => { }); const downloadResponse = await fileURL.download(Aborter.none, 0); - const downloadedFile = path.join( - tempFolderPath, - getUniqueName("downloadfile.") - ); - await readStreamToLocalFile( - downloadResponse.readableStreamBody!, - downloadedFile - ); + const downloadedFile = path.join(tempFolderPath, getUniqueName("downloadfile.")); + await readStreamToLocalFile(downloadResponse.readableStreamBody!, downloadedFile); const downloadedData = await fs.readFileSync(downloadedFile); const uploadedData = await fs.readFileSync(tempFileLarge); @@ -101,14 +82,8 @@ describe("Highlevel", () => { }); const downloadResponse = await fileURL.download(Aborter.none, 0); - const downloadedFile = path.join( - tempFolderPath, - getUniqueName("downloadfile.") - ); - await readStreamToLocalFile( - downloadResponse.readableStreamBody!, - downloadedFile - ); + const downloadedFile = path.join(tempFolderPath, getUniqueName("downloadfile.")); + await readStreamToLocalFile(downloadResponse.readableStreamBody!, downloadedFile); const downloadedData = await fs.readFileSync(downloadedFile); const uploadedData = await fs.readFileSync(tempFileSmall); @@ -152,7 +127,7 @@ describe("Highlevel", () => { try { await uploadFileToAzureFile(aborter, tempFileLarge, fileURL, { parallelism: 20, - progress: ev => { + progress: (ev) => { assert.ok(ev.loadedBytes); eventTriggered = true; aborter.abort(); @@ -170,7 +145,7 @@ describe("Highlevel", () => { try { await uploadFileToAzureFile(aborter, tempFileSmall, fileURL, { parallelism: 20, - progress: ev => { + progress: (ev) => { assert.ok(ev.loadedBytes); eventTriggered = true; aborter.abort(); @@ -194,14 +169,8 @@ describe("Highlevel", () => { const downloadResponse = await fileURL.download(Aborter.none, 0); - const downloadFilePath = path.join( - tempFolderPath, - getUniqueName("downloadFile") - ); - await readStreamToLocalFile( - downloadResponse.readableStreamBody!, - downloadFilePath - ); + const downloadFilePath = path.join(tempFolderPath, getUniqueName("downloadFile")); + await readStreamToLocalFile(downloadResponse.readableStreamBody!, downloadFilePath); const downloadedBuffer = fs.readFileSync(downloadFilePath); const uploadedBuffer = fs.readFileSync(tempFileLarge); @@ -215,14 +184,7 @@ describe("Highlevel", () => { const aborter = Aborter.timeout(1); try { - await uploadStreamToAzureFile( - aborter, - rs, - tempFileLargeLength, - fileURL, - 4 * 1024 * 1024, - 20 - ); + await uploadStreamToAzureFile(aborter, rs, tempFileLargeLength, fileURL, 4 * 1024 * 1024, 20); assert.fail(); } catch (err) { assert.ok((err.code as string).toLowerCase().includes("abort")); @@ -241,7 +203,7 @@ describe("Highlevel", () => { 4 * 1024 * 1024, 20, { - progress: ev => { + progress: (ev) => { assert.ok(ev.loadedBytes); eventTriggered = true; } @@ -284,17 +246,10 @@ describe("Highlevel", () => { try { const buf = Buffer.alloc(tempFileLargeLength); - await downloadAzureFileToBuffer( - Aborter.timeout(1), - buf, - fileURL, - 0, - undefined, - { - parallelism: 20, - rangeSize: 4 * 1024 * 1024 - } - ); + await downloadAzureFileToBuffer(Aborter.timeout(1), buf, fileURL, 0, undefined, { + parallelism: 20, + rangeSize: 4 * 1024 * 1024 + }); assert.fail(); } catch (err) { assert.ok((err.code as string).toLowerCase().includes("abort")); @@ -335,31 +290,19 @@ describe("Highlevel", () => { }); let retirableReadableStreamOptions: IRetriableReadableStreamOptions; - const downloadResponse = await fileURL.download( - Aborter.none, - 0, - undefined, - { - maxRetryRequests: 1, - progress: ev => { - if (ev.loadedBytes >= tempFileSmallLength) { - retirableReadableStreamOptions.doInjectErrorOnce = true; - } + const downloadResponse = await fileURL.download(Aborter.none, 0, undefined, { + maxRetryRequests: 1, + progress: (ev) => { + if (ev.loadedBytes >= tempFileSmallLength) { + retirableReadableStreamOptions.doInjectErrorOnce = true; } } - ); + }); - retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any) - .options; + retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any).options; - const downloadedFile = path.join( - tempFolderPath, - getUniqueName("downloadfile.") - ); - await readStreamToLocalFile( - downloadResponse.readableStreamBody!, - downloadedFile - ); + const downloadedFile = path.join(tempFolderPath, getUniqueName("downloadfile.")); + await readStreamToLocalFile(downloadResponse.readableStreamBody!, downloadedFile); const downloadedData = await fs.readFileSync(downloadedFile); const uploadedData = await fs.readFileSync(tempFileSmall); @@ -376,31 +319,19 @@ describe("Highlevel", () => { let retirableReadableStreamOptions: IRetriableReadableStreamOptions; let injectedErrors = 0; - const downloadResponse = await fileURL.download( - Aborter.none, - 0, - undefined, - { - maxRetryRequests: 3, - progress: () => { - if (injectedErrors++ < 3) { - retirableReadableStreamOptions.doInjectErrorOnce = true; - } + const downloadResponse = await fileURL.download(Aborter.none, 0, undefined, { + maxRetryRequests: 3, + progress: () => { + if (injectedErrors++ < 3) { + retirableReadableStreamOptions.doInjectErrorOnce = true; } } - ); + }); - retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any) - .options; + retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any).options; - const downloadedFile = path.join( - tempFolderPath, - getUniqueName("downloadfile.") - ); - await readStreamToLocalFile( - downloadResponse.readableStreamBody!, - downloadedFile - ); + const downloadedFile = path.join(tempFolderPath, getUniqueName("downloadfile.")); + await readStreamToLocalFile(downloadResponse.readableStreamBody!, downloadedFile); const downloadedData = await fs.readFileSync(downloadedFile); const uploadedData = await fs.readFileSync(tempFileSmall); @@ -419,31 +350,19 @@ describe("Highlevel", () => { let retirableReadableStreamOptions: IRetriableReadableStreamOptions; let injectedErrors = 0; - const downloadResponse = await fileURL.download( - Aborter.none, - 1, - partialSize, - { - maxRetryRequests: 3, - progress: () => { - if (injectedErrors++ < 3) { - retirableReadableStreamOptions.doInjectErrorOnce = true; - } + const downloadResponse = await fileURL.download(Aborter.none, 1, partialSize, { + maxRetryRequests: 3, + progress: () => { + if (injectedErrors++ < 3) { + retirableReadableStreamOptions.doInjectErrorOnce = true; } } - ); + }); - retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any) - .options; + retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any).options; - const downloadedFile = path.join( - tempFolderPath, - getUniqueName("downloadfile.") - ); - await readStreamToLocalFile( - downloadResponse.readableStreamBody!, - downloadedFile - ); + const downloadedFile = path.join(tempFolderPath, getUniqueName("downloadfile.")); + await readStreamToLocalFile(downloadResponse.readableStreamBody!, downloadedFile); const downloadedData = await fs.readFileSync(downloadedFile); const uploadedData = await fs.readFileSync(tempFileSmall); @@ -458,35 +377,23 @@ describe("Highlevel", () => { parallelism: 20 }); - const downloadedFile = path.join( - tempFolderPath, - getUniqueName("downloadfile.") - ); + const downloadedFile = path.join(tempFolderPath, getUniqueName("downloadfile.")); let retirableReadableStreamOptions: IRetriableReadableStreamOptions; let injectedErrors = 0; let expectedError = false; try { - const downloadResponse = await fileURL.download( - Aborter.none, - 0, - undefined, - { - maxRetryRequests: 0, - progress: () => { - if (injectedErrors++ < 1) { - retirableReadableStreamOptions.doInjectErrorOnce = true; - } + const downloadResponse = await fileURL.download(Aborter.none, 0, undefined, { + maxRetryRequests: 0, + progress: () => { + if (injectedErrors++ < 1) { + retirableReadableStreamOptions.doInjectErrorOnce = true; } } - ); - retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any) - .options; - await readStreamToLocalFile( - downloadResponse.readableStreamBody!, - downloadedFile - ); + }); + retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any).options; + await readStreamToLocalFile(downloadResponse.readableStreamBody!, downloadedFile); } catch (error) { expectedError = true; } @@ -501,10 +408,7 @@ describe("Highlevel", () => { parallelism: 20 }); - const downloadedFile = path.join( - tempFolderPath, - getUniqueName("downloadfile.") - ); + const downloadedFile = path.join(tempFolderPath, getUniqueName("downloadfile.")); let retirableReadableStreamOptions: IRetriableReadableStreamOptions; let injectedErrors = 0; @@ -524,12 +428,8 @@ describe("Highlevel", () => { } } }); - retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any) - .options; - await readStreamToLocalFile( - downloadResponse.readableStreamBody!, - downloadedFile - ); + retirableReadableStreamOptions = (downloadResponse.readableStreamBody! as any).options; + await readStreamToLocalFile(downloadResponse.readableStreamBody!, downloadedFile); } catch (error) { expectedError = true; } diff --git a/sdk/storage/storage-file/test/node/sas.test.ts b/sdk/storage/storage-file/test/node/sas.test.ts index f8c5900c5c48..1005c7dcc35c 100644 --- a/sdk/storage/storage-file/test/node/sas.test.ts +++ b/sdk/storage/storage-file/test/node/sas.test.ts @@ -191,10 +191,7 @@ describe("Shared Access Signature (SAS) generation Node.js only", () => { ); const sasURL = `${shareURL.url}?${shareSAS}`; - const shareURLwithSAS = new ShareURL( - sasURL, - StorageURL.newPipeline(new AnonymousCredential()) - ); + const shareURLwithSAS = new ShareURL(sasURL, StorageURL.newPipeline(new AnonymousCredential())); const dirURLwithSAS = DirectoryURL.fromShareURL(shareURLwithSAS, ""); await dirURLwithSAS.listFilesAndDirectoriesSegment(Aborter.none); @@ -249,10 +246,7 @@ describe("Shared Access Signature (SAS) generation Node.js only", () => { ); const sasURL = `${fileURL.url}?${fileSAS}`; - const fileURLwithSAS = new FileURL( - sasURL, - StorageURL.newPipeline(new AnonymousCredential()) - ); + const fileURLwithSAS = new FileURL(sasURL, StorageURL.newPipeline(new AnonymousCredential())); const properties = await fileURLwithSAS.getProperties(Aborter.none); assert.equal(properties.cacheControl, "cache-control-override"); @@ -312,10 +306,7 @@ describe("Shared Access Signature (SAS) generation Node.js only", () => { ); const sasURL = `${shareURL.url}?${shareSAS}`; - const shareURLwithSAS = new ShareURL( - sasURL, - StorageURL.newPipeline(new AnonymousCredential()) - ); + const shareURLwithSAS = new ShareURL(sasURL, StorageURL.newPipeline(new AnonymousCredential())); const dirURLwithSAS = DirectoryURL.fromShareURL(shareURLwithSAS, ""); await dirURLwithSAS.listFilesAndDirectoriesSegment(Aborter.none); diff --git a/sdk/storage/storage-file/test/node/shareurl.test.ts b/sdk/storage/storage-file/test/node/shareurl.test.ts index 7e5dd66af850..d0f7aabe67a4 100644 --- a/sdk/storage/storage-file/test/node/shareurl.test.ts +++ b/sdk/storage/storage-file/test/node/shareurl.test.ts @@ -37,14 +37,9 @@ describe("ShareURL", () => { ]; await shareURL.setAccessPolicy(Aborter.none, identifiers); - const getAccessPolicyResponse = await shareURL.getAccessPolicy( - Aborter.none - ); + const getAccessPolicyResponse = await shareURL.getAccessPolicy(Aborter.none); - assert.equal( - getAccessPolicyResponse.signedIdentifiers[0].id, - identifiers[0].id - ); + assert.equal(getAccessPolicyResponse.signedIdentifiers[0].id, identifiers[0].id); assert.equal( getAccessPolicyResponse.signedIdentifiers[0].accessPolicy.expiry.getTime(), identifiers[0].accessPolicy.expiry.getTime() @@ -59,7 +54,7 @@ describe("ShareURL", () => { ); }); - it("getAccessPolicy", done => { + it("getAccessPolicy", (done) => { // create() with default parameters has been tested in setAccessPolicy done(); }); diff --git a/sdk/storage/storage-file/test/retrypolicy.test.ts b/sdk/storage/storage-file/test/retrypolicy.test.ts index 5816ef8a393d..c5af1421663f 100644 --- a/sdk/storage/storage-file/test/retrypolicy.test.ts +++ b/sdk/storage/storage-file/test/retrypolicy.test.ts @@ -7,7 +7,7 @@ import { Pipeline } from "../src/Pipeline"; import { getBSU, getUniqueName } from "./utils"; import { InjectorPolicyFactory } from "./utils/InjectorPolicyFactory"; import * as dotenv from "dotenv"; -dotenv.config({path:"../.env"}); +dotenv.config({ path: "../.env" }); describe("RetryPolicy", () => { const serviceURL = getBSU(); @@ -29,11 +29,7 @@ describe("RetryPolicy", () => { const injector = new InjectorPolicyFactory(() => { if (injectCounter === 0) { injectCounter++; - return new RestError( - "Server Internal Error", - "ServerInternalError", - 500 - ); + return new RestError("Server Internal Error", "ServerInternalError", 500); } }); const factories = shareURL.pipeline.factories.slice(); // clone factories array @@ -57,8 +53,7 @@ describe("RetryPolicy", () => { return new RestError("Server Internal Error", "ServerInternalError", 500); }); - const credential = - shareURL.pipeline.factories[shareURL.pipeline.factories.length - 1]; + const credential = shareURL.pipeline.factories[shareURL.pipeline.factories.length - 1]; const factories = StorageURL.newPipeline(credential, { retryOptions: { maxTries: 3 } }).factories; diff --git a/sdk/storage/storage-file/test/serviceurl.test.ts b/sdk/storage/storage-file/test/serviceurl.test.ts index 95230f66bc2c..11eb16b92527 100644 --- a/sdk/storage/storage-file/test/serviceurl.test.ts +++ b/sdk/storage/storage-file/test/serviceurl.test.ts @@ -4,7 +4,7 @@ import { Aborter } from "../src/Aborter"; import { ShareURL } from "../src/ShareURL"; import { getBSU, getUniqueName, wait } from "./utils"; import * as dotenv from "dotenv"; -dotenv.config({path:"../.env"}); +dotenv.config({ path: "../.env" }); describe("ServiceURL", () => { it("ListShares with default parameters", async () => { @@ -38,15 +38,11 @@ describe("ServiceURL", () => { await shareURL1.create(Aborter.none, { metadata: { key: "val" } }); await shareURL2.create(Aborter.none, { metadata: { key: "val" } }); - const result1 = await serviceURL.listSharesSegment( - Aborter.none, - undefined, - { - include: ["metadata", "snapshots"], - maxresults: 1, - prefix: shareNamePrefix - } - ); + const result1 = await serviceURL.listSharesSegment(Aborter.none, undefined, { + include: ["metadata", "snapshots"], + maxresults: 1, + prefix: shareNamePrefix + }); assert.ok(result1.nextMarker); assert.equal(result1.shareItems!.length, 1); @@ -55,15 +51,11 @@ describe("ServiceURL", () => { assert.ok(result1.shareItems![0].properties.lastModified); assert.deepEqual(result1.shareItems![0].metadata!.key, "val"); - const result2 = await serviceURL.listSharesSegment( - Aborter.none, - result1.nextMarker, - { - include: ["metadata", "snapshots"], - maxresults: 1, - prefix: shareNamePrefix - } - ); + const result2 = await serviceURL.listSharesSegment(Aborter.none, result1.nextMarker, { + include: ["metadata", "snapshots"], + maxresults: 1, + prefix: shareNamePrefix + }); assert.ok(!result2.nextMarker); assert.equal(result2.shareItems!.length, 1); diff --git a/sdk/storage/storage-file/test/shareurl.test.ts b/sdk/storage/storage-file/test/shareurl.test.ts index feef6c17aab1..5fa09975097c 100644 --- a/sdk/storage/storage-file/test/shareurl.test.ts +++ b/sdk/storage/storage-file/test/shareurl.test.ts @@ -4,7 +4,7 @@ import { Aborter } from "../src/Aborter"; import { ShareURL } from "../src/ShareURL"; import { getBSU, getUniqueName } from "./utils"; import * as dotenv from "dotenv"; -dotenv.config({path:"../.env"}); +dotenv.config({ path: "../.env" }); describe("ShareURL", () => { const serviceURL = getBSU(); @@ -42,23 +42,20 @@ describe("ShareURL", () => { assert.ok(result.date); }); - it("create with default parameters", done => { + it("create with default parameters", (done) => { // create() with default parameters has been tested in beforeEach done(); }); it("create with all parameters configured", async () => { - const shareURL2 = ShareURL.fromServiceURL( - serviceURL, - getUniqueName(shareName) - ); + const shareURL2 = ShareURL.fromServiceURL(serviceURL, getUniqueName(shareName)); const metadata = { key: "value" }; await shareURL2.create(Aborter.none, { metadata }); const result = await shareURL2.getProperties(Aborter.none); assert.deepEqual(result.metadata, metadata); }); - it("delete", done => { + it("delete", (done) => { // delete() with default parameters has been tested in afterEach done(); }); @@ -85,9 +82,7 @@ describe("ShareURL", () => { const sanpshot = createSnapshotResponse.snapshot!; const snapshotShareURL = shareURL.withSnapshot(sanpshot); - const snapshotProperties = await snapshotShareURL.getProperties( - Aborter.none - ); + const snapshotProperties = await snapshotShareURL.getProperties(Aborter.none); assert.deepStrictEqual(snapshotProperties.metadata, metadata); const originProperties = await shareURL.getProperties(Aborter.none); diff --git a/sdk/storage/storage-file/test/specialnaming.test.ts b/sdk/storage/storage-file/test/specialnaming.test.ts index 7e148a548a3b..8ced7c1be3a2 100644 --- a/sdk/storage/storage-file/test/specialnaming.test.ts +++ b/sdk/storage/storage-file/test/specialnaming.test.ts @@ -6,7 +6,7 @@ import * as assert from "assert"; import { appendToURLPath } from "../src/utils/utils.common"; import { DirectoryURL } from "../src/DirectoryURL"; import * as dotenv from "dotenv"; -dotenv.config({path:"../.env"}); +dotenv.config({ path: "../.env" }); describe("Special Naming Tests", () => { const serviceURL = getBSU(); @@ -29,31 +29,20 @@ describe("Special Naming Tests", () => { const fileURL = FileURL.fromDirectoryURL(directoryURL, fileName); await fileURL.create(Aborter.none, 10); - const response = await directoryURL.listFilesAndDirectoriesSegment( - Aborter.none, - undefined, - { - prefix: fileName - } - ); + const response = await directoryURL.listFilesAndDirectoriesSegment(Aborter.none, undefined, { + prefix: fileName + }); assert.notDeepEqual(response.segment.fileItems.length, 0); }); it("Should work with special container and file names with spaces in URL string", async () => { const fileName: string = getUniqueName("file empty"); - const fileURL = new FileURL( - appendToURLPath(directoryURL.url, fileName), - directoryURL.pipeline - ); + const fileURL = new FileURL(appendToURLPath(directoryURL.url, fileName), directoryURL.pipeline); await fileURL.create(Aborter.none, 10); - const response = await directoryURL.listFilesAndDirectoriesSegment( - Aborter.none, - undefined, - { - prefix: fileName - } - ); + const response = await directoryURL.listFilesAndDirectoriesSegment(Aborter.none, undefined, { + prefix: fileName + }); assert.notDeepEqual(response.segment.fileItems.length, 0); }); @@ -63,32 +52,21 @@ describe("Special Naming Tests", () => { await fileURL.create(Aborter.none, 10); await fileURL.getProperties(Aborter.none); - const response = await directoryURL.listFilesAndDirectoriesSegment( - Aborter.none, - undefined, - { - prefix: fileName - } - ); + const response = await directoryURL.listFilesAndDirectoriesSegment(Aborter.none, undefined, { + prefix: fileName + }); assert.notDeepEqual(response.segment.fileItems.length, 0); }); it("Should work with special container and file names uppercase in URL string", async () => { const fileName: string = getUniqueName("Upper file empty another"); - const fileURL = new FileURL( - appendToURLPath(directoryURL.url, fileName), - directoryURL.pipeline - ); + const fileURL = new FileURL(appendToURLPath(directoryURL.url, fileName), directoryURL.pipeline); await fileURL.create(Aborter.none, 10); await fileURL.getProperties(Aborter.none); - const response = await directoryURL.listFilesAndDirectoriesSegment( - Aborter.none, - undefined, - { - prefix: fileName - } - ); + const response = await directoryURL.listFilesAndDirectoriesSegment(Aborter.none, undefined, { + prefix: fileName + }); assert.notDeepEqual(response.segment.fileItems.length, 0); }); @@ -98,90 +76,59 @@ describe("Special Naming Tests", () => { await fileURL.create(Aborter.none, 10); await fileURL.getProperties(Aborter.none); - const response = await directoryURL.listFilesAndDirectoriesSegment( - Aborter.none, - undefined, - { - prefix: fileName - } - ); + const response = await directoryURL.listFilesAndDirectoriesSegment(Aborter.none, undefined, { + prefix: fileName + }); assert.notDeepEqual(response.segment.fileItems.length, 0); }); it("Should work with special file names Chinese characters in URL string", async () => { const fileName: string = getUniqueName("Upper file empty another 汉字"); - const fileURL = new FileURL( - appendToURLPath(directoryURL.url, fileName), - directoryURL.pipeline - ); + const fileURL = new FileURL(appendToURLPath(directoryURL.url, fileName), directoryURL.pipeline); await fileURL.create(Aborter.none, 10); await fileURL.getProperties(Aborter.none); - const response = await directoryURL.listFilesAndDirectoriesSegment( - Aborter.none, - undefined, - { - prefix: fileName - } - ); + const response = await directoryURL.listFilesAndDirectoriesSegment(Aborter.none, undefined, { + prefix: fileName + }); assert.notDeepEqual(response.segment.fileItems.length, 0); }); it("Should work with special file name characters", async () => { - const fileName: string = getUniqueName( - "汉字. special ~!@#$%^&()_+`1234567890-={}[];','" - ); + const fileName: string = getUniqueName("汉字. special ~!@#$%^&()_+`1234567890-={}[];','"); const fileURL = FileURL.fromDirectoryURL(directoryURL, fileName); await fileURL.create(Aborter.none, 10); await fileURL.getProperties(Aborter.none); - const response = await directoryURL.listFilesAndDirectoriesSegment( - Aborter.none, - undefined, - { - // NOTICE: Azure Storage Server will replace "\" with "/" in the file names - prefix: fileName.replace(/\\/g, "/") - } - ); + const response = await directoryURL.listFilesAndDirectoriesSegment(Aborter.none, undefined, { + // NOTICE: Azure Storage Server will replace "\" with "/" in the file names + prefix: fileName.replace(/\\/g, "/") + }); assert.notDeepEqual(response.segment.fileItems.length, 0); }); it("Should work with special file name characters in URL string", async () => { - const fileName: string = getUniqueName( - "汉字. special ~!@#$%^&()_+`1234567890-={}[];','" - ); + const fileName: string = getUniqueName("汉字. special ~!@#$%^&()_+`1234567890-={}[];','"); const fileURL = new FileURL( // There are 2 special cases for a URL string: // Escape "%" when creating XXXURL object with URL strings // Escape "?" otherwise string after "?" will be treated as URL parameters - appendToURLPath( - directoryURL.url, - fileName.replace(/%/g, "%25").replace(/\?/g, "%3F") - ), + appendToURLPath(directoryURL.url, fileName.replace(/%/g, "%25").replace(/\?/g, "%3F")), directoryURL.pipeline ); await fileURL.create(Aborter.none, 10); await fileURL.getProperties(Aborter.none); - const response = await directoryURL.listFilesAndDirectoriesSegment( - Aborter.none, - undefined, - { - // NOTICE: Azure Storage Server will replace "\" with "/" in the file names - prefix: fileName.replace(/\\/g, "/") - } - ); + const response = await directoryURL.listFilesAndDirectoriesSegment(Aborter.none, undefined, { + // NOTICE: Azure Storage Server will replace "\" with "/" in the file names + prefix: fileName.replace(/\\/g, "/") + }); assert.notDeepEqual(response.segment.fileItems.length, 0); }); it("Should work with special directory name characters", async () => { - const directoryName: string = getUniqueName( - "汉字. special ~!@#$%^&()_+`1234567890-={}[];','" - ); - const specialDirectoryURL = DirectoryURL.fromShareURL( - shareURL, - directoryName - ); + const directoryName: string = getUniqueName("汉字. special ~!@#$%^&()_+`1234567890-={}[];','"); + const specialDirectoryURL = DirectoryURL.fromShareURL(shareURL, directoryName); const rootDirectoryURL = DirectoryURL.fromShareURL(shareURL, ""); await specialDirectoryURL.create(Aborter.none); @@ -198,17 +145,12 @@ describe("Special Naming Tests", () => { }); it("Should work with special directory name characters in URL string", async () => { - const directoryName: string = getUniqueName( - "汉字. special ~!@#$%^&()_+`1234567890-={}[];','" - ); + const directoryName: string = getUniqueName("汉字. special ~!@#$%^&()_+`1234567890-={}[];','"); const specialDirectoryURL = new DirectoryURL( // There are 2 special cases for a URL string: // Escape "%" when creating XXXURL object with URL strings // Escape "?" otherwise string after "?" will be treated as URL parameters - appendToURLPath( - shareURL.url, - directoryName.replace(/%/g, "%25").replace(/\?/g, "%3F") - ), + appendToURLPath(shareURL.url, directoryName.replace(/%/g, "%25").replace(/\?/g, "%3F")), shareURL.pipeline ); @@ -234,13 +176,9 @@ describe("Special Naming Tests", () => { await fileURL.create(Aborter.none, 10); await fileURL.getProperties(Aborter.none); - const response = await directoryURL.listFilesAndDirectoriesSegment( - Aborter.none, - undefined, - { - prefix: blobNameEncoded - } - ); + const response = await directoryURL.listFilesAndDirectoriesSegment(Aborter.none, undefined, { + prefix: blobNameEncoded + }); assert.notDeepEqual(response.segment.fileItems.length, 0); }); @@ -250,32 +188,21 @@ describe("Special Naming Tests", () => { await fileURL.create(Aborter.none, 10); await fileURL.getProperties(Aborter.none); - const response = await directoryURL.listFilesAndDirectoriesSegment( - Aborter.none, - undefined, - { - prefix: fileName - } - ); + const response = await directoryURL.listFilesAndDirectoriesSegment(Aborter.none, undefined, { + prefix: fileName + }); assert.notDeepEqual(response.segment.fileItems.length, 0); }); it("Should work with special file name Russian in URL string", async () => { const fileName: string = getUniqueName("ру́сский язы́к"); - const fileURL = new FileURL( - appendToURLPath(directoryURL.url, fileName), - directoryURL.pipeline - ); + const fileURL = new FileURL(appendToURLPath(directoryURL.url, fileName), directoryURL.pipeline); await fileURL.create(Aborter.none, 10); await fileURL.getProperties(Aborter.none); - const response = await directoryURL.listFilesAndDirectoriesSegment( - Aborter.none, - undefined, - { - prefix: fileName - } - ); + const response = await directoryURL.listFilesAndDirectoriesSegment(Aborter.none, undefined, { + prefix: fileName + }); assert.notDeepEqual(response.segment.fileItems.length, 0); }); @@ -286,13 +213,9 @@ describe("Special Naming Tests", () => { await fileURL.create(Aborter.none, 10); await fileURL.getProperties(Aborter.none); - const response = await directoryURL.listFilesAndDirectoriesSegment( - Aborter.none, - undefined, - { - prefix: blobNameEncoded - } - ); + const response = await directoryURL.listFilesAndDirectoriesSegment(Aborter.none, undefined, { + prefix: blobNameEncoded + }); assert.notDeepEqual(response.segment.fileItems.length, 0); }); @@ -302,32 +225,21 @@ describe("Special Naming Tests", () => { await fileURL.create(Aborter.none, 10); await fileURL.getProperties(Aborter.none); - const response = await directoryURL.listFilesAndDirectoriesSegment( - Aborter.none, - undefined, - { - prefix: fileName - } - ); + const response = await directoryURL.listFilesAndDirectoriesSegment(Aborter.none, undefined, { + prefix: fileName + }); assert.notDeepEqual(response.segment.fileItems.length, 0); }); it("Should work with special file name Arabic in URL string", async () => { const fileName: string = getUniqueName("عربيعربى"); - const fileURL = new FileURL( - appendToURLPath(directoryURL.url, fileName), - directoryURL.pipeline - ); + const fileURL = new FileURL(appendToURLPath(directoryURL.url, fileName), directoryURL.pipeline); await fileURL.create(Aborter.none, 10); await fileURL.getProperties(Aborter.none); - const response = await directoryURL.listFilesAndDirectoriesSegment( - Aborter.none, - undefined, - { - prefix: fileName - } - ); + const response = await directoryURL.listFilesAndDirectoriesSegment(Aborter.none, undefined, { + prefix: fileName + }); assert.notDeepEqual(response.segment.fileItems.length, 0); }); @@ -338,13 +250,9 @@ describe("Special Naming Tests", () => { await fileURL.create(Aborter.none, 10); await fileURL.getProperties(Aborter.none); - const response = await directoryURL.listFilesAndDirectoriesSegment( - Aborter.none, - undefined, - { - prefix: blobNameEncoded - } - ); + const response = await directoryURL.listFilesAndDirectoriesSegment(Aborter.none, undefined, { + prefix: blobNameEncoded + }); assert.notDeepEqual(response.segment.fileItems.length, 0); }); @@ -354,32 +262,21 @@ describe("Special Naming Tests", () => { await fileURL.create(Aborter.none, 10); await fileURL.getProperties(Aborter.none); - const response = await directoryURL.listFilesAndDirectoriesSegment( - Aborter.none, - undefined, - { - prefix: fileName - } - ); + const response = await directoryURL.listFilesAndDirectoriesSegment(Aborter.none, undefined, { + prefix: fileName + }); assert.notDeepEqual(response.segment.fileItems.length, 0); }); it("Should work with special file name Japanese in URL string", async () => { const fileName: string = getUniqueName("にっぽんごにほんご"); - const fileURL = new FileURL( - appendToURLPath(directoryURL.url, fileName), - directoryURL.pipeline - ); + const fileURL = new FileURL(appendToURLPath(directoryURL.url, fileName), directoryURL.pipeline); await fileURL.create(Aborter.none, 10); await fileURL.getProperties(Aborter.none); - const response = await directoryURL.listFilesAndDirectoriesSegment( - Aborter.none, - undefined, - { - prefix: fileName - } - ); + const response = await directoryURL.listFilesAndDirectoriesSegment(Aborter.none, undefined, { + prefix: fileName + }); assert.notDeepEqual(response.segment.fileItems.length, 0); }); }); diff --git a/sdk/storage/storage-file/test/utils/InjectorPolicy.ts b/sdk/storage/storage-file/test/utils/InjectorPolicy.ts index 87dcc133dcf9..3d41732dcddb 100644 --- a/sdk/storage/storage-file/test/utils/InjectorPolicy.ts +++ b/sdk/storage/storage-file/test/utils/InjectorPolicy.ts @@ -27,11 +27,7 @@ export class InjectorPolicy extends BaseRequestPolicy { * @param {RequestPolicyOptions} options * @memberof InjectorPolicy */ - public constructor( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions, - injector: Injector - ) { + public constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, injector: Injector) { super(nextPolicy, options); this.injector = injector; } @@ -43,9 +39,7 @@ export class InjectorPolicy extends BaseRequestPolicy { * @returns {Promise} * @memberof InjectorPolicy */ - public async sendRequest( - request: WebResource - ): Promise { + public async sendRequest(request: WebResource): Promise { const error = this.injector(); if (error) { throw error; diff --git a/sdk/storage/storage-file/test/utils/InjectorPolicyFactory.ts b/sdk/storage/storage-file/test/utils/InjectorPolicyFactory.ts index c1f478b9b226..ebd5412e76d5 100644 --- a/sdk/storage/storage-file/test/utils/InjectorPolicyFactory.ts +++ b/sdk/storage/storage-file/test/utils/InjectorPolicyFactory.ts @@ -1,8 +1,4 @@ -import { - RequestPolicy, - RequestPolicyFactory, - RequestPolicyOptions -} from "../../src"; +import { RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "../../src"; import { InjectorPolicy, Injector } from "./InjectorPolicy"; /** @@ -19,10 +15,7 @@ export class InjectorPolicyFactory implements RequestPolicyFactory { this.injector = injector; } - public create( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions - ): InjectorPolicy { + public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): InjectorPolicy { return new InjectorPolicy(nextPolicy, options, this.injector); } } diff --git a/sdk/storage/storage-file/test/utils/index.browser.ts b/sdk/storage/storage-file/test/utils/index.browser.ts index 8514c6938719..c87d3be4cc4b 100644 --- a/sdk/storage/storage-file/test/utils/index.browser.ts +++ b/sdk/storage/storage-file/test/utils/index.browser.ts @@ -4,10 +4,7 @@ import { StorageURL } from "../../src/StorageURL"; export * from "./testutils.common"; -export function getGenericBSU( - accountType: string, - accountNameSuffix: string = "" -): ServiceURL { +export function getGenericBSU(accountType: string, accountNameSuffix: string = ""): ServiceURL { const accountNameEnvVar = `${accountType}ACCOUNT_NAME`; const accountSASEnvVar = `${accountType}ACCOUNT_SAS`; @@ -84,10 +81,7 @@ export async function blobToArrayBuffer(blob: Blob): Promise { }); } -export function arrayBufferEqual( - buf1: ArrayBuffer, - buf2: ArrayBuffer -): boolean { +export function arrayBufferEqual(buf1: ArrayBuffer, buf2: ArrayBuffer): boolean { if (buf1.byteLength !== buf2.byteLength) { return false; } diff --git a/sdk/storage/storage-file/test/utils/index.ts b/sdk/storage/storage-file/test/utils/index.ts index 2077373c98dc..fe1d61c81d45 100644 --- a/sdk/storage/storage-file/test/utils/index.ts +++ b/sdk/storage/storage-file/test/utils/index.ts @@ -9,10 +9,7 @@ import { getUniqueName } from "./testutils.common"; export * from "./testutils.common"; -export function getGenericBSU( - accountType: string, - accountNameSuffix: string = "" -): ServiceURL { +export function getGenericBSU(accountType: string, accountNameSuffix: string = ""): ServiceURL { const accountNameEnvVar = `${accountType}ACCOUNT_NAME`; const accountKeyEnvVar = `${accountType}ACCOUNT_KEY`; @@ -112,10 +109,7 @@ export async function createRandomLocalFile( // Returns a Promise which is completed after the file handle is closed. // If Promise is rejected, the reason will be set to the first error raised by either the // ReadableStream or the fs.WriteStream. -export async function readStreamToLocalFile( - rs: NodeJS.ReadableStream, - file: string -) { +export async function readStreamToLocalFile(rs: NodeJS.ReadableStream, file: string) { return new Promise((resolve, reject) => { const ws = fs.createWriteStream(file); @@ -134,7 +128,7 @@ export async function readStreamToLocalFile( ws.on("unpipe", () => console.log("ws.unpipe")); } - let error : Error; + let error: Error; rs.on("error", (err: Error) => { // First error wins diff --git a/sdk/storage/storage-file/test/utils/testutils.common.ts b/sdk/storage/storage-file/test/utils/testutils.common.ts index 4ec999c08633..de4d969696c9 100644 --- a/sdk/storage/storage-file/test/utils/testutils.common.ts +++ b/sdk/storage/storage-file/test/utils/testutils.common.ts @@ -14,7 +14,7 @@ export function getUniqueName(prefix: string): string { } export async function sleep(time: number): Promise { - return new Promise(resolve => { + return new Promise((resolve) => { setTimeout(resolve, time); }); } @@ -24,17 +24,13 @@ export function base64encode(content: string): string { } export function base64decode(encodedString: string): string { - return isBrowser() - ? atob(encodedString) - : Buffer.from(encodedString, "base64").toString(); + return isBrowser() ? atob(encodedString) : Buffer.from(encodedString, "base64").toString(); } export class ConsoleHttpPipelineLogger implements IHttpPipelineLogger { constructor(public minimumLogLevel: HttpPipelineLogLevel) {} public log(logLevel: HttpPipelineLogLevel, message: string): void { - const logMessage = `${new Date().toISOString()} ${ - HttpPipelineLogLevel[logLevel] - }: ${message}`; + const logMessage = `${new Date().toISOString()} ${HttpPipelineLogLevel[logLevel]}: ${message}`; switch (logLevel) { case HttpPipelineLogLevel.ERROR: // tslint:disable-next-line:no-console @@ -53,7 +49,7 @@ export class ConsoleHttpPipelineLogger implements IHttpPipelineLogger { } export async function wait(time: number): Promise { - return new Promise(resolve => { + return new Promise((resolve) => { setTimeout(resolve, time); }); } diff --git a/sdk/storage/storage-file/tsconfig.json b/sdk/storage/storage-file/tsconfig.json index 61885eb2e18c..e271ee388662 100644 --- a/sdk/storage/storage-file/tsconfig.json +++ b/sdk/storage/storage-file/tsconfig.json @@ -22,4 +22,4 @@ "compileOnSave": true, "exclude": ["node_modules", "./samples/*"], "include": ["./src/**/*.ts", "./test/**/*.ts"] -} \ No newline at end of file +} diff --git a/sdk/storage/storage-queue/.prettierignore b/sdk/storage/storage-queue/.prettierignore new file mode 100644 index 000000000000..3fd7f651ed5f --- /dev/null +++ b/sdk/storage/storage-queue/.prettierignore @@ -0,0 +1,2 @@ +src/generated/**/*.ts +package-lock.json diff --git a/sdk/storage/storage-queue/.prettierrc.json b/sdk/storage/storage-queue/.prettierrc.json deleted file mode 100644 index 1ca87ab7d8af..000000000000 --- a/sdk/storage/storage-queue/.prettierrc.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "singleQuote": false -} diff --git a/sdk/storage/storage-queue/gulpfile.js b/sdk/storage/storage-queue/gulpfile.js index e966445ed2b2..d094f97460cd 100644 --- a/sdk/storage/storage-queue/gulpfile.js +++ b/sdk/storage/storage-queue/gulpfile.js @@ -5,13 +5,9 @@ const version = require("./package.json").version; const zipFileName = `azurestoragejs.queue-${version}.zip`; gulp.task("zip", function(callback) { - gulp - .src([ - "browser/azure-storage.queue.js", - "browser/azure-storage.queue.min.js", - "browser/*.txt" - ]) - .pipe(zip(zipFileName)) - .pipe(gulp.dest("browser")) - .on("end", callback); -}); \ No newline at end of file + gulp + .src(["browser/azure-storage.queue.js", "browser/azure-storage.queue.min.js", "browser/*.txt"]) + .pipe(zip(zipFileName)) + .pipe(gulp.dest("browser")) + .on("end", callback); +}); diff --git a/sdk/storage/storage-queue/karma.conf.js b/sdk/storage/storage-queue/karma.conf.js index f4e5570b2382..0f2659a3760a 100644 --- a/sdk/storage/storage-queue/karma.conf.js +++ b/sdk/storage/storage-queue/karma.conf.js @@ -1,119 +1,119 @@ // https://github.com/karma-runner/karma-chrome-launcher process.env.CHROME_BIN = require("puppeteer").executablePath(); -require("dotenv").config({path:"../.env"}); +require("dotenv").config({ path: "../.env" }); module.exports = function(config) { - config.set({ - // base path that will be used to resolve all patterns (eg. files, exclude) - basePath: "./", - - // frameworks to use - // available frameworks: https://npmjs.org/browse/keyword/karma-adapter - frameworks: ["mocha"], - - plugins: [ - "karma-mocha", - "karma-mocha-reporter", - "karma-chrome-launcher", - "karma-edge-launcher", - "karma-firefox-launcher", - "karma-ie-launcher", - "karma-env-preprocessor", - "karma-coverage", - "karma-remap-coverage", - "karma-junit-reporter" - ], - - // list of files / patterns to load in the browser - files: [ - // polyfill service supporting IE11 missing features - // Promise,String.prototype.startsWith,String.prototype.endsWith,String.prototype.repeat,String.prototype.includes,Array.prototype.includes,Object.keys - "https://cdn.polyfill.io/v2/polyfill.js?features=Promise,String.prototype.startsWith,String.prototype.endsWith,String.prototype.repeat,String.prototype.includes,Array.prototype.includes,Object.keys|always", - "dist-test/index.browser.js" - ], - - // list of files / patterns to exclude - exclude: [], - - // preprocess matching files before serving them to the browser - // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor - preprocessors: { - "**/*.js": ["env"], - // IMPORTANT: COMMENT following line if you want to debug in your browsers!! - // Preprocess source file to calculate code coverage, however this will make source file unreadable - "dist-test/index.browser.js": ["coverage"] - }, - - // inject following environment values into browser testing with window.__env__ - // environment values MUST be exported or set with same console running "karma start" - // https://www.npmjs.com/package/karma-env-preprocessor - envPreprocessor: ["ACCOUNT_NAME", "ACCOUNT_SAS"], - - // test results reporter to use - // possible values: 'dots', 'progress' - // available reporters: https://npmjs.org/browse/keyword/karma-reporter - reporters: ["mocha", "coverage", "remap-coverage", "junit"], - - coverageReporter: { type: "in-memory" }, - - // Coverage report settings - remapCoverageReporter: { - "text-summary": null, // to show summary in console - html: "./coverage-browser", - cobertura: "./coverage-browser/cobertura-coverage.xml" - }, - - // Exclude coverage calculation for following files - remapOptions: { - exclude: /node_modules|tests/g - }, - - junitReporter: { - outputDir: "", // results will be saved as $outputDir/$browserName.xml - outputFile: "test-results.browser.xml", // if included, results will be saved as $outputDir/$browserName/$outputFile - suite: "", // suite will become the package name attribute in xml testsuite element - useBrowserName: false, // add browser name to report and classes names - nameFormatter: undefined, // function (browser, result) to customize the name attribute in xml testcase element - classNameFormatter: undefined, // function (browser, result) to customize the classname attribute in xml testcase element - properties: {} // key value pair of properties to add to the section of the report - }, - - // web server port - port: 9328, - - // enable / disable colors in the output (reporters and logs) - colors: true, - - // level of logging - // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG - logLevel: config.LOG_INFO, - - // enable / disable watching file and executing tests whenever any file changes - autoWatch: false, - - // start these browsers - // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher - // 'ChromeHeadless', 'Chrome', 'Firefox', 'Edge', 'IE' - browsers: ["ChromeHeadless"], - - // Continuous Integration mode - // if true, Karma captures browsers, runs the tests and exits - singleRun: false, - - // Concurrency level - // how many browser should be started simultaneous - concurrency: 1, - - browserNoActivityTimeout: 600000, - browserDisconnectTimeout: 10000, - browserDisconnectTolerance: 3, - - client: { - mocha: { - // change Karma's debug.html to the mocha web reporter - reporter: "html", - timeout: "600000" - } - } - }); -}; \ No newline at end of file + config.set({ + // base path that will be used to resolve all patterns (eg. files, exclude) + basePath: "./", + + // frameworks to use + // available frameworks: https://npmjs.org/browse/keyword/karma-adapter + frameworks: ["mocha"], + + plugins: [ + "karma-mocha", + "karma-mocha-reporter", + "karma-chrome-launcher", + "karma-edge-launcher", + "karma-firefox-launcher", + "karma-ie-launcher", + "karma-env-preprocessor", + "karma-coverage", + "karma-remap-coverage", + "karma-junit-reporter" + ], + + // list of files / patterns to load in the browser + files: [ + // polyfill service supporting IE11 missing features + // Promise,String.prototype.startsWith,String.prototype.endsWith,String.prototype.repeat,String.prototype.includes,Array.prototype.includes,Object.keys + "https://cdn.polyfill.io/v2/polyfill.js?features=Promise,String.prototype.startsWith,String.prototype.endsWith,String.prototype.repeat,String.prototype.includes,Array.prototype.includes,Object.keys|always", + "dist-test/index.browser.js" + ], + + // list of files / patterns to exclude + exclude: [], + + // preprocess matching files before serving them to the browser + // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor + preprocessors: { + "**/*.js": ["env"], + // IMPORTANT: COMMENT following line if you want to debug in your browsers!! + // Preprocess source file to calculate code coverage, however this will make source file unreadable + "dist-test/index.browser.js": ["coverage"] + }, + + // inject following environment values into browser testing with window.__env__ + // environment values MUST be exported or set with same console running "karma start" + // https://www.npmjs.com/package/karma-env-preprocessor + envPreprocessor: ["ACCOUNT_NAME", "ACCOUNT_SAS"], + + // test results reporter to use + // possible values: 'dots', 'progress' + // available reporters: https://npmjs.org/browse/keyword/karma-reporter + reporters: ["mocha", "coverage", "remap-coverage", "junit"], + + coverageReporter: { type: "in-memory" }, + + // Coverage report settings + remapCoverageReporter: { + "text-summary": null, // to show summary in console + html: "./coverage-browser", + cobertura: "./coverage-browser/cobertura-coverage.xml" + }, + + // Exclude coverage calculation for following files + remapOptions: { + exclude: /node_modules|tests/g + }, + + junitReporter: { + outputDir: "", // results will be saved as $outputDir/$browserName.xml + outputFile: "test-results.browser.xml", // if included, results will be saved as $outputDir/$browserName/$outputFile + suite: "", // suite will become the package name attribute in xml testsuite element + useBrowserName: false, // add browser name to report and classes names + nameFormatter: undefined, // function (browser, result) to customize the name attribute in xml testcase element + classNameFormatter: undefined, // function (browser, result) to customize the classname attribute in xml testcase element + properties: {} // key value pair of properties to add to the section of the report + }, + + // web server port + port: 9328, + + // enable / disable colors in the output (reporters and logs) + colors: true, + + // level of logging + // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG + logLevel: config.LOG_INFO, + + // enable / disable watching file and executing tests whenever any file changes + autoWatch: false, + + // start these browsers + // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher + // 'ChromeHeadless', 'Chrome', 'Firefox', 'Edge', 'IE' + browsers: ["ChromeHeadless"], + + // Continuous Integration mode + // if true, Karma captures browsers, runs the tests and exits + singleRun: false, + + // Concurrency level + // how many browser should be started simultaneous + concurrency: 1, + + browserNoActivityTimeout: 600000, + browserDisconnectTimeout: 10000, + browserDisconnectTolerance: 3, + + client: { + mocha: { + // change Karma's debug.html to the mocha web reporter + reporter: "html", + timeout: "600000" + } + } + }); +}; diff --git a/sdk/storage/storage-queue/package.json b/sdk/storage/storage-queue/package.json index 28abeb38700e..130356122833 100644 --- a/sdk/storage/storage-queue/package.json +++ b/sdk/storage/storage-queue/package.json @@ -71,10 +71,10 @@ "build:nodebrowser": "rollup -c 2>&1", "build:test": "npm run build:es6 && rollup -c rollup.test.config.js 2>&1", "build": "npm run build:es6 && npm run build:nodebrowser && npm run build:browserzip", - "check-format": "prettier --list-different --config .prettierrc.json \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", + "check-format": "prettier --list-different --config ../../.prettierrc.json \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", "clean": "rimraf dist dist-esm dist-test typings temp browser/*.js* browser/*.zip statistics.html coverage coverage-browser .nyc_output *.tgz *.log test*.xml TEST*.xml", "extract-api": "tsc -p . && api-extractor run --local", - "format": "prettier --write --config .prettierrc.json \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", + "format": "prettier --write --config ../../.prettierrc.json \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", "integration-test:browser": "karma start --single-run", "integration-test:node": "cross-env TS_NODE_COMPILER_OPTIONS=\"{\\\"module\\\": \\\"commonjs\\\"}\" nyc mocha --compilers ts-node/register --require source-map-support/register --reporter mocha-multi --reporter-options spec=-,mocha-junit-reporter=- --full-trace --no-timeouts test/*.test.ts test/node/*.test.ts", "integration-test": "npm run integration-test:node && npm run integration-test:browser", diff --git a/sdk/storage/storage-queue/rollup.config.js b/sdk/storage/storage-queue/rollup.config.js index edde22230377..9dd5f44ce62a 100644 --- a/sdk/storage/storage-queue/rollup.config.js +++ b/sdk/storage/storage-queue/rollup.config.js @@ -7,88 +7,88 @@ import shim from "rollup-plugin-shim"; const version = require("./package.json").version; const banner = [ - "/*!", - ` * Azure Storage SDK for JavaScript - Queue, ${version}`, - " * Copyright (c) Microsoft and contributors. All rights reserved.", - " */" + "/*!", + ` * Azure Storage SDK for JavaScript - Queue, ${version}`, + " * Copyright (c) Microsoft and contributors. All rights reserved.", + " */" ].join("\n"); const nodeRollupConfigFactory = () => { - return { - external: ["@azure/ms-rest-js", "crypto", "fs", "os"], - input: "dist-esm/src/index.js", - output: { - file: "dist/index.js", - format: "cjs", - sourcemap: true - }, - preserveSymlinks: false, - plugins: [nodeResolve(), uglify()] - }; + return { + external: ["@azure/ms-rest-js", "crypto", "fs", "os"], + input: "dist-esm/src/index.js", + output: { + file: "dist/index.js", + format: "cjs", + sourcemap: true + }, + preserveSymlinks: false, + plugins: [nodeResolve(), uglify()] + }; }; -const browserRollupConfigFactory = isProduction => { - const browserRollupConfig = { - input: "dist-esm/src/index.browser.js", - output: { - file: "browser/azure-storage.queue.js", - banner: banner, - format: "umd", - name: "azqueue", - sourcemap: true - }, - preserveSymlinks: false, - plugins: [ - replace({ - delimiters: ["", ""], - values: { - // replace dynamic checks with if (false) since this is for - // browser only. Rollup's dead code elimination will remove - // any code guarded by if (isNode) { ... } - "if (isNode)": "if (false)" - } - }), - // os is not used by the browser bundle, so just shim it - shim({ - dotenv: `export function config() { }`, - os: ` +const browserRollupConfigFactory = (isProduction) => { + const browserRollupConfig = { + input: "dist-esm/src/index.browser.js", + output: { + file: "browser/azure-storage.queue.js", + banner: banner, + format: "umd", + name: "azqueue", + sourcemap: true + }, + preserveSymlinks: false, + plugins: [ + replace({ + delimiters: ["", ""], + values: { + // replace dynamic checks with if (false) since this is for + // browser only. Rollup's dead code elimination will remove + // any code guarded by if (isNode) { ... } + "if (isNode)": "if (false)" + } + }), + // os is not used by the browser bundle, so just shim it + shim({ + dotenv: `export function config() { }`, + os: ` export const type = 1; export const release = 1; ` - }), - nodeResolve({ - mainFields: ['module', 'browser'], - preferBuiltins: false - }), - commonjs({ - namedExports: { - assert: ["ok", "deepEqual", "equal", "fail", "deepStrictEqual"] - } - }) - ] - }; + }), + nodeResolve({ + mainFields: ["module", "browser"], + preferBuiltins: false + }), + commonjs({ + namedExports: { + assert: ["ok", "deepEqual", "equal", "fail", "deepStrictEqual"] + } + }) + ] + }; - if (isProduction) { - browserRollupConfig.output.file = "browser/azure-storage.queue.min.js"; - browserRollupConfig.plugins.push( - uglify({ - output: { - preamble: banner - } - }) - // Comment visualizer because it only works on Node.js 8+; Uncomment it to get bundle analysis report - // visualizer({ - // filename: "./statistics.html", - // sourcemap: true - // }) - ); - } + if (isProduction) { + browserRollupConfig.output.file = "browser/azure-storage.queue.min.js"; + browserRollupConfig.plugins.push( + uglify({ + output: { + preamble: banner + } + }) + // Comment visualizer because it only works on Node.js 8+; Uncomment it to get bundle analysis report + // visualizer({ + // filename: "./statistics.html", + // sourcemap: true + // }) + ); + } - return browserRollupConfig; + return browserRollupConfig; }; export default [ - browserRollupConfigFactory(false), - browserRollupConfigFactory(true), - nodeRollupConfigFactory() -]; \ No newline at end of file + browserRollupConfigFactory(false), + browserRollupConfigFactory(true), + nodeRollupConfigFactory() +]; diff --git a/sdk/storage/storage-queue/rollup.test.config.js b/sdk/storage/storage-queue/rollup.test.config.js index c938a6ac63f6..24622435837c 100644 --- a/sdk/storage/storage-queue/rollup.test.config.js +++ b/sdk/storage/storage-queue/rollup.test.config.js @@ -10,4 +10,4 @@ browser.plugins.unshift(multi()); browser.plugins.unshift(sourcemaps()); browser.context = "null"; -export default [browser]; \ No newline at end of file +export default [browser]; diff --git a/sdk/storage/storage-queue/src/Aborter.ts b/sdk/storage/storage-queue/src/Aborter.ts index 7fa68611a9e3..7f1633f83887 100644 --- a/sdk/storage/storage-queue/src/Aborter.ts +++ b/sdk/storage/storage-queue/src/Aborter.ts @@ -59,16 +59,14 @@ export class Aborter implements AbortSignalLike { * * @memberof Aborter */ - public onabort?: ((ev?: Event) => any); + public onabort?: (ev?: Event) => any; // tslint:disable-next-line:variable-name private _aborted: boolean = false; private timer?: any; private readonly parent?: Aborter; private readonly children: Aborter[] = []; // When child object calls dispose(), remove child from here - private readonly abortEventListeners: Array< - (this: AbortSignalLike, ev?: any) => any - > = []; + private readonly abortEventListeners: Array<(this: AbortSignalLike, ev?: any) => any> = []; // Pipeline proxies need to use "abortSignal as Aborter" in order to access non AbortSignalLike methods // immutable primitive types private readonly key?: string; @@ -140,10 +138,7 @@ export class Aborter implements AbortSignalLike { * @returns {Aborter} * @memberof Aborter */ - public withValue( - key: string, - value?: string | number | boolean | null - ): Aborter { + public withValue(key: string, value?: string | number | boolean | null): Aborter { const childCancelContext = new Aborter(this, 0, key, value); this.children.push(childCancelContext); return childCancelContext; @@ -160,11 +155,7 @@ export class Aborter implements AbortSignalLike { * @memberof Aborter */ public getValue(key: string): string | number | boolean | null | undefined { - for ( - let parent: Aborter | undefined = this; - parent; - parent = parent.parent - ) { + for (let parent: Aborter | undefined = this; parent; parent = parent.parent) { if (parent.key === key) { return parent.value; } @@ -192,11 +183,11 @@ export class Aborter implements AbortSignalLike { this.onabort.call(this); } - this.abortEventListeners.forEach(listener => { + this.abortEventListeners.forEach((listener) => { listener.call(this, undefined); }); - this.children.forEach(child => child.cancelByParent()); + this.children.forEach((child) => child.cancelByParent()); this._aborted = true; } diff --git a/sdk/storage/storage-queue/src/BrowserPolicyFactory.ts b/sdk/storage/storage-queue/src/BrowserPolicyFactory.ts index 095475fb00ce..786d6d8e8137 100644 --- a/sdk/storage/storage-queue/src/BrowserPolicyFactory.ts +++ b/sdk/storage/storage-queue/src/BrowserPolicyFactory.ts @@ -1,8 +1,4 @@ -import { - RequestPolicy, - RequestPolicyFactory, - RequestPolicyOptions -} from "@azure/ms-rest-js"; +import { RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "@azure/ms-rest-js"; import { BrowserPolicy } from "./policies/BrowserPolicy"; @@ -14,10 +10,7 @@ import { BrowserPolicy } from "./policies/BrowserPolicy"; * @implements {RequestPolicyFactory} */ export class BrowserPolicyFactory implements RequestPolicyFactory { - public create( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions - ): BrowserPolicy { + public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): BrowserPolicy { return new BrowserPolicy(nextPolicy, options); } } diff --git a/sdk/storage/storage-queue/src/IAccountSASSignatureValues.ts b/sdk/storage/storage-queue/src/IAccountSASSignatureValues.ts index 34907b76dbe9..c93a6c567e3a 100644 --- a/sdk/storage/storage-queue/src/IAccountSASSignatureValues.ts +++ b/sdk/storage/storage-queue/src/IAccountSASSignatureValues.ts @@ -117,9 +117,7 @@ export function generateAccountSASQueryParameters( const parsedPermissions = AccountSASPermissions.parse( accountSASSignatureValues.permissions ).toString(); - const parsedServices = AccountSASServices.parse( - accountSASSignatureValues.services - ).toString(); + const parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString(); const parsedResourceTypes = AccountSASResourceTypes.parse( accountSASSignatureValues.resourceTypes ).toString(); @@ -133,12 +131,8 @@ export function generateAccountSASQueryParameters( ? truncatedISO8061Date(accountSASSignatureValues.startTime, false) : "", truncatedISO8061Date(accountSASSignatureValues.expiryTime, false), - accountSASSignatureValues.ipRange - ? ipRangeToString(accountSASSignatureValues.ipRange) - : "", - accountSASSignatureValues.protocol - ? accountSASSignatureValues.protocol - : "", + accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", + accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", version, "" // Account SAS requires an additional newline character ].join("\n"); diff --git a/sdk/storage/storage-queue/src/IQueueSASSignatureValues.ts b/sdk/storage/storage-queue/src/IQueueSASSignatureValues.ts index f62a9d7a8f5d..f96df7a36393 100644 --- a/sdk/storage/storage-queue/src/IQueueSASSignatureValues.ts +++ b/sdk/storage/storage-queue/src/IQueueSASSignatureValues.ts @@ -122,9 +122,7 @@ export function generateQueueSASQueryParameters( // Calling parse and toString guarantees the proper ordering and throws on invalid characters. if (queueSASSignatureValues.permissions) { - verifiedPermissions = QueueSASPermissions.parse( - queueSASSignatureValues.permissions - ).toString(); + verifiedPermissions = QueueSASPermissions.parse(queueSASSignatureValues.permissions).toString(); } // Signature is generated on the un-url-encoded values. @@ -136,14 +134,9 @@ export function generateQueueSASQueryParameters( queueSASSignatureValues.expiryTime ? truncatedISO8061Date(queueSASSignatureValues.expiryTime, false) : "", - getCanonicalName( - sharedKeyCredential.accountName, - queueSASSignatureValues.queueName - ), + getCanonicalName(sharedKeyCredential.accountName, queueSASSignatureValues.queueName), queueSASSignatureValues.identifier, - queueSASSignatureValues.ipRange - ? ipRangeToString(queueSASSignatureValues.ipRange) - : "", + queueSASSignatureValues.ipRange ? ipRangeToString(queueSASSignatureValues.ipRange) : "", queueSASSignatureValues.protocol ? queueSASSignatureValues.protocol : "", version ].join("\n"); @@ -164,10 +157,7 @@ export function generateQueueSASQueryParameters( ); } -function getCanonicalName( - accountName: string, - queueName: string -): string { +function getCanonicalName(accountName: string, queueName: string): string { // Queue: "/queue/account/queueName" return `/queue/${accountName}/${queueName}`; } diff --git a/sdk/storage/storage-queue/src/LoggingPolicyFactory.ts b/sdk/storage/storage-queue/src/LoggingPolicyFactory.ts index 29b9081d157d..d6f1057480b4 100644 --- a/sdk/storage/storage-queue/src/LoggingPolicyFactory.ts +++ b/sdk/storage/storage-queue/src/LoggingPolicyFactory.ts @@ -1,8 +1,4 @@ -import { - RequestPolicy, - RequestPolicyFactory, - RequestPolicyOptions -} from "@azure/ms-rest-js"; +import { RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "@azure/ms-rest-js"; import { LoggingPolicy } from "./policies/LoggingPolicy"; @@ -36,10 +32,7 @@ export class LoggingPolicyFactory implements RequestPolicyFactory { this.loggingOptions = loggingOptions; } - public create( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions - ): LoggingPolicy { + public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): LoggingPolicy { return new LoggingPolicy(nextPolicy, options, this.loggingOptions); } } diff --git a/sdk/storage/storage-queue/src/MessageIdURL.ts b/sdk/storage/storage-queue/src/MessageIdURL.ts index 4ec0ff9bb475..306335be73a9 100644 --- a/sdk/storage/storage-queue/src/MessageIdURL.ts +++ b/sdk/storage/storage-queue/src/MessageIdURL.ts @@ -19,14 +19,8 @@ export class MessageIdURL extends StorageURL { * @param messagesURL * @param messageId */ - public static fromMessagesURL( - messagesURL: MessagesURL, - messageId: string - ): MessageIdURL { - return new MessageIdURL( - appendToURLPath(messagesURL.url, messageId), - messagesURL.pipeline - ); + public static fromMessagesURL(messagesURL: MessagesURL, messageId: string): MessageIdURL { + return new MessageIdURL(appendToURLPath(messagesURL.url, messageId), messagesURL.pipeline); } /** @@ -86,8 +80,8 @@ export class MessageIdURL extends StorageURL { /** * Update changes a message's visibility timeout and contents. - * The message content is up to 64KB in size, and must be in a format that can be included in an XML request with UTF-8 encoding. - * To include markup in the message, the contents of the message must either be XML-escaped or Base64-encode. + * The message content is up to 64KB in size, and must be in a format that can be included in an XML request with UTF-8 encoding. + * To include markup in the message, the contents of the message must either be XML-escaped or Base64-encode. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/update-message * * @param {Aborter} aborter Create a new Aborter instance with Aborter.none or Aborter.timeout(), diff --git a/sdk/storage/storage-queue/src/MessagesURL.ts b/sdk/storage/storage-queue/src/MessagesURL.ts index a65cd418fd94..28d9656bb014 100644 --- a/sdk/storage/storage-queue/src/MessagesURL.ts +++ b/sdk/storage/storage-queue/src/MessagesURL.ts @@ -111,10 +111,7 @@ export class MessagesURL extends StorageURL { * @param queueName */ public static fromQueueURL(queueURL: QueueURL): MessagesURL { - return new MessagesURL( - appendToURLPath(queueURL.url, "messages"), - queueURL.pipeline - ); + return new MessagesURL(appendToURLPath(queueURL.url, "messages"), queueURL.pipeline); } /** @@ -171,8 +168,8 @@ export class MessagesURL extends StorageURL { /** * Enqueue adds a new message to the back of a queue. The visibility timeout specifies how long * the message should be invisible to Dequeue and Peek operations. - * The message content is up to 64KB in size, and must be in a format that can be included in an XML request with UTF-8 encoding. - * To include markup in the message, the contents of the message must either be XML-escaped or Base64-encode. + * The message content is up to 64KB in size, and must be in a format that can be included in an XML request with UTF-8 encoding. + * To include markup in the message, the contents of the message must either be XML-escaped or Base64-encode. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-message * * @param {Aborter} aborter Create a new Aborter instance with Aborter.none or Aborter.timeout(), diff --git a/sdk/storage/storage-queue/src/Pipeline.ts b/sdk/storage/storage-queue/src/Pipeline.ts index fd3af1c23ed5..01c05b7a8ec7 100644 --- a/sdk/storage/storage-queue/src/Pipeline.ts +++ b/sdk/storage/storage-queue/src/Pipeline.ts @@ -61,10 +61,7 @@ export class Pipeline { * @param {IPipelineOptions} [options={}] * @memberof Pipeline */ - constructor( - factories: RequestPolicyFactory[], - options: IPipelineOptions = {} - ) { + constructor(factories: RequestPolicyFactory[], options: IPipelineOptions = {}) { this.factories = factories; this.options = options; } diff --git a/sdk/storage/storage-queue/src/QueueURL.ts b/sdk/storage/storage-queue/src/QueueURL.ts index 13175e202aaa..f67da72aa7e0 100644 --- a/sdk/storage/storage-queue/src/QueueURL.ts +++ b/sdk/storage/storage-queue/src/QueueURL.ts @@ -72,14 +72,8 @@ export class QueueURL extends StorageURL { * @param serviceURL * @param queueName */ - public static fromServiceURL( - serviceURL: ServiceURL, - queueName: string - ): QueueURL { - return new QueueURL( - appendToURLPath(serviceURL.url, queueName), - serviceURL.pipeline - ); + public static fromServiceURL(serviceURL: ServiceURL, queueName: string): QueueURL { + return new QueueURL(appendToURLPath(serviceURL.url, queueName), serviceURL.pipeline); } /** @@ -148,9 +142,7 @@ export class QueueURL extends StorageURL { * @returns {Promise} * @memberof QueueURL */ - public async getProperties( - aborter: Aborter - ): Promise { + public async getProperties(aborter: Aborter): Promise { return this.queueContext.getProperties({ abortSignal: aborter }); @@ -208,9 +200,7 @@ export class QueueURL extends StorageURL { * @returns {Promise} * @memberof QueueURL */ - public async getAccessPolicy( - aborter: Aborter - ): Promise { + public async getAccessPolicy(aborter: Aborter): Promise { const response = await this.queueContext.getAccessPolicy({ abortSignal: aborter }); diff --git a/sdk/storage/storage-queue/src/RetryPolicyFactory.ts b/sdk/storage/storage-queue/src/RetryPolicyFactory.ts index 1ae647a0c064..670a370b41ac 100644 --- a/sdk/storage/storage-queue/src/RetryPolicyFactory.ts +++ b/sdk/storage/storage-queue/src/RetryPolicyFactory.ts @@ -1,8 +1,4 @@ -import { - RequestPolicy, - RequestPolicyFactory, - RequestPolicyOptions -} from "@azure/ms-rest-js"; +import { RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "@azure/ms-rest-js"; import { RetryPolicy, RetryPolicyType } from "./policies/RetryPolicy"; @@ -94,10 +90,7 @@ export class RetryPolicyFactory implements RequestPolicyFactory { this.retryOptions = retryOptions; } - public create( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions - ): RetryPolicy { + public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): RetryPolicy { return new RetryPolicy(nextPolicy, options, this.retryOptions); } } diff --git a/sdk/storage/storage-queue/src/SASQueryParameters.ts b/sdk/storage/storage-queue/src/SASQueryParameters.ts index c2fe81d00a69..8a747c24ae42 100644 --- a/sdk/storage/storage-queue/src/SASQueryParameters.ts +++ b/sdk/storage/storage-queue/src/SASQueryParameters.ts @@ -192,19 +192,7 @@ export class SASQueryParameters { * @memberof SASQueryParameters */ public toString(): string { - const params: string[] = [ - "sv", - "ss", - "srt", - "spr", - "st", - "se", - "sip", - "si", - "sr", - "sp", - "sig" - ]; + const params: string[] = ["sv", "ss", "srt", "spr", "st", "se", "sip", "si", "sr", "sp", "sig"]; const queries: string[] = []; for (const param of params) { @@ -225,18 +213,14 @@ export class SASQueryParameters { this.tryAppendQueryParameter( queries, param, - this.startTime - ? truncatedISO8061Date(this.startTime, false) - : undefined + this.startTime ? truncatedISO8061Date(this.startTime, false) : undefined ); break; case "se": this.tryAppendQueryParameter( queries, param, - this.expiryTime - ? truncatedISO8061Date(this.expiryTime, false) - : undefined + this.expiryTime ? truncatedISO8061Date(this.expiryTime, false) : undefined ); break; case "sip": @@ -273,11 +257,7 @@ export class SASQueryParameters { * @returns {void} * @memberof SASQueryParameters */ - private tryAppendQueryParameter( - queries: string[], - key: string, - value?: string - ): void { + private tryAppendQueryParameter(queries: string[], key: string, value?: string): void { if (!value) { return; } diff --git a/sdk/storage/storage-queue/src/ServiceURL.ts b/sdk/storage/storage-queue/src/ServiceURL.ts index d39deba82168..2d77645d0c32 100644 --- a/sdk/storage/storage-queue/src/ServiceURL.ts +++ b/sdk/storage/storage-queue/src/ServiceURL.ts @@ -83,9 +83,7 @@ export class ServiceURL extends StorageURL { * @returns {Promise} * @memberof ServiceURL */ - public async getProperties( - aborter: Aborter - ): Promise { + public async getProperties(aborter: Aborter): Promise { return this.serviceContext.getProperties({ abortSignal: aborter }); @@ -122,9 +120,7 @@ export class ServiceURL extends StorageURL { * @returns {Promise} * @memberof ServiceURL */ - public async getStatistics( - aborter: Aborter - ): Promise { + public async getStatistics(aborter: Aborter): Promise { return this.serviceContext.getStatistics({ abortSignal: aborter }); diff --git a/sdk/storage/storage-queue/src/StorageURL.ts b/sdk/storage/storage-queue/src/StorageURL.ts index a2f7efd48a10..cec792d2d5ae 100644 --- a/sdk/storage/storage-queue/src/StorageURL.ts +++ b/sdk/storage/storage-queue/src/StorageURL.ts @@ -6,10 +6,7 @@ import { StorageClientContext } from "./generated/lib/storageClientContext"; import { LoggingPolicyFactory } from "./LoggingPolicyFactory"; import { IHttpClient, IHttpPipelineLogger, Pipeline } from "./Pipeline"; import { IRetryOptions, RetryPolicyFactory } from "./RetryPolicyFactory"; -import { - ITelemetryOptions, - TelemetryPolicyFactory -} from "./TelemetryPolicyFactory"; +import { ITelemetryOptions, TelemetryPolicyFactory } from "./TelemetryPolicyFactory"; import { UniqueRequestIDPolicyFactory } from "./UniqueRequestIDPolicyFactory"; export { deserializationPolicy }; @@ -109,11 +106,8 @@ export abstract class StorageURL { protected constructor(url: string, pipeline: Pipeline) { this.url = url; this.pipeline = pipeline; - this.storageClientContext = new StorageClientContext( - url, - pipeline.toServiceClientOptions() - ); - + this.storageClientContext = new StorageClientContext(url, pipeline.toServiceClientOptions()); + // Override protocol layer's default content-type const storageClientContext = this.storageClientContext as any; storageClientContext.requestContentType = undefined; diff --git a/sdk/storage/storage-queue/src/TelemetryPolicyFactory.ts b/sdk/storage/storage-queue/src/TelemetryPolicyFactory.ts index 5d53fc5a876a..a75dad719028 100644 --- a/sdk/storage/storage-queue/src/TelemetryPolicyFactory.ts +++ b/sdk/storage/storage-queue/src/TelemetryPolicyFactory.ts @@ -40,10 +40,7 @@ export class TelemetryPolicyFactory implements RequestPolicyFactory { if (isNode) { if (telemetry) { const telemetryString = telemetry.value; - if ( - telemetryString.length > 0 && - userAgentInfo.indexOf(telemetryString) === -1 - ) { + if (telemetryString.length > 0 && userAgentInfo.indexOf(telemetryString) === -1) { userAgentInfo.push(telemetryString); } } @@ -55,9 +52,7 @@ export class TelemetryPolicyFactory implements RequestPolicyFactory { } // e.g. (NODE-VERSION 4.9.1; Windows_NT 10.0.16299) - const runtimeInfo = `(NODE-VERSION ${ - process.version - }; ${os.type()} ${os.release()})`; + const runtimeInfo = `(NODE-VERSION ${process.version}; ${os.type()} ${os.release()})`; if (userAgentInfo.indexOf(runtimeInfo) === -1) { userAgentInfo.push(runtimeInfo); } @@ -66,10 +61,7 @@ export class TelemetryPolicyFactory implements RequestPolicyFactory { this.telemetryString = userAgentInfo.join(" "); } - public create( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions - ): TelemetryPolicy { + public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): TelemetryPolicy { return new TelemetryPolicy(nextPolicy, options, this.telemetryString); } } diff --git a/sdk/storage/storage-queue/src/UniqueRequestIDPolicyFactory.ts b/sdk/storage/storage-queue/src/UniqueRequestIDPolicyFactory.ts index d586a6fa8fc6..6610c6ff3b53 100644 --- a/sdk/storage/storage-queue/src/UniqueRequestIDPolicyFactory.ts +++ b/sdk/storage/storage-queue/src/UniqueRequestIDPolicyFactory.ts @@ -1,8 +1,4 @@ -import { - RequestPolicy, - RequestPolicyFactory, - RequestPolicyOptions -} from "@azure/ms-rest-js"; +import { RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "@azure/ms-rest-js"; import { UniqueRequestIDPolicy } from "./policies/UniqueRequestIDPolicy"; @@ -14,10 +10,7 @@ import { UniqueRequestIDPolicy } from "./policies/UniqueRequestIDPolicy"; * @implements {RequestPolicyFactory} */ export class UniqueRequestIDPolicyFactory implements RequestPolicyFactory { - public create( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions - ): UniqueRequestIDPolicy { + public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): UniqueRequestIDPolicy { return new UniqueRequestIDPolicy(nextPolicy, options); } } diff --git a/sdk/storage/storage-queue/src/credentials/Credential.ts b/sdk/storage/storage-queue/src/credentials/Credential.ts index d87d71befb84..ba47b60f6d5d 100644 --- a/sdk/storage/storage-queue/src/credentials/Credential.ts +++ b/sdk/storage/storage-queue/src/credentials/Credential.ts @@ -1,8 +1,4 @@ -import { - RequestPolicy, - RequestPolicyFactory, - RequestPolicyOptions -} from "@azure/ms-rest-js"; +import { RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "@azure/ms-rest-js"; import { CredentialPolicy } from "../policies/CredentialPolicy"; diff --git a/sdk/storage/storage-queue/src/credentials/TokenCredential.ts b/sdk/storage/storage-queue/src/credentials/TokenCredential.ts index b14b71555e1a..862d98a951d6 100644 --- a/sdk/storage/storage-queue/src/credentials/TokenCredential.ts +++ b/sdk/storage/storage-queue/src/credentials/TokenCredential.ts @@ -55,10 +55,7 @@ export class TokenCredential extends Credential { * @returns {TokenCredentialPolicy} * @memberof TokenCredential */ - public create( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions - ): TokenCredentialPolicy { + public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): TokenCredentialPolicy { return new TokenCredentialPolicy(nextPolicy, options, this); } } diff --git a/sdk/storage/storage-queue/src/index.browser.ts b/sdk/storage/storage-queue/src/index.browser.ts index b8ba37ab2ca8..c482b05d79be 100644 --- a/sdk/storage/storage-queue/src/index.browser.ts +++ b/sdk/storage/storage-queue/src/index.browser.ts @@ -16,7 +16,7 @@ export * from "./RetryPolicyFactory"; export * from "./LoggingPolicyFactory"; export * from "./TelemetryPolicyFactory"; export * from "./policies/TokenCredentialPolicy"; -export * from "./QueueURL" +export * from "./QueueURL"; export * from "./QueueSASPermissions"; export * from "./UniqueRequestIDPolicyFactory"; export * from "./ServiceURL"; diff --git a/sdk/storage/storage-queue/src/index.ts b/sdk/storage/storage-queue/src/index.ts index e129ad096855..b7863b153798 100644 --- a/sdk/storage/storage-queue/src/index.ts +++ b/sdk/storage/storage-queue/src/index.ts @@ -22,9 +22,9 @@ export * from "./LoggingPolicyFactory"; export * from "./policies/SharedKeyCredentialPolicy"; export * from "./TelemetryPolicyFactory"; export * from "./policies/TokenCredentialPolicy"; -export * from "./QueueURL" +export * from "./QueueURL"; export * from "./QueueSASPermissions"; -export * from "./IQueueSASSignatureValues" +export * from "./IQueueSASSignatureValues"; export * from "./UniqueRequestIDPolicyFactory"; export * from "./ServiceURL"; export * from "./StorageURL"; diff --git a/sdk/storage/storage-queue/src/models.ts b/sdk/storage/storage-queue/src/models.ts index 737bf9d7f712..38beb06f8eb2 100644 --- a/sdk/storage/storage-queue/src/models.ts +++ b/sdk/storage/storage-queue/src/models.ts @@ -1,3 +1,3 @@ export interface IMetadata { [propertyName: string]: string; -} \ No newline at end of file +} diff --git a/sdk/storage/storage-queue/src/policies/BrowserPolicy.ts b/sdk/storage/storage-queue/src/policies/BrowserPolicy.ts index 054a67c29f13..da28a835c088 100644 --- a/sdk/storage/storage-queue/src/policies/BrowserPolicy.ts +++ b/sdk/storage/storage-queue/src/policies/BrowserPolicy.ts @@ -42,17 +42,12 @@ export class BrowserPolicy extends BaseRequestPolicy { * @returns {Promise} * @memberof BrowserPolicy */ - public async sendRequest( - request: WebResource - ): Promise { + public async sendRequest(request: WebResource): Promise { if (isNode) { return this._nextPolicy.sendRequest(request); } - if ( - request.method.toUpperCase() === "GET" || - request.method.toUpperCase() === "HEAD" - ) { + if (request.method.toUpperCase() === "GET" || request.method.toUpperCase() === "HEAD") { request.url = setURLParameter( request.url, URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, diff --git a/sdk/storage/storage-queue/src/policies/CredentialPolicy.ts b/sdk/storage/storage-queue/src/policies/CredentialPolicy.ts index ee09c0e002b9..9a25c8b94b2a 100644 --- a/sdk/storage/storage-queue/src/policies/CredentialPolicy.ts +++ b/sdk/storage/storage-queue/src/policies/CredentialPolicy.ts @@ -1,8 +1,4 @@ -import { - BaseRequestPolicy, - HttpOperationResponse, - WebResource -} from "@azure/ms-rest-js"; +import { BaseRequestPolicy, HttpOperationResponse, WebResource } from "@azure/ms-rest-js"; /** * Credential policy used to sign HTTP(S) requests before sending. This is an diff --git a/sdk/storage/storage-queue/src/policies/LoggingPolicy.ts b/sdk/storage/storage-queue/src/policies/LoggingPolicy.ts index 51fdb8307f64..0d1fa108a316 100644 --- a/sdk/storage/storage-queue/src/policies/LoggingPolicy.ts +++ b/sdk/storage/storage-queue/src/policies/LoggingPolicy.ts @@ -52,9 +52,7 @@ export class LoggingPolicy extends BaseRequestPolicy { * @returns {Promise} * @memberof LoggingPolicy */ - public async sendRequest( - request: WebResource - ): Promise { + public async sendRequest(request: WebResource): Promise { this.tryCount++; this.requestStartTime = new Date(); if (this.tryCount === 1) { @@ -63,11 +61,7 @@ export class LoggingPolicy extends BaseRequestPolicy { let safeURL: string = request.url; if (getURLParameter(safeURL, URLConstants.Parameters.SIGNATURE)) { - safeURL = setURLParameter( - safeURL, - URLConstants.Parameters.SIGNATURE, - "*****" - ); + safeURL = setURLParameter(safeURL, URLConstants.Parameters.SIGNATURE, "*****"); } this.log( HttpPipelineLogLevel.INFO, @@ -78,10 +72,8 @@ export class LoggingPolicy extends BaseRequestPolicy { const response = await this._nextPolicy.sendRequest(request); const requestEndTime = new Date(); - const requestCompletionTime = - requestEndTime.getTime() - this.requestStartTime.getTime(); - const operationDuration = - requestEndTime.getTime() - this.operationStartTime.getTime(); + const requestCompletionTime = requestEndTime.getTime() - this.requestStartTime.getTime(); + const operationDuration = requestEndTime.getTime() - this.operationStartTime.getTime(); let currentLevel: HttpPipelineLogLevel = HttpPipelineLogLevel.INFO; let logMessage: string = ""; @@ -91,10 +83,7 @@ export class LoggingPolicy extends BaseRequestPolicy { } // If the response took too long, we'll upgrade to warning. - if ( - requestCompletionTime >= - this.loggingOptions.logWarningIfTryOverThreshold - ) { + if (requestCompletionTime >= this.loggingOptions.logWarningIfTryOverThreshold) { // Log a warning if the try duration exceeded the specified threshold. if (this.shouldLog(HttpPipelineLogLevel.WARNING)) { currentLevel = HttpPipelineLogLevel.WARNING; @@ -110,8 +99,7 @@ export class LoggingPolicy extends BaseRequestPolicy { (response.status !== HTTPURLConnection.HTTP_NOT_FOUND && response.status !== HTTPURLConnection.HTTP_CONFLICT && response.status !== HTTPURLConnection.HTTP_PRECON_FAILED && - response.status !== - HTTPURLConnection.HTTP_RANGE_NOT_SATISFIABLE)) || + response.status !== HTTPURLConnection.HTTP_RANGE_NOT_SATISFIABLE)) || (response.status >= 500 && response.status <= 509) ) { const errorString = `REQUEST ERROR: HTTP request failed with status code: ${ @@ -131,9 +119,7 @@ export class LoggingPolicy extends BaseRequestPolicy { } catch (err) { this.log( HttpPipelineLogLevel.ERROR, - `Unexpected failure attempting to make request. Error message: ${ - err.message - }` + `Unexpected failure attempting to make request. Error message: ${err.message}` ); throw err; } diff --git a/sdk/storage/storage-queue/src/policies/RetryPolicy.ts b/sdk/storage/storage-queue/src/policies/RetryPolicy.ts index 8d80c4c3e655..771ff296038d 100644 --- a/sdk/storage/storage-queue/src/policies/RetryPolicy.ts +++ b/sdk/storage/storage-queue/src/policies/RetryPolicy.ts @@ -21,14 +21,9 @@ import { setURLHost, setURLParameter } from "../utils/utils.common"; * @param {IRetryOptions} retryOptions * @returns */ -export function NewRetryPolicyFactory( - retryOptions?: IRetryOptions -): RequestPolicyFactory { +export function NewRetryPolicyFactory(retryOptions?: IRetryOptions): RequestPolicyFactory { return { - create: ( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions - ): RetryPolicy => { + create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions): RetryPolicy => { return new RetryPolicy(nextPolicy, options, retryOptions); } }; @@ -136,9 +131,7 @@ export class RetryPolicy extends BaseRequestPolicy { * @returns {Promise} * @memberof RetryPolicy */ - public async sendRequest( - request: WebResource - ): Promise { + public async sendRequest(request: WebResource): Promise { return this.attemptSendRequest(request, false, 1); } @@ -166,18 +159,11 @@ export class RetryPolicy extends BaseRequestPolicy { const isPrimaryRetry = secondaryHas404 || !this.retryOptions.secondaryHost || - !( - request.method === "GET" || - request.method === "HEAD" || - request.method === "OPTIONS" - ) || + !(request.method === "GET" || request.method === "HEAD" || request.method === "OPTIONS") || attempt % 2 === 1; if (!isPrimaryRetry) { - newRequest.url = setURLHost( - newRequest.url, - this.retryOptions.secondaryHost! - ); + newRequest.url = setURLHost(newRequest.url, this.retryOptions.secondaryHost!); } // Set the server-side timeout query parameter "timeout=[seconds]" @@ -191,17 +177,14 @@ export class RetryPolicy extends BaseRequestPolicy { try { this.logf( HttpPipelineLogLevel.INFO, - `RetryPolicy: =====> Try=${attempt} ${ - isPrimaryRetry ? "Primary" : "Secondary" - }` + `RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}` ); response = await this._nextPolicy.sendRequest(newRequest); if (!this.shouldRetry(isPrimaryRetry, attempt, response)) { return response; } - secondaryHas404 = - secondaryHas404 || (!isPrimaryRetry && response.status === 404); + secondaryHas404 = secondaryHas404 || (!isPrimaryRetry && response.status === 404); } catch (err) { this.logf( HttpPipelineLogLevel.ERROR, @@ -276,10 +259,7 @@ export class RetryPolicy extends BaseRequestPolicy { if (response || err) { const statusCode = response ? response.status : err ? err.statusCode : 0; if (!isPrimaryRetry && statusCode === 404) { - this.logf( - HttpPipelineLogLevel.INFO, - `RetryPolicy: Secondary access with 404, will retry.` - ); + this.logf(HttpPipelineLogLevel.INFO, `RetryPolicy: Secondary access with 404, will retry.`); return true; } @@ -338,10 +318,7 @@ export class RetryPolicy extends BaseRequestPolicy { delayTimeInMs = Math.random() * 1000; } - this.logf( - HttpPipelineLogLevel.INFO, - `RetryPolicy: Delay for ${delayTimeInMs}ms` - ); + this.logf(HttpPipelineLogLevel.INFO, `RetryPolicy: Delay for ${delayTimeInMs}ms`); return delay(delayTimeInMs); } } diff --git a/sdk/storage/storage-queue/src/policies/SharedKeyCredentialPolicy.ts b/sdk/storage/storage-queue/src/policies/SharedKeyCredentialPolicy.ts index 27ba638c7361..c8ca2b8f9c1e 100644 --- a/sdk/storage/storage-queue/src/policies/SharedKeyCredentialPolicy.ts +++ b/sdk/storage/storage-queue/src/policies/SharedKeyCredentialPolicy.ts @@ -48,11 +48,7 @@ export class SharedKeyCredentialPolicy extends CredentialPolicy { request.headers.set(HeaderConstants.X_MS_DATE, new Date().toUTCString()); let contentLength = this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LENGTH); - if ( - request.body && - typeof request.body === "string" && - request.body.length > 0 - ) { + if (request.body && typeof request.body === "string" && request.body.length > 0) { // Workaround for https://github.com/axios/axios/issues/2107 // We should properly set the 'content-length' header once the issue is solved contentLength = `${Buffer.byteLength(request.body)}`; @@ -100,10 +96,7 @@ export class SharedKeyCredentialPolicy extends CredentialPolicy { * @returns {string} * @memberof SharedKeyCredentialPolicy */ - private getHeaderValueToSign( - request: WebResource, - headerName: string - ): string { + private getHeaderValueToSign(request: WebResource, headerName: string): string { const value = request.headers.get(headerName); if (!value) { @@ -137,10 +130,8 @@ export class SharedKeyCredentialPolicy extends CredentialPolicy { * @memberof SharedKeyCredentialPolicy */ private getCanonicalizedHeadersString(request: WebResource): string { - let headersArray = request.headers.headersArray().filter(value => { - return value.name - .toLowerCase() - .startsWith(HeaderConstants.PREFIX_FOR_STORAGE); + let headersArray = request.headers.headersArray().filter((value) => { + return value.name.toLowerCase().startsWith(HeaderConstants.PREFIX_FOR_STORAGE); }); headersArray.sort( @@ -151,17 +142,14 @@ export class SharedKeyCredentialPolicy extends CredentialPolicy { // Remove duplicate headers headersArray = headersArray.filter((value, index, array) => { - if ( - index > 0 && - value.name.toLowerCase() === array[index - 1].name.toLowerCase() - ) { + if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) { return false; } return true; }); let canonicalizedHeadersStringToSign: string = ""; - headersArray.forEach(header => { + headersArray.forEach((header) => { canonicalizedHeadersStringToSign += `${header.name .toLowerCase() .trimRight()}:${header.value.trimLeft()}\n`; @@ -198,9 +186,7 @@ export class SharedKeyCredentialPolicy extends CredentialPolicy { queryKeys.sort(); for (const key of queryKeys) { - canonicalizedResourceString += `\n${key}:${decodeURIComponent( - lowercaseQueries[key] - )}`; + canonicalizedResourceString += `\n${key}:${decodeURIComponent(lowercaseQueries[key])}`; } } diff --git a/sdk/storage/storage-queue/src/policies/TelemetryPolicy.ts b/sdk/storage/storage-queue/src/policies/TelemetryPolicy.ts index fedf88f4a524..cedefe68fde4 100644 --- a/sdk/storage/storage-queue/src/policies/TelemetryPolicy.ts +++ b/sdk/storage/storage-queue/src/policies/TelemetryPolicy.ts @@ -32,11 +32,7 @@ export class TelemetryPolicy extends BaseRequestPolicy { * @param {ITelemetryOptions} [telemetry] * @memberof TelemetryPolicy */ - constructor( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions, - telemetry: string - ) { + constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, telemetry: string) { super(nextPolicy, options); this.telemetry = telemetry; } @@ -48,9 +44,7 @@ export class TelemetryPolicy extends BaseRequestPolicy { * @returns {Promise} * @memberof TelemetryPolicy */ - public async sendRequest( - request: WebResource - ): Promise { + public async sendRequest(request: WebResource): Promise { if (isNode) { if (!request.headers) { request.headers = new HttpHeaders(); diff --git a/sdk/storage/storage-queue/src/policies/TokenCredentialPolicy.ts b/sdk/storage/storage-queue/src/policies/TokenCredentialPolicy.ts index a92a04d39bfc..fc1b4d8610c5 100644 --- a/sdk/storage/storage-queue/src/policies/TokenCredentialPolicy.ts +++ b/sdk/storage/storage-queue/src/policies/TokenCredentialPolicy.ts @@ -1,9 +1,4 @@ -import { - HttpHeaders, - RequestPolicy, - RequestPolicyOptions, - WebResource -} from "@azure/ms-rest-js"; +import { HttpHeaders, RequestPolicy, RequestPolicyOptions, WebResource } from "@azure/ms-rest-js"; import { TokenCredential } from "../credentials/TokenCredential"; import { HeaderConstants } from "../utils/constants"; diff --git a/sdk/storage/storage-queue/src/policies/UniqueRequestIDPolicy.ts b/sdk/storage/storage-queue/src/policies/UniqueRequestIDPolicy.ts index b4ff96983f9c..3e4e4e9dd17b 100644 --- a/sdk/storage/storage-queue/src/policies/UniqueRequestIDPolicy.ts +++ b/sdk/storage/storage-queue/src/policies/UniqueRequestIDPolicy.ts @@ -33,14 +33,9 @@ export class UniqueRequestIDPolicy extends BaseRequestPolicy { * @returns {Promise} * @memberof UniqueRequestIDPolicy */ - public async sendRequest( - request: WebResource - ): Promise { + public async sendRequest(request: WebResource): Promise { if (!request.headers.contains(HeaderConstants.X_MS_CLIENT_REQUEST_ID)) { - request.headers.set( - HeaderConstants.X_MS_CLIENT_REQUEST_ID, - generateUuid() - ); + request.headers.set(HeaderConstants.X_MS_CLIENT_REQUEST_ID, generateUuid()); } return this._nextPolicy.sendRequest(request); diff --git a/sdk/storage/storage-queue/src/utils/utils.common.ts b/sdk/storage/storage-queue/src/utils/utils.common.ts index 4abd6c49b786..a4d6993436c2 100644 --- a/sdk/storage/storage-queue/src/utils/utils.common.ts +++ b/sdk/storage/storage-queue/src/utils/utils.common.ts @@ -13,11 +13,7 @@ export function appendToURLPath(url: string, name: string): string { const urlParsed = URLBuilder.parse(url); let path = urlParsed.getPath(); - path = path - ? path.endsWith("/") - ? `${path}${name}` - : `${path}/${name}` - : name; + path = path ? (path.endsWith("/") ? `${path}${name}` : `${path}/${name}`) : name; urlParsed.setPath(path); return urlParsed.toString(); @@ -33,11 +29,7 @@ export function appendToURLPath(url: string, name: string): string { * @param {string} [value] Parameter value * @returns {string} An updated URL string */ -export function setURLParameter( - url: string, - name: string, - value?: string -): string { +export function setURLParameter(url: string, name: string, value?: string): string { const urlParsed = URLBuilder.parse(url); urlParsed.setQueryParameter(name, value); return urlParsed.toString(); @@ -51,10 +43,7 @@ export function setURLParameter( * @param {string} name * @returns {(string | string[] | undefined)} */ -export function getURLParameter( - url: string, - name: string -): string | string[] | undefined { +export function getURLParameter(url: string, name: string): string | string[] | undefined { const urlParsed = URLBuilder.parse(url); return urlParsed.getQueryParameterValue(name); } @@ -99,18 +88,14 @@ export function getURLQueries(url: string): { [key: string]: string } { } queryString = queryString.trim(); - queryString = queryString.startsWith("?") - ? queryString.substr(1) - : queryString; + queryString = queryString.startsWith("?") ? queryString.substr(1) : queryString; let querySubStrings: string[] = queryString.split("&"); querySubStrings = querySubStrings.filter((value: string) => { const indexOfEqual = value.indexOf("="); const lastIndexOfEqual = value.lastIndexOf("="); return ( - indexOfEqual > 0 && - indexOfEqual === lastIndexOfEqual && - lastIndexOfEqual < value.length - 1 + indexOfEqual > 0 && indexOfEqual === lastIndexOfEqual && lastIndexOfEqual < value.length - 1 ); }); @@ -134,10 +119,7 @@ export function getURLQueries(url: string): { [key: string]: string } { * If false, YYYY-MM-DDThh:mm:ssZ will be returned. * @returns {string} Date string in ISO8061 format, with or without 7 milliseconds component */ -export function truncatedISO8061Date( - date: Date, - withMilliseconds: boolean = true -): string { +export function truncatedISO8061Date(date: Date, withMilliseconds: boolean = true): string { // Date.toISOString() will return like "2018-10-29T06:34:36.139Z" const dateString = date.toISOString(); diff --git a/sdk/storage/storage-queue/test/aborter.test.ts b/sdk/storage/storage-queue/test/aborter.test.ts index d7871465103f..976ba0a887a3 100644 --- a/sdk/storage/storage-queue/test/aborter.test.ts +++ b/sdk/storage/storage-queue/test/aborter.test.ts @@ -4,7 +4,7 @@ import { Aborter } from "../src/Aborter"; import { QueueURL } from "../src/QueueURL"; import { getQSU, getUniqueName } from "./utils"; import * as dotenv from "dotenv"; -dotenv.config({path:"../.env"}); +dotenv.config({ path: "../.env" }); // tslint:disable:no-empty describe("Aborter", () => { diff --git a/sdk/storage/storage-queue/test/messageidurl.test.ts b/sdk/storage/storage-queue/test/messageidurl.test.ts index 8c4d4091f605..ee8703d50ddf 100644 --- a/sdk/storage/storage-queue/test/messageidurl.test.ts +++ b/sdk/storage/storage-queue/test/messageidurl.test.ts @@ -6,7 +6,7 @@ import { MessagesURL } from "../src/MessagesURL"; import { MessageIdURL } from "../src/MessageIdURL"; import { getQSU, getUniqueName, sleep } from "./utils"; import * as dotenv from "dotenv"; -dotenv.config({path:"../.env"}); +dotenv.config({ path: "../.env" }); describe("MessageIdURL", () => { const serviceURL = getQSU(); @@ -37,16 +37,8 @@ describe("MessageIdURL", () => { assert.ok(eResult.version); let newMessage = ""; - let messageIdURL = MessageIdURL.fromMessagesURL( - messagesURL, - eResult.messageId - ); - let uResult = await messageIdURL.update( - Aborter.none, - eResult.popReceipt, - 0, - newMessage - ); + let messageIdURL = MessageIdURL.fromMessagesURL(messagesURL, eResult.messageId); + let uResult = await messageIdURL.update(Aborter.none, eResult.popReceipt, 0, newMessage); assert.ok(uResult.version); assert.ok(uResult.timeNextVisible); assert.ok(uResult.date); @@ -55,10 +47,7 @@ describe("MessageIdURL", () => { let pResult = await messagesURL.peek(Aborter.none); assert.equal(pResult.peekedMessageItems.length, 1); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].messageText, - newMessage - ); + assert.deepStrictEqual(pResult.peekedMessageItems[0].messageText, newMessage); let dResult = await messageIdURL.delete(Aborter.none, uResult.popReceipt!); assert.ok(dResult.date); @@ -82,16 +71,8 @@ describe("MessageIdURL", () => { assert.ok(eResult.version); let newMessage = "New Message"; - let messageIdURL = MessageIdURL.fromMessagesURL( - messagesURL, - eResult.messageId - ); - let uResult = await messageIdURL.update( - Aborter.none, - eResult.popReceipt, - 10, - newMessage - ); + let messageIdURL = MessageIdURL.fromMessagesURL(messagesURL, eResult.messageId); + let uResult = await messageIdURL.update(Aborter.none, eResult.popReceipt, 10, newMessage); assert.ok(uResult.version); assert.ok(uResult.timeNextVisible); assert.ok(uResult.date); @@ -100,15 +81,12 @@ describe("MessageIdURL", () => { let pResult = await messagesURL.peek(Aborter.none); assert.equal(pResult.peekedMessageItems.length, 0); - + await sleep(11 * 1000); // Sleep 11 seconds, and wait the message to be visible again let pResult2 = await messagesURL.peek(Aborter.none); assert.equal(pResult2.peekedMessageItems.length, 1); - assert.deepStrictEqual( - pResult2.peekedMessageItems[0].messageText, - newMessage - ); + assert.deepStrictEqual(pResult2.peekedMessageItems[0].messageText, newMessage); }); it("update message with 64KB characters size which is computed after encoding", async () => { @@ -123,17 +101,9 @@ describe("MessageIdURL", () => { assert.ok(eResult.timeNextVisible); assert.ok(eResult.version); - let newMessage = new Array(64*1024 + 1).join('a'); - let messageIdURL = MessageIdURL.fromMessagesURL( - messagesURL, - eResult.messageId - ); - let uResult = await messageIdURL.update( - Aborter.none, - eResult.popReceipt, - 0, - newMessage - ); + let newMessage = new Array(64 * 1024 + 1).join("a"); + let messageIdURL = MessageIdURL.fromMessagesURL(messagesURL, eResult.messageId); + let uResult = await messageIdURL.update(Aborter.none, eResult.popReceipt, 0, newMessage); assert.ok(uResult.version); assert.ok(uResult.timeNextVisible); assert.ok(uResult.date); @@ -142,10 +112,7 @@ describe("MessageIdURL", () => { let pResult = await messagesURL.peek(Aborter.none); assert.equal(pResult.peekedMessageItems.length, 1); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].messageText, - newMessage - ); + assert.deepStrictEqual(pResult.peekedMessageItems[0].messageText, newMessage); }); it("update message negative with 65537B (64KB+1B) characters size which is computed after encoding", async () => { @@ -160,43 +127,35 @@ describe("MessageIdURL", () => { assert.ok(eResult.timeNextVisible); assert.ok(eResult.version); - let newMessage = new Array(64*1024 + 2).join('a'); - - let messageIdURL = MessageIdURL.fromMessagesURL( - messagesURL, - eResult.messageId - ); + let newMessage = new Array(64 * 1024 + 2).join("a"); + + let messageIdURL = MessageIdURL.fromMessagesURL(messagesURL, eResult.messageId); let error; - try{ - await messageIdURL.update( - Aborter.none, - eResult.popReceipt, - 0, - newMessage - ); - } catch(err) { - error = err + try { + await messageIdURL.update(Aborter.none, eResult.popReceipt, 0, newMessage); + } catch (err) { + error = err; } assert.ok(error); - assert.ok(error.message.includes("The request body is too large and exceeds the maximum permissible limit.")) + assert.ok( + error.message.includes( + "The request body is too large and exceeds the maximum permissible limit." + ) + ); }); - it("delete message negative", async () => { let messagesURL = MessagesURL.fromQueueURL(queueURL); let eResult = await messagesURL.enqueue(Aborter.none, messageContent); - let messageIdURL = MessageIdURL.fromMessagesURL( - messagesURL, - eResult.messageId - ); + let messageIdURL = MessageIdURL.fromMessagesURL(messagesURL, eResult.messageId); - let error - try{ + let error; + try { await messageIdURL.delete(Aborter.none, "invalid"); - } catch(err) { - error = err + } catch (err) { + error = err; } assert.ok(error); }); diff --git a/sdk/storage/storage-queue/test/messagesurl.test.ts b/sdk/storage/storage-queue/test/messagesurl.test.ts index 6198139cca9f..fbb3c06e3e53 100644 --- a/sdk/storage/storage-queue/test/messagesurl.test.ts +++ b/sdk/storage/storage-queue/test/messagesurl.test.ts @@ -5,7 +5,7 @@ import { QueueURL } from "../src/QueueURL"; import { MessagesURL } from "../src/MessagesURL"; import { getQSU, getUniqueName } from "./utils"; import * as dotenv from "dotenv"; -dotenv.config({path:"../.env"}); +dotenv.config({ path: "../.env" }); describe("MessagesURL", () => { const serviceURL = getQSU(); @@ -42,14 +42,8 @@ describe("MessagesURL", () => { assert.ok(pResult.requestId); assert.ok(pResult.version); assert.deepStrictEqual(pResult.peekedMessageItems.length, 1); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].messageText, - messageContent - ); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].messageId, - eResult.messageId - ); + assert.deepStrictEqual(pResult.peekedMessageItems[0].messageText, messageContent); + assert.deepStrictEqual(pResult.peekedMessageItems[0].messageId, eResult.messageId); let dqResult = await messagesURL.dequeue(Aborter.none); assert.ok(dqResult.date); @@ -57,14 +51,8 @@ describe("MessagesURL", () => { assert.ok(dqResult.version); assert.deepStrictEqual(dqResult.dequeuedMessageItems.length, 1); assert.ok(dqResult.dequeuedMessageItems[0].popReceipt); - assert.deepStrictEqual( - dqResult.dequeuedMessageItems[0].messageText, - messageContent - ); - assert.deepStrictEqual( - dqResult.dequeuedMessageItems[0].messageId, - eResult.messageId - ); + assert.deepStrictEqual(dqResult.dequeuedMessageItems[0].messageText, messageContent); + assert.deepStrictEqual(dqResult.dequeuedMessageItems[0].messageId, eResult.messageId); let cResult = await messagesURL.clear(Aborter.none); assert.ok(cResult.date); @@ -111,41 +99,17 @@ describe("MessagesURL", () => { assert.ok(pResult.requestId); assert.ok(pResult.version); assert.deepStrictEqual(pResult.peekedMessageItems.length, 2); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].messageText, - messageContent - ); + assert.deepStrictEqual(pResult.peekedMessageItems[0].messageText, messageContent); assert.deepStrictEqual(pResult.peekedMessageItems[0].dequeueCount, 0); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].messageId, - eResult.messageId - ); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].insertionTime, - eResult.insertionTime - ); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].expirationTime, - eResult.expirationTime - ); + assert.deepStrictEqual(pResult.peekedMessageItems[0].messageId, eResult.messageId); + assert.deepStrictEqual(pResult.peekedMessageItems[0].insertionTime, eResult.insertionTime); + assert.deepStrictEqual(pResult.peekedMessageItems[0].expirationTime, eResult.expirationTime); - assert.deepStrictEqual( - pResult.peekedMessageItems[1].messageText, - messageContent - ); + assert.deepStrictEqual(pResult.peekedMessageItems[1].messageText, messageContent); assert.deepStrictEqual(pResult.peekedMessageItems[1].dequeueCount, 0); - assert.deepStrictEqual( - pResult.peekedMessageItems[1].messageId, - eResult2.messageId - ); - assert.deepStrictEqual( - pResult.peekedMessageItems[1].insertionTime, - eResult2.insertionTime - ); - assert.deepStrictEqual( - pResult.peekedMessageItems[1].expirationTime, - eResult2.expirationTime - ); + assert.deepStrictEqual(pResult.peekedMessageItems[1].messageId, eResult2.messageId); + assert.deepStrictEqual(pResult.peekedMessageItems[1].insertionTime, eResult2.insertionTime); + assert.deepStrictEqual(pResult.peekedMessageItems[1].expirationTime, eResult2.expirationTime); let dResult = await messagesURL.dequeue(Aborter.none, { visibilitytimeout: 10, @@ -155,30 +119,15 @@ describe("MessagesURL", () => { assert.ok(dResult.requestId); assert.ok(dResult.version); assert.deepStrictEqual(dResult.dequeuedMessageItems.length, 2); - assert.deepStrictEqual( - dResult.dequeuedMessageItems[0].messageText, - messageContent - ); + assert.deepStrictEqual(dResult.dequeuedMessageItems[0].messageText, messageContent); assert.deepStrictEqual(dResult.dequeuedMessageItems[0].dequeueCount, 1); - assert.deepStrictEqual( - dResult.dequeuedMessageItems[0].messageId, - eResult.messageId - ); - assert.deepStrictEqual( - dResult.dequeuedMessageItems[0].insertionTime, - eResult.insertionTime - ); - assert.deepStrictEqual( - dResult.dequeuedMessageItems[0].expirationTime, - eResult.expirationTime - ); + assert.deepStrictEqual(dResult.dequeuedMessageItems[0].messageId, eResult.messageId); + assert.deepStrictEqual(dResult.dequeuedMessageItems[0].insertionTime, eResult.insertionTime); + assert.deepStrictEqual(dResult.dequeuedMessageItems[0].expirationTime, eResult.expirationTime); assert.ok(dResult.dequeuedMessageItems[0].popReceipt); assert.ok(dResult.dequeuedMessageItems[0].timeNextVisible); - assert.deepStrictEqual( - pResult.peekedMessageItems[1].messageText, - messageContent - ); + assert.deepStrictEqual(pResult.peekedMessageItems[1].messageText, messageContent); // check no message is visible let pResult2 = await messagesURL.peek(Aborter.none); @@ -207,23 +156,11 @@ describe("MessagesURL", () => { assert.ok(pResult.requestId); assert.ok(pResult.version); assert.deepStrictEqual(pResult.peekedMessageItems.length, 1); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].messageText, - "" - ); + assert.deepStrictEqual(pResult.peekedMessageItems[0].messageText, ""); assert.deepStrictEqual(pResult.peekedMessageItems[0].dequeueCount, 0); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].messageId, - eResult.messageId - ); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].insertionTime, - eResult.insertionTime - ); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].expirationTime, - eResult.expirationTime - ); + assert.deepStrictEqual(pResult.peekedMessageItems[0].messageId, eResult.messageId); + assert.deepStrictEqual(pResult.peekedMessageItems[0].insertionTime, eResult.insertionTime); + assert.deepStrictEqual(pResult.peekedMessageItems[0].expirationTime, eResult.expirationTime); let dResult = await messagesURL.dequeue(Aborter.none, { visibilitytimeout: 10, @@ -233,23 +170,11 @@ describe("MessagesURL", () => { assert.ok(dResult.requestId); assert.ok(dResult.version); assert.deepStrictEqual(dResult.dequeuedMessageItems.length, 1); - assert.deepStrictEqual( - dResult.dequeuedMessageItems[0].messageText, - '' - ); + assert.deepStrictEqual(dResult.dequeuedMessageItems[0].messageText, ""); assert.deepStrictEqual(dResult.dequeuedMessageItems[0].dequeueCount, 1); - assert.deepStrictEqual( - dResult.dequeuedMessageItems[0].messageId, - eResult.messageId - ); - assert.deepStrictEqual( - dResult.dequeuedMessageItems[0].insertionTime, - eResult.insertionTime - ); - assert.deepStrictEqual( - dResult.dequeuedMessageItems[0].expirationTime, - eResult.expirationTime - ); + assert.deepStrictEqual(dResult.dequeuedMessageItems[0].messageId, eResult.messageId); + assert.deepStrictEqual(dResult.dequeuedMessageItems[0].insertionTime, eResult.insertionTime); + assert.deepStrictEqual(dResult.dequeuedMessageItems[0].expirationTime, eResult.expirationTime); assert.ok(dResult.dequeuedMessageItems[0].popReceipt); assert.ok(dResult.dequeuedMessageItems[0].timeNextVisible); }); @@ -257,7 +182,8 @@ describe("MessagesURL", () => { it("enqueue, peek, dequeue special characters", async () => { let messagesURL = MessagesURL.fromQueueURL(queueURL); - let specialMessage = '!@#$%^&*()_+`-=[]\|};\'":,./?><`~漢字㒈保ᨍ揫^p[뷁)׷񬓔7񈺝l鮍򧽶ͺ簣ڞ츊䈗㝯綞߫⯹?ÎᦡC왶żsmt㖩닡򈸱𕩣ОլFZ򃀮9tC榅ٻ컦驿Ϳ[𱿛봻烌󱰷򙥱Ռ򽒏򘤰δŊϜ췮㐦9ͽƙp퐂ʩ由巩•KFÓ֮򨾭⨿󊻅aBm󶴂旨Ϣ񓙠򻐪񇧱򆋸ջ֨ipn򒷐ꝷՆ򆊙斡賆𒚑m˞\𻆕󛿓򐞺Ӯ򡗺򴜍<񐸩԰Bu)򁉂񖨞á<џɏ嗂�⨣1PJ㬵┡ḸI򰱂ˮaࢸ۳i灛ȯɨb𹺪򕕱뿶uٔ䎴񷯆Φ륽󬃨س_NƵ¦\u00E9' + let specialMessage = + "!@#$%^&*()_+`-=[]|};'\":,./?><`~漢字㒈保ᨍ揫^p[뷁)׷񬓔7񈺝l鮍򧽶ͺ簣ڞ츊䈗㝯綞߫⯹?ÎᦡC왶żsmt㖩닡򈸱𕩣ОլFZ򃀮9tC榅ٻ컦驿Ϳ[𱿛봻烌󱰷򙥱Ռ򽒏򘤰δŊϜ췮㐦9ͽƙp퐂ʩ由巩•KFÓ֮򨾭⨿󊻅aBm󶴂旨Ϣ񓙠򻐪񇧱򆋸ջ֨ipn򒷐ꝷՆ򆊙斡賆𒚑m˞𻆕󛿓򐞺Ӯ򡗺򴜍<񐸩԰Bu)򁉂񖨞á<џɏ嗂�⨣1PJ㬵┡ḸI򰱂ˮaࢸ۳i灛ȯɨb𹺪򕕱뿶uٔ䎴񷯆Φ륽󬃨س_NƵ¦\u00E9"; let eResult = await messagesURL.enqueue(Aborter.none, specialMessage, { messageTimeToLive: 40, @@ -277,23 +203,11 @@ describe("MessagesURL", () => { assert.ok(pResult.requestId); assert.ok(pResult.version); assert.deepStrictEqual(pResult.peekedMessageItems.length, 1); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].messageText, - specialMessage - ); + assert.deepStrictEqual(pResult.peekedMessageItems[0].messageText, specialMessage); assert.deepStrictEqual(pResult.peekedMessageItems[0].dequeueCount, 0); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].messageId, - eResult.messageId - ); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].insertionTime, - eResult.insertionTime - ); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].expirationTime, - eResult.expirationTime - ); + assert.deepStrictEqual(pResult.peekedMessageItems[0].messageId, eResult.messageId); + assert.deepStrictEqual(pResult.peekedMessageItems[0].insertionTime, eResult.insertionTime); + assert.deepStrictEqual(pResult.peekedMessageItems[0].expirationTime, eResult.expirationTime); let dResult = await messagesURL.dequeue(Aborter.none, { visibilitytimeout: 10, @@ -303,30 +217,18 @@ describe("MessagesURL", () => { assert.ok(dResult.requestId); assert.ok(dResult.version); assert.deepStrictEqual(dResult.dequeuedMessageItems.length, 1); - assert.deepStrictEqual( - dResult.dequeuedMessageItems[0].messageText, - specialMessage - ); + assert.deepStrictEqual(dResult.dequeuedMessageItems[0].messageText, specialMessage); assert.deepStrictEqual(dResult.dequeuedMessageItems[0].dequeueCount, 1); - assert.deepStrictEqual( - dResult.dequeuedMessageItems[0].messageId, - eResult.messageId - ); - assert.deepStrictEqual( - dResult.dequeuedMessageItems[0].insertionTime, - eResult.insertionTime - ); - assert.deepStrictEqual( - dResult.dequeuedMessageItems[0].expirationTime, - eResult.expirationTime - ); + assert.deepStrictEqual(dResult.dequeuedMessageItems[0].messageId, eResult.messageId); + assert.deepStrictEqual(dResult.dequeuedMessageItems[0].insertionTime, eResult.insertionTime); + assert.deepStrictEqual(dResult.dequeuedMessageItems[0].expirationTime, eResult.expirationTime); assert.ok(dResult.dequeuedMessageItems[0].popReceipt); assert.ok(dResult.dequeuedMessageItems[0].timeNextVisible); }); it("enqueue, peek, dequeue with 64KB characters size which is computed after encoding", async () => { let messagesURL = MessagesURL.fromQueueURL(queueURL); - let messageContent = new Array(64*1024 + 1).join('a'); + let messageContent = new Array(64 * 1024 + 1).join("a"); let eResult = await messagesURL.enqueue(Aborter.none, messageContent, { messageTimeToLive: 40, @@ -346,23 +248,11 @@ describe("MessagesURL", () => { assert.ok(pResult.requestId); assert.ok(pResult.version); assert.deepStrictEqual(pResult.peekedMessageItems.length, 1); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].messageText, - messageContent - ); + assert.deepStrictEqual(pResult.peekedMessageItems[0].messageText, messageContent); assert.deepStrictEqual(pResult.peekedMessageItems[0].dequeueCount, 0); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].messageId, - eResult.messageId - ); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].insertionTime, - eResult.insertionTime - ); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].expirationTime, - eResult.expirationTime - ); + assert.deepStrictEqual(pResult.peekedMessageItems[0].messageId, eResult.messageId); + assert.deepStrictEqual(pResult.peekedMessageItems[0].insertionTime, eResult.insertionTime); + assert.deepStrictEqual(pResult.peekedMessageItems[0].expirationTime, eResult.expirationTime); let dResult = await messagesURL.dequeue(Aborter.none, { visibilitytimeout: 10, @@ -372,23 +262,11 @@ describe("MessagesURL", () => { assert.ok(dResult.requestId); assert.ok(dResult.version); assert.deepStrictEqual(dResult.dequeuedMessageItems.length, 1); - assert.deepStrictEqual( - dResult.dequeuedMessageItems[0].messageText, - messageContent - ); + assert.deepStrictEqual(dResult.dequeuedMessageItems[0].messageText, messageContent); assert.deepStrictEqual(dResult.dequeuedMessageItems[0].dequeueCount, 1); - assert.deepStrictEqual( - dResult.dequeuedMessageItems[0].messageId, - eResult.messageId - ); - assert.deepStrictEqual( - dResult.dequeuedMessageItems[0].insertionTime, - eResult.insertionTime - ); - assert.deepStrictEqual( - dResult.dequeuedMessageItems[0].expirationTime, - eResult.expirationTime - ); + assert.deepStrictEqual(dResult.dequeuedMessageItems[0].messageId, eResult.messageId); + assert.deepStrictEqual(dResult.dequeuedMessageItems[0].insertionTime, eResult.insertionTime); + assert.deepStrictEqual(dResult.dequeuedMessageItems[0].expirationTime, eResult.expirationTime); assert.ok(dResult.dequeuedMessageItems[0].popReceipt); assert.ok(dResult.dequeuedMessageItems[0].timeNextVisible); }); @@ -431,23 +309,11 @@ describe("MessagesURL", () => { assert.ok(pResult.requestId); assert.ok(pResult.version); assert.deepStrictEqual(pResult.peekedMessageItems.length, 1); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].messageText, - messageContent - ); + assert.deepStrictEqual(pResult.peekedMessageItems[0].messageText, messageContent); assert.deepStrictEqual(pResult.peekedMessageItems[0].dequeueCount, 0); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].messageId, - eResult.messageId - ); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].insertionTime, - eResult.insertionTime - ); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].expirationTime, - eResult.expirationTime - ); + assert.deepStrictEqual(pResult.peekedMessageItems[0].messageId, eResult.messageId); + assert.deepStrictEqual(pResult.peekedMessageItems[0].insertionTime, eResult.insertionTime); + assert.deepStrictEqual(pResult.peekedMessageItems[0].expirationTime, eResult.expirationTime); // Note visibility time could be larger then message time to live for dequeue. await messagesURL.dequeue(Aborter.none, { @@ -458,15 +324,19 @@ describe("MessagesURL", () => { it("enqueue negative with 65537B(64KB+1B) characters size which is computed after encoding", async () => { let messagesURL = MessagesURL.fromQueueURL(queueURL); - let messageContent = new Array(64*1024 + 2).join('a'); + let messageContent = new Array(64 * 1024 + 2).join("a"); - let error + let error; try { await messagesURL.enqueue(Aborter.none, messageContent, {}); - } catch(err) { - error = err + } catch (err) { + error = err; } - assert.ok(error) - assert.ok(error.message.includes("The request body is too large and exceeds the maximum permissible limit.")) + assert.ok(error); + assert.ok( + error.message.includes( + "The request body is too large and exceeds the maximum permissible limit." + ) + ); }); -}); \ No newline at end of file +}); diff --git a/sdk/storage/storage-queue/test/node/messageidurl.test.ts b/sdk/storage/storage-queue/test/node/messageidurl.test.ts index 3d40b2961ddb..cf4dee051a6c 100644 --- a/sdk/storage/storage-queue/test/node/messageidurl.test.ts +++ b/sdk/storage/storage-queue/test/node/messageidurl.test.ts @@ -34,21 +34,14 @@ describe("MessageIdURL Node", () => { assert.ok(eResult.timeNextVisible); assert.ok(eResult.version); - let specialChars = '!@#$%^&*()_+`-=[]\|};\'":,./?><`~漢字㒈保ᨍ揫^p[뷁)׷񬓔7񈺝l鮍򧽶ͺ簣ڞ츊䈗㝯綞߫⯹?ÎᦡC왶żsmt㖩닡򈸱𕩣ОլFZ򃀮9tC榅ٻ컦驿Ϳ[𱿛봻烌󱰷򙥱Ռ򽒏򘤰δŊϜ췮㐦9ͽƙp퐂ʩ由巩•KFÓ֮򨾭⨿󊻅aBm󶴂旨Ϣ񓙠򻐪񇧱򆋸ջ֨ipn򒷐ꝷՆ򆊙斡賆𒚑m˞\𻆕󛿓򐞺Ӯ򡗺򴜍<񐸩԰Bu)򁉂񖨞á<џɏ嗂�⨣1PJ㬵┡ḸI򰱂ˮaࢸ۳i灛ȯɨb𹺪򕕱뿶uٔ䎴񷯆Φ륽󬃨س_NƵ¦' - let buffer = Buffer.alloc(64*1024); //64KB - buffer.fill('a'); + let specialChars = + "!@#$%^&*()_+`-=[]|};'\":,./?><`~漢字㒈保ᨍ揫^p[뷁)׷񬓔7񈺝l鮍򧽶ͺ簣ڞ츊䈗㝯綞߫⯹?ÎᦡC왶żsmt㖩닡򈸱𕩣ОլFZ򃀮9tC榅ٻ컦驿Ϳ[𱿛봻烌󱰷򙥱Ռ򽒏򘤰δŊϜ췮㐦9ͽƙp퐂ʩ由巩•KFÓ֮򨾭⨿󊻅aBm󶴂旨Ϣ񓙠򻐪񇧱򆋸ջ֨ipn򒷐ꝷՆ򆊙斡賆𒚑m˞𻆕󛿓򐞺Ӯ򡗺򴜍<񐸩԰Bu)򁉂񖨞á<џɏ嗂�⨣1PJ㬵┡ḸI򰱂ˮaࢸ۳i灛ȯɨb𹺪򕕱뿶uٔ䎴񷯆Φ륽󬃨س_NƵ¦"; + let buffer = Buffer.alloc(64 * 1024); //64KB + buffer.fill("a"); buffer.write(specialChars, 0); let newMessage = buffer.toString(); - let messageIdURL = MessageIdURL.fromMessagesURL( - messagesURL, - eResult.messageId - ); - let uResult = await messageIdURL.update( - Aborter.none, - eResult.popReceipt, - 0, - newMessage - ); + let messageIdURL = MessageIdURL.fromMessagesURL(messagesURL, eResult.messageId); + let uResult = await messageIdURL.update(Aborter.none, eResult.popReceipt, 0, newMessage); assert.ok(uResult.version); assert.ok(uResult.timeNextVisible); assert.ok(uResult.date); @@ -57,10 +50,7 @@ describe("MessageIdURL Node", () => { let pResult = await messagesURL.peek(Aborter.none); assert.equal(pResult.peekedMessageItems.length, 1); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].messageText, - newMessage - ); + assert.deepStrictEqual(pResult.peekedMessageItems[0].messageText, newMessage); }); it("update message negative with 65537B (64KB+1B) characters including special char which is computed after encoding", async () => { @@ -75,28 +65,25 @@ describe("MessageIdURL Node", () => { assert.ok(eResult.timeNextVisible); assert.ok(eResult.version); - let specialChars = '!@#$%^&*()_+`-=[]\|};\'":,./?><`~漢字㒈保ᨍ揫^p[뷁)׷񬓔7񈺝l鮍򧽶ͺ簣ڞ츊䈗㝯綞߫⯹?ÎᦡC왶żsmt㖩닡򈸱𕩣ОլFZ򃀮9tC榅ٻ컦驿Ϳ[𱿛봻烌󱰷򙥱Ռ򽒏򘤰δŊϜ췮㐦9ͽƙp퐂ʩ由巩•KFÓ֮򨾭⨿󊻅aBm󶴂旨Ϣ񓙠򻐪񇧱򆋸ջ֨ipn򒷐ꝷՆ򆊙斡賆𒚑m˞\𻆕󛿓򐞺Ӯ򡗺򴜍<񐸩԰Bu)򁉂񖨞á<џɏ嗂�⨣1PJ㬵┡ḸI򰱂ˮaࢸ۳i灛ȯɨb𹺪򕕱뿶uٔ䎴񷯆Φ륽󬃨س_NƵ¦' - let buffer = Buffer.alloc(64*1024 + 1); - buffer.fill('a'); + let specialChars = + "!@#$%^&*()_+`-=[]|};'\":,./?><`~漢字㒈保ᨍ揫^p[뷁)׷񬓔7񈺝l鮍򧽶ͺ簣ڞ츊䈗㝯綞߫⯹?ÎᦡC왶żsmt㖩닡򈸱𕩣ОլFZ򃀮9tC榅ٻ컦驿Ϳ[𱿛봻烌󱰷򙥱Ռ򽒏򘤰δŊϜ췮㐦9ͽƙp퐂ʩ由巩•KFÓ֮򨾭⨿󊻅aBm󶴂旨Ϣ񓙠򻐪񇧱򆋸ջ֨ipn򒷐ꝷՆ򆊙斡賆𒚑m˞𻆕󛿓򐞺Ӯ򡗺򴜍<񐸩԰Bu)򁉂񖨞á<џɏ嗂�⨣1PJ㬵┡ḸI򰱂ˮaࢸ۳i灛ȯɨb𹺪򕕱뿶uٔ䎴񷯆Φ륽󬃨س_NƵ¦"; + let buffer = Buffer.alloc(64 * 1024 + 1); + buffer.fill("a"); buffer.write(specialChars, 0); let newMessage = buffer.toString(); - let messageIdURL = MessageIdURL.fromMessagesURL( - messagesURL, - eResult.messageId - ); + let messageIdURL = MessageIdURL.fromMessagesURL(messagesURL, eResult.messageId); let error; - try{ - await messageIdURL.update( - Aborter.none, - eResult.popReceipt, - 0, - newMessage - ); - } catch(err) { - error = err + try { + await messageIdURL.update(Aborter.none, eResult.popReceipt, 0, newMessage); + } catch (err) { + error = err; } assert.ok(error); - assert.ok(error.message.includes("The request body is too large and exceeds the maximum permissible limit.")) + assert.ok( + error.message.includes( + "The request body is too large and exceeds the maximum permissible limit." + ) + ); }); }); diff --git a/sdk/storage/storage-queue/test/node/messagesurl.test.ts b/sdk/storage/storage-queue/test/node/messagesurl.test.ts index 96ae4dbfb074..fa18ae2342ae 100644 --- a/sdk/storage/storage-queue/test/node/messagesurl.test.ts +++ b/sdk/storage/storage-queue/test/node/messagesurl.test.ts @@ -22,9 +22,10 @@ describe("MessagesURL Node", () => { it("enqueue, peek, dequeue with 64KB characters including special char which is computed after encoding", async () => { let messagesURL = MessagesURL.fromQueueURL(queueURL); - let specialChars = '!@#$%^&*()_+`-=[]\|};\'":,./?><`~漢字㒈保ᨍ揫^p[뷁)׷񬓔7񈺝l鮍򧽶ͺ簣ڞ츊䈗㝯綞߫⯹?ÎᦡC왶żsmt㖩닡򈸱𕩣ОլFZ򃀮9tC榅ٻ컦驿Ϳ[𱿛봻烌󱰷򙥱Ռ򽒏򘤰δŊϜ췮㐦9ͽƙp퐂ʩ由巩•KFÓ֮򨾭⨿󊻅aBm󶴂旨Ϣ񓙠򻐪񇧱򆋸ջ֨ipn򒷐ꝷՆ򆊙斡賆𒚑m˞\𻆕󛿓򐞺Ӯ򡗺򴜍<񐸩԰Bu)򁉂񖨞á<џɏ嗂�⨣1PJ㬵┡ḸI򰱂ˮaࢸ۳i灛ȯɨb𹺪򕕱뿶uٔ䎴񷯆Φ륽󬃨س_NƵ¦' - let buffer = Buffer.alloc(64*1024); //64KB - buffer.fill('a'); + let specialChars = + "!@#$%^&*()_+`-=[]|};'\":,./?><`~漢字㒈保ᨍ揫^p[뷁)׷񬓔7񈺝l鮍򧽶ͺ簣ڞ츊䈗㝯綞߫⯹?ÎᦡC왶żsmt㖩닡򈸱𕩣ОլFZ򃀮9tC榅ٻ컦驿Ϳ[𱿛봻烌󱰷򙥱Ռ򽒏򘤰δŊϜ췮㐦9ͽƙp퐂ʩ由巩•KFÓ֮򨾭⨿󊻅aBm󶴂旨Ϣ񓙠򻐪񇧱򆋸ջ֨ipn򒷐ꝷՆ򆊙斡賆𒚑m˞𻆕󛿓򐞺Ӯ򡗺򴜍<񐸩԰Bu)򁉂񖨞á<џɏ嗂�⨣1PJ㬵┡ḸI򰱂ˮaࢸ۳i灛ȯɨb𹺪򕕱뿶uٔ䎴񷯆Φ륽󬃨س_NƵ¦"; + let buffer = Buffer.alloc(64 * 1024); //64KB + buffer.fill("a"); buffer.write(specialChars, 0); let messageContent = buffer.toString(); @@ -46,23 +47,11 @@ describe("MessagesURL Node", () => { assert.ok(pResult.requestId); assert.ok(pResult.version); assert.deepStrictEqual(pResult.peekedMessageItems.length, 1); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].messageText, - messageContent - ); + assert.deepStrictEqual(pResult.peekedMessageItems[0].messageText, messageContent); assert.deepStrictEqual(pResult.peekedMessageItems[0].dequeueCount, 0); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].messageId, - eResult.messageId - ); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].insertionTime, - eResult.insertionTime - ); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].expirationTime, - eResult.expirationTime - ); + assert.deepStrictEqual(pResult.peekedMessageItems[0].messageId, eResult.messageId); + assert.deepStrictEqual(pResult.peekedMessageItems[0].insertionTime, eResult.insertionTime); + assert.deepStrictEqual(pResult.peekedMessageItems[0].expirationTime, eResult.expirationTime); let dResult = await messagesURL.dequeue(Aborter.none, { visibilitytimeout: 10, @@ -72,42 +61,35 @@ describe("MessagesURL Node", () => { assert.ok(dResult.requestId); assert.ok(dResult.version); assert.deepStrictEqual(dResult.dequeuedMessageItems.length, 1); - assert.deepStrictEqual( - dResult.dequeuedMessageItems[0].messageText, - messageContent - ); + assert.deepStrictEqual(dResult.dequeuedMessageItems[0].messageText, messageContent); assert.deepStrictEqual(dResult.dequeuedMessageItems[0].dequeueCount, 1); - assert.deepStrictEqual( - dResult.dequeuedMessageItems[0].messageId, - eResult.messageId - ); - assert.deepStrictEqual( - dResult.dequeuedMessageItems[0].insertionTime, - eResult.insertionTime - ); - assert.deepStrictEqual( - dResult.dequeuedMessageItems[0].expirationTime, - eResult.expirationTime - ); + assert.deepStrictEqual(dResult.dequeuedMessageItems[0].messageId, eResult.messageId); + assert.deepStrictEqual(dResult.dequeuedMessageItems[0].insertionTime, eResult.insertionTime); + assert.deepStrictEqual(dResult.dequeuedMessageItems[0].expirationTime, eResult.expirationTime); assert.ok(dResult.dequeuedMessageItems[0].popReceipt); assert.ok(dResult.dequeuedMessageItems[0].timeNextVisible); }); it("enqueue negative with 65537B(64KB+1B) characters including special char which is computed after encoding", async () => { let messagesURL = MessagesURL.fromQueueURL(queueURL); - let specialChars = '!@#$%^&*()_+`-=[]\|};\'":,./?><`~漢字㒈保ᨍ揫^p[뷁)׷񬓔7񈺝l鮍򧽶ͺ簣ڞ츊䈗㝯綞߫⯹?ÎᦡC왶żsmt㖩닡򈸱𕩣ОլFZ򃀮9tC榅ٻ컦驿Ϳ[𱿛봻烌󱰷򙥱Ռ򽒏򘤰δŊϜ췮㐦9ͽƙp퐂ʩ由巩•KFÓ֮򨾭⨿󊻅aBm󶴂旨Ϣ񓙠򻐪񇧱򆋸ջ֨ipn򒷐ꝷՆ򆊙斡賆𒚑m˞\𻆕󛿓򐞺Ӯ򡗺򴜍<񐸩԰Bu)򁉂񖨞á<џɏ嗂�⨣1PJ㬵┡ḸI򰱂ˮaࢸ۳i灛ȯɨb𹺪򕕱뿶uٔ䎴񷯆Φ륽󬃨س_NƵ¦' - let buffer = Buffer.alloc(64*1024 + 1); - buffer.fill('a'); + let specialChars = + "!@#$%^&*()_+`-=[]|};'\":,./?><`~漢字㒈保ᨍ揫^p[뷁)׷񬓔7񈺝l鮍򧽶ͺ簣ڞ츊䈗㝯綞߫⯹?ÎᦡC왶żsmt㖩닡򈸱𕩣ОլFZ򃀮9tC榅ٻ컦驿Ϳ[𱿛봻烌󱰷򙥱Ռ򽒏򘤰δŊϜ췮㐦9ͽƙp퐂ʩ由巩•KFÓ֮򨾭⨿󊻅aBm󶴂旨Ϣ񓙠򻐪񇧱򆋸ջ֨ipn򒷐ꝷՆ򆊙斡賆𒚑m˞𻆕󛿓򐞺Ӯ򡗺򴜍<񐸩԰Bu)򁉂񖨞á<џɏ嗂�⨣1PJ㬵┡ḸI򰱂ˮaࢸ۳i灛ȯɨb𹺪򕕱뿶uٔ䎴񷯆Φ륽󬃨س_NƵ¦"; + let buffer = Buffer.alloc(64 * 1024 + 1); + buffer.fill("a"); buffer.write(specialChars, 0); let messageContent = buffer.toString(); - let error + let error; try { await messagesURL.enqueue(Aborter.none, messageContent, {}); - } catch(err) { - error = err + } catch (err) { + error = err; } - assert.ok(error) - assert.ok(error.message.includes("The request body is too large and exceeds the maximum permissible limit.")) + assert.ok(error); + assert.ok( + error.message.includes( + "The request body is too large and exceeds the maximum permissible limit." + ) + ); }); -}); \ No newline at end of file +}); diff --git a/sdk/storage/storage-queue/test/node/sas.test.ts b/sdk/storage/storage-queue/test/node/sas.test.ts index aadf45f837d1..085a4c0adbe0 100644 --- a/sdk/storage/storage-queue/test/node/sas.test.ts +++ b/sdk/storage/storage-queue/test/node/sas.test.ts @@ -190,10 +190,7 @@ describe("Shared Access Signature (SAS) generation Node.js only", () => { ); const sasURL = `${queueURL.url}?${queueSAS}`; - const queueURLwithSAS = new QueueURL( - sasURL, - StorageURL.newPipeline(new AnonymousCredential()) - ); + const queueURLwithSAS = new QueueURL(sasURL, StorageURL.newPipeline(new AnonymousCredential())); await queueURLwithSAS.getProperties(Aborter.none); await queueURL.delete(Aborter.none); @@ -235,18 +232,12 @@ describe("Shared Access Signature (SAS) generation Node.js only", () => { sasURLForMessages, StorageURL.newPipeline(new AnonymousCredential()) ); - const enqueueResult = await messagesURLWithSAS.enqueue( - Aborter.none, - messageContent - ); + const enqueueResult = await messagesURLWithSAS.enqueue(Aborter.none, messageContent); let pResult = await messagesURL.peek(Aborter.none); assert.deepStrictEqual(pResult.peekedMessageItems.length, 1); - const messageIdURL = MessageIdURL.fromMessagesURL( - messagesURL, - enqueueResult.messageId - ); + const messageIdURL = MessageIdURL.fromMessagesURL(messagesURL, enqueueResult.messageId); const sasURLForMessageId = `${messageIdURL.url}?${queueSAS}`; const messageIdURLWithSAS = new MessageIdURL( sasURLForMessageId, @@ -306,23 +297,14 @@ describe("Shared Access Signature (SAS) generation Node.js only", () => { const messageContent = "hello"; - const eResult = await messagesURLwithSAS.enqueue( - Aborter.none, - messageContent - ); + const eResult = await messagesURLwithSAS.enqueue(Aborter.none, messageContent); assert.ok(eResult.messageId); const pResult = await messagesURLwithSAS.peek(Aborter.none); - assert.deepStrictEqual( - pResult.peekedMessageItems[0].messageText, - messageContent - ); + assert.deepStrictEqual(pResult.peekedMessageItems[0].messageText, messageContent); const dResult = await messagesURLwithSAS.dequeue(Aborter.none, { visibilitytimeout: 1 }); - assert.deepStrictEqual( - dResult.dequeuedMessageItems[0].messageText, - messageContent - ); + assert.deepStrictEqual(dResult.dequeuedMessageItems[0].messageText, messageContent); await sleep(2 * 1000); diff --git a/sdk/storage/storage-queue/test/queueurl.test.ts b/sdk/storage/storage-queue/test/queueurl.test.ts index efac43b89276..3c0504aed2aa 100644 --- a/sdk/storage/storage-queue/test/queueurl.test.ts +++ b/sdk/storage/storage-queue/test/queueurl.test.ts @@ -4,7 +4,7 @@ import { Aborter } from "../src/Aborter"; import { QueueURL } from "../src/QueueURL"; import { getQSU, getUniqueName } from "./utils"; import * as dotenv from "dotenv"; -dotenv.config({path:"../.env"}); +dotenv.config({ path: "../.env" }); describe("QueueURL", () => { const serviceURL = getQSU(); @@ -42,8 +42,8 @@ describe("QueueURL", () => { }); it("getPropertis negative", async () => { - const queueName2 = getUniqueName("queue") - const queueURL2 = QueueURL.fromServiceURL(serviceURL, queueName2) + const queueName2 = getUniqueName("queue"); + const queueURL2 = QueueURL.fromServiceURL(serviceURL, queueName2); let error; try { await queueURL2.getProperties(Aborter.none); @@ -52,13 +52,13 @@ describe("QueueURL", () => { } assert.ok(error); assert.ok(error.statusCode); - assert.deepEqual(error.statusCode, 404) - assert.ok(error.response) - assert.ok(error.response.body) - assert.ok(error.response.body.includes("QueueNotFound")) - }) + assert.deepEqual(error.statusCode, 404); + assert.ok(error.response); + assert.ok(error.response.body); + assert.ok(error.response.body.includes("QueueNotFound")); + }); - it("create with default parameters", done => { + it("create with default parameters", (done) => { // create() with default parameters has been tested in beforeEach done(); }); @@ -72,23 +72,23 @@ describe("QueueURL", () => { }); // create with invalid queue name - it("create negative", async() => { + it("create negative", async () => { const qURL = QueueURL.fromServiceURL(serviceURL, ""); let error; try { await qURL.create(Aborter.none); - } catch(err) { + } catch (err) { error = err; } assert.ok(error); assert.ok(error.statusCode); - assert.deepEqual(error.statusCode, 400) - assert.ok(error.response) - assert.ok(error.response.body) - assert.ok(error.response.body.includes("InvalidResourceName")) + assert.deepEqual(error.statusCode, 400); + assert.ok(error.response); + assert.ok(error.response.body); + assert.ok(error.response.body.includes("InvalidResourceName")); }); - it("delete", done => { + it("delete", (done) => { // delete() with default parameters has been tested in afterEach done(); }); diff --git a/sdk/storage/storage-queue/test/retrypolicy.test.ts b/sdk/storage/storage-queue/test/retrypolicy.test.ts index c18b99e38caa..b49787db4a1c 100644 --- a/sdk/storage/storage-queue/test/retrypolicy.test.ts +++ b/sdk/storage/storage-queue/test/retrypolicy.test.ts @@ -8,7 +8,7 @@ import { Pipeline } from "../src/Pipeline"; import { getQSU, getUniqueName } from "./utils"; import { InjectorPolicyFactory } from "./utils/InjectorPolicyFactory"; import * as dotenv from "dotenv"; -dotenv.config({path:"../.env"}); +dotenv.config({ path: "../.env" }); describe("RetryPolicy", () => { const serviceURL = getQSU(); @@ -30,11 +30,7 @@ describe("RetryPolicy", () => { const injector = new InjectorPolicyFactory(() => { if (injectCounter === 0) { injectCounter++; - return new RestError( - "Server Internal Error", - "ServerInternalError", - 500 - ); + return new RestError("Server Internal Error", "ServerInternalError", 500); } }); const factories = queueURL.pipeline.factories.slice(); // clone factories array @@ -58,10 +54,7 @@ describe("RetryPolicy", () => { return new RestError("Server Internal Error", "ServerInternalError", 500); }); - const credential = - queueURL.pipeline.factories[ - queueURL.pipeline.factories.length - 1 - ]; + const credential = queueURL.pipeline.factories[queueURL.pipeline.factories.length - 1]; const factories = StorageURL.newPipeline(credential, { retryOptions: { maxTries: 3 } }).factories; @@ -87,11 +80,7 @@ describe("RetryPolicy", () => { let injectCounter = 0; const injector = new InjectorPolicyFactory(() => { if (injectCounter++ < 1) { - return new RestError( - "Server Internal Error", - "ServerInternalError", - 500 - ); + return new RestError("Server Internal Error", "ServerInternalError", 500); } }); @@ -104,10 +93,7 @@ describe("RetryPolicy", () => { hostParts.unshift(secondaryAccount); const secondaryHost = hostParts.join("."); - const credential = - queueURL.pipeline.factories[ - queueURL.pipeline.factories.length - 1 - ]; + const credential = queueURL.pipeline.factories[queueURL.pipeline.factories.length - 1]; const factories = StorageURL.newPipeline(credential, { retryOptions: { maxTries: 2, secondaryHost } }).factories; @@ -123,9 +109,6 @@ describe("RetryPolicy", () => { finalRequestURL = err.request ? err.request.url : ""; } - assert.deepStrictEqual( - URLBuilder.parse(finalRequestURL).getHost(), - secondaryHost - ); + assert.deepStrictEqual(URLBuilder.parse(finalRequestURL).getHost(), secondaryHost); }); }); diff --git a/sdk/storage/storage-queue/test/serviceurl.test.ts b/sdk/storage/storage-queue/test/serviceurl.test.ts index 641d256b532a..4861e817d1fb 100644 --- a/sdk/storage/storage-queue/test/serviceurl.test.ts +++ b/sdk/storage/storage-queue/test/serviceurl.test.ts @@ -5,7 +5,7 @@ import { QueueURL } from "../src/QueueURL"; import { ServiceURL } from "../src/ServiceURL"; import { getAlternateQSU, getQSU, getUniqueName, wait } from "./utils"; import * as dotenv from "dotenv"; -dotenv.config({path:"../.env"}); +dotenv.config({ path: "../.env" }); describe("ServiceURL", () => { it("listQueuesSegment with default parameters", async () => { @@ -36,30 +36,22 @@ describe("ServiceURL", () => { await queueURL1.create(Aborter.none, { metadata: { key: "val" } }); await queueURL2.create(Aborter.none, { metadata: { key: "val" } }); - const result1 = await serviceURL.listQueuesSegment( - Aborter.none, - undefined, - { - include: 'metadata', - maxresults: 1, - prefix: queueNamePrefix - } - ); + const result1 = await serviceURL.listQueuesSegment(Aborter.none, undefined, { + include: "metadata", + maxresults: 1, + prefix: queueNamePrefix + }); assert.ok(result1.nextMarker); assert.equal(result1.queueItems!.length, 1); assert.ok(result1.queueItems![0].name.startsWith(queueNamePrefix)); assert.deepEqual(result1.queueItems![0].metadata!.key, "val"); - const result2 = await serviceURL.listQueuesSegment( - Aborter.none, - result1.nextMarker, - { - include: 'metadata', - maxresults: 1, - prefix: queueNamePrefix - } - ); + const result2 = await serviceURL.listQueuesSegment(Aborter.none, result1.nextMarker, { + include: "metadata", + maxresults: 1, + prefix: queueNamePrefix + }); assert.ok(!result2.nextMarker); assert.equal(result2.queueItems!.length, 1); @@ -148,7 +140,7 @@ describe("ServiceURL", () => { assert.deepEqual(result.hourMetrics, serviceProperties.hourMetrics); }); - it("getStatistics with default/all parameters secondary", done => { + it("getStatistics with default/all parameters secondary", (done) => { let serviceURL: ServiceURL | undefined; try { serviceURL = getAlternateQSU(); @@ -159,7 +151,7 @@ describe("ServiceURL", () => { serviceURL! .getStatistics(Aborter.none) - .then(result => { + .then((result) => { assert.ok(result.geoReplication!.lastSyncTime); done(); }) diff --git a/sdk/storage/storage-queue/test/utils/InjectorPolicy.ts b/sdk/storage/storage-queue/test/utils/InjectorPolicy.ts index 07f566a7acc5..3d41732dcddb 100644 --- a/sdk/storage/storage-queue/test/utils/InjectorPolicy.ts +++ b/sdk/storage/storage-queue/test/utils/InjectorPolicy.ts @@ -1,58 +1,51 @@ import { - BaseRequestPolicy, - HttpOperationResponse, - RequestPolicy, - RequestPolicyOptions, - WebResource, - RestError - } from "../../src"; - - export interface INextInjectErrorHolder { - nextInjectError?: RestError; + BaseRequestPolicy, + HttpOperationResponse, + RequestPolicy, + RequestPolicyOptions, + WebResource, + RestError +} from "../../src"; + +export interface INextInjectErrorHolder { + nextInjectError?: RestError; +} + +export type Injector = () => RestError | undefined; + +/** + * InjectorPolicy will inject a customized error before next HTTP request. + * + * @class InjectorPolicy + * @extends {BaseRequestPolicy} + */ +export class InjectorPolicy extends BaseRequestPolicy { + /** + * Creates an instance of InjectorPolicy. + * + * @param {RequestPolicy} nextPolicy + * @param {RequestPolicyOptions} options + * @memberof InjectorPolicy + */ + public constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, injector: Injector) { + super(nextPolicy, options); + this.injector = injector; } - - export type Injector = () => RestError | undefined; - + /** - * InjectorPolicy will inject a customized error before next HTTP request. + * Sends request. * - * @class InjectorPolicy - * @extends {BaseRequestPolicy} + * @param {WebResource} request + * @returns {Promise} + * @memberof InjectorPolicy */ - export class InjectorPolicy extends BaseRequestPolicy { - /** - * Creates an instance of InjectorPolicy. - * - * @param {RequestPolicy} nextPolicy - * @param {RequestPolicyOptions} options - * @memberof InjectorPolicy - */ - public constructor( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions, - injector: Injector - ) { - super(nextPolicy, options); - this.injector = injector; - } - - /** - * Sends request. - * - * @param {WebResource} request - * @returns {Promise} - * @memberof InjectorPolicy - */ - public async sendRequest( - request: WebResource - ): Promise { - const error = this.injector(); - if (error) { - throw error; - } - return this._nextPolicy.sendRequest(request); + public async sendRequest(request: WebResource): Promise { + const error = this.injector(); + if (error) { + throw error; } - - private injector: Injector; + return this._nextPolicy.sendRequest(request); } - \ No newline at end of file + + private injector: Injector; +} diff --git a/sdk/storage/storage-queue/test/utils/InjectorPolicyFactory.ts b/sdk/storage/storage-queue/test/utils/InjectorPolicyFactory.ts index f2eab351b18d..73ca1749b535 100644 --- a/sdk/storage/storage-queue/test/utils/InjectorPolicyFactory.ts +++ b/sdk/storage/storage-queue/test/utils/InjectorPolicyFactory.ts @@ -1,29 +1,21 @@ -import { - RequestPolicy, - RequestPolicyFactory, - RequestPolicyOptions - } from "../../src"; - import { InjectorPolicy, Injector } from "./InjectorPolicy"; - - /** - * InjectorPolicyFactory is a factory class injects customized errors for retry policy testing. - * - * @export - * @class InjectorPolicyFactory - * @implements {RequestPolicyFactory} - */ - export class InjectorPolicyFactory implements RequestPolicyFactory { - public readonly injector: Injector; - - public constructor(injector: Injector) { - this.injector = injector; - } - - public create( - nextPolicy: RequestPolicy, - options: RequestPolicyOptions - ): InjectorPolicy { - return new InjectorPolicy(nextPolicy, options, this.injector); - } +import { RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "../../src"; +import { InjectorPolicy, Injector } from "./InjectorPolicy"; + +/** + * InjectorPolicyFactory is a factory class injects customized errors for retry policy testing. + * + * @export + * @class InjectorPolicyFactory + * @implements {RequestPolicyFactory} + */ +export class InjectorPolicyFactory implements RequestPolicyFactory { + public readonly injector: Injector; + + public constructor(injector: Injector) { + this.injector = injector; } - \ No newline at end of file + + public create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): InjectorPolicy { + return new InjectorPolicy(nextPolicy, options, this.injector); + } +} diff --git a/sdk/storage/storage-queue/test/utils/index.browser.ts b/sdk/storage/storage-queue/test/utils/index.browser.ts index f9cf1aa051f3..696ce7c7957b 100644 --- a/sdk/storage/storage-queue/test/utils/index.browser.ts +++ b/sdk/storage/storage-queue/test/utils/index.browser.ts @@ -4,10 +4,7 @@ import { StorageURL } from "../../src/StorageURL"; export * from "./testutils.common"; -export function getGenericQSU( - accountType: string, - accountNameSuffix: string = "" -): ServiceURL { +export function getGenericQSU(accountType: string, accountNameSuffix: string = ""): ServiceURL { const accountNameEnvVar = `${accountType}ACCOUNT_NAME`; const accountSASEnvVar = `${accountType}ACCOUNT_SAS`; @@ -84,10 +81,7 @@ export async function blobToArrayBuffer(blob: Blob): Promise { }); } -export function arrayBufferEqual( - buf1: ArrayBuffer, - buf2: ArrayBuffer -): boolean { +export function arrayBufferEqual(buf1: ArrayBuffer, buf2: ArrayBuffer): boolean { if (buf1.byteLength !== buf2.byteLength) { return false; } diff --git a/sdk/storage/storage-queue/test/utils/index.ts b/sdk/storage/storage-queue/test/utils/index.ts index 69a10ea21650..22b30798a188 100644 --- a/sdk/storage/storage-queue/test/utils/index.ts +++ b/sdk/storage/storage-queue/test/utils/index.ts @@ -7,10 +7,7 @@ import { StorageURL } from "../../src/StorageURL"; export * from "./testutils.common"; -export function getGenericQSU( - accountType: string, - accountNameSuffix: string = "" -): ServiceURL { +export function getGenericQSU(accountType: string, accountNameSuffix: string = ""): ServiceURL { const accountNameEnvVar = `${accountType}ACCOUNT_NAME`; const accountKeyEnvVar = `${accountType}ACCOUNT_KEY`; diff --git a/sdk/storage/storage-queue/test/utils/testutils.common.ts b/sdk/storage/storage-queue/test/utils/testutils.common.ts index 4ec999c08633..de4d969696c9 100644 --- a/sdk/storage/storage-queue/test/utils/testutils.common.ts +++ b/sdk/storage/storage-queue/test/utils/testutils.common.ts @@ -14,7 +14,7 @@ export function getUniqueName(prefix: string): string { } export async function sleep(time: number): Promise { - return new Promise(resolve => { + return new Promise((resolve) => { setTimeout(resolve, time); }); } @@ -24,17 +24,13 @@ export function base64encode(content: string): string { } export function base64decode(encodedString: string): string { - return isBrowser() - ? atob(encodedString) - : Buffer.from(encodedString, "base64").toString(); + return isBrowser() ? atob(encodedString) : Buffer.from(encodedString, "base64").toString(); } export class ConsoleHttpPipelineLogger implements IHttpPipelineLogger { constructor(public minimumLogLevel: HttpPipelineLogLevel) {} public log(logLevel: HttpPipelineLogLevel, message: string): void { - const logMessage = `${new Date().toISOString()} ${ - HttpPipelineLogLevel[logLevel] - }: ${message}`; + const logMessage = `${new Date().toISOString()} ${HttpPipelineLogLevel[logLevel]}: ${message}`; switch (logLevel) { case HttpPipelineLogLevel.ERROR: // tslint:disable-next-line:no-console @@ -53,7 +49,7 @@ export class ConsoleHttpPipelineLogger implements IHttpPipelineLogger { } export async function wait(time: number): Promise { - return new Promise(resolve => { + return new Promise((resolve) => { setTimeout(resolve, time); }); } diff --git a/sdk/storage/storage-queue/tsconfig.json b/sdk/storage/storage-queue/tsconfig.json index 61885eb2e18c..e271ee388662 100644 --- a/sdk/storage/storage-queue/tsconfig.json +++ b/sdk/storage/storage-queue/tsconfig.json @@ -22,4 +22,4 @@ "compileOnSave": true, "exclude": ["node_modules", "./samples/*"], "include": ["./src/**/*.ts", "./test/**/*.ts"] -} \ No newline at end of file +}