html-minifier 6.0.0

This library minifies streaming HTML, including embedded JavaScript and CSS, while preserving pre and textarea content.
Documentation
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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
use std::mem::take;

use educe::Educe;

use crate::{HTMLMinifierError, HTMLWriter, comment::HeldComment, functions::*};

/// The deepest nesting of template literals that is followed. Deeper code is kept as it is.
const MAX_TEMPLATE_DEPTH: usize = 256;

/// The most content that is held after `<!--` while looking for `<script`.
const MAX_DEFERRED_LENGTH: usize = 256 * 1024;

/// Keywords after which a `/` starts a regular expression.
const REGEX_KEYWORDS: [&[u8]; 16] = [
    b"return",
    b"typeof",
    b"instanceof",
    b"in",
    b"new",
    b"delete",
    b"void",
    b"throw",
    b"case",
    b"do",
    b"else",
    b"debugger",
    b"break",
    b"continue",
    b"default",
    b"extends",
];

#[derive(Educe, Debug, Copy, Clone, Eq, PartialEq)]
#[educe(Default)]
enum JSStep {
    #[educe(Default)]
    Normal,
    Slash,
    LineComment,
    BlockComment,
    KeptBlockComment,
    String,
    Template,
    Regex,
    RegexFlags,
    Unicode,
    /// A comment line that is kept, such as `<!--` in a classic script.
    LineKept,
    Verbatim,
}

/// The kind of the latest token, which decides how a `/` and a line break after it work.
#[derive(Educe, Debug, Copy, Clone, Eq, PartialEq)]
#[educe(Default)]
enum Token {
    #[educe(Default)]
    None,
    /// An identifier or a keyword that a division can follow.
    Word,
    /// A keyword that a regular expression can follow, such as `return`.
    RegexKeyword,
    Number,
    /// A punctuator that continues an expression, such as `=` or `(`.
    Punctuator,
    /// `++` or `--`.
    IncDec,
    /// `)` that a division can follow.
    CloseParen,
    /// `)` of `if`, `while`, `for` or `with`, which a regular expression can follow.
    ControlParen,
    CloseBracket,
    CloseBrace,
    /// A token whose following slash needs more syntax context.
    Ambiguous,
    /// A string or a template literal.
    Literal,
    Regex,
    /// A string or a regular expression that a line break ends, which is an error.
    Unterminated,
}

/// Check whether a byte can be a part of an identifier, a keyword or a number.
#[inline]
const fn is_word_byte(e: u8) -> bool {
    e.is_ascii_alphanumeric() || matches!(e, b'_' | b'$' | b'\\') || e >= 0x80
}

/// Minify the JavaScript content of a `script` element, which arrives in chunks.
/// Only comments and whitespace are removed, and line breaks that can change automatic semicolon insertion stay.
#[derive(Educe, Clone)]
#[educe(Debug, Default)]
pub(crate) struct JSMinifier {
    step:                     JSStep,
    module:                   bool,
    /// The last two written bytes, with the latest one at the end. 0 means nothing.
    last:                     [u8; 2],
    token:                    Token,
    /// Whether the latest punctuator is `.`, which makes the next word a property name.
    after_dot:                bool,
    /// Whether the latest word is `if`, `while`, `for`, `with` or the `await` of `for await`.
    control_word:             bool,
    /// Whether the latest word is `for`.
    after_for:                bool,
    /// Whether whitespace or comments are pending between two tokens.
    gap:                      bool,
    /// Whether the pending gap includes a line break.
    gap_newline:              bool,
    /// Whether only whitespace and comments are after the latest line break.
    line_start:               bool,
    word:                     [u8; 10],
    /// The length of the current word, up to 255.
    word_length:              u8,
    word_after_dot:           bool,
    unicode:                  [u8; 3],
    unicode_length:           u8,
    /// One bit for each open parenthesis, which is set for `if (`, `while (`, `for (` and `with (`.
    parens:                   u64,
    paren_depth:              u32,
    brace_depth:              u32,
    /// The brace depths where template substitutions start.
    templates:                Vec<u32>,
    quote:                    u8,
    escape:                   bool,
    regex_class:              bool,
    template_dollar:          bool,
    comment_star:             bool,
    comment_newline:          bool,
    /// How many bytes of U+2028 or U+2029 have been matched.
    separator:                u8,
    /// How many bytes of `<!--` have been matched as tokens, in a classic script.
    html_open:                u8,
    /// How many bytes of `-->` have been matched as tokens at the start of a line, in a classic script.
    html_close:               u8,
    /// Whether the script starts with `#`, which can start `#!`.
    hashbang:                 bool,
    /// The token state before a comment that is written as tokens, such as `<!--`.
    saved_token:              (Token, bool),
    /// How many bytes of `<!--` have been matched in the input.
    raw_open:                 u8,
    /// How many bytes of `<script` have been matched in the input after `<!--`.
    raw_script:               u8,
    /// Whether `<!--` has been found in the input.
    escaped:                  bool,
    /// Whether the input after `<!--` is being held.
    deferring:                bool,
    /// Whether `<!--` is in a line comment, whose start has been removed.
    deferred_in_line_comment: bool,
    #[educe(Debug(method = "str_bytes_fmt"))]
    deferred:                 Vec<u8>,
    comment:                  HeldComment,
}

