From fb152db08a15a81edd2a734efbc67a7713c31fcc Mon Sep 17 00:00:00 2001 From: "Kamat, Trivikram" <16024985+trivikr@users.noreply.github.com> Date: Wed, 8 May 2024 20:52:57 +0000 Subject: [PATCH 1/5] Bump prettier to 3.2.5 --- package.json | 2 +- yarn.lock | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/package.json b/package.json index 6fabe5bfdab..94dbe0273b4 100644 --- a/package.json +++ b/package.json @@ -59,7 +59,7 @@ "karma-sourcemap-loader": "0.3.8", "karma-typescript": "5.5.3", "karma-webpack": "5.0.0", - "prettier": "2.2.1", + "prettier": "3.2.5", "puppeteer": "^19.2.0", "ts-jest": "28.0.5", "turbo": "latest", diff --git a/yarn.lock b/yarn.lock index 072d02ec77a..9ea1d682daf 100644 --- a/yarn.lock +++ b/yarn.lock @@ -8996,12 +8996,12 @@ __metadata: languageName: node linkType: hard -"prettier@npm:2.2.1": - version: 2.2.1 - resolution: "prettier@npm:2.2.1" +"prettier@npm:3.2.5": + version: 3.2.5 + resolution: "prettier@npm:3.2.5" bin: - prettier: bin-prettier.js - checksum: 800de2df3d37067ab24478c7f32c60ca0c57b01742133287829feeb4a70d239a7bf6bccb56196784777af591ad80fb9ba70c1a49b0fcecf9f5622a764d513edb + prettier: bin/prettier.cjs + checksum: 2ee4e1417572372afb7a13bb446b34f20f1bf1747db77cf6ccaf57a9be005f2f15c40f903d41a6b79eec3f57fff14d32a20fb6dee1f126da48908926fe43c311 languageName: node linkType: hard @@ -9877,7 +9877,7 @@ __metadata: karma-sourcemap-loader: 0.3.8 karma-typescript: 5.5.3 karma-webpack: 5.0.0 - prettier: 2.2.1 + prettier: 3.2.5 puppeteer: ^19.2.0 rimraf: ^3.0.2 ts-jest: 28.0.5 From d715e884e449512d12c127b775212c0733f40f6c Mon Sep 17 00:00:00 2001 From: "Kamat, Trivikram" <16024985+trivikr@users.noreply.github.com> Date: Wed, 8 May 2024 21:00:08 +0000 Subject: [PATCH 2/5] chore: set trailingComma to 'es5' to undo large refactor --- prettier.config.js | 1 + 1 file changed, 1 insertion(+) diff --git a/prettier.config.js b/prettier.config.js index 20ccf897315..05097dd1f06 100644 --- a/prettier.config.js +++ b/prettier.config.js @@ -1,4 +1,5 @@ module.exports = { // Custom printWidth: 120, + trailingComma: "es5" }; From ac17f2a08d948fe1975a877a4a27e88948e2c151 Mon Sep 17 00:00:00 2001 From: "Kamat, Trivikram" <16024985+trivikr@users.noreply.github.com> Date: Wed, 8 May 2024 21:15:57 +0000 Subject: [PATCH 3/5] chore: yarn prettier --write packages/**/*.{ts,md,json} --- .../src/regionInfo/getResolvedHostname.ts | 4 +- .../getHttpAuthSchemeEndpointRuleSetPlugin.ts | 4 +- .../getHttpAuthSchemePlugin.ts | 4 +- .../httpAuthSchemeMiddleware.ts | 93 +-- .../httpSigningMiddleware.ts | 55 +- .../core/src/pagination/createPaginator.ts | 2 +- packages/core/src/protocols/requestBuilder.ts | 5 +- .../error/InstanceMetadataV1FallbackError.ts | 5 +- .../src/fromInstanceMetadata.spec.ts | 4 +- ...xtendedInstanceMetadataCredentials.spec.ts | 4 +- .../src/utils/staticStabilityProvider.spec.ts | 2 +- .../src/HeaderMarshaller.spec.ts | 42 +- .../eventstream-codec/src/HeaderMarshaller.ts | 5 +- .../src/TestVectors.fixture.ts | 594 +----------------- .../src/HttpAuthSchemeProvider.ts | 2 +- .../src/endpointRuleSet.ts | 74 +-- .../getHttpAuthSchemeEndpointRuleSetPlugin.ts | 4 +- .../getHttpAuthSchemePlugin.ts | 4 +- .../httpAuthSchemeMiddleware.ts | 93 +-- .../httpSigningMiddleware.ts | 51 +- .../hash-stream-node/src/HashCalculator.ts | 5 +- .../src/readableStreamHasher.spec.ts | 10 +- .../src/applyMd5BodyChecksumMiddleware.ts | 59 +- .../src/compressionMiddleware.spec.ts | 4 +- .../src/compressionMiddleware.ts | 117 ++-- .../middleware-content-length/src/index.ts | 53 +- .../adaptors/getEndpointFromInstructions.ts | 4 +- .../src/endpointMiddleware.ts | 81 ++- .../src/StandardRetryStrategy.spec.ts | 32 +- .../src/StandardRetryStrategy.ts | 5 +- .../src/middleware-retry.integ.spec.ts | 3 +- .../src/omitRetryHeadersMiddleware.spec.ts | 2 +- .../src/omitRetryHeadersMiddleware.ts | 23 +- .../src/retryMiddleware.spec.ts | 16 +- .../middleware-retry/src/retryMiddleware.ts | 122 ++-- .../src/deserializerMiddleware.ts | 84 ++- packages/middleware-serde/src/serdePlugin.ts | 2 +- .../src/serializerMiddleware.ts | 60 +- .../src/MiddlewareStack.spec.ts | 17 +- .../middleware-stack/src/MiddlewareStack.ts | 17 +- packages/middleware-stack/src/types.ts | 2 +- packages/node-config-provider/src/fromEnv.ts | 26 +- .../src/fromSharedConfigFiles.ts | 51 +- .../src/node-http-handler.spec.ts | 2 +- .../src/node-http-handler.ts | 10 +- packages/node-http-handler/src/server.mock.ts | 80 ++- .../src/CredentialsProviderError.ts | 5 +- .../property-provider/src/ProviderError.ts | 5 +- .../src/TokenProviderError.ts | 5 +- packages/property-provider/src/chain.ts | 36 +- packages/property-provider/src/fromStatic.ts | 5 +- .../src/sdk-client-toc-plugin.ts | 6 +- .../signature-v4/src/HeaderFormatter.spec.ts | 42 +- packages/signature-v4/src/SignatureV4.spec.ts | 2 +- packages/smithy-client/src/client.ts | 5 +- packages/smithy-client/src/command.ts | 21 +- .../types/src/auth/HttpAuthSchemeProvider.ts | 2 +- packages/types/src/client.ts | 2 +- packages/types/src/command.ts | 2 +- .../transform/type-transform.ts | 16 +- .../src/transform/client-method-transforms.ts | 19 +- .../client-payload-blob-type-narrow.spec.ts | 8 +- .../client-payload-blob-type-narrow.ts | 22 +- .../types/src/transform/no-undefined.spec.ts | 12 +- packages/types/src/transform/no-undefined.ts | 36 +- .../types/src/transform/type-transform.ts | 18 +- .../util-base64/src/toBase64.browser.spec.ts | 2 +- .../util-retry/src/AdaptiveRetryStrategy.ts | 5 +- .../src/sdk-stream-mixin.spec.ts | 2 +- .../util-stream/src/sdk-stream-mixin.spec.ts | 2 +- packages/util-utf8/src/fromUtf8.spec.ts | 128 +--- packages/util-utf8/src/toUtf8.spec.ts | 128 +--- 72 files changed, 831 insertions(+), 1643 deletions(-) diff --git a/packages/config-resolver/src/regionInfo/getResolvedHostname.ts b/packages/config-resolver/src/regionInfo/getResolvedHostname.ts index 1c5ac6f75e0..b22b2b78792 100644 --- a/packages/config-resolver/src/regionInfo/getResolvedHostname.ts +++ b/packages/config-resolver/src/regionInfo/getResolvedHostname.ts @@ -16,5 +16,5 @@ export const getResolvedHostname = ( regionHostname ? regionHostname : partitionHostname - ? partitionHostname.replace("{region}", resolvedRegion) - : undefined; + ? partitionHostname.replace("{region}", resolvedRegion) + : undefined; diff --git a/packages/core/src/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.ts b/packages/core/src/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.ts index cc6c03afcbb..4bea7d6048d 100644 --- a/packages/core/src/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.ts +++ b/packages/core/src/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.ts @@ -30,7 +30,7 @@ interface HttpAuthSchemeEndpointRuleSetPluginOptions< TConfig extends object, TContext extends HandlerExecutionContext, TParameters extends HttpAuthSchemeParameters, - TInput extends object + TInput extends object, > { httpAuthSchemeParametersProvider: HttpAuthSchemeParametersProvider; identityProviderConfigProvider: (config: TConfig) => Promise; @@ -43,7 +43,7 @@ export const getHttpAuthSchemeEndpointRuleSetPlugin = < TConfig extends object, TContext extends HandlerExecutionContext, TParameters extends HttpAuthSchemeParameters, - TInput extends object + TInput extends object, >( config: TConfig & PreviouslyResolved, { diff --git a/packages/core/src/middleware-http-auth-scheme/getHttpAuthSchemePlugin.ts b/packages/core/src/middleware-http-auth-scheme/getHttpAuthSchemePlugin.ts index 56dba5e3d71..919b569da16 100644 --- a/packages/core/src/middleware-http-auth-scheme/getHttpAuthSchemePlugin.ts +++ b/packages/core/src/middleware-http-auth-scheme/getHttpAuthSchemePlugin.ts @@ -30,7 +30,7 @@ interface HttpAuthSchemePluginOptions< TConfig extends object, TContext extends HandlerExecutionContext, TParameters extends HttpAuthSchemeParameters, - TInput extends object + TInput extends object, > { httpAuthSchemeParametersProvider: HttpAuthSchemeParametersProvider; identityProviderConfigProvider: (config: TConfig) => Promise; @@ -43,7 +43,7 @@ export const getHttpAuthSchemePlugin = < TConfig extends object, TContext extends HandlerExecutionContext, TParameters extends HttpAuthSchemeParameters, - TInput extends object + TInput extends object, >( config: TConfig & PreviouslyResolved, { diff --git a/packages/core/src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts b/packages/core/src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts index ac2b15f0c59..80251e7abfc 100644 --- a/packages/core/src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts +++ b/packages/core/src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts @@ -30,7 +30,7 @@ interface HttpAuthSchemeMiddlewareOptions< TConfig extends object, TContext extends HandlerExecutionContext, TParameters extends HttpAuthSchemeParameters, - TInput extends object + TInput extends object, > { httpAuthSchemeParametersProvider: HttpAuthSchemeParametersProvider; identityProviderConfigProvider: (config: TConfig) => Promise; @@ -65,50 +65,51 @@ function convertHttpAuthSchemesToMap(httpAuthSchemes: HttpAuthScheme[]): Map( - config: TConfig & PreviouslyResolved, - mwOptions: HttpAuthSchemeMiddlewareOptions -): SerializeMiddleware => ( - next: SerializeHandler, - context: HttpAuthSchemeMiddlewareHandlerExecutionContext -): SerializeHandler => async ( - args: SerializeHandlerArguments -): Promise> => { - const options = config.httpAuthSchemeProvider( - await mwOptions.httpAuthSchemeParametersProvider(config, context as TContext, args.input) - ); - const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); - const smithyContext: HttpAuthSchemeMiddlewareSmithyContext = getSmithyContext(context); - const failureReasons = []; - for (const option of options) { - const scheme = authSchemes.get(option.schemeId); - if (!scheme) { - failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); - continue; +export const httpAuthSchemeMiddleware = + < + TInput extends object, + Output extends object, + TConfig extends object, + TContext extends HttpAuthSchemeMiddlewareHandlerExecutionContext, + TParameters extends HttpAuthSchemeParameters, + >( + config: TConfig & PreviouslyResolved, + mwOptions: HttpAuthSchemeMiddlewareOptions + ): SerializeMiddleware => + ( + next: SerializeHandler, + context: HttpAuthSchemeMiddlewareHandlerExecutionContext + ): SerializeHandler => + async (args: SerializeHandlerArguments): Promise> => { + const options = config.httpAuthSchemeProvider( + await mwOptions.httpAuthSchemeParametersProvider(config, context as TContext, args.input) + ); + const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); + const smithyContext: HttpAuthSchemeMiddlewareSmithyContext = getSmithyContext(context); + const failureReasons = []; + for (const option of options) { + const scheme = authSchemes.get(option.schemeId); + if (!scheme) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); + continue; + } + const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); + if (!identityProvider) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); + continue; + } + const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; + option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); + option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); + smithyContext.selectedHttpAuthScheme = { + httpAuthOption: option, + identity: await identityProvider(option.identityProperties), + signer: scheme.signer, + }; + break; } - const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); - if (!identityProvider) { - failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); - continue; + if (!smithyContext.selectedHttpAuthScheme) { + throw new Error(failureReasons.join("\n")); } - const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; - option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); - option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); - smithyContext.selectedHttpAuthScheme = { - httpAuthOption: option, - identity: await identityProvider(option.identityProperties), - signer: scheme.signer, - }; - break; - } - if (!smithyContext.selectedHttpAuthScheme) { - throw new Error(failureReasons.join("\n")); - } - return next(args); -}; + return next(args); + }; diff --git a/packages/core/src/middleware-http-signing/httpSigningMiddleware.ts b/packages/core/src/middleware-http-signing/httpSigningMiddleware.ts index c77fc96acc0..2c24b7906fd 100644 --- a/packages/core/src/middleware-http-signing/httpSigningMiddleware.ts +++ b/packages/core/src/middleware-http-signing/httpSigningMiddleware.ts @@ -38,32 +38,31 @@ const defaultSuccessHandler: SuccessHandler = ( /** * @internal */ -export const httpSigningMiddleware = ( - config: object -): FinalizeRequestMiddleware => ( - next: FinalizeHandler, - context: HttpSigningMiddlewareHandlerExecutionContext -): FinalizeHandler => async ( - args: FinalizeHandlerArguments -): Promise> => { - if (!HttpRequest.isInstance(args.request)) { - return next(args); - } +export const httpSigningMiddleware = + (config: object): FinalizeRequestMiddleware => + ( + next: FinalizeHandler, + context: HttpSigningMiddlewareHandlerExecutionContext + ): FinalizeHandler => + async (args: FinalizeHandlerArguments): Promise> => { + if (!HttpRequest.isInstance(args.request)) { + return next(args); + } - const smithyContext: HttpSigningMiddlewareSmithyContext = getSmithyContext(context); - const scheme = smithyContext.selectedHttpAuthScheme; - if (!scheme) { - throw new Error(`No HttpAuthScheme was selected: unable to sign request`); - } - const { - httpAuthOption: { signingProperties = {} }, - identity, - signer, - } = scheme; - const output = await next({ - ...args, - request: await signer.sign(args.request, identity, signingProperties), - }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); - (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); - return output; -}; + const smithyContext: HttpSigningMiddlewareSmithyContext = getSmithyContext(context); + const scheme = smithyContext.selectedHttpAuthScheme; + if (!scheme) { + throw new Error(`No HttpAuthScheme was selected: unable to sign request`); + } + const { + httpAuthOption: { signingProperties = {} }, + identity, + signer, + } = scheme; + const output = await next({ + ...args, + request: await signer.sign(args.request, identity, signingProperties), + }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); + (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); + return output; + }; diff --git a/packages/core/src/pagination/createPaginator.ts b/packages/core/src/pagination/createPaginator.ts index a82a49209b8..dd3fb09adcb 100644 --- a/packages/core/src/pagination/createPaginator.ts +++ b/packages/core/src/pagination/createPaginator.ts @@ -20,7 +20,7 @@ const makePagedClientRequest = async , export function createPaginator< PaginationConfigType extends PaginationConfiguration, InputType extends object, - OutputType extends object + OutputType extends object, >( ClientCtor: any, CommandCtor: any, diff --git a/packages/core/src/protocols/requestBuilder.ts b/packages/core/src/protocols/requestBuilder.ts index 963c4675d22..7abd252f00f 100644 --- a/packages/core/src/protocols/requestBuilder.ts +++ b/packages/core/src/protocols/requestBuilder.ts @@ -23,7 +23,10 @@ export class RequestBuilder { private resolvePathStack: Array<(path: string) => void> = []; - public constructor(private input: any, private context: SerdeContext) {} + public constructor( + private input: any, + private context: SerdeContext + ) {} public async build() { const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint(); diff --git a/packages/credential-provider-imds/src/error/InstanceMetadataV1FallbackError.ts b/packages/credential-provider-imds/src/error/InstanceMetadataV1FallbackError.ts index b0f4d721b10..b3127bc44e7 100644 --- a/packages/credential-provider-imds/src/error/InstanceMetadataV1FallbackError.ts +++ b/packages/credential-provider-imds/src/error/InstanceMetadataV1FallbackError.ts @@ -9,7 +9,10 @@ import { CredentialsProviderError } from "@smithy/property-provider"; export class InstanceMetadataV1FallbackError extends CredentialsProviderError { public name = "InstanceMetadataV1FallbackError"; - constructor(message: string, public readonly tryNextLink: boolean = true) { + constructor( + message: string, + public readonly tryNextLink: boolean = true + ) { super(message, tryNextLink); Object.setPrototypeOf(this, InstanceMetadataV1FallbackError.prototype); } diff --git a/packages/credential-provider-imds/src/fromInstanceMetadata.spec.ts b/packages/credential-provider-imds/src/fromInstanceMetadata.spec.ts index 22aef475780..e532ae6b838 100644 --- a/packages/credential-provider-imds/src/fromInstanceMetadata.spec.ts +++ b/packages/credential-provider-imds/src/fromInstanceMetadata.spec.ts @@ -60,7 +60,7 @@ describe("fromInstanceMetadata", () => { beforeEach(() => { (staticStabilityProvider as jest.Mock).mockImplementation((input) => input); (getInstanceMetadataEndpoint as jest.Mock).mockResolvedValue({ hostname }); - ((isImdsCredentials as unknown) as jest.Mock).mockReturnValue(true); + (isImdsCredentials as unknown as jest.Mock).mockReturnValue(true); (providerConfigFromInit as jest.Mock).mockReturnValue({ timeout: mockTimeout, maxRetries: mockMaxRetries, @@ -139,7 +139,7 @@ describe("fromInstanceMetadata", () => { .mockResolvedValueOnce(JSON.stringify(mockImdsCreds)); (retry as jest.Mock).mockImplementation((fn: any) => fn()); - ((isImdsCredentials as unknown) as jest.Mock).mockReturnValueOnce(false); + (isImdsCredentials as unknown as jest.Mock).mockReturnValueOnce(false); await expect(fromInstanceMetadata()()).rejects.toEqual( new CredentialsProviderError("Invalid response received from instance metadata service.") diff --git a/packages/credential-provider-imds/src/utils/getExtendedInstanceMetadataCredentials.spec.ts b/packages/credential-provider-imds/src/utils/getExtendedInstanceMetadataCredentials.spec.ts index 35d3e2276db..8ee4cdfa06f 100644 --- a/packages/credential-provider-imds/src/utils/getExtendedInstanceMetadataCredentials.spec.ts +++ b/packages/credential-provider-imds/src/utils/getExtendedInstanceMetadataCredentials.spec.ts @@ -22,7 +22,7 @@ describe("getExtendedInstanceMetadataCredentials()", () => { }); it("should extend the expiration random time(5~10 mins) from now", () => { - const anyDate: Date = ("any date" as unknown) as Date; + const anyDate: Date = "any date" as unknown as Date; (Math.random as jest.Mock).mockReturnValue(0.5); expect(getExtendedInstanceMetadataCredentials({ ...staticSecret, expiration: anyDate }, logger)).toEqual({ ...staticSecret, @@ -33,7 +33,7 @@ describe("getExtendedInstanceMetadataCredentials()", () => { }); it("should print warning message when extending the credentials", () => { - const anyDate: Date = ("any date" as unknown) as Date; + const anyDate: Date = "any date" as unknown as Date; getExtendedInstanceMetadataCredentials({ ...staticSecret, expiration: anyDate }, logger); expect(logger.warn).toBeCalledWith(expect.stringContaining("Attempting credential expiration extension")); }); diff --git a/packages/credential-provider-imds/src/utils/staticStabilityProvider.spec.ts b/packages/credential-provider-imds/src/utils/staticStabilityProvider.spec.ts index a2ea7ddaf40..e0e6cd4cdfd 100644 --- a/packages/credential-provider-imds/src/utils/staticStabilityProvider.spec.ts +++ b/packages/credential-provider-imds/src/utils/staticStabilityProvider.spec.ts @@ -89,7 +89,7 @@ describe("staticStabilityProvider", () => { it("should allow custom logger to print warning messages", async () => { const provider = jest.fn().mockResolvedValueOnce(mockCreds).mockRejectedValue("Error"); - const logger = ({ warn: jest.fn() } as unknown) as Logger; + const logger = { warn: jest.fn() } as unknown as Logger; const stableProvider = staticStabilityProvider(provider, { logger }); expect(await stableProvider()).toEqual(mockCreds); // load initial creds await stableProvider(); diff --git a/packages/eventstream-codec/src/HeaderMarshaller.spec.ts b/packages/eventstream-codec/src/HeaderMarshaller.spec.ts index 6b1a8c5e284..ca70ad00fab 100644 --- a/packages/eventstream-codec/src/HeaderMarshaller.spec.ts +++ b/packages/eventstream-codec/src/HeaderMarshaller.spec.ts @@ -182,45 +182,9 @@ describe("HeaderMarshaller", () => { [ "a sequence of headers", Uint8Array.from([ - 0x04, - 0xf0, - 0x9f, - 0xa6, - 0x84, - 0x06, - 0x00, - 0x04, - 0xde, - 0xad, - 0xbe, - 0xef, - 0x04, - 0xf0, - 0x9f, - 0x8f, - 0x87, - 0x00, - 0x04, - 0xf0, - 0x9f, - 0x90, - 0x8e, - 0x07, - 0x00, - 0x07, - 0xe2, - 0x98, - 0x83, - 0xf0, - 0x9f, - 0x92, - 0xa9, - 0x04, - 0xf0, - 0x9f, - 0x90, - 0xb4, - 0x01, + 0x04, 0xf0, 0x9f, 0xa6, 0x84, 0x06, 0x00, 0x04, 0xde, 0xad, 0xbe, 0xef, 0x04, 0xf0, 0x9f, 0x8f, 0x87, 0x00, + 0x04, 0xf0, 0x9f, 0x90, 0x8e, 0x07, 0x00, 0x07, 0xe2, 0x98, 0x83, 0xf0, 0x9f, 0x92, 0xa9, 0x04, 0xf0, 0x9f, + 0x90, 0xb4, 0x01, ]), { "🦄": { diff --git a/packages/eventstream-codec/src/HeaderMarshaller.ts b/packages/eventstream-codec/src/HeaderMarshaller.ts index 63f688541b3..e93db024919 100644 --- a/packages/eventstream-codec/src/HeaderMarshaller.ts +++ b/packages/eventstream-codec/src/HeaderMarshaller.ts @@ -7,7 +7,10 @@ import { Int64 } from "./Int64"; * @internal */ export class HeaderMarshaller { - constructor(private readonly toUtf8: Encoder, private readonly fromUtf8: Decoder) {} + constructor( + private readonly toUtf8: Encoder, + private readonly fromUtf8: Decoder + ) {} format(headers: MessageHeaders): Uint8Array { const chunks: Array = []; diff --git a/packages/eventstream-codec/src/TestVectors.fixture.ts b/packages/eventstream-codec/src/TestVectors.fixture.ts index a15efd0eb4a..c83ca5c37ad 100644 --- a/packages/eventstream-codec/src/TestVectors.fixture.ts +++ b/packages/eventstream-codec/src/TestVectors.fixture.ts @@ -5,210 +5,14 @@ export const vectors: TestVectors = { all_headers: { expectation: "success", encoded: Uint8Array.from([ - 0, - 0, - 0, - 204, - 0, - 0, - 0, - 175, - 15, - 174, - 100, - 202, - 10, - 101, - 118, - 101, - 110, - 116, - 45, - 116, - 121, - 112, - 101, - 4, - 0, - 0, - 160, - 12, - 12, - 99, - 111, - 110, - 116, - 101, - 110, - 116, - 45, - 116, - 121, - 112, - 101, - 7, - 0, - 16, - 97, - 112, - 112, - 108, - 105, - 99, - 97, - 116, - 105, - 111, - 110, - 47, - 106, - 115, - 111, - 110, - 10, - 98, - 111, - 111, - 108, - 32, - 102, - 97, - 108, - 115, - 101, - 1, - 9, - 98, - 111, - 111, - 108, - 32, - 116, - 114, - 117, - 101, - 0, - 4, - 98, - 121, - 116, - 101, - 2, - 207, - 8, - 98, - 121, - 116, - 101, - 32, - 98, - 117, - 102, - 6, - 0, - 20, - 73, - 39, - 109, - 32, - 97, - 32, - 108, - 105, - 116, - 116, - 108, - 101, - 32, - 116, - 101, - 97, - 112, - 111, - 116, - 33, - 9, - 116, - 105, - 109, - 101, - 115, - 116, - 97, - 109, - 112, - 8, - 0, - 0, - 0, - 0, - 0, - 132, - 95, - 237, - 5, - 105, - 110, - 116, - 49, - 54, - 3, - 0, - 42, - 5, - 105, - 110, - 116, - 54, - 52, - 5, - 0, - 0, - 0, - 0, - 2, - 135, - 87, - 178, - 4, - 117, - 117, - 105, - 100, - 9, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 16, - 123, - 39, - 102, - 111, - 111, - 39, - 58, - 39, - 98, - 97, - 114, - 39, - 125, - 171, - 165, - 241, - 12, + 0, 0, 0, 204, 0, 0, 0, 175, 15, 174, 100, 202, 10, 101, 118, 101, 110, 116, 45, 116, 121, 112, 101, 4, 0, 0, 160, + 12, 12, 99, 111, 110, 116, 101, 110, 116, 45, 116, 121, 112, 101, 7, 0, 16, 97, 112, 112, 108, 105, 99, 97, 116, + 105, 111, 110, 47, 106, 115, 111, 110, 10, 98, 111, 111, 108, 32, 102, 97, 108, 115, 101, 1, 9, 98, 111, 111, 108, + 32, 116, 114, 117, 101, 0, 4, 98, 121, 116, 101, 2, 207, 8, 98, 121, 116, 101, 32, 98, 117, 102, 6, 0, 20, 73, 39, + 109, 32, 97, 32, 108, 105, 116, 116, 108, 101, 32, 116, 101, 97, 112, 111, 116, 33, 9, 116, 105, 109, 101, 115, + 116, 97, 109, 112, 8, 0, 0, 0, 0, 0, 132, 95, 237, 5, 105, 110, 116, 49, 54, 3, 0, 42, 5, 105, 110, 116, 54, 52, + 5, 0, 0, 0, 0, 2, 135, 87, 178, 4, 117, 117, 105, 100, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, + 123, 39, 102, 111, 111, 39, 58, 39, 98, 97, 114, 39, 125, 171, 165, 241, 12, ]), decoded: { headers: { @@ -235,26 +39,7 @@ export const vectors: TestVectors = { "byte buf": { type: "binary", value: Uint8Array.from([ - 73, - 39, - 109, - 32, - 97, - 32, - 108, - 105, - 116, - 116, - 108, - 101, - 32, - 116, - 101, - 97, - 112, - 111, - 116, - 33, + 73, 39, 109, 32, 97, 32, 108, 105, 116, 116, 108, 101, 32, 116, 101, 97, 112, 111, 116, 33, ]), }, timestamp: { @@ -288,51 +73,8 @@ export const vectors: TestVectors = { int32_header: { expectation: "success", encoded: Uint8Array.from([ - 0, - 0, - 0, - 45, - 0, - 0, - 0, - 16, - 65, - 196, - 36, - 184, - 10, - 101, - 118, - 101, - 110, - 116, - 45, - 116, - 121, - 112, - 101, - 4, - 0, - 0, - 160, - 12, - 123, - 39, - 102, - 111, - 111, - 39, - 58, - 39, - 98, - 97, - 114, - 39, - 125, - 54, - 244, - 128, - 160, + 0, 0, 0, 45, 0, 0, 0, 16, 65, 196, 36, 184, 10, 101, 118, 101, 110, 116, 45, 116, 121, 112, 101, 4, 0, 0, 160, 12, + 123, 39, 102, 111, 111, 39, 58, 39, 98, 97, 114, 39, 125, 54, 244, 128, 160, ]), decoded: { headers: { @@ -347,34 +89,7 @@ export const vectors: TestVectors = { payload_no_headers: { expectation: "success", encoded: Uint8Array.from([ - 0, - 0, - 0, - 29, - 0, - 0, - 0, - 0, - 253, - 82, - 140, - 90, - 123, - 39, - 102, - 111, - 111, - 39, - 58, - 39, - 98, - 97, - 114, - 39, - 125, - 195, - 101, - 57, + 0, 0, 0, 29, 0, 0, 0, 0, 253, 82, 140, 90, 123, 39, 102, 111, 111, 39, 58, 39, 98, 97, 114, 39, 125, 195, 101, 57, 54, ]), decoded: { @@ -385,67 +100,9 @@ export const vectors: TestVectors = { payload_one_str_header: { expectation: "success", encoded: Uint8Array.from([ - 0, - 0, - 0, - 61, - 0, - 0, - 0, - 32, - 7, - 253, - 131, - 150, - 12, - 99, - 111, - 110, - 116, - 101, - 110, - 116, - 45, - 116, - 121, - 112, - 101, - 7, - 0, - 16, - 97, - 112, - 112, - 108, - 105, - 99, - 97, - 116, - 105, - 111, - 110, - 47, - 106, - 115, - 111, - 110, - 123, - 39, - 102, - 111, - 111, - 39, - 58, - 39, - 98, - 97, - 114, - 39, - 125, - 141, - 156, - 8, - 177, + 0, 0, 0, 61, 0, 0, 0, 32, 7, 253, 131, 150, 12, 99, 111, 110, 116, 101, 110, 116, 45, 116, 121, 112, 101, 7, 0, + 16, 97, 112, 112, 108, 105, 99, 97, 116, 105, 111, 110, 47, 106, 115, 111, 110, 123, 39, 102, 111, 111, 39, 58, + 39, 98, 97, 114, 39, 125, 141, 156, 8, 177, ]), decoded: { headers: { @@ -460,232 +117,31 @@ export const vectors: TestVectors = { corrupted_headers: { expectation: "failure", encoded: Uint8Array.from([ - 0, - 0, - 0, - 61, - 0, - 0, - 0, - 32, - 7, - 253, - 131, - 150, - 12, - 99, - 111, - 110, - 116, - 101, - 110, - 116, - 45, - 116, - 121, - 112, - 101, - 7, - 0, - 16, - 97, - 112, - 112, - 108, - 105, - 99, - 97, - 116, - 105, - 111, - 110, - 47, - 106, - 115, - 111, - 110, - 123, - 97, - 102, - 111, - 111, - 39, - 58, - 39, - 98, - 97, - 114, - 39, - 125, - 141, - 156, - 8, - 177, + 0, 0, 0, 61, 0, 0, 0, 32, 7, 253, 131, 150, 12, 99, 111, 110, 116, 101, 110, 116, 45, 116, 121, 112, 101, 7, 0, + 16, 97, 112, 112, 108, 105, 99, 97, 116, 105, 111, 110, 47, 106, 115, 111, 110, 123, 97, 102, 111, 111, 39, 58, + 39, 98, 97, 114, 39, 125, 141, 156, 8, 177, ]), }, corrupted_header_len: { expectation: "failure", encoded: Uint8Array.from([ - 0, - 0, - 0, - 61, - 0, - 0, - 0, - 33, - 7, - 253, - 131, - 150, - 12, - 99, - 111, - 110, - 116, - 101, - 110, - 116, - 45, - 116, - 121, - 112, - 101, - 7, - 0, - 16, - 97, - 112, - 112, - 108, - 105, - 99, - 97, - 116, - 105, - 111, - 110, - 47, - 106, - 115, - 111, - 110, - 123, - 39, - 102, - 111, - 111, - 39, - 58, - 39, - 98, - 97, - 114, - 39, - 125, - 141, - 156, - 8, - 177, + 0, 0, 0, 61, 0, 0, 0, 33, 7, 253, 131, 150, 12, 99, 111, 110, 116, 101, 110, 116, 45, 116, 121, 112, 101, 7, 0, + 16, 97, 112, 112, 108, 105, 99, 97, 116, 105, 111, 110, 47, 106, 115, 111, 110, 123, 39, 102, 111, 111, 39, 58, + 39, 98, 97, 114, 39, 125, 141, 156, 8, 177, ]), }, corrupted_length: { expectation: "failure", encoded: Uint8Array.from([ - 0, - 0, - 0, - 62, - 0, - 0, - 0, - 32, - 7, - 253, - 131, - 150, - 12, - 99, - 111, - 110, - 116, - 101, - 110, - 116, - 45, - 116, - 121, - 112, - 101, - 7, - 0, - 16, - 97, - 112, - 112, - 108, - 105, - 99, - 97, - 116, - 105, - 111, - 110, - 47, - 106, - 115, - 111, - 110, - 123, - 39, - 102, - 111, - 111, - 39, - 58, - 39, - 98, - 97, - 114, - 39, - 125, - 141, - 156, - 8, - 177, + 0, 0, 0, 62, 0, 0, 0, 32, 7, 253, 131, 150, 12, 99, 111, 110, 116, 101, 110, 116, 45, 116, 121, 112, 101, 7, 0, + 16, 97, 112, 112, 108, 105, 99, 97, 116, 105, 111, 110, 47, 106, 115, 111, 110, 123, 39, 102, 111, 111, 39, 58, + 39, 98, 97, 114, 39, 125, 141, 156, 8, 177, ]), }, corrupted_payload: { expectation: "failure", encoded: Uint8Array.from([ - 0, - 0, - 0, - 29, - 0, - 0, - 0, - 0, - 253, - 82, - 140, - 90, - 91, - 39, - 102, - 111, - 111, - 39, - 58, - 39, - 98, - 97, - 114, - 39, - 125, - 195, - 101, - 57, + 0, 0, 0, 29, 0, 0, 0, 0, 253, 82, 140, 90, 91, 39, 102, 111, 111, 39, 58, 39, 98, 97, 114, 39, 125, 195, 101, 57, 54, ]), }, diff --git a/packages/experimental-identity-and-auth/src/HttpAuthSchemeProvider.ts b/packages/experimental-identity-and-auth/src/HttpAuthSchemeProvider.ts index ac18d7b6de6..c77cac5576e 100644 --- a/packages/experimental-identity-and-auth/src/HttpAuthSchemeProvider.ts +++ b/packages/experimental-identity-and-auth/src/HttpAuthSchemeProvider.ts @@ -23,7 +23,7 @@ export interface HttpAuthSchemeParametersProvider< TConfig extends object, TContext extends HandlerExecutionContext, TParameters extends HttpAuthSchemeParameters, - TInput extends object + TInput extends object, > { (config: TConfig, context: TContext, input: TInput): Promise; } diff --git a/packages/experimental-identity-and-auth/src/endpointRuleSet.ts b/packages/experimental-identity-and-auth/src/endpointRuleSet.ts index 86f12a178e4..c68a2ae9d6f 100644 --- a/packages/experimental-identity-and-auth/src/endpointRuleSet.ts +++ b/packages/experimental-identity-and-auth/src/endpointRuleSet.ts @@ -14,7 +14,7 @@ import { */ export interface EndpointRuleSetHttpAuthSchemeProvider< EndpointParametersT extends EndpointParameters, - HttpAuthSchemeParametersT extends HttpAuthSchemeParameters + HttpAuthSchemeParametersT extends HttpAuthSchemeParameters, > extends HttpAuthSchemeProvider {} /** @@ -29,7 +29,7 @@ export interface DefaultEndpointResolver( defaultEndpointResolver: DefaultEndpointResolver, defaultHttpAuthSchemeResolver: HttpAuthSchemeProvider @@ -88,45 +88,47 @@ export interface EndpointRuleSetHttpAuthSchemeParametersProvider< TConfig extends object, TContext extends HandlerExecutionContext, TParameters extends HttpAuthSchemeParameters & EndpointParameters, - TInput extends object + TInput extends object, > extends HttpAuthSchemeParametersProvider {} /** * @internal */ -export const createEndpointRuleSetHttpAuthSchemeParametersProvider = < - TConfig extends object, - TContext extends HandlerExecutionContext, - THttpAuthSchemeParameters extends HttpAuthSchemeParameters, - TEndpointParameters extends EndpointParameters, - TParameters extends THttpAuthSchemeParameters & TEndpointParameters, - TInput extends object ->( - defaultHttpAuthSchemeParametersProvider: HttpAuthSchemeParametersProvider< +export const createEndpointRuleSetHttpAuthSchemeParametersProvider = + < + TConfig extends object, + TContext extends HandlerExecutionContext, + THttpAuthSchemeParameters extends HttpAuthSchemeParameters, + TEndpointParameters extends EndpointParameters, + TParameters extends THttpAuthSchemeParameters & TEndpointParameters, + TInput extends object, + >( + defaultHttpAuthSchemeParametersProvider: HttpAuthSchemeParametersProvider< + TConfig, + TContext, + THttpAuthSchemeParameters, + TInput + > + ): EndpointRuleSetHttpAuthSchemeParametersProvider< TConfig, TContext, - THttpAuthSchemeParameters, + THttpAuthSchemeParameters & TEndpointParameters, TInput - > -): EndpointRuleSetHttpAuthSchemeParametersProvider< - TConfig, - TContext, - THttpAuthSchemeParameters & TEndpointParameters, - TInput -> => async (config: TConfig, context: TContext, input: TInput): Promise => { - if (!input) { - throw new Error(`Could not find \`input\` for \`defaultEndpointRuleSetHttpAuthSchemeParametersProvider\``); - } - const defaultParameters = await defaultHttpAuthSchemeParametersProvider(config, context, input); - const instructionsFn = (getSmithyContext(context) as EndpointRuleSetSmithyContext)?.endpointRuleSet - ?.getEndpointParameterInstructions; - if (!instructionsFn) { - throw new Error(`getEndpointParameterInstructions() is not defined on \`${context.commandName!}\``); - } - const endpointParameters = await resolveParams( - input as Record, - { getEndpointParameterInstructions: instructionsFn! }, - config as Record - ); - return Object.assign(defaultParameters, endpointParameters) as TParameters; -}; + > => + async (config: TConfig, context: TContext, input: TInput): Promise => { + if (!input) { + throw new Error(`Could not find \`input\` for \`defaultEndpointRuleSetHttpAuthSchemeParametersProvider\``); + } + const defaultParameters = await defaultHttpAuthSchemeParametersProvider(config, context, input); + const instructionsFn = (getSmithyContext(context) as EndpointRuleSetSmithyContext)?.endpointRuleSet + ?.getEndpointParameterInstructions; + if (!instructionsFn) { + throw new Error(`getEndpointParameterInstructions() is not defined on \`${context.commandName!}\``); + } + const endpointParameters = await resolveParams( + input as Record, + { getEndpointParameterInstructions: instructionsFn! }, + config as Record + ); + return Object.assign(defaultParameters, endpointParameters) as TParameters; + }; diff --git a/packages/experimental-identity-and-auth/src/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.ts b/packages/experimental-identity-and-auth/src/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.ts index 3c1cb8899ed..99a67a4761f 100644 --- a/packages/experimental-identity-and-auth/src/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.ts +++ b/packages/experimental-identity-and-auth/src/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.ts @@ -24,7 +24,7 @@ interface HttpAuthSchemeEndpointRuleSetPluginOptions< TConfig extends object, TContext extends HandlerExecutionContext, TParameters extends HttpAuthSchemeParameters, - TInput extends object + TInput extends object, > { httpAuthSchemeParametersProvider: HttpAuthSchemeParametersProvider; identityProviderConfigProvider: (config: TConfig) => Promise; @@ -37,7 +37,7 @@ export const getHttpAuthSchemeEndpointRuleSetPlugin = < TConfig extends object, TContext extends HandlerExecutionContext, TParameters extends HttpAuthSchemeParameters, - TInput extends object + TInput extends object, >( config: TConfig & PreviouslyResolved, { diff --git a/packages/experimental-identity-and-auth/src/middleware-http-auth-scheme/getHttpAuthSchemePlugin.ts b/packages/experimental-identity-and-auth/src/middleware-http-auth-scheme/getHttpAuthSchemePlugin.ts index be43e90ea67..e7c72c2cc9e 100644 --- a/packages/experimental-identity-and-auth/src/middleware-http-auth-scheme/getHttpAuthSchemePlugin.ts +++ b/packages/experimental-identity-and-auth/src/middleware-http-auth-scheme/getHttpAuthSchemePlugin.ts @@ -24,7 +24,7 @@ interface HttpAuthSchemePluginOptions< TConfig extends object, TContext extends HandlerExecutionContext, TParameters extends HttpAuthSchemeParameters, - TInput extends object + TInput extends object, > { httpAuthSchemeParametersProvider: HttpAuthSchemeParametersProvider; identityProviderConfigProvider: (config: TConfig) => Promise; @@ -37,7 +37,7 @@ export const getHttpAuthSchemePlugin = < TConfig extends object, TContext extends HandlerExecutionContext, TParameters extends HttpAuthSchemeParameters, - TInput extends object + TInput extends object, >( config: TConfig & PreviouslyResolved, { diff --git a/packages/experimental-identity-and-auth/src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts b/packages/experimental-identity-and-auth/src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts index 5078e6a9ee2..77c81b17455 100644 --- a/packages/experimental-identity-and-auth/src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts +++ b/packages/experimental-identity-and-auth/src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts @@ -31,7 +31,7 @@ interface HttpAuthSchemeMiddlewareOptions< TConfig extends object, TContext extends HandlerExecutionContext, TParameters extends HttpAuthSchemeParameters, - TInput extends object + TInput extends object, > { httpAuthSchemeParametersProvider: HttpAuthSchemeParametersProvider; identityProviderConfigProvider: (config: TConfig) => Promise; @@ -66,50 +66,51 @@ function convertHttpAuthSchemesToMap(httpAuthSchemes: HttpAuthScheme[]): Map( - config: TConfig & PreviouslyResolved, - mwOptions: HttpAuthSchemeMiddlewareOptions -): SerializeMiddleware => ( - next: SerializeHandler, - context: HttpAuthSchemeMiddlewareHandlerExecutionContext -): SerializeHandler => async ( - args: SerializeHandlerArguments -): Promise> => { - const options = config.httpAuthSchemeProvider( - await mwOptions.httpAuthSchemeParametersProvider(config, context as TContext, args.input) - ); - const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); - const smithyContext: HttpAuthSchemeMiddlewareSmithyContext = getSmithyContext(context); - const failureReasons = []; - for (const option of options) { - const scheme = authSchemes.get(option.schemeId); - if (!scheme) { - failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); - continue; +export const httpAuthSchemeMiddleware = + < + TInput extends object, + Output extends object, + TConfig extends object, + TContext extends HttpAuthSchemeMiddlewareHandlerExecutionContext, + TParameters extends HttpAuthSchemeParameters, + >( + config: TConfig & PreviouslyResolved, + mwOptions: HttpAuthSchemeMiddlewareOptions + ): SerializeMiddleware => + ( + next: SerializeHandler, + context: HttpAuthSchemeMiddlewareHandlerExecutionContext + ): SerializeHandler => + async (args: SerializeHandlerArguments): Promise> => { + const options = config.httpAuthSchemeProvider( + await mwOptions.httpAuthSchemeParametersProvider(config, context as TContext, args.input) + ); + const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); + const smithyContext: HttpAuthSchemeMiddlewareSmithyContext = getSmithyContext(context); + const failureReasons = []; + for (const option of options) { + const scheme = authSchemes.get(option.schemeId); + if (!scheme) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); + continue; + } + const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); + if (!identityProvider) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); + continue; + } + const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; + option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); + option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); + smithyContext.selectedHttpAuthScheme = { + httpAuthOption: option, + identity: await identityProvider(option.identityProperties), + signer: scheme.signer, + }; + break; } - const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); - if (!identityProvider) { - failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); - continue; + if (!smithyContext.selectedHttpAuthScheme) { + throw new Error(failureReasons.join("\n")); } - const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; - option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); - option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); - smithyContext.selectedHttpAuthScheme = { - httpAuthOption: option, - identity: await identityProvider(option.identityProperties), - signer: scheme.signer, - }; - break; - } - if (!smithyContext.selectedHttpAuthScheme) { - throw new Error(failureReasons.join("\n")); - } - return next(args); -}; + return next(args); + }; diff --git a/packages/experimental-identity-and-auth/src/middleware-http-signing/httpSigningMiddleware.ts b/packages/experimental-identity-and-auth/src/middleware-http-signing/httpSigningMiddleware.ts index 1181b132ce3..ab9a6d8ea73 100644 --- a/packages/experimental-identity-and-auth/src/middleware-http-signing/httpSigningMiddleware.ts +++ b/packages/experimental-identity-and-auth/src/middleware-http-signing/httpSigningMiddleware.ts @@ -28,30 +28,29 @@ interface HttpSigningMiddlewareHandlerExecutionContext extends HandlerExecutionC /** * @internal */ -export const httpSigningMiddleware = ( - config: object -): FinalizeRequestMiddleware => ( - next: FinalizeHandler, - context: HttpSigningMiddlewareHandlerExecutionContext -): FinalizeHandler => async ( - args: FinalizeHandlerArguments -): Promise> => { - if (!HttpRequest.isInstance(args.request)) { - return next(args); - } +export const httpSigningMiddleware = + (config: object): FinalizeRequestMiddleware => + ( + next: FinalizeHandler, + context: HttpSigningMiddlewareHandlerExecutionContext + ): FinalizeHandler => + async (args: FinalizeHandlerArguments): Promise> => { + if (!HttpRequest.isInstance(args.request)) { + return next(args); + } - const smithyContext: HttpSigningMiddlewareSmithyContext = getSmithyContext(context); - const scheme = smithyContext.selectedHttpAuthScheme; - if (!scheme) { - throw new Error(`No HttpAuthScheme was selected: unable to sign request`); - } - const { - httpAuthOption: { signingProperties }, - identity, - signer, - } = scheme; - return next({ - ...args, - request: await signer.sign(args.request, identity, signingProperties || {}), - }); -}; + const smithyContext: HttpSigningMiddlewareSmithyContext = getSmithyContext(context); + const scheme = smithyContext.selectedHttpAuthScheme; + if (!scheme) { + throw new Error(`No HttpAuthScheme was selected: unable to sign request`); + } + const { + httpAuthOption: { signingProperties }, + identity, + signer, + } = scheme; + return next({ + ...args, + request: await signer.sign(args.request, identity, signingProperties || {}), + }); + }; diff --git a/packages/hash-stream-node/src/HashCalculator.ts b/packages/hash-stream-node/src/HashCalculator.ts index d7774c95367..191f5bef6bd 100644 --- a/packages/hash-stream-node/src/HashCalculator.ts +++ b/packages/hash-stream-node/src/HashCalculator.ts @@ -6,7 +6,10 @@ import { Writable, WritableOptions } from "stream"; * @internal */ export class HashCalculator extends Writable { - constructor(public readonly hash: Checksum | Hash, options?: WritableOptions) { + constructor( + public readonly hash: Checksum | Hash, + options?: WritableOptions + ) { super(options); } diff --git a/packages/hash-stream-node/src/readableStreamHasher.spec.ts b/packages/hash-stream-node/src/readableStreamHasher.spec.ts index 7aae48bcc37..ef42a77f959 100644 --- a/packages/hash-stream-node/src/readableStreamHasher.spec.ts +++ b/packages/hash-stream-node/src/readableStreamHasher.spec.ts @@ -19,7 +19,11 @@ describe(readableStreamHasher.name, () => { const mockHash = new Uint8Array(Buffer.from("mockHash")); class MockHashCalculator extends Writable { - constructor(public readonly hash: Hash, public readonly mockWrite, public readonly mockEnd) { + constructor( + public readonly hash: Hash, + public readonly mockWrite, + public readonly mockEnd + ) { super(); } @@ -35,7 +39,7 @@ describe(readableStreamHasher.name, () => { } beforeEach(() => { - ((HashCalculator as unknown) as jest.Mock).mockImplementation( + (HashCalculator as unknown as jest.Mock).mockImplementation( (hash) => new MockHashCalculator(hash, mockHashCalculatorWrite, mockHashCalculatorEnd) ); mockDigest.mockResolvedValue(mockHash); @@ -108,7 +112,7 @@ describe(readableStreamHasher.name, () => { mockHashCalculatorWrite, mockHashCalculatorEnd ); - ((HashCalculator as unknown) as jest.Mock).mockImplementation((hash) => mockHashCalculator); + (HashCalculator as unknown as jest.Mock).mockImplementation((hash) => mockHashCalculator); const readableStream = new Readable({ read: (size) => {}, diff --git a/packages/middleware-apply-body-checksum/src/applyMd5BodyChecksumMiddleware.ts b/packages/middleware-apply-body-checksum/src/applyMd5BodyChecksumMiddleware.ts index 7bd17a7e9b7..1abd166a10f 100644 --- a/packages/middleware-apply-body-checksum/src/applyMd5BodyChecksumMiddleware.ts +++ b/packages/middleware-apply-body-checksum/src/applyMd5BodyChecksumMiddleware.ts @@ -13,38 +13,37 @@ import { import { Md5BodyChecksumResolvedConfig } from "./md5Configuration"; -export const applyMd5BodyChecksumMiddleware = (options: Md5BodyChecksumResolvedConfig): BuildMiddleware => < - Output extends MetadataBearer ->( - next: BuildHandler -): BuildHandler => async (args: BuildHandlerArguments): Promise> => { - let { request } = args; - if (HttpRequest.isInstance(request)) { - const { body, headers } = request; - if (!hasHeader("content-md5", headers)) { - let digest: Promise; - if (body === undefined || typeof body === "string" || ArrayBuffer.isView(body) || isArrayBuffer(body)) { - const hash = new options.md5(); - hash.update(body || ""); - digest = hash.digest(); - } else { - digest = options.streamHasher(options.md5, body); - } +export const applyMd5BodyChecksumMiddleware = + (options: Md5BodyChecksumResolvedConfig): BuildMiddleware => + (next: BuildHandler): BuildHandler => + async (args: BuildHandlerArguments): Promise> => { + let { request } = args; + if (HttpRequest.isInstance(request)) { + const { body, headers } = request; + if (!hasHeader("content-md5", headers)) { + let digest: Promise; + if (body === undefined || typeof body === "string" || ArrayBuffer.isView(body) || isArrayBuffer(body)) { + const hash = new options.md5(); + hash.update(body || ""); + digest = hash.digest(); + } else { + digest = options.streamHasher(options.md5, body); + } - request = { - ...request, - headers: { - ...headers, - "content-md5": options.base64Encoder(await digest), - }, - }; + request = { + ...request, + headers: { + ...headers, + "content-md5": options.base64Encoder(await digest), + }, + }; + } } - } - return next({ - ...args, - request, - }); -}; + return next({ + ...args, + request, + }); + }; export const applyMd5BodyChecksumMiddlewareOptions: BuildHandlerOptions = { name: "applyMd5BodyChecksumMiddleware", diff --git a/packages/middleware-compression/src/compressionMiddleware.spec.ts b/packages/middleware-compression/src/compressionMiddleware.spec.ts index 5821ffea153..88f8832fe4c 100644 --- a/packages/middleware-compression/src/compressionMiddleware.spec.ts +++ b/packages/middleware-compression/src/compressionMiddleware.spec.ts @@ -32,7 +32,7 @@ describe(compressionMiddleware.name, () => { it("skips compression if it's not an HttpRequest", async () => { const { isInstance } = HttpRequest; - ((isInstance as unknown) as jest.Mock).mockReturnValue(false); + (isInstance as unknown as jest.Mock).mockReturnValue(false); await compressionMiddleware(mockConfig, mockMiddlewareConfig)(mockNext, mockContext)({ ...mockArgs } as any); expect(mockNext).toHaveBeenCalledWith(mockArgs); }); @@ -40,7 +40,7 @@ describe(compressionMiddleware.name, () => { describe("HttpRequest", () => { beforeEach(() => { const { isInstance } = HttpRequest; - ((isInstance as unknown) as jest.Mock).mockReturnValue(true); + (isInstance as unknown as jest.Mock).mockReturnValue(true); (isStreaming as jest.Mock).mockReturnValue(false); }); diff --git a/packages/middleware-compression/src/compressionMiddleware.ts b/packages/middleware-compression/src/compressionMiddleware.ts index 552a2b06a7e..a5b437d9014 100644 --- a/packages/middleware-compression/src/compressionMiddleware.ts +++ b/packages/middleware-compression/src/compressionMiddleware.ts @@ -34,75 +34,76 @@ export interface CompressionMiddlewareConfig { /** * @internal */ -export const compressionMiddleware = ( - config: CompressionResolvedConfig & CompressionPreviouslyResolved, - middlewareConfig: CompressionMiddlewareConfig -): BuildMiddleware => ( - next: BuildHandler -): BuildHandler => async (args: BuildHandlerArguments): Promise> => { - if (!HttpRequest.isInstance(args.request)) { - return next(args); - } +export const compressionMiddleware = + ( + config: CompressionResolvedConfig & CompressionPreviouslyResolved, + middlewareConfig: CompressionMiddlewareConfig + ): BuildMiddleware => + (next: BuildHandler): BuildHandler => + async (args: BuildHandlerArguments): Promise> => { + if (!HttpRequest.isInstance(args.request)) { + return next(args); + } - const disableRequestCompression = await config.disableRequestCompression(); - if (disableRequestCompression) { - return next(args); - } + const disableRequestCompression = await config.disableRequestCompression(); + if (disableRequestCompression) { + return next(args); + } - const { request } = args; - const { body, headers } = request; - const { encodings, streamRequiresLength } = middlewareConfig; + const { request } = args; + const { body, headers } = request; + const { encodings, streamRequiresLength } = middlewareConfig; - let updatedBody = body; - let updatedHeaders = headers; + let updatedBody = body; + let updatedHeaders = headers; - for (const algorithm of encodings) { - if (CLIENT_SUPPORTED_ALGORITHMS.includes(algorithm as CompressionAlgorithm)) { - let isRequestCompressed = false; - if (isStreaming(body)) { - if (!streamRequiresLength) { - updatedBody = await compressStream(body); - isRequestCompressed = true; + for (const algorithm of encodings) { + if (CLIENT_SUPPORTED_ALGORITHMS.includes(algorithm as CompressionAlgorithm)) { + let isRequestCompressed = false; + if (isStreaming(body)) { + if (!streamRequiresLength) { + updatedBody = await compressStream(body); + isRequestCompressed = true; + } else { + // Invalid case. We should never get here. + throw new Error("Compression is not supported for streaming blobs that require a length."); + } } else { - // Invalid case. We should never get here. - throw new Error("Compression is not supported for streaming blobs that require a length."); + const bodyLength = config.bodyLengthChecker(body); + const requestMinCompressionSizeBytes = await config.requestMinCompressionSizeBytes(); + if (bodyLength && bodyLength >= requestMinCompressionSizeBytes) { + updatedBody = await compressString(body); + isRequestCompressed = true; + } } - } else { - const bodyLength = config.bodyLengthChecker(body); - const requestMinCompressionSizeBytes = await config.requestMinCompressionSizeBytes(); - if (bodyLength && bodyLength >= requestMinCompressionSizeBytes) { - updatedBody = await compressString(body); - isRequestCompressed = true; - } - } - if (isRequestCompressed) { - // Either append to the header if it already exists, else set it - if (headers["Content-Encoding"]) { - updatedHeaders = { - ...headers, - "Content-Encoding": `${headers["Content-Encoding"]},${algorithm}`, - }; - } else { - updatedHeaders = { ...headers, "Content-Encoding": algorithm }; - } + if (isRequestCompressed) { + // Either append to the header if it already exists, else set it + if (headers["Content-Encoding"]) { + updatedHeaders = { + ...headers, + "Content-Encoding": `${headers["Content-Encoding"]},${algorithm}`, + }; + } else { + updatedHeaders = { ...headers, "Content-Encoding": algorithm }; + } - // We've matched on one supported algorithm in the - // priority-ordered list, so we're finished. - break; + // We've matched on one supported algorithm in the + // priority-ordered list, so we're finished. + break; + } } } - } - return next({ - ...args, - request: { - ...request, - body: updatedBody, - headers: updatedHeaders, - }, - }); -}; + return next({ + ...args, + request: { + ...request, + body: updatedBody, + headers: updatedHeaders, + }, + }); + }; export const compressionMiddlewareOptions: BuildHandlerOptions & AbsoluteLocation = { name: "compressionMiddleware", diff --git a/packages/middleware-content-length/src/index.ts b/packages/middleware-content-length/src/index.ts index 7e17524c08a..a7e6fd93f02 100644 --- a/packages/middleware-content-length/src/index.ts +++ b/packages/middleware-content-length/src/index.ts @@ -13,36 +13,35 @@ import { const CONTENT_LENGTH_HEADER = "content-length"; export function contentLengthMiddleware(bodyLengthChecker: BodyLengthCalculator): BuildMiddleware { - return (next: BuildHandler): BuildHandler => async ( - args: BuildHandlerArguments - ): Promise> => { - const request = args.request; - if (HttpRequest.isInstance(request)) { - const { body, headers } = request; - if ( - body && - Object.keys(headers) - .map((str) => str.toLowerCase()) - .indexOf(CONTENT_LENGTH_HEADER) === -1 - ) { - try { - const length = bodyLengthChecker(body); - request.headers = { - ...request.headers, - [CONTENT_LENGTH_HEADER]: String(length), - }; - } catch (error) { - // ToDo: Add 'transfer-encoding' as chunked only for HTTP/1.1 request - // Refs: https://github.com/aws/aws-sdk-js-v3/pull/3403 + return (next: BuildHandler): BuildHandler => + async (args: BuildHandlerArguments): Promise> => { + const request = args.request; + if (HttpRequest.isInstance(request)) { + const { body, headers } = request; + if ( + body && + Object.keys(headers) + .map((str) => str.toLowerCase()) + .indexOf(CONTENT_LENGTH_HEADER) === -1 + ) { + try { + const length = bodyLengthChecker(body); + request.headers = { + ...request.headers, + [CONTENT_LENGTH_HEADER]: String(length), + }; + } catch (error) { + // ToDo: Add 'transfer-encoding' as chunked only for HTTP/1.1 request + // Refs: https://github.com/aws/aws-sdk-js-v3/pull/3403 + } } } - } - return next({ - ...args, - request, - }); - }; + return next({ + ...args, + request, + }); + }; } export const contentLengthMiddlewareOptions: BuildHandlerOptions = { diff --git a/packages/middleware-endpoint/src/adaptors/getEndpointFromInstructions.ts b/packages/middleware-endpoint/src/adaptors/getEndpointFromInstructions.ts index 3dcbd5466c3..4e841c9a486 100644 --- a/packages/middleware-endpoint/src/adaptors/getEndpointFromInstructions.ts +++ b/packages/middleware-endpoint/src/adaptors/getEndpointFromInstructions.ts @@ -31,7 +31,7 @@ export type EndpointParameterInstructionsSupplier = Partial<{ export const getEndpointFromInstructions = async < T extends EndpointParameters, CommandInput extends Record, - Config extends Record + Config extends Record, >( commandInput: CommandInput, instructionsSupplier: EndpointParameterInstructionsSupplier, @@ -61,7 +61,7 @@ export const getEndpointFromInstructions = async < export const resolveParams = async < T extends EndpointParameters, CommandInput extends Record, - Config extends Record + Config extends Record, >( commandInput: CommandInput, instructionsSupplier: EndpointParameterInstructionsSupplier, diff --git a/packages/middleware-endpoint/src/endpointMiddleware.ts b/packages/middleware-endpoint/src/endpointMiddleware.ts index 015550af533..e4c4202e754 100644 --- a/packages/middleware-endpoint/src/endpointMiddleware.ts +++ b/packages/middleware-endpoint/src/endpointMiddleware.ts @@ -34,50 +34,49 @@ export const endpointMiddleware = ({ instructions: EndpointParameterInstructions; }): SerializeMiddleware => { return ( - next: SerializeHandler, - context: HandlerExecutionContext - ): SerializeHandler => async ( - args: SerializeHandlerArguments - ): Promise> => { - const endpoint: EndpointV2 = await getEndpointFromInstructions( - args.input, - { - getEndpointParameterInstructions() { - return instructions; + next: SerializeHandler, + context: HandlerExecutionContext + ): SerializeHandler => + async (args: SerializeHandlerArguments): Promise> => { + const endpoint: EndpointV2 = await getEndpointFromInstructions( + args.input, + { + getEndpointParameterInstructions() { + return instructions; + }, }, - }, - { ...config }, - context - ); + { ...config }, + context + ); - context.endpointV2 = endpoint; - context.authSchemes = endpoint.properties?.authSchemes; + context.endpointV2 = endpoint; + context.authSchemes = endpoint.properties?.authSchemes; - const authScheme: AuthScheme | undefined = context.authSchemes?.[0]; - if (authScheme) { - context["signing_region"] = authScheme.signingRegion; - context["signing_service"] = authScheme.signingName; - const smithyContext: EndpointMiddlewareSmithyContext = getSmithyContext(context); - const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption; - if (httpAuthOption) { - // TODO(experimentalIdentityAndAuth): Should be constrained somehow, but currently the only properties - // found were `signing_region` and `signing_service`. - httpAuthOption.signingProperties = Object.assign( - httpAuthOption.signingProperties || {}, - { - signing_region: authScheme.signingRegion, - signingRegion: authScheme.signingRegion, - signing_service: authScheme.signingName, - signingName: authScheme.signingName, - signingRegionSet: authScheme.signingRegionSet, - }, - authScheme.properties - ); + const authScheme: AuthScheme | undefined = context.authSchemes?.[0]; + if (authScheme) { + context["signing_region"] = authScheme.signingRegion; + context["signing_service"] = authScheme.signingName; + const smithyContext: EndpointMiddlewareSmithyContext = getSmithyContext(context); + const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption; + if (httpAuthOption) { + // TODO(experimentalIdentityAndAuth): Should be constrained somehow, but currently the only properties + // found were `signing_region` and `signing_service`. + httpAuthOption.signingProperties = Object.assign( + httpAuthOption.signingProperties || {}, + { + signing_region: authScheme.signingRegion, + signingRegion: authScheme.signingRegion, + signing_service: authScheme.signingName, + signingName: authScheme.signingName, + signingRegionSet: authScheme.signingRegionSet, + }, + authScheme.properties + ); + } } - } - return next({ - ...args, - }); - }; + return next({ + ...args, + }); + }; }; diff --git a/packages/middleware-retry/src/StandardRetryStrategy.spec.ts b/packages/middleware-retry/src/StandardRetryStrategy.spec.ts index 807ea9702d2..ad63a672f17 100644 --- a/packages/middleware-retry/src/StandardRetryStrategy.spec.ts +++ b/packages/middleware-retry/src/StandardRetryStrategy.spec.ts @@ -90,10 +90,10 @@ describe("defaultStrategy", () => { (defaultDelayDecider as jest.Mock).mockReturnValue(0); (defaultRetryDecider as jest.Mock).mockReturnValue(true); (getDefaultRetryQuota as jest.Mock).mockReturnValue(mockDefaultRetryQuota); - ((HttpRequest as unknown) as jest.Mock).mockReturnValue({ + (HttpRequest as unknown as jest.Mock).mockReturnValue({ isInstance: jest.fn().mockReturnValue(false), }); - ((HttpResponse as unknown) as jest.Mock).mockReturnValue({ + (HttpResponse as unknown as jest.Mock).mockReturnValue({ isInstance: jest.fn().mockReturnValue(false), }); (v4 as jest.Mock).mockReturnValue("42"); @@ -244,8 +244,8 @@ describe("defaultStrategy", () => { expect(defaultDelayDecider as jest.Mock).toHaveBeenCalledTimes(maxAttempts - 1); expect(setTimeout).toHaveBeenCalledTimes(maxAttempts - 1); - expect(((setTimeout as unknown) as jest.Mock).mock.calls[0][1]).toBe(FIRST_DELAY); - expect(((setTimeout as unknown) as jest.Mock).mock.calls[1][1]).toBe(SECOND_DELAY); + expect((setTimeout as unknown as jest.Mock).mock.calls[0][1]).toBe(FIRST_DELAY); + expect((setTimeout as unknown as jest.Mock).mock.calls[1][1]).toBe(SECOND_DELAY); }); }); @@ -278,7 +278,7 @@ describe("defaultStrategy", () => { describe("uses retry-after value if it's greater than that from delayDecider", () => { beforeEach(() => { const { isInstance } = HttpResponse; - ((isInstance as unknown) as jest.Mock).mockReturnValueOnce(true); + (isInstance as unknown as jest.Mock).mockReturnValueOnce(true); }); describe("when value is in seconds", () => { @@ -288,7 +288,7 @@ describe("defaultStrategy", () => { const error = await getErrorWithValues(delayDeciderInMs, retryAfterInSeconds, retryAfterHeaderName); expect(error.$metadata.totalRetryDelay).toEqual(retryAfterInSeconds * 1000); - expect(((setTimeout as unknown) as jest.Mock).mock.calls[0][1]).toBe(retryAfterInSeconds * 1000); + expect((setTimeout as unknown as jest.Mock).mock.calls[0][1]).toBe(retryAfterInSeconds * 1000); }; it("with header in small case", async () => { @@ -310,7 +310,7 @@ describe("defaultStrategy", () => { const error = await getErrorWithValues(delayDeciderInMs, retryAfterDate.toISOString()); expect(error.$metadata.totalRetryDelay).toEqual(retryAfterInSeconds * 1000); - expect(((setTimeout as unknown) as jest.Mock).mock.calls[0][1]).toBe(retryAfterInSeconds * 1000); + expect((setTimeout as unknown as jest.Mock).mock.calls[0][1]).toBe(retryAfterInSeconds * 1000); }); }); @@ -320,7 +320,7 @@ describe("defaultStrategy", () => { const error = await getErrorWithValues(delayDeciderInMs, retryAfterInSeconds); expect(error.$metadata.totalRetryDelay).toEqual(delayDeciderInMs); - expect(((setTimeout as unknown) as jest.Mock).mock.calls[0][1]).toBe(delayDeciderInMs); + expect((setTimeout as unknown as jest.Mock).mock.calls[0][1]).toBe(delayDeciderInMs); }); }); }); @@ -492,7 +492,7 @@ describe("defaultStrategy", () => { it("uses a unique header for every SDK operation invocation", async () => { const { isInstance } = HttpRequest; - ((isInstance as unknown) as jest.Mock).mockReturnValue(true); + (isInstance as unknown as jest.Mock).mockReturnValue(true); const uuidForInvocationOne = "uuid-invocation-1"; const uuidForInvocationTwo = "uuid-invocation-2"; @@ -511,12 +511,12 @@ describe("defaultStrategy", () => { expect(next.mock.calls[0][0].request.headers["amz-sdk-invocation-id"]).toBe(uuidForInvocationOne); expect(next.mock.calls[1][0].request.headers["amz-sdk-invocation-id"]).toBe(uuidForInvocationTwo); - ((isInstance as unknown) as jest.Mock).mockReturnValue(false); + (isInstance as unknown as jest.Mock).mockReturnValue(false); }); it("uses same value for additional HTTP requests associated with an SDK operation", async () => { const { isInstance } = HttpRequest; - ((isInstance as unknown) as jest.Mock).mockReturnValueOnce(true); + (isInstance as unknown as jest.Mock).mockReturnValueOnce(true); const uuidForInvocation = "uuid-invocation-1"; (v4 as jest.Mock).mockReturnValueOnce(uuidForInvocation); @@ -527,7 +527,7 @@ describe("defaultStrategy", () => { expect(next.mock.calls[0][0].request.headers["amz-sdk-invocation-id"]).toBe(uuidForInvocation); expect(next.mock.calls[1][0].request.headers["amz-sdk-invocation-id"]).toBe(uuidForInvocation); - ((isInstance as unknown) as jest.Mock).mockReturnValue(false); + (isInstance as unknown as jest.Mock).mockReturnValue(false); }); }); @@ -558,7 +558,7 @@ describe("defaultStrategy", () => { it("adds header for each attempt", async () => { const { isInstance } = HttpRequest; - ((isInstance as unknown) as jest.Mock).mockReturnValue(true); + (isInstance as unknown as jest.Mock).mockReturnValue(true); const mockError = new Error("mockError"); next = jest.fn((args) => { @@ -578,14 +578,14 @@ describe("defaultStrategy", () => { } expect(next).toHaveBeenCalledTimes(maxAttempts); - ((isInstance as unknown) as jest.Mock).mockReturnValue(false); + (isInstance as unknown as jest.Mock).mockReturnValue(false); }); }); describe("defaults maxAttempts to DEFAULT_MAX_ATTEMPTS", () => { it("when maxAttemptsProvider throws error", async () => { const { isInstance } = HttpRequest; - ((isInstance as unknown) as jest.Mock).mockReturnValue(true); + (isInstance as unknown as jest.Mock).mockReturnValue(true); next = jest.fn((args) => { expect(args.request.headers["amz-sdk-request"]).toBe(`attempt=1; max=${DEFAULT_MAX_ATTEMPTS}`); @@ -599,7 +599,7 @@ describe("defaultStrategy", () => { await retryStrategy.retry(next, { request: { headers: {} } } as any); expect(next).toHaveBeenCalledTimes(1); - ((isInstance as unknown) as jest.Mock).mockReturnValue(false); + (isInstance as unknown as jest.Mock).mockReturnValue(false); }); }); }); diff --git a/packages/middleware-retry/src/StandardRetryStrategy.ts b/packages/middleware-retry/src/StandardRetryStrategy.ts index dd5259e3a64..1dc685b0608 100644 --- a/packages/middleware-retry/src/StandardRetryStrategy.ts +++ b/packages/middleware-retry/src/StandardRetryStrategy.ts @@ -37,7 +37,10 @@ export class StandardRetryStrategy implements RetryStrategy { private retryQuota: RetryQuota; public mode: string = RETRY_MODES.STANDARD; - constructor(private readonly maxAttemptsProvider: Provider, options?: StandardRetryStrategyOptions) { + constructor( + private readonly maxAttemptsProvider: Provider, + options?: StandardRetryStrategyOptions + ) { this.retryDecider = options?.retryDecider ?? defaultRetryDecider; this.delayDecider = options?.delayDecider ?? defaultDelayDecider; this.retryQuota = options?.retryQuota ?? getDefaultRetryQuota(INITIAL_RETRY_TOKENS); diff --git a/packages/middleware-retry/src/middleware-retry.integ.spec.ts b/packages/middleware-retry/src/middleware-retry.integ.spec.ts index 4b56ff4c14c..704b8181056 100644 --- a/packages/middleware-retry/src/middleware-retry.integ.spec.ts +++ b/packages/middleware-retry/src/middleware-retry.integ.spec.ts @@ -9,7 +9,8 @@ describe("middleware-retry", () => { requireRequestsFrom(client).toMatch({ hostname: "foo.bar", headers: { - "amz-sdk-invocation-id": /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, + "amz-sdk-invocation-id": + /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, "amz-sdk-request": "attempt=1; max=3", }, }); diff --git a/packages/middleware-retry/src/omitRetryHeadersMiddleware.spec.ts b/packages/middleware-retry/src/omitRetryHeadersMiddleware.spec.ts index 4ed59a80c80..a6d15b2686b 100644 --- a/packages/middleware-retry/src/omitRetryHeadersMiddleware.spec.ts +++ b/packages/middleware-retry/src/omitRetryHeadersMiddleware.spec.ts @@ -19,7 +19,7 @@ describe("getOmitRetryHeadersPlugin", () => { }); it(`adds omitRetryHeadersMiddleware`, () => { - getOmitRetryHeadersPlugin({}).applyToStack((mockClientStack as unknown) as MiddlewareStack); + getOmitRetryHeadersPlugin({}).applyToStack(mockClientStack as unknown as MiddlewareStack); expect(mockClientStack.addRelativeTo).toHaveBeenCalledTimes(1); expect(mockClientStack.addRelativeTo.mock.calls[0][1]).toEqual(omitRetryHeadersMiddlewareOptions); }); diff --git a/packages/middleware-retry/src/omitRetryHeadersMiddleware.ts b/packages/middleware-retry/src/omitRetryHeadersMiddleware.ts index 4aca521bde9..0d86e3e3c47 100644 --- a/packages/middleware-retry/src/omitRetryHeadersMiddleware.ts +++ b/packages/middleware-retry/src/omitRetryHeadersMiddleware.ts @@ -9,18 +9,17 @@ import { } from "@smithy/types"; import { INVOCATION_ID_HEADER, REQUEST_HEADER } from "@smithy/util-retry"; -export const omitRetryHeadersMiddleware = () => ( - next: FinalizeHandler -): FinalizeHandler => async ( - args: FinalizeHandlerArguments -): Promise> => { - const { request } = args; - if (HttpRequest.isInstance(request)) { - delete request.headers[INVOCATION_ID_HEADER]; - delete request.headers[REQUEST_HEADER]; - } - return next(args); -}; +export const omitRetryHeadersMiddleware = + () => + (next: FinalizeHandler): FinalizeHandler => + async (args: FinalizeHandlerArguments): Promise> => { + const { request } = args; + if (HttpRequest.isInstance(request)) { + delete request.headers[INVOCATION_ID_HEADER]; + delete request.headers[REQUEST_HEADER]; + } + return next(args); + }; export const omitRetryHeadersMiddlewareOptions: RelativeMiddlewareOptions = { name: "omitRetryHeadersMiddleware", diff --git a/packages/middleware-retry/src/retryMiddleware.spec.ts b/packages/middleware-retry/src/retryMiddleware.spec.ts index c39ac5bb1c4..b8e8439daa6 100644 --- a/packages/middleware-retry/src/retryMiddleware.spec.ts +++ b/packages/middleware-retry/src/retryMiddleware.spec.ts @@ -22,10 +22,10 @@ describe(getRetryPlugin.name, () => { (isThrottlingError as jest.Mock).mockReturnValue(false); (isTransientError as jest.Mock).mockReturnValue(false); (isServerError as jest.Mock).mockReturnValue(false); - ((HttpRequest as unknown) as jest.Mock).mockReturnValue({ + (HttpRequest as unknown as jest.Mock).mockReturnValue({ isInstance: jest.fn().mockReturnValue(false), }); - ((HttpResponse as unknown) as jest.Mock).mockReturnValue({ + (HttpResponse as unknown as jest.Mock).mockReturnValue({ isInstance: jest.fn().mockReturnValue(false), }); (v4 as jest.Mock).mockReturnValue("42"); @@ -41,7 +41,7 @@ describe(getRetryPlugin.name, () => { getRetryPlugin({ maxAttempts: () => Promise.resolve(maxAttempts), retryStrategy: jest.fn().mockResolvedValue(mockRetryStrategy), - }).applyToStack((mockClientStack as unknown) as MiddlewareStack); + }).applyToStack(mockClientStack as unknown as MiddlewareStack); expect(mockClientStack.add).toHaveBeenCalledTimes(1); expect(mockClientStack.add.mock.calls[0][1]).toEqual(retryMiddlewareOptions); }); @@ -262,7 +262,7 @@ describe(retryMiddleware.name, () => { describe("when retry-after is not set", () => { it("should not set retryAfter in errorInfo", async () => { const { isInstance } = HttpResponse; - ((isInstance as unknown) as jest.Mock).mockReturnValue(true); + (isInstance as unknown as jest.Mock).mockReturnValue(true); Object.defineProperty(mockError, "$response", { value: { headers: { ["other-header"]: "foo" }, @@ -293,7 +293,7 @@ describe(retryMiddleware.name, () => { const now = Date.now(); const retryAfterDate = new Date(now + 3000); const { isInstance } = HttpResponse; - ((isInstance as unknown) as jest.Mock).mockReturnValue(true); + (isInstance as unknown as jest.Mock).mockReturnValue(true); const errorInfo = { error: mockError, errorType: "CLIENT_ERROR", @@ -350,7 +350,7 @@ describe(retryMiddleware.name, () => { expect(output.$metadata.attempts).toBe(2); expect(output.$metadata.totalRetryDelay).toBeDefined(); }); - ((isInstance as unknown) as jest.Mock).mockReturnValue(false); + (isInstance as unknown as jest.Mock).mockReturnValue(false); }); }); @@ -387,7 +387,7 @@ describe(retryMiddleware.name, () => { const retryAfterDate = new Date(Date.now() + 3000); const error = getErrorWithValues(retryAfterDate.toISOString()); const { isInstance } = HttpRequest; - ((isInstance as unknown) as jest.Mock).mockReturnValue(true); + (isInstance as unknown as jest.Mock).mockReturnValue(true); (isThrottlingError as jest.Mock).mockReturnValue(true); const next = jest.fn().mockRejectedValueOnce(error).mockResolvedValueOnce(mockSuccess); await retryMiddleware({ @@ -405,7 +405,7 @@ describe(retryMiddleware.name, () => { const retryAfterDate = new Date(Date.now() + 3000); const error = getErrorWithValues(retryAfterDate.toISOString()); const { isInstance } = HttpRequest; - ((isInstance as unknown) as jest.Mock).mockReturnValue(true); + (isInstance as unknown as jest.Mock).mockReturnValue(true); (isThrottlingError as jest.Mock).mockReturnValue(true); const next = jest.fn().mockRejectedValueOnce(error).mockResolvedValueOnce(mockSuccess); await retryMiddleware({ diff --git a/packages/middleware-retry/src/retryMiddleware.ts b/packages/middleware-retry/src/retryMiddleware.ts index 50afe9f23da..69048d1726f 100644 --- a/packages/middleware-retry/src/retryMiddleware.ts +++ b/packages/middleware-retry/src/retryMiddleware.ts @@ -24,71 +24,73 @@ import { RetryResolvedConfig } from "./configurations"; import { isStreamingPayload } from "./isStreamingPayload/isStreamingPayload"; import { asSdkError } from "./util"; -export const retryMiddleware = (options: RetryResolvedConfig) => ( - next: FinalizeHandler, - context: HandlerExecutionContext -): FinalizeHandler => async ( - args: FinalizeHandlerArguments -): Promise> => { - let retryStrategy = await options.retryStrategy(); - const maxAttempts = await options.maxAttempts(); - - if (isRetryStrategyV2(retryStrategy)) { - retryStrategy = retryStrategy as RetryStrategyV2; - let retryToken: RetryToken = await retryStrategy.acquireInitialRetryToken(context["partition_id"]); - let lastError: SdkError = new Error(); - let attempts = 0; - let totalRetryDelay = 0; - const { request } = args; - const isRequest = HttpRequest.isInstance(request); - - if (isRequest) { - request.headers[INVOCATION_ID_HEADER] = v4(); - } - while (true) { - try { - if (isRequest) { - request.headers[REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; - } - const { response, output } = await next(args); - retryStrategy.recordSuccess(retryToken); - output.$metadata.attempts = attempts + 1; - output.$metadata.totalRetryDelay = totalRetryDelay; - return { response, output }; - } catch (e: any) { - const retryErrorInfo = getRetryErrorInfo(e); - lastError = asSdkError(e); - - if (isRequest && isStreamingPayload(request)) { - (context.logger instanceof NoOpLogger ? console : context.logger)?.warn( - "An error was encountered in a non-retryable streaming request." - ); - throw lastError; - } - +export const retryMiddleware = + (options: RetryResolvedConfig) => + ( + next: FinalizeHandler, + context: HandlerExecutionContext + ): FinalizeHandler => + async (args: FinalizeHandlerArguments): Promise> => { + let retryStrategy = await options.retryStrategy(); + const maxAttempts = await options.maxAttempts(); + + if (isRetryStrategyV2(retryStrategy)) { + retryStrategy = retryStrategy as RetryStrategyV2; + let retryToken: RetryToken = await retryStrategy.acquireInitialRetryToken(context["partition_id"]); + let lastError: SdkError = new Error(); + let attempts = 0; + let totalRetryDelay = 0; + const { request } = args; + const isRequest = HttpRequest.isInstance(request); + + if (isRequest) { + request.headers[INVOCATION_ID_HEADER] = v4(); + } + while (true) { try { - retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo); - } catch (refreshError) { - if (!lastError.$metadata) { - lastError.$metadata = {}; + if (isRequest) { + request.headers[REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; + } + const { response, output } = await next(args); + retryStrategy.recordSuccess(retryToken); + output.$metadata.attempts = attempts + 1; + output.$metadata.totalRetryDelay = totalRetryDelay; + return { response, output }; + } catch (e: any) { + const retryErrorInfo = getRetryErrorInfo(e); + lastError = asSdkError(e); + + if (isRequest && isStreamingPayload(request)) { + (context.logger instanceof NoOpLogger ? console : context.logger)?.warn( + "An error was encountered in a non-retryable streaming request." + ); + throw lastError; } - lastError.$metadata.attempts = attempts + 1; - lastError.$metadata.totalRetryDelay = totalRetryDelay; - throw lastError; + + try { + retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo); + } catch (refreshError) { + if (!lastError.$metadata) { + lastError.$metadata = {}; + } + lastError.$metadata.attempts = attempts + 1; + lastError.$metadata.totalRetryDelay = totalRetryDelay; + throw lastError; + } + attempts = retryToken.getRetryCount(); + const delay = retryToken.getRetryDelay(); + totalRetryDelay += delay; + await new Promise((resolve) => setTimeout(resolve, delay)); } - attempts = retryToken.getRetryCount(); - const delay = retryToken.getRetryDelay(); - totalRetryDelay += delay; - await new Promise((resolve) => setTimeout(resolve, delay)); } - } - } else { - retryStrategy = retryStrategy as RetryStrategy; - if (retryStrategy?.mode) context.userAgent = [...(context.userAgent || []), ["cfg/retry-mode", retryStrategy.mode]]; + } else { + retryStrategy = retryStrategy as RetryStrategy; + if (retryStrategy?.mode) + context.userAgent = [...(context.userAgent || []), ["cfg/retry-mode", retryStrategy.mode]]; - return retryStrategy.retry(next, args); - } -}; + return retryStrategy.retry(next, args); + } + }; const isRetryStrategyV2 = (retryStrategy: RetryStrategy | RetryStrategyV2) => typeof (retryStrategy as RetryStrategyV2).acquireInitialRetryToken !== "undefined" && diff --git a/packages/middleware-serde/src/deserializerMiddleware.ts b/packages/middleware-serde/src/deserializerMiddleware.ts index 4e27d68496d..091ce3cfece 100644 --- a/packages/middleware-serde/src/deserializerMiddleware.ts +++ b/packages/middleware-serde/src/deserializerMiddleware.ts @@ -12,53 +12,47 @@ import { /** * @internal */ -export const deserializerMiddleware = < - Input extends object = any, - Output extends object = any, - CommandSerdeContext extends SerdeContext = any ->( - options: SerdeFunctions, - deserializer: ResponseDeserializer -): DeserializeMiddleware => ( - next: DeserializeHandler, - context: HandlerExecutionContext -): DeserializeHandler => async ( - args: DeserializeHandlerArguments -): Promise> => { - const { response } = await next(args); - try { - /** - * [options] is upgraded from SerdeFunctions to CommandSerdeContext, - * since the generated deserializer expects CommandSerdeContext. - * - * This is okay because options is from the same client's resolved config, - * and the deserializer doesn't need the `endpoint` field. - */ - const parsed = await deserializer(response, options as CommandSerdeContext); - return { - response, - output: parsed as Output, - }; - } catch (error) { - // For security reasons, the error response is not completely visible by default. - Object.defineProperty(error, "$response", { - value: response, - }); +export const deserializerMiddleware = + ( + options: SerdeFunctions, + deserializer: ResponseDeserializer + ): DeserializeMiddleware => + (next: DeserializeHandler, context: HandlerExecutionContext): DeserializeHandler => + async (args: DeserializeHandlerArguments): Promise> => { + const { response } = await next(args); + try { + /** + * [options] is upgraded from SerdeFunctions to CommandSerdeContext, + * since the generated deserializer expects CommandSerdeContext. + * + * This is okay because options is from the same client's resolved config, + * and the deserializer doesn't need the `endpoint` field. + */ + const parsed = await deserializer(response, options as CommandSerdeContext); + return { + response, + output: parsed as Output, + }; + } catch (error) { + // For security reasons, the error response is not completely visible by default. + Object.defineProperty(error, "$response", { + value: response, + }); - if (!("$metadata" in error)) { - // only apply this to non-ServiceException. - const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; - error.message += "\n " + hint; + if (!("$metadata" in error)) { + // only apply this to non-ServiceException. + const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + error.message += "\n " + hint; - if (typeof error.$responseBodyText !== "undefined") { - // if $responseBodyText was collected by the error parser, assign it to - // replace the response body, because it was consumed and is now empty. - if (error.$response) { - error.$response.body = error.$responseBodyText; + if (typeof error.$responseBodyText !== "undefined") { + // if $responseBodyText was collected by the error parser, assign it to + // replace the response body, because it was consumed and is now empty. + if (error.$response) { + error.$response.body = error.$responseBodyText; + } } } - } - throw error; - } -}; + throw error; + } + }; diff --git a/packages/middleware-serde/src/serdePlugin.ts b/packages/middleware-serde/src/serdePlugin.ts index e82de8c3cca..2afe0d16694 100644 --- a/packages/middleware-serde/src/serdePlugin.ts +++ b/packages/middleware-serde/src/serdePlugin.ts @@ -47,7 +47,7 @@ export type V1OrV2Endpoint = { export function getSerdePlugin< InputType extends object = any, CommandSerdeContext extends SerdeContext = any, - OutputType extends MetadataBearer = any + OutputType extends MetadataBearer = any, >( config: V1OrV2Endpoint & SerdeFunctions, serializer: RequestSerializer, diff --git a/packages/middleware-serde/src/serializerMiddleware.ts b/packages/middleware-serde/src/serializerMiddleware.ts index f4e2ac12246..aed695760d4 100644 --- a/packages/middleware-serde/src/serializerMiddleware.ts +++ b/packages/middleware-serde/src/serializerMiddleware.ts @@ -16,39 +16,33 @@ import type { V1OrV2Endpoint } from "./serdePlugin"; /** * @internal */ -export const serializerMiddleware = < - Input extends object = any, - Output extends object = any, - CommandSerdeContext extends SerdeContext = any ->( - options: V1OrV2Endpoint & SerdeFunctions, - serializer: RequestSerializer -): SerializeMiddleware => ( - next: SerializeHandler, - context: HandlerExecutionContext -): SerializeHandler => async ( - args: SerializeHandlerArguments -): Promise> => { - const endpoint: Provider = - context.endpointV2?.url && options.urlParser - ? async () => options.urlParser!(context.endpointV2!.url as URL) - : options.endpoint!; +export const serializerMiddleware = + ( + options: V1OrV2Endpoint & SerdeFunctions, + serializer: RequestSerializer + ): SerializeMiddleware => + (next: SerializeHandler, context: HandlerExecutionContext): SerializeHandler => + async (args: SerializeHandlerArguments): Promise> => { + const endpoint: Provider = + context.endpointV2?.url && options.urlParser + ? async () => options.urlParser!(context.endpointV2!.url as URL) + : options.endpoint!; - if (!endpoint) { - throw new Error("No valid endpoint provider available."); - } + if (!endpoint) { + throw new Error("No valid endpoint provider available."); + } - /** - * [options] is upgraded from SerdeFunctions to CommandSerdeContext, - * since the generated serializer expects CommandSerdeContext. - * - * This is okay because options is from the same client's resolved config, - * and `endpoint` has been provided here by checking two sources. - */ - const request = await serializer(args.input, { ...options, endpoint } as CommandSerdeContext); + /** + * [options] is upgraded from SerdeFunctions to CommandSerdeContext, + * since the generated serializer expects CommandSerdeContext. + * + * This is okay because options is from the same client's resolved config, + * and `endpoint` has been provided here by checking two sources. + */ + const request = await serializer(args.input, { ...options, endpoint } as CommandSerdeContext); - return next({ - ...args, - request, - }); -}; + return next({ + ...args, + request, + }); + }; diff --git a/packages/middleware-stack/src/MiddlewareStack.spec.ts b/packages/middleware-stack/src/MiddlewareStack.spec.ts index e939e9ffffb..2723d169f60 100644 --- a/packages/middleware-stack/src/MiddlewareStack.spec.ts +++ b/packages/middleware-stack/src/MiddlewareStack.spec.ts @@ -13,14 +13,15 @@ type input = Array; type output = object; //return tagged union to make compiler happy -const getConcatMiddleware = (message: string) => ( - next: FinalizeHandler -): InitializeHandler => (args: any) => - next({ - ...args, - input: args.input.concat(message), - request: undefined as any, - }); +const getConcatMiddleware = + (message: string) => + (next: FinalizeHandler): InitializeHandler => + (args: any) => + next({ + ...args, + input: args.input.concat(message), + request: undefined as any, + }); describe("MiddlewareStack", () => { describe("add", () => { diff --git a/packages/middleware-stack/src/MiddlewareStack.ts b/packages/middleware-stack/src/MiddlewareStack.ts index a806f06909d..52caaac9ad1 100644 --- a/packages/middleware-stack/src/MiddlewareStack.ts +++ b/packages/middleware-stack/src/MiddlewareStack.ts @@ -174,11 +174,14 @@ export const constructStack = (): M const mainChain = sort(normalizedAbsoluteEntries) .map(expandRelativeMiddlewareList) - .reduce((wholeList, expandedMiddlewareList) => { - // TODO: Replace it with Array.flat(); - wholeList.push(...expandedMiddlewareList); - return wholeList; - }, [] as MiddlewareEntry[]); + .reduce( + (wholeList, expandedMiddlewareList) => { + // TODO: Replace it with Array.flat(); + wholeList.push(...expandedMiddlewareList); + return wholeList; + }, + [] as MiddlewareEntry[] + ); return mainChain; }; @@ -304,9 +307,9 @@ export const constructStack = (): M return getMiddlewareList(true).map((mw: MiddlewareEntry) => { const step = mw.step ?? - ((mw as unknown) as RelativeMiddlewareOptions).relation + + (mw as unknown as RelativeMiddlewareOptions).relation + " " + - ((mw as unknown) as RelativeMiddlewareOptions).toMiddleware; + (mw as unknown as RelativeMiddlewareOptions).toMiddleware; return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step; }); }, diff --git a/packages/middleware-stack/src/types.ts b/packages/middleware-stack/src/types.ts index b1fc9025213..129d6901f72 100644 --- a/packages/middleware-stack/src/types.ts +++ b/packages/middleware-stack/src/types.ts @@ -18,7 +18,7 @@ export interface RelativeMiddlewareEntry, Input extends object = {}, - Output extends object = {} + Output extends object = {}, > = T & { after: Normalized, Input, Output>[]; before: Normalized, Input, Output>[]; diff --git a/packages/node-config-provider/src/fromEnv.ts b/packages/node-config-provider/src/fromEnv.ts index 5a613c49af1..7d28654b30b 100644 --- a/packages/node-config-provider/src/fromEnv.ts +++ b/packages/node-config-provider/src/fromEnv.ts @@ -8,16 +8,18 @@ export type GetterFromEnv = (env: Record) => T | * Get config value given the environment variable name or getter from * environment variable. */ -export const fromEnv = (envVarSelector: GetterFromEnv): Provider => async () => { - try { - const config = envVarSelector(process.env); - if (config === undefined) { - throw new Error(); +export const fromEnv = + (envVarSelector: GetterFromEnv): Provider => + async () => { + try { + const config = envVarSelector(process.env); + if (config === undefined) { + throw new Error(); + } + return config as T; + } catch (e) { + throw new CredentialsProviderError( + e.message || `Cannot load config from environment variables with getter: ${envVarSelector}` + ); } - return config as T; - } catch (e) { - throw new CredentialsProviderError( - e.message || `Cannot load config from environment variables with getter: ${envVarSelector}` - ); - } -}; + }; diff --git a/packages/node-config-provider/src/fromSharedConfigFiles.ts b/packages/node-config-provider/src/fromSharedConfigFiles.ts index cfc459c7a3f..66a5e0ab511 100644 --- a/packages/node-config-provider/src/fromSharedConfigFiles.ts +++ b/packages/node-config-provider/src/fromSharedConfigFiles.ts @@ -16,30 +16,33 @@ export type GetterFromConfig = (profile: Profile, configFile?: ParsedIniData) /** * Get config value from the shared config files with inferred profile name. */ -export const fromSharedConfigFiles = ( - configSelector: GetterFromConfig, - { preferredFile = "config", ...init }: SharedConfigInit = {} -): Provider => async () => { - const profile = getProfileName(init); - const { configFile, credentialsFile } = await loadSharedConfigFiles(init); +export const fromSharedConfigFiles = + ( + configSelector: GetterFromConfig, + { preferredFile = "config", ...init }: SharedConfigInit = {} + ): Provider => + async () => { + const profile = getProfileName(init); + const { configFile, credentialsFile } = await loadSharedConfigFiles(init); - const profileFromCredentials = credentialsFile[profile] || {}; - const profileFromConfig = configFile[profile] || {}; - const mergedProfile = - preferredFile === "config" - ? { ...profileFromCredentials, ...profileFromConfig } - : { ...profileFromConfig, ...profileFromCredentials }; + const profileFromCredentials = credentialsFile[profile] || {}; + const profileFromConfig = configFile[profile] || {}; + const mergedProfile = + preferredFile === "config" + ? { ...profileFromCredentials, ...profileFromConfig } + : { ...profileFromConfig, ...profileFromCredentials }; - try { - const cfgFile = preferredFile === "config" ? configFile : credentialsFile; - const configValue = configSelector(mergedProfile, cfgFile); - if (configValue === undefined) { - throw new Error(); + try { + const cfgFile = preferredFile === "config" ? configFile : credentialsFile; + const configValue = configSelector(mergedProfile, cfgFile); + if (configValue === undefined) { + throw new Error(); + } + return configValue; + } catch (e) { + throw new CredentialsProviderError( + e.message || + `Cannot load config for profile ${profile} in SDK configuration files with getter: ${configSelector}` + ); } - return configValue; - } catch (e) { - throw new CredentialsProviderError( - e.message || `Cannot load config for profile ${profile} in SDK configuration files with getter: ${configSelector}` - ); - } -}; + }; diff --git a/packages/node-http-handler/src/node-http-handler.spec.ts b/packages/node-http-handler/src/node-http-handler.spec.ts index c6c2155bff7..c9dc27ecf6b 100644 --- a/packages/node-http-handler/src/node-http-handler.spec.ts +++ b/packages/node-http-handler/src/node-http-handler.spec.ts @@ -123,7 +123,7 @@ describe("NodeHttpHandler", () => { const nodeHttpHandler = new NodeHttpHandler(slowConfigProvider); const promises = Promise.all( - Array.from({ length: 20 }).map(() => nodeHttpHandler.handle(({} as unknown) as HttpRequest)) + Array.from({ length: 20 }).map(() => nodeHttpHandler.handle({} as unknown as HttpRequest)) ); expect(providerInvokedCount).toBe(1); diff --git a/packages/node-http-handler/src/node-http-handler.ts b/packages/node-http-handler/src/node-http-handler.ts index 33709853cc8..46b81d4f8fc 100644 --- a/packages/node-http-handler/src/node-http-handler.ts +++ b/packages/node-http-handler/src/node-http-handler.ts @@ -173,9 +173,13 @@ export class NodeHttpHandler implements HttpHandler { // If the request is taking a long time, check socket usage and potentially warn. // This warning will be cancelled if the request resolves. - socketCheckTimeoutId = setTimeout(() => { - this.socketWarningTimestamp = NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp); - }, this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2000) + (this.config.connectionTimeout ?? 1000)); + socketCheckTimeoutId = setTimeout( + () => { + this.socketWarningTimestamp = NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp); + }, + this.config.socketAcquisitionWarningTimeout ?? + (this.config.requestTimeout ?? 2000) + (this.config.connectionTimeout ?? 1000) + ); const queryString = buildQueryString(request.query || {}); let auth = undefined; diff --git a/packages/node-http-handler/src/server.mock.ts b/packages/node-http-handler/src/server.mock.ts index 725b3a38c0a..a06b9016d18 100644 --- a/packages/node-http-handler/src/server.mock.ts +++ b/packages/node-http-handler/src/server.mock.ts @@ -22,33 +22,27 @@ const setResponseBody = (response: ServerResponse, body: string | NodeJsRuntimeB } }; -export const createResponseFunction = (httpResp: HttpResponse) => ( - request: IncomingMessage, - response: ServerResponse -) => { - response.statusCode = httpResp.statusCode; - setResponseHeaders(response, httpResp.headers); - setResponseBody(response, httpResp.body); -}; +export const createResponseFunction = + (httpResp: HttpResponse) => (request: IncomingMessage, response: ServerResponse) => { + response.statusCode = httpResp.statusCode; + setResponseHeaders(response, httpResp.headers); + setResponseBody(response, httpResp.body); + }; -export const createResponseFunctionWithDelay = (httpResp: HttpResponse, delay: number) => ( - request: IncomingMessage, - response: ServerResponse -) => { - response.statusCode = httpResp.statusCode; - setResponseHeaders(response, httpResp.headers); - setTimeout(() => setResponseBody(response, httpResp.body), delay); -}; +export const createResponseFunctionWithDelay = + (httpResp: HttpResponse, delay: number) => (request: IncomingMessage, response: ServerResponse) => { + response.statusCode = httpResp.statusCode; + setResponseHeaders(response, httpResp.headers); + setTimeout(() => setResponseBody(response, httpResp.body), delay); + }; -export const createContinueResponseFunction = (httpResp: HttpResponse) => ( - request: IncomingMessage, - response: ServerResponse -) => { - response.writeContinue(); - setTimeout(() => { - createResponseFunction(httpResp)(request, response); - }, 100); -}; +export const createContinueResponseFunction = + (httpResp: HttpResponse) => (request: IncomingMessage, response: ServerResponse) => { + response.writeContinue(); + setTimeout(() => { + createResponseFunction(httpResp)(request, response); + }, 100); + }; export const createMockHttpsServer = (): HttpsServer => { const server = createHttpsServer({ @@ -68,25 +62,23 @@ export const createMockHttp2Server = (): Http2Server => { return server; }; -export const createMirrorResponseFunction = (httpResp: HttpResponse) => ( - request: IncomingMessage, - response: ServerResponse -) => { - const bufs: Buffer[] = []; - request.on("data", (chunk) => { - bufs.push(chunk); - }); - request.on("end", () => { - response.statusCode = httpResp.statusCode; - setResponseHeaders(response, httpResp.headers); - setResponseBody(response, Buffer.concat(bufs)); - }); - request.on("error", (err) => { - response.statusCode = 500; - setResponseHeaders(response, httpResp.headers); - setResponseBody(response, err.message); - }); -}; +export const createMirrorResponseFunction = + (httpResp: HttpResponse) => (request: IncomingMessage, response: ServerResponse) => { + const bufs: Buffer[] = []; + request.on("data", (chunk) => { + bufs.push(chunk); + }); + request.on("end", () => { + response.statusCode = httpResp.statusCode; + setResponseHeaders(response, httpResp.headers); + setResponseBody(response, Buffer.concat(bufs)); + }); + request.on("error", (err) => { + response.statusCode = 500; + setResponseHeaders(response, httpResp.headers); + setResponseBody(response, err.message); + }); + }; export const getResponseBody = (response: HttpResponse) => { return new Promise((resolve, reject) => { diff --git a/packages/property-provider/src/CredentialsProviderError.ts b/packages/property-provider/src/CredentialsProviderError.ts index 7099304056d..c5a62f12ef4 100644 --- a/packages/property-provider/src/CredentialsProviderError.ts +++ b/packages/property-provider/src/CredentialsProviderError.ts @@ -13,7 +13,10 @@ import { ProviderError } from "./ProviderError"; */ export class CredentialsProviderError extends ProviderError { name = "CredentialsProviderError"; - constructor(message: string, public readonly tryNextLink: boolean = true) { + constructor( + message: string, + public readonly tryNextLink: boolean = true + ) { super(message, tryNextLink); // Remove once we stop targetting ES5. Object.setPrototypeOf(this, CredentialsProviderError.prototype); diff --git a/packages/property-provider/src/ProviderError.ts b/packages/property-provider/src/ProviderError.ts index ff03e34a40a..4f1603ebf79 100644 --- a/packages/property-provider/src/ProviderError.ts +++ b/packages/property-provider/src/ProviderError.ts @@ -11,7 +11,10 @@ */ export class ProviderError extends Error { name = "ProviderError"; - constructor(message: string, public readonly tryNextLink: boolean = true) { + constructor( + message: string, + public readonly tryNextLink: boolean = true + ) { super(message); // Remove once we stop targetting ES5. Object.setPrototypeOf(this, ProviderError.prototype); diff --git a/packages/property-provider/src/TokenProviderError.ts b/packages/property-provider/src/TokenProviderError.ts index d99ebf2f06f..b0c461e85c8 100644 --- a/packages/property-provider/src/TokenProviderError.ts +++ b/packages/property-provider/src/TokenProviderError.ts @@ -13,7 +13,10 @@ import { ProviderError } from "./ProviderError"; */ export class TokenProviderError extends ProviderError { name = "TokenProviderError"; - constructor(message: string, public readonly tryNextLink: boolean = true) { + constructor( + message: string, + public readonly tryNextLink: boolean = true + ) { super(message, tryNextLink); // Remove once we stop targetting ES5. Object.setPrototypeOf(this, TokenProviderError.prototype); diff --git a/packages/property-provider/src/chain.ts b/packages/property-provider/src/chain.ts index 69ba53ba030..c4a379ce03f 100755 --- a/packages/property-provider/src/chain.ts +++ b/packages/property-provider/src/chain.ts @@ -13,23 +13,25 @@ import { ProviderError } from "./ProviderError"; * If no providers were received or no provider resolves successfully, the * returned promise will be rejected. */ -export const chain = (...providers: Array>): Provider => async () => { - if (providers.length === 0) { - throw new ProviderError("No providers in chain"); - } +export const chain = + (...providers: Array>): Provider => + async () => { + if (providers.length === 0) { + throw new ProviderError("No providers in chain"); + } - let lastProviderError: Error | undefined; - for (const provider of providers) { - try { - const credentials = await provider(); - return credentials; - } catch (err) { - lastProviderError = err; - if (err?.tryNextLink) { - continue; + let lastProviderError: Error | undefined; + for (const provider of providers) { + try { + const credentials = await provider(); + return credentials; + } catch (err) { + lastProviderError = err; + if (err?.tryNextLink) { + continue; + } + throw err; } - throw err; } - } - throw lastProviderError; -}; + throw lastProviderError; + }; diff --git a/packages/property-provider/src/fromStatic.ts b/packages/property-provider/src/fromStatic.ts index 2b5ebf4a18d..d8b9ee51db9 100644 --- a/packages/property-provider/src/fromStatic.ts +++ b/packages/property-provider/src/fromStatic.ts @@ -3,4 +3,7 @@ import { Provider } from "@smithy/types"; /** * @internal */ -export const fromStatic = (staticValue: T): Provider => () => Promise.resolve(staticValue); +export const fromStatic = + (staticValue: T): Provider => + () => + Promise.resolve(staticValue); diff --git a/packages/service-client-documentation-generator/src/sdk-client-toc-plugin.ts b/packages/service-client-documentation-generator/src/sdk-client-toc-plugin.ts index bb16e3187dc..194cf52f2f9 100644 --- a/packages/service-client-documentation-generator/src/sdk-client-toc-plugin.ts +++ b/packages/service-client-documentation-generator/src/sdk-client-toc-plugin.ts @@ -32,7 +32,11 @@ export class SdkClientTocPlugin { @BindOption("defaultCategory") readonly defaultCategory: string; - constructor(public readonly options: Options, public readonly logger: Logger, private readonly renderer: Renderer) { + constructor( + public readonly options: Options, + public readonly logger: Logger, + private readonly renderer: Renderer + ) { this.renderer.application.converter.on(Converter.EVENT_END, this.changeLinksToLowerCase); this.renderer.application.converter.on(Converter.EVENT_RESOLVE_END, this.onEndResolve); } diff --git a/packages/signature-v4/src/HeaderFormatter.spec.ts b/packages/signature-v4/src/HeaderFormatter.spec.ts index f7e589a7a32..a33746df628 100644 --- a/packages/signature-v4/src/HeaderFormatter.spec.ts +++ b/packages/signature-v4/src/HeaderFormatter.spec.ts @@ -184,45 +184,9 @@ describe("HeaderFormatter", () => { [ "a sequence of headers", Uint8Array.from([ - 0x04, - 0xf0, - 0x9f, - 0xa6, - 0x84, - 0x06, - 0x00, - 0x04, - 0xde, - 0xad, - 0xbe, - 0xef, - 0x04, - 0xf0, - 0x9f, - 0x8f, - 0x87, - 0x00, - 0x04, - 0xf0, - 0x9f, - 0x90, - 0x8e, - 0x07, - 0x00, - 0x07, - 0xe2, - 0x98, - 0x83, - 0xf0, - 0x9f, - 0x92, - 0xa9, - 0x04, - 0xf0, - 0x9f, - 0x90, - 0xb4, - 0x01, + 0x04, 0xf0, 0x9f, 0xa6, 0x84, 0x06, 0x00, 0x04, 0xde, 0xad, 0xbe, 0xef, 0x04, 0xf0, 0x9f, 0x8f, 0x87, 0x00, + 0x04, 0xf0, 0x9f, 0x90, 0x8e, 0x07, 0x00, 0x07, 0xe2, 0x98, 0x83, 0xf0, 0x9f, 0x92, 0xa9, 0x04, 0xf0, 0x9f, + 0x90, 0xb4, 0x01, ]), { "🦄": { diff --git a/packages/signature-v4/src/SignatureV4.spec.ts b/packages/signature-v4/src/SignatureV4.spec.ts index 27a97af349b..7679df3577e 100644 --- a/packages/signature-v4/src/SignatureV4.spec.ts +++ b/packages/signature-v4/src/SignatureV4.spec.ts @@ -837,7 +837,7 @@ describe("SignatureV4", () => { const mockDate = new Date(); beforeEach(() => { - dateSpy = jest.spyOn(global, "Date").mockImplementation(() => (mockDate as unknown) as string); + dateSpy = jest.spyOn(global, "Date").mockImplementation(() => mockDate as unknown as string); }); afterEach(() => { diff --git a/packages/smithy-client/src/client.ts b/packages/smithy-client/src/client.ts index 7c7cacbae8c..c0fd856b53c 100644 --- a/packages/smithy-client/src/client.ts +++ b/packages/smithy-client/src/client.ts @@ -41,8 +41,9 @@ export class Client< HandlerOptions, ClientInput extends object, ClientOutput extends MetadataBearer, - ResolvedClientConfiguration extends SmithyResolvedConfiguration -> implements IClient { + ResolvedClientConfiguration extends SmithyResolvedConfiguration, +> implements IClient +{ public middlewareStack: MiddlewareStack = constructStack(); readonly config: ResolvedClientConfiguration; constructor(config: ResolvedClientConfiguration) { diff --git a/packages/smithy-client/src/command.ts b/packages/smithy-client/src/command.ts index 93c9a3b1acc..290972b30c2 100644 --- a/packages/smithy-client/src/command.ts +++ b/packages/smithy-client/src/command.ts @@ -26,8 +26,9 @@ export abstract class Command< Output extends ClientOutput, ResolvedClientConfiguration, ClientInput extends object = any, - ClientOutput extends MetadataBearer = any -> implements ICommand { + ClientOutput extends MetadataBearer = any, +> implements ICommand +{ public abstract input: Input; public readonly middlewareStack: IMiddlewareStack = constructStack(); @@ -40,7 +41,7 @@ export abstract class Command< O extends SO, C extends { logger: Logger; requestHandler: RequestHandler }, SI extends object = any, - SO extends MetadataBearer = any + SO extends MetadataBearer = any, >() { return new ClassBuilder(); } @@ -115,16 +116,12 @@ class ClassBuilder< O extends SO, C extends { logger: Logger; requestHandler: RequestHandler }, SI extends object = any, - SO extends MetadataBearer = any + SO extends MetadataBearer = any, > { private _init: (_: Command) => void = () => {}; private _ep: EndpointParameterInstructions = {}; - private _middlewareFn: ( - CommandCtor: any, - clientStack: any, - config: any, - options: any - ) => Pluggable[] = () => []; + private _middlewareFn: (CommandCtor: any, clientStack: any, config: any, options: any) => Pluggable[] = + () => []; private _commandName = ""; private _clientName = ""; private _additionalContext = {} as HandlerExecutionContext; @@ -241,7 +238,7 @@ class ClassBuilder< */ public constructor(...[input]: OptionalParameter) { super(); - this.input = input ?? (({} as unknown) as I); + this.input = input ?? ({} as unknown as I); closure._init(this); } @@ -285,7 +282,7 @@ export interface CommandImpl< O extends SO, C extends { logger: Logger; requestHandler: RequestHandler }, SI extends object = any, - SO extends MetadataBearer = any + SO extends MetadataBearer = any, > extends Command { readonly input: I; resolveMiddleware(stack: IMiddlewareStack, configuration: C, options: any): Handler; diff --git a/packages/types/src/auth/HttpAuthSchemeProvider.ts b/packages/types/src/auth/HttpAuthSchemeProvider.ts index 6ae9d1e3850..b675bd74f03 100644 --- a/packages/types/src/auth/HttpAuthSchemeProvider.ts +++ b/packages/types/src/auth/HttpAuthSchemeProvider.ts @@ -22,7 +22,7 @@ export interface HttpAuthSchemeParametersProvider< TConfig extends object, TContext extends HandlerExecutionContext, TParameters extends HttpAuthSchemeParameters, - TInput extends object + TInput extends object, > { (config: TConfig, context: TContext, input: TInput): Promise; } diff --git a/packages/types/src/client.ts b/packages/types/src/client.ts index cc1a4b651a1..df78b6e6a6d 100644 --- a/packages/types/src/client.ts +++ b/packages/types/src/client.ts @@ -19,7 +19,7 @@ export type CheckOptionalClientConfig = OptionalParameter; export interface InvokeFunction< InputTypes extends object, OutputTypes extends MetadataBearer, - ResolvedClientConfiguration + ResolvedClientConfiguration, > { ( command: Command, diff --git a/packages/types/src/command.ts b/packages/types/src/command.ts index 962326e4bb4..955350fa4b3 100644 --- a/packages/types/src/command.ts +++ b/packages/types/src/command.ts @@ -9,7 +9,7 @@ export interface Command< InputType extends ClientInput, ClientOutput extends MetadataBearer, OutputType extends ClientOutput, - ResolvedConfiguration + ResolvedConfiguration, > { readonly input: InputType; readonly middlewareStack: MiddlewareStack; diff --git a/packages/types/src/downlevel-ts3.4/transform/type-transform.ts b/packages/types/src/downlevel-ts3.4/transform/type-transform.ts index f129361c55f..b59970542a1 100644 --- a/packages/types/src/downlevel-ts3.4/transform/type-transform.ts +++ b/packages/types/src/downlevel-ts3.4/transform/type-transform.ts @@ -24,11 +24,11 @@ type TransformExact = [T] extends [FromType] ? ([FromType] type RecursiveTransformExact = T extends Function ? T : T extends object - ? { - [key in keyof T]: [T[key]] extends [FromType] - ? [FromType] extends [T[key]] - ? ToType - : RecursiveTransformExact - : RecursiveTransformExact; - } - : TransformExact; + ? { + [key in keyof T]: [T[key]] extends [FromType] + ? [FromType] extends [T[key]] + ? ToType + : RecursiveTransformExact + : RecursiveTransformExact; + } + : TransformExact; diff --git a/packages/types/src/transform/client-method-transforms.ts b/packages/types/src/transform/client-method-transforms.ts index e5f0dd147f6..9071032878d 100644 --- a/packages/types/src/transform/client-method-transforms.ts +++ b/packages/types/src/transform/client-method-transforms.ts @@ -13,7 +13,7 @@ export interface NarrowedInvokeFunction< HttpHandlerOptions, InputTypes extends object, OutputTypes extends MetadataBearer, - ResolvedClientConfiguration + ResolvedClientConfiguration, > { ( command: Command, @@ -44,11 +44,12 @@ export interface NarrowedInvokeMethod< NarrowType, HttpHandlerOptions, InputType extends object, - OutputType extends MetadataBearer + OutputType extends MetadataBearer, > { - (input: InputType, options?: HttpHandlerOptions): Promise< - Transform - >; + ( + input: InputType, + options?: HttpHandlerOptions + ): Promise>; ( input: InputType, cb: (err: unknown, data?: Transform) => void @@ -58,7 +59,9 @@ export interface NarrowedInvokeMethod< options: HttpHandlerOptions, cb: (err: unknown, data?: Transform) => void ): void; - (input: InputType, options?: HttpHandlerOptions, cb?: (err: unknown, data?: OutputType) => void): Promise< - Transform - > | void; + ( + input: InputType, + options?: HttpHandlerOptions, + cb?: (err: unknown, data?: OutputType) => void + ): Promise> | void; } diff --git a/packages/types/src/transform/client-payload-blob-type-narrow.spec.ts b/packages/types/src/transform/client-payload-blob-type-narrow.spec.ts index f348e878d60..efec5dc37e2 100644 --- a/packages/types/src/transform/client-payload-blob-type-narrow.spec.ts +++ b/packages/types/src/transform/client-payload-blob-type-narrow.spec.ts @@ -45,7 +45,7 @@ interface MyClient extends Client { { interface NodeJsMyClient extends NodeJsClient {} - const mockClient = (null as unknown) as NodeJsMyClient; + const mockClient = null as unknown as NodeJsMyClient; type Input = Parameters[0]; const assert1: Exact< @@ -58,7 +58,7 @@ interface MyClient extends Client { { interface NodeJsMyClient extends NodeJsClient {} - const mockClient = (null as unknown) as NodeJsMyClient; + const mockClient = null as unknown as NodeJsMyClient; const getObjectCall = () => mockClient.getObject({}); type A = Awaited>; @@ -69,7 +69,7 @@ interface MyClient extends Client { { interface NodeJsMyClient extends BrowserClient {} - const mockClient = (null as unknown) as NodeJsMyClient; + const mockClient = null as unknown as NodeJsMyClient; const putObjectCall = () => new Promise((resolve) => { mockClient.putObject({}, (err: unknown, data) => { @@ -85,7 +85,7 @@ interface MyClient extends Client { { interface NodeJsMyClient extends NodeJsClient {} - const mockClient = (null as unknown) as NodeJsMyClient; + const mockClient = null as unknown as NodeJsMyClient; const sendCall = () => mockClient.send(null as any, { abortSignal: null as any }); type A = Awaited>; diff --git a/packages/types/src/transform/client-payload-blob-type-narrow.ts b/packages/types/src/transform/client-payload-blob-type-narrow.ts index 60e97453afa..f91611c85b2 100644 --- a/packages/types/src/transform/client-payload-blob-type-narrow.ts +++ b/packages/types/src/transform/client-payload-blob-type-narrow.ts @@ -80,12 +80,12 @@ export type BrowserXhrClient = NarrowPayloadBlobTypes */ export type NarrowPayloadBlobOutputType = { [key in keyof ClientType]: [ClientType[key]] extends [ - InvokeFunction + InvokeFunction, ] ? NarrowedInvokeFunction : [ClientType[key]] extends [InvokeMethod] - ? NarrowedInvokeMethod - : ClientType[key]; + ? NarrowedInvokeMethod + : ClientType[key]; }; /** @@ -95,7 +95,7 @@ export type NarrowPayloadBlobOutputType = { */ export type NarrowPayloadBlobTypes = { [key in keyof ClientType]: [ClientType[key]] extends [ - InvokeFunction + InvokeFunction, ] ? NarrowedInvokeFunction< O, @@ -105,11 +105,11 @@ export type NarrowPayloadBlobTypes = { ConfigType > : [ClientType[key]] extends [InvokeMethod] - ? NarrowedInvokeMethod< - O, - HttpHandlerOptions, - Transform, - FunctionOutputTypes - > - : ClientType[key]; + ? NarrowedInvokeMethod< + O, + HttpHandlerOptions, + Transform, + FunctionOutputTypes + > + : ClientType[key]; }; diff --git a/packages/types/src/transform/no-undefined.spec.ts b/packages/types/src/transform/no-undefined.spec.ts index 85378e50952..63b48b17cfc 100644 --- a/packages/types/src/transform/no-undefined.spec.ts +++ b/packages/types/src/transform/no-undefined.spec.ts @@ -59,14 +59,14 @@ type A = { { // AssertiveClient should enforce union of undefined on inputs // but preserve undefined outputs. - const c = (null as unknown) as AssertiveClient; + const c = null as unknown as AssertiveClient; const input = { a: "", b: 0, c: 0, }; const get = c.getObject(input); - const output = (null as unknown) as Awaited; + const output = null as unknown as Awaited; const assert1: Exact = true as const; const assert2: Exact = true as const; @@ -81,14 +81,14 @@ type A = { { // UncheckedClient both removes union-undefined from inputs // and the nullability of outputs. - const c = (null as unknown) as UncheckedClient; + const c = null as unknown as UncheckedClient; const input = { a: "", b: 0, c: 0, }; const get = c.getObject(input); - const output = (null as unknown) as Awaited; + const output = null as unknown as Awaited; const assert1: Exact = true as const; const assert2: Exact = true as const; @@ -100,9 +100,9 @@ type A = { { // Handles methods with optionally zero args. - const c = (null as unknown) as AssertiveClient; + const c = null as unknown as AssertiveClient; const list = c.listObjects(); - const output = (null as unknown) as Awaited; + const output = null as unknown as Awaited; const assert1: Exact = true as const; const assert2: Exact = true as const; diff --git a/packages/types/src/transform/no-undefined.ts b/packages/types/src/transform/no-undefined.ts index f259bc1a83c..dab839b01af 100644 --- a/packages/types/src/transform/no-undefined.ts +++ b/packages/types/src/transform/no-undefined.ts @@ -34,10 +34,10 @@ export type UncheckedClient = UncheckedClientOutputTypes< export type NoUndefined = T extends Function ? T : [T] extends [object] - ? { - [key in keyof T]: NoUndefined; - } - : Exclude; + ? { + [key in keyof T]: NoUndefined; + } + : Exclude; /** * @internal @@ -47,10 +47,10 @@ export type NoUndefined = T extends Function export type RecursiveRequired = T extends Function ? T : [T] extends [object] - ? { - [key in keyof T]-?: RecursiveRequired; - } - : Exclude; + ? { + [key in keyof T]-?: RecursiveRequired; + } + : Exclude; /** * @internal @@ -59,14 +59,14 @@ export type RecursiveRequired = T extends Function */ type NarrowClientIOTypes = { [key in keyof ClientType]: [ClientType[key]] extends [ - InvokeMethodOptionalArgs + InvokeMethodOptionalArgs, ] ? InvokeMethodOptionalArgs, NoUndefined> : [ClientType[key]] extends [InvokeFunction] - ? InvokeFunction, NoUndefined, ConfigType> - : [ClientType[key]] extends [InvokeMethod] - ? InvokeMethod, NoUndefined> - : ClientType[key]; + ? InvokeFunction, NoUndefined, ConfigType> + : [ClientType[key]] extends [InvokeMethod] + ? InvokeMethod, NoUndefined> + : ClientType[key]; }; /** @@ -76,12 +76,12 @@ type NarrowClientIOTypes = { */ type UncheckedClientOutputTypes = { [key in keyof ClientType]: [ClientType[key]] extends [ - InvokeMethodOptionalArgs + InvokeMethodOptionalArgs, ] ? InvokeMethodOptionalArgs, RecursiveRequired> : [ClientType[key]] extends [InvokeFunction] - ? InvokeFunction, RecursiveRequired, ConfigType> - : [ClientType[key]] extends [InvokeMethod] - ? InvokeMethod, RecursiveRequired> - : ClientType[key]; + ? InvokeFunction, RecursiveRequired, ConfigType> + : [ClientType[key]] extends [InvokeMethod] + ? InvokeMethod, RecursiveRequired> + : ClientType[key]; }; diff --git a/packages/types/src/transform/type-transform.ts b/packages/types/src/transform/type-transform.ts index a4d0522348b..bfc7d94fa4b 100644 --- a/packages/types/src/transform/type-transform.ts +++ b/packages/types/src/transform/type-transform.ts @@ -24,14 +24,14 @@ type TransformExact = [T] extends [FromType] ? ([FromType] type RecursiveTransformExact = T extends Function ? T : T extends object - ? { - [key in keyof T]: [T[key]] extends [FromType] - ? [FromType] extends [T[key]] - ? ToType - : ConditionalRecursiveTransformExact - : ConditionalRecursiveTransformExact; - } - : TransformExact; + ? { + [key in keyof T]: [T[key]] extends [FromType] + ? [FromType] extends [T[key]] + ? ToType + : ConditionalRecursiveTransformExact + : ConditionalRecursiveTransformExact; + } + : TransformExact; /** * @internal @@ -40,7 +40,7 @@ type RecursiveTransformExact = T extends Function * unless there is a matching transformed member. */ type ConditionalRecursiveTransformExact = [T] extends [ - RecursiveTransformExact + RecursiveTransformExact, ] ? [RecursiveTransformExact] extends [T] ? T diff --git a/packages/util-base64/src/toBase64.browser.spec.ts b/packages/util-base64/src/toBase64.browser.spec.ts index 2be1ecc4fd2..d496ecf3163 100644 --- a/packages/util-base64/src/toBase64.browser.spec.ts +++ b/packages/util-base64/src/toBase64.browser.spec.ts @@ -25,6 +25,6 @@ describe(toBase64.name, () => { expect(() => (toBase64 as Encoder)([])).not.toThrow(); const helloUtf8Array = fromBase64("aGVsbG8="); - expect(toBase64(([...helloUtf8Array] as unknown) as Uint8Array)).toEqual("aGVsbG8="); + expect(toBase64([...helloUtf8Array] as unknown as Uint8Array)).toEqual("aGVsbG8="); }); }); diff --git a/packages/util-retry/src/AdaptiveRetryStrategy.ts b/packages/util-retry/src/AdaptiveRetryStrategy.ts index 8bffa3cb241..b838e92266b 100644 --- a/packages/util-retry/src/AdaptiveRetryStrategy.ts +++ b/packages/util-retry/src/AdaptiveRetryStrategy.ts @@ -32,7 +32,10 @@ export class AdaptiveRetryStrategy implements RetryStrategyV2 { private standardRetryStrategy: StandardRetryStrategy; public readonly mode: string = RETRY_MODES.ADAPTIVE; - constructor(private readonly maxAttemptsProvider: Provider, options?: AdaptiveRetryStrategyOptions) { + constructor( + private readonly maxAttemptsProvider: Provider, + options?: AdaptiveRetryStrategyOptions + ) { const { rateLimiter } = options ?? {}; this.rateLimiter = rateLimiter ?? new DefaultRateLimiter(); this.standardRetryStrategy = new StandardRetryStrategy(maxAttemptsProvider); diff --git a/packages/util-stream-node/src/sdk-stream-mixin.spec.ts b/packages/util-stream-node/src/sdk-stream-mixin.spec.ts index 9f8db07a5aa..654a9c664b2 100644 --- a/packages/util-stream-node/src/sdk-stream-mixin.spec.ts +++ b/packages/util-stream-node/src/sdk-stream-mixin.spec.ts @@ -98,7 +98,7 @@ describe(sdkStreamMixin.name, () => { () => ({ decode: jest.fn(), - } as any) + }) as any ); (fromArrayBuffer as jest.Mock).mockReturnValue({ toString: toStringMock }); const sdkStream = sdkStreamMixin(passThrough); diff --git a/packages/util-stream/src/sdk-stream-mixin.spec.ts b/packages/util-stream/src/sdk-stream-mixin.spec.ts index beff40a87cb..f5900baf630 100644 --- a/packages/util-stream/src/sdk-stream-mixin.spec.ts +++ b/packages/util-stream/src/sdk-stream-mixin.spec.ts @@ -113,7 +113,7 @@ describe(sdkStreamMixin.name, () => { () => ({ decode: jest.fn(), - } as any) + }) as any ); (fromArrayBuffer as jest.Mock).mockReturnValue({ toString: toStringMock }); const sdkStream = sdkStreamMixin(passThrough); diff --git a/packages/util-utf8/src/fromUtf8.spec.ts b/packages/util-utf8/src/fromUtf8.spec.ts index 5841fdb76e3..5cc02b88e9b 100644 --- a/packages/util-utf8/src/fromUtf8.spec.ts +++ b/packages/util-utf8/src/fromUtf8.spec.ts @@ -5,132 +5,16 @@ const utf8StringsToByteArrays: Record = { "🐎👱❤": new Uint8Array([240, 159, 144, 142, 240, 159, 145, 177, 226, 157, 164]), "☃💩": new Uint8Array([226, 152, 131, 240, 159, 146, 169]), "The rain in Spain falls mainly on the plain.": new Uint8Array([ - 84, - 104, - 101, - 32, - 114, - 97, - 105, - 110, - 32, - 105, - 110, - 32, - 83, - 112, - 97, - 105, - 110, - 32, - 102, - 97, - 108, - 108, - 115, - 32, - 109, - 97, - 105, - 110, - 108, - 121, - 32, - 111, - 110, - 32, - 116, - 104, - 101, - 32, - 112, - 108, - 97, - 105, - 110, - 46, + 84, 104, 101, 32, 114, 97, 105, 110, 32, 105, 110, 32, 83, 112, 97, 105, 110, 32, 102, 97, 108, 108, 115, 32, 109, + 97, 105, 110, 108, 121, 32, 111, 110, 32, 116, 104, 101, 32, 112, 108, 97, 105, 110, 46, ]), "دست‌نوشته‌ها نمی‌سوزند": new Uint8Array([ - 216, - 175, - 216, - 179, - 216, - 170, - 226, - 128, - 140, - 217, - 134, - 217, - 136, - 216, - 180, - 216, - 170, - 217, - 135, - 226, - 128, - 140, - 217, - 135, - 216, - 167, - 32, - 217, - 134, - 217, - 133, - 219, - 140, - 226, - 128, - 140, - 216, - 179, - 217, - 136, - 216, - 178, - 217, - 134, - 216, - 175, + 216, 175, 216, 179, 216, 170, 226, 128, 140, 217, 134, 217, 136, 216, 180, 216, 170, 217, 135, 226, 128, 140, 217, + 135, 216, 167, 32, 217, 134, 217, 133, 219, 140, 226, 128, 140, 216, 179, 217, 136, 216, 178, 217, 134, 216, 175, ]), "Рукописи не горят": new Uint8Array([ - 208, - 160, - 209, - 131, - 208, - 186, - 208, - 190, - 208, - 191, - 208, - 184, - 209, - 129, - 208, - 184, - 32, - 208, - 189, - 208, - 181, - 32, - 208, - 179, - 208, - 190, - 209, - 128, - 209, - 143, - 209, - 130, + 208, 160, 209, 131, 208, 186, 208, 190, 208, 191, 208, 184, 209, 129, 208, 184, 32, 208, 189, 208, 181, 32, 208, + 179, 208, 190, 209, 128, 209, 143, 209, 130, ]), }; diff --git a/packages/util-utf8/src/toUtf8.spec.ts b/packages/util-utf8/src/toUtf8.spec.ts index 32a3b1610c0..2e315834f5e 100644 --- a/packages/util-utf8/src/toUtf8.spec.ts +++ b/packages/util-utf8/src/toUtf8.spec.ts @@ -7,132 +7,16 @@ const utf8StringsToByteArrays: Record = { "🐎👱❤": new Uint8Array([240, 159, 144, 142, 240, 159, 145, 177, 226, 157, 164]), "☃💩": new Uint8Array([226, 152, 131, 240, 159, 146, 169]), "The rain in Spain falls mainly on the plain.": new Uint8Array([ - 84, - 104, - 101, - 32, - 114, - 97, - 105, - 110, - 32, - 105, - 110, - 32, - 83, - 112, - 97, - 105, - 110, - 32, - 102, - 97, - 108, - 108, - 115, - 32, - 109, - 97, - 105, - 110, - 108, - 121, - 32, - 111, - 110, - 32, - 116, - 104, - 101, - 32, - 112, - 108, - 97, - 105, - 110, - 46, + 84, 104, 101, 32, 114, 97, 105, 110, 32, 105, 110, 32, 83, 112, 97, 105, 110, 32, 102, 97, 108, 108, 115, 32, 109, + 97, 105, 110, 108, 121, 32, 111, 110, 32, 116, 104, 101, 32, 112, 108, 97, 105, 110, 46, ]), "دست‌نوشته‌ها نمی‌سوزند": new Uint8Array([ - 216, - 175, - 216, - 179, - 216, - 170, - 226, - 128, - 140, - 217, - 134, - 217, - 136, - 216, - 180, - 216, - 170, - 217, - 135, - 226, - 128, - 140, - 217, - 135, - 216, - 167, - 32, - 217, - 134, - 217, - 133, - 219, - 140, - 226, - 128, - 140, - 216, - 179, - 217, - 136, - 216, - 178, - 217, - 134, - 216, - 175, + 216, 175, 216, 179, 216, 170, 226, 128, 140, 217, 134, 217, 136, 216, 180, 216, 170, 217, 135, 226, 128, 140, 217, + 135, 216, 167, 32, 217, 134, 217, 133, 219, 140, 226, 128, 140, 216, 179, 217, 136, 216, 178, 217, 134, 216, 175, ]), "Рукописи не горят": new Uint8Array([ - 208, - 160, - 209, - 131, - 208, - 186, - 208, - 190, - 208, - 191, - 208, - 184, - 209, - 129, - 208, - 184, - 32, - 208, - 189, - 208, - 181, - 32, - 208, - 179, - 208, - 190, - 209, - 128, - 209, - 143, - 209, - 130, + 208, 160, 209, 131, 208, 186, 208, 190, 208, 191, 208, 184, 209, 129, 208, 184, 32, 208, 189, 208, 181, 32, 208, + 179, 208, 190, 209, 128, 209, 143, 209, 130, ]), }; From adfb0b4f748ff013e0d13a4010642cc8d14caf9c Mon Sep 17 00:00:00 2001 From: "Kamat, Trivikram" <16024985+trivikr@users.noreply.github.com> Date: Wed, 8 May 2024 21:19:52 +0000 Subject: [PATCH 4/5] chore: yarn prettier --write 'smithy-typescript-ssdk-libs/**/*.{ts,md,json}' --- .../server-common/src/validation/validators.spec.ts | 6 ++---- .../server-common/src/validation/validators.ts | 8 ++++---- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/smithy-typescript-ssdk-libs/server-common/src/validation/validators.spec.ts b/smithy-typescript-ssdk-libs/server-common/src/validation/validators.spec.ts index 2f2c805fa57..05d07bf4b02 100644 --- a/smithy-typescript-ssdk-libs/server-common/src/validation/validators.spec.ts +++ b/smithy-typescript-ssdk-libs/server-common/src/validation/validators.spec.ts @@ -27,10 +27,8 @@ import { describe("sensitive validation", () => { function sensitize(validator: SingleConstraintValidator, input: T): V { - const failure = new SensitiveConstraintValidator( - new CompositeValidator([validator]) - ).validate(input, "")[0]; - return (failure as unknown) as V; + const failure = new SensitiveConstraintValidator(new CompositeValidator([validator])).validate(input, "")[0]; + return failure as unknown as V; } describe("strips the failure value from the resultant validation failure", () => { diff --git a/smithy-typescript-ssdk-libs/server-common/src/validation/validators.ts b/smithy-typescript-ssdk-libs/server-common/src/validation/validators.ts index 63112172fd6..9d60b2ca2e1 100644 --- a/smithy-typescript-ssdk-libs/server-common/src/validation/validators.ts +++ b/smithy-typescript-ssdk-libs/server-common/src/validation/validators.ts @@ -238,8 +238,8 @@ export class LengthValidator implements SingleConstraintValidator Date: Thu, 9 May 2024 15:12:56 +0000 Subject: [PATCH 5/5] chore: changeset add --empty --- .changeset/fuzzy-coats-rush.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .changeset/fuzzy-coats-rush.md diff --git a/.changeset/fuzzy-coats-rush.md b/.changeset/fuzzy-coats-rush.md new file mode 100644 index 00000000000..a845151cc84 --- /dev/null +++ b/.changeset/fuzzy-coats-rush.md @@ -0,0 +1,2 @@ +--- +---