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
//! Data structures for fingerprint rulesets.
//!
//! This module contains the core data structures used for technology detection:
//! - `Technology`: A single technology fingerprint rule
//! - `FingerprintMetadata`: Metadata about a ruleset (source, version, timestamp)
//! - `FingerprintRuleset`: Container for all technologies and categories
//! - `Category`: Category information from categories.json

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::SystemTime;

/// Technology fingerprint rule structure matching Wappalyzer schema
/// Note: The technology name is the key in the JSON, not a field
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Technology {
    /// Category IDs
    #[serde(default)]
    pub cats: Vec<u32>,
    /// Website URL
    #[serde(default)]
    pub website: String,
    /// Header patterns: `header_name` -> pattern
    #[serde(default)]
    pub headers: HashMap<String, String>,
    /// Cookie patterns: `cookie_name` -> pattern
    #[serde(default)]
    pub cookies: HashMap<String, String>,
    /// Meta tag patterns: `meta_name` -> pattern(s)
    /// In Wappalyzer, meta values can be either a string or an array of strings
    #[serde(default)]
    #[serde(deserialize_with = "deserialize_meta_map")]
    pub meta: HashMap<String, Vec<String>>,
    /// Script source URL patterns (can be string or array) - Wappalyzer uses "scriptSrc"
    #[serde(default)]
    #[serde(alias = "scriptSrc")]
    #[serde(deserialize_with = "deserialize_string_or_array")]
    pub script: Vec<String>,
    /// Inline (and external) JavaScript source-code patterns — Wappalyzer `scripts`.
    /// Matched against inline `<script>` text only (no JS execution / no fetch).
    #[serde(default)]
    #[serde(deserialize_with = "deserialize_string_or_array")]
    pub scripts: Vec<String>,
    /// HTML text patterns (can be string or array)
    #[serde(default)]
    #[serde(deserialize_with = "deserialize_string_or_array")]
    pub html: Vec<String>,
    /// URL patterns (can be string or array)
    #[serde(default)]
    #[serde(deserialize_with = "deserialize_string_or_array")]
    pub url: Vec<String>,
    /// DNS record patterns: record type (TXT/MX/NS/…) -> pattern(s).
    /// Matching uses NS and CNAME only; TXT/MX stay in satellite tables.
    #[serde(default)]
    #[serde(deserialize_with = "deserialize_meta_map")]
    pub dns: HashMap<String, Vec<String>>,
    /// SSL certificate issuer patterns (Wappalyzer `certIssuer`)
    #[serde(default)]
    #[serde(alias = "certIssuer")]
    #[serde(deserialize_with = "deserialize_string_or_array")]
    pub cert_issuer: Vec<String>,
    /// JavaScript object properties to check
    #[serde(default)]
    pub js: HashMap<String, String>,
    /// Implies other technologies (can be string or array)
    #[serde(default)]
    #[serde(deserialize_with = "deserialize_string_or_array")]
    pub implies: Vec<String>,
    /// Excludes other technologies (can be string or array)
    #[serde(default)]
    #[serde(deserialize_with = "deserialize_string_or_array")]
    pub excludes: Vec<String>,
    /// Parent technologies that must already be detected (`requires`).
    #[serde(default)]
    #[serde(deserialize_with = "deserialize_string_or_array")]
    pub requires: Vec<String>,
    /// Category IDs that must be present on another detected technology.
    #[serde(default)]
    #[serde(alias = "requiresCategory")]
    #[serde(deserialize_with = "deserialize_u32_or_array")]
    pub requires_category: Vec<u32>,
}

/// Deserializes a field that can be either a string or an array of strings
fn deserialize_string_or_array<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::de::{self, Visitor};
    use std::fmt;

    struct StringOrArrayVisitor;

    impl<'de> Visitor<'de> for StringOrArrayVisitor {
        type Value = Vec<String>;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("a string or an array of strings")
        }

        fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(vec![value.to_string()])
        }

        fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(vec![value])
        }

        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
        where
            A: de::SeqAccess<'de>,
        {
            let mut vec = Vec::new();
            while let Some(elem) = seq.next_element::<String>()? {
                vec.push(elem);
            }
            Ok(vec)
        }
    }

    deserializer.deserialize_any(StringOrArrayVisitor)
}

