dezoomify-rs 2.18.1

Allows downloading zoomable images. Supports several different formats such as zoomify, iiif, and deep zoom images.
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
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
use std::collections::HashSet;
use std::sync::{Arc, LazyLock};

use custom_error::custom_error;
use itertools::Itertools;
use log::debug;
use log::warn;
use regex::Regex;

use krpano_metadata::{KrpanoMetadata, TemplateString, TemplateStringPart, XY};

use crate::dezoomer::{
    Dezoomer, DezoomerError, DezoomerInput, DezoomerInputWithContents, Images, IntoZoomLevels,
    PageContents, ResolvedImage, TileReference, TilesRect, Vec2d, ZoomLevels,
};
use crate::krpano::krpano_metadata::{ImageInfo, LevelDesc};
use crate::network::resolve_relative;
use krpano_decrypt::{decrypt_xml, is_encrypted_xml};

#[cfg(test)]
use crate::dezoomer::test_utils::{expect_only, expect_resolved_images, expect_single_resolved};

mod krpano_metadata;

/// A dezoomer for krpano images
/// See <https://krpano.com/docu/xml/#top>
#[derive(Default)]
pub struct KrpanoDezoomer {
    /// State machine for the `NeedsData` resolution chain.
    state: ResolveState,
}

/// Where we are in the HTML → JS → XML → (decrypt JS) resolution chain.
#[derive(Default)]
enum ResolveState {
    #[default]
    None,
    /// XML has been requested (from HTML or viewer-JS entry points).
    /// Carries the viewer JS (if any) so it can be reused if the XML is
    /// encrypted, plus remaining JS candidates to try on decrypt failure.
    NeedXml {
        xml_uri: String,
        viewer_js: Vec<u8>,
        remaining_js_uris: Vec<String>,
    },
    /// Encrypted XML is pending; need the viewer JS to decrypt it.
    /// (Used when the entry point is XML directly, not HTML.)
    NeedJsToDecrypt {
        xml_uri: String,
        xml_contents: Vec<u8>,
        remaining_js_uris: Vec<String>,
    },
}

impl Dezoomer for KrpanoDezoomer {
    fn name(&self) -> &'static str {
        "krpano"
    }

    fn images(&mut self, data: &DezoomerInput) -> Result<Images, DezoomerError> {
        self.handle_input(data, |uri, contents| {
            Ok(load_images_from_properties(uri, contents)?.into())
        })
    }
}

impl KrpanoDezoomer {
    /// Navigate the HTML → JS → XML → (decrypt if encrypted) resolution chain.
    fn handle_input<T>(
        &mut self,
        data: &DezoomerInput,
        parse: impl FnOnce(&str, &[u8]) -> Result<T, DezoomerError>,
    ) -> Result<T, DezoomerError> {
        if let Some(error) = self.handle_failed_js_download(data) {
            return Err(error);
        }

        let DezoomerInputWithContents { uri, contents } = data.with_contents()?;
        debug!(
            "krpano handle_input: uri={uri}, content_len={}",
            contents.len()
        );

        match std::mem::take(&mut self.state) {
            ResolveState::None => self.handle_initial_contents(uri, contents, parse),
            ResolveState::NeedXml {
                xml_uri,
                viewer_js,
                remaining_js_uris,
            } => self.handle_requested_xml(contents, xml_uri, &viewer_js, remaining_js_uris, parse),
            ResolveState::NeedJsToDecrypt {
                xml_uri,
                xml_contents,
                remaining_js_uris,
            } => self.handle_viewer_js(contents, xml_uri, xml_contents, remaining_js_uris, parse),
        }
    }

    fn handle_failed_js_download(&mut self, data: &DezoomerInput) -> Option<DezoomerError> {
        if !matches!(self.state, ResolveState::NeedJsToDecrypt { .. })
            || !matches!(
                data.contents,
                PageContents::Error(_) | PageContents::Unknown
            )
        {
            return None;
        }

        let ResolveState::NeedJsToDecrypt {
            xml_uri,
            xml_contents,
            mut remaining_js_uris,
        } = std::mem::take(&mut self.state)
        else {
            unreachable!();
        };
        if let Some(next_js_uri) = next_js_candidate(&mut remaining_js_uris) {
            debug!(
                "krpano: viewer JS download failed for {}; trying next JS candidate {next_js_uri}",
                data.uri
            );
            self.state = ResolveState::NeedJsToDecrypt {
                xml_uri,
                xml_contents,
                remaining_js_uris,
            };
            Some(DezoomerError::NeedsData { uri: next_js_uri })
        } else {
            Some(DezoomerError::DownloadError {
                msg: format!("failed to download viewer JS from {}", data.uri),
            })
        }
    }

    fn handle_requested_xml<T>(
        &mut self,
        contents: &[u8],
        xml_uri: String,
        viewer_js: &[u8],
        mut remaining_js_uris: Vec<String>,
        parse: impl FnOnce(&str, &[u8]) -> Result<T, DezoomerError>,
    ) -> Result<T, DezoomerError> {
        debug!(
            "krpano state=NeedXml → got content ({} bytes), xml_uri={xml_uri}",
            contents.len()
        );

        if !is_encrypted_xml(contents) {
            debug!("krpano: XML is plain, parsing directly");
            return parse(&xml_uri, contents);
        }

        let decrypt_result = if viewer_js.is_empty() {
            debug!("krpano: XML is encrypted, trying decryption without viewer JS");
            decrypt_xml(contents, None)
        } else {
            debug!(
                "krpano: XML is encrypted, decrypting with saved viewer JS ({} bytes)",
                viewer_js.len()
            );
            decrypt_xml(contents, Some(viewer_js))
        };
        match decrypt_result {
            Ok(decrypted) => {
                debug!("krpano: decrypted XML = {} bytes", decrypted.len());
                parse(&xml_uri, &decrypted)
            }
            Err(error) => {
                let Some(next_js_uri) = next_js_candidate(&mut remaining_js_uris) else {
                    return Err(error.into());
                };
                debug!("krpano: decrypt failed: {error}; trying next JS candidate {next_js_uri}");
                self.state = ResolveState::NeedJsToDecrypt {
                    xml_uri,
                    xml_contents: contents.to_vec(),
                    remaining_js_uris,
                };
                Err(DezoomerError::NeedsData { uri: next_js_uri })
            }
        }
    }

