esi 0.7.0-beta.4

A streaming parser and executor for Edge Side Includes
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
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
// Parser tests for ESI parser
// These tests verify that the parser correctly handles ESI tags and produces the expected AST

use bytes::Bytes;
use esi::parse_complete;

#[test]
fn test_parse_basic_include() {
    let input = br#"<html><body><esi:include src="https://example.com/hello"/></body></html>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    // Find the Include tag
    let include_found = elements.iter().any(|element| {
        matches!(element, esi::Element::Esi(
            esi::Tag::Include { attrs, .. }
        ) if matches!(&attrs.src, esi::Expr::String(Some(s)) if s == "https://example.com/hello") 
            && attrs.alt.is_none() 
            && !attrs.continue_on_error 
            && attrs.params.is_empty())
    });

    assert!(
        include_found,
        "Should find Include tag with correct attributes"
    );
}

#[test]
fn test_parse_include_with_alt_and_onerror() {
    let input = br#"<esi:include src="abc" alt="def" onerror="continue"/>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    let include_found = elements.iter().any(|element| {
        matches!(element, esi::Element::Esi(
            esi::Tag::Include { attrs, .. }
        ) if matches!(&attrs.src, esi::Expr::String(Some(s)) if s == "abc")
            && matches!(&attrs.alt, Some(esi::Expr::String(Some(a))) if a == "def")
            && attrs.continue_on_error 
            && attrs.params.is_empty())
    });

    assert!(
        include_found,
        "Should find Include with alt and continue_on_error"
    );
}

#[test]
fn test_parse_open_close_include() {
    let input = br#"<esi:include src="abc" alt="def" onerror="continue"></esi:include>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    let include_found = elements.iter().any(|element| {
        matches!(element, esi::Element::Esi(
            esi::Tag::Include { attrs, .. }
        ) if matches!(&attrs.src, esi::Expr::String(Some(s)) if s == "abc")
            && matches!(&attrs.alt, Some(esi::Expr::String(Some(a))) if a == "def")
            && attrs.continue_on_error
            && attrs.params.is_empty())
    });

    assert!(include_found, "Should parse open-close include tag");
}

#[test]
fn test_parse_include_with_onerror() {
    let input = br#"<esi:include src="/_fragments/content.html" onerror="continue"/>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    let include_found = elements.iter().any(|element| {
        matches!(element, esi::Element::Esi(
            esi::Tag::Include { attrs, .. }
        ) if matches!(&attrs.src, esi::Expr::String(Some(s)) if s == "/_fragments/content.html")
            && attrs.alt.is_none() 
            && attrs.continue_on_error 
            && attrs.params.is_empty())
    });

    assert!(include_found, "Should find Include with onerror=continue");
}

#[test]
fn test_parse_include_with_single_param() {
    let input = br#"<esi:include src="/fragment">
    <esi:param name="foo" value="bar"/>
</esi:include>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    let include_found = elements.iter().any(|element| {
        matches!(element, esi::Element::Esi(
            esi::Tag::Include { attrs, .. }
        ) if matches!(&attrs.src, esi::Expr::String(Some(s)) if s == "/fragment")
            && attrs.alt.is_none() 
            && !attrs.continue_on_error 
            && attrs.params.len() == 1
            && attrs.params[0].0 == "foo"
            && matches!(&attrs.params[0].1, esi::Expr::String(Some(v)) if v == "bar"))
    });

    assert!(include_found, "Should find Include with one param");
}