/// Deserializes a field that can be a number or an array of numbers.
fn deserialize_u32_or_array<'de, D>(deserializer: D) -> Result<Vec<u32>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::de::{self, Visitor};
    use std::fmt;

    struct U32OrArrayVisitor;

    impl<'de> Visitor<'de> for U32OrArrayVisitor {
        type Value = Vec<u32>;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("a number or an array of numbers")
        }

        fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            u32::try_from(value)
                .map(|n| vec![n])
                .map_err(|_| de::Error::custom("category id exceeds u32"))
        }

        fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            u32::try_from(value)
                .map(|n| vec![n])
                .map_err(|_| de::Error::custom("category id must be a non-negative u32"))
        }

        fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            value
                .parse::<u32>()
                .map(|n| vec![n])
                .map_err(|_| de::Error::custom("category id string is not u32"))
        }

        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
        where
            A: de::SeqAccess<'de>,
        {
            let mut vec = Vec::new();
            while let Some(elem) = seq.next_element::<serde_json::Value>()? {
                let n = match elem {
                    serde_json::Value::Number(num) => num
                        .as_u64()
                        .and_then(|v| u32::try_from(v).ok())
                        .ok_or_else(|| de::Error::custom("category id is not u32"))?,
                    serde_json::Value::String(s) => s
                        .parse::<u32>()
                        .map_err(|_| de::Error::custom("category id string is not u32"))?,
                    _ => {
                        return Err(de::Error::invalid_type(
                            de::Unexpected::Other("expected number or string"),
                            &self,
                        ));
                    }
                };
                vec.push(n);
            }
            Ok(vec)
        }
    }

    deserializer.deserialize_any(U32OrArrayVisitor)
}

/// Deserializes a meta map where values can be either strings or arrays of strings
/// This matches the Go implementation which uses reflection to handle both cases
fn deserialize_meta_map<'de, D>(deserializer: D) -> Result<HashMap<String, Vec<String>>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::de::{self, MapAccess, Visitor};
    use std::fmt;

    struct MetaMapVisitor;

    impl<'de> Visitor<'de> for MetaMapVisitor {
        type Value = HashMap<String, Vec<String>>;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("a map of string to string or array of strings")
        }

        fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
        where
            M: MapAccess<'de>,
        {
            let mut result = HashMap::new();
            while let Some((key, value)) = map.next_entry::<String, serde_json::Value>()? {
                let patterns = match value {
                    serde_json::Value::String(s) => vec![s],
                    serde_json::Value::Array(arr) => arr
                        .into_iter()
                        .filter_map(|v| v.as_str().map(std::string::ToString::to_string))
                        .collect(),
                    _ => {
                        return Err(de::Error::invalid_type(
                            de::Unexpected::Other("expected string or array"),
                            &self,
                        ));
                    }
                };
                result.insert(key, patterns);
            }
            Ok(result)
        }
    }

    deserializer.deserialize_map(MetaMapVisitor)
}

/// Fingerprint ruleset metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FingerprintMetadata {
    /// Source URL or path
    pub source: String,
    /// Version/commit identifier
    pub version: String,
    /// Last update timestamp
    pub last_updated: SystemTime,
}

/// Category information from categories.json
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct Category {
    pub(crate) name: String,
    #[serde(default)]
    description: String,
    #[serde(default)]
    priority: u32,
}

/// Fingerprint ruleset container
#[derive(Debug, Clone)]
pub struct FingerprintRuleset {
    /// Technologies indexed by name
    pub technologies: HashMap<String, Technology>,
    /// Categories indexed by ID (u32) -> name
    pub categories: HashMap<u32, String>,
    /// Metadata about the ruleset
    pub metadata: FingerprintMetadata,
}