    fn handle_viewer_js<T>(
        &mut self,
        contents: &[u8],
        xml_uri: String,
        xml_contents: Vec<u8>,
        mut remaining_js_uris: Vec<String>,
        parse: impl FnOnce(&str, &[u8]) -> Result<T, DezoomerError>,
    ) -> Result<T, DezoomerError> {
        debug!(
            "krpano state=NeedJsToDecrypt → got potential viewer JS ({} bytes)",
            contents.len()
        );

        let viewer_js = extract_viewer_js(contents).unwrap_or_else(|| contents.to_vec());
        match decrypt_xml(&xml_contents, Some(&viewer_js)) {
            Ok(decrypted) => {
                debug!("krpano: decrypted XML = {} bytes", decrypted.len());
                parse(&xml_uri, &decrypted)
            }
            Err(error) => {
                let Some(next_js_uri) = next_js_candidate(&mut remaining_js_uris) else {
                    return Err(error.into());
                };
                debug!(
                    "krpano: decrypt failed with candidate JS: {error}; trying next JS candidate {next_js_uri}"
                );
                self.state = ResolveState::NeedJsToDecrypt {
                    xml_uri,
                    xml_contents,
                    remaining_js_uris,
                };
                Err(DezoomerError::NeedsData { uri: next_js_uri })
            }
        }
    }

    fn handle_initial_contents<T>(
        &mut self,
        uri: &str,
        contents: &[u8],
        parse: impl FnOnce(&str, &[u8]) -> Result<T, DezoomerError>,
    ) -> Result<T, DezoomerError> {
        // If the content is a krpano XML file, skip HTML/JS detection and go
        // straight to encrypted/plain XML handling.  XML files may contain
        // <script> or embedpano() in comments or data blocks, which would
        // otherwise trigger false HTML detection.
        if !looks_like_krpano_xml(contents) && looks_like_viewer_js(contents) {
            let xml_uri = sibling_uri(uri, "tour.xml");
            debug!(
                "krpano: content looks like viewer JS ({} bytes), requesting XML: {xml_uri}",
                contents.len()
            );
            // Store the viewer JS so it can be used to decrypt the XML if it
            // turns out to be encrypted.
            self.state = ResolveState::NeedXml {
                xml_uri: xml_uri.clone(),
                viewer_js: contents.to_vec(),
                remaining_js_uris: Vec::new(),
            };
            return Err(DezoomerError::NeedsData { uri: xml_uri });
        }

        if !looks_like_krpano_xml(contents) && looks_like_krpano_html(contents) {
            debug!("krpano: content looks like HTML ({} bytes)", contents.len());
            let html = String::from_utf8_lossy(contents);
            let js_uris = extract_js_candidates_from_html(&html, uri);
            let xml_uri = extract_xml_from_embedpano(&html).map_or_else(
                || sibling_uri(uri, "tour.xml"),
                |rel| resolve_relative(uri, &rel),
            );

            // Request the XML first.  For plain-XML pages this avoids fetching
            // the viewer JS at all; for encrypted pages the JS candidates are
            // tried only after encryption is detected.
            debug!("krpano HTML: js_uris={js_uris:?}, xml_uri={xml_uri}");
            self.state = ResolveState::NeedXml {
                xml_uri: xml_uri.clone(),
                viewer_js: Vec::new(),
                remaining_js_uris: js_uris,
            };
            return Err(DezoomerError::NeedsData { uri: xml_uri });
        }

        if is_encrypted_xml(contents) {
            // Try decrypting without the viewer JS first — works for public
            // ClassicZ / ClassicB payloads whose default keys are known.
            // This avoids an unnecessary network round trip for the JS file.
            if let Ok(decrypted) = decrypt_xml(contents, None) {
                debug!(
                    "krpano: encrypted XML decrypted without viewer JS ({} bytes)",
                    decrypted.len()
                );
                return parse(uri, &decrypted);
            }

            // Needs the viewer JS to extract the wrapper key and engine.
            // Derive JS candidate URIs from the XML filename, with
            // tour.js and krpano.js as fallbacks.
            let mut js_uris = viewer_js_candidates_for_xml(uri);
            let js_uri =
                next_js_candidate(&mut js_uris).unwrap_or_else(|| sibling_uri(uri, "tour.js"));
            debug!("krpano: encrypted XML needs viewer JS, requesting: {js_uri}");
            self.state = ResolveState::NeedJsToDecrypt {
                xml_uri: uri.to_string(),
                xml_contents: contents.to_vec(),
                remaining_js_uris: js_uris,
            };
            return Err(DezoomerError::NeedsData { uri: js_uri });
        }

        // Plain (non-encrypted) krpano XML — parse directly.
        debug!(
            "krpano: trying to parse as plain XML ({} bytes)",
            contents.len()
        );
        parse(uri, contents)
    }
}

