Skip to content
Open
Show file tree
Hide file tree
Changes from all 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: 5 additions & 3 deletions src/event/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,12 @@ export const isBase64 = (value: unknown): boolean =>
export const isBuffer = (value: unknown): boolean => value instanceof Buffer;

export const asBuffer = (value: string | Buffer | TypeArray): Buffer =>
isBinary(value)
? Buffer.from((value as unknown) as string)
: isBuffer(value)
isBuffer(value)
? (value as Buffer)
: isBinary(value)
? // Copy the underlying bytes. Buffer.from(typedArray) would copy the element
// values instead, truncating each one to a single byte (e.g. Float32Array).
Buffer.from((value as TypeArray).buffer, (value as TypeArray).byteOffset, (value as TypeArray).byteLength)
: (() => {
throw new TypeError("is not buffer or a valid binary");
})();
Expand Down
13 changes: 13 additions & 0 deletions test/integration/spec_1_tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,19 @@ describe("CloudEvents Spec v1.0", () => {
const ce = cloudevent.cloneWith({ datacontenttype: "text/plain", data: test.data });
expect(ce.data_base64).to.equal(test.expected);
});

it(`should encode every byte of a '${test.type.name}' in data_base64`, () => {
const ce = cloudevent.cloneWith({ datacontenttype: "application/octet-stream", data: test.data });
const bytes = Buffer.from(test.data.buffer, test.data.byteOffset, test.data.byteLength);
expect(ce.data_base64).to.equal(bytes.toString("base64"));
});
});

it("should encode only the viewed bytes of a typed array over a larger buffer", () => {
const backing = new Uint8Array([9, 9, 1, 0, 2, 0, 9, 9]);
const view = new Uint16Array(backing.buffer, 2, 2);
const ce = cloudevent.cloneWith({ datacontenttype: "application/octet-stream", data: view });
expect(ce.data_base64).to.equal(Buffer.from([1, 0, 2, 0]).toString("base64"));
});
});
});