impl JSMinifier {
    /// Prepare for a new script.
    #[inline]
    pub(crate) fn reset(&mut self, module: bool) {
        let mut templates = take(&mut self.templates);
        let mut deferred = take(&mut self.deferred);
        let comment = take(&mut self.comment);

        templates.clear();
        deferred.clear();

        *self = Self {
            module,
            line_start: true,
            templates,
            deferred,
            comment,
            ..Self::default()
        };
    }

    #[inline]
    fn wrote(&mut self, e: u8) {
        self.last = [self.last[1], e];
    }

    /// Check whether the latest written token and a token starting with `next` become different tokens without a space between them.
    fn merges(&self, next: u8) -> bool {
        let [before, last] = self.last;

        (is_word_byte(last) && is_word_byte(next))
            || (self.token == Token::Regex && is_word_byte(next))
            || (self.token == Token::Number && next == b'.')
            || (matches!(last, b'+' | b'-' | b'/') && next == last)
            || (last == b'/' && next == b'*')
            // `</`, `<!--` and `<script` affect where browsers end a `script` element.
            || (last == b'<' && matches!(next, b'!' | b'/' | b's' | b'S'))
            || (before == b'<' && last == b'!' && next == b'-')
            || (before == b'-' && last == b'-' && next == b'>')
    }

    /// Check whether a line break between the latest token and a token starting with `next` can be removed without changing automatic semicolon insertion.
    fn removes_newline(&self, next: u8) -> bool {
        // The line break ends an unterminated string or regular expression, and a line starting with `-->` is a comment in a classic script.
        if self.token == Token::Unterminated || (!self.module && next == b'-') {
            return false;
        }

        self.token == Token::Punctuator
            || matches!(
                next,
                b')' | b']'
                    | b'}'
                    | b','
                    | b';'
                    | b':'
                    | b'?'
                    | b'='
                    | b'%'
                    | b'<'
                    | b'>'
                    | b'&'
                    | b'|'
                    | b'^'
            )
    }

    /// Write what replaces the pending whitespace and comments before a token starting with `next`.
    fn write_gap(&mut self, next: u8, out: &mut impl HTMLWriter) -> Result<(), HTMLMinifierError> {
        // Nothing is needed at the start of the script.
        if self.last[1] != 0 {
            if self.gap_newline && !self.removes_newline(next) {
                out.push(b'\n')?;
                self.wrote(b'\n');
            } else if self.merges(next) {
                out.push(b' ')?;
                self.wrote(b' ');
            }
        }

        self.gap = false;
        self.gap_newline = false;

        Ok(())
    }

    /// Write the pending gap before a comment that is kept.
    fn write_comment_gap(&mut self, out: &mut impl HTMLWriter) -> Result<(), HTMLMinifierError> {
        // The next token is not known yet, so a pending line break always stays.
        if self.gap && self.last[1] != 0 {
            if self.gap_newline {
                out.push(b'\n')?;
                self.wrote(b'\n');
            } else if self.merges(b'/') {
                out.push(b' ')?;
                self.wrote(b' ');
            }
        }

        self.gap = false;
        self.gap_newline = false;

        Ok(())
    }

    /// Write the held comment, which has to be kept.
    fn keep_comment(&mut self, out: &mut impl HTMLWriter) -> Result<(), HTMLMinifierError> {
        self.write_comment_gap(out)?;

        let held = self.comment.as_bytes();
        out.push_bytes(held)?;
        self.last = [held[held.len() - 2], held[held.len() - 1]];

        self.step = JSStep::KeptBlockComment;

        Ok(())
    }

    /// Check whether a byte completes U+2028 or U+2029, which are line breaks.
    #[inline]
    fn completes_separator(&mut self, e: u8) -> bool {
        self.separator = match (self.separator, e) {
            (_, 0xE2) => 1,
            (1, 0x80) => 2,
            (2, 0xA8 | 0xA9) => {
                self.separator = 0;

                return true;
            },
            _ => 0,
        };

        false
    }

    #[inline]
    fn regex_allowed(&self) -> Option<bool> {
        // A line break can end a statement by ASI, such as `var x` or `import "a"`, and then a regular expression can follow.
        let after_statement = self.line_start
            && (self.token == Token::Word || (self.module && self.token == Token::Literal));

        if matches!(self.token, Token::CloseBrace | Token::Ambiguous) || after_statement {
            return None;
        }

        Some(matches!(
            self.token,
            Token::None | Token::Punctuator | Token::RegexKeyword | Token::ControlParen
        ))
    }

    /// Decide the kind of the current word, which has ended.
    fn end_word(&mut self) {
        if self.word_length == 0 {
            return;
        }

        let keyword: &[u8] = if self.word_length <= 10 && !self.word_after_dot {
            &self.word[..usize::from(self.word_length)]
        } else {
            &[]
        };

        self.token = if self.word[0].is_ascii_digit() {
            Token::Number
        } else if matches!(keyword, b"of" | b"yield" | b"await") {
            Token::Ambiguous
        } else if REGEX_KEYWORDS.contains(&keyword) {
            Token::RegexKeyword
        } else {
            Token::Word
        };
        self.control_word = matches!(keyword, b"if" | b"while" | b"for" | b"with")
            || (keyword == b"await" && self.after_for);
        self.after_for = keyword == b"for";
        self.word_length = 0;
    }

    #[inline]
    fn word_byte(&mut self, e: u8, out: &mut impl HTMLWriter) -> Result<(), HTMLMinifierError> {
        if self.word_length == 0 {
            if self.gap {
                self.write_gap(e, out)?;
            }

            self.word_after_dot = self.after_dot;
            self.after_dot = false;
            self.word[0] = e;
        } else if self.word_length < 10 {
            self.word[usize::from(self.word_length)] = e;
        }

        self.word_length = self.word_length.saturating_add(1);
        self.wrote(e);
        self.line_start = false;
        self.html_open = 0;
        self.html_close = 0;
        self.hashbang = false;
        Ok(())
    }

    /// Keep a held prefix that is not Unicode whitespace.
    fn write_unicode(&mut self, out: &mut impl HTMLWriter) -> Result<(), HTMLMinifierError> {
        let bytes = self.unicode;
        let length = usize::from(self.unicode_length);

        for &e in &bytes[..length] {
            self.word_byte(e, out)?;
        }
        out.push_bytes(&bytes[..length])?;
        self.unicode_length = 0;
        self.step = JSStep::Normal;
        Ok(())
    }

