reserve-core 0.5.1

Core lookup, catalog, and rate-limiting engine behind the reserve domain finder
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
//! Reading a plain-text registry answer; the protocol has no status codes, so every signal is weighed.

use crate::lookup::outcome::{Reason, scrub};

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum TextVerdict {
    Available,
    Taken,
    Unknown(Reason),
}

const TAKEN_MARKERS: &[&str] = &[
    "already registered",
    "is already in use",
    "domain status: registered",
    "status: registered",
    "status: connect",
    "status: active",
    "registrar:",
    "sponsoring registrar",
    "creation date",
    "created:",
    "created on",
    "registered on",
    "activation date",
    "expiry date",
    "expiration date",
    "registry expiry date",
    "nameserver",
    "nserver",
    "cannot be registered",
    "can not be registered",
    "not available for registration",
];

const AVAILABLE_MARKERS: &[&str] = &[
    // @docgen Hungary answers a free name with "Nincs talalat / No match" and nothing else, so the trailing "for" cannot be required.
    "no match",
    "no matching record",
    // @docgen Austria's whole answer for a free name is "% nothing found", which shares no substring with "not found".
    "nothing found",
    "no object found",
    // @docgen Mexico joins its words with underscores, so "Object_Not_Found" shares no substring with the spaced form.
    "object_not_found",
    // @docgen Argentina answers only this sentence, with no newline and no field, so nothing else in the reply can carry the verdict.
    "no se encuentra registrado",
    "no entries found",
    "no data found",
    "not found",
    "does not exist",
    "no such domain",
    "domain not found",
    "not registered",
    // @docgen Hong Kong's whole answer for a free name; "not registered" is not a substring of "has not been registered".
    "not been registered",
    // @docgen Israel's wording, which shares no substring with "no data found".
    "no data was found",
    "is available",
    "domain status: available",
    "status: free",
    "status: available",
    "available for registration",
];

/// @docgen A name the registry refuses to register is a real answer, never a free one.
const NOT_REGISTRABLE_MARKERS: &[&str] = &[
    "reserved word",
    "reserved name",
    "is reserved",
    "name is blocked",
    "blocked name",
    "prohibited name",
    "restricted name",
    "not permitted for registration",
    // @docgen BTCL's own spelling of "uncensored"; both are carried because the reply is matched verbatim.
    "contains unsensored word",
    "contains uncensored word",
];

const DECLINED_MARKERS: &[&str] = &[
    "tld is not supported",
    "tld not supported",
    "not supported by this registry",
    "this tld has no whois server",
    "no whois server is known",
    "access denied",
    "requests of this client are not permitted",
    "queries are not permitted",
    "not allowed for this domain category",
    "use only approved characters",
];

/// @docgen Several registries print a standing rate-limit notice on answers they served perfectly, so the bare phrase alone cannot mark a refusal.
/// @docgen The reply echoes the name asked about, so `corporate.test` would match the bare marker `rate` and read as a refusal.
pub(crate) fn refused(text: &str, domain: &str) -> bool {
    let without_name = text.replace(&domain.to_lowercase(), " ");
    REFUSAL_MARKERS
        .iter()
        .any(|marker| contains_word(&without_name, marker))
}

/// @docgen A one-word marker inside a longer word is a coincidence, so a match only counts when it stands on its own.
pub(crate) fn contains_word(haystack: &str, needle: &str) -> bool {
    if needle.is_empty() {
        return false;
    }
    let bytes = haystack.as_bytes();
    let mut from = 0;
    while let Some(rest) = haystack.get(from..) {
        let Some(at) = rest.find(needle) else {
            return false;
        };
        let start = from.saturating_add(at);
        let end = start.saturating_add(needle.len());
        let opens = start == 0
            || bytes
                .get(start.saturating_sub(1))
                .is_none_or(|byte| !byte.is_ascii_alphanumeric());
        let closes = bytes
            .get(end)
            .is_none_or(|byte| !byte.is_ascii_alphanumeric());
        if opens && closes {
            return true;
        }
        from = start.saturating_add(1);
    }
    false
}