impl FingerprintRuleset {
    /// Empty ruleset for unit tests that do not exercise fingerprint matching.
    #[cfg(test)]
    #[must_use]
    pub fn empty_for_tests() -> Self {
        Self {
            technologies: HashMap::new(),
            categories: HashMap::new(),
            metadata: FingerprintMetadata {
                source: "test".into(),
                version: "0".into(),
                last_updated: SystemTime::now(),
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Test deserializing a technology with string fields (single values)
    #[test]
    fn test_technology_deserialize_string_fields() {
        let json = r#"{
            "cats": [1, 2],
            "website": "https://example.com",
            "html": "pattern1",
            "script": "jquery.js",
            "implies": "PHP"
        }"#;

        let tech: Technology = serde_json::from_str(json).expect("Failed to deserialize");
        assert_eq!(tech.cats, vec![1, 2]);
        assert_eq!(tech.website, "https://example.com");
        assert_eq!(tech.html, vec!["pattern1"]);
        assert_eq!(tech.script, vec!["jquery.js"]);
        assert_eq!(tech.implies, vec!["PHP"]);
    }

    /// Test deserializing a technology with array fields (multiple values)
    #[test]
    fn test_technology_deserialize_array_fields() {
        let json = r#"{
            "cats": [1],
            "html": ["pattern1", "pattern2"],
            "script": ["jquery.js", "bootstrap.js"],
            "implies": ["PHP", "MySQL"]
        }"#;

        let tech: Technology = serde_json::from_str(json).expect("Failed to deserialize");
        assert_eq!(tech.html, vec!["pattern1", "pattern2"]);
        assert_eq!(tech.script, vec!["jquery.js", "bootstrap.js"]);
        assert_eq!(tech.implies, vec!["PHP", "MySQL"]);
    }

    /// Test deserializing meta tags with string values
    #[test]
    fn test_technology_deserialize_meta_string() {
        let json = r#"{
            "meta": {
                "generator": "WordPress"
            }
        }"#;

        let tech: Technology = serde_json::from_str(json).expect("Failed to deserialize");
        assert_eq!(
            tech.meta.get("generator"),
            Some(&vec!["WordPress".to_string()])
        );
    }

    /// Test deserializing meta tags with array values
    #[test]
    fn test_technology_deserialize_meta_array() {
        let json = r#"{
            "meta": {
                "generator": ["WordPress", "Drupal"]
            }
        }"#;