    /// Check the next byte of a possible Unicode space or line break.
    fn unicode_whitespace(&self, e: u8) -> bool {
        match (self.unicode[0], self.unicode_length) {
            (0xC2, 1) => e == 0xA0,
            (0xE1, 1) => e == 0x9A,
            (0xE2, 1) => matches!(e, 0x80 | 0x81),
            (0xE3, 1) => e == 0x80,
            (0xEF, 1) => e == 0xBB,
            (0xE1 | 0xE3, 2) => e == 0x80,
            (0xE2, 2) if self.unicode[1] == 0x80 => matches!(e, 0x80..=0x8A | 0xA8 | 0xA9 | 0xAF),
            (0xE2, 2) => e == 0x9F,
            (0xEF, 2) => e == 0xBF,
            _ => false,
        }
    }

    /// Find `#!` at the start, and `<!--` and `-->` at the start of a line in a classic script.
    /// They start comment lines that are kept.
    fn starts_line_comment(&mut self, e: u8, adjacent: bool, first: bool) -> bool {
        let saved = (self.token, self.after_dot);

        if self.hashbang {
            self.hashbang = false;

            if adjacent && e == b'!' {
                return true;
            }
        }

        if first && e == b'#' {
            self.saved_token = saved;
            self.hashbang = true;

            return false;
        }

        if self.module {
            return false;
        }

        self.html_open = match (self.html_open, e) {
            (_, b'<') => {
                self.saved_token = saved;
                1
            },
            (1, b'!') if adjacent => 2,
            (2, b'-') if adjacent => 3,
            (3, b'-') if adjacent => 4,
            _ => 0,
        };

        self.html_close = match (self.html_close, e) {
            (0, b'-') if self.line_start => {
                self.saved_token = saved;
                1
            },
            (1, b'-') if adjacent => 2,
            (2, b'>') if adjacent => 3,
            _ => 0,
        };

        if self.html_open == 4 || self.html_close == 3 {
            self.html_open = 0;
            self.html_close = 0;

            true
        } else {
            false
        }
    }

    #[inline]
    fn push_paren(&mut self, control: bool) {
        if self.paren_depth < 64 {
            let bit = 1 << self.paren_depth;

            self.parens = if control { self.parens | bit } else { self.parens & !bit };
        }

        self.paren_depth = self.paren_depth.saturating_add(1);
    }

    #[inline]
    fn pop_paren(&mut self) -> Option<bool> {
        if self.paren_depth == 0 {
            return Some(false);
        }

        self.paren_depth -= 1;

        (self.paren_depth < 64).then(|| self.parens & (1 << self.paren_depth) != 0)
    }

    /// Track a punctuator, which has been written.
    fn punctuator(&mut self, e: u8, adjacent: bool) {
        let control = self.control_word;

        self.control_word = false;
        self.after_for = false;
        self.after_dot = matches!(e, b'.' | b'#');

        self.token = match e {
            b'"' | b'\'' => {
                self.quote = e;
                self.escape = false;
                self.step = JSStep::String;

                return;
            },
            b'`' => {
                self.escape = false;
                self.template_dollar = false;
                self.step = JSStep::Template;

                return;
            },
            b'(' => {
                self.push_paren(control);

                Token::Punctuator
            },
            b')' => match self.pop_paren() {
                Some(true) => Token::ControlParen,
                Some(false) => Token::CloseParen,
                None => Token::Ambiguous,
            },
            b']' => Token::CloseBracket,
            b'.' if self.token == Token::Number => Token::Ambiguous,
            b'{' => {
                self.brace_depth = self.brace_depth.saturating_add(1);

                Token::Punctuator
            },
            b'}' => {
                if self.templates.last() == Some(&self.brace_depth) {
                    // The substitution of a template literal ends.
                    self.templates.pop();
                    self.escape = false;
                    self.template_dollar = false;
                    self.step = JSStep::Template;

                    return;
                }

                self.brace_depth = self.brace_depth.saturating_sub(1);

                Token::CloseBrace
            },
            b'+' | b'-' if adjacent && self.last[0] == e => Token::IncDec,
            _ => Token::Punctuator,
        };
    }

