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
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,9 @@ export default defineConfig({
});
```

The images are recompressed losslessly before they are written, because the
browser's own encoder makes them several times larger than they need to be
(this needs Node 22.2 or later for `zlib.crc32`).
Only images that actually changed are rewritten, so an update is a reviewable
diff rather than every fixture touched. Regenerating one is never routine: it
means accepting that the output changed.
Expand Down
6 changes: 5 additions & 1 deletion src/node.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import {writeFileSync} from 'node:fs';
import {resolve} from 'node:path';
import {defineBrowserCommand} from '@vitest/browser';

import {recompressPng} from './png.js';

/**
* Builds the `saveFixtureImage` browser command.
*
Expand All @@ -36,7 +38,9 @@ import {defineBrowserCommand} from '@vitest/browser';
export function createSaveFixtureImage({dir = 'test/fixtures'} = {}) {
return defineBrowserCommand((_context, name, dataUrl) => {
const file = resolve(process.cwd(), dir, `${name}.png`);
writeFileSync(file, Buffer.from(dataUrl.split(',')[1], 'base64'));
// Chromium encodes with the fastest deflate setting, which makes the image
// several times larger than its pixels need.
writeFileSync(file, recompressPng(Buffer.from(dataUrl.split(',')[1], 'base64')));
// biome-ignore lint/suspicious/noConsole: telling the developer which image was rewritten
console.log(`updated ${file}`);
});
Expand Down
60 changes: 60 additions & 0 deletions src/png.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/**
* Lossless PNG recompression for the reference images written in update mode.
*
* Chromium's `canvas.toDataURL()` encodes with the fastest deflate setting, which
* makes a PNG several times larger than its pixels need. Re-deflating the same
* filtered scanlines at the best level changes no pixel.
*/

import {crc32, deflateSync, inflateSync} from 'node:zlib';

const SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);

/**
* Re-deflates the pixel data of a PNG, leaving every other byte as it was.
*
* The IDAT chunks become one chunk and all other chunks are copied through in
* order. The scanline filters are not touched, so the format is irrelevant.
* Anything unexpected, or a result that is not smaller, returns the input.
* Never throws.
*
* @param {Buffer} png
* @returns {Buffer}
*/
export function recompressPng(png) {
try {
if (!png.subarray(0, SIGNATURE.length).equals(SIGNATURE)) {
return png;
}
const parts = [SIGNATURE];
const idat = [];
let slot = -1;
for (let pos = SIGNATURE.length; pos < png.length; ) {
const end = pos + 12 + png.readUInt32BE(pos);
if (end > png.length) {
return png;
}
if (png.toString('latin1', pos + 4, pos + 8) === 'IDAT') {
idat.push(png.subarray(pos + 8, end - 4));
slot = slot < 0 ? parts.push(null) - 1 : slot;
} else {
parts.push(png.subarray(pos, end));
}
pos = end;
}
if (slot < 0) {
return png;
}
const data = deflateSync(inflateSync(Buffer.concat(idat)), {level: 9});
const chunk = Buffer.alloc(data.length + 12);
chunk.writeUInt32BE(data.length, 0);
chunk.write('IDAT', 4, 'latin1');
data.copy(chunk, 8);
chunk.writeUInt32BE(crc32(chunk.subarray(4, chunk.length - 4)), chunk.length - 4);
parts[slot] = chunk;
const out = Buffer.concat(parts);
return out.length < png.length ? out : png;
} catch {
return png;
}
}
104 changes: 104 additions & 0 deletions test/unit/png.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import assert from 'node:assert';
import {crc32, deflateSync, inflateSync} from 'node:zlib';
import {describe, it} from 'vitest';

import {recompressPng} from '../../src/png.js';

const SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);

function chunk(type, data) {
const out = Buffer.alloc(data.length + 12);
out.writeUInt32BE(data.length, 0);
out.write(type, 4, 'latin1');
data.copy(out, 8);
out.writeUInt32BE(crc32(out.subarray(4, out.length - 4)), out.length - 4);
return out;
}

function chunksOf(png) {
const list = [];
for (let pos = 8; pos < png.length; pos += 12 + png.readUInt32BE(pos)) {
list.push({
type: png.toString('latin1', pos + 4, pos + 8),
bytes: png.subarray(pos, pos + 12 + png.readUInt32BE(pos))
});
}
return list;
}

/** A PNG of filtered rows; the filter bytes are what the browser would have chosen, not checked here. */
function makePng({idatChunks = 1, level = 1, middle = []} = {}) {
const rows = Buffer.alloc(33 * 40, 7);
const idat = deflateSync(rows, {level});
const size = Math.ceil(idat.length / idatChunks);
const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(8, 0);
ihdr.writeUInt32BE(40, 4);
ihdr.set([8, 6, 0, 0, 0], 8);
return {
rows,
png: Buffer.concat([
SIGNATURE,
chunk('IHDR', ihdr),
...middle,
...Array.from({length: idatChunks}, (_, i) => chunk('IDAT', idat.subarray(i * size, (i + 1) * size))),
chunk('IEND', Buffer.alloc(0))
])
};
}

const pixels = (png) =>
inflateSync(
Buffer.concat(
chunksOf(png)
.filter((c) => c.type === 'IDAT')
.map((c) => c.bytes.subarray(8, -4))
)
);

describe('recompressPng', () => {
it('keeps the filtered rows, in one IDAT chunk, with a correct CRC', () => {
const {png, rows} = makePng({idatChunks: 3});
const out = recompressPng(png);
assert.ok(out.length < png.length);
assert.ok(pixels(out).equals(rows));
const idat = chunksOf(out).filter((c) => c.type === 'IDAT');
assert.equal(idat.length, 1);
assert.equal(idat[0].bytes.readUInt32BE(idat[0].bytes.length - 4), crc32(idat[0].bytes.subarray(4, -4)));
});

it('copies the other chunks through in order', () => {
const middle = [chunk('gAMA', Buffer.from([0, 1, 0x86, 0xa0])), chunk('tEXt', Buffer.from('a\0b'))];
const {png} = makePng({middle});
const before = chunksOf(png).filter((c) => c.type !== 'IDAT');
const after = chunksOf(recompressPng(png)).filter((c) => c.type !== 'IDAT');
assert.deepEqual(after, before);
assert.deepEqual(
chunksOf(recompressPng(png)).map((c) => c.type),
['IHDR', 'gAMA', 'tEXt', 'IDAT', 'IEND']
);
});

describe('returns the input unchanged', () => {
const unchanged = (png) => assert.strictEqual(recompressPng(png), png);

it('for something that is not a PNG', () => {
unchanged(Buffer.from('not a png at all'));
unchanged(Buffer.alloc(0));
});

it('for a truncated PNG', () => {
unchanged(makePng().png.subarray(0, 60));
});

it('for corrupt pixel data', () => {
const {png} = makePng({middle: [chunk('IDAT', Buffer.from('garbage'))]});
unchanged(png);
});

it('when the result would not be smaller', () => {
const once = recompressPng(makePng().png);
assert.strictEqual(recompressPng(once), once);
});
});
});