/// True if the content looks like a krpano XML file rather than HTML.
///
/// Detects an XML prolog (`<?xml`) or a `<krpano` root element.  This prevents
/// XML files that contain `<script>` or `embedpano()` in comments or data
/// blocks from being misclassified as HTML.
fn looks_like_krpano_xml(contents: &[u8]) -> bool {
    // Strip optional UTF-8 BOM, then leading whitespace.
    let contents = contents.strip_prefix(b"\xef\xbb\xbf").unwrap_or(contents);
    let text = String::from_utf8_lossy(contents);
    let trimmed = text.trim_start();
    if trimmed.starts_with("<?xml") {
        return true;
    }
    trimmed.to_ascii_lowercase().starts_with("<krpano")
}

/// True if the content looks like a krpano HTML page.
///
/// Requires krpano-specific evidence (an `embedpano` call, a
/// `createPanoViewer` call, or a `<script>` reference to a krpano viewer)
/// so that generic HTML pages from other dezoomers are not claimed in
/// auto mode.  All checks are case-insensitive.
fn looks_like_krpano_html(contents: &[u8]) -> bool {
    let text = String::from_utf8_lossy(contents);
    let lower = text.to_ascii_lowercase();
    // Strongest signal: the krpano embedding API is called.
    if lower.contains("embedpano(") || lower.contains("createpanoviewer(") {
        return true;
    }
    // Weaker signal: a <script> tag referencing a krpano viewer file.
    // This avoids claiming arbitrary HTML pages that merely contain <script>.
    lower.contains("<script") && (lower.contains("krpano") || lower.contains("tour.js"))
}

/// True if the content looks like a krpano viewer JavaScript file.
///
/// Krpano viewer JS files have a UTF-8 BOM followed by either:
/// - A `/* krpano ... */` comment header (krpano 1.16+), or
/// - `function createPanoViewer(` / `function embedpano(` (very old versions).
fn looks_like_viewer_js(contents: &[u8]) -> bool {
    // Strip optional UTF-8 BOM.
    let contents = if contents.starts_with(b"\xef\xbb\xbf") {
        &contents[3..]
    } else {
        contents
    };

    // Modern krpano viewer JS (1.16+) starts with "/* krpano ... */" comment.
    // Require "krpano" within the first 512 bytes to avoid false positives
    // from unrelated JS files that happen to start with a comment.
    if contents.starts_with(b"/*") {
        let window = &contents[..contents.len().min(512)];
        return window.windows(6).any(|w| w == b"krpano");
    }

    // Very old krpano viewer JS starts with "function ".
    // Look for known viewer entry points or "krpano" in the first 8 KB to avoid
    // false positives on random JS files that start with "function ".
    if contents.starts_with(b"function ") {
        let window = &contents[..contents.len().min(8192)];
        return window.windows(6).any(|w| w == b"krpano")
            || window.windows(9).any(|w| w == b"embedpano")
            || window.windows(16).any(|w| w == b"createPanoViewer");
    }

    false
}

/// Try to extract viewer JS candidates from an HTML page.
///
/// The candidates are ranked so krpano viewer filenames (`tour.js`,
/// `krpano.js`, `*krpano*.js`) come before common library or analytics
/// scripts.  Less likely scripts are retained as fallbacks for encrypted XML
/// pages whose actual viewer has a non-standard filename.
fn extract_js_candidates_from_html(html: &str, html_uri: &str) -> Vec<String> {
    debug!(
        "extract_js_from_html: scanning {} bytes of HTML",
        html.len()
    );

    let mut candidates = Vec::new();
    let mut seen = HashSet::new();

    for (index, tag) in SCRIPT_TAG_RE.find_iter(html).enumerate() {
        let tag = tag.as_str();
        let Some(src) = extract_src_attr(tag) else {
            continue;
        };
        if !is_javascript_src(&src) {
            debug!("extract_js_from_html: skipping non-JS src: {src}");
            continue;
        }

        let resolved = resolve_relative(html_uri, &src);
        if seen.insert(resolved.clone()) {
            let score = viewer_script_score(&src);
            debug!("extract_js_from_html: candidate {src} → {resolved}, score={score}");
            candidates.push(ScriptCandidate {
                uri: resolved,
                score,
                index,
            });
        }
    }

    candidates.sort_by(|a, b| b.score.cmp(&a.score).then_with(|| a.index.cmp(&b.index)));
    let uris = candidates
        .into_iter()
        .map(|candidate| candidate.uri)
        .collect::<Vec<_>>();

    if !uris.is_empty() {
        debug!("extract_js_from_html: ranked candidates={uris:?}");
        return uris;
    }

    debug!("extract_js_from_html: no <script src> found");
    Vec::new()
}

/// Extract the XML URL from an `embedpano({xml:"..."})` or
/// `createPanoViewer({xml:"..."})` call in an HTML page.
///
/// Tolerates whitespace around the `xml:` separator (e.g. `xml : "..."`) and
/// whitespace between the closing `}` and `)` (e.g. pretty-printed `}\n);`).
/// The embedding call name is matched case-insensitively.
fn extract_xml_from_embedpano(html: &str) -> Option<String> {
    // Case-insensitive search for the embedding call.
    let lower = html.to_ascii_lowercase();
    let start = lower
        .find("embedpano(")
        .or_else(|| lower.find("createpanoviewer("))?;
    debug!("extract_xml_from_embedpano: found embed call at offset {start}");
    let body = &html[start..];
    let end = EMBEDPANO_END_RE.find(body)?;
    let params = &body[..end.end()];
    let caps = EMBEDPANO_XML_RE.captures(params)?;
    let xml = &caps[1];
    debug!("extract_xml_from_embedpano: found xml={xml:?}");
    Some(xml.to_string())
}

/// Extract the `src` attribute value from a <script> tag.
fn extract_src_attr(line: &str) -> Option<String> {
    let captures = SCRIPT_SRC_RE.captures(line)?;
    captures
        .get(1)
        .or_else(|| captures.get(2))
        .or_else(|| captures.get(3))
        .map(|capture| capture.as_str().to_string())
}