#[test]
fn test_parse_include_with_multiple_params() {
    let input = br#"<esi:include src="/fragment" alt="/fallback" onerror="continue">
    <esi:param name="user" value="alice"/>
    <esi:param name="role" value="admin"/>
    <esi:param name="id" value="123"/>
</esi:include>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    let include_found = elements.iter().any(|element| {
        matches!(element, esi::Element::Esi(
            esi::Tag::Include { attrs, .. }
        ) if matches!(&attrs.src, esi::Expr::String(Some(s)) if s == "/fragment")
            && matches!(&attrs.alt, Some(esi::Expr::String(Some(a))) if a == "/fallback")
            && attrs.continue_on_error 
            && attrs.params.len() == 3
            && attrs.params[0].0 == "user" && matches!(&attrs.params[0].1, esi::Expr::String(Some(v)) if v == "alice")
            && attrs.params[1].0 == "role" && matches!(&attrs.params[1].1, esi::Expr::String(Some(v)) if v == "admin")
            && attrs.params[2].0 == "id" && matches!(&attrs.params[2].1, esi::Expr::Integer(123)))
    });

    assert!(include_found, "Should find Include with multiple params");
}

#[test]
fn test_parse_include_self_closing_has_no_params() {
    let input = br#"<esi:include src="/test"/>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    let include_found = elements.iter().any(|element| {
        matches!(element, esi::Element::Esi(
            esi::Tag::Include { attrs, .. }
        ) if matches!(&attrs.src, esi::Expr::String(Some(s)) if s == "/test") && attrs.params.is_empty())
    });

    assert!(include_found, "Self-closing include should have no params");
}

#[test]
fn test_parse_include_no_store_attribute() {
    let input = br#"<esi:include src="/test" no-store="on"/>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    let include_found = elements.iter().any(|element| {
        matches!(element, esi::Element::Esi(
            esi::Tag::Include { attrs, .. }
        ) if matches!(&attrs.src, esi::Expr::String(Some(s)) if s == "/test")
            && attrs.no_store)
    });

    assert!(
        include_found,
        "Should parse include with no-store attribute"
    );
}

#[test]
fn test_parse_include_no_store_off_attribute() {
    let input = br#"<esi:include src="/test" no-store="off"/>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    let include_found = elements.iter().any(|element| {
        matches!(element, esi::Element::Esi(
            esi::Tag::Include { attrs, .. }
        ) if matches!(&attrs.src, esi::Expr::String(Some(s)) if s == "/test")
            && !attrs.no_store)
    });

    assert!(
        include_found,
        "Should parse include with no-store=off as cacheable"
    );
}

#[test]
fn test_parse_include_no_store_true_is_not_enabled() {
    let input = br#"<esi:include src="/test" no-store="true"/>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    let include_found = elements.iter().any(|element| {
        matches!(element, esi::Element::Esi(
            esi::Tag::Include { attrs, .. }
        ) if matches!(&attrs.src, esi::Expr::String(Some(s)) if s == "/test")
            && !attrs.no_store)
    });

    assert!(
        include_found,
        "no-store=true should not enable no-store; only on/off are supported"
    );
}

#[test]
fn test_parse_include_numbered_header_attributes() {
    let input = br#"<esi:include src="/frag" setheader1="X-A: one" appendheader2="X-B: two" removeheader1="X-C"/>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    let include_found = elements.iter().any(|element| {
        matches!(element, esi::Element::Esi(
            esi::Tag::Include { attrs, .. }
        ) if attrs.setheaders.len() == 1
            && attrs.appendheaders.len() == 1
            && attrs.removeheaders.len() == 1)
    });

    assert!(
        include_found,
        "Should parse include with numbered set/append/remove header attributes"
    );
}

#[test]
fn test_parse_include_duplicate_setheader_attrs() {
    // ESI spec allows multiple setheader attributes on the same tag:
    //   setheader="a_header: a_value", setheader="b_header: b_value"
    let input = br#"<esi:include src="/frag" setheader="X-A: val_a" setheader="X-B: val_b"/>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    let found = elements.iter().any(|element| {
        matches!(element, esi::Element::Esi(
            esi::Tag::Include { attrs, .. }
        ) if attrs.setheaders.len() == 2)
    });

    assert!(
        found,
        "Both duplicate setheader attributes should be preserved"
    );
}

