Skip to content

fix: count string-level appends and prepends in isEmpty - #345

Merged
antfu merged 1 commit into
Rich-Harris:masterfrom
wahidrizka:fix-isempty-string-edges
Sep 10, 2026
Merged

fix: count string-level appends and prepends in isEmpty#345
antfu merged 1 commit into
Rich-Harris:masterfrom
wahidrizka:fix-isempty-string-edges

Conversation

@wahidrizka

Copy link
Copy Markdown
Contributor

isEmpty() is documented, both in the README and in its own JSDoc, as returning true when "the resulting source is empty (disregarding white space)". The resulting source is what toString() produces.

However, isEmpty() only walked the chunks. It never looked at the string-level intro and outro that plain prepend() and append() write to (unlike prependLeft/prependRight/appendLeft/appendRight, which write to chunk intro/outro and were already covered). So a source whose only output came from append() or prepend() was reported as empty even though toString() returned that content.

import MagicString from 'magic-string';

const s = new MagicString('').append('X');
s.toString(); // "X"
s.isEmpty();  // true before this fix, false after

This is different from length(), which is documented and tested to deliberately exclude edge inserts. isEmpty() has no such contract: its existing test only ever prepends and appends whitespace, so it never locked the old behaviour, and every other output-facing method (toString(), generateMap(), lastChar()) already accounts for intro and outro.

The fix adds the two missing checks, mirroring the toString() order (intro first, outro last) and reusing the same whitespace-disregarding idiom already used for chunks and in Bundle#isEmpty. Bundle#isEmpty() delegates to this method per source, so it inherits the fix as well.

I added a test that fails on the old code and passes now, plus a guard test confirming that whitespace-only appends and prepends are still treated as empty. The suite goes from 262 to 264 passing; tsc and eslint are clean.

isEmpty() only walked the chunks, so it ignored the string-level intro
and outro that plain prepend() and append() write to. A source whose
only output came from append() or prepend() was reported as empty even
though toString() returned that content. isEmpty() now checks intro and
outro as well, the same way toString(), generateMap() and lastChar()
already do, while still disregarding whitespace.
@antfu
antfu merged commit d489a75 into Rich-Harris:master Sep 10, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants