domain-status 0.2.1

Concurrent URL status checker that captures comprehensive metadata in SQLite.
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
1272
//! Pattern matching utilities for technology detection.
//!
//! This module provides pattern matching functions that support Wappalyzer pattern syntax:
//! - Simple substring / escaped-literal matching
//! - Regex pattern matching
//! - Meta tag pattern matching with prefix support
//!
//! Note: Comments referencing wappalyzergo Go source line numbers (e.g.,
//! `patterns.go:122`) are from the original port circa 2024 and may drift
//! as the upstream project evolves.

mod version;

use moka::sync::Cache;
use std::collections::HashMap;
use std::sync::LazyLock;

/// Maximum number of compiled regex patterns to cache.
///
/// This is set to a generous size (10,000) to handle large rulesets without eviction
/// in typical use cases. LRU eviction automatically handles overflow if needed.
///
/// **Rationale:**
/// - Wappalyzer rulesets contain 2000-3000 technologies with many patterns each
/// - Only regex patterns (containing special chars) need compilation and caching
/// - Typical production usage sees ~1000-3000 unique regex patterns
/// - 10k provides ample headroom without memory concerns (each compiled regex is ~1-5KB)
const MAX_REGEX_CACHE_SIZE: u64 = 10_000;

/// Global cache for compiled regex patterns.
/// This cache is shared across all threads and persists for the lifetime of the program.
/// Regex compilation is expensive (10-100x slower than matching), so caching provides
/// significant performance improvements when the same patterns are used repeatedly.
///
/// Uses moka's lock-free concurrent cache for high-throughput concurrent access,
/// avoiding the mutex contention that would occur with `std::sync::Mutex<LruCache>`.
static REGEX_CACHE: LazyLock<Cache<String, regex::Regex>> =
    LazyLock::new(|| Cache::new(MAX_REGEX_CACHE_SIZE));

/// Minimum Wappalyzer `\\;confidence:N` required for a pattern to match.
pub(crate) const MIN_PATTERN_CONFIDENCE: u32 = 50;

/// Result of meta pattern matching with optional version
#[derive(Debug, Clone)]
pub(crate) struct MetaMatchResult {
    pub matched: bool,
    pub version: Option<String>,
}

/// Checks if meta tag patterns match any meta tag values.
///
/// Wappalyzer meta patterns can be:
/// - Simple name: "generator" -> matches meta name="generator"
/// - Prefixed: "property:og:title" -> matches meta property="og:title"
/// - Prefixed: "http-equiv:content-type" -> matches meta http-equiv="content-type"
///
/// For simple keys (without prefix), tries all three attribute types (name, property, http-equiv).
///
/// # Arguments
///
/// * `meta_key` - The meta key from the technology ruleset
/// * `patterns` - Vector of patterns to match against meta values
/// * `meta_tags` - `HashMap` of extracted meta tags (key format: "prefix:name")
///
/// # Returns
///
/// `MetaMatchResult` with match status and extracted version (if any).
pub(crate) fn check_meta_patterns(
    meta_key: &str,
    patterns: &[String],
    meta_tags: &HashMap<String, Vec<String>>,
) -> MetaMatchResult {
    // wappalyzergo normalizes meta keys to lowercase during update (update-fingerprints/main.go line 271)
    // But when matching, it compares lowercase fingerprint key against raw HTML name (case-sensitive comparison)
    // However, since fingerprint keys are lowercase and we normalize HTML names to lowercase when extracting,
    // we can match directly. But we need to handle the case where meta_key might have a prefix.
    let meta_key_lower = meta_key.to_lowercase();

    // Helper to check patterns against meta values and extract version
    // wappalyzergo passes raw content value to pattern.Evaluate (which uses case-insensitive regex)
    // We pass raw content, which is correct
    // meta_values is a Vec<String> because there can be multiple meta tags with the same name
    let check_patterns = |meta_values: &[String]| -> MetaMatchResult {
        let mut matched_version: Option<String> = None;
        let mut has_match = false;

        // Check all meta values (there can be multiple meta tags with the same name)
        for meta_value in meta_values {
            for pattern in patterns {
                let result = matches_pattern(pattern, meta_value);
                if result.matched {
                    has_match = true;
                    // Take the first version found (matching wappalyzergo behavior)
                    if matched_version.is_none() && result.version.is_some() {
                        matched_version.clone_from(&result.version);
                    }
                    // If we found a version, we can stop checking patterns for this meta value
                    if matched_version.is_some() {
                        break;
                    }
                }
            }
            // If we found a version, we can stop checking other meta values
            if matched_version.is_some() {
                break;
            }
        }

        MetaMatchResult {
            matched: has_match,
            version: matched_version,
        }
    };

    // wappalyzergo's matchKeyValueString does: if data != key { continue }
    // where data is the fingerprint meta key (lowercase) and key is the raw HTML meta name
    // Since fingerprint keys are lowercase and we normalize HTML names to lowercase,
    // we can match directly. But we need to handle prefixes correctly.

    // Check if key already has a prefix (property: or http-equiv:)
    // Note: meta_tags keys are pre-normalized to lowercase in html.rs (lines 86, 94, 102),
    // so exact HashMap::get() is sufficient -- no case-insensitive fallback needed.
    if meta_key_lower.starts_with("property:") {
        let key_without_prefix = meta_key_lower
            .strip_prefix("property:")
            .unwrap_or(&meta_key_lower);
        if let Some(meta_value) = meta_tags.get(&format!("property:{key_without_prefix}")) {
            let result = check_patterns(meta_value);
            if result.matched {
                return result;
            }
        }
    } else if meta_key_lower.starts_with("http-equiv:") {
        let key_without_prefix = meta_key_lower
            .strip_prefix("http-equiv:")
            .unwrap_or(&meta_key_lower);
        if let Some(meta_value) = meta_tags.get(&format!("http-equiv:{key_without_prefix}")) {
            let result = check_patterns(meta_value);
            if result.matched {
                return result;
            }
        }
    } else {
        // Simple key (like "generator") - try all three attribute types
        // wappalyzergo matches against raw HTML name (case-sensitive), but fingerprint key is lowercase
        // Since we normalize HTML names to lowercase, we can match directly
        // Try name: prefix (most common)
        if let Some(meta_value) = meta_tags.get(&format!("name:{meta_key_lower}")) {
            let result = check_patterns(meta_value);
            if result.matched {
                return result;
            }
        }
        // Try property: prefix (Open Graph, etc.)
        if let Some(meta_value) = meta_tags.get(&format!("property:{meta_key_lower}")) {
            let result = check_patterns(meta_value);
            if result.matched {
                return result;
            }
        }
        // Try http-equiv: prefix
        if let Some(meta_value) = meta_tags.get(&format!("http-equiv:{meta_key_lower}")) {
            let result = check_patterns(meta_value);
            if result.matched {
                return result;
            }
        }
    }

    MetaMatchResult {
        matched: false,
        version: None,
    }
}

/// Pattern matching result with optional version extraction.
#[derive(Debug, Clone)]
pub(crate) struct PatternMatchResult {
    pub matched: bool,
    pub version: Option<String>,
}

/// Parsed pattern structure
struct ParsedPattern {
    pattern_for_match: String,
    version_template: Option<String>,
    /// Upstream confidence 0–100; defaults to 100 when omitted.
    confidence: u32,
}

/// Parses a Wappalyzer pattern string into pattern and version template.
///
/// Wappalyzer patterns can contain metadata after "\;" separators:
/// - Pattern: "nginx/(\\d+)\\;version:\\1" -> pattern="nginx/(\\d+)", `version_template`="\\1"
/// - Pattern: "jquery\\;confidence:50" -> pattern="jquery", `version_template=None`
///
/// # Arguments
///
/// * `pattern` - The full pattern string from the ruleset
///
/// # Returns
///
/// `ParsedPattern` with the pattern to match and optional version template
#[cfg_attr(test, allow(dead_code))]
fn parse_pattern(pattern: &str) -> ParsedPattern {
    let parts: Vec<&str> = pattern.split("\\;").collect();
    let pattern_for_match = parts[0].trim().to_string();

    // Find version / confidence metadata in subsequent parts.
    let mut version_template: Option<String> = None;
    let mut confidence: u32 = 100;
    for part in parts.iter().skip(1) {
        if let Some(colon_pos) = part.find(':') {
            let key = &part[..colon_pos];
            let value = &part[colon_pos + 1..];

            if key == "version" && version_template.is_none() {
                // First "version:" wins (wappalyzergo order).
                version_template = Some(value.to_string());
            } else if key == "confidence" {
                if let Ok(n) = value.trim().parse::<u32>() {
                    confidence = n;
                }
            }
            // Unknown keys are ignored.
        }
    }

    ParsedPattern {
        pattern_for_match,
        version_template,
        confidence,
    }
}

/// Parses a technology reference used in `implies` / `excludes`.
///
/// Upstream encodes metadata after `\;`, e.g. `PHP\;confidence:75` or
/// `Magento\;version:2`. Returns `(technology_name, optional_literal_version)`.
#[must_use]
pub(crate) fn parse_technology_reference(raw: &str) -> (String, Option<String>) {
    let parsed = parse_pattern(raw);
    (parsed.pattern_for_match, parsed.version_template)
}

/// Checks if a pattern string contains regex-like syntax.
///
/// Patterns starting with ^ or containing regex special chars are likely regex.
///
/// # Arguments
///
/// * `pattern` - The pattern string to check
///
/// # Returns
///
/// `true` if the pattern looks like regex, `false` otherwise
fn is_regex_pattern(pattern: &str) -> bool {
    pattern.starts_with('^')
        || pattern.contains('$')
        || pattern.contains('\\')
        || pattern.contains('[')
        || pattern.contains('(')
        || pattern.contains('*')
        || pattern.contains('+')
        || pattern.contains('?')
}

/// Gets or compiles a regex pattern with caching.
///
/// Returns the compiled regex, or `None` if compilation fails.
/// Uses moka's lock-free concurrent cache for high-throughput access.
///
/// # Arguments
///
/// * `pattern` - The pattern string (will be made case-insensitive)
/// * `cache_key` - The key to use for caching (usually the original pattern)
///
/// # Returns
///
/// `Some(Regex)` if compilation succeeds, `None` if it fails
pub(crate) fn get_or_compile_regex(pattern: &str, cache_key: &str) -> Option<regex::Regex> {
    // wappalyzergo uses case-insensitive matching: regexp.Compile("(?i)" + regexPattern)
    let case_insensitive_pattern = format!("(?i){pattern}");

    // Try to get from cache first (lock-free read)
    if let Some(cached) = REGEX_CACHE.get(cache_key) {
        return Some(cached);
    }

    // Compile regex (this is expensive, so we cache it)
    // moka handles concurrent access automatically - if multiple threads try to
    // compile the same pattern simultaneously, all will succeed and one wins the cache
    match regex::Regex::new(&case_insensitive_pattern) {
        Ok(re) => {
            // Cache the compiled regex (moka handles eviction automatically)
            REGEX_CACHE.insert(cache_key.to_string(), re.clone());
            Some(re)
        }
        Err(_) => None, // Compilation failed
    }
}

/// Handles empty pattern matching (matches anything).
///
/// If there's a version template, extracts the literal version from the template.
/// The template is already the value after "version:" (e.g., "ga4" not "version:ga4").
///
/// # Arguments
///
/// * `version_template` - Optional version template string (value after "version:")
///
/// # Returns
///
/// `PatternMatchResult` with match=true and optional version
fn handle_empty_pattern(version_template: Option<&str>) -> PatternMatchResult {
    let version = if let Some(template) = version_template {
        let template = template.trim();
        if template.is_empty() {
            None
        } else {
            // Check if it's a literal (no capture groups like \1, \2)
            if !template.contains('\\') || !template.chars().any(|c| c.is_ascii_digit()) {
                // It's a literal version string (e.g., "ga4", "ua")
                Some(template.to_string())
            } else {
                // It has capture groups, but we have no captures for an empty pattern
                // This shouldn't happen for empty patterns, but handle it gracefully
                None
            }
        }
    } else {
        None
    };

    PatternMatchResult {
        matched: true,
        version,
    }
}

/// Pattern matching supporting Wappalyzer pattern syntax
/// Patterns can be:
/// - Simple strings (substring match)
/// - Regex patterns (if they start with ^ or contain regex special chars)
/// - Patterns with version extraction (e.g., "version:\\1")
///
/// Returns `PatternMatchResult` with match status and extracted version (if any).
pub(crate) fn matches_pattern(pattern: &str, text: &str) -> PatternMatchResult {
    let parsed = parse_pattern(pattern);

    if parsed.confidence < MIN_PATTERN_CONFIDENCE {
        return PatternMatchResult {
            matched: false,
            version: None,
        };
    }

    // Handle empty pattern (matches anything)
    if parsed.pattern_for_match.is_empty() {
        return handle_empty_pattern(parsed.version_template.as_deref());
    }

    // Check if pattern contains regex-like syntax
    let is_regex = is_regex_pattern(&parsed.pattern_for_match);

    if is_regex {
        // Try to compile as regex (with caching)
        let cache_key = parsed.pattern_for_match.clone();

        let Some(re) = get_or_compile_regex(&parsed.pattern_for_match, &cache_key) else {
            // Invalid regex patterns are skipped (no silent substring match).
            return PatternMatchResult {
                matched: false,
                version: None,
            };
        };

        // Match and extract version
        if let Some(captures) = re.captures(text) {
            let version = if let Some(template) = &parsed.version_template {
                // template is already the value after "version:" (e.g., "\1" or "\1?next:")
                // extract_version_from_template expects "version:..." format
                extract_version_from_template(&format!("version:{template}"), &captures)
            } else {
                None
            };
            PatternMatchResult {
                matched: true,
                version,
            }
        } else {
            PatternMatchResult {
                matched: false,
                version: None,
            }
        }
    } else {
        // Simple string pattern - wappalyzergo compiles ALL patterns as regex, even simple strings
        // For a simple string like "jquery", wappalyzergo compiles it as "(?i)jquery" which matches
        // "jquery" anywhere in the string (case-insensitive). We need to match this behavior.
        let escaped_pattern = regex::escape(&parsed.pattern_for_match);
        let cache_key = parsed.pattern_for_match.clone();

        let Some(re) = get_or_compile_regex(&escaped_pattern, &cache_key) else {
            // Escaped literal should always compile; if not, skip the pattern.
            return PatternMatchResult {
                matched: false,
                version: None,
            };
        };

        // Match using regex (like wappalyzergo does)
        PatternMatchResult {
            matched: re.is_match(text),
            version: None,
        }
    }
}

// Version template helpers live in `version`.
use version::*;

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Mutex, OnceLock};

    /// Serializes tests that clear or assert on the global `REGEX_CACHE`.
    /// Without this, `invalidate_all` in one test races with cache lookups in others
    /// (observed flake: `test_regex_cache_works` on macOS CI).
    fn cache_test_lock() -> std::sync::MutexGuard<'static, ()> {
        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
        LOCK.get_or_init(|| Mutex::new(()))
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    /// Clears the regex cache (useful for testing). Caller must hold [`cache_test_lock`].
    fn clear_regex_cache() {
        REGEX_CACHE.invalidate_all();
    }

    #[test]
    fn test_matches_pattern_empty_pattern() {
        // Empty pattern matches anything
        assert!(matches_pattern("", "anything").matched);
        assert!(matches_pattern("", "").matched);
        assert!(matches_pattern("", "test string").matched);
    }

    #[test]
    fn test_matches_pattern_simple_substring() {
        // Simple substring matching (case-insensitive to match wappalyzergo)
        // wappalyzergo normalizes everything to lowercase: normalizedBody := bytes.ToLower(body)
        assert!(matches_pattern("nginx", "nginx/1.18.0").matched);
        assert!(matches_pattern("WordPress", "Powered by WordPress").matched); // Case-insensitive
        assert!(matches_pattern("wordpress", "Powered by WordPress").matched); // Case-insensitive
        assert!(matches_pattern("WORDPRESS", "Powered by WordPress").matched); // Case-insensitive
        assert!(!matches_pattern("apache", "nginx/1.18.0").matched);
        assert!(!matches_pattern("nginx", "apache/2.4").matched);
    }

    #[test]
    fn test_matches_pattern_regex_starts_with_caret() {
        // Regex pattern starting with ^
        assert!(matches_pattern("^nginx", "nginx/1.18.0").matched);
        assert!(!matches_pattern("^nginx", "server: nginx/1.18.0").matched);
    }

    #[test]
    fn test_matches_pattern_regex_ends_with_dollar() {
        // Regex pattern ending with $
        assert!(matches_pattern("nginx$", "nginx").matched);
        assert!(!matches_pattern("nginx$", "nginx/1.18.0").matched);
    }

    #[test]
    fn test_matches_pattern_regex_special_chars() {
        // Regex patterns with special characters
        assert!(matches_pattern("nginx.*", "nginx/1.18.0").matched);
        assert!(matches_pattern("wordpress\\+", "wordpress+").matched);
        assert!(matches_pattern("test\\?", "test?").matched);
        assert!(matches_pattern("[0-9]+", "version 123").matched);
    }

    #[test]
    fn test_matches_pattern_version_extraction() {
        // Patterns with version extraction syntax
        let result1 = matches_pattern(
            "jquery(?:-(\\d+\\.\\d+\\.\\d+))[/.-]\\;version:\\1",
            "jquery-3.6.0.min.js",
        );
        assert!(result1.matched);
        assert_eq!(result1.version, Some("3.6.0".to_string()));

        let result2 = matches_pattern("^wordpress\\;version:\\1$", "wordpress");
        assert!(result2.matched);
    }

    #[test]
    fn test_check_meta_patterns_simple_name() {
        let mut meta_tags = HashMap::new();
        meta_tags.insert("name:generator".to_string(), vec!["WordPress".to_string()]);

        assert!(check_meta_patterns("generator", &["WordPress".to_string()], &meta_tags).matched);
        assert!(!check_meta_patterns("generator", &["Drupal".to_string()], &meta_tags).matched);
    }

    #[test]
    fn test_check_meta_patterns_property_prefix() {
        let mut meta_tags = HashMap::new();
        meta_tags.insert(
            "property:og:title".to_string(),
            vec!["My Title".to_string()],
        );

        assert!(
            check_meta_patterns("property:og:title", &["My Title".to_string()], &meta_tags).matched
        );
        assert!(
            !check_meta_patterns(
                "property:og:title",
                &["Other Title".to_string()],
                &meta_tags
            )
            .matched
        );
    }

    #[test]
    fn test_check_meta_patterns_http_equiv_prefix() {
        let mut meta_tags = HashMap::new();
        meta_tags.insert(
            "http-equiv:content-type".to_string(),
            vec!["text/html".to_string()],
        );

        assert!(
            check_meta_patterns(
                "http-equiv:content-type",
                &["text/html".to_string()],
                &meta_tags
            )
            .matched
        );
    }

    #[test]
    fn test_check_meta_patterns_tries_all_prefixes() {
        // Simple key should try name:, property:, and http-equiv:
        let mut meta_tags = HashMap::new();
        meta_tags.insert(
            "property:generator".to_string(),
            vec!["WordPress".to_string()],
        );

        // Should find it via property: prefix
        assert!(check_meta_patterns("generator", &["WordPress".to_string()], &meta_tags).matched);
    }

    #[test]
    fn test_check_meta_patterns_case_insensitive_key() {
        let mut meta_tags = HashMap::new();
        // Key is lowercased in the function, so we need to use lowercase in the map
        meta_tags.insert("name:generator".to_string(), vec!["WordPress".to_string()]);

        // Key should be lowercased when looking up
        assert!(check_meta_patterns("GENERATOR", &["WordPress".to_string()], &meta_tags).matched);
    }

    #[test]
    fn test_check_meta_patterns_multiple_patterns() {
        let mut meta_tags = HashMap::new();
        meta_tags.insert(
            "name:generator".to_string(),
            vec!["WordPress 5.0".to_string()],
        );

        // Should match if any pattern matches
        assert!(
            check_meta_patterns(
                "generator",
                &["Drupal".to_string(), "WordPress".to_string()],
                &meta_tags
            )
            .matched
        );
    }

    #[test]
    fn test_check_meta_patterns_empty_meta_tags() {
        let meta_tags = HashMap::new();
        assert!(!check_meta_patterns("generator", &["WordPress".to_string()], &meta_tags).matched);
    }

    #[test]
    fn test_check_meta_patterns_empty_patterns() {
        let mut meta_tags = HashMap::new();
        meta_tags.insert("name:generator".to_string(), vec!["WordPress".to_string()]);

        // Empty patterns should not match
        assert!(!check_meta_patterns("generator", &[], &meta_tags).matched);
    }

    #[test]
    fn test_check_meta_patterns_regex_in_patterns() {
        let mut meta_tags = HashMap::new();
        meta_tags.insert(
            "name:generator".to_string(),
            vec!["WordPress 5.0".to_string()],
        );

        // Patterns can contain regex
        assert!(check_meta_patterns("generator", &["^WordPress".to_string()], &meta_tags).matched);
    }

    #[test]
    fn test_regex_cache_works() {
        let _guard = cache_test_lock();
        // Unique key as defense in depth against any unlocked clear paths.
        use std::time::{SystemTime, UNIX_EPOCH};
        let stamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let pattern = format!("^nginx_cache_works_{stamp}");
        let text = format!("nginx_cache_works_{stamp}/1.18.0");

        assert!(matches_pattern(&pattern, &text).matched);
        assert!(matches_pattern(&pattern, &text).matched);
        assert!(
            REGEX_CACHE.get(&pattern).is_some(),
            "Cache should contain compiled regex for '{pattern}'"
        );
    }

    #[test]
    fn test_regex_cache_thread_safety() {
        let _guard = cache_test_lock();
        // Use unique patterns with a test-specific prefix and timestamp to avoid conflicts
        // with other tests running in parallel. This ensures the test is deterministic.
        use std::time::{SystemTime, UNIX_EPOCH};
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let test_prefix = format!("thread_safety_test_{}_", timestamp);

        // Test that multiple threads can safely use the cache
        use std::thread;
        let patterns: Vec<String> = (0..10).map(|i| format!("^{}{}", test_prefix, i)).collect();

        // First, verify patterns work correctly (this also populates the cache)
        for (i, pattern) in patterns.iter().enumerate() {
            let text = format!("{}{}value", test_prefix, i);
            assert!(
                matches_pattern(pattern, &text).matched,
                "Pattern '{}' should match text '{}'",
                pattern,
                text
            );
        }

        // Now test concurrent access - all threads should be able to use cached patterns
        let handles: Vec<_> = patterns
            .iter()
            .enumerate()
            .map(|(i, pattern)| {
                let pattern_clone = pattern.clone();
                let prefix_clone = test_prefix.clone();
                thread::spawn(move || {
                    let text = format!("{}{}value", prefix_clone, i);
                    // Call twice to ensure cache is used
                    let result1 = matches_pattern(&pattern_clone, &text);
                    let result2 = matches_pattern(&pattern_clone, &text);
                    // Both calls should return the same result
                    assert_eq!(
                        result1.matched, result2.matched,
                        "Cached and uncached calls should return same result"
                    );
                    result1
                })
            })
            .collect();

        // Verify all threads completed successfully (no panics or data races)
        // This is the primary test - if the cache wasn't thread-safe, we'd see panics, data races,
        // or incorrect results. The fact that all threads complete successfully with correct results
        // proves the cache is thread-safe.
        for handle in handles {
            assert!(
                handle.join().unwrap().matched,
                "Thread should return true for pattern match"
            );
        }

        // Note: We don't verify cache state here because:
        // 1. The primary goal is to test thread safety, which is proven by successful completion
        // 2. Cache state verification is racy when tests run in parallel (other tests may clear/modify cache)
        // 3. Cache functionality is already tested in test_regex_cache_works
        // 4. The fact that all threads completed without panics or incorrect results proves the cache
        //    is working correctly and is thread-safe
    }

    #[test]
    fn test_regex_cache_benchmark() {
        let _guard = cache_test_lock();
        clear_regex_cache();

        // Benchmark: compile same regex 1000 times
        let pattern = "^nginx.*version";
        let text = "nginx/1.18.0 version";

        // Without cache (simulated by clearing each time)
        let start = std::time::Instant::now();
        for _ in 0..1000 {
            clear_regex_cache();
            let _ = matches_pattern(pattern, text);
        }
        let without_cache_time = start.elapsed();

        // With cache
        clear_regex_cache();
        let start = std::time::Instant::now();
        for _ in 0..1000 {
            let _ = matches_pattern(pattern, text);
        }
        let with_cache_time = start.elapsed();

        // Cached version should be significantly faster
        // In practice, this should be 10-100x faster
        assert!(
            with_cache_time < without_cache_time,
            "Cached version should be faster. Without cache: {:?}, With cache: {:?}",
            without_cache_time,
            with_cache_time
        );

        // SAFETY: Cast u128 to f64 for performance test speedup calculation
        // - Converting nanosecond Duration measurements to f64 for ratio calculation
        // - Test durations are typically microseconds to milliseconds (10^3 to 10^9 nanoseconds)
        // - f64 has 53 bits of precision, can exactly represent integers up to 2^53 (~9 x 10^15)
        // - Test timing values (< 10^12 ns) are well within f64 precision range
        // - This is test-only code for performance comparison
        // - Precision loss for very large durations is acceptable (test result still meaningful)
        #[allow(clippy::cast_precision_loss)]
        let speedup = if with_cache_time.as_nanos() > 0 {
            without_cache_time.as_nanos() as f64 / with_cache_time.as_nanos() as f64
        } else {
            0.0 // Fallback if with_cache_time is 0 (shouldn't happen due to assertion above)
        };
        println!(
            "Regex cache benchmark: Without cache: {:?}, With cache: {:?}, Speedup: {:.2}x",
            without_cache_time, with_cache_time, speedup
        );
    }

    #[test]
    fn test_matches_pattern_invalid_regex_is_skipped() {
        // Invalid regex patterns must not silently substring-match.
        assert!(!matches_pattern("[unclosed", "text with [unclosed bracket").matched);
        assert!(!matches_pattern("[unclosed", "text without pattern").matched);
        assert!(!matches_pattern(r"\invalid", r"text with \invalid").matched);
        assert!(!matches_pattern("(unclosed", "text with (unclosed paren").matched);

        // `{` is not treated as regex syntax here, so this is an escaped literal match.
        assert!(matches_pattern("test{invalid", "text with test{invalid").matched);
    }

    #[test]
    fn test_check_meta_patterns_malformed_prefix() {
        // Test edge cases with malformed prefixes
        let mut meta_tags = HashMap::new();
        meta_tags.insert("name:generator".to_string(), vec!["WordPress".to_string()]);

        // Key with double prefix (should not match)
        assert!(
            !check_meta_patterns(
                "property:property:og:title",
                &["WordPress".to_string()],
                &meta_tags
            )
            .matched
        );

        // Key with empty prefix value
        assert!(!check_meta_patterns("property:", &["WordPress".to_string()], &meta_tags).matched);
    }

    #[test]
    fn test_matches_pattern_very_long_string() {
        // Test pattern matching with very long strings (performance/overflow edge case)
        let very_long_text = "A".repeat(1_000_000);
        let pattern = "test";

        // Should handle very long strings without panicking or excessive memory usage
        let result = matches_pattern(pattern, &very_long_text);
        assert!(
            !result.matched,
            "Pattern should not match in very long string"
        );
    }

    #[test]
    fn test_matches_pattern_special_regex_chars_in_substring() {
        // Test that special regex characters in substring mode don't cause issues
        // These should be treated as literal characters, not regex
        let text = "test[pattern]with(special)chars";

        // Patterns without ^ or other regex indicators should be substring matches
        assert!(matches_pattern("[pattern]", text).matched);
        assert!(matches_pattern("(special)", text).matched);
        assert!(matches_pattern("chars", text).matched);
    }

    #[test]
    fn test_matches_pattern_version_extraction_complex() {
        // Test version extraction syntax with complex patterns
        // Version extraction syntax: "\;version:\\1" should be stripped before matching
        // Note: In Rust string literals, "\;" is written as "\\;"
        let pattern = r"^nginx/(\d+\.\d+)\;version:\1";
        let text = "nginx/1.18.0";

        // Should match the pattern part (before \;) and extract version
        // Pattern: ^nginx/(\d+\.\d+) should match "nginx/1.18" from "nginx/1.18.0"
        // Version template: \1 should extract "1.18" (first capture group)
        let result = matches_pattern(pattern, text);
        assert!(result.matched, "Pattern should match 'nginx/1.18.0'");
        assert_eq!(result.version, Some("1.18".to_string()));
    }

    #[test]
    fn test_matches_pattern_regex_anchors_edge_cases() {
        // Test regex anchors with edge cases
        // ^ at start, $ at end
        assert!(matches_pattern("^start", "start of text").matched);
        assert!(!matches_pattern("^start", "text with start").matched);
        assert!(matches_pattern("end$", "text with end").matched);
        assert!(!matches_pattern("end$", "end of text with more").matched);
        assert!(matches_pattern("^exact$", "exact").matched);
        assert!(!matches_pattern("^exact$", "not exact").matched);
    }

    #[test]
    fn test_check_meta_patterns_empty_patterns_vector() {
        // Test with empty patterns vector (edge case)
        let mut meta_tags = HashMap::new();
        meta_tags.insert("name:generator".to_string(), vec!["WordPress".to_string()]);

        // Empty patterns should not match
        assert!(!check_meta_patterns("generator", &[], &meta_tags).matched);
    }

    #[test]
    fn test_check_meta_patterns_multiple_prefixes_same_key() {
        // Test that simple key tries all prefixes correctly
        let mut meta_tags = HashMap::new();
        meta_tags.insert("name:test".to_string(), vec!["value1".to_string()]);
        meta_tags.insert("property:test".to_string(), vec!["value2".to_string()]);
        meta_tags.insert("http-equiv:test".to_string(), vec!["value3".to_string()]);

        // Should match if any prefix matches
        assert!(check_meta_patterns("test", &["value1".to_string()], &meta_tags).matched);
        assert!(check_meta_patterns("test", &["value2".to_string()], &meta_tags).matched);
        assert!(check_meta_patterns("test", &["value3".to_string()], &meta_tags).matched);
    }

    #[test]
    fn test_check_meta_patterns_wordpress_version_extraction() {
        // Test WordPress version extraction from generator meta tag
        // Pattern: ^wordpress(?: ([\d.]+))?\;version:\1
        // Content: WordPress 6.8.3
        // Should extract version: 6.8.3
        let mut meta_tags = HashMap::new();
        meta_tags.insert(
            "name:generator".to_string(),
            vec!["WordPress 6.8.3".to_string()],
        );

        let result = check_meta_patterns(
            "generator",
            &[r"^wordpress(?: ([\d.]+))?\;version:\1".to_string()],
            &meta_tags,
        );

        assert!(result.matched, "Should match WordPress generator meta tag");
        assert_eq!(
            result.version,
            Some("6.8.3".to_string()),
            "Should extract WordPress version 6.8.3"
        );
    }

    #[test]
    fn test_matches_pattern_with_version_template() {
        // Test pattern with version template
        let pattern = r"^version ([\d.]+)\;version:\1";
        let text = "version 5.0";

        let result = matches_pattern(pattern, text);

        assert!(result.matched, "Should match pattern");
        assert_eq!(
            result.version,
            Some("5.0".to_string()),
            "Should extract version 5.0"
        );
    }

    #[test]
    fn test_matches_pattern_ignores_non_version_template() {
        // Test that patterns with metadata (not starting with "version:") are ignored
        let pattern = r"^test\;metadata:value";
        let text = "test";

        let result = matches_pattern(pattern, text);

        assert!(result.matched, "Should match pattern");
        assert_eq!(
            result.version, None,
            "Should not extract version when template doesn't start with 'version:'"
        );
    }

    // Tests for extracted helper functions (indirectly tested through matches_pattern)

    #[test]
    fn test_parse_pattern_extracts_version_template() {
        // Test pattern parsing through matches_pattern
        let pattern = r"nginx/(\d+\.\d+)\;version:\1";
        let result = matches_pattern(pattern, "nginx/1.18.0");

        assert!(result.matched);
        assert_eq!(result.version, Some("1.18".to_string()));
    }

    #[test]
    fn test_parse_pattern_respects_confidence_threshold() {
        // Below threshold → no match
        let low = matches_pattern(r"jquery\;confidence:49", "jquery.min.js");
        assert!(!low.matched);

        // At/above threshold → match
        let ok = matches_pattern(r"jquery\;confidence:50", "jquery.min.js");
        assert!(ok.matched);
        assert_eq!(ok.version, None);
    }

    #[test]
    fn test_is_regex_pattern_detection() {
        // Test regex detection through matches_pattern behavior
        // Patterns with ^ should be treated as regex
        assert!(matches_pattern("^nginx", "nginx/1.18.0").matched);
        assert!(!matches_pattern("^nginx", "server: nginx/1.18.0").matched);

        // Patterns with $ should be treated as regex
        assert!(matches_pattern("nginx$", "nginx").matched);
        assert!(!matches_pattern("nginx$", "nginx/1.18.0").matched);

        // Patterns with regex special chars should be treated as regex
        assert!(matches_pattern("nginx.*", "nginx/1.18.0").matched);
    }

    #[test]
    fn test_get_or_compile_regex_caching() {
        let _guard = cache_test_lock();
        // Unique key — lock prevents parallel invalidate_all races.
        use std::time::{SystemTime, UNIX_EPOCH};
        let stamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let pattern = format!("^test_pattern_cache_{stamp}");
        let text = format!("test_pattern_cache_{stamp}_value");

        assert!(
            REGEX_CACHE.get(&pattern).is_none(),
            "Cache should not contain the unique pattern before first use"
        );

        assert!(matches_pattern(&pattern, &text).matched);
        assert!(
            REGEX_CACHE.get(&pattern).is_some(),
            "Cache should contain compiled regex after first use"
        );

        assert!(matches_pattern(&pattern, &text).matched);
    }

    #[test]
    fn test_regex_cache_eviction() {
        let _guard = cache_test_lock();
        // Test that LRU caching works correctly
        // Note: With 10k cache size, filling to capacity is impractical for unit tests.
        // This test verifies the cache stores and retrieves patterns correctly.
        //
        // We verify behavior: patterns match correctly, which proves caching works.

        // Use unique patterns with timestamp + thread ID hash to avoid conflicts
        use std::hash::{Hash, Hasher};
        use std::time::{SystemTime, UNIX_EPOCH};
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        std::thread::current().id().hash(&mut hasher);
        let thread_hash = hasher.finish();
        let unique_suffix = format!("{}_{}", timestamp, thread_hash);

        // Add patterns to cache (first use compiles and caches them)
        let pattern1 = format!("^evict_test_{}_1", unique_suffix);
        let pattern2 = format!("^evict_test_{}_2", unique_suffix);
        let pattern3 = format!("^evict_test_{}_3", unique_suffix);

        // First use: should compile, cache, and match
        assert!(
            matches_pattern(&pattern1, &format!("evict_test_{}_1_value", unique_suffix)).matched,
            "Pattern 1 should match on first use"
        );
        assert!(
            matches_pattern(&pattern2, &format!("evict_test_{}_2_value", unique_suffix)).matched,
            "Pattern 2 should match on first use"
        );
        assert!(
            matches_pattern(&pattern3, &format!("evict_test_{}_3_value", unique_suffix)).matched,
            "Pattern 3 should match on first use"
        );

        // Second use: should retrieve from cache and match (proves caching works)
        assert!(
            matches_pattern(&pattern1, &format!("evict_test_{}_1_value", unique_suffix)).matched,
            "Pattern 1 should match on second use (cached)"
        );
        assert!(
            matches_pattern(&pattern2, &format!("evict_test_{}_2_value", unique_suffix)).matched,
            "Pattern 2 should match on second use (cached)"
        );
        assert!(
            matches_pattern(&pattern3, &format!("evict_test_{}_3_value", unique_suffix)).matched,
            "Pattern 3 should match on second use (cached)"
        );

        // Verify non-matching patterns still don't match (sanity check)
        assert!(
            !matches_pattern(&pattern1, "completely_different_value").matched,
            "Pattern should not match unrelated text"
        );
    }

    #[test]
    fn test_handle_empty_pattern_with_literal_version() {
        // Test empty pattern with literal version template
        let pattern = r"\;version:ga4";
        let result = matches_pattern(pattern, "anything");

        assert!(result.matched, "Empty pattern should match anything");
        assert_eq!(result.version, Some("ga4".to_string()));
    }

    #[test]
    fn test_handle_empty_pattern_without_version() {
        // Test empty pattern without version template
        let pattern = "";
        let result = matches_pattern(pattern, "anything");

        assert!(result.matched, "Empty pattern should match anything");
        assert_eq!(result.version, None);
    }

    #[test]
    fn test_get_or_compile_regex_skips_invalid_regex() {
        // Invalid regex must not silently substring-match
        let pattern = "[invalid"; // Unclosed bracket
        let result = matches_pattern(pattern, "text with [invalid bracket");

        assert!(!result.matched);
        assert_eq!(result.version, None);
    }

    // Tests for evaluate_version_ternary and extracted helper functions

    #[test]
    fn test_replace_placeholders_simple() {
        // Test placeholder replacement through version extraction
        let pattern = r"nginx/(\d+\.\d+)\;version:\1";
        let result = matches_pattern(pattern, "nginx/1.18.0");

        assert!(result.matched);
        assert_eq!(result.version, Some("1.18".to_string()));
    }

    #[test]
    fn test_replace_placeholders_multiple_groups() {
        // Test multiple placeholder replacement
        let pattern = r"(\d+)\.(\d+)\;version:\1.\2";
        let result = matches_pattern(pattern, "1.18");

        assert!(result.matched);
        assert_eq!(result.version, Some("1.18".to_string()));
    }

    #[test]
    fn test_parse_ternary_expression_valid() {
        // Test ternary parsing through version extraction
        // Pattern with ternary: \1?\1:\2 means "if capture group 1 exists, use it, else use capture group 2"
        let pattern = r"(\d+)?(\d+)\;version:\1?\1:\2";
        let result = matches_pattern(pattern, "18");

        // Should match and evaluate ternary
        assert!(result.matched);
    }

    #[test]
    fn test_ternary_evaluated_before_placeholder_replacement() {
        // Regression: version string containing '?' or ':' must not be split by the ternary parser.
        // Template \1?\1:\2 with group 1 = "beta:v2" used to be replaced first, producing
        // "beta:v2?beta:v2:\2", which the parser split on ? and :, corrupting the version.
        // Ternary must be evaluated on the raw template (with \1, \2), then placeholders
        // replaced in the chosen branch only.
        let pattern = r"^(beta:v\d+)(\.\d+)?\;version:\1?\1:\2";
        let result = matches_pattern(pattern, "beta:v2");
        assert!(result.matched, "Pattern should match");
        assert_eq!(
            result.version,
            Some("beta:v2".to_string()),
            "Version must be intact, not split on ':' by ternary parser"
        );
    }

    #[test]
    fn test_parse_ternary_expression_invalid() {
        // Test that invalid ternary expressions are handled gracefully
        // Missing colon should return expression as-is
        let pattern = r"test\;version:\1?\1";
        let result = matches_pattern(pattern, "test");

        // Should match but not extract version (invalid ternary)
        assert!(result.matched);
    }

    #[test]
    fn test_evaluate_version_ternary_with_capture_groups() {
        // Test ternary evaluation when capture groups exist
        // Pattern: \1?\1:\2 with captures -> should use \1
        let pattern = r"(\d+)\.(\d+)\;version:\1?\1:\2";
        let result = matches_pattern(pattern, "1.18");

        assert!(result.matched);
        // Should use true_part (\1) because we have capture groups
        assert_eq!(result.version, Some("1".to_string()));
    }

    #[test]
    fn test_evaluate_version_ternary_without_capture_groups() {
        // Test ternary evaluation when no capture groups exist
        // Pattern: \1?\1:\2 without captures -> should use \2 (false_part)
        // But since there are no captures, \2 will be empty
        // This is a complex case - let's test through a simpler pattern
        let pattern = r"test\;version:\1?\1:fallback";
        let result = matches_pattern(pattern, "test");

        // Should match but version extraction depends on ternary logic
        assert!(result.matched);
    }

    #[test]
    fn test_evaluate_version_ternary_empty_true_part() {
        // Test ternary with empty true_part
        // Pattern: ?:\2 means "if no captures, use empty, else use \2"
        let pattern = r"(\d+)\;version:?:\1";
        let result = matches_pattern(pattern, "123");

        assert!(result.matched);
        // Should use false_part (\1) because true_part is empty
        assert_eq!(result.version, Some("123".to_string()));
    }

    #[test]
    fn test_evaluate_version_ternary_both_parts_empty() {
        // Test ternary with both parts empty
        let pattern = r"test\;version:?:";
        let result = matches_pattern(pattern, "test");

        assert!(result.matched);
        // Should return empty version
        assert_eq!(result.version, None);
    }

    #[test]
    fn test_extract_version_semicolon_in_captured_value() {
        // Test version extraction when captured value contains semicolon
        // This is critical - semicolons in version strings could break parsing
        // The code at line 560-569 handles this by taking first part before semicolon
        // when template only had one placeholder
        let pattern = r"version (\d+);(\d+)\;version:\1";
        let text = "version 64;5.3";

        let result = matches_pattern(pattern, text);
        assert!(result.matched);
        // Should extract "64" (first part before semicolon) when template only had \1
        assert_eq!(result.version, Some("64".to_string()));
    }

    #[test]
    fn test_extract_version_multiple_placeholders_with_semicolon() {
        // Test version extraction with multiple placeholders and semicolon (intentional)
        // When template has multiple placeholders like \1;\2, semicolon is intentional
        // However, the code at line 560-569 checks if template had multiple placeholders
        // by counting \d+ matches. The pattern \1;\2 has 2 placeholders, so semicolon is preserved.
        // But the actual behavior may differ - let's test what actually happens
        let pattern = r"v(\d+)\.(\d+)\;version:\1;\2";
        let text = "v1.2";

        let result = matches_pattern(pattern, text);
        assert!(result.matched);
        // The semicolon handling logic may take first part only if it detects single placeholder
        // Let's verify it extracts something (the exact format may vary)
        assert!(result.version.is_some());
        // Version should contain at least "1" from first capture group
        assert!(result.version.unwrap().contains("1"));
    }

    #[test]
    fn test_extract_version_high_capture_group_number() {
        // Test version extraction with capture group 9 (highest supported)
        // The code at line 521 only checks \1 through \9
        // This ensures high capture groups don't cause issues
        let pattern = r"v(\d+)\.(\d+)\.(\d+)\.(\d+)\.(\d+)\.(\d+)\.(\d+)\.(\d+)\.(\d+)\;version:\9";
        let text = "v1.2.3.4.5.6.7.8.9";

        let result = matches_pattern(pattern, text);
        assert!(result.matched);
        // Should extract capture group 9 (the last digit)
        assert_eq!(result.version, Some("9".to_string()));
    }

    #[test]
    fn test_extract_version_unmatched_placeholder_removed() {
        // Test that unmatched placeholders (e.g., \3 when only \1 and \2 matched) are removed
        // The code at line 545 removes remaining placeholders using regex
        let pattern = r"v(\d+)\.(\d+)\;version:\1.\2.\3";
        let text = "v1.2";

        let result = matches_pattern(pattern, text);
        assert!(result.matched);
        // Should extract "1.2." (unmatched \3 is removed, but trailing dot remains)
        // The regex removal removes \3 but leaves the dot before it
        assert_eq!(result.version, Some("1.2.".to_string()));
    }

    #[test]
    fn test_extract_version_reverse_order_replacement() {
        // Test that placeholders are replaced in reverse order to avoid partial matches
        // This is critical - replacing \1 before \10 would cause "1" to match in "10"
        // The code at line 530 replaces in reverse order (highest first)
        let pattern =
            r"v(\d+)\.(\d+)\.(\d+)\.(\d+)\.(\d+)\.(\d+)\.(\d+)\.(\d+)\.(\d+)\.(\d+)\;version:\10";
        let text = "v1.2.3.4.5.6.7.8.9.10";

        let result = matches_pattern(pattern, text);
        assert!(result.matched);
        // Should extract "10" (not "1" from partial match)
        // Note: The code only checks \1-\9, so \10 won't work, but this tests the reverse order logic
        // For \9, it should work correctly
        if let Some(version) = result.version {
            // If version extraction works, verify it's correct
            // Should not be "1" (partial match)
            assert_ne!(version, "1");
        }
    }
}