/// Extract viewer JS from a data block — the content might be the JS itself,
/// or an HTML wrapper.  Returns the JS bytes if found.
fn extract_viewer_js(contents: &[u8]) -> Option<Vec<u8>> {
    if looks_like_viewer_js(contents) {
        return Some(contents.to_vec());
    }
    // If wrapped in HTML, look for inline <script> blocks.
    let text = String::from_utf8_lossy(contents);
    if let Some(start) = text.find("<script>") {
        let body = &text[start + 8..];
        if let Some(end) = body.find("</script>") {
            let js = body[..end].trim();
            if looks_like_viewer_js(js.as_bytes()) {
                return Some(js.as_bytes().to_vec());
            }
        }
    }
    None
}

/// Build a list of candidate viewer JS URIs for an encrypted XML file.
///
/// The primary candidate is derived from the XML filename (e.g. `map_core.xml`
/// → `map_core.js`), with `tour.js` and `krpano.js` as fallbacks.
fn viewer_js_candidates_for_xml(xml_uri: &str) -> Vec<String> {
    // Strip query/fragment so cache-busting params don't corrupt the stem.
    let path = xml_uri.split_once(['?', '#']).map_or(xml_uri, |(p, _)| p);
    let xml_stem = path
        .rsplit(['/', '\\'])
        .next()
        .and_then(|name| name.rsplit_once('.').map(|(stem, _)| stem))
        .filter(|stem| !stem.is_empty())
        .unwrap_or("tour");
    let mut candidates = vec![sibling_uri(xml_uri, &format!("{xml_stem}.js"))];
    // Add common fallbacks, avoiding duplicates.
    for fallback in ["tour.js", "krpano.js"] {
        let uri = sibling_uri(xml_uri, fallback);
        if !candidates.contains(&uri) {
            candidates.push(uri);
        }
    }
    candidates
}

/// Replace the last path component of `uri` with `filename`.
///
/// Handles both `/` (URLs, Unix paths) and `\` (Windows paths) as separators.
/// For URLs with a scheme (`https://`), separators inside the `://` authority
/// prefix are skipped so that bare-origin URLs like `https://example.com`
/// resolve to `https://example.com/filename` rather than `https://filename`.
/// Query strings and fragments in the URI are stripped.
fn sibling_uri(uri: &str, filename: &str) -> String {
    // Strip query/fragment so they don't interfere with path resolution.
    let uri = uri.split_once(['?', '#']).map_or(uri, |(path, _)| path);
    // Find the start of the path (after the "://" scheme prefix if present).
    let scheme_end = uri.find("://").map(|i| i + 3);
    let search_start = scheme_end.unwrap_or(0);
    let after_scheme = &uri[search_start..];
    match after_scheme.rfind(['/', '\\']) {
        Some(rel_idx) => {
            let idx = search_start + rel_idx;
            format!("{}{}{filename}", &uri[..idx], &uri[idx..=idx])
        }
        None => {
            if scheme_end.is_some() {
                // URL with no path after the authority: append "/filename".
                format!("{uri}/{filename}")
            } else {
                // Local path with no separator: just the filename.
                filename.to_string()
            }
        }
    }
}

#[derive(Debug)]
struct ScriptCandidate {
    uri: String,
    score: i32,
    index: usize,
}

static SCRIPT_TAG_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?is)<script\b[^>]*>").unwrap());

static SCRIPT_SRC_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"(?is)(?:^|[\s<])src\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))"#).unwrap()
});

/// Matches the end of an `embedpano({...})` call, tolerating whitespace
/// between `}` and `)` (e.g. pretty-printed `}\n);`).
static EMBEDPANO_END_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\}\s*\)").unwrap());

/// Matches the `xml` key inside an embedpano options object, tolerating
/// whitespace around the colon and optional quotes around the key.
static EMBEDPANO_XML_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#"(?i)\bxml["']?\s*:\s*["']([^"']+)["']"#).unwrap());

fn is_javascript_src(src: &str) -> bool {
    let without_query = src.split_once(['?', '#']).map_or(src, |(path, _)| path);
    let filename = without_query.rsplit(['/', '\\']).next().unwrap_or_default();
    filename
        .rsplit_once('.')
        .is_some_and(|(_, extension)| extension.eq_ignore_ascii_case("js"))
}

fn viewer_script_score(src: &str) -> i32 {
    let lower = src.to_ascii_lowercase();
    let path = lower
        .split_once(['?', '#'])
        .map_or(lower.as_str(), |(path, _)| path);
    let filename = path.rsplit(['/', '\\']).next().unwrap_or(path);
    let mut score = 0;

    if filename == "tour.js" {
        score += 1_000;
    } else if filename == "krpano.js" {
        score += 950;
    } else {
        if filename.contains("krpano") {
            score += 850;
        }
        if filename.contains("pano") {
            score += 450;
        }
        if filename.contains("tour") {
            score += 400;
        }
        if filename.contains("viewer") {
            score += 250;
        }
    }

    if is_common_non_viewer_script(filename) || is_common_non_viewer_script(path) {
        score -= 1_000;
    }

    score
}

fn is_common_non_viewer_script(value: &str) -> bool {
    [
        "jquery",
        "analytics",
        "gtag",
        "googletagmanager",
        "matomo",
        "piwik",
        "bootstrap",
        "modernizr",
        "polyfill",
        "underscore",
        "lodash",
        "react",
        "vue",
        "angular",
        "runtime",
        "vendor",
    ]
    .iter()
    .any(|needle| value.contains(needle))
}

fn next_js_candidate(js_uris: &mut Vec<String>) -> Option<String> {
    if js_uris.is_empty() {
        None
    } else {
        Some(js_uris.remove(0))
    }
}