        let tech: Technology = serde_json::from_str(json).expect("Failed to deserialize");
        assert_eq!(
            tech.meta.get("generator"),
            Some(&vec!["WordPress".to_string(), "Drupal".to_string()])
        );
    }

    /// Test deserializing headers map
    #[test]
    fn test_technology_deserialize_headers() {
        let json = r#"{
            "headers": {
                "Server": "Apache",
                "X-Powered-By": "PHP"
            }
        }"#;

        let tech: Technology = serde_json::from_str(json).expect("Failed to deserialize");
        assert_eq!(tech.headers.get("Server"), Some(&"Apache".to_string()));
        assert_eq!(tech.headers.get("X-Powered-By"), Some(&"PHP".to_string()));
    }

    /// Test deserializing cookies map
    #[test]
    fn test_technology_deserialize_cookies() {
        let json = r#"{
            "cookies": {
                "PHPSESSID": "",
                "laravel_session": "^eyJ"
            }
        }"#;

        let tech: Technology = serde_json::from_str(json).expect("Failed to deserialize");
        assert_eq!(tech.cookies.get("PHPSESSID"), Some(&"".to_string()));
        assert_eq!(
            tech.cookies.get("laravel_session"),
            Some(&"^eyJ".to_string())
        );
    }

    /// Test deserializing scriptSrc alias
    #[test]
    fn test_technology_deserialize_script_src_alias() {
        let json = r#"{
            "scriptSrc": ["jquery.min.js", "bootstrap.bundle.js"]
        }"#;

        let tech: Technology = serde_json::from_str(json).expect("Failed to deserialize");
        assert_eq!(tech.script, vec!["jquery.min.js", "bootstrap.bundle.js"]);
    }

    /// Test deserializing empty/default fields
    #[test]
    fn test_technology_deserialize_defaults() {
        let json = r#"{}"#;

        let tech: Technology = serde_json::from_str(json).expect("Failed to deserialize");
        assert!(tech.cats.is_empty());
        assert!(tech.website.is_empty());
        assert!(tech.headers.is_empty());
        assert!(tech.cookies.is_empty());
        assert!(tech.meta.is_empty());
        assert!(tech.script.is_empty());
        assert!(tech.scripts.is_empty());
        assert!(tech.html.is_empty());
        assert!(tech.url.is_empty());
        assert!(tech.dns.is_empty());
        assert!(tech.cert_issuer.is_empty());
        assert!(tech.js.is_empty());
        assert!(tech.implies.is_empty());
        assert!(tech.excludes.is_empty());
        assert!(tech.requires.is_empty());
        assert!(tech.requires_category.is_empty());
    }

    #[test]
    fn test_technology_deserialize_requires_and_requires_category() {
        let json = r#"{
            "requires": "WordPress",
            "requiresCategory": 1
        }"#;
        let tech: Technology = serde_json::from_str(json).expect("deserialize");
        assert_eq!(tech.requires, vec!["WordPress"]);
        assert_eq!(tech.requires_category, vec![1]);

        let json_arr = r#"{
            "requires": ["WordPress", "PHP"],
            "requiresCategory": [1, 11]
        }"#;
        let tech: Technology = serde_json::from_str(json_arr).expect("deserialize");
        assert_eq!(tech.requires, vec!["WordPress", "PHP"]);
        assert_eq!(tech.requires_category, vec![1, 11]);
    }

    /// Test deserializing dns, certIssuer, and scripts fields
    #[test]
    fn test_technology_deserialize_dns_cert_scripts() {
        let json = r#"{
            "dns": {
                "TXT": "google-site-verification",
                "MX": ["google\\.com", "aspmx"]
            },
            "certIssuer": "Let's Encrypt",
            "scripts": "function webpackJsonpCallback\\(data\\) {"
        }"#;

        let tech: Technology = serde_json::from_str(json).expect("Failed to deserialize");
        assert_eq!(
            tech.dns.get("TXT"),
            Some(&vec!["google-site-verification".to_string()])
        );
        assert_eq!(
            tech.dns.get("MX"),
            Some(&vec!["google\\.com".to_string(), "aspmx".to_string()])
        );
        assert_eq!(tech.cert_issuer, vec!["Let's Encrypt".to_string()]);
        assert_eq!(
            tech.scripts,
            vec![r"function webpackJsonpCallback\(data\) {".to_string()]
        );
    }

    /// Test deserializing a complete technology (real-world example)
    #[test]
    fn test_technology_deserialize_complete() {
        let json = r#"{
            "cats": [1, 11],
            "website": "https://wordpress.org",
            "headers": {
                "X-Powered-By": "WordPress"
            },
            "cookies": {
                "wp-settings-": ""
            },
            "meta": {
                "generator": "^WordPress\\s+([\\d.]+)?\\;version:\\1"
            },
            "html": [
                "<link[^>]+/wp-(?:content|includes)/",
                "data-flavor=\"developer\""
            ],
            "scriptSrc": "wp-(?:content|includes)/",
            "implies": ["PHP", "MySQL"]
        }"#;

        let tech: Technology = serde_json::from_str(json).expect("Failed to deserialize");
        assert_eq!(tech.cats, vec![1, 11]);
        assert_eq!(tech.website, "https://wordpress.org");
        assert_eq!(tech.headers.len(), 1);
        assert_eq!(tech.cookies.len(), 1);
        assert_eq!(tech.meta.len(), 1);
        assert_eq!(tech.html.len(), 2);
        assert_eq!(tech.script.len(), 1);
        assert_eq!(tech.implies, vec!["PHP", "MySQL"]);
    }

    /// Test Category deserialization
    #[test]
    fn test_category_deserialize() {
        let json = r#"{
            "name": "CMS",
            "description": "Content Management System",
            "priority": 10
        }"#;

        let cat: Category = serde_json::from_str(json).expect("Failed to deserialize");
        assert_eq!(cat.name, "CMS");
    }

    /// Test Category deserialization with defaults
    #[test]
    fn test_category_deserialize_defaults() {
        let json = r#"{"name": "CMS"}"#;

        let cat: Category = serde_json::from_str(json).expect("Failed to deserialize");
        assert_eq!(cat.name, "CMS");
        // description and priority should use defaults
    }

    /// Test `FingerprintMetadata` serialization roundtrip
    #[test]
    fn test_fingerprint_metadata_roundtrip() {
        let metadata = FingerprintMetadata {
            source: "https://example.com/rules".to_string(),
            version: "1.0.0".to_string(),
            last_updated: SystemTime::now(),
        };

        let json = serde_json::to_string(&metadata).expect("Failed to serialize");
        let deserialized: FingerprintMetadata =
            serde_json::from_str(&json).expect("Failed to deserialize");

        assert_eq!(deserialized.source, metadata.source);
        assert_eq!(deserialized.version, metadata.version);
    }

    /// Test mixed meta types in same object
    #[test]
    fn test_technology_deserialize_mixed_meta() {
        let json = r#"{
            "meta": {
                "generator": "WordPress",
                "author": ["John", "Jane"],
                "keywords": "single keyword"
            }
        }"#;

        let tech: Technology = serde_json::from_str(json).expect("Failed to deserialize");
        assert_eq!(
            tech.meta.get("generator"),
            Some(&vec!["WordPress".to_string()])
        );
        assert_eq!(
            tech.meta.get("author"),
            Some(&vec!["John".to_string(), "Jane".to_string()])
        );
        assert_eq!(
            tech.meta.get("keywords"),
            Some(&vec!["single keyword".to_string()])
        );
    }

    /// Test URL patterns
    #[test]
    fn test_technology_deserialize_url_patterns() {
        let json = r#"{
            "url": ["^https?://[^/]+/wp-admin/", "\\.aspx$"]
        }"#;

        let tech: Technology = serde_json::from_str(json).expect("Failed to deserialize");
        assert_eq!(tech.url.len(), 2);
        assert!(tech.url[0].contains("wp-admin"));
        assert!(tech.url[1].contains("aspx"));
    }

    /// Test JS patterns
    #[test]
    fn test_technology_deserialize_js_patterns() {
        let json = r#"{
            "js": {
                "jQuery": "",
                "jQuery.fn.jquery": "\\;version:\\1"
            }
        }"#;

        let tech: Technology = serde_json::from_str(json).expect("Failed to deserialize");
        assert_eq!(tech.js.len(), 2);
        assert_eq!(tech.js.get("jQuery"), Some(&"".to_string()));
    }

    /// Test excludes field
    #[test]
    fn test_technology_deserialize_excludes() {
        let json = r#"{
            "excludes": ["WordPress", "Drupal"]
        }"#;

        let tech: Technology = serde_json::from_str(json).expect("Failed to deserialize");
        assert_eq!(tech.excludes, vec!["WordPress", "Drupal"]);
    }

    /// Test error handling for invalid JSON
    #[test]
    fn test_technology_deserialize_invalid_json() {
        let invalid_json = r#"{
            "cats": [1, 2],
            "html": "pattern1",
            "invalid_field": {
                "nested": "invalid"
            }
        }"#;

        // Invalid JSON should fail to deserialize
        let result: Result<Technology, _> = serde_json::from_str(invalid_json);
        // This should succeed because serde ignores unknown fields by default
        // But we verify the deserialization works correctly
        assert!(result.is_ok(), "Should handle invalid fields gracefully");
    }

    /// Test error handling for wrong type in array field
    #[test]
    fn test_technology_deserialize_wrong_type_in_array() {
        let json = r#"{
            "html": [123, "pattern2"]
        }"#;

        // This should fail because html expects strings, not numbers
        let result: Result<Technology, _> = serde_json::from_str(json);
        assert!(
            result.is_err(),
            "Should fail when array contains non-string values"
        );
    }

    /// Test error handling for wrong type in meta map
    #[test]
    fn test_technology_deserialize_wrong_type_in_meta() {
        let json = r#"{
            "meta": {
                "generator": 123
            }
        }"#;

        // This should fail because meta values must be strings or arrays of strings
        let result: Result<Technology, _> = serde_json::from_str(json);
        assert!(
            result.is_err(),
            "Should fail when meta value is not string or array"
        );
    }

    /// Test error handling for malformed meta array
    #[test]
    fn test_technology_deserialize_malformed_meta_array() {
        let json = r#"{
            "meta": {
                "generator": [123, "WordPress"]
            }
        }"#;

        // The deserializer filters out non-string values, so this succeeds
        // but only "WordPress" is included (123 is filtered out)
        let result: Result<Technology, _> = serde_json::from_str(json);
        assert!(
            result.is_ok(),
            "Should handle non-string values by filtering them out"
        );
        let tech = result.unwrap();
        assert_eq!(
            tech.meta.get("generator"),
            Some(&vec!["WordPress".to_string()]),
            "Should only include string values"
        );
    }

    /// Test error handling for invalid category JSON
    #[test]
    fn test_category_deserialize_invalid_json() {
        let invalid_json = r#"{
            "name": 123
        }"#;

        // This should fail because name must be a string
        let result: Result<Category, _> = serde_json::from_str(invalid_json);
        assert!(
            result.is_err(),
            "Should fail when category name is not a string"
        );
    }

    /// Test error handling for missing required field in category
    #[test]
    fn test_category_deserialize_missing_name() {
        let json = r#"{
            "description": "Test"
        }"#;

        // This should fail because name is required (no default)
        let result: Result<Category, _> = serde_json::from_str(json);
        assert!(result.is_err(), "Should fail when category name is missing");
    }

    /// Test deserializing empty arrays for `string_or_array` fields
    #[test]
    fn test_technology_deserialize_empty_arrays() {
        // Test that empty arrays are handled correctly (should return empty Vec)
        // This is critical - empty arrays are valid and should not cause errors
        let json = r#"{
            "html": [],
            "script": [],
            "url": [],
            "implies": [],
            "excludes": []
        }"#;

        let tech: Technology = serde_json::from_str(json).expect("Failed to deserialize");
        assert!(tech.html.is_empty());
        assert!(tech.script.is_empty());
        assert!(tech.url.is_empty());
        assert!(tech.implies.is_empty());
        assert!(tech.excludes.is_empty());
    }

    /// Test deserializing empty strings in arrays
    #[test]
    fn test_technology_deserialize_empty_strings_in_arrays() {
        // Test that empty strings in arrays are preserved
        // This is critical - empty strings are valid pattern values
        let json = r#"{
            "html": ["pattern1", "", "pattern2"],
            "script": [""]
        }"#;

        let tech: Technology = serde_json::from_str(json).expect("Failed to deserialize");
        assert_eq!(tech.html.len(), 3);
        assert_eq!(tech.html[0], "pattern1");
        assert_eq!(tech.html[1], "");
        assert_eq!(tech.html[2], "pattern2");
        assert_eq!(tech.script.len(), 1);
        assert_eq!(tech.script[0], "");
    }

    /// Test deserializing empty meta map
    #[test]
    fn test_technology_deserialize_empty_meta_map() {
        // Test that empty meta map is handled correctly
        let json = r#"{
            "meta": {}
        }"#;

        let tech: Technology = serde_json::from_str(json).expect("Failed to deserialize");
        assert!(tech.meta.is_empty());
    }

    /// Test deserializing meta array with null values
    #[test]
    fn test_technology_deserialize_meta_array_with_nulls() {
        // Test that null values in meta arrays are filtered out (line 134 uses filter_map)
        // This is critical - null values should not break deserialization
        let json = r#"{
            "meta": {
                "generator": [null, "WordPress", null]
            }
        }"#;

        let tech: Technology = serde_json::from_str(json).expect("Failed to deserialize");
        assert_eq!(
            tech.meta.get("generator"),
            Some(&vec!["WordPress".to_string()]),
            "Should filter out null values and only include strings"
        );
    }

    /// Test deserializing meta array with empty strings
    #[test]
    fn test_technology_deserialize_meta_array_with_empty_strings() {
        // Test that empty strings in meta arrays are preserved
        // This is critical - empty strings are valid pattern values
        let json = r#"{
            "meta": {
                "generator": ["WordPress", "", "Drupal"]
            }
        }"#;

        let tech: Technology = serde_json::from_str(json).expect("Failed to deserialize");
        assert_eq!(
            tech.meta.get("generator"),
            Some(&vec![
                "WordPress".to_string(),
                "".to_string(),
                "Drupal".to_string()
            ]),
            "Should preserve empty strings in meta arrays"
        );
    }

    /// Test deserializing meta with empty string key
    #[test]
    fn test_technology_deserialize_meta_empty_key() {
        // Test that empty string keys in meta map are handled
        // This is an edge case - empty keys are technically valid in JSON
        let json = r#"{
            "meta": {
                "": "value",
                "generator": "WordPress"
            }
        }"#;

        let tech: Technology = serde_json::from_str(json).expect("Failed to deserialize");
        assert_eq!(tech.meta.get(""), Some(&vec!["value".to_string()]));
        assert_eq!(
            tech.meta.get("generator"),
            Some(&vec!["WordPress".to_string()])
        );
    }

    /// Test deserializing `string_or_array` with null value
    #[test]
    fn test_technology_deserialize_string_or_array_null() {
        // Test that null values are rejected for string_or_array fields
        // The visitor doesn't implement visit_none/visit_unit, so null should fail
        let json = r#"{
            "html": null
        }"#;

        let result: Result<Technology, _> = serde_json::from_str(json);
        assert!(
            result.is_err(),
            "Should fail when string_or_array field is null"
        );
    }

    /// Test deserializing meta with null value in array
    #[test]
    fn test_technology_deserialize_meta_array_mixed_with_other_types() {
        // Test that meta array with mixed types (null, number, string) filters correctly
        // This is critical - ensures filter_map works correctly
        let json = r#"{
            "meta": {
                "generator": [null, 123, "WordPress", true, "Drupal"]
            }
        }"#;

        let tech: Technology = serde_json::from_str(json).expect("Failed to deserialize");
        // Should only include string values: "WordPress" and "Drupal"
        assert_eq!(
            tech.meta.get("generator"),
            Some(&vec!["WordPress".to_string(), "Drupal".to_string()]),
            "Should filter out null, numbers, and booleans, keeping only strings"
        );
    }

    /// Test `FingerprintMetadata` with empty strings
    #[test]
    fn test_fingerprint_metadata_empty_strings() {
        // Test that empty source/version strings are handled
        // This is critical - empty strings might be valid in some contexts
        let metadata = FingerprintMetadata {
            source: "".to_string(),
            version: "".to_string(),
            last_updated: SystemTime::now(),
        };

        let json = serde_json::to_string(&metadata).expect("Failed to serialize");
        let deserialized: FingerprintMetadata =
            serde_json::from_str(&json).expect("Failed to deserialize");

        assert_eq!(deserialized.source, "");
        assert_eq!(deserialized.version, "");
    }

    /// Test Category with empty name
    #[test]
    fn test_category_deserialize_empty_name() {
        // Test that empty name string is accepted (empty string is still a string)
        // This is an edge case - empty name might be valid in some contexts
        let json = r#"{
            "name": ""
        }"#;

        let cat: Category = serde_json::from_str(json).expect("Failed to deserialize");
        assert_eq!(cat.name, "");
    }

    /// Test deserializing technology with all fields as empty arrays/strings
    #[test]
    fn test_technology_deserialize_all_empty() {
        // Test that technology with all fields empty is valid
        // This is critical - ensures defaults work correctly
        let json = r#"{
            "cats": [],
            "website": "",
            "headers": {},
            "cookies": {},
            "meta": {},
            "script": [],
            "html": [],
            "url": [],
            "js": {},
            "implies": [],
            "excludes": []
        }"#;

        let tech: Technology = serde_json::from_str(json).expect("Failed to deserialize");
        assert!(tech.cats.is_empty());
        assert!(tech.website.is_empty());
        assert!(tech.headers.is_empty());
        assert!(tech.cookies.is_empty());
        assert!(tech.meta.is_empty());
        assert!(tech.script.is_empty());
        assert!(tech.scripts.is_empty());
        assert!(tech.html.is_empty());
        assert!(tech.url.is_empty());
        assert!(tech.dns.is_empty());
        assert!(tech.cert_issuer.is_empty());
        assert!(tech.js.is_empty());
        assert!(tech.implies.is_empty());
        assert!(tech.excludes.is_empty());
        assert!(tech.requires.is_empty());
        assert!(tech.requires_category.is_empty());
    }
}