/// @docgen Shared with the structured reader, which sees only a whole body and so needs the same refusal vocabulary.
pub(crate) const REFUSAL_MARKERS: &[&str] = &[
    "rate",
    "too many",
    "quota",
    "limit exceeded",
    "try again later",
    "temporarily unavailable",
    "service unavailable",
    "connection refused",
    "blocked",
    "denied",
    "forbidden",
    "unauthorized",
    "excessive",
    "throttle",
    "abuse",
];

const RATE_LIMIT_MARKERS: &[&str] = &[
    "limit exceeded",
    "rate limit exceeded",
    "too many requests",
    // @docgen HKIRC refuses a fast caller with this bare code and nothing else, so there is no sentence to match.
    "cmm174",
    "try again later",
    "quota exceeded",
    "quota has been exceeded",
    "temporarily unavailable",
    "service unavailable",
    "connection refused",
    "blocked",
    // @docgen Qatar answers a fast caller with this word and its own wording for the limit, and neither matched anything above.
    "blacklisted",
    "exceeded the query limit",
    "query limit",
    "quota reached",
    "limit reached",
];

/// @docgen A closing notice repeats the words a verdict is read from, so the record above it is where the verdict lives.
const NOTICE_STARTS: &[&str] = &[
    ">>> last update of whois database",
    "terms of use:",
    "note: failure to locate a record",
    "notice: the expiration date",
    "by submitting this query",
    "access to whois information is provided",
    "the data in this record is provided",
];

fn record_of(text: &str) -> &str {
    // @docgen Plenty of registries open with the notice instead of closing with it, and cutting there would throw away the answer that follows.
    let cut = NOTICE_STARTS
        .iter()
        .filter_map(|marker| text.find(marker))
        .filter(|at| carries_a_record(&text[..*at]))
        .min();
    match cut {
        Some(at) => &text[..at],
        None => text,
    }
}

/// @docgen A registry writes its own notes behind these, so a line carrying one is not a plain statement about the name.
fn record_lines(text: &str) -> String {
    text.lines()
        .map(str::trim)
        .filter(|line| !line.is_empty() && !line.starts_with(['%', '#']))
        .collect::<Vec<&str>>()
        .join("\n")
}

/// @docgen Austria answers `% nothing found` and Luxembourg `% No such domain <name>`, so a marked line can carry the answer.
/// @docgen It counts when it names the domain asked about, or when little is left once the marker is taken out.
const NOTE_RESIDUE: usize = 20;
/// @docgen These turn up in every anti-harvesting notice, so they count only where a record writes them, before a colon.
const RECORD_KEYS: &[&str] = &["registrant", "name server"];

fn opens_a_record_line(record: &str) -> bool {
    record.lines().map(str::trim).any(|line| {
        let line = line.trim_start_matches(['%', '#']).trim();
        RECORD_KEYS.iter().any(|key| {
            line.strip_prefix(key)
                .is_some_and(|rest| rest.trim_start().starts_with(':'))
        })
    })
}

fn states(record: &str, domain: &str, marker: &str) -> bool {
    let name = domain.trim().trim_end_matches('.').to_lowercase();
    record.lines().map(str::trim).any(|line| {
        let Some(note) = line.strip_prefix(['%', '#']) else {
            return unnegated(line, marker);
        };
        let note = note.trim();
        if !unnegated(note, marker) {
            return false;
        }
        // @docgen An explanation of what a missing record does not prove names no domain and leaves a whole clause behind.
        if !name.is_empty() && note.contains(&name) {
            return true;
        }
        let rest = note.replacen(marker, " ", 1);
        rest.chars()
            .filter(|letter| letter.is_alphanumeric())
            .count()
            <= NOTE_RESIDUE
    })
}

fn carries_a_record(head: &str) -> bool {
    head.lines().any(|line| {
        let line = line.trim();
        !line.is_empty() && !line.starts_with('%') && !line.starts_with('#')
    })
}

