Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: encoders accept strings #1176

Merged
merged 3 commits into from
Mar 7, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/fluffy-deers-doubt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@smithy/middleware-serde": minor
"@smithy/util-base64": minor
"@smithy/util-utf8": minor
"@smithy/types": minor
---

encoders allow string inputs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { EndpointBearer, SerdeFunctions } from "@smithy/types";

import { deserializerMiddleware } from "./deserializerMiddleware";

describe("deserializerMiddleware", () => {
Expand All @@ -11,7 +13,7 @@ describe("deserializerMiddleware", () => {
hostname: "hostname",
path: "path",
}),
};
} as EndpointBearer & SerdeFunctions;

const mockArgs = {
input: {
Expand Down
10 changes: 7 additions & 3 deletions packages/middleware-serde/src/deserializerMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@ import {
DeserializeMiddleware,
HandlerExecutionContext,
ResponseDeserializer,
SerdeFunctions,
} from "@smithy/types";

export const deserializerMiddleware = <Input extends object, Output extends object, RuntimeUtils = any>(
options: RuntimeUtils,
deserializer: ResponseDeserializer<any, any, RuntimeUtils>
/**
* @internal
*/
export const deserializerMiddleware = <Input extends object, Output extends object>(
options: SerdeFunctions,
deserializer: ResponseDeserializer<any, any, SerdeFunctions>
): DeserializeMiddleware<Input, Output> => (
next: DeserializeHandler<Input, Output>,
context: HandlerExecutionContext
Expand Down
16 changes: 11 additions & 5 deletions packages/middleware-serde/src/serdePlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
Provider,
RequestSerializer,
ResponseDeserializer,
SerdeFunctions,
SerializeHandlerOptions,
UrlParser,
} from "@smithy/types";
Expand Down Expand Up @@ -39,14 +40,19 @@ export type V1OrV2Endpoint = {
endpoint?: Provider<Endpoint>;
};

export function getSerdePlugin<InputType extends object, SerDeContext, OutputType extends MetadataBearer>(
config: V1OrV2Endpoint,
serializer: RequestSerializer<any, SerDeContext & EndpointBearer>,
deserializer: ResponseDeserializer<OutputType, any, SerDeContext>
/**
* @internal
*
* Note: 2nd type parameter is deprecated and unused.
*/
export function getSerdePlugin<InputType extends object, _, OutputType extends MetadataBearer>(
config: V1OrV2Endpoint & SerdeFunctions,
serializer: RequestSerializer<any, SerdeFunctions & EndpointBearer>,
deserializer: ResponseDeserializer<OutputType, any, SerdeFunctions>
): Pluggable<InputType, OutputType> {
return {
applyToStack: (commandStack: MiddlewareStack<InputType, OutputType>) => {
commandStack.add(deserializerMiddleware(config as SerDeContext, deserializer), deserializerMiddlewareOption);
commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption);
commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption);
},
};
Expand Down
4 changes: 2 additions & 2 deletions packages/middleware-serde/src/serializerMiddleware.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { EndpointBearer } from "@smithy/types";
import { EndpointBearer, SerdeFunctions } from "@smithy/types";

import { serializerMiddleware } from "./serializerMiddleware";

Expand All @@ -13,7 +13,7 @@ describe("serializerMiddleware", () => {
hostname: "hostname",
path: "path",
}),
};
} as EndpointBearer & SerdeFunctions;

const mockRequest = {
method: "GET",
Expand Down
14 changes: 10 additions & 4 deletions packages/middleware-serde/src/serializerMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
EndpointBearer,
HandlerExecutionContext,
RequestSerializer,
SerdeFunctions,
SerializeHandler,
SerializeHandlerArguments,
SerializeHandlerOutput,
Expand All @@ -10,9 +11,14 @@ import {

import type { V1OrV2Endpoint } from "./serdePlugin";

export const serializerMiddleware = <Input extends object, Output extends object, RuntimeUtils extends EndpointBearer>(
options: V1OrV2Endpoint,
serializer: RequestSerializer<any, RuntimeUtils>
/**
* @internal
*
* Note: 3rd type parameter is deprecated and unused.
*/
export const serializerMiddleware = <Input extends object, Output extends object, _>(
options: V1OrV2Endpoint & SerdeFunctions,
serializer: RequestSerializer<any, SerdeFunctions & EndpointBearer>
): SerializeMiddleware<Input, Output> => (
next: SerializeHandler<Input, Output>,
context: HandlerExecutionContext
Expand All @@ -28,7 +34,7 @@ export const serializerMiddleware = <Input extends object, Output extends object
throw new Error("No valid endpoint provider available.");
}

const request = await serializer(args.input, { ...options, endpoint } as RuntimeUtils);
const request = await serializer(args.input, { ...options, endpoint });

return next({
...args,
Expand Down
14 changes: 11 additions & 3 deletions packages/types/src/serde.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,22 @@ export interface StreamCollector {
*
* Request and Response serde util functions and settings for AWS services
*/
export interface SerdeContext extends EndpointBearer {
export interface SerdeContext extends SerdeFunctions, EndpointBearer {
requestHandler: RequestHandler<any, any>;
disableHostPrefix: boolean;
}

/**
* @public
*
* Serde functions from the client config.
*/
export interface SerdeFunctions {
base64Encoder: Encoder;
base64Decoder: Decoder;
utf8Encoder: Encoder;
utf8Decoder: Decoder;
streamCollector: StreamCollector;
requestHandler: RequestHandler<any, any>;
disableHostPrefix: boolean;
}

/**
Expand Down
20 changes: 11 additions & 9 deletions packages/types/src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,29 +12,31 @@ export type Exact<Type1, Type2> = [Type1] extends [Type2] ? ([Type2] extends [Ty
/**
* @public
*
* A function that, given a TypedArray of bytes, can produce a string
* representation thereof.
* A function that, given a Uint8Array of bytes, can produce a string
* representation thereof. The function may optionally attempt to
* convert other input types to Uint8Array before encoding.
*
* @example An encoder function that converts bytes to hexadecimal
* representation would return `'deadbeef'` when given
* `new Uint8Array([0xde, 0xad, 0xbe, 0xef])`.
* representation would return `'hello'` when given
* `new Uint8Array([104, 101, 108, 108, 111])`.
*/
export interface Encoder {
(input: Uint8Array): string;
(input: Uint8Array | string | any): string;
}

/**
* @public
*
* A function that, given a string, can derive the bytes represented by that
* string.
* string. The function may optionally attempt to
* convert other input types to string before decoding.
*
* @example A decoder function that converts bytes to hexadecimal
* representation would return `new Uint8Array([0xde, 0xad, 0xbe, 0xef])` when
* given the string `'deadbeef'`.
* representation would return `new Uint8Array([104, 101, 108, 108, 111])` when
* given the string `'hello'`.
*/
export interface Decoder {
(input: string): Uint8Array;
(input: Uint8Array | string | any): Uint8Array;
}

/**
Expand Down
1 change: 1 addition & 0 deletions packages/util-base64/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"license": "Apache-2.0",
"dependencies": {
"@smithy/util-buffer-from": "workspace:^",
"@smithy/util-utf8": "workspace:^",
"tslib": "^2.5.0"
},
"devDependencies": {
Expand Down
4 changes: 4 additions & 0 deletions packages/util-base64/src/toBase64.browser.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,8 @@ describe(toBase64.name, () => {
it.each(testCases as Array<[string, string, number[]]>)("%s", (desc, encoded, decoded) => {
expect(toBase64(new Uint8Array(decoded))).toEqual(encoded);
});

it("also converts strings", () => {
expect(toBase64("hello")).toEqual("aGVsbG8=");
});
});
16 changes: 13 additions & 3 deletions packages/util-base64/src/toBase64.browser.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
import { fromUtf8 } from "@smithy/util-utf8";

import { alphabetByValue, bitsPerByte, bitsPerLetter, maxLetterValue } from "./constants.browser";

/**
* Converts a Uint8Array of binary data to a base-64 encoded string.
* Converts a Uint8Array of binary data or a utf-8 string to a base-64 encoded string.
*
* @param input The binary data to encode
* @param _input - the binary data or string to encode.
* @returns base64 string.
*
* @see https://tools.ietf.org/html/rfc4648#section-4
*/
export function toBase64(input: Uint8Array): string {
export function toBase64(_input: Uint8Array | string): string {
let input: Uint8Array;
if (typeof _input === "string") {
input = fromUtf8(_input);
} else {
input = _input as Uint8Array;
}
let str = "";
for (let i = 0; i < input.length; i += 3) {
let bits = 0;
Expand Down
4 changes: 4 additions & 0 deletions packages/util-base64/src/toBase64.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,8 @@ describe(toBase64.name, () => {
it("should throw when given a number", () => {
expect(() => toBase64(0xdeadbeefface as any)).toThrow();
});

it("also converts strings", () => {
expect(toBase64("hello")).toEqual("aGVsbG8=");
});
});
17 changes: 13 additions & 4 deletions packages/util-base64/src/toBase64.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
import { fromArrayBuffer } from "@smithy/util-buffer-from";
import { fromUtf8 } from "@smithy/util-utf8";

/**
* Converts a Uint8Array of binary data to a base-64 encoded string using
* Converts a Uint8Array of binary data or a utf-8 string to a base-64 encoded string using
* Node.JS's `buffer` module.
*
* @param input The binary data to encode
* @param _input - the binary data or string to encode.
* @returns base64 string.
*/
export const toBase64 = (input: Uint8Array): string =>
fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("base64");
export const toBase64 = (_input: Uint8Array | string): string => {
let input: Uint8Array;
if (typeof _input === "string") {
input = fromUtf8(_input);
} else {
input = _input as Uint8Array;
}
return fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("base64");
};
7 changes: 6 additions & 1 deletion packages/util-utf8/src/toUtf8.browser.ts
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
export const toUtf8 = (input: Uint8Array): string => new TextDecoder("utf-8").decode(input);
export const toUtf8 = (input: Uint8Array | string): string => {
if (typeof input === "string") {
return input;
}
return new TextDecoder("utf-8").decode(input);
};
8 changes: 6 additions & 2 deletions packages/util-utf8/src/toUtf8.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { fromArrayBuffer } from "@smithy/util-buffer-from";

export const toUtf8 = (input: Uint8Array): string =>
fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("utf8");
export const toUtf8 = (input: Uint8Array | string): string => {
if (typeof input === "string") {
return input;
}
return fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("utf8");
};
1 change: 1 addition & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2554,6 +2554,7 @@ __metadata:
resolution: "@smithy/util-base64@workspace:packages/util-base64"
dependencies:
"@smithy/util-buffer-from": "workspace:^"
"@smithy/util-utf8": "workspace:^"
"@tsconfig/recommended": 1.0.1
"@types/node": ^14.14.31
concurrently: 7.0.0
Expand Down
Loading