#[test]
fn test_parse_include_duplicate_appendheader_same_name() {
    // ESI spec allows multiple appendheader attributes with the same header name:
    //   appendheader="a_header: value1", appendheader="a_header: value2"
    let input =
        br#"<esi:include src="/frag" appendheader="X-Multi: value1" appendheader="X-Multi: value2"/>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    let found = elements.iter().any(|element| {
        matches!(element, esi::Element::Esi(
            esi::Tag::Include { attrs, .. }
        ) if attrs.appendheaders.len() == 2)
    });

    assert!(
        found,
        "Both duplicate appendheader attributes with the same header name should be preserved"
    );
}

#[test]
fn test_parse_include_duplicate_removeheader_attrs() {
    // Multiple removeheader attributes on the same tag
    let input = br#"<esi:include src="/frag" removeheader="X-A" removeheader="X-B"/>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    let found = elements.iter().any(|element| {
        matches!(element, esi::Element::Esi(
            esi::Tag::Include { attrs, .. }
        ) if attrs.removeheaders.len() == 2)
    });

    assert!(
        found,
        "Both duplicate removeheader attributes should be preserved"
    );
}

#[test]
fn test_parse_include_appendheader_dynamic_expression() {
    // ESI spec example: header name and value are both dynamic expressions
    //   appendheader="$(a_name) + ':' + $(a_value)"
    let input = br#"<esi:include src="obj.htm" appendheader="$(a_name) + ':' + $(a_value)"/>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    let found = elements.iter().any(|element| {
        matches!(element, esi::Element::Esi(
            esi::Tag::Include { attrs, .. }
        ) if attrs.appendheaders.len() == 1)
    });

    assert!(
        found,
        "appendheader with dynamic expression for name and value should be parsed as a single Expr"
    );
}

#[test]
fn test_parse_include_with_query_string_variable() {
    // Example from Akamai ESI spec
    // Mixed text+variable interpolation is now properly parsed at parse-time
    let input =
        br#"<esi:include src="http://search.akamai.com/search?query=$(QUERY_STRING{'query'})"/>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    // The src is parsed as Interpolated with text and expression parts
    let include_found = elements.iter().any(|element| {
        matches!(element, esi::Element::Esi(
            esi::Tag::Include { attrs, .. }
        ) if matches!(&attrs.src, esi::Expr::Interpolated(_)))
    });

    assert!(include_found, "Should find Include with interpolated src");
}

#[test]
fn test_parse_param_value_with_variable_expression() {
    let input = br#"<esi:assign name="var1" value="'variable_2'"/>
<esi:include src="a.xml">
<esi:param name="foo" value="$(var1)"/>
</esi:include>"#;
    let bytes = Bytes::from_static(input);
    let result = parse_complete(&bytes);

    assert!(
        result.is_ok(),
        "Should parse successfully: {:?}",
        result.err()
    );

    let (remaining, elements) = result.unwrap();
    assert_eq!(remaining, b"");

    // Check what the param value looks like
    let include_found = elements.iter().find_map(|element| {
        if let esi::Element::Esi(esi::Tag::Include { attrs, .. }) = element {
            Some(&attrs.params)
        } else {
            None
        }
    });

    assert!(include_found.is_some(), "Should find include");
    let params = include_found.unwrap();
    assert_eq!(params.len(), 1);
    assert_eq!(params[0].0, "foo");

    // Now the value is parsed as a Variable expression!
    println!("Param value: {:?}", params[0].1);
    assert!(
        matches!(&params[0].1, esi::Expr::Variable(name, _, _) if name == "var1"),
        "Param value should be parsed as a Variable expression"
    );
}