    /// Input a chunk of JavaScript.
    pub(crate) fn feed(
        &mut self,
        bytes: &[u8],
        out: &mut impl HTMLWriter,
    ) -> Result<(), HTMLMinifierError> {
        if self.step == JSStep::Verbatim {
            return out.push_bytes(bytes);
        }

        if self.deferring {
            return self.defer(bytes, out);
        }

        // The start of the bytes that are written as they are.
        let mut run = 0;
        let mut p = 0;

        while p < bytes.len() {
            let e = bytes[p];

            match self.step {
                JSStep::Normal => {
                    if is_whitespace(e) || e == b'/' {
                        if run < p {
                            out.push_bytes(&bytes[run..p])?;
                        }

                        run = p + 1;
                        self.end_word();
                        self.html_open = 0;
                        self.html_close = 0;
                        self.hashbang = false;

                        if e == b'/' {
                            self.step = JSStep::Slash;
                        } else {
                            self.gap = true;

                            if matches!(e, b'\n' | b'\r') {
                                self.gap_newline = true;
                                self.line_start = true;
                            }
                        }
                    } else if matches!(e, 0xC2 | 0xE1..=0xE3 | 0xEF) {
                        if run < p {
                            out.push_bytes(&bytes[run..p])?;
                        }
                        run = p + 1;
                        self.unicode[0] = e;
                        self.unicode_length = 1;
                        self.step = JSStep::Unicode;
                    } else if is_word_byte(e) {
                        self.word_byte(e, out)?;
                    } else {
                        self.end_word();

                        let adjacent = !self.gap;
                        let first = self.last[1] == 0 && !self.gap;

                        if self.gap {
                            self.write_gap(e, out)?;
                        }

                        self.wrote(e);

                        if self.starts_line_comment(e, adjacent, first) {
                            // The comment is not a token, so the token state before it comes back.
                            (self.token, self.after_dot) = self.saved_token;
                            self.separator = 0;
                            self.step = JSStep::LineKept;
                        } else {
                            self.punctuator(e, adjacent);
                        }

                        self.line_start = false;
                    }
                },
                JSStep::Slash => match e {
                    b'/' => {
                        run = p + 1;
                        self.gap = true;
                        self.separator = 0;
                        self.step = JSStep::LineComment;
                    },
                    b'*' => {
                        run = p + 1;
                        self.gap = true;
                        self.comment.start();
                        self.comment_star = false;
                        self.comment_newline = false;
                        self.separator = 0;
                        self.step = JSStep::BlockComment;
                    },
                    _ => {
                        // The `/` is a division or the start of a regular expression.
                        let Some(regex) = self.regex_allowed() else {
                            // Keep the rest when a slash needs syntax context that is not tracked.
                            self.write_comment_gap(out)?;
                            out.push(b'/')?;
                            self.step = JSStep::Verbatim;
                            return out.push_bytes(&bytes[p..]);
                        };

                        if self.gap {
                            self.write_gap(b'/', out)?;
                        }

                        out.push(b'/')?;
                        self.wrote(b'/');
                        self.line_start = false;
                        self.control_word = false;
                        self.after_for = false;
                        self.after_dot = false;

                        if regex {
                            self.escape = false;
                            self.regex_class = false;
                            self.step = JSStep::Regex;
                        } else {
                            self.token = Token::Punctuator;
                            self.step = JSStep::Normal;
                        }

                        continue;
                    },
                },
                JSStep::LineComment => {
                    run = p + 1;

                    if matches!(e, b'\n' | b'\r') {
                        // The line break is a part of the gap.
                        self.step = JSStep::Normal;

                        continue;
                    }

                    if self.completes_separator(e) {
                        self.gap_newline = true;
                        self.line_start = true;
                        self.step = JSStep::Normal;
                    }
                },
                JSStep::BlockComment => {
                    run = p + 1;

                    if self.comment_star && e == b'/' {
                        // The comment is removed, and a comment with a line break works as a line break.
                        if self.comment_newline {
                            self.gap_newline = true;
                            self.line_start = true;
                        }

                        self.step = JSStep::Normal;
                    } else {
                        if matches!(e, b'\n' | b'\r') || self.completes_separator(e) {
                            self.comment_newline = true;
                        }

                        if self.comment.push(e) {
                            self.keep_comment(out)?;
                        }
                    }

                    self.comment_star = e == b'*';
                },
                JSStep::KeptBlockComment => {
                    self.wrote(e);

                    if self.comment_star && e == b'/' {
                        // The token before the comment stays the latest token.
                        self.line_start |= self.comment_newline;
                        self.step = JSStep::Normal;
                    } else if matches!(e, b'\n' | b'\r') || self.completes_separator(e) {
                        self.comment_newline = true;
                    }

                    self.comment_star = e == b'*';
                },
                JSStep::String => {
                    if !self.escape && matches!(e, b'\n' | b'\r') {
                        // An unterminated string stays as it is.
                        self.token = Token::Unterminated;
                        self.step = JSStep::Normal;

                        continue;
                    }

                    self.wrote(e);

                    if self.escape {
                        self.escape = false;
                    } else if e == b'\\' {
                        self.escape = true;
                    } else if e == self.quote {
                        self.token = Token::Literal;
                        self.step = JSStep::Normal;
                    }
                },
                JSStep::Template => {
                    let escaped = self.escape;

                    self.wrote(e);
                    self.escape = !escaped && e == b'\\';

                    if !escaped {
                        if e == b'`' {
                            self.token = Token::Literal;
                            self.step = JSStep::Normal;
                        } else if self.template_dollar && e == b'{' {
                            if self.templates.len() >= MAX_TEMPLATE_DEPTH {
                                // Such deep nesting is kept as it is.
                                self.step = JSStep::Verbatim;
                            } else {
                                self.templates.push(self.brace_depth);
                                self.token = Token::Punctuator;
                                self.step = JSStep::Normal;
                            }
                        }
                    }

                    self.template_dollar = !escaped && e == b'$';
                },
                JSStep::Regex => {
                    if matches!(e, b'\n' | b'\r') {
                        // An unterminated regular expression stays as it is.
                        self.token = Token::Unterminated;
                        self.step = JSStep::Normal;

                        continue;
                    }

                    self.wrote(e);

                    if self.escape {
                        self.escape = false;
                    } else if e == b'\\' {
                        self.escape = true;
                    } else if self.regex_class {
                        self.regex_class = e != b']';
                    } else if e == b'[' {
                        self.regex_class = true;
                    } else if e == b'/' {
                        self.step = JSStep::RegexFlags;
                    }
                },
                JSStep::RegexFlags => {
                    if is_word_byte(e) && e < 0x80 {
                        self.wrote(e);
                    } else {
                        self.token = Token::Regex;
                        self.step = JSStep::Normal;

                        continue;
                    }
                },
                JSStep::Unicode => {
                    if !self.unicode_whitespace(e) {
                        self.write_unicode(out)?;
                        run = p;
                        continue;
                    }

                    self.unicode[usize::from(self.unicode_length)] = e;
                    self.unicode_length += 1;
                    run = p + 1;

                    if self.unicode[0] == 0xC2 || self.unicode_length == 3 {
                        let newline = self.unicode[0] == 0xE2
                            && self.unicode[1] == 0x80
                            && matches!(e, 0xA8 | 0xA9);
                        self.end_word();
                        self.gap = true;
                        self.gap_newline |= newline;
                        self.line_start |= newline;
                        self.html_open = 0;
                        self.html_close = 0;
                        self.hashbang = false;
                        self.unicode_length = 0;
                        self.step = JSStep::Normal;
                    }
                },
                JSStep::LineKept => {
                    self.wrote(e);

                    if matches!(e, b'\n' | b'\r') || self.completes_separator(e) {
                        // The line break after the comment is written as it is.
                        self.line_start = true;
                        self.step = JSStep::Normal;
                    }
                },
                JSStep::Verbatim => (),
            }

            if !self.escaped && self.step != JSStep::Verbatim {
                self.raw_open = match (self.raw_open, e) {
                    (_, b'<') => 1,
                    (1, b'!') => 2,
                    (2, b'-') => 3,
                    (3, b'-') => 4,
                    _ => 0,
                };

                if self.raw_open == 4 {
                    // `<!--` can change how browsers end the `script` element.
                    self.escaped = true;

                    if self.step == JSStep::BlockComment {
                        self.keep_comment(out)?;
                    }

                    if run <= p {
                        out.push_bytes(&bytes[run..=p])?;
                    }

                    self.deferring = true;
                    self.deferred_in_line_comment = self.step == JSStep::LineComment;

                    return self.defer(&bytes[p + 1..], out);
                }
            }

            p += 1;
        }

        if run < bytes.len() {
            out.push_bytes(&bytes[run..])?;
        }

        Ok(())
    }