/// @docgen The registry's own free-name phrase is trusted only where it is not negated, or "not available" reads as free.
pub(crate) fn classify(raw: &str, available_phrase: &str, domain: &str) -> TextVerdict {
    let text = normalize(raw);

    if text.trim().is_empty() {
        return TextVerdict::Unknown(Reason::Malformed {
            detail: "the registry sent nothing back".to_owned(),
        });
    }

    // @docgen Read from the record alone; a throttle or a refusal can sit anywhere, so those still scan the whole reply.
    let record = record_of(&text);
    // @docgen A banner is the registry talking about itself, and reading `not found` out of one reported a whole zone free.
    let stated = record_lines(record);
    let held = TAKEN_MARKERS
        .iter()
        .any(|marker| states(record, domain, marker))
        || opens_a_record_line(record);
    let absent = AVAILABLE_MARKERS
        .iter()
        .any(|marker| states(record, domain, marker));
    let declined = DECLINED_MARKERS
        .iter()
        .find(|marker| text.contains(**marker));
    let blocked = NOT_REGISTRABLE_MARKERS
        .iter()
        .any(|marker| text.contains(*marker));
    // @docgen The reply echoes the name, so `unblocked.de` would match the bare marker `blocked` and a free name would read as throttled.
    let without_name = text.replace(&domain.to_lowercase(), " ");
    let throttled = RATE_LIMIT_MARKERS
        .iter()
        .find(|marker| contains_word(&without_name, marker));
    let by_phrase =
        !available_phrase.trim().is_empty() && unnegated(&stated, &normalize(available_phrase));

    // @docgen Throttling never describes the name, so it is checked before anything that could be read as an answer.
    if throttled.is_some() && !held {
        return TextVerdict::Unknown(Reason::RateLimited);
    }
    if let Some(marker) = declined {
        return TextVerdict::Unknown(Reason::Declined {
            detail: (*marker).to_owned(),
        });
    }

    if blocked {
        return TextVerdict::Unknown(Reason::NotRegistrable);
    }

    // @docgen An answer about some other name proves nothing about the one asked, so it must not be read either way.
    if let Some(subject) = subject_of(raw)
        && subject != domain.trim_end_matches('.').to_lowercase()
    {
        return TextVerdict::Unknown(Reason::WrongSubject {
            answered_about: subject,
        });
    }

    // @docgen In a full record "not available" usually refers to withheld contact data, so only a terse reply reads as taken.
    let terse = stated.trim().len() < 40;
    if terse && !held && (stated.contains("not available") || stated.contains("unavailable")) {
        return TextVerdict::Taken;
    }

    match (held, absent || by_phrase) {
        // @docgen A record that also carries an available phrase is still a record, so held wins and the name never reads as free.
        (true, true) => TextVerdict::Taken,
        (true, false) => TextVerdict::Taken,
        (false, true) => TextVerdict::Available,
        (false, false) => TextVerdict::Unknown(Reason::Malformed {
            detail: "the answer matched nothing we recognise".to_owned(),
        }),
    }
}

fn unnegated(haystack: &str, needle: &str) -> bool {
    if needle.is_empty() {
        return false;
    }
    let mut from = 0;
    while let Some(offset) = haystack.get(from..).and_then(|rest| rest.find(needle)) {
        let at = from + offset;
        let before = haystack.get(..at).unwrap_or_default();
        let last_word = before
            .trim_end()
            .rsplit(|c: char| !c.is_alphanumeric() && c != '\'')
            .next()
            .unwrap_or_default();

        let negated = matches!(last_word, "not" | "no" | "isn't" | "cannot" | "never")
            || before.ends_with("un")
            || before.ends_with("non");

        if !negated {
            return true;
        }
        from = at.saturating_add(needle.len().max(1));
    }
    false
}

fn subject_of(raw: &str) -> Option<String> {
    for line in raw.lines() {
        // @docgen Real replies open with a banner, so ending the scan on the first colonless line disables this guard.
        let Some((key, value)) = line.trim().split_once(':') else {
            continue;
        };
        let key = key.trim().to_lowercase();
        if matches!(
            key.as_str(),
            "domain name" | "domain" | "domainname" | "internationalized domain name"
        ) {
            let value = value.trim().trim_end_matches('.').to_lowercase();
            if !value.is_empty() && value.contains('.') {
                return Some(scrub(&value));
            }
        }
    }
    None
}