#[test]
fn test_parse_try_with_attempt_and_except() {
    let input = br#"
<esi:try>
    <esi:attempt>
        <esi:include src="/abc"/>
    </esi:attempt>
    <esi:except>
        <esi:include src="/xyz"/>
        <a href="/efg"/>
        just text
    </esi:except>
</esi:try>"#;

    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");
    assert_eq!(remaining, b"");

    // Find the Try tag
    let try_tag_found = elements.iter().any(|element| {
        if let esi::Element::Esi(esi::Tag::Try {
            attempt_events,
            except_events,
        }) = element
        {
            // Check attempt contains include for /abc
            let attempt_has_abc = attempt_events.iter().any(|attempt_elements| {
                attempt_elements.iter().any(|c| {
                    matches!(c, esi::Element::Esi(
                        esi::Tag::Include { attrs, .. }
                    ) if matches!(&attrs.src, esi::Expr::String(Some(s)) if s == "/abc"))
                })
            });

            // Check except contains include for /xyz
            let except_has_xyz = except_events.iter().any(|c| {
                matches!(c, esi::Element::Esi(
                    esi::Tag::Include { attrs, .. }
                ) if matches!(&attrs.src, esi::Expr::String(Some(s)) if s == "/xyz"))
            });

            attempt_has_abc && except_has_xyz
        } else {
            false
        }
    });

    assert!(
        try_tag_found,
        "Should find Try tag with correct attempt and except branches"
    );
}

#[test]
fn test_parse_nested_try() {
    let input = br#"<esi:try>
    <esi:attempt>
        <esi:include src="/abc"/>
        <esi:try>
            <esi:attempt>
                <esi:include src="/foo"/>
            </esi:attempt>
            <esi:except>
                <esi:include src="/bar"/>
            </esi:except>
        </esi:try>
    </esi:attempt>
    <esi:except>
        <esi:include src="/xyz"/>
    </esi:except>
</esi:try>"#;

    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");
    assert_eq!(remaining, b"");

    // Find outer Try tag
    let nested_try_found = elements.iter().any(|element| {
        if let esi::Element::Esi(esi::Tag::Try {
            attempt_events,
            except_events,
        }) = element
        {
            // Check outer attempt contains /abc
            let has_abc = attempt_events.iter().any(|attempt_elements| {
                attempt_elements.iter().any(|c| {
                    matches!(c, esi::Element::Esi(
                        esi::Tag::Include { attrs, .. }
                    ) if matches!(&attrs.src, esi::Expr::String(Some(s)) if s == "/abc"))
                })
            });

            // Check outer attempt contains nested Try
            let has_nested_try = attempt_events.iter().any(|attempt_elements| {
                attempt_elements
                    .iter()
                    .any(|c| matches!(c, esi::Element::Esi(esi::Tag::Try { .. })))
            });

            // Check outer except contains /xyz
            let has_xyz = except_events.iter().any(|c| {
                matches!(c, esi::Element::Esi(
                    esi::Tag::Include { attrs, .. }
                ) if matches!(&attrs.src, esi::Expr::String(Some(s)) if s == "/xyz"))
            });

            has_abc && has_nested_try && has_xyz
        } else {
            false
        }
    });

    assert!(nested_try_found, "Should parse nested try blocks correctly");
}

#[test]
fn test_parse_assign() {
    let input = br#"<esi:assign name="foo" value="bar"/>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    let assign_found = elements.iter().any(|element| {
        if let esi::Element::Esi(esi::Tag::Assign {
            name,
            subscript: _,
            value,
        }) = element
        {
            // Value is now a pre-parsed Expr
            // "bar" (not a valid ESI expression) becomes Expr::String(Some(ref s)) if s == "bar"
            *name == "foo" && matches!(value, esi::Expr::String(Some(ref s)) if s == "bar")
        } else {
            false
        }
    });

    assert!(
        assign_found,
        "Should find Assign tag with value as String expression"
    );
}

#[test]
fn test_parse_assign_short_with_integer() {
    let input = br#"<esi:assign name="count" value="123"/>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    let assign_found = elements.iter().any(|element| {
        if let esi::Element::Esi(esi::Tag::Assign {
            name,
            subscript: _,
            value,
        }) = element
        {
            *name == "count" && *value == esi::Expr::Integer(123)
        } else {
            false
        }
    });

    assert!(assign_found, "Should parse integer value");
}