custom_error! {pub KrpanoError
    XmlError{source: serde_xml_rs::Error} = "Unable to parse the krpano xml file: {source}",
}

impl From<krpano_decrypt::KrpanoDecryptError> for DezoomerError {
    fn from(err: krpano_decrypt::KrpanoDecryptError) -> Self {
        DezoomerError::Other { source: err.into() }
    }
}

impl From<KrpanoError> for DezoomerError {
    fn from(err: KrpanoError) -> Self {
        DezoomerError::Other { source: err.into() }
    }
}

fn load_images_from_properties(
    url: &str,
    contents: &[u8],
) -> Result<Vec<ResolvedImage>, DezoomerError> {
    let decrypted;
    let contents = if is_encrypted_xml(contents) {
        decrypted = decrypt_xml(contents, None)?;
        decrypted.as_slice()
    } else {
        contents
    };
    let image_properties = KrpanoMetadata::from_reader(contents).map_err(KrpanoError::from)?;
    let base_url = Arc::from(url);
    let global_title = image_properties.get_title().unwrap_or("").to_string();

    let images = image_properties
        .into_image_iter()
        .map(|ImageInfo { image, name }| {
            let root_tile_size = image.tilesize.map(Vec2d::square);
            let base_index = image.baseindex;
            let base_url = Arc::clone(&base_url);
            let global_title_for_levels = Arc::from(global_title.as_str());
            let name_for_levels = Arc::clone(&name);

            let levels: ZoomLevels = image
                .into_levels()
                .enumerate()
                .flat_map(move |(level_index, level)| {
                    let name = Arc::clone(&name_for_levels);
                    let base_url = Arc::clone(&base_url);
                    let global_title = Arc::clone(&global_title_for_levels);
                    level
                        .level_descriptions(None, level_index)
                        .into_iter()
                        .flat_map(move |level_desc| {
                            let name = Arc::clone(&name);
                            let base_url = Arc::clone(&base_url);
                            let global_title = Arc::clone(&global_title);
                            level_desc
                                .map_err(|err| warn!("bad krpano level: {err}"))
                                .into_iter()
                                .flat_map(
                                    move |LevelDesc {
                                              name: shape_name,
                                              size,
                                              tilesize,
                                              url,
                                              level_index,
                                          }| {
                                        let level = level_index + base_index as usize;
                                        let name = Arc::clone(&name);
                                        let base_url = Arc::clone(&base_url);
                                        let global_title = Arc::clone(&global_title);
                                        url.all_sides(level).filter_map(
                                            move |(side_name, template)| {
                                                let base_url = Arc::clone(&base_url);
                                                let name = Arc::clone(&name);
                                                let global_title = Arc::clone(&global_title);
                                                tilesize.or(root_tile_size).map(|tile_size| Level {
                                                    base_url,
                                                    size,
                                                    tile_size,
                                                    base_index,
                                                    template,
                                                    shape_name,
                                                    side_name,
                                                    name: Arc::clone(&name),
                                                    title: Arc::clone(&global_title),
                                                })
                                            },
                                        )
                                    },
                                )
                        })
                })
                .into_zoom_levels();

            let image_title = if name.is_empty() && global_title.is_empty() {
                None
            } else {
                let title = [global_title.as_str(), name.as_ref()]
                    .iter()
                    .filter(|s| !s.is_empty())
                    .copied()
                    .collect::<Vec<_>>()
                    .join(" ");
                Some(title)
            };

            ResolvedImage::new(levels, image_title)
        })
        .collect::<Vec<_>>();

    Ok(images)
}

#[derive(PartialEq, Eq)]
struct Level {
    base_url: Arc<str>,
    size: Vec2d,
    tile_size: Vec2d,
    base_index: u32,
    template: TemplateString<XY>,
    shape_name: &'static str,
    side_name: &'static str,
    name: Arc<str>,
    title: Arc<str>,
}

impl TilesRect for Level {
    fn size(&self) -> Vec2d {
        self.size
    }

    fn tile_size(&self) -> Vec2d {
        self.tile_size
    }

    fn tile_url(&self, Vec2d { x, y }: Vec2d) -> String {
        use std::fmt::Write;
        let mut result = String::new();
        for part in &self.template.0 {
            match part {
                TemplateStringPart::Literal(s) => result += s,
                TemplateStringPart::Variable { padding, variable } => {
                    write!(
                        result,
                        "{value:0padding$}",
                        value = self.base_index
                            + match variable {
                                XY::X => x,
                                XY::Y => y,
                            },
                        padding = *padding
                    )
                    .unwrap();
                }
            }
        }
        resolve_relative(&self.base_url, &result)
    }

    fn title(&self) -> Option<String> {
        if self.title.is_empty() && self.name.is_empty() {
            None
        } else {
            let title = [self.title.as_ref(), self.name.as_ref()].join(" ");
            Some(title)
        }
    }

    fn tile_ref(&self, pos: Vec2d) -> TileReference {
        TileReference {
            url: self.tile_url(pos),
            position: self.tile_size() * pos,
        }
    }
}

impl std::fmt::Debug for Level {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let parts = ["Krpano", self.shape_name, self.side_name, &self.name];
        write!(f, "{}", parts.iter().filter(|s| !s.is_empty()).join(" "))
    }
}

