1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
use std::{cell::RefCell, collections::HashMap, rc::Rc, string::ToString};
use crate::utils::{normalize_index, trim};
#[cfg(feature = "node-api")]
use napi_derive::napi;
use crate::{
chunk::Chunk,
mapping::{Mapping, Mappings},
result::Result,
source_map::SourceMap,
utils::locator::Locator,
Error, MagicStringErrorType,
};
#[cfg(feature = "node-api")]
#[napi(object)]
#[derive(Debug, Default, Clone)]
pub struct GenerateDecodedMapOptions {
pub file: Option<String>,
pub source_root: Option<String>,
pub source: Option<String>,
pub include_content: bool,
pub hires: bool,
}
#[cfg(not(feature = "node-api"))]
#[derive(Debug, Default, Clone)]
pub struct GenerateDecodedMapOptions {
pub file: Option<String>,
pub source_root: Option<String>,
pub source: Option<String>,
pub include_content: bool,
pub hires: bool,
}
#[cfg(feature = "node-api")]
#[napi(object)]
#[derive(Debug, Default, Clone)]
pub struct OverwriteOptions {
pub content_only: bool,
}
#[cfg(not(feature = "node-api"))]
#[derive(Debug, Default, Clone)]
pub struct OverwriteOptions {
pub content_only: bool,
}
#[derive(Debug, Serialize)]
pub struct DecodedMap {
pub file: Option<String>,
pub sources: Vec<Option<String>>,
pub source_root: Option<String>,
pub sources_content: Vec<Option<String>>,
pub names: Vec<String>,
pub mappings: Mappings,
}
#[derive(Debug, Clone)]
pub struct MagicString {
original_str: String,
original_str_locator: Locator,
intro: String,
outro: String,
chunk_by_start: HashMap<u32, Rc<RefCell<Chunk>>>,
chunk_by_end: HashMap<u32, Rc<RefCell<Chunk>>>,
last_searched_chunk: Rc<RefCell<Chunk>>,
first_chunk: Rc<RefCell<Chunk>>,
last_chunk: Rc<RefCell<Chunk>>,
}
impl MagicString {
/// ## Create a new `MagicString` instance
///
/// Example:
/// ```
/// use magic_string::MagicString;
///
/// let mut s = MagicString::new("import React from 'react'");
///
/// assert_eq!(s.to_string(), "import React from 'react'");
/// ```
///
///
pub fn new(str: &str) -> MagicString {
let original_chunk = Rc::new(RefCell::new(Chunk::new(0u32, str.len() as u32, str)));
MagicString {
original_str: String::from(str),
intro: String::default(),
outro: String::default(),
chunk_by_start: HashMap::default(),
chunk_by_end: HashMap::default(),
first_chunk: Rc::clone(&original_chunk),
last_chunk: Rc::clone(&original_chunk),
last_searched_chunk: Rc::clone(&original_chunk),
original_str_locator: Locator::new(str),
}
}
/// ## Append `string`
///
/// Appends the specified content to the end of the string. Returns `self`.
///
/// Example:
/// ```
/// use magic_string::MagicString;
///
/// let mut s = MagicString::new("import React from 'react'");
///
/// s.append("\nexport default React");
///
/// assert_eq!(s.to_string(), "import React from 'react'\nexport default React");
///
/// ```
pub fn append(&mut self, str: &str) -> Result<&mut Self> {
self.outro = format!("{}{}", self.outro, str);
Ok(self)
}
/// ## Prepend `string`
///
/// Prepends the string with the specified content. Returns `self`.
///
/// Example:
/// ```
/// use magic_string::MagicString;
///
/// let mut s = MagicString::new("export default React");
///
/// s.prepend("import React from 'react'\n");
///
/// assert_eq!(s.to_string(), "import React from 'react'\nexport default React");
///
/// ```
pub fn prepend(&mut self, str: &str) -> Result<&mut Self> {
self.intro = format!("{}{}", str, self.intro);
Ok(self)
}
/// ## Prepend left
///
/// Same as `s.append_left(...)`, except that the inserted content will go before any previous appends or prepends at index. Returns `self`.
pub fn prepend_left(&mut self, index: u32, str: &str) -> Result<&mut Self> {
self._split_at_index(index)?;
if let Some(chunk) = self.chunk_by_end.get(&index) {
chunk.borrow_mut().prepend_outro(str);
} else {
self.intro = format!("{}{}", str, self.intro)
};
Ok(self)
}
/// ## Prepend right
///
/// Same as `s.append_right(...)`, except that the inserted content will go before any previous appends or prepends at index. Returns `self`.
pub fn prepend_right(&mut self, index: u32, str: &str) -> Result<&mut Self> {
self._split_at_index(index)?;
if let Some(chunk) = self.chunk_by_start.get(&index) {
chunk.borrow_mut().prepend_intro(str);
} else {
self.outro = format!("{}{}", str, self.outro)
};
Ok(self)
}
/// ## Append left
///
/// Appends the specified content at the index in the original string.
/// If a range ending with index is subsequently moved, the insert will be moved with it. Returns this. See also `s.prepend_left(...)`. Returns `self`.
pub fn append_left(&mut self, index: u32, str: &str) -> Result<&mut Self> {
self._split_at_index(index)?;
if let Some(chunk) = self.chunk_by_end.get(&index) {
chunk.borrow_mut().append_outro(str);
} else {
self.intro = format!("{}{}", self.intro, str);
};
Ok(self)
}
/// ## Append right
///
/// Appends the specified content at the index in the original string.
/// If a range starting with index is subsequently moved, the insert will be moved with it. Returns this. See also `s.prepend_right(...)`. Returns `self`.
pub fn append_right(&mut self, index: u32, str: &str) -> Result<&mut Self> {
self._split_at_index(index)?;
if let Some(chunk) = self.chunk_by_start.get(&index) {
chunk.borrow_mut().append_intro(str);
} else {
self.append(str)?;
};
Ok(self)
}
/// ## Overwrite
///
/// Replaces the characters from start to end with content. Returns `self`.
/// The fourth argument is optional.
/// - and a `content_only` property which determines whether only the content is overwritten, or anything that was appended/prepended to the range as well.
///
/// Example:
/// ```
/// use magic_string::{MagicString, OverwriteOptions};
///
///
/// let mut s = MagicString::new("abcdefg");
///
/// s.overwrite(1,4, "z", OverwriteOptions::default());
/// assert_eq!(s.to_string(), "azefg")
///
/// ```
///
pub fn overwrite(
&mut self,
start: i64,
end: i64,
content: &str,
options: OverwriteOptions,
) -> Result<&mut Self> {
let content_only = options.content_only;
let start = normalize_index(self.original_str.as_str(), start)?;
let end = normalize_index(self.original_str.as_str(), end)?;
let start = start as u32;
let end = end as u32;
if start == end {
return Err(Error::new_with_reason(
MagicStringErrorType::MagicStringOutOfRangeError,
"Start and end should not be the same. Please consider using `append_(left|right)` or `prepend_(left|right)` instead",
));
}
if start > end {
return Err(Error::new_with_reason(
MagicStringErrorType::MagicStringOutOfRangeError,
"Start must be greater than end.",
));
}
self._split_at_index(start)?;
self._split_at_index(end)?;
let start_chunk: Option<Rc<RefCell<Chunk>>> = self.chunk_by_start.get(&start).map(Rc::clone);
let end_chunk: Option<Rc<RefCell<Chunk>>> = self.chunk_by_end.get(&end).map(Rc::clone);
if let Some(start_chunk) = start_chunk {
// Note: This original implementation looks a little bit weird to me.
// It should check whether the latter chunks had been edited(not only for content-wise, but also for intro and outro) or not,
// then we could return the Error. But for now, It's been doing just fine.
if start_chunk.borrow().end < end
&& (start_chunk.borrow().next
!= self
.chunk_by_start
.get(&start_chunk.borrow().end)
.map(Rc::clone))
{
return Err(Error::new_with_reason(
MagicStringErrorType::MagicStringCrossChunkError,
"unable to edit overlapped chunks",
));
}
Chunk::try_each_next(Rc::clone(&start_chunk), |chunk| {
if start_chunk == chunk {
start_chunk.borrow_mut().content = content.to_owned();
if !content_only {
start_chunk.borrow_mut().intro = String::default();
start_chunk.borrow_mut().outro = String::default();
}
return Ok(false);
}
if end_chunk.is_some()
&& chunk.borrow().start
>= (end_chunk.as_ref().map(Rc::clone).unwrap() as Rc<RefCell<Chunk>>)
.borrow()
.end
{
return Ok(true);
}
chunk.borrow_mut().content = String::default();
if !content_only {
chunk.borrow_mut().intro = String::default();
chunk.borrow_mut().outro = String::default();
}
Ok(false)
})?
}
Ok(self)
}
/// ## Trim start and end
///
/// Trims content matching `pattern` (defaults to '\s', i.e. whitespace) from the start and the end. Returns `self`.
/// Note that in Rust, '\t'(char) and "\\t"(string) are different types, whereas they are regarded the same pattern in Regex, which means you can pass eiter one of them to `pattern` argument.
///
/// Example:
/// ```
/// use magic_string::MagicString;
///
/// let mut s = MagicString::new(" abc ");
/// s.trim(None);
///
/// assert_eq!(s.to_string(), "abc");
///
/// let mut s = MagicString::new("\t\t abc \t\t");
/// s.trim(Some("\t"));
///
/// assert_eq!(s.to_string(), " abc ");
///
/// let mut s = MagicString::new("\t\t abc \t\t");
/// s.trim(Some("\t|\\s"));
///
/// assert_eq!(s.to_string(), "abc");
/// ```
pub fn trim(&mut self, pattern: Option<&str>) -> Result<&mut Self> {
self.trim_start(pattern)?.trim_end(pattern)
}
/// ## Trim start
///
/// Trims content matching `pattern` (defaults to '\s', i.e. whitespace) from the start. Returns `self`.
///
/// Example:
/// ```
/// use magic_string::MagicString;
///
/// let mut s = MagicString::new(" abc");
/// s.trim_start(None);
///
/// assert_eq!(s.to_string(), "abc");
///
/// let mut s = MagicString::new(" abc");
/// s.prepend(" ");
/// s.trim_start(None);
///
/// assert_eq!(s.to_string(), "abc");
///
/// let mut s = MagicString::new(" abc");
/// s.prepend("\t\ta");
/// s.trim_start(Some("\t"));
///
/// assert_eq!(s.to_string(), "a abc");
/// ```
pub fn trim_start(&mut self, pattern: Option<&str>) -> Result<&mut Self> {
let pattern = pattern.unwrap_or("\\s");
self.intro = trim::trim_start_regexp(self.intro.as_str(), pattern)?.to_owned();
if !self.intro.is_empty() {
return Ok(self);
}
let error = Error::default();
Chunk::try_each_next(Rc::clone(&self.first_chunk), |chunk| {
self.last_searched_chunk = Rc::clone(&chunk);
if let Err(e) = chunk.borrow_mut().trim_start_regexp(pattern) {
return Err(e);
}
Ok(!chunk.borrow().to_string().is_empty())
})?;
if error != Error::default() {
return Err(error);
}
if self.last_searched_chunk == self.last_chunk
&& self.last_chunk.borrow().content.to_string().is_empty()
{
self.outro = trim::trim_start_regexp(self.outro.as_str(), pattern)?.to_owned()
}
Ok(self)
}
/// ## Trim end
///
/// Trims content matching `pattern` (defaults to '\s', i.e. whitespace) from the end. Returns `self`.
///
/// Example:
/// ```
/// use magic_string::MagicString;
///
/// let mut s = MagicString::new("abc ");
/// s.trim_end(None);
///
/// assert_eq!(s.to_string(), "abc");
///
/// let mut s = MagicString::new("abc ");
/// s.append(" ");
/// s.trim_end(None);
///
/// assert_eq!(s.to_string(), "abc");
///
/// let mut s = MagicString::new("abc");
/// s.append(" a\t\t");
/// s.trim_end(Some("\t"));
///
/// assert_eq!(s.to_string(), "abc a");
pub fn trim_end(&mut self, pattern: Option<&str>) -> Result<&mut Self> {
let pattern = pattern.unwrap_or("\\s");
self.outro = trim::trim_end_regexp(self.outro.as_str(), pattern)?.to_owned();
if !self.outro.is_empty() {
return Ok(self);
}
Chunk::try_each_prev(Rc::clone(&self.last_chunk), |chunk| {
self.last_searched_chunk = Rc::clone(&chunk);
if let Err(e) = chunk.borrow_mut().trim_end_regexp(pattern) {
return Err(e);
}
Ok(!chunk.borrow().to_string().is_empty())
})?;
if self.last_searched_chunk == self.first_chunk
&& self.first_chunk.borrow().content.to_string().is_empty()
{
self.intro = trim::trim_end_regexp(self.intro.as_str(), pattern)?.to_owned()
}
Ok(self)
}
/// ## Trim lines
///
/// Removes empty lines from the start and end. Returns `self`.
///
/// Example:
/// ```
/// use magic_string::MagicString;
///
/// let mut s = MagicString::new("\n\nabc\n");
/// s.append("\n");
/// s.prepend("\n");
///
/// s.trim_lines();
///
/// assert_eq!(s.to_string(), "abc")
/// ```
pub fn trim_lines(&mut self) -> Result<&mut Self> {
self.trim_start(Some("\n"))?.trim_end(Some("\n"))
}
/// ## Remove
///
/// Removes the characters from start to end (of the original string, not the generated string).
/// Removing the same content twice, or making removals that partially overlap, will cause an error. Returns `self`.
///
/// Example:
/// ```
/// use magic_string::MagicString;
/// let mut s = MagicString::new("abcdefghijkl");
///
/// s.remove(1, 5);
/// assert_eq!(s.to_string(), "afghijkl");
///
/// s.remove(9, 12);
/// assert_eq!(s.to_string(), "afghi");
///
/// ```
pub fn remove(&mut self, start: i64, end: i64) -> Result<&mut Self> {
let start = normalize_index(self.original_str.as_str(), start)?;
let end = normalize_index(self.original_str.as_str(), end)?;
let start = start as u32;
let end = end as u32;
if start == end {
// according to the original implementation, this is a noop.
return Ok(self);
}
if start > end {
return Err(Error::new_with_reason(
MagicStringErrorType::MagicStringOutOfRangeError,
"Start must be greater than end.",
));
}
self._split_at_index(start)?;
self._split_at_index(end)?;
let start_chunk = self.chunk_by_start.get(&start);
let end_chunk = self.chunk_by_end.get(&end);
if start_chunk.is_some() {
Chunk::try_each_next(start_chunk.map(Rc::clone).unwrap(), |chunk| {
chunk.borrow_mut().content = String::default();
chunk.borrow_mut().intro = String::default();
chunk.borrow_mut().outro = String::default();
Ok(chunk == Rc::clone(end_chunk.unwrap()))
})?;
}
Ok(self)
}
/// ## Is empty
///
/// Returns `true` if the resulting source is empty (disregarding white space).
///
/// Example:
/// ```
/// use magic_string::MagicString;
///
/// let mut s = MagicString::new("");
///
/// assert_eq!(s.is_empty(), true);
///
/// let mut s = MagicString::new("abc");
///
/// assert_eq!(s.is_empty(), false);
/// ```
pub fn is_empty(&self) -> bool {
self.to_string().trim().is_empty()
}
/// ## Length
///
/// Returns the length of the modified string.
pub fn len(&self) -> usize {
self.to_string().len()
}
/// ## Generate decoded map
///
/// Generates a sourcemap object with raw mappings in array form, rather than encoded as a string.
/// See generate_map documentation below for options details.
/// Useful if you need to manipulate the sourcemap further, but most of the time you will use generateMap instead.
///
/// Notice: All decoded mappings are positioned absolutely.
///
/// Example
/// ```
/// use magic_string::{MagicString, GenerateDecodedMapOptions};
///
/// let mut s = MagicString::new("export default React");
/// s.prepend("import React from 'react'\n");
///
/// s.generate_decoded_map(GenerateDecodedMapOptions {
/// file: Some("index.js".to_owned()),
/// source: Some("index.ts".to_owned()),
/// source_root: Some("./".to_owned()),
/// include_content: true,
/// hires: false,
/// });
/// ```
pub fn generate_decoded_map(&self, options: GenerateDecodedMapOptions) -> Result<DecodedMap> {
let mut map = Mapping::new(options.hires);
let locator = &self.original_str_locator;
map.advance(self.intro.as_str());
Chunk::try_each_next(Rc::clone(&self.first_chunk), |chunk| {
let loc = locator.locate(chunk.borrow().start);
map.add_chunk(Rc::clone(&chunk), loc);
Ok(false)
})?;
map.advance(self.outro.as_str());
Ok(DecodedMap {
file: options.file.to_owned(),
mappings: map.get_decoded_mappings(),
source_root: options.source_root.to_owned(),
sources: vec![options.source],
names: Vec::default(),
sources_content: {
if options.include_content {
vec![Some(self.original_str.to_owned())]
} else {
Default::default()
}
},
})
}
/// ## Generate Map
///
/// Generates a version 3 sourcemap. All options are optional, see `GenerateDecodedMapOptions` for detailed document.
///
/// ```
/// use magic_string::{MagicString, GenerateDecodedMapOptions};
///
/// let mut s = MagicString::new("export default React");
/// s.prepend("import React from 'react'\n");
///
/// let generated_map = s.generate_map(GenerateDecodedMapOptions {
/// file: Some("index.js".to_owned()),
/// source: Some("index.ts".to_owned()),
/// source_root: Some("./".to_owned()),
/// include_content: true,
/// hires: true,
/// }).expect("fail to generate map");
///
/// generated_map.to_string(); // generates v3 sourcemap in JSON format
/// generated_map.to_url(); // generates v3 inline sourcemap
/// ```
pub fn generate_map(&self, options: GenerateDecodedMapOptions) -> Result<SourceMap> {
let decoded_map = self.generate_decoded_map(options)?;
SourceMap::new_from_decoded(decoded_map)
}
fn _split_at_index(&mut self, index: u32) -> Result {
if self.chunk_by_end.contains_key(&index) || self.chunk_by_start.contains_key(&index) {
// early bail-out if it's already split
return Ok(());
}
let chunk = Rc::clone(&self.last_searched_chunk);
let search_forward = index > chunk.borrow().start;
let mut curr = Some(chunk);
while let Some(c) = curr {
if c.borrow().contains(index) {
self._split_chunk_at_index(c, index)?;
return Ok(());
} else {
curr = {
if search_forward {
self.chunk_by_start.get(&c.borrow().end).map(Rc::clone)
} else {
self.chunk_by_end.get(&c.borrow().start).map(Rc::clone)
}
}
}
}
Ok(())
}
fn _split_chunk_at_index(&mut self, chunk: Rc<RefCell<Chunk>>, index: u32) -> Result {
// Zero-length edited chunks can be split into different chunks, cause split chunks are the same.
if chunk.borrow().is_content_edited() && !chunk.borrow().content.is_empty() {
return Err(Error::new(
MagicStringErrorType::MagicStringDoubleSplitError,
));
}
let new_chunk = Chunk::split(Rc::clone(&chunk), index);
let new_chunk_original = new_chunk.borrow();
self.chunk_by_end.insert(index, Rc::clone(&chunk));
self.chunk_by_start.insert(index, Rc::clone(&new_chunk));
self
.chunk_by_end
.insert(new_chunk_original.end, Rc::clone(&new_chunk));
if self.last_chunk == chunk {
self.last_chunk = Rc::clone(&new_chunk);
}
self.last_searched_chunk = Rc::clone(&chunk);
Ok(())
}
}
impl ToString for MagicString {
/// ## To string
///
/// Returns a modified string.
///
/// Example:
/// ```
/// use magic_string::MagicString;
///
/// let mut s = MagicString::new("abc");
///
/// assert_eq!(s.to_string(), "abc");
/// ```
fn to_string(&self) -> String {
let mut str = self.intro.to_owned();
Chunk::try_each_next(Rc::clone(&self.first_chunk), |chunk| {
str = format!("{}{}", str, chunk.borrow().to_string());
Ok(false)
})
.unwrap();
format!("{}{}", str, self.outro)
}
}