#[test]
fn test_parse_assign_short_with_variable() {
    let input = br#"<esi:assign name="copy" value="$(HTTP_HOST)"/>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    let assign_found = elements.iter().any(|element| {
        if let esi::Element::Esi(esi::Tag::Assign {
            name,
            subscript: _,
            value,
        }) = element
        {
            *name == "copy"
                && matches!(value, esi::Expr::Variable(ref n, None, None) if n == "HTTP_HOST")
        } else {
            false
        }
    });

    assert!(assign_found, "Should parse variable expression");
}

#[test]
fn test_parse_assign_short_with_quoted_string() {
    let input = br#"<esi:assign name="text" value="'hello world'"/>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    let assign_found = elements.iter().any(|element| {
        if let esi::Element::Esi(esi::Tag::Assign {
            name,
            subscript: _,
            value,
        }) = element
        {
            *name == "text" && matches!(value, esi::Expr::String(Some(ref s)) if s == "hello world")
        } else {
            false
        }
    });

    assert!(assign_found, "Should parse quoted string expression");
}

#[test]
fn test_parse_assign_long_form() {
    let input = br#"<esi:assign name="message">
        'This is a long form assign'
    </esi:assign>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    let assign_found = elements.iter().any(|element| {
        if let esi::Element::Esi(esi::Tag::Assign {
            name,
            subscript: _,
            value,
        }) = element
        {
            *name == "message" && matches!(value, esi::Expr::String(Some(_)))
        } else {
            false
        }
    });

    assert!(assign_found, "Should parse long form assign");
}

#[test]
fn test_parse_assign_long_with_variable() {
    let input = br#"<esi:assign name="host">$(HTTP_HOST)</esi:assign>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    let assign_found = elements.iter().any(|element| {
        if let esi::Element::Esi(esi::Tag::Assign {
            name,
            subscript: _,
            value,
        }) = element
        {
            *name == "host"
                && matches!(value, esi::Expr::Variable(ref n, None, None) if n == "HTTP_HOST")
        } else {
            false
        }
    });

    assert!(assign_found, "Should parse long form with variable");
}

#[test]
fn test_parse_assign_with_function() {
    let input = br#"<esi:assign name="result" value="$url_encode('hello world')"/>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    let assign_found = elements.iter().any(|element| {
        if let esi::Element::Esi(esi::Tag::Assign {
            name,
            subscript: _,
            value,
        }) = element
        {
            *name == "result" && matches!(value, esi::Expr::Call(ref n, _) if n == "url_encode")
        } else {
            false
        }
    });

    assert!(assign_found, "Should parse function call in value");
}

#[test]
fn test_parse_assign_long_with_interpolation() {
    // Test compound expression with mixed text and variable
    let input = br#"<esi:assign name="message">Hello $(name)!</esi:assign>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    let assign_found = elements.iter().any(|element| {
        if let esi::Element::Esi(esi::Tag::Assign {
            name,
            subscript: _,
            value,
        }) = element
        {
            if *name == "message" {
                // Should be an Interpolated expression with multiple elements
                if let esi::Expr::Interpolated(elements) = value {
                    // Should have: "Hello ", $(name), "!"
                    if elements.len() != 3 {
                        return false;
                    }
                    // Check first element is Text("Hello ")
                    let first_ok = if let esi::Element::Content(ref bytes) = elements[0] {
                        &bytes[..] == b"Hello "
                    } else {
                        false
                    };
                    // Check second element is Variable("name", None, None)
                    let second_ok =
                        if let esi::Element::Expr(esi::Expr::Variable(ref n, None, None)) =
                            &elements[1]
                        {
                            n == "name"
                        } else {
                            false
                        };
                    // Check third element is Text("!")
                    let third_ok = if let esi::Element::Content(ref bytes) = elements[2] {
                        &bytes[..] == b"!"
                    } else {
                        false
                    };
                    first_ok && second_ok && third_ok
                } else {
                    false
                }
            } else {
                false
            }
        } else {
            false
        }
    });

    assert!(assign_found, "Should parse long form with interpolation");
}