#[test]
fn test_cube() {
    let image = expect_only(load_images_from_properties(
        "http://test.com",
        r#"<krpano showerrors="false" logkey="false">
        <image type="cube" multires="true" tilesize="512" progressive="false" multiresthreshold="-0.3">
            <level download="view" decode="view" tiledimagewidth="1000" tiledimageheight="100">
                <cube url="http://example.com/%s/%r/%c.jpg"/>
            </level>
        </image>
        </krpano>"#.as_bytes(),
    ).unwrap());
    let mut levels = image.into_zoom_levels();
    assert_eq!(levels.len(), 6);
    assert_eq!(levels[0].size_hint(), Some(Vec2d { x: 1000, y: 100 }));
    assert_eq!(format!("{:?}", levels[0]), "Krpano Cube forward");
    assert_eq!(
        levels[0].next_tiles(None),
        vec![
            TileReference {
                url: "http://example.com/f/1/1.jpg".to_string(),
                position: Vec2d { x: 0, y: 0 }
            },
            TileReference {
                url: "http://example.com/f/1/2.jpg".to_string(),
                position: Vec2d { x: 512, y: 0 }
            }
        ]
    );
}

#[test]
fn test_flat_multires() {
    let image = expect_only(
        load_images_from_properties(
            "http://test.com",
            r#"<krpano>
        <image>
            <flat url="level=%l x=%0x y=%0y" multires="1,2x3,3x4x3"/>
        </image>
        </krpano>"#
                .as_bytes(),
        )
        .unwrap(),
    );
    let mut levels = image.into_zoom_levels();
    assert_eq!(levels.len(), 2);
    assert_eq!(levels[1].size_hint(), Some(Vec2d { x: 3, y: 4 }));
    assert_eq!(format!("{:?}", levels[0]), "Krpano Flat");
    assert_eq!(
        levels[1].next_tiles(None),
        vec![
            TileReference {
                url: "http://test.com/level=2%20x=01%20y=01".to_string(),
                position: Vec2d { x: 0, y: 0 }
            },
            TileReference {
                url: "http://test.com/level=2%20x=01%20y=02".to_string(),
                position: Vec2d { x: 0, y: 3 }
            }
        ]
    );
}

#[cfg(test)]
const BELLEGAMBE_XML_URL: &str =
    "https://pba.lille.fr/gigapixels/Gigapixelweb/gigapixels_1515_bellegambe/gigapixels.xml";

#[cfg(test)]
fn assert_bellegambe_levels(levels: &ZoomLevels) {
    let expected_sizes = [
        Vec2d { x: 512, y: 342 },
        Vec2d { x: 768, y: 514 },
        Vec2d { x: 1536, y: 1026 },
        Vec2d { x: 3072, y: 2052 },
        Vec2d { x: 5888, y: 3930 },
        Vec2d { x: 11904, y: 7946 },
        Vec2d { x: 23808, y: 15892 },
        Vec2d { x: 47616, y: 31782 },
        Vec2d { x: 94976, y: 63392 },
    ];
    assert_eq!(levels.len(), expected_sizes.len());
    assert_eq!(
        levels
            .iter()
            .map(|level| level.size_hint())
            .collect::<Vec<_>>(),
        expected_sizes.into_iter().map(Some).collect::<Vec<_>>()
    );

    let selected_level = &levels[7];
    assert_eq!(selected_level.tile_count_hint(), Some(5859));
    assert_eq!(
        selected_level
            .http_headers()
            .get("Referer")
            .map(String::as_str),
        Some(
            "https://pba.lille.fr/gigapixels/Gigapixelweb/gigapixels_1515_bellegambe/gigapixels.tiles/l8/001/l8_001_001.jpg"
        )
    );
}

#[test]
fn explicit_levels_expand_level_placeholder() {
    let data = std::fs::read("testdata/krpano/pba_lille_gigapixels_1515_bellegambe.xml").unwrap();
    let image = expect_only(load_images_from_properties(BELLEGAMBE_XML_URL, &data).unwrap());
    let levels = image.into_zoom_levels();
    assert_bellegambe_levels(&levels);
}

#[test]
fn explicit_levels_expand_level_placeholder_in_image() {
    let data = std::fs::read("testdata/krpano/pba_lille_gigapixels_1515_bellegambe.xml").unwrap();
    let input = DezoomerInput {
        uri: BELLEGAMBE_XML_URL.to_string(),
        contents: PageContents::Success(data),
    };
    let image = expect_single_resolved(KrpanoDezoomer::default().images(&input).unwrap());
    let levels = image.into_zoom_levels();
    assert_bellegambe_levels(&levels);
}

#[test]
fn test_single_image() {
    let mut dezoomer = KrpanoDezoomer::default();
    let data = r#"<krpano>
        <image>
            <flat url="level=%l x=%0x y=%0y" multires="1,2x3,3x4x3"/>
        </image>
        </krpano>"#
        .as_bytes();

    let input = DezoomerInput {
        uri: "http://test.com".to_string(),
        contents: PageContents::Success(data.to_vec()),
    };

    let image = expect_single_resolved(dezoomer.images(&input).unwrap());
    assert_eq!(image.title(), None);
    assert_eq!(image.levels().len(), 2);
}

#[test]
fn test_cube_faces_form_one_image() {
    let mut dezoomer = KrpanoDezoomer::default();
    let data = r#"<krpano showerrors="false" logkey="false">
        <image type="cube" multires="true" tilesize="512" progressive="false" multiresthreshold="-0.3">
            <level download="view" decode="view" tiledimagewidth="1000" tiledimageheight="100">
                <cube url="http://example.com/%s/%r/%c.jpg"/>
            </level>
        </image>
        </krpano>"#.as_bytes();

    let input = DezoomerInput {
        uri: "http://test.com".to_string(),
        contents: PageContents::Success(data.to_vec()),
    };

    let image = expect_single_resolved(dezoomer.images(&input).unwrap());
    assert_eq!(image.title(), None);
    assert_eq!(image.levels().len(), 6);
}