    /// Hold the input after `<!--` until it is clear whether `<script` follows.
    fn defer(&mut self, bytes: &[u8], out: &mut impl HTMLWriter) -> Result<(), HTMLMinifierError> {
        let length = bytes.len().min(MAX_DEFERRED_LENGTH + 1 - self.deferred.len());

        for (p, &e) in bytes[..length].iter().enumerate() {
            let e = e.to_ascii_lowercase();

            self.raw_script = match self.raw_script {
                _ if e == b'<' => 1,
                n @ 1..=6 if e == b"<script"[usize::from(n)] => n + 1,
                _ => 0,
            };

            if self.raw_script == 7 {
                // After `<!--`, `<script` can make browsers ignore the next `</script>`, so everything from `<!--` is kept.
                self.deferred.extend_from_slice(&bytes[..=p]);
                self.write_deferred(out)?;

                return out.push_bytes(&bytes[p + 1..]);
            }
        }

        self.deferred.extend_from_slice(&bytes[..length]);

        if self.deferred.len() > MAX_DEFERRED_LENGTH {
            self.write_deferred(out)?;
            return out.push_bytes(&bytes[length..]);
        }

        Ok(())
    }

    /// Write the held input as it is, and keep the rest of the script as it is.
    fn write_deferred(&mut self, out: &mut impl HTMLWriter) -> Result<(), HTMLMinifierError> {
        if self.deferred_in_line_comment {
            // The start of the line comment has been removed, so the comment starts again.
            self.write_comment_gap(out)?;
            out.push_bytes(b"//<!--")?;
        }

        out.push_bytes(&self.deferred)?;
        self.deferred.clear();
        self.deferring = false;
        self.step = JSStep::Verbatim;

        Ok(())
    }

