From 68a3af51d8f9830d3c583424aef4dd6a03e777c0 Mon Sep 17 00:00:00 2001 From: Mathias Wulff Date: Fri, 23 Oct 2026 05:15:42 +1100 Subject: [PATCH 1/2] Count bytes and size in the encoding of the file in --replacement-js to close #688 --- src/engine.ts | 3 ++- test/js/encoding.test.js | 23 ++++++++++------------- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/src/engine.ts b/src/engine.ts index c9b4d2e4..9446cc37 100644 --- a/src/engine.ts +++ b/src/engine.ts @@ -563,7 +563,8 @@ function dynamicReplacement(_file_rr, _config_rr, _data_rr) { } if (needsByteOrSize && -1 === _bytes) { - _bytes = Buffer.from(_text).length; + // The size in the encoding of the file, not of the text as utf8 + _bytes = Buffer.byteLength(_text, _config_rr.encoding); _size = readableSize(_bytes); } diff --git a/test/js/encoding.test.js b/test/js/encoding.test.js index 8fc75d70..d6d7d53d 100644 --- a/test/js/encoding.test.js +++ b/test/js/encoding.test.js @@ -125,18 +125,15 @@ describe('--encoding', () => { expect((await rr('æ', 'text.length + text', config)).out).toBe('f3fæoo\n'); }); - test.todo( - 'BUG #688: with --replacement-js `bytes` is the size of the file in its encoding', - async () => { - fs.writeFileSync('my.file', latin1()); - const config = { - includeGlob: ['my.file'], - encoding: 'latin1', - replacementJs: true, - output: true, - }; - expect((await rr('^', 'bytes + ":"', config)).out).toBe('3:fæo'); - } - ); + test('with --replacement-js `bytes` and `size` are the size of the file in its encoding (#688)', async () => { + fs.writeFileSync('my.file', latin1()); + const config = { + includeGlob: ['my.file'], + encoding: 'latin1', + replacementJs: true, + output: true, + }; + expect((await rr('^', 'bytes + ":" + size + ":"', config)).out).toBe('3:3 Bytes:fæo\n'); + }); }); }); From cafbce2523e28efc7f11d3355afad8c866991031 Mon Sep 17 00:00:00 2001 From: Mathias Wulff Date: Fri, 23 Oct 2026 10:08:54 +1100 Subject: [PATCH 2/2] Test bytes and size of --replacement-js on a file where they differ from utf8 --- test/js/encoding.test.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/test/js/encoding.test.js b/test/js/encoding.test.js index d6d7d53d..ae651cfc 100644 --- a/test/js/encoding.test.js +++ b/test/js/encoding.test.js @@ -126,14 +126,17 @@ describe('--encoding', () => { }); test('with --replacement-js `bytes` and `size` are the size of the file in its encoding (#688)', async () => { - fs.writeFileSync('my.file', latin1()); + // 1500 times `æ`: one byte each in latin1, but two in utf8 (that would give 3000 and 2.9 KB) + fs.writeFileSync('my.file', Buffer.alloc(1500, 0xe6)); const config = { includeGlob: ['my.file'], encoding: 'latin1', replacementJs: true, output: true, }; - expect((await rr('^', 'bytes + ":" + size + ":"', config)).out).toBe('3:3 Bytes:fæo\n'); + expect((await rr('^', 'bytes + ":" + size + ":"', config)).out).toBe( + '1500:1.5 KB:' + 'æ'.repeat(1500) + '\n' + ); }); }); });