#[test]
fn test_multiple_scenes_remain_separate() {
    let mut dezoomer = KrpanoDezoomer::default();
    let data = std::fs::read("testdata/krpano/krpano_scenes.xml").unwrap();

    let input = DezoomerInput {
        uri: "http://test.com/scenes.xml".to_string(),
        contents: PageContents::Success(data),
    };

    let images = expect_resolved_images(dezoomer.images(&input).unwrap());
    let titles = images.iter().map(ResolvedImage::title).collect::<Vec<_>>();
    assert_eq!(
        titles,
        [
            Some(
                " Saint Thomas (1618 - 1620) - Diego Velazquez - Museum of Fine Arts, Orleans ( France) scene_Color"
            ),
            Some(
                " Saint Thomas (1618 - 1620) - Diego Velazquez - Museum of Fine Arts, Orleans ( France) scene_3D"
            ),
            Some(
                " Saint Thomas (1618 - 1620) - Diego Velazquez - Museum of Fine Arts, Orleans ( France) scene_3Dcolor"
            ),
        ]
    );
}

#[test]
fn encrypted_xml_decrypted_without_js() {
    // Public ClassicB (KENCPUBR) can be decrypted without viewer JS.
    // This fixture has only the encrypted XML + expected plaintext (no JS).
    let xml = std::fs::read("testdata/krpano/encrypted/2013-08-09-B/tour.xml").unwrap();
    let expected = std::fs::read_to_string("testdata/krpano/encrypted/2013-08-09-B/plaintext.xml")
        .unwrap()
        .replace("\r\n", "\n"); // the decrypted XML may have CRLF line endings on Windows

    let plaintext_bytes = krpano_decrypt::decrypt_xml(&xml, None).unwrap();
    let plaintext = std::str::from_utf8(&plaintext_bytes).unwrap();
    assert_eq!(
        plaintext, expected,
        "decrypted plaintext does not match expected plaintext.xml"
    );
}

#[test]
fn html_script_candidates_prefer_krpano_viewer() {
    let html = r#"
        <html>
            <head>
                <script src="/assets/jquery.min.js"></script>
                <script src='https://www.googletagmanager.com/gtag/js?id=G-TEST'></script>
                <script data-src="ignored.js" src = "assets/tour.js?cache=1"></script>
            </head>
        </html>
    "#;

    let candidates = extract_js_candidates_from_html(html, "http://example.com/pano/index.html");
    assert_eq!(
        candidates.first().map(String::as_str),
        Some("http://example.com/pano/assets/tour.js?cache=1")
    );
}

#[test]
fn sibling_uri_handles_url_and_local_paths() {
    // HTTP URL: last segment replaced, separator preserved.
    assert_eq!(
        sibling_uri("http://example.com/pano/tour.js", "tour.xml"),
        "http://example.com/pano/tour.xml"
    );
    // Trailing-slash URL keeps the slash.
    assert_eq!(
        sibling_uri("http://example.com/pano/", "tour.xml"),
        "http://example.com/pano/tour.xml"
    );
    // Unix local path.
    assert_eq!(
        sibling_uri("/home/user/tour.js", "tour.xml"),
        "/home/user/tour.xml"
    );
    // Windows local path uses backslash separator.
    assert_eq!(
        sibling_uri("C:\\foo\\bar\\tour.js", "tour.xml"),
        "C:\\foo\\bar\\tour.xml"
    );
    // UNC path.
    assert_eq!(
        sibling_uri("\\\\server\\share\\tour.js", "tour.xml"),
        "\\\\server\\share\\tour.xml"
    );
    // No separator: just the filename.
    assert_eq!(sibling_uri("tour.js", "tour.xml"), "tour.xml");
    // Bare-origin URL (no path after authority): append "/filename".
    assert_eq!(
        sibling_uri("https://example.com", "tour.xml"),
        "https://example.com/tour.xml"
    );
    assert_eq!(
        sibling_uri("http://example.com", "tour.js"),
        "http://example.com/tour.js"
    );
    // Bare-origin URL with query/fragment: strip query before appending.
    assert_eq!(
        sibling_uri("https://example.com?scene=1", "tour.xml"),
        "https://example.com/tour.xml"
    );
    assert_eq!(
        sibling_uri("https://example.com#section", "tour.xml"),
        "https://example.com/tour.xml"
    );
    // URL with path and query: strip query, replace last segment.
    assert_eq!(
        sibling_uri("https://example.com/pano/tour.js?cache=1", "tour.xml"),
        "https://example.com/pano/tour.xml"
    );
}

#[test]
fn viewer_js_candidates_derived_from_xml_filename() {
    // Custom XML name → derived JS first, then fallbacks.
    assert_eq!(
        viewer_js_candidates_for_xml("https://example.com/panos/map_core.xml"),
        vec![
            "https://example.com/panos/map_core.js".to_string(),
            "https://example.com/panos/tour.js".to_string(),
            "https://example.com/panos/krpano.js".to_string(),
        ]
    );
    // tour.xml → tour.js first, then krpano.js (no duplicate).
    assert_eq!(
        viewer_js_candidates_for_xml("https://example.com/tour.xml"),
        vec![
            "https://example.com/tour.js".to_string(),
            "https://example.com/krpano.js".to_string(),
        ]
    );
    // Query/fragment stripped before deriving the stem.
    assert_eq!(
        viewer_js_candidates_for_xml("https://example.com/panos/map_core.xml?v=1.2"),
        vec![
            "https://example.com/panos/map_core.js".to_string(),
            "https://example.com/panos/tour.js".to_string(),
            "https://example.com/panos/krpano.js".to_string(),
        ]
    );
}

