* Flattens the bundle into a single `MagicString`, so the concatenated result can be * processed further with the full `MagicString` API. The returned string's `original` * is the concatenation of every source's `original`, and all existing edits, inserts, * intros, outros and separators ar
()
| 176 | * over; generate the bundle's map before flattening if you need the multi-source mapping. |
| 177 | */ |
| 178 | toMagicString(): MagicString { |
| 179 | const combined = new MagicString(this.sources.map(source => source.content.original).join('')) |
| 180 | |
| 181 | let offset = 0 |
| 182 | let pending = this.intro |
| 183 | let first: Chunk | null = null |
| 184 | let last: Chunk | null = null |
| 185 | const byStart = new Map<number, Chunk>() |
| 186 | const byEnd = new Map<number, Chunk>() |
| 187 | let hasMovedChunks = false |
| 188 | |
| 189 | for (const [i, source] of this.sources.entries()) { |
| 190 | const magicString = source.content |
| 191 | const separator = i > 0 ? source.separator : '' |
| 192 | |
| 193 | // A source with no original contributes only inserted text (its intro, any |
| 194 | // appends, its outro), which has no place in the combined coordinate space, |
| 195 | // so fold it into the text waiting in front of the next real chunk. |
| 196 | if (magicString.original.length === 0) { |
| 197 | pending += separator + magicString.toString() |
| 198 | continue |
| 199 | } |
| 200 | |
| 201 | pending += separator + magicString.intro |
| 202 | |
| 203 | let sourceFirst: Chunk | null = null |
| 204 | let previous: Chunk | null = null |
| 205 | let originalChunk: Chunk | null = magicString.firstChunk |
| 206 | while (originalChunk) { |
| 207 | const chunk = originalChunk.clone() |
| 208 | chunk.start += offset |
| 209 | chunk.end += offset |
| 210 | // these record positions in the source's original too |
| 211 | if (chunk.replacesUntil !== -1) |
| 212 | chunk.replacesUntil += offset |
| 213 | if (chunk.replacedFrom !== -1) |
| 214 | chunk.replacedFrom += offset |
| 215 | chunk.previous = previous |
| 216 | chunk.next = null |
| 217 | if (previous) |
| 218 | previous.next = chunk |
| 219 | byStart.set(chunk.start, chunk) |
| 220 | byEnd.set(chunk.end, chunk) |
| 221 | sourceFirst ??= chunk |
| 222 | previous = chunk |
| 223 | originalChunk = originalChunk.next |
| 224 | } |
| 225 | const sourceLast = previous! |
| 226 | |
| 227 | sourceFirst!.intro = pending + sourceFirst!.intro |
| 228 | pending = '' |
| 229 | sourceLast.outro += magicString.outro |
| 230 | |
| 231 | if (last) { |
| 232 | last.next = sourceFirst |
| 233 | sourceFirst!.previous = last |
| 234 | } |
| 235 | else { |