Skip to content
Merged
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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { etag } from "etag";

### etag(entity, [options])

Generate an ETag for a string, `Buffer`, or file stats object. Pass the complete body when using a string or `Buffer`. File stats can come from `fs.stat` or `fs.statSync`, with or without `{ bigint: true }`. Strings and buffers generate strong ETags by default. File stats generate weak ETags by default. Use `options.weak` to override the default.
Generate an ETag for a string, ArrayBuffer view (a typed array such as `Buffer`, or a `DataView`), or file stats object. Pass the complete body when using a string or view. Only the bytes within the view are hashed. File stats can come from `fs.stat` or `fs.statSync`, with or without `{ bigint: true }`. Strings and views generate strong ETags by default. File stats generate weak ETags by default. Use `options.weak` to override the default.

```js
res.setHeader("ETag", etag(body));
Expand All @@ -38,7 +38,7 @@ res.setHeader("ETag", etag(body));

##### weak

Specifies whether the generated ETag includes the weak validator mark (the leading `W/`). The actual entity tag is the same. The default is `true` for file stats and `false` for strings and buffers.
Specifies whether the generated ETag includes the weak validator mark (the leading `W/`). The actual entity tag is the same. The default is `true` for file stats and `false` for strings and ArrayBuffer views.

## License

Expand Down
51 changes: 43 additions & 8 deletions src/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,18 @@ describe("etag(entity)", function () {
assert.throws(() => etag(), /argument entity is required/);
});

it("generates identical tags for strings and buffers around the hashing cutoff", () => {
for (const [length, expected] of [
[100 * 1024, '"9c00~OY4RezC_tF67Vh3XNOuWnQe6tz9JnPGOj8VzKJvOSWw"'],
[100 * 1024 + 1, '"9c03~JFHYAYfsvpSdSOmMOhcgQB0UG37LT8Vp9Ckwm2UPl98"'],
] as const) {
const entity = "论".repeat(length);
it.each([
[100 * 1024, '"3400~DaQsX3VThEpAXzlxC1q14A1asMDRZk-IkxobmY6XW1k"'],
[100 * 1024 + 1, '"3401~vF2SNLRIR6Dy8QjWQez8H0mMj-q75R22XQvgrlwkoDI"'],
] as const)(
"generates identical tags for a Unicode string and Buffer of %i bytes",
(length, expected) => {
const entity =
"论".repeat(Math.floor(length / 3)) + "x".repeat(length % 3);
assert.equal(etag(entity), expected);
assert.equal(etag(Buffer.from(entity)), expected);
}
});
},
);

describe('when "entity" is a string', function () {
it("should generate a strong ETag", function () {
Expand Down Expand Up @@ -71,6 +73,39 @@ describe("etag(entity)", function () {
});
});

describe('when "entity" is an ArrayBuffer view', function () {
it("generates the same tag as a Buffer with the same bytes", function () {
const bytes = Uint8Array.of(1, 2, 3);
const expected = etag(Buffer.from(bytes));

assert.strictEqual(etag(bytes), expected);
assert.strictEqual(etag(bytes, { weak: true }), "W/" + expected);
});

it.each([0, 3, (100 * 1024) / Uint16Array.BYTES_PER_ELEMENT + 1])(
"hashes only the view bytes for %i Uint16Array elements",
function (length) {
const backing = new Uint16Array(length + 2).fill(0xabcd);
const view = backing.subarray(1, length + 1).fill(0x1234);
const bytes = Buffer.from(
view.buffer,
view.byteOffset,
view.byteLength,
);

const dataView = new DataView(
view.buffer,
view.byteOffset,
view.byteLength,
);
const expected = etag(bytes);

assert.strictEqual(etag(view), expected);
assert.strictEqual(etag(dataView), expected);
},
);
});

describe('when "entity" is a fs.Stats', function () {
it("should generate a weak ETag", function () {
assert.ok(isweak(etag(fs.statSync(filename))));
Expand Down
17 changes: 9 additions & 8 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const ONESHOT_MAX_LENGTH = 100 * 1024;

/** Options for generating an entity tag. */
export interface Options {
/** Override the default: weak for file stats, strong for strings and buffers. */
/** Override the default: weak for file stats, strong for strings and ArrayBuffer views. */
weak?: boolean;
}

Expand All @@ -26,33 +26,34 @@ export interface StatsLike<T extends number | bigint> {

export type FileStats = StatsLike<number> | StatsLike<bigint>;

/** Create an ETag for a string, buffer, or file stats object. */
/** Create an ETag for a string, ArrayBuffer view, or file stats object. */
export function etag(
entity: string | Buffer | FileStats,
entity: string | NodeJS.ArrayBufferView | FileStats,
options?: Options,
): string {
if (entity == null) {
throw new TypeError("argument entity is required");
}

const isBody = typeof entity === "string" || Buffer.isBuffer(entity);
const isBody = typeof entity === "string" || ArrayBuffer.isView(entity);
const weak = typeof options?.weak === "boolean" ? options.weak : !isBody;
const tag = isBody ? entitytag(entity) : stattag(entity);

return weak ? `W/${tag}` : tag;
}

/** Generate a tag from the entity's byte length and hash. */
function entitytag(entity: string | Buffer): string {
if (entity.length === 0) {
function entitytag(entity: string | NodeJS.ArrayBufferView): string {
const length = Buffer.byteLength(entity);
if (length === 0) {
return '"0~47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU"';
}

const digest =
entity.length <= ONESHOT_MAX_LENGTH
length <= ONESHOT_MAX_LENGTH
? hash("sha256", entity, "base64url")
: createHash("sha256").update(entity).digest("base64url");
const size = Buffer.byteLength(entity).toString(32);
const size = length.toString(32);

return `"${size}~${digest}"`;
}
Expand Down