#[test]
fn extract_xml_from_embedpano_tolerates_whitespace() {
    // Whitespace before the colon: `xml : "..."`.
    let html = r#"<script>embedpano({ xml : "panos/tour.xml", target:"pano" });</script>"#;
    assert_eq!(
        extract_xml_from_embedpano(html),
        Some("panos/tour.xml".to_string())
    );

    // Pretty-printed ending: `}\n);` with whitespace between } and ).
    let html = r#"
        embedpano({
            xml: "panos/tour.xml"
        }
        );
    "#;
    assert_eq!(
        extract_xml_from_embedpano(html),
        Some("panos/tour.xml".to_string())
    );

    // Quoted key: `"xml": "..."`.
    let html = r#"embedpano({ "xml": "panos/tour.xml" });"#;
    assert_eq!(
        extract_xml_from_embedpano(html),
        Some("panos/tour.xml".to_string())
    );

    // Older createPanoViewer API.
    let html = r#"<script>createPanoViewer({ xml: "panos/tour.xml" });</script>"#;
    assert_eq!(
        extract_xml_from_embedpano(html),
        Some("panos/tour.xml".to_string())
    );

    // Case-insensitive embedding call lookup.
    let html = r#"<script>EMBEDPANO({ xml: "panos/tour.xml" });</script>"#;
    assert_eq!(
        extract_xml_from_embedpano(html),
        Some("panos/tour.xml".to_string())
    );
    let html = r#"<script>CreatePanoViewer({ xml: "panos/tour.xml" });</script>"#;
    assert_eq!(
        extract_xml_from_embedpano(html),
        Some("panos/tour.xml".to_string())
    );
}

#[test]
fn looks_like_krpano_xml_detects_xml_roots() {
    // XML prolog.
    assert!(looks_like_krpano_xml(
        b"<?xml version=\"1.0\"?><krpano></krpano>"
    ));
    // Direct <krpano> root.
    assert!(looks_like_krpano_xml(b"<krpano><image></image></krpano>"));
    // BOM + XML prolog.
    assert!(looks_like_krpano_xml(
        b"\xef\xbb\xbf<?xml version=\"1.0\"?><krpano/>"
    ));
    // XML with <script> inside should still be detected as XML, not HTML.
    assert!(looks_like_krpano_xml(
        b"<?xml version=\"1.0\"?><krpano><action><![CDATA[embedpano();]]></action></krpano>"
    ));
    // HTML is not XML.
    assert!(!looks_like_krpano_xml(b"<html><body></body></html>"));
    // Viewer JS is not XML.
    assert!(!looks_like_krpano_xml(b"/* krpano */ function() {}"));
}

#[test]
fn viewer_js_is_detected_before_html_embed_markers() {
    let mut dezoomer = KrpanoDezoomer::default();
    let viewer_js = b"function embedpano(opts) { /* krpano viewer */ }";
    let data = DezoomerInput {
        uri: "https://example.com/krpano.js".to_string(),
        contents: PageContents::Success(viewer_js.to_vec()),
    };

    let err = dezoomer.images(&data).unwrap_err();

    assert!(matches!(
        err,
        DezoomerError::NeedsData { ref uri } if uri == "https://example.com/tour.xml"
    ));
    assert!(matches!(
        dezoomer.state,
        ResolveState::NeedXml { ref viewer_js, ref remaining_js_uris, .. }
            if viewer_js == b"function embedpano(opts) { /* krpano viewer */ }"
                && remaining_js_uris.is_empty()
    ));
}

#[test]
fn old_create_pano_viewer_js_is_detected_as_viewer_js() {
    let mut dezoomer = KrpanoDezoomer::default();
    let viewer_js = b"function createPanoViewer(opts) { return buildViewer(opts); }";
    let data = DezoomerInput {
        uri: "https://example.com/viewer.js".to_string(),
        contents: PageContents::Success(viewer_js.to_vec()),
    };

    let err = dezoomer.images(&data).unwrap_err();

    assert!(matches!(
        err,
        DezoomerError::NeedsData { ref uri } if uri == "https://example.com/tour.xml"
    ));
    assert!(matches!(
        dezoomer.state,
        ResolveState::NeedXml { ref viewer_js, ref remaining_js_uris, .. }
            if viewer_js == b"function createPanoViewer(opts) { return buildViewer(opts); }"
                && remaining_js_uris.is_empty()
    ));
}

#[test]
fn looks_like_krpano_html_requires_krpano_evidence() {
    // embedpano call — strongest signal.
    assert!(looks_like_krpano_html(
        b"<html><script>embedpano({xml:'tour.xml'})</script></html>"
    ));
    // Uppercase tags + embedpano (case-insensitive).
    assert!(looks_like_krpano_html(
        b"<HTML><BODY><SCRIPT>EMBEDPANO({xml:'tour.xml'})</SCRIPT></BODY></HTML>"
    ));
    // createPanoViewer — older API.
    assert!(looks_like_krpano_html(
        b"<script>createPanoViewer({xml:'tour.xml'});</script>"
    ));
    // <script> with krpano viewer reference.
    assert!(looks_like_krpano_html(
        b"<html><script src='krpano.js'></script></html>"
    ));
    // <script> with tour.js reference.
    assert!(looks_like_krpano_html(
        b"<html><script src='tour.js'></script></html>"
    ));
    // Uppercase <SCRIPT> with tour.js.
    assert!(looks_like_krpano_html(
        b"<HTML><SCRIPT SRC='tour.js'></SCRIPT></HTML>"
    ));
    // Generic HTML with <script> but no krpano evidence — should NOT match.
    assert!(!looks_like_krpano_html(
        b"<html><script src='jquery.min.js'></script></html>"
    ));
    // Generic HTML with uppercase <SCRIPT> — should NOT match.
    assert!(!looks_like_krpano_html(
        b"<HTML><SCRIPT src='analytics.js'></SCRIPT></HTML>"
    ));
    // Plain HTML, no scripts at all.
    assert!(!looks_like_krpano_html(b"<html><body>Hello</body></html>"));
}