magic-string edits by original index, and its README example ends inside an unclosed call
Manipulate strings like a wizard
At a glance
- What is it?
- A string manipulation utility that keeps every character index anchored to the original text and emits a version 3 sourcemap for the result. Its packaging is ESM-only, its hires option has four values, and two thirds of its method list is about which edge of a range an insert binds to.
- Who is it for?
- This fits a specific job: light edits to source you did not author, where reparsing and reprinting would lose formatting you were trying to keep, and where you need a sourcemap for the result. recast is named in the project's own opening as the thing this avoids being, on the grounds that it is overkill or that the source is not JavaScript at all.
- Can I use it commercially?
- Yes. MIT is a permissive licence: you can use, modify and sell software built on it, as long as you keep its copyright and licence notices.
- Is it still maintained?
- Yes. The repository last received commits 19 days ago.
- What is it written in?
- Mainly TypeScript, according to GitHub's language statistics.
Answers come from the project's GitHub data, last synced on November 15, 2026, and from our analysis. They are not legal advice.
Star history
- Rich-Harris/magic-string2,783 ★ · +5
| Repository | 2026-10-04 | 2026-11-15 |
|---|---|---|
| Rich-Harris/magic-string | 2.8k | 2.8k |
5 Stars in the last 42 days, measured from the daily GitHub snapshot. Compare with other projects
Editorial analysis
The usage example writes the map with an unclosed call
The opening example is the one every reader copies first, and it does not parse.
It builds a string, updates two ranges, prepends and appends, generates a map and then writes two files. The last line reads `fs.writeFileSync('converted.js.map', map`, with no closing parenthesis and no semicolon, and the code block ends there. The line before it, `fs.writeFileSync('converted.js', s.toString())`, is complete, so the omission is in the final statement rather than a truncation of the whole snippet.
The mechanics above it are the clearest statement of the core design in the whole document. A string is created, `s.update(0, 8, 'answer')` replaces a range, and a second update at indices 11 and 13 carries the comment that character indices always refer to the original string. That property is what makes the library safe to chain: the edits are anchored to the input, so a later `prepend('var ')` and `append(';')` cannot invalidate an earlier index, and the accumulated result comes out of `toString()` as `'var answer = 42;'`.
So the example teaches the right thing and then fails to compile. Copying it means fixing one character, and anyone who does not notice gets a syntax error rather than a subtly wrong map.
ESM-only, and the browser import reaches past the exports map
There is no CommonJS entry point, and the browser example loads a file path rather than a package name.
Installation for node is one line, `npm i magic-string`, and the next paragraph states that magic-string is ESM-only. For browsers it points at an ESM CDN and imports from a full file path:
<script type="module">
import MagicString from 'https://unpkg.com/magic-string/dist/index.mjs';
</script>The manifest explains why that path is the only one available. The `exports` map has exactly two entries, `.` pointing at `./dist/index.mjs` and `./package.json` pointing at the manifest itself, `types` is `./dist/index.d.mts`, and `files` ships `README.md` and `dist/*`. So the CDN URL and the exports map resolve to the same file, and the difference is that a CDN cannot honour a bare specifier, which is why the documentation hardcodes the `dist/` path that the manifest itself treats as internal.
Two smaller manifest facts sit alongside. `sideEffects` is false, so importing the package for a single method and bundling it will not drag in the rest. And `packageManager` pins pnpm at 12.3.4 with a `pnpm-lock.yaml` and a `pnpm-workspace.yaml` at the root, while the installation instruction a consumer reads says npm. Contributor tooling and consumer tooling are two different tools here, which is a small thing to know before you file an issue about a lockfile.
hires takes four values and one of them is labelled experimental
The granularity of the generated map is a single option with four settings, and the choice is a promise about what devtools can do.
`false` is the default and gives low resolution mappings: one mapping per line, plus any locations added with `s.addSourcemapLocation()`. The tradeoff is stated plainly, quicker to generate and less bulky, but devtools may only be able to identify the correct line and not the exact column. `true` maps every single character, so devtools can pinpoint the exact location of a call.
The two in between are the interesting ones. `"boundary"` is semi hi res, segmented per word boundary instead of per character, and it is described as suitable for string semantics that are separated by words, which is the case where per character mapping buys nothing. `"experimental-range"` maps ranges rather than positions, using a source map extension proposed in the tc39 ecma426 repository, so a whole span can be covered with fewer mappings than mapping each character. It carries two conditions: the consumer has to support range mappings, and the feature is called experimental.
The option is passed to both `generateMap` and `generateDecodedMap`, so the same four settings apply whether you want the encoded map or the raw one. The practical reading is that three values are safe and one is a forward bet on your tooling catching up.
appendLeft and appendRight differ only in which edge they bind to
Two of the methods look redundant until you read the sentence about movement, and that sentence is the whole difference.
`s.appendLeft(index, content)` appends content at an index in the original string, and if a range ending with that index is subsequently moved, the insert moves with it. `s.appendRight(index, content)` appends at the same kind of index, and if a range starting with that index is subsequently moved, the insert moves with it. Both return `this`, and each points at its counterpart.
So the choice is not about left or right on screen, it is about which boundary of a moved range your inserted text should belong to. Text inserted to the left of a range travels when that range's right edge is the one that moves, and text inserted to the right travels when its left edge moves. Pick the wrong one and your insertion stays behind while the code it was meant to annotate moves away, which is a bug that shows up as a comment or a log line in the wrong place rather than as an error.
The same family has `prependLeft` and `prependRight`, which are the mirror operations. All four of them, along with `slice`, `update`, `overwrite`, `move`, `reset` and `remove`, take their index from the original string, which is the property that makes the whole scheme coherent.
offset shifts a named list of methods and addSourcemapLocation is not on it
The offset exists for when your indices come from somewhere other than the string you constructed, and the documentation is explicit about which calls it touches and which it does not.
Setting the offset property adjusts the incoming position for these APIs: `slice`, `update`, `overwrite`, `appendLeft`, `prependLeft`, `appendRight`, `prependRight`, `move`, `reset` and `remove`. Ten names, all of which take an index. The worked example is short:
const s = new MagicString('hello world', { offset: 6 })
s.offset = 6
s.slice() === 'world'Note that the constructor takes `offset` as well, so the value can be set at creation or reassigned afterwards, and reassigning it changes what later index arguments mean.
Two absences are worth noticing. `addSourcemapLocation` is not on that list, and its own entry says it adds the specified character index with respect to the original string, which is the unshifted coordinate system. So a sourcemap location and an edit index can refer to different places in the same string once an offset is in play. And `indent` is not on the list either, which fits, since it takes a prefix rather than an index.
`getIndentString()` is also outside the offset system: it guesses the indentation from the original content and falls back to a single tab character, and that guess is made from the source string rather than from any shifted coordinate.
indent counts lines in the output, so added content is indented too
Indentation is computed against the string you are about to produce, not the one you started with, and the example proves it.
const s = new MagicString('var a = 1;\nvar b = 2;')
s.prependRight(11, 'debugger;\n')
s.toString() // 'var a = 1;\ndebugger;\nvar b = 2;'
s.indent(' ')
s.toString() // ' var a = 1;\n debugger;\n var b = 2;'The inserted `debugger;` line was added after construction, and it receives the prefix along with the two original lines. The documentation states the rule: lines are counted in the generated string, so content added with `append` and `prepend` is indented too, and a line break inside that added content starts a new line just like a line break in the original. That second half is the part that catches people, because a multi line string literal added in one call becomes several indented lines rather than one.
The `options` argument adds an `exclude` property, an array of `[start, end]` character ranges left out of the indentation, described as useful for multiline strings. So the escape hatch for a template literal you did not want reformatted is a range, and the ranges are in the same original string coordinates as every other index here.
generateMap returns an object with two hidden methods, and the codec is the only dependency
The returned map is not plain JSON, and that is deliberate.
Two non enumerable methods are attached for convenience. `toString` returns the equivalent of `JSON.stringify(map)`, which is why the usage example can hand the object straight to a write call. `toUrl` returns a DataURI containing the sourcemap, intended for appending to generated code, which the documentation shows as a template literal appending a sourceMappingURL comment built from `map.toUrl()`.
Non enumerable means the two functions do not appear when the object is enumerated or serialised, so a consumer that only knows about sourcemap fields sees a plain object. The inlined form is not hypothetical: the tree carries `example/app.inlinemap.js` next to `example/app.js`, `example/app.js.map` and `example/app.source.js`, plus `example/build.js` and `example/index.html`, which is a worked example of both the separate map file and the inline one.
The runtime dependency list is a single entry, `@jridgewell/sourcemap-codec`, and it is there for the other method. `generateDecodedMap` produces mappings in array form rather than as an encoded string, which is what a codec is for, and it is the option to reach for when you intend to manipulate the map further. Everything else in the manifest is a development dependency, including vitest, tsdown, eslint, publint and the `benchmark` package that `pnpm bench` runs after a build.
Editorial conclusion
This fits a specific job: light edits to source you did not author, where reparsing and reprinting would lose formatting you were trying to keep, and where you need a sourcemap for the result. recast is named in the project's own opening as the thing this avoids being, on the grounds that it is overkill or that the source is not JavaScript at all. It is not a parser and does not pretend to be one, which is exactly why every index refers to the original string and why the four hires modes exist as a separate decision. Three things to settle first. Which hires mode your sourcemap consumer can actually read, since experimental-range needs range mapping support and the default only promises a line. Whether appendLeft or appendRight is the one you want, because the difference decides whether your inserted text travels with a range that ends at that index or one that starts there. And whether the tab fallback in the indentation guess matches your project, because a file with no detectable indentation gets a tab regardless of what the rest of the codebase uses. The package is ESM-only and ships one runtime dependency, so adopting it costs a bundler entry and a type file, not a dependency tree.
Frequently asked questions
What does magic-string do to a string?
It applies edits by character index against the original string, and every index you pass refers to that original rather than to the current output. It can prepend, append, overwrite, slice, move, remove and indent, and it can generate a version 3 sourcemap for the result.
Is magic-string ESM-only, and how is it loaded in a browser?
It is ESM-only. In node you install with npm i magic-string, and in a browser you import it from an ESM CDN, with the documentation pointing at https://unpkg.com/magic-string/dist/index.mjs. The manifest has no CommonJS entry in its exports map.
What are the hires options in magic-string?
false for the default low resolution mappings, one per line plus any index added with addSourcemapLocation; true to map every character; boundary to segment per word boundary instead of per character; and experimental-range, which uses range mappings and needs support for them in the consumer.
What is the difference between appendLeft and appendRight in magic-string?
Both insert content at an index in the original string. An appendLeft insert moves along with a range that ends with that index, while an appendRight insert moves with a range that starts with it. prependLeft and prependRight are the mirror operations.
What does the offset option change in magic-string?
It adjusts the incoming position for slice, update, overwrite, appendLeft, prependLeft, appendRight, prependRight, move, reset and remove. In the given example, an offset of 6 on 'hello world' makes s.slice() return 'world'.
How many runtime dependencies does magic-string have?
One, @jridgewell/sourcemap-codec, which backs generateDecodedMap. Everything else in the manifest is a development dependency, and the published files are README.md and dist/*, with types at ./dist/index.d.mts.
Official sources
Add this badge to your README
If you maintain this project, the badge below links readers to this analysis and shows its maintenance status from the daily GitHub snapshot. Paste the markdown into your README; add ?metric=license or ?metric=stars to the image URL for a different field.
[](https://hysenlabs.com/projects/rich-harris-magic-string)Star history chart for your README
[](https://hysenlabs.com/projects/rich-harris-magic-string)Was this useful?