/// @docgen Collapsing spacing keeps marker matching independent of how a registry lays out its columns.
fn normalize(raw: &str) -> String {
    let mut out = String::with_capacity(raw.len());
    let mut last_was_space = false;
    for ch in raw.chars() {
        let ch = if ch == '\t' { ' ' } else { ch };
        if ch == ' ' {
            if !last_was_space {
                out.push(' ');
            }
            last_was_space = true;
        } else {
            last_was_space = false;
            out.extend(ch.to_lowercase());
        }
    }
    out
}

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

    /// @docgen Every reply below was captured from the live registry, so a change that breaks one of these has broken a real lookup.
    #[test]
    fn a_standing_notice_that_a_service_is_rate_limited_is_not_a_refusal() {
        let served = "The queried object does not exist: DOMAIN NOT FOUND\n\n             >>> Last update of WHOIS database: 2026-08-19T20:01:25.0Z <<<\n\n             Access to the whois service is rate limited. For more information, please\n             see the referenced URL.\n";
        assert_eq!(
            classify(served, "", "probe.la"),
            TextVerdict::Available,
            "this answer was served, and the notice at the foot of it is policy text"
        );
    }

    #[test]
    fn a_refusal_that_says_a_limit_was_passed_is_still_a_refusal() {
        for refusal in [
            "% Quota exceeded",
            "WHOIS LIMIT EXCEEDED - SEE WWW.PIR.ORG",
            "Too many requests, please try again later",
        ] {
            assert!(
                matches!(
                    classify(refusal, "", "probe.test"),
                    TextVerdict::Unknown(Reason::RateLimited)
                ),
                "{refusal} must never read as an answer"
            );
        }
    }

    /// @docgen The free reply carries a terms-of-use notice saying "contact the registrant", which read as a record and marked a free name taken.
    #[test]
    fn a_closing_legal_notice_never_decides_the_verdict() {
        let free = "Domain not found.\n\n            >>> Last update of WHOIS database: 2026-08-19T20:02:00Z <<<\n\n            Terms of Use: Access to WHOIS information is provided to assist persons in             determining the contents of a domain name registration record in the registry             database. Should you wish to contact the registrant, please refer to the Whois             records available through the registrar URL listed above. Queries to the Whois             services are throttled. By submitting this query, you agree to abide by this policy.\n";
        assert_eq!(
            classify(free, "Domain not found", "probe.bz"),
            TextVerdict::Available,
            "the notice mentions a registrant and throttling; the record says the name is free"
        );
    }

    /// @docgen Captured live: these three open with the notice, so cutting at it would have thrown the answer away.
    #[test]
    fn a_marked_line_answers_only_when_the_marker_is_the_whole_of_it() {
        // @docgen Registry boilerplate saying what a no-match does not prove is the exact shape that used to read as free.
        for caveat in [
            "% No match is not proof of availability.\n% Query limit reached for this client.\n",
            "% A no-match response does not guarantee availability.\n",
            "% not found does not mean the name can be registered\n",
        ] {
            assert_ne!(
                classify(caveat, "", "sazzad.test"),
                TextVerdict::Available,
                "a sentence about what a marker means is not the marker: {caveat:?}"
            );
        }

        // @docgen Iceland and Serbia answer inside a marked line with a few words around the marker.
        assert_eq!(
            classify(
                "% No entries found for query \"sazzad.is\".",
                "",
                "sazzad.is"
            ),
            TextVerdict::Available,
            "an answer naming the domain is an answer"
        );
        assert_eq!(
            classify("%ERROR:103: Domain is not registered", "", "sazzad.rs"),
            TextVerdict::Available,
            "a short code around the marker is still an answer"
        );

        // The terse machine answers stay readable, however long the name they echo.
        assert_eq!(
            classify("% nothing found", "", "sazzad.at"),
            TextVerdict::Available
        );
        assert_eq!(
            classify(
                "% No such domain a-rather-long-name-to-check-2026.lu",
                "",
                "a-rather-long-name-to-check-2026.lu"
            ),
            TextVerdict::Available,
            "the allowance must not depend on how long the name is"
        );
    }

    #[test]
    fn a_registry_saying_it_blocked_us_is_never_read_as_a_broken_answer() {
        // @docgen Qatar answers a fast caller like this, and reading it as nonsense stopped the pacer from backing off.
        for pushback in [
            "BLACKLISTED: You have exceeded the query limit for your network or IP address",
            "Query limit reached for this client, please wait",
            "% quota reached, retry shortly",
        ] {
            assert_eq!(
                classify(pushback, "", "sazzad.test"),
                TextVerdict::Unknown(Reason::RateLimited),
                "being told to slow down is pushback, not a broken answer: {pushback:?}"
            );
        }
    }

    #[test]
    fn an_anti_harvesting_notice_does_not_make_a_free_name_read_as_taken() {
        // @docgen Every registry prints one of these, and reading `registrant` out of it made a throttle read as a record.
        let notice = "The data in this record is provided for information purposes only.\n                      You agree not to use it to contact a registrant for marketing.\n                      Our name server data is likewise not for bulk collection.\n                      Query limit exceeded, please try again later.\n";
        assert_eq!(
            classify(notice, "", "sazzad.test"),
            TextVerdict::Unknown(Reason::RateLimited),
            "a throttle is the answer here, not a record"
        );

        // A record that really writes those keys is still a record.
        let record = "Domain Name: sazzad.test\n                      Registrant: Withheld\n                      Name Server: ns1.example.test\n";
        assert_eq!(classify(record, "", "sazzad.test"), TextVerdict::Taken);
    }

    #[test]
    fn a_reply_that_is_only_the_registrys_own_notes_never_reads_as_free() {
        // @docgen Every line is the service talking about itself, and one of them happens to carry the words `not found`.
        let banner = "% Whois service for the .bd zone\n                      % A name that is not found in this database may still be taken.\n                      % Query quota reached, please retry in 60 seconds.\n";
        assert_ne!(
            classify(banner, "", "sazzad.bd"),
            TextVerdict::Available,
            "a banner is not an answer about the name"
        );

        let prose = "% This server is provided for informational use only.\n                     % The absence of a record does not mean the name is available.\n";
        assert_ne!(
            classify(prose, "", "sazzad.bd"),
            TextVerdict::Available,
            "a sentence explaining what absence means is not an answer"
        );

        // The terse machine answers those same services send are still read.
        assert_eq!(
            classify("% nothing found", "", "sazzad.at"),
            TextVerdict::Available
        );
        assert_eq!(
            classify("% No such domain sazzad.lu", "", "sazzad.lu"),
            TextVerdict::Available
        );
    }

    #[test]
    fn a_notice_printed_before_the_answer_never_hides_it() {
        for (reply, zone) in [
            (
                "% TCI Whois Service. Terms of use:\n% https://tcinet.ru/documents/whois_ru_rf.pdf (in Russian)\n\nNo entries found for the selected source(s).\n",
                "probe.ru",
            ),
            (
                "% Access to RESTENA DNS-LU WHOIS information is provided to assist persons\n% in determining the content of a domain name registration record in the LU\n% registration database. The data in this record is provided by RESTENA DNS-LU\n% for information purposes only.\n\n% No such domain sazzad-reserve-probe-2026.lu\n",
                // @docgen The reply names the domain it answers about, so the fixture has to ask about that same one.
                "sazzad-reserve-probe-2026.lu",
            ),
        ] {
            assert_eq!(
                classify(reply, "", zone),
                TextVerdict::Available,
                "{zone} opens with its notice and answers underneath it"
            );
        }
    }

    #[test]
    fn a_record_that_precedes_the_notice_is_still_read() {
        let taken = "Domain Name: google.bz\nRegistrar: MarkMonitor Inc.\nCreation Date: 2006-02-12T18:08:52Z\n\n            >>> Last update of WHOIS database: 2026-08-19T20:02:00Z <<<\n\n            Terms of Use: Should you wish to contact the registrant, refer to the registrar.\n";
        assert_eq!(
            classify(taken, "Domain not found", "google.bz"),
            TextVerdict::Taken
        );
    }

    #[test]
    fn a_free_name_is_recognised_in_each_registrys_own_wording() {
        for (reply, zone) in [
            ("% nothing found", "probe.at"),
            (
                "% Whois server 4.1 serving the hu ccTLD\n\n\r\nNincs talalat / No match\r\n",
                "probe.hu",
            ),
            (
                "El dominio no se encuentra registrado en NIC Argentina",
                "probe.com.ar",
            ),
            (
                "\r\nNo_Se_Encontro_El_Objeto/Object_Not_Found\r\n",
                "probe.mx",
            ),
            ("Domain not found.\n", "probe.bz"),
        ] {
            assert_eq!(
                classify(reply, "", zone),
                TextVerdict::Available,
                "{zone} was not read as free"
            );
        }
    }

    #[test]
    fn a_registered_name_in_those_same_registries_is_never_read_as_free() {
        for (reply, zone) in [
            (
                "% Whois server 4.1 serving the hu ccTLD\n\n\r\ndomain:         index.hu\r\nrecord created: 1999-05-17\r\n",
                "index.hu",
            ),
            (
                "domain:\t\tclarin.com.ar\nregistrant:\t30500124152\nregistrar:\tnicar\nnserver:\tcash.ns.cloudflare.com ()\n",
                "clarin.com.ar",
            ),
            (
                "\r\nDomain Name:       unam.mx\r\n\r\nCreated On:        1989-03-31\r\nExpiration Date:   2027-03-30\r\nRegistrar:         AKKY ONLINE SOLUTIONS, S.A. DE C.V.\r\n",
                "unam.mx",
            ),
            (
                "Domain Name: google.bz\nRegistry Domain ID: 461b9755-DONUTS\nCreation Date: 2006-02-12T18:08:52Z\nRegistry Expiry Date: 2027-02-12T18:08:52Z\nRegistrar: MarkMonitor Inc.\n",
                "google.bz",
            ),
        ] {
            assert_eq!(classify(reply, "", zone), TextVerdict::Taken, "{zone}");
        }
    }

    #[test]
    fn a_free_name_is_read_as_free() {
        let raw = "Domain Name: example.bd\nDomain Status: Available\n\
                   Whois Server: whois.get.bd\nMessage: Domain is available";
        assert_eq!(
            classify(raw, "Domain is available", "example.bd"),
            TextVerdict::Available
        );
    }

    #[test]
    fn a_held_name_wins_over_a_status_of_error() {
        // @docgen A real registry answers a taken name with a status of error, and matching that first would call it unknown.
        let raw = "Domain Name: sample.bd\nDomain Status: Error\n\
                   Whois Server: whois.get.bd\nMessage: Domain already registered";
        assert_eq!(
            classify(raw, "Domain is available", "sample.bd"),
            TextVerdict::Taken
        );
    }

    #[test]
    fn a_full_record_reads_as_taken() {
        let raw = "Domain Name: demo.bd\nDomain Status: Registered\n\
                   Registrant's Name: Someone\nActivation Date: 14/01/2026\n\
                   Expiry Date: 14/01/2028\nPrimary DNS: a.ns.example";
        assert_eq!(
            classify(raw, "Domain is available", "demo.bd"),
            TextVerdict::Taken
        );
    }

    #[test]
    fn a_throttle_is_never_read_as_free() {
        for raw in [
            "Query rate limit exceeded, try again later",
            "WHOIS LIMIT EXCEEDED - NOT FOUND",
            "Too many requests from your address",
        ] {
            match classify(raw, "", "x.com") {
                TextVerdict::Unknown(Reason::RateLimited) => {}
                other => panic!("{raw:?} became {other:?}"),
            }
        }
    }

    #[test]
    fn a_negated_phrase_does_not_read_as_free() {
        // @docgen A registry answering only "Available" or "Not Available" turns a plain substring test into a false free on every taken name.
        assert_eq!(
            classify("Not Available", "Available", "x.au"),
            TextVerdict::Taken
        );
        assert_eq!(
            classify("Available", "Available", "example.test"),
            TextVerdict::Available
        );
    }

    #[test]
    fn attached_negation_is_caught() {
        assert!(!unnegated("this name is unavailable", "available"));
        assert!(!unnegated("this name is not available", "available"));
        assert!(unnegated("this name is available", "available"));
        assert!(!unnegated("nonavailable", "available"));
    }

    #[test]
    fn an_answer_about_another_name_is_refused() {
        let raw = "Domain Name: ac.bd\nStatus: active\nRegistrar: someone";
        match classify(raw, "", "example.ac.bd") {
            TextVerdict::Unknown(Reason::WrongSubject { answered_about }) => {
                assert_eq!(answered_about, "ac.bd");
            }
            other => panic!("expected a refusal, got {other:?}"),
        }
    }

    #[test]
    fn a_banner_before_the_record_does_not_disable_the_wrong_subject_guard() {
        // @docgen A banner or blank line opens real replies, and ending the scan there would let an answer about another name read as available.
        let raw = "% This is the registry whois server.\n%\n\n\
                   Domain Name: ac.bd\nStatus: active\nRegistrar: someone";
        match classify(raw, "", "example.ac.bd") {
            TextVerdict::Unknown(Reason::WrongSubject { answered_about }) => {
                assert_eq!(answered_about, "ac.bd");
            }
            other => panic!("a banner must not disable the guard, got {other:?}"),
        }
    }

    #[test]
    fn a_banner_before_a_no_match_still_reads_as_available() {
        let raw = "% registry banner\n\nNo match for \"NOTHING.COM\".";
        assert_eq!(classify(raw, "", "nothing.com"), TextVerdict::Available);
    }

    #[test]
    fn a_declined_extension_is_unclear_not_free() {
        let raw = "This TLD has no whois server, but you can access the whois database";
        assert!(matches!(classify(raw, "", "x.zz"), TextVerdict::Unknown(_)));
    }

    #[test]
    fn an_empty_answer_is_unclear() {
        assert!(matches!(classify("", "", "x.com"), TextVerdict::Unknown(_)));
        assert!(matches!(
            classify("   \n  ", "", "x.com"),
            TextVerdict::Unknown(_)
        ));
    }

    #[test]
    fn an_unrecognised_answer_is_unclear_not_free() {
        assert!(matches!(
            classify("something entirely unexpected", "", "x.com"),
            TextVerdict::Unknown(_)
        ));
    }

    #[test]
    fn a_classic_no_match_reads_as_free() {
        assert_eq!(
            classify("No match for \"NOTHING.COM\".", "", "nothing.com"),
            TextVerdict::Available
        );
        assert_eq!(
            classify("NOT FOUND", "", "nothing.com"),
            TextVerdict::Available
        );
        assert_eq!(
            classify("Status: free", "", "nothing.de"),
            TextVerdict::Available
        );
    }

    #[test]
    fn layout_does_not_change_the_reading() {
        let spaced = "Domain Status:\t\tAvailable\nMessage:   Domain is available";
        assert_eq!(
            classify(spaced, "Domain is available", "x.bd"),
            TextVerdict::Available
        );
    }

    #[test]
    fn a_record_that_also_says_available_still_reads_as_taken() {
        // @docgen Contact data withheld for privacy often contains "not available", which must not read as free.
        let raw = "Domain Name: x.com\nRegistrar: Example\nCreation Date: 2020-01-01\n\
                   Registrant Phone: not available";
        assert_eq!(classify(raw, "", "x.com"), TextVerdict::Taken);
    }

    #[test]
    fn a_free_name_containing_a_throttle_word_is_not_reported_as_throttled() {
        let reply = "Domain: unblocked.de\nStatus: free\n";
        assert_eq!(
            classify(reply, "", "unblocked.de"),
            TextVerdict::Available,
            "the letters in the name must not read as a rate limit"
        );
    }

    #[test]
    fn a_real_throttle_is_still_caught_beside_such_a_name() {
        let reply = "% Quota exceeded, try again later\n";
        assert!(
            matches!(
                classify(reply, "", "unblocked.de"),
                TextVerdict::Unknown(Reason::RateLimited)
            ),
            "a throttle standing as its own words is still a throttle"
        );
    }

    #[test]
    fn a_marker_only_counts_when_it_stands_as_its_own_word() {
        assert!(contains_word("quota exceeded", "quota"));
        assert!(contains_word("the rate, exceeded", "rate"));
        assert!(!contains_word("corporate.test", "rate"));
        assert!(!contains_word("unblocked.de", "blocked"));
        assert!(!contains_word("", "rate"));
    }
}