    /// Write the rest of the minified JavaScript.
    pub(crate) fn finish(&mut self, out: &mut impl HTMLWriter) -> Result<(), HTMLMinifierError> {
        if self.deferring {
            // `<script` does not follow `<!--`, so the held input is minified as usual.
            self.deferring = false;

            let deferred = take(&mut self.deferred);

            self.feed(&deferred, out)?;
            self.deferred = deferred;
        }

        match self.step {
            JSStep::Unicode => self.write_unicode(out)?,
            JSStep::Slash => {
                // A `/` at the end is a division or an unterminated regular expression.
                if self.gap {
                    self.write_gap(b'/', out)?;
                }

                out.push(b'/')?;
            },
            JSStep::BlockComment => {
                // An unterminated comment is a syntax error, so it is kept to keep the error.
                self.keep_comment(out)?;
            },
            _ => (),
        }

        // Whitespace at the end is removed.
        self.reset(self.module);

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::{JSMinifier, MAX_DEFERRED_LENGTH};

    #[test]
    fn large_chunks_keep_deferred_memory_bounded() {
        let mut input = b"<!--\n".to_vec();
        input.resize(MAX_DEFERRED_LENGTH * 4, b' ');

        for chunk_size in [input.len(), 4096] {
            let mut minifier = JSMinifier::default();
            minifier.reset(false);
            let mut out = Vec::new();

            for chunk in input.chunks(chunk_size) {
                minifier.feed(chunk, &mut out).unwrap();
            }
            minifier.finish(&mut out).unwrap();

            assert_eq!(input, out);
            assert!(minifier.deferred.capacity() <= 2 * (MAX_DEFERRED_LENGTH + 1));
        }
    }
}