#[test]
fn test_parse_assign_long_with_multiple_variables() {
    // Test compound expression with multiple variables
    let input = br#"<esi:assign name="full_name">$(first) $(last)</esi:assign>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    let assign_found = elements.iter().any(|element| {
        if let esi::Element::Esi(esi::Tag::Assign {
            name,
            subscript: _,
            value,
        }) = element
        {
            if *name == "full_name" {
                // Should be an Interpolated expression
                matches!(value, esi::Expr::Interpolated(_))
            } else {
                false
            }
        } else {
            false
        }
    });

    assert!(
        assign_found,
        "Should parse long form with multiple variables"
    );
}

#[test]
fn test_parse_vars_short_form() {
    let input = br#"<esi:vars name="$(foo)"/>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    // Short form vars should produce an expression element
    let var_found = elements.iter().any(|element| {
        if let esi::Element::Expr(esi::Expr::Variable(ref n, None, None)) = element {
            n == "foo"
        } else {
            false
        }
    });

    assert!(
        var_found,
        "Should find variable expression from short-form vars"
    );
}

#[test]
fn test_parse_vars_long_form() {
    let input = br#"<esi:vars>$(foo)</esi:vars>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    // Long form vars should produce an expression element
    let var_found = elements.iter().any(|element| {
        if let esi::Element::Expr(esi::Expr::Variable(ref n, None, None)) = element {
            n == "foo"
        } else {
            false
        }
    });

    assert!(
        var_found,
        "Should find variable expression from long-form vars"
    );
}

#[test]
fn test_parse_choose_when_otherwise() {
    let input = br#"
<esi:choose>
    <esi:when test="$(condition)">
        Content when true
    </esi:when>
    <esi:otherwise>
        Content when false
    </esi:otherwise>
</esi:choose>"#;

    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");
    assert_eq!(remaining, b"");

    let choose_found = elements.iter().any(|element| {
        if let esi::Element::Esi(esi::Tag::Choose {
            when_branches,
            otherwise_events,
        }) = element
        {
            let has_when = !when_branches.is_empty();
            let has_otherwise = !otherwise_events.is_empty();

            // Verify the new WhenBranch structure
            if let Some(first_when) = when_branches.first() {
                // Test is now a pre-parsed Expr, so we check it's a Variable expression
                assert!(matches!(first_when.test, esi::Expr::Variable(..)));
                assert!(first_when.match_name.is_none());
                assert!(!first_when.content.is_empty());
            }

            has_when && has_otherwise
        } else {
            false
        }
    });

    assert!(choose_found, "Should parse choose/when/otherwise structure");
}

#[test]
fn test_parse_choose_multiple_when() {
    // Test multiple when branches - only first true one should execute
    let input = br#"
<esi:choose>
    <esi:when test="0">
        First when (false)
    </esi:when>
    <esi:when test="1">
        Second when (true)
    </esi:when>
    <esi:when test="1">
        Third when (also true, but should not execute)
    </esi:when>
    <esi:otherwise>
        Otherwise (should not execute)
    </esi:otherwise>
</esi:choose>"#;

    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");
    assert_eq!(remaining, b"");

    // Verify we have multiple when branches using the new structure
    let choose_found = elements.iter().any(|element| {
        if let esi::Element::Esi(esi::Tag::Choose {
            when_branches,
            otherwise_events,
        }) = element
        {
            // Should have 3 when branches
            assert_eq!(when_branches.len(), 3, "Should have 3 when branches");

            // Verify test expressions are pre-parsed as Integers
            assert_eq!(when_branches[0].test, esi::Expr::Integer(0));
            assert_eq!(when_branches[1].test, esi::Expr::Integer(1));
            assert_eq!(when_branches[2].test, esi::Expr::Integer(1));

            // Should have otherwise content
            assert!(
                !otherwise_events.is_empty(),
                "Should have otherwise content"
            );

            true
        } else {
            false
        }
    });

    assert!(
        choose_found,
        "Should parse choose with multiple when branches"
    );
}

