@@ -28,6 +28,8 @@ import { spliceChangesIntoString, visit } from './utils.js'
28
28
29
29
let base = await loadPlugins ( )
30
30
31
+ const ESCAPE_SEQUENCE_PATTERN = / \\ ( [ ' " \\ n r t b f v 0 - 7 x u U ] ) / g
32
+
31
33
function createParser (
32
34
parserFormat : string ,
33
35
transform : ( ast : any , context : TransformerContext ) => void ,
@@ -505,41 +507,41 @@ function sortStringLiteral(
505
507
removeDuplicates,
506
508
collapseWhitespace,
507
509
} )
510
+
508
511
let didChange = result !== node . value
509
- node . value = result
510
512
511
- // A string literal was escaped if:
512
- // - There are backslashes in the raw value; AND
513
- // - The raw value is not the same as the value (excluding the surrounding quotes)
514
- let wasEscaped = false
513
+ if ( ! didChange ) return false
515
514
516
- if ( node . extra ) {
517
- // JavaScript (StringLiteral)
518
- wasEscaped =
519
- node . extra ?. rawValue . includes ( '\\' ) &&
520
- node . extra ?. raw . slice ( 1 , - 1 ) !== node . value
521
- } else {
522
- // TypeScript (Literal)
523
- wasEscaped =
524
- node . value . includes ( '\\' ) && node . raw . slice ( 1 , - 1 ) !== node . value
525
- }
515
+ node . value = result
526
516
527
- let escaped = wasEscaped ? result . replace ( / \\ / g, '\\\\' ) : result
517
+ // Preserve the original escaping level for the new content
518
+ let raw = node . extra ?. raw ?? node . raw
519
+ let quote = raw [ 0 ]
520
+ let originalRawContent = raw . slice ( 1 , - 1 )
521
+ let originalValue = node . extra ?. rawValue ?? node . value
528
522
529
523
if ( node . extra ) {
524
+ // The original list has ecapes so we ensure that the sorted list also
525
+ // maintains those by replacing backslashes from escape sequences.
526
+ //
527
+ // It seems that TypeScript-based ASTs don't need this special handling
528
+ // which is why this is guarded inside the `node.extra` check
529
+ if ( originalRawContent !== originalValue && originalValue . includes ( '\\' ) ) {
530
+ result = result . replace ( ESCAPE_SEQUENCE_PATTERN , '\\\\$1' )
531
+ }
532
+
530
533
// JavaScript (StringLiteral)
531
- let raw = node . extra . raw
532
534
node . extra = {
533
535
...node . extra ,
534
536
rawValue : result ,
535
- raw : raw [ 0 ] + escaped + raw . slice ( - 1 ) ,
537
+ raw : quote + result + quote ,
536
538
}
537
539
} else {
538
540
// TypeScript (Literal)
539
- let raw = node . raw
540
- node . raw = raw [ 0 ] + escaped + raw . slice ( - 1 )
541
+ node . raw = quote + result + quote
541
542
}
542
- return didChange
543
+
544
+ return true
543
545
}
544
546
545
547
function isStringLiteral ( node : any ) {
0 commit comments