#[test]
fn test_parse_remove() {
    let input =
        br#"<html><esi:remove>This should not appear</esi:remove><body>visible</body></html>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    // esi:remove content should not appear in elements at all
    let has_removed_text = elements.iter().any(|element| {
        if let esi::Element::Content(t) = element {
            // Check if bytes contain the substring
            let needle = b"should not appear";
            t.windows(needle.len()).any(|window| window == needle)
        } else {
            false
        }
    });

    assert!(
        !has_removed_text,
        "Content inside esi:remove should not appear in parsed elements"
    );

    // But visible content should be there
    let has_visible = elements.iter().any(|element| {
        if let esi::Element::Content(t) = element {
            let needle = b"visible";
            t.windows(needle.len()).any(|window| window == needle)
        } else {
            false
        }
    });

    assert!(has_visible, "Content outside esi:remove should be parsed");
}

#[test]
fn test_parse_comment() {
    let input = br#"<html><esi:comment text="This is a comment"/><body>visible</body></html>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    // esi:comment should not produce any elements
    let comment_count = elements
        .iter()
        .filter(|element| matches!(element, esi::Element::Esi(esi::Tag::Vars { .. })))
        .count();

    assert_eq!(comment_count, 0, "Comments should not produce elements");
}

#[test]
fn test_parse_text_tag() {
    let input = br#"<esi:text>This <esi:include src="test"/> should appear as-is</esi:text>"#;
    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");

    assert_eq!(remaining, b"");

    // esi:text content should be plain text, ESI tags inside should not be parsed
    let text_found = elements.iter().any(|element| {
        if let esi::Element::Content(t) = element {
            let needle1 = b"<esi:include";
            let needle2 = b"should appear as-is";
            t.windows(needle1.len()).any(|w| w == needle1)
                && t.windows(needle2.len()).any(|w| w == needle2)
        } else {
            false
        }
    });

    assert!(
        text_found,
        "esi:text content should be treated as plain text"
    );
}

#[test]
fn test_parse_mixed_content() {
    let input = br#"
<html>
    <head><title>Test</title></head>
    <body>
        <esi:vars>Hello $(USER_NAME)</esi:vars>
        <esi:include src="/header"/>
        <p>Some content</p>
        <esi:assign name="foo" value="bar"/>
    </body>
</html>"#;

    let bytes = Bytes::from_static(input);
    let (remaining, elements) = parse_complete(&bytes).expect("should parse");
    assert_eq!(remaining, b"");

    // Should have HTML, expressions, ESI tags, and text
    let has_html = elements.iter().any(|c| matches!(c, esi::Element::Html(_)));
    let has_expr = elements.iter().any(|c| matches!(c, esi::Element::Expr(_)));
    let has_esi = elements.iter().any(|c| matches!(c, esi::Element::Esi(_)));
    let has_text = elements
        .iter()
        .any(|c| matches!(c, esi::Element::Content(_)));

    assert!(has_html, "Should have HTML elements");
    assert!(has_expr, "Should have expression elements");
    assert!(has_esi, "Should have ESI tag elements");
    assert!(has_text, "Should have text elements");
}

#[test]
fn test_parse_include_with_esi_attributes() {
    // Test TTL attribute
    let input = br#"<esi:include src="/fragment" ttl="120m"/>"#;
    let bytes = Bytes::from_static(input);
    let result = parse_complete(&bytes);

    match result {
        Ok((remaining, elements)) => {
            assert_eq!(remaining, b"");
            // Just verify that we got some elements
            assert!(!elements.is_empty(), "Should have parsed some elements");
            // Check that at least one is an Include tag
            let has_include = elements
                .iter()
                .any(|e| matches!(e, esi::Element::Esi(esi::Tag::Include { .. })));
            assert!(has_include, "Should have an Include tag");
        }
        Err(e) => {
            panic!("Failed to parse: {:?}", e);
        }
    }
}