1use chrono::Datelike;
4use std::io::IsTerminal;
5use std::path::Path;
6use std::sync::{LazyLock, OnceLock};
7
8#[derive(serde::Deserialize)]
10#[serde(deny_unknown_fields, bound(deserialize = "'de: 'static"))]
11pub struct Words {
12 reserved: Vec<&'static str>,
14 alone: Vec<&'static str>,
17 pub lists: Vec<&'static str>,
20 pub aliases: Vec<(&'static str, &'static str)>,
23 elsewhere: Vec<(&'static str, &'static str)>,
26 verbs: Vec<&'static str>,
28 pub keys: Vec<&'static str>,
30 bools: Vec<&'static str>,
31 pub commands: Vec<&'static str>,
34 led: Vec<&'static str>,
36 operators: Vec<&'static str>,
38 tlds: Vec<&'static str>,
41 pub path_lead: Vec<&'static str>,
43 file_tlds: Vec<&'static str>,
46 pub secret_names: Vec<&'static str>,
48 pub secret_headers: Vec<&'static str>,
50 pub media: Vec<&'static str>,
52 pub hosts: Vec<(&'static str, &'static str)>,
55 pub mcp_hosts: Vec<(&'static str, Vec<&'static str>, &'static str, &'static str)>,
62 pub ssh: Vec<&'static str>,
64 pub stop: Vec<&'static str>,
66}
67
68pub static WORDS: LazyLock<Words> = LazyLock::new(|| crate::settings::table("words"));
69
70pub const CARD: &str = "\
71fats <url|file.pdf> fetch, outline fats u3 u3#2 u3#2 l4 page section link
72fats u3#2 <words> filter inside fats <words> web search → ids site:ex.com since:7d
73mods key:value limit:20 match:exact|words country:de js:true wait:30 (then pending) provider:plain|bd|oxy|decodo device:mobile
74more up all full json fats = status fats setup = keys fats account = balance j8.u3 = another session's id";
75
76pub const GUIDE: &str = include_str!("data/guide.md");
79
80pub fn to_guide() -> String {
83 format!("agents: {} guide = the manual (~{} tok)", bin(), ksize(crate::clean::tok(GUIDE)))
84}
85
86const HELP_FLAGS: [&str; 4] = ["--help", "-h", "—help", "–help"];
88
89pub const SCREENS: [(&str, &str); 11] = crate::settings::embed!("screens/", ".txt": "home", "ready", "yours",
92 "help", "help-mcp", "help-setup", "help-search", "tip-page", "tip-search", "setup", "telemetry");
93
94const STYLES: [(&str, u8); 6] = [("bold", 1), ("dim", 2), ("green", 32), ("red", 31), ("cyan", 36), ("/", 0)];
97
98pub const NO_HOLES: [(&str, &str); 0] = [];
100
101pub fn screen(name: &str) -> &'static str {
102 SCREENS.iter().find(|s| s.0 == name).map_or("", |s| s.1)
103}
104
105pub fn draw(text: &str, holes: &[(&str, impl AsRef<str>)]) -> String {
108 holes.iter().fold(text.to_string(), |t, (name, value)| t.replace(&format!("{{{name}}}"), value.as_ref()))
109}
110
111pub fn paint(text: &str, holes: &[(&str, impl AsRef<str>)]) -> String {
113 let plain = std::env::var_os("NO_COLOR").is_some_and(|v| !v.is_empty());
114 #[cfg(test)]
115 let plain = tests::NO_COLOR.get().unwrap_or(plain);
116 draw(&draw(text, holes), &STYLES.map(|(k, n)| (k, if plain { String::new() } else { format!("\x1b[{n}m") })))
117}
118
119pub static HUMAN: OnceLock<bool> = OnceLock::new();
122
123pub fn human(json: bool) -> bool {
125 let forced = std::env::var("FATS_HUMAN").ok().and_then(|v| crate::settings::boolean(&v));
126 let agent = json || cfg!(test) || crate::cli::FENCE.get().is_some();
127 !agent && forced.unwrap_or_else(|| std::io::stdout().is_terminal())
128}
129
130pub fn help_screen(argv: &[String]) -> Option<String> {
133 let first = argv.first().is_some_and(|a| a.eq_ignore_ascii_case("help"));
134 let topic = argv.get(1).filter(|_| first).map(|t| screen(&format!("help-{}", t.to_lowercase())));
135 let text = topic.filter(|t| !t.is_empty()).unwrap_or(screen("help"));
136 (first || argv.iter().any(|a| HELP_FLAGS.contains(&a.as_str()))).then(|| paint(text, &NO_HOLES))
137}
138
139pub fn tip(cmd: &Cmd, out: &Out, search: bool) -> Option<String> {
142 let paid = crate::fetch::keyed().iter().any(|t| t.spec().price > 0.0);
143 let keyless = !paid && out.rc != 0 && out.parts.is_empty() && out.lines.iter().any(|l| l.contains("! no_key "));
144 let page = |u: &String| paint(screen("tip-page"), &[("site", crate::fetch::site(u))]);
145 let tip = if search { Some(paint(screen("tip-search"), &NO_HOLES)) } else { cmd.urls.first().map(page) };
146 tip.filter(|_| keyless && cmd.urls.len() < 2 && cmd.verb.is_none() && !cmd.flag("dry"))
147}
148
149static BIN: OnceLock<String> = OnceLock::new();
150
151pub fn bin() -> &'static str {
154 BIN.get_or_init(|| {
155 let p = std::path::PathBuf::from(std::env::args().next().unwrap_or_default());
156 let name = p.extension().filter(|e| e.eq_ignore_ascii_case("exe")).map_or(p.file_name(), |_| p.file_stem());
157 name.map(|f| f.to_string_lossy().into_owned()).filter(|s| !s.is_empty()).unwrap_or_else(|| "fats".into())
158 })
159}
160
161pub static FIX: LazyLock<Vec<(&str, &str)>> = LazyLock::new(|| crate::settings::table("errors"));
168const RETRY: &str = "{b} {id} fresh:true";
170
171#[derive(Default)]
174pub struct At<'a> {
175 pub id: &'a str,
176 pub url: &'a str,
177 pub arg: &'a str,
178 pub done: &'a [&'a str],
179}
180
181pub fn fix(code: &str, at: &At) -> String {
185 let hit = |k: &str| k.strip_suffix('*').map_or(k == code, |p| code.starts_with(p));
186 let t = FIX.iter().find(|r| hit(r.0)).map_or(RETRY, |r| r.1);
187 let env = code == "no_key" && crate::settings::env_key(at.arg).is_some();
189 let f = draw(t, &[("b", bin()), ("id", at.id), ("url", at.url), ("arg", if env { "import-env" } else { at.arg })]);
190 if code == "no_key" && !at.arg.is_empty() && !env && HUMAN.get() != Some(&true) {
193 return format!("run {f}, give the user its 3 lines");
194 }
195 let js = f.split(' ').any(|w| w == "js:true");
197 let js = js.then(|| crate::provider::Tier::ALL.into_iter().find(|t| t.renders())).flatten().map(|t| t.spec().short);
198 let tier = js.or(f.split(' ').filter_map(|w| w.strip_prefix("provider:")).next_back());
200 let sent = tier.is_some_and(|t| at.done.contains(&t));
202 let barred = sent || f.split(' ').any(|w| w.contains(':') && at.done.contains(&w));
203 if sent
207 && (js.is_some() || crate::provider::REFUSED.contains(&code))
208 && let Some((_, arrow)) = crate::fetch::left_ask(at.id, at.url, &crate::provider::Tier::ALL, at.done, |_| true)
209 {
210 return arrow;
211 }
212 if barred {
213 let open = if at.url.is_empty() { String::new() } else { format!(" · open {} in a browser", at.url) };
214 return format!("nothing left to try{open}");
215 }
216 let toks: Vec<&str> = f.split(' ').filter(|w| !w.is_empty()).collect();
218 fn key(w: &str) -> Option<&str> {
219 w.split_once(':').map(|p| p.0).filter(|k| WORDS.keys.contains(k))
220 }
221 let later = |i: usize| key(toks[i]).is_some_and(|k| toks[i + 1..].iter().any(|w| key(w) == Some(k)));
222 let f = toks.iter().enumerate().filter(|&(i, _)| !later(i)).map(|p| *p.1).collect::<Vec<_>>().join(" ");
223 let (cmd, rest) = f.split_once(", ").map_or((f.as_str(), ""), |(c, _)| (c, &f[c.len()..]));
225 let quoted = priced(cmd, at.url);
226 if code == "budget_hit" && quoted == cmd {
228 return fix("no_key", &At::default());
229 }
230 let free = quoted != cmd && crate::provider::REFUSED.contains(&code);
231 format!("{quoted}{}{rest}", if free { " · last try not charged" } else { "" })
232}
233
234pub fn priced(cmd: &str, url: &str) -> String {
237 let c = crate::fetch::worst(cmd, url).map_or(0.0, |r| r.1);
238 if c > 0.0 { format!("{cmd} ≤${c:.4}") } else { cmd.into() }
239}
240
241#[derive(Default)]
244pub struct Flag {
245 pub code: String,
246 pub what: String,
247 pub next: String,
248 pub row: bool,
249}
250
251impl Flag {
252 pub fn bang(&self, subject: &str) -> String {
254 format!("{subject} ! {}", self.body()).trim_start().to_string()
255 }
256
257 pub fn body(&self) -> String {
259 let head = [&self.code, &self.what].iter().filter(|s| !s.is_empty()).map(|s| s.as_str()).collect::<Vec<_>>();
260 if self.next.is_empty() { head.join(" ") } else { format!("{} → {}", head.join(" "), self.next) }
261 }
262}
263
264pub fn restamp(row: &str, id: &str, url: &str) -> String {
268 let ((head, f), code) = (row.split_once(" → ").unwrap_or((row, "")), row.split(' ').nth(1).unwrap_or_default());
269 let t = FIX.iter().find(|r| r.0 == code).map_or("", |r| r.1);
272 let named = row.split(' ').nth(2).filter(|_| t.contains("{arg}") && !t.contains("{id}"));
273 let arg =
274 f.split(' ').find_map(|w| w.strip_prefix("cost:").or(w.strip_prefix("zone:"))).or(named).unwrap_or_default();
275 format!("{head} → {}{}", fix(code, &At { id, url, arg, done: &[] }), f.find(" · ").map_or("", |i| &f[i..]))
276}
277
278pub fn bang(subject: &str, code: &str, detail: &str, at: &At) -> String {
280 Flag { code: code.into(), what: detail.into(), next: fix(code, at), row: true }.bang(subject)
281}
282
283pub fn uniq<T, K: PartialEq>(it: impl IntoIterator<Item = T>, key: impl Fn(&T) -> K) -> Vec<T> {
285 let mut out: Vec<T> = Vec::new();
286 for x in it {
287 if !out.iter().any(|o| key(o) == key(&x)) {
288 out.push(x);
289 }
290 }
291 out
292}
293
294pub fn cut(s: &str, n: usize) -> &str {
296 s.char_indices().nth(n).map_or(s, |(i, _)| &s[..i])
297}
298
299pub fn ksize(n: usize) -> String {
300 match n {
301 0..1000 => n.to_string(),
302 1000..1_000_000 => format!("{:.1}k", n as f64 / 1e3),
303 _ => format!("{:.1}M", n as f64 / 1e6),
304 }
305}
306
307pub fn mib(n: u64) -> String {
309 if n >= 1 << 20 { format!("{:.0} MiB", n as f64 / (1u64 << 20) as f64) } else { format!("{} KiB", n >> 10) }
310}
311
312pub fn short(url: &str, n: usize) -> String {
314 let s = url.strip_prefix("https://").or_else(|| url.strip_prefix("http://")).unwrap_or(url);
315 let s = if s != url { s.strip_prefix("www.").unwrap_or(s) } else { s };
316 if s.chars().count() <= n { s.to_string() } else { format!("{}…", cut(s, n - 1)) }
317}
318
319#[derive(Clone, Copy, PartialEq, Debug)]
320pub enum Match {
321 Exact,
322 Words,
323 Near,
324 Topic,
325}
326
327const MATCH: [&str; 4] = ["exact", "words", "near", "topic"];
329
330impl Match {
331 pub fn name(self) -> &'static str {
332 MATCH[self as usize]
333 }
334}
335
336#[derive(Clone, Copy, Debug, PartialEq, Default)]
337pub struct Id {
338 pub job: Option<usize>,
339 pub u: usize,
340 pub sec: Option<usize>,
341 pub part: usize,
342}
343
344impl Id {
345 fn parse(t: &str) -> Option<Id> {
346 let (job, rest) = match t.strip_prefix('j').and_then(|r| r.split_once('.')) {
347 Some((j, r)) => (Some(num(j)?), r),
348 None => (None, t),
349 };
350 let rest = rest.strip_prefix('u')?;
351 let (u, sec) = rest.split_once('#').map_or((rest, None), |(u, s)| (u, Some(s)));
352 let mut id = Id { job, u: num(u)?, ..Id::default() };
353 if let Some(s) = sec {
354 let d = s.trim_end_matches(|c: char| c.is_ascii_lowercase());
355 id.sec = Some(num(d)?);
356 id.part = part_of(&s[d.len()..])?;
357 }
358 Some(id)
359 }
360
361 pub fn sec_tail(&self) -> String {
363 let part = if self.part > 0 { letters(self.part) } else { String::new() };
364 self.sec.map(|k| format!("#{k}{part}")).unwrap_or_default()
365 }
366
367 pub fn page(&self) -> String {
368 format!("{}u{}", self.job.map(|j| format!("j{j}.")).unwrap_or_default(), self.u)
369 }
370}
371
372pub fn letters(part: usize) -> String {
374 let (mut n, mut out) = (part + 1, Vec::new());
375 while n > 0 {
376 n -= 1;
377 out.push(b'a' + (n % 26) as u8);
378 n /= 26;
379 }
380 out.iter().rev().map(|&b| b as char).collect()
381}
382
383fn part_of(s: &str) -> Option<usize> {
385 Some(s.bytes().try_fold(0usize, |n, b| n.checked_mul(26)?.checked_add((b - b'a') as usize + 1))?.saturating_sub(1))
386}
387
388pub fn since_date(v: &str, today: i64) -> Option<String> {
391 let unit =
392 v.chars().last().and_then(|u| [('d', 1), ('w', 7), ('m', 30), ('y', 365)].into_iter().find(|x| x.0 == u));
393 if let Some((_, days)) = unit {
394 let count = num(&v[..v.len() - 1])?.min(100_000) as i64;
395 let (year, month, day) = civil(today - count * days);
396 return Some(format!("{year:04}-{month:02}-{day:02}"));
397 }
398 let parts: Vec<&str> = v.split('-').collect();
399 let ok = |s: &&str, len: usize, hi: usize| s.len() == len && num(s).is_some_and(|n| (1..=hi).contains(&n));
400 let fine = parts.len() <= 3 && ok(&parts[0], 4, 9999) && parts.get(1).is_none_or(|m| ok(m, 2, 12));
401 (fine && parts.get(2).is_none_or(|d| ok(d, 2, 31)))
402 .then(|| format!("{}-{}-{}", parts[0], parts.get(1).unwrap_or(&"01"), parts.get(2).unwrap_or(&"01")))
403}
404
405pub fn civil(z: i64) -> (i32, u32, u32) {
407 let d = chrono::DateTime::from_timestamp(z * 86_400, 0).unwrap_or_default().date_naive();
408 (d.year(), d.month(), d.day())
409}
410
411fn count(s: &str) -> Option<usize> {
413 let (n, k) = s.strip_suffix(['k', 'K']).map_or((s, 1.0), |n| (n, 1000.0));
414 let x = n.parse::<f64>().ok().filter(|x| x.is_finite() && *x > 0.0)? * k;
415 (1.0..1e9).contains(&x).then_some(x as usize)
416}
417
418fn secs(s: &str, lo: u64, hi: u64) -> Option<u64> {
420 s.strip_suffix('s').unwrap_or(s).parse().ok().filter(|n| (lo..=hi).contains(n))
421}
422
423fn bytes(s: &str) -> Option<u64> {
425 let l = s.to_ascii_lowercase();
426 let n = l.trim_end_matches(['b', 'i']);
427 let kib = || n.strip_suffix('k').map_or((n, 0), |n| (n, 10));
428 let (n, shift) = n.strip_suffix('m').map_or_else(kib, |n| (n, 20));
429 n.parse::<u64>().ok()?.checked_mul(1 << shift)
430}
431
432fn num(s: &str) -> Option<usize> {
433 (!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())).then(|| s.parse().ok()).flatten()
434}
435
436#[derive(Default, Debug)]
437pub struct Cmd {
438 pub ids: Vec<Id>,
439 pub jobs: Vec<usize>,
441 pub links: Vec<usize>,
442 pub media: Vec<usize>,
444 pub urls: Vec<String>,
445 pub files: Vec<String>,
446 pub reserved: Vec<&'static str>,
447 pub words: Vec<String>,
448 pub mods: Vec<(String, String)>,
449 pub sub: Vec<String>,
451 pub verb: Option<String>,
454 pub idle: bool,
457 pub ask: Option<String>,
459 pub raw: String,
460}
461
462impl Cmd {
463 pub fn has(&self, r: &str) -> bool {
464 self.reserved.contains(&r)
465 }
466
467 pub fn get(&self, k: &str) -> Option<&str> {
468 self.mods.iter().rev().find(|(a, _)| a == k).map(|(_, v)| v.as_str())
469 }
470
471 pub fn flag(&self, k: &str) -> bool {
472 self.get(k) == Some("true")
473 }
474
475 pub fn fresh(&self) -> bool {
477 self.flag("fresh") || self.flag("js")
478 }
479
480 pub fn count(&self, k: &str) -> Option<usize> {
482 self.get(k).and_then(count)
483 }
484
485 pub fn canon(&self) -> String {
488 self.with_mod("", None)
489 }
490
491 pub fn with_mod(&self, k: &str, v: Option<&str>) -> String {
493 let mut p: Vec<String> = self.verb.iter().cloned().collect();
494 p.extend(self.ids.iter().map(|i| i.page() + &i.sec_tail()));
495 p.extend(self.jobs.iter().map(|j| format!("j{j}")));
496 p.extend(self.links.iter().map(|l| format!("l{l}")));
497 p.extend(self.media.iter().map(|m| format!("m{m}")));
498 p.extend(self.urls.iter().cloned());
499 p.extend(self.files.iter().cloned());
500 p.extend(self.reserved.iter().map(|r| r.to_string()));
501 p.extend(self.words.iter().cloned());
502 p.extend(self.mods.iter().filter(|(a, _)| a != k).map(|(k, v)| format!("{k}:{v}")));
503 p.extend(v.map(|v| format!("{k}:{v}")));
504 p.join(" ")
505 }
506}
507
508fn is_url(t: &str) -> bool {
509 let l = t.to_ascii_lowercase();
510 if let Some(r) = l.strip_prefix("https://").or_else(|| l.strip_prefix("http://")) {
511 return !r.is_empty();
512 }
513 let host = l.split('/').next().unwrap_or("");
515 let labels: Vec<&str> = host.split('.').collect();
516 labels.len() >= 2
517 && labels.iter().all(|x| !x.is_empty() && x.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-'))
518 && labels.last().is_some_and(|x| x.len() >= 2 && x.bytes().all(|b| b.is_ascii_alphabetic()))
519}
520
521fn bare_tld(low: &str) -> Option<&str> {
525 low.rsplit_once('.').filter(|_| !low.contains('/')).map(|(_, tld)| tld)
526}
527
528pub fn real_host(url: &str) -> bool {
532 let host = crate::clean::host_of(url);
533 let tld = host.strip_suffix('.').unwrap_or(&host).rsplit('.').next().unwrap_or_default();
534 host.parse::<std::net::IpAddr>().is_ok() || (WORDS.tlds.contains(&tld) && askable(&host))
535}
536
537pub fn askable(host: &str) -> bool {
541 let label_ok = |l: &str| (1..=63).contains(&l.len()) && !l.starts_with('-') && !l.ends_with('-');
542 host.strip_suffix('.').unwrap_or(host).split('.').all(label_ok)
543}
544
545fn is_file(t: &str, any_id: bool) -> Result<bool, String> {
552 if t == "-" || t.starts_with('/') {
553 return Ok(true);
554 }
555 let ext = Path::new(t).extension().map(|e| e.to_string_lossy().to_ascii_lowercase());
556 let doc = ext.as_ref().is_some_and(|e| crate::fetch::doc_kind(&format!(".{e}")).is_some());
557 let file = !any_id && !t.contains("://") && (doc || filed(Path::new(t)) || crate::cli::secret(Path::new(t)));
558 match file_or_site(t, &WORDS.tlds).filter(|_| file && doc) {
559 Some(q) => Err(q),
560 None => Ok(file),
561 }
562}
563
564fn file_or_site(t: &str, tlds: &[&str]) -> Option<String> {
567 let tld = bare_tld(&t.to_lowercase()).filter(|d| tlds.contains(d) && t.matches('.').count() == 1).is_some();
568 (tld && !filed(Path::new(t))).then(|| format!("? {t}: a missing file or a site · type ./{t} or https://{t}"))
569}
570
571fn shaped(t: &str) -> bool {
579 let (b, low) = (t.as_bytes(), t.to_ascii_lowercase());
580 let drive = b.len() > 2 && b[0].is_ascii_alphabetic() && b[1] == b':' && matches!(b[2], b'/' | b'\\');
581 let segments = t.split('/').filter(|s| !s.is_empty()).count();
582 let deep = if t.starts_with('/') { segments >= 2 } else { segments >= 3 && !is_url(t) && !t.contains(':') };
583 let name = |r: &str, dot: bool| {
585 let n = r.split('/').next().unwrap_or_default();
586 n.starts_with(|c: char| c.is_ascii_alphabetic() || "_{".contains(c)) && !(dot && WORDS.tlds.contains(&n))
587 };
588 let home = |s: char| low.strip_prefix(s).is_some_and(|r| r.contains('/') && name(r, false));
589 let dot = low.strip_prefix('.').is_some_and(|r| name(r, true));
590 let lead = ["./", "../", "~/", "file:", ".\\", "..\\", "~\\", "\\\\"].iter().any(|p| low.starts_with(p));
591 drive || deep || home('~') || home('$') || dot || lead
592}
593
594pub fn local_path(f: &str) -> std::path::PathBuf {
597 f.strip_prefix("~/").map_or_else(|| f.into(), |r| std::env::home_dir().unwrap_or_default().join(r))
598}
599
600fn filed(p: &Path) -> bool {
603 crate::cli::outside(p) || p.is_file()
604}
605
606fn modifier(k: &str, v: &str) -> Result<(String, String), String> {
608 let (k, v) = alias(&k.to_ascii_lowercase(), v)?;
609 if let Some(built) = crate::settings::LIMITS.get(k.as_str()) {
611 let fit = crate::settings::fits(&k, &v).map(|_| (k.clone(), v.clone()));
612 return fit.ok_or(format!("? {k}:{v} · a number like {k}:{built}"));
613 }
614 if !WORDS.keys.contains(&k.as_str()) {
615 return Err(format!("? {k}: unknown · keys {}", WORDS.keys.join(" ")));
616 }
617 value(&k, v).map(|v| (k, v))
618}
619
620fn free_key(k: &str, v: &str) -> bool {
623 let k = k.to_ascii_lowercase();
624 let near = WORDS.keys.iter().any(|m| strsim::osa_distance(&k, m) < 2);
625 !near && alias(&k, v).is_ok_and(|a| a.0 == k) && !crate::settings::LIMITS.contains_key(k.as_str())
627}
628
629fn alias(k: &str, v: &str) -> Result<(String, String), String> {
631 let (k, v) = match k {
632 "n" => ("limit", v.to_string()),
633 "geo" | "loc" | "gl" | "country" => ("country", v.to_ascii_lowercase()),
634 "budget" => ("cost", v.to_string()),
635 "device" | "ua" => match v.to_ascii_lowercase().as_str() {
636 "mobile" | "phone" => ("device", "mobile".into()),
637 "desktop" | "pc" => ("device", "desktop".into()),
638 _ => return Err(format!("? device:{v} · use device:mobile|desktop (Oxylabs only)")),
639 },
640 "loose" => {
641 let n: u32 =
642 v.parse().map_err(|_| format!("? loose:{v} · loose takes 0..100 · or match:exact|words|near|topic"))?;
643 ("match", MATCH[[1, 50, 80].iter().filter(|&&lo| n >= lo).count()].into())
645 }
646 _ => (k, v.to_string()),
647 };
648 Ok((k.to_string(), v))
649}
650
651fn value(k: &str, v: String) -> Result<String, String> {
653 if WORDS.bools.contains(&k) {
654 let b = crate::settings::boolean(&v).ok_or_else(|| format!("? {k}:{v} · use {k}:true or {k}:false"))?;
655 return Ok(b.to_string());
656 }
657 let n = match k {
658 "hedge" => secs(&v, 0, 60).ok_or("hedge:{v} · seconds before the second provider, 0 to 60: hedge:0"),
659 "wait" => secs(&v, 0, 300).ok_or("wait:{v} · seconds before a fetch answers pending, 0 to 300: wait:30"),
660 "timeout" => secs(&v, 1, 300).ok_or("timeout:{v} · seconds for bd and oxyjs, 1 to 300: timeout:150"),
661 "max_bytes" => bytes(&v)
662 .filter(|n| (1 << 10..=crate::cli::MAX_BYTES_CEIL).contains(n))
663 .ok_or("max_bytes:{v} · 1k to 64m (KiB, MiB): max_bytes:32m"),
664 "fetch" => v.parse().ok().filter(|n| *n <= 50).ok_or("fetch:{v} · results to fetch ahead, 0 to 50: fetch:0"),
665 "limit" | "max" | "from" => count(&v).map(|n| n as u64).ok_or("{k}:{v} · {k} takes a count: {k}:20 · {k}:1k"),
666 _ => return text_value(k, v),
667 };
668 n.map(|n| n.to_string()).map_err(|q| format!("? {}", draw(q, &[("k", k), ("v", &v)])))
669}
670
671fn text_value(k: &str, v: String) -> Result<String, String> {
673 let (ok, why) = match k {
674 "match" => (MATCH.contains(&v.as_str()), "use match:exact|words|near|topic"),
675 "country" => {
676 (v.len() == 2 && v.bytes().all(|b| b.is_ascii_alphabetic()), "two letters: country:de · country:us")
677 }
678 "zone" => (
679 v.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-'),
680 "a Bright Data zone name: zone:web_unlocker1",
681 ),
682 "since" => (since_date(&v, 0).is_some(), "an age or a date: since:7d · since:2w · since:2026-01"),
683 "cost" => {
684 (v.parse::<f64>().is_ok_and(|x| x.is_finite() && x >= 0.0), "cost takes US dollars per call: cost:0.5")
685 }
686 "provider" => {
687 use crate::provider::Tier;
689 let t = Tier::parse(&v.to_ascii_lowercase()).filter(|t| !t.renders());
690 let p = t.map(|t| t.spec().short).or((v.eq_ignore_ascii_case("auto")).then_some("auto"));
691 let all: Vec<&str> = Tier::ALL.iter().filter(|t| !t.renders()).map(|t| t.spec().short).collect();
692 return p.map(String::from).ok_or(format!("? provider:{v} · use provider:auto|{}", all.join("|")));
693 }
694 "site" => {
695 let s = v.to_ascii_lowercase();
696 let s = s.strip_prefix("https://").or(s.strip_prefix("http://")).unwrap_or(&s).trim_end_matches('/');
697 let host = is_url(s).then(|| s.to_string());
698 return host.ok_or(format!("? site:{v} · a host: site:example.com · site:docs.rs/serde"));
699 }
700 _ => (true, ""),
701 };
702 if ok { Ok(v) } else { Err(format!("? {k}:{v} · {why}")) }
703}
704
705fn repair(argv: &[String]) -> (Vec<String>, Vec<String>) {
708 let s = argv.join(" ");
709 let s = s.trim().trim_matches('`').trim();
710 let s = s.strip_prefix("fats ").unwrap_or(s);
711 let (mut out, mut flagged): (Vec<String>, Vec<String>) = (Vec::new(), Vec::new());
712 let mut it = s.split_whitespace().map(|t| t.trim_matches(|c| matches!(c, '"' | '\'' | '`'))).peekable();
713 while let Some(t) = it.next() {
714 if t.is_empty() || t == "--" {
716 continue;
717 }
718 let mut t = t.to_string();
719 if t.starts_with(['U', 'J']) && t[1..].starts_with(|c: char| c.is_ascii_digit()) {
721 t = t.to_lowercase();
722 }
723 let job =
724 t.split_once(['/', ':']).filter(|(a, b)| a.strip_prefix('j').and_then(num).is_some() && b.starts_with('u'));
725 if let Some((a, b)) = job {
726 t = format!("{a}.{b}");
727 }
728 let sec = t.strip_prefix('u').and_then(|r| r.split_once('.')).filter(|(a, b)| num(a).and(num(b)).is_some());
729 if let Some((a, b)) = sec {
730 t = format!("u{a}#{b}");
731 }
732 if let Some(on) = [("-v", "verbose:true"), ("--json", "json:true")].iter().find(|s| s.0 == t) {
735 t = on.1.into();
736 } else if let Some(r) = t.strip_prefix("--").filter(|r| *r != "help" && WORDS.reserved.contains(r)) {
737 t = r.to_string();
738 flagged.push(t.clone());
739 } else if t == "-n" && it.peek().is_some_and(|n| num(n).is_some()) {
740 t = format!("limit:{}", it.next().unwrap_or_default());
741 } else if let Some((k, v)) = t.split_once('=')
742 && !k.is_empty()
743 && k.bytes().all(|b| b.is_ascii_lowercase())
744 && !v.is_empty()
745 {
746 t = format!("{k}:{v}");
747 }
748 if t == "l" && it.peek().is_some_and(|n| num(n).is_some()) {
750 t = format!("l{}", it.next().unwrap_or_default());
751 }
752 if let (Some(r), Some(prev)) = (t.strip_prefix('#'), out.last_mut())
753 && num(r).is_some()
754 && Id::parse(prev).is_some_and(|i| i.sec.is_none())
755 {
756 prev.push_str(&t);
757 continue;
758 }
759 out.push(t);
760 }
761 (undecorate(out), flagged)
762}
763
764fn undecorate(toks: Vec<String>) -> Vec<String> {
770 let first = toks.first().map(|t| t.to_ascii_lowercase()).unwrap_or_default();
771 let job = first.strip_prefix('j').and_then(num).is_some();
772 let url = ["http://", "https://"].iter().any(|s| first.starts_with(s));
773 if !(Id::parse(&first).is_some() || job || url || ["setup", "stats", "config"].contains(&first.as_str())) {
774 return toks;
775 }
776 let (mut group, mut dot) = (false, false);
777 let mut keep = |t: &String| {
778 let inside = group || t.starts_with('(');
779 group = inside && !t.ends_with(')');
780 dot = (dot || t == "·") && key_value(t).is_none();
781 let time = t.strip_prefix(['~', '≈']).and_then(|r| r.strip_suffix('s')).is_some_and(|n| num(n).is_some());
782 !(inside || dot || t.starts_with('≤') || time)
784 };
785 toks.into_iter().filter(|t| keep(t)).collect()
786}
787
788fn key_value(t: &str) -> Option<(&str, &str)> {
790 let (k, v) = t.split_once(':')?;
791 let key = !k.is_empty() && k.bytes().all(|b| b.is_ascii_alphabetic() || b == b'_');
792 let scheme = ["http", "https"].contains(&k.to_ascii_lowercase().as_str());
793 (key && !scheme && !v.is_empty() && !v.starts_with('/')).then_some((k, v))
794}
795
796fn typo(w: &str, led: bool) -> Option<&'static str> {
801 let w = w.to_lowercase();
802 if WORDS.reserved.contains(&w.as_str()) {
803 return None; }
805 let extra = if led { &WORDS.led[..] } else { &[] };
806 let max = |r: &str| if led { 2.min((r.len() - 1) / 2) } else { 1 };
807 WORDS.commands.iter().chain(extra).copied().find(|r| (1..=max(r)).contains(&strsim::osa_distance(&w, r)))
808}
809
810enum Class {
811 Id(Id),
812 Job(usize),
813 Link(usize),
814 Media(usize),
815 Url(String),
816 File(String),
817 Res(&'static str),
818 Mod(String, String),
819 Num(String),
820 Word,
821}
822
823pub fn parse(argv: &[String]) -> Cmd {
824 let (mut toks, flagged) = repair(argv);
825 let mut cmd = Cmd { raw: toks.join(" "), ..Cmd::default() };
826 let lead = toks.iter().position(|t| !matches!(class_of(t, false, false, true), Ok(Class::Mod(..))));
828 cmd.verb = lead.filter(|&i| WORDS.verbs.contains(&toks[i].to_lowercase().as_str())).map(|i| toks.remove(i));
829 if let Some(i) = lead.filter(|_| cmd.verb.is_none()) {
830 own_words(&mut cmd, &mut toks, i);
831 }
832 let first_help = cmd.verb.is_none() && lead.is_some_and(|i| toks[i].eq_ignore_ascii_case("help"));
835 if first_help || toks.iter().any(|t| HELP_FLAGS.contains(&t.as_str())) {
836 toks = vec!["help".into()];
837 }
838 let has_id = toks.iter().any(|t| Id::parse(t).is_some());
839 let (mut cls, mut any_id) = (Vec::new(), false);
840 for t in &toks {
841 match class_of(t, has_id, any_id, cmd.verb.is_some()) {
842 Ok(Class::File(f)) if !crate::cli::outside(&local_path(&f)) && local_path(&f).is_dir() => {
845 cmd.ask.get_or_insert(format!("? {f} is a directory · name a file in it"));
846 }
847 Ok(c) => {
848 any_id |= matches!(c, Class::Id(_));
849 cls.push((t.clone(), c));
850 }
851 Err(q) => {
852 cmd.ask.get_or_insert(q);
853 }
854 }
855 }
856 as_words(&mut cls);
857 let search = cmd.verb.is_none() && !cls.iter().any(|p| matches!(p.1, Class::Id(_) | Class::File(_)));
863 let words: Vec<&String> = cls.iter().filter(|p| search && matches!(p.1, Class::Word)).map(|p| &p.0).collect();
864 if let Some(t) = words.first().filter(|_| words.iter().all(|t| is_flag(t))) {
865 let name = t.trim_start_matches(['-', '–', '—']);
866 let fix =
867 if WORDS.bools.contains(&name) { format!("mod: {name}:true") } else { format!("keys: {} setup", bin()) };
868 cmd.ask.get_or_insert(format!("! unknown flag {t} · {fix} · help: {} --help", bin()));
869 }
870 let kinds: Vec<&(String, Class)> =
873 cls.iter().filter(|p| !matches!(p.1, Class::Mod(..) | Class::Res("json"))).collect();
874 let led = matches!(kinds[..], [(_, Class::Word), (_, Class::Url(_) | Class::Id(_)), ..]);
875 let (lone, none) = (matches!(kinds[..], [(_, Class::Word)]), kinds.is_empty());
876 if let [(t, Class::Url(_))] = kinds[..]
878 && let Some(q) = file_or_site(t, &WORDS.file_tlds)
879 {
880 cmd.ask.get_or_insert(q);
881 }
882 sort_into(&mut cmd, kinds.len() == 1, cls, any_id);
883 if crate::cli::is_search(&cmd) {
886 (cmd.files, cmd.words) = std::mem::take(&mut cmd.words).into_iter().partition(|w| w.contains('\\'));
887 }
888 flag_word(&mut cmd, &flagged);
889 cmd.idle = none && cmd.get("site").is_none() || cmd.ask.is_some();
890 if cmd.verb.is_none() && (led || lone) {
891 ask_typo(&mut cmd, led);
892 }
893 if cmd.ask.is_some() && cmd.words.last().is_some_and(|w| w.eq_ignore_ascii_case("json")) {
895 cmd.words.pop();
896 cmd.reserved.push("json");
897 }
898 cmd
899}
900
901fn flag_word(cmd: &mut Cmd, flagged: &[String]) {
904 let page = !(cmd.ids.is_empty() && cmd.urls.is_empty() && cmd.files.is_empty() && cmd.jobs.is_empty());
905 let Some(f) = flagged.iter().find(|f| !page && cmd.words.contains(f)) else { return };
906 let rest = cmd.words.iter().filter(|w| *w != f).map(String::as_str).collect::<Vec<_>>().join(" ");
907 let (b, search) = (bin(), "is a mod, not a search word · search first:");
908 cmd.ask.get_or_insert(format!("? --{f} {search} {b} {rest} · then: {b} u1 {f}"));
909}
910
911fn class_of(t: &str, has_id: bool, any_id: bool, verb: bool) -> Result<Class, String> {
915 let low = t.to_lowercase();
916 if let Some(id) = Id::parse(t) {
917 return Ok(Class::Id(id));
918 }
919 if let Some(n) = t.strip_prefix('j').and_then(num) {
920 return Ok(Class::Job(n));
921 }
922 if let Some(n) = t.strip_prefix('l').and_then(num) {
923 return Ok(Class::Link(n));
924 }
925 if let Some(n) = t.strip_prefix('m').and_then(num).filter(|_| has_id) {
927 return Ok(Class::Media(n));
928 }
929 if let Some((a, w)) = t.split_once(':')
930 && Id::parse(a).is_some_and(|i| i.sec.is_some())
931 && w.split('-').all(|x| num(x).is_some())
932 {
933 return Err(format!("? {t}: line windows are not in v1 · read the section: {} {a}", bin()));
935 }
936 let alias = WORDS.aliases.iter().find(|a| !verb && (a.0 == low || a.0 == t)).map(|a| a.1);
938 if let Some(r) = WORDS.reserved.iter().copied().find(|r| *r == low).or(alias) {
939 return Ok(Class::Res(r));
940 }
941 if shaped(t) && !low.starts_with("file:") && !(has_id && t.starts_with('.') && !t.contains(['/', '\\'])) {
944 return Ok(Class::File(t.to_string()));
946 }
947 if low.starts_with("file:") {
948 let path = url::Url::parse(t).ok().filter(|u| u.scheme() == "file" && u.host().is_none());
952 let path = path.and_then(|u| u.to_file_path().ok()).map(|p| Class::File(p.to_string_lossy().into_owned()));
953 return path.ok_or(format!("? {t}: a file URL names a local path: {} /path/to/file", bin()));
954 }
955 if let Some((k, v)) = key_value(t) {
956 if WORDS.operators.contains(&k.to_ascii_lowercase().as_str()) || !has_id && free_key(k, v) {
959 return Ok(Class::Word);
960 }
961 return modifier(k, v).map(|(k, v)| Class::Mod(k, v));
962 }
963 if is_file(t, has_id)? {
964 return Ok(Class::File(t.to_string()));
965 }
966 if !any_id && is_url(t) && bare_tld(&low).is_none_or(|tld| WORDS.tlds.contains(&tld)) {
967 return Ok(Class::Url(if low.starts_with("http") { t.to_string() } else { format!("https://{t}") }));
968 }
969 if num(t).is_some() {
970 return Ok(Class::Num(t.to_string()));
971 }
972 if t.len() > 1
973 && t.trim_start_matches(['u', 'j', 'l']).len() + 1 == t.len()
974 && t[1..].bytes().all(|b| b.is_ascii_digit())
975 {
976 return Err(format!("? {t}: out of range"));
978 }
979 Ok(Class::Word)
980}
981
982fn as_words(cls: &mut [(String, Class)]) {
988 let free = cls.iter().any(|(t, c)| matches!(c, Class::Word | Class::Num(_)) && !is_flag(t));
989 let lead = cls.iter().position(|(t, c)| !matches!(c, Class::Mod(..)) && !is_flag(t));
990 for (i, (t, c)) in cls.iter_mut().enumerate() {
991 let typed = Some(i) == lead && !t.bytes().any(|b| b.is_ascii_uppercase());
992 if matches!(c, Class::Url(_)) && bare_tld(&t.to_lowercase()).is_some() && free && !typed {
993 *c = Class::Word;
994 }
995 }
996 if cls.iter().any(|p| matches!(p.1, Class::Word)) {
1001 for (t, c) in cls.iter_mut() {
1002 if let Class::File(p) = c
1003 && (p == "-" || !shaped(t) && Path::new(p).extension().is_none() && !filed(&local_path(p)))
1004 {
1005 *c = Class::Word;
1006 }
1007 }
1008 }
1009}
1010
1011fn is_flag(t: &str) -> bool {
1013 t.len() > 1 && t.starts_with(['-', '–', '—'])
1014}
1015
1016fn sort_into(cmd: &mut Cmd, alone: bool, cls: Vec<(String, Class)>, any_id: bool) {
1021 let words = cls.iter().filter(|(_, c)| matches!(c, Class::Word)).count();
1022 let nums = cls.iter().filter(|(_, c)| matches!(c, Class::Num(_))).count();
1023 let pinned = cls.iter().any(|(_, c)| matches!(c, Class::Mod(k, _) if k == "match"));
1025 let free = words > 0 || nums > 1 || (nums > 0 && (!any_id || pinned));
1026 let page = cls.iter().any(|(_, c)| matches!(c, Class::Id(_) | Class::Url(_) | Class::File(_)));
1027 let lead = cls.iter().position(|(_, c)| matches!(c, Class::Res(_) | Class::Word | Class::Num(_)));
1028 let index = lead.is_some_and(|i| matches!(cls[i].1, Class::Res("stats")));
1030 let read = index || cls.iter().any(|(_, c)| matches!(c, Class::Id(_) | Class::File(_)));
1033 let last = cls.iter().rposition(|(_, c)| !matches!(c, Class::Mod(..)));
1034 let list = |i, r: &str| index || Some(i) == lead && any_id && WORDS.lists.contains(&r);
1035 for (i, (t, c)) in cls.into_iter().enumerate() {
1036 match c {
1037 Class::Res(r) if r == "json" && Some(i) == last && read => cmd.reserved.push(r),
1038 Class::Id(i) => cmd.ids.push(i),
1039 Class::Job(j) => cmd.jobs.push(j),
1040 Class::Link(l) => cmd.links.push(l),
1041 Class::Media(m) => cmd.media.push(m),
1042 Class::Url(u) => cmd.urls.push(u),
1043 Class::File(f) => cmd.files.push(f),
1044 Class::Mod(k, v) => cmd.mods.push((k, v)),
1045 Class::Res(r) if !free && (alone || !page || !WORDS.alone.contains(&r)) || list(i, r) => {
1046 cmd.reserved.push(r)
1047 }
1048 Class::Num(n) if cmd.reserved.iter().any(|r| WORDS.lists.contains(r)) => cmd.words.push(n),
1049 Class::Num(n) if !free => {
1050 let q = number_ask(cmd, &n);
1051 cmd.ask.get_or_insert(q);
1052 }
1053 _ => cmd.words.push(t),
1054 }
1055 }
1056}
1057
1058fn number_ask(cmd: &Cmd, n: &str) -> String {
1060 let b = bin();
1061 match cmd.ids.last() {
1062 Some(i) => {
1063 let (full, page) = (cmd.canon(), i.page());
1064 format!("? {n}: link → {b} {full} l{n} · section → {b} {page}#{n} · text → {b} {full} {n} match:words")
1065 }
1066 None => format!("? {n}: link → {b} l{n} · text → {b} {n} match:words"),
1067 }
1068}
1069
1070fn own_words(cmd: &mut Cmd, toks: &mut Vec<String>, i: usize) {
1074 let at = |k: usize| toks.get(i + k).map(|t| t.to_lowercase()).unwrap_or_default();
1075 let (verb, on, switches) =
1076 (toks[i].to_lowercase(), ["on", "off", "stop"].contains(&at(2).as_str()), crate::settings::SWITCHES);
1077 let own = |t: &String| {
1078 !HELP_FLAGS.contains(&t.as_str())
1079 && t != "json"
1080 && !matches!(class_of(t, false, false, true), Ok(Class::Mod(..)))
1081 };
1082 let n = match (verb.as_str(), at(1).as_str()) {
1083 ("setup", w) if switches.contains(&w) || w == "plain" => 1 + usize::from(on),
1084 ("setup", "telemetry" | "mcp") => 1 + usize::from(toks.get(i + 2).is_some_and(own)),
1086 ("telemetry", "show") | ("setup", "import-env") => 1,
1087 ("config", "set") => 3 + toks.iter().skip(i + 4).take_while(|t| own(t)).count(),
1089 ("config", "unset") => 2,
1090 _ => 0,
1091 };
1092 let sub = toks.drain(i + 1..(i + 1 + n).min(toks.len())).enumerate();
1093 let low =
1094 |(k, t): (usize, String)| if k > 1 { t } else { t.to_lowercase().replacen("plain", "free", (k == 0).into()) };
1095 cmd.sub = sub.map(low).collect();
1096 if cmd.sub.len() > 3 {
1097 let v = cmd.sub.split_off(2).join(" ");
1098 cmd.sub.push(v);
1099 }
1100 let word = |t: &&String| own(t) && matches!(class_of(t, false, false, true), Ok(Class::Word));
1101 let Some(w) = toks[i + 1..].iter().find(word).filter(|_| verb == "setup") else { return };
1102 let near =
1103 switches.into_iter().chain(["on", "off", "stop"]).find(|n| strsim::osa_distance(&w.to_lowercase(), n) == 1);
1104 let (raw, b, all) = (&cmd.raw, bin(), switches.join("|"));
1105 let fix = near.map_or(format!(" · {b} setup <{all}|plain> [on|off|stop] · zone:<name>"), |n| {
1106 format!(" → {b} {}", raw.replace(w.as_str(), n))
1107 });
1108 cmd.ask = Some(format!("? {raw}{fix}"));
1109}
1110
1111fn ask_typo(cmd: &mut Cmd, led: bool) {
1114 let (Some(w), b) = (cmd.words.first().cloned(), bin()) else { return };
1115 if let Some((_, why)) = WORDS.elsewhere.iter().find(|e| !led && e.0.split(' ').any(|o| w.eq_ignore_ascii_case(o))) {
1116 cmd.ask.get_or_insert(format!("! {w}{} · {}", draw(why, &[("b", b)]), to_guide()));
1117 }
1118 if let Some(r) = typo(&w, led) {
1119 let fixed: Vec<&str> = cmd.raw.split(' ').map(|t| if t == w { r } else { t }).collect();
1120 let q = format!("? {w}: a command? {b} {} · a web search: {b} search {}", fixed.join(" "), cmd.raw);
1121 cmd.ask.get_or_insert(q);
1122 }
1123}
1124
1125#[derive(Default)]
1127pub struct Out {
1128 pub lines: Vec<String>,
1129 pub rc: i32,
1130 pub rec: Box<serde_json::Map<String, serde_json::Value>>,
1132 pub parts: Vec<Out>,
1134}
1135
1136impl Out {
1137 pub fn new(lines: Vec<String>) -> Out {
1138 Out { lines, ..Out::default() }
1139 }
1140
1141 pub fn ask(line: &str) -> Out {
1143 Out { rc: 2, ..Out::new(vec![crate::setup::masked(line)]).with("error", "usage") }
1144 }
1145
1146 pub fn fail(code: &str, eq: String, hint: String) -> Out {
1148 Out { rc: 1, ..Out::new(vec![eq, hint.clone()]).with("error", code).with("hint", hint) }
1149 }
1150
1151 pub fn set(&mut self, k: &str, v: impl Into<serde_json::Value>) -> &mut Out {
1152 self.rec.insert(k.into(), v.into());
1153 self
1154 }
1155
1156 pub fn with(mut self, k: &str, v: impl Into<serde_json::Value>) -> Out {
1158 self.set(k, v);
1159 self
1160 }
1161
1162 pub fn warn(&mut self, rows: Vec<String>) {
1165 if rows.is_empty() {
1166 return;
1167 }
1168 let bang = |l: &String| l.starts_with("! ") || l.split(' ').nth(1) == Some("!");
1170 let at = self.lines.len().min(1) + self.lines.iter().skip(1).take_while(|l| bang(l)).count();
1171 self.lines.splice(at..at, rows.iter().cloned());
1172 let mut all = self.rec.remove("warnings").and_then(|w| w.as_array().cloned()).unwrap_or_default();
1173 all.extend(rows.into_iter().map(Into::into));
1174 self.set("warnings", all);
1175 }
1176
1177 pub fn cap(&mut self, max: usize, fix: &str) {
1179 let mut used = 0;
1180 let Some(keep) = self.lines.iter().skip(1).position(|l| {
1181 used += crate::clean::tok(l);
1182 used > max
1183 }) else {
1184 return;
1185 };
1186 let cut: Vec<String> = self.lines.drain(keep + 1..).collect();
1187 let t: usize = cut.iter().map(|l| crate::clean::tok(l)).sum();
1188 self.lines.push(format!("… max:{max} cut {} lines ~{t}tok → {} {fix}", cut.len(), bin()));
1189 self.set("cut", cut.len());
1190 }
1191}
1192
1193pub fn emit(o: &Out, json: bool) -> String {
1196 let text = match (json, o.parts.is_empty()) {
1197 (false, _) => o.lines.join("\n") + "\n",
1198 (true, true) => record(o, &[]),
1199 (true, false) => {
1200 let warn = o.rec.get("warnings").and_then(|w| w.as_array()).map_or(&[][..], |w| w.as_slice());
1201 o.parts.iter().map(|p| record(p, warn)).collect()
1202 }
1203 };
1204 redact(&text, &crate::settings::secrets())
1205}
1206
1207pub const MASK: &str = "***";
1208const SECRET_RUN: usize = 12;
1210const SECRET_MIN: usize = 8;
1212
1213pub fn redact(text: &str, secrets: &[String]) -> String {
1216 let (mut hide, low) = (vec![false; text.len()], text.to_ascii_lowercase());
1217 for s in secrets.iter().map(|s| s.to_ascii_lowercase()) {
1218 let at: Vec<usize> = s.char_indices().map(|c| c.0).chain([s.len()]).collect();
1219 let n = at.len() - 1;
1220 if n < SECRET_MIN {
1221 continue;
1222 }
1223 let w = n.min(SECRET_RUN);
1224 for i in 0..=n - w {
1225 let run = &s[at[i]..at[i + w]];
1226 for (j, _) in low.match_indices(run) {
1227 hide[j..j + run.len()].fill(true);
1228 }
1229 }
1230 }
1231 let mut out = String::with_capacity(text.len());
1233 for (i, c) in text.char_indices() {
1234 if !hide[i] {
1235 out.push(c);
1236 } else if i == 0 || !hide[i - 1] {
1237 out.push_str(MASK);
1238 }
1239 }
1240 out
1241}
1242
1243fn record(o: &Out, warn: &[serde_json::Value]) -> String {
1244 let mut r = o.rec.clone();
1245 if !warn.is_empty() {
1246 let mut all = warn.to_vec();
1247 if let Some(serde_json::Value::Array(own)) = r.remove("warnings") {
1248 all.extend(own);
1249 }
1250 r.insert("warnings".into(), all.into());
1251 }
1252 let text = o.lines.join("\n");
1253 for (k, v) in [
1254 ("provider", "local".into()),
1255 ("ms", 0.into()),
1256 ("cost", 0.0.into()),
1257 ("bytes_in", 0.into()),
1258 ("cache", false.into()),
1259 ("id", serde_json::Value::Null),
1260 ("url", serde_json::Value::Null),
1261 ] {
1262 r.entry(k).or_insert(v);
1263 }
1264 r.insert("bytes_out".into(), text.len().into());
1265 r.insert("lines".into(), o.lines.clone().into());
1266 r.sort_keys();
1267 serde_json::Value::Object(*r).to_string() + "\n"
1268}
1269
1270#[cfg(test)]
1271pub(crate) mod tests {
1272 use super::*;
1273
1274 thread_local! {
1275 pub(crate) static NO_COLOR: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
1278 }
1279
1280 fn c(s: &str) -> Cmd {
1281 parse(&s.split(' ').map(String::from).collect::<Vec<_>>())
1282 }
1283
1284 #[test]
1286 fn draw_fills_named_holes_only() {
1287 assert_eq!(draw("{a}+{a} {c} {\"k\": 1} {", &[("a", "1"), ("b", "2")]), "1+1 {c} {\"k\": 1} {");
1288 assert_eq!(draw("{bold}x{/}", &NO_HOLES), "{bold}x{/}");
1289 }
1290
1291 #[test]
1294 fn every_screen_fills_every_hole() {
1295 let mut fills = vec!["ready", "yours", "pages", "id", "last", "spent", "site", "label", "text", "from"];
1296 fills.extend([
1297 "status", "name", "short", "mint", "signup", "step", "rank", "free", "cost", "b", "url", "env", "level",
1298 "life",
1299 ]);
1300 let holes: Vec<(&str, &str)> = fills.iter().map(|h| (*h, "X")).collect();
1301 for (name, text) in SCREENS {
1302 let out = paint(text, &holes);
1303 let left = out.split('{').skip(1).find(|r| r.split_once('}').is_some_and(|(h, _)| !h.contains(' ')));
1304 assert!(!text.is_empty() && left.is_none(), "{name}: {left:?}");
1305 }
1306 assert_eq!(screen("help-nope"), "");
1307 assert_eq!(help_screen(&["help".into(), "nope".into()]), Some(paint(screen("help"), &NO_HOLES)));
1308 assert_eq!(help_screen(&["rust".into(), "help".into()]), None, "a search for help");
1309 }
1310
1311 const REPAIRS: &[(&str, &str)] = &[
1313 ("read u2#3", "read u2#3"),
1315 ("open u6", "open u6"),
1316 ("search cheap proxies", "search cheap proxies"),
1317 ("u2.3", "u2#3"),
1318 ("u2 #3", "u2#3"),
1319 ("\"u2#3\"", "u2#3"),
1320 ("U2#3", "u2#3"),
1321 ("`fats u2#3`", "u2#3"),
1322 ("u2#3 --full", "u2#3 full"),
1323 ("u2 -n 20", "u2 limit:20"),
1324 ("u2 n=20", "u2 limit:20"),
1325 ("u2#3 l 4", "u2#3 l4"),
1326 ("j8/u2", "j8.u2"),
1327 ("j8:u2", "j8.u2"),
1328 ("J8.U2#3b", "j8.u2#3b"),
1329 ("u3 loose:50", "u3 match:near"),
1330 ("u3 price js:1", "u3 price js:true"),
1331 ("u3 n:5 geo:FR budget:0.5", "u3 limit:5 country:fr cost:0.5"),
1332 ("ex.com ua:Phone", "https://ex.com device:mobile"),
1333 ("u3#2 full price", "u3#2 full price"),
1334 ("u3#2 links", "u3#2 links"),
1335 ("u1 links From:11", "u1 links from:11"),
1336 ("u1 iphone 15", "u1 iphone 15"),
1337 ("u1 15 match:words", "u1 15 match:words"),
1338 ("u1 -n", "u1 -n"),
1339 ("u1 -x -y", "u1 -x -y"),
1340 ("example.com", "https://example.com"),
1341 ("opencode mcp config opencode.yaml", "opencode mcp config opencode.yaml"),
1344 ("pyproject.toml build backend options", "pyproject.toml build backend options"),
1345 ("nextjs next.config.mjs", "nextjs next.config.mjs"),
1346 ("main.go error", "main.go error"),
1347 ("logo.png size", "logo.png size"),
1348 ("cargo build main.rs", "cargo build main.rs"),
1349 ("build lib.so", "build lib.so"),
1350 ("rust x.ai", "rust x.ai"),
1351 ("contact at acme.com phone", "contact at acme.com phone"),
1352 ("Purchasing.NYC Lakewood New Jersey", "Purchasing.NYC Lakewood New Jersey"),
1353 ("Booking.com hotels Lisbon", "Booking.com hotels Lisbon"),
1354 ("Booking.com", "https://Booking.com"),
1355 ("fetch docs.rs tokio", "fetch https://docs.rs tokio"),
1356 ("docs.rs tokio spawn", "https://docs.rs tokio spawn"),
1357 ("limit:5 docs.rs tokio", "https://docs.rs tokio limit:5"),
1358 ("example.com example.org", "https://example.com https://example.org"),
1360 ("Example.com Example.org limit:5", "https://Example.com https://Example.org limit:5"),
1361 ("example.com example.org rust", "https://example.com example.org rust"),
1362 ("main.rs error handling", "https://main.rs error handling"),
1363 ("rust example.com", "rust example.com"),
1364 ("example.com rust", "https://example.com rust"),
1365 ("x.co", "https://x.co"),
1366 ("a.io", "https://a.io"),
1367 ("blog.rust-lang.org", "https://blog.rust-lang.org"),
1368 ("tokio docs.rs/tokio", "https://docs.rs/tokio tokio"),
1369 ("https://main.rs", "https://main.rs"),
1370 ("https://ex.com/a?b=1", "https://ex.com/a?b=1"),
1371 ("u1 v2.0", "u1 v2.0"),
1372 ("dry:yes u1#2", "u1#2 dry:true"),
1373 ("l4", "l4"),
1374 ("help", "help"),
1375 ("u1 max_bytes:32MiB", "u1 max_bytes:33554432"),
1376 ("-h", "help"),
1377 ("--help", "help"),
1378 ("how to get help", "how to get help"),
1379 ("u1 hedge:0", "u1 hedge:0"),
1380 ("u1 hedge:5s", "u1 hedge:5"),
1381 ("u1 timeout:300", "u1 timeout:300"),
1382 ("rust news site:HTTPS://Blog.Rust-Lang.org/ since:2w", "rust news site:blog.rust-lang.org since:2w"),
1383 ("serde site:docs.rs/serde", "serde site:docs.rs/serde"),
1384 ("status", "status"),
1386 ("ls", "status"),
1387 ("--version", "version"),
1388 ("-V", "version"),
1389 ("rust status", "rust status"),
1390 ("u1 version", "u1 version"),
1391 ("status json:true", "status json:true"),
1392 ("search stat", "search stat"),
1393 ("search login", "search login"),
1394 ("stats", "stats"),
1395 ("ale", "ale"),
1396 ("yelp", "yelp"),
1398 ("fuel", "fuel"),
1399 ("jason", "jason"),
1400 ("mode", "mode"),
1401 ("acont", "acont"),
1403 ("acont limit:5", "acont limit:5"),
1404 ("yelp limit:5", "yelp limit:5"),
1405 ("go https://go.dev", "https://go.dev go"),
1406 ("rust u1", "u1 rust"),
1407 ("search fetchh https://x.com", "search https://x.com fetchh"),
1408 ("fetchh rust", "fetchh rust"),
1409 #[cfg(unix)]
1411 ("file:///tmp/a%20b.html", "/tmp/a b.html"),
1412 #[cfg(unix)]
1413 ("file://localhost/tmp/x", "/tmp/x"),
1414 #[cfg(windows)]
1415 ("file:///C:/tmp/a%20b.html", "C:\\tmp\\a b.html"),
1416 ("login", "setup"),
1418 ("Sign-In", "setup"),
1419 ("usage", "account"),
1420 ("-v", "verbose:true"),
1421 ("rust --json", "rust json:true"),
1422 ("stat json", "stats json"),
1423 ("login limit:5", "setup limit:5"),
1424 ("keys json", "setup json"),
1425 ("login page design", "login page design"),
1426 ("u1 key", "u1 key"),
1427 ("u1 install", "u1 install"),
1428 ("rust --help", "help"),
1430 ("rust —help", "help"),
1431 ("–help", "help"),
1432 ("-- rust", "rust"),
1433 ("u1 Rust — the book", "u1 Rust — the book"),
1435 ("rust — tokio", "rust — tokio"),
1436 ("tokio —the runtime", "tokio —the runtime"),
1437 ("1990 – 2000 census", "1990 – 2000 census"),
1438 ("help login", "help"),
1439 ("git rebase --onto", "git rebase --onto"),
1441 ("search -tokio rust", "search -tokio rust"),
1442 ("rust -tokio", "rust -tokio"),
1444 ("rust filetype:pdf before:2026-01", "rust filetype:pdf before:2026-01"),
1446 ("NORTHROP GRUMMAN CORP /DE/ company", "NORTHROP GRUMMAN CORP /DE/ company"),
1447 ("irs liaison committee - tei", "irs liaison committee - tei"),
1448 ("./nope.md summary", "./nope.md summary"),
1449 ("acme /etc/hosts", "/etc/hosts acme"),
1451 ("C:\\x acme", "C:\\x acme"),
1452 ("C:/x", "C:/x"),
1453 ("docs.rs tokio", "https://docs.rs tokio"),
1454 ("acme .\\secret\\plan", ".\\secret\\plan acme"),
1457 ("acme ~alice/secret", "~alice/secret acme"),
1458 ("acme ${HOME}/secret", "${HOME}/secret acme"),
1459 ("acme internal/hr/salaries", "internal/hr/salaries acme"),
1460 ("acme Documents/plan.key", "Documents/plan.key acme"),
1461 ("TCP/IP and/or AC/DC", "TCP/IP and/or AC/DC"),
1462 ("~5/10 $5/mo plan", "~5/10 $5/mo plan"),
1463 ("docs.rs/tokio/latest/tokio spawn", "https://docs.rs/tokio/latest/tokio spawn"),
1464 ("summary .env", ".env summary"),
1466 ("discord embed og:image gif", "discord embed og:image gif"),
1468 ("x foo:1 schema:org", "x foo:1 schema:org"),
1469 (".ssh/config", ".ssh/config"),
1470 ("learn .NET core .io ... .5mm", "learn .NET core .io ... .5mm"),
1471 ];
1472
1473 const ASKS: &[(&str, &str)] = &[
1475 ("u2#3 4", "? 4: link → "),
1476 ("u1 og:image", "? og: unknown · keys limit match"),
1478 ("x wiat:30", "? wiat: unknown · keys"),
1479 ("x jsn:true", "? jsn: unknown · keys"),
1480 ("rust countr:lt", "? countr: unknown · keys"),
1481 ("notes.md hello", "? notes.md: a missing file or a site · type ./notes.md or https://notes.md"),
1482 ("main.rs", "? main.rs: a missing file or a site · type ./main.rs or https://main.rs"),
1484 ("docs.rs limit:5", "? docs.rs: a missing file or a site"),
1485 ("acme phone ./src", "? ./src is a directory · name a file in it"),
1487 ("u1 js:maybe", "? js:maybe · use js:true"),
1488 ("u1 match:fuzzy", "? match:fuzzy"),
1489 ("u1 max_bytes:65m", "? max_bytes:65m · 1k to 64m"),
1490 ("u1 max_bytes:lots", "? max_bytes:lots"),
1491 ("ex.com device:tablet", "? device:tablet · use device:mobile|desktop"),
1492 ("u1 hedge:61", "? hedge:61 · seconds before the second provider, 0 to 60"),
1493 ("u1 hedge:soon", "? hedge:soon"),
1494 ("u1 timeout:301", "? timeout:301 · seconds for bd and oxyjs, 1 to 300"),
1495 ("u1 timeout:99999999", "? timeout:99999999"),
1496 ("ex.com provider:oxyjs", "? provider:oxyjs · use provider:auto|plain|bd|oxy|decodo"),
1497 ("rust since:lately", "? since:lately · an age or a date"),
1498 ("rust since:2026-13", "? since:2026-13"),
1499 ("rust site:not_a_host", "? site:not_a_host · a host"),
1500 ("stts", "? stts: a command? "),
1501 ("acount", "? acount: a command? "),
1502 ("confg", "? confg: a command? "),
1503 ("cofnig", "? cofnig: a command? "),
1504 ("verison", "? verison: a command? "),
1505 ("versoin", "? versoin: a command? "),
1506 ("rotues", "? rotues: a command? "),
1507 ("fetchh", "? fetchh: a command? fats fetch · a web search: fats search fetchh"),
1508 ("fetchh https://x.com", "? fetchh: a command? fats fetch https://x.com · a web search: fats search fetchh"),
1509 ("fecth u1", "? fecth: a command? fats fetch u1 "),
1510 ("acont u1", "? acont: a command? fats account u1 "),
1511 ("hlep u1", "? hlep: a command? fats help u1 "),
1512 ("stts json:true", "? stts: a command? fats stats json:true "),
1513 ("file://host/x", "? file://host/x: a file URL names a local path"),
1515 ("l99999999999999999999", "? l99999999999999999999: out of range"),
1516 ("u1 u99999999999999999999", "? u99999999999999999999: out of range"),
1517 ("--login", "! unknown flag --login · keys: fats setup · help: fats --help"),
1518 ("-x", "! unknown flag -x · "),
1519 ("limit:5 -x", "! unknown flag -x · "),
1520 ("–x", "! unknown flag –x · "),
1521 ("-x -y", "! unknown flag -x · "),
1523 ("--login -x", "! unknown flag --login · "),
1524 ("—", "! unknown flag — · "),
1525 ("--dry ex.com", "! unknown flag --dry · mod: dry:true · "),
1526 ("fatsearch forum --cards", "? --cards is a mod, not a search word · search first: fats fatsearch forum · "),
1528 (
1529 "rust news --full",
1530 "? --full is a mod, not a search word · search first: fats rust news · then: fats u1 full",
1531 ),
1532 ("logout", "! logout is not a fats command · "),
1533 ("install json", "! install: see docs/installation.md"),
1534 ("stts json", "? stts: a command? "),
1535 ];
1536
1537 #[test]
1539 fn tlds_and_host_shapes() {
1540 assert_eq!((WORDS.tlds.len(), WORDS.tlds[0], WORDS.tlds.last().copied()), (1437, "aaa", Some("zw")));
1541 assert_eq!(
1543 (c("rust site:wiki.corp").get("site"), c("wiki.corp/a b").urls[0].as_str()),
1544 (Some("wiki.corp"), "https://wiki.corp/a")
1545 );
1546 let ours = |o: &&&str| WORDS.keys.contains(o) || crate::settings::LIMITS.contains_key(**o);
1548 assert_eq!(WORDS.operators.iter().find(ours), None);
1549 }
1550
1551 #[test]
1554 fn real_host_needs_askable_labels() {
1555 let (l63, l64) = ("a".repeat(63), "a".repeat(64));
1556 let good = [format!("https://{l63}.com/"), "https://a-b.example.com./x".into(), "http://[::1]/".into()];
1557 let good = good.into_iter().chain(["https://xn--bcher-kva.de/".into(), "https://93.184.215.14/a".into()]);
1558 for u in good {
1559 assert!(real_host(&u), "{u}");
1560 }
1561 let bad = [format!("https://{l64}.com/"), format!("https://x.{l64}.com/"), "https://a..com/".into()];
1562 let bad = bad
1563 .into_iter()
1564 .chain(["https://-a.com/", "https://a-.com/", "https://a.-com.com/", "https://.a.com/"].map(String::from));
1565 for u in bad.chain(["https://dead.invalid/a".into(), "https://a.com../".into()]) {
1566 assert!(!real_host(&u), "{u}");
1567 }
1568 }
1569
1570 #[test]
1573 fn a_backslash_is_a_path_on_a_search() {
1574 let (path, word) = (c("u1 C:\\Users\\x"), c("u1 a\\b"));
1575 assert!(path.files == ["C:\\Users\\x"] && path.words.is_empty() && word.files.is_empty());
1576 assert_eq!((word.words, c("u1 price\\|cost").words), (vec!["a\\b".to_string()], vec!["price\\|cost".into()]));
1577 for q in ["Documents\\salaries 2026", "search a\\b rust", "2026 Documents\\salaries"] {
1578 let got = c(q);
1579 assert!(
1580 got.files.len() == 1 && got.files[0].contains('\\') && !crate::cli::is_search(&got),
1581 "{q}: {:?}",
1582 got.files
1583 );
1584 }
1585 }
1586
1587 #[test]
1590 fn a_no_key_arrow_is_one_rule() {
1591 let (b, at) = (bin(), At::default());
1592 assert_eq!(bang("u3", "no_key", "bd", &at), format!("u3 ! no_key bd → {b} setup"));
1593 let bd = format!("u3 ! no_key bd → run {b} setup bd, give the user its 3 lines");
1594 assert_eq!(bang("u3", "no_key", "bd", &At { arg: "bd", ..at }), bd, "an agent runs the key's setup");
1595 assert_eq!(
1596 restamp(&format!("! no_key bd → {b} setup bd · https://x"), "u3", ""),
1597 bd[3..].to_string() + " · https://x"
1598 );
1599 }
1600
1601 #[test]
1602 fn repair_table() {
1603 for (i, want) in REPAIRS {
1604 let got = c(i);
1605 assert!(got.ask.is_none(), "{i} → {:?}", got.ask);
1606 assert_eq!(&got.canon(), want, "input: {i}");
1607 }
1608 for (i, _) in REPAIRS {
1609 let (once, twice) = (c(i).canon(), c(&c(i).canon()).canon());
1610 assert_eq!((c(&once).words, &twice), (c(i).words, &once), "{i}: the canonical form replays");
1611 }
1612 let reading =
1614 |m: &Cmd| (m.verb.clone(), m.words.clone(), m.reserved.clone(), m.ids.iter().map(Id::page).collect());
1615 for (v, w) in WORDS.verbs.iter().flat_map(|v| ["login", "u1", "stat"].map(|w| (v, w))) {
1616 for i in [format!("limit:5 {v} {w}"), format!("{v} {w} limit:5"), format!("-v {v} {w}")] {
1617 let once = c(&i);
1618 let want: (_, _, _, Vec<String>) = reading(&once);
1619 assert!(once.verb.is_some() && once.ask.is_none(), "{i}: the verb is read");
1620 for line in [once.canon(), once.with_mod("limit", Some("3"))] {
1621 assert_eq!(reading(&c(&line)), want, "{i} → {line}: the same reading");
1622 }
1623 }
1624 }
1625 for (i, want) in ASKS {
1626 let got = c(i).ask.unwrap_or_default().replace(bin(), "fats");
1627 assert!(got.starts_with(want), "{i} → {got}");
1628 }
1629 for m in ["links", "cards", "all", "full", "media"] {
1631 let u = c(&format!("example.com/a {m}"));
1632 assert!(u.urls == ["https://example.com/a"] && u.reserved == [m] && u.words.is_empty() && u.ask.is_none());
1633 }
1634 assert!(c("u1 --cards").ask.is_none() && c("u1 --cards").reserved == ["cards"]);
1636 let searches = [
1639 ("rust news json", "rust news json"),
1640 ("json parser", "json parser"),
1641 ("example.com rust json", "rust json"),
1642 ];
1643 for (i, json, words) in searches.map(|(i, w)| (i, false, w)) {
1644 let got = c(i);
1645 assert_eq!((got.has("json"), got.words.join(" ").as_str()), (json, words), "{i}");
1646 }
1647 let mod_on = c("rust news json:true");
1648 assert!(mod_on.flag("json"));
1649 assert_eq!(mod_on.words, ["rust", "news"]);
1650 for asked in ["whoami json", "stts json"] {
1652 assert!(c(asked).has("json") && !c(asked).words.contains(&"json".to_string()), "{asked}");
1653 }
1654 assert!(c("u1 price json").has("json") && c("u1 price json").words == ["price"]);
1655 let st = c("stats rust http all json");
1657 assert!(st.has("stats") && st.has("all") && st.has("json") && st.words == ["rust", "http"], "{:?}", st.words);
1658 assert!(c("rust stats").words == ["rust", "stats"], "a search that names stats stays one");
1659 for i in ["guide all", "setup full", "account more", "login all", "keys links"] {
1662 assert!(c(i).words.is_empty() && c(i).ask.is_none(), "{i}: {:?} {:?}", c(i).words, c(i).ask);
1663 }
1664 assert_eq!((c("u1 setup").words, c("https://a.b setup").words), (vec!["setup".into()], vec!["setup".into()]));
1665 }
1666
1667 #[test]
1669 fn warnings_follow_the_cause() {
1670 let mut o = Out::new(vec!["= u1 ! js_shell T".into(), "u1 ! js_shell x → fix".into(), "[u1#1] # T".into()]);
1671 o.warn(vec!["u1 ! no_key oxy → fats setup".into()]);
1672 o.warn(vec!["u1 ! ignored device".into()]);
1673 let want =
1674 ["= u1 ! js_shell T", "u1 ! js_shell x → fix", "u1 ! no_key oxy → fats setup", "u1 ! ignored device"];
1675 assert_eq!(o.lines[..4], want);
1676 assert_eq!(o.rec["warnings"], serde_json::json!(want[2..]));
1677 let mut o = Out::fail("no_key", "= ! no_key search".into(), "! no_key oxy".into());
1679 o.warn(vec!["! no_key bd".into()]);
1680 assert_eq!(o.lines, ["= ! no_key search", "! no_key oxy", "! no_key bd"]);
1681 }
1682
1683 #[test]
1685 fn near_words() {
1686 for (a, b, n) in [
1687 ("stat", "stats", 1),
1688 ("acount", "account", 1),
1689 ("confg", "config", 1),
1690 ("cofnig", "config", 1),
1691 ("sats", "stats", 1),
1692 ("fetchh", "fetch", 1),
1693 ("sta", "stats", 2),
1694 ("acont", "account", 2),
1695 ("cinfog", "config", 2),
1696 ("rust", "status", 5),
1697 ("ab", "ba x", 3),
1698 ] {
1699 assert_eq!((strsim::osa_distance(a, b), strsim::osa_distance(b, a)), (n, n), "{a} {b}");
1700 }
1701 assert_eq!((typo("stat", false), typo("ale", false), typo("us", false)), (Some("stats"), None, None));
1702 assert_eq!((typo("stats", false), typo("yelp", false), typo("fuel", false)), (None, None, None));
1703 assert_eq!(
1704 (typo("rotues", false), typo("fetchh", false), typo("acont", false)),
1705 (Some("routes"), Some("fetch"), None)
1706 );
1707 assert_eq!(
1708 (typo("acont", true), typo("hlep", true), typo("gh", true), typo("map", true)),
1709 (Some("account"), Some("help"), None, Some("mcp"))
1710 );
1711 }
1712
1713 #[test]
1715 fn hostile_inputs() {
1716 let junk = [
1717 "", " ", "#", "u", "u#", "u1#", "u1#a", "u99999999999999999999999", "j.u1", "j1.", "l", "l-1", "::", "a:",
1718 ":b", "http:", "https://", "--", "-n", "-n x", "n=", "=5", "``", "\"", "u1 #", "u1 # 3", "ü1#2", "u1#2zz",
1719 "\u{0}", "u1\u{a0}links", "🙂 u1", "j8/u", "file:///etc/passwd", "../", "~/", "u1 l 4 l 5", "all all",
1720 ];
1721 for j in junk {
1722 let cmd = c(j);
1723 cmd.canon();
1724 let usage = |q: &String| q.starts_with("? ") || q.starts_with("! unknown flag ");
1725 assert!(cmd.ask.as_ref().is_none_or(usage), "{j} → {:?}", cmd.ask);
1726 }
1727 for a in ['a', 'u', '#', '1', ':', '.', ' ', 'l', 'j', '/'] {
1728 for b in ['a', 'u', '#', '1', ':', '.', ' ', 'l', 'j', '/'] {
1729 c(&format!("u1{a}{b}2{a}")).canon();
1730 }
1731 }
1732 }
1733
1734 #[test]
1736 fn part_ids_round_trip() {
1737 assert_eq!(
1738 [letters(0), letters(1), letters(25), letters(26), letters(27), letters(701), letters(702)],
1739 ["a", "b", "z", "aa", "ab", "zz", "aaa"]
1740 );
1741 for p in 0..20_000 {
1742 let id = Id::parse(&format!("j3.u2#7{}", letters(p))).unwrap_or_default();
1743 assert_eq!((id.job, id.u, id.sec, id.part), (Some(3), 2, Some(7), p));
1744 }
1745 assert_eq!(Id::parse("u2#7").map(|i| i.part), Some(0));
1746 assert!(Id::parse(&format!("u2#7{}", "z".repeat(40))).is_none());
1747 }
1748
1749 #[test]
1754 fn every_paid_arrow_is_priced() {
1755 let args = ["", "js:true", "provider:bd", "provider:oxy js:true", "wait:30", "timeout:30", "0.0025"];
1756 let dones: [&[&str]; 4] = [&[], &["plain", "bd"], &["plain", "oxyjs"], &["plain", "oxy", "oxyjs"]];
1757 let cases = args
1759 .into_iter()
1760 .flat_map(|a| dones.map(|d| (a, d)))
1761 .flat_map(|c| [("https://93.184.215.14/a", c), ("", c)]);
1762 let (mut paid, b) = (0, bin());
1763 for (url, (arg, done)) in cases.collect::<Vec<_>>() {
1764 let fits = |r: &&(&str, &str)| match r.0 {
1766 "budget_hit" => arg == "0.0025",
1767 "provider_timeout" => arg != "0.0025",
1768 _ => arg.is_empty() || !r.1.contains("{arg}"),
1769 };
1770 for code in FIX.iter().filter(fits).map(|r| r.0.replace('*', "403")) {
1771 let f = fix(&code, &At { id: "u3", url, arg, done });
1772 let cmd = f.split(", ").next().unwrap_or_default().split(" ≤$").next().unwrap_or_default();
1773 let mods = ["fresh:", "js:", "provider:", "timeout:"];
1774 if !cmd.starts_with(b) || !cmd.split(' ').any(|w| mods.iter().any(|k| w.starts_with(k))) {
1775 continue;
1776 }
1777 paid += 1;
1778 let words: Vec<String> = cmd.split(' ').skip(1).map(Into::into).collect();
1779 assert_eq!(parse(&words).ask, None, "{code} {arg}: {f}");
1780 let price = f.split(" ≤$").nth(1).and_then(|p| p.get(..6)).unwrap_or_default();
1781 let dry = words.iter().map(|w| if w == "u3" && !url.is_empty() { url } else { w.as_str() });
1782 let dry: Vec<String> = dry.map(Into::into).chain(["dry:true".into()]).collect();
1783 let c = crate::cache::Cache::at(crate::settings::get().cache.value.clone(), "t".into());
1784 let rows = crate::cli::plan(&parse(&dry), &c).lines.join("\n");
1785 let up = rows.split(" up to ").nth(1).and_then(|r| r.split([' ', '\n']).next()).unwrap_or("none");
1786 if !url.is_empty() {
1787 assert_eq!(format!("${price}"), up, "{code} {arg}: {f}\n{rows}");
1788 }
1789 assert!(f.starts_with(&format!("{cmd} ≤$")), "{code} {arg}: {f}");
1790 }
1791 }
1792 assert!(paid > 500, "{paid}");
1793 }
1794
1795 #[test]
1797 fn a_third_key_is_the_move() {
1798 let at = At { id: "u3", done: &["plain", "oxy", "bd", "oxyjs"], ..Default::default() };
1799 assert_eq!(fix("captcha_wall", &at), format!("{} u3 fresh:true provider:decodo", bin()));
1800 }
1801
1802 #[test]
1805 fn error_table() {
1806 let keys: Vec<&str> = FIX.iter().map(|r| r.0).collect();
1807 let mut uniq = keys.clone();
1808 uniq.sort_unstable();
1809 uniq.dedup();
1810 assert_eq!(uniq.len(), keys.len(), "a code with two fixes");
1811 let born = [include_str!("provider.rs"), include_str!("fetch.rs"), include_str!("stats.rs")].concat();
1812 let mut codes: Vec<&str> = born
1813 .split('"')
1814 .skip(1)
1815 .step_by(2)
1816 .filter(|w| w.contains('_') && w.bytes().all(|b| b.is_ascii_lowercase() || b == b'_' || b.is_ascii_digit()))
1817 .collect();
1818 codes.extend(crate::fetch::CHECK.rules.iter().map(|w| w.code).filter(|c| !c.is_empty()));
1819 codes.extend(["blocked_403", "http_502", "fetch_failed", "no_file", "not_allowed", "too_big", "offline"]);
1820 let names = ["b_algo", "result__a", "cf_chl_opt", "search_query", "status_code", "run_js", "max_results"];
1822 let names = [&names[..], &["brd_json", "dns_wait", "dns_fast_ms"]].concat();
1823 for c in codes.iter().filter(|c| !names.contains(c)) {
1824 let hit = keys.iter().any(|k| k.strip_suffix('*').map_or(k == c, |p| c.starts_with(p)));
1825 assert!(hit, "code {c} has no fix in FIX");
1826 }
1827 let at = At { id: "u3", url: "https://ex.com/a", arg: "0.0025", done: &[] };
1828 let b = bin();
1829 assert_eq!(
1830 fix("provider_timeout", &At { arg: "js:true", ..at }),
1831 format!("{b} u3 fresh:true js:true ≤$0.0030")
1832 );
1833 let at = At { id: "u3", url: "https://ex.com/a", arg: "0.0025", done: &[] };
1834 assert_eq!(
1835 fix("budget_hit", &at),
1836 format!("{b} u3 fresh:true cost:0.0025 ≤$0.0025"),
1837 "dry routes the cap: oxy no-JS + bd"
1838 );
1839 assert_eq!(fix("provider_timeout", &At { arg: "", ..at }), format!("{b} u3 fresh:true ≤$0.0040"), "one space");
1840 assert_eq!(fix("not_found", &at), format!("check the URL · search for it: {b} <words>"), "no home");
1841 let search = At { id: "provider:bd rules", url: "", ..at };
1842 assert_eq!(
1843 fix("provider_refused", &search),
1844 format!("{b} rules fresh:true provider:oxy ≤$0.0010 · last try not charged"),
1845 "one provider:, and bd's refusal is one of `provider::REFUSED`, unbilled"
1846 );
1847 let ceil = At { url: "big.html", done: &["max_bytes:64m"], ..at };
1848 assert_eq!(fix("too_big", &ceil), "nothing left to try · open big.html in a browser", "the cap in force");
1849 assert_eq!(fix("blocked_451", &at), format!("{b} u3 fresh:true provider:oxy js:true ≤$0.0015"));
1850 assert_eq!(fix("brightdata_refused", &at), format!("{b} u3 fresh:true ≤$0.0040"), "an old code: the retry");
1851 assert!(FIX.iter().all(|r| !r.1.contains("FATS_ALLOW_PRIVATE")), "a fix prints the private-address bypass");
1853 assert_eq!(fix("private_address", &at), format!("private address refused · see {b} config"));
1854 let done = At { done: &["plain", "oxy", "bd"], ..at };
1856 assert_eq!(fix("not_pdf", &done), "nothing left to try · open https://ex.com/a in a browser");
1857 let want = format!("{b} u3 fresh:true provider:oxy js:true ≤$0.0015");
1858 assert_eq!(fix("captcha_wall", &done), want, "oxyjs untried");
1859 assert_eq!(fix("provider_refused", &done), want, "a refusal's no-JS fix, oxyjs untried");
1860 let all = At { done: &["plain", "oxy", "bd", "oxyjs", "decodo", "decodojs"], url: "", ..at };
1861 assert_eq!(fix("captcha_wall", &all), "nothing left to try");
1862 let skipped = At { done: &["plain", "oxyjs", "bd"], ..at };
1864 assert_eq!(fix("captcha_wall", &skipped), format!("{b} u3 fresh:true provider:oxy ≤$0.0025"));
1865 let free = format!("{b} u3 fresh:true ≤$0.0040 · last try not charged");
1866 assert_eq!(fix("provider_error", &At { arg: "", ..all }), free, "a transient retry names no tier");
1867 let named = At { arg: "provider:oxy js:true", done: &["plain", "oxy", "bd"], ..all };
1868 assert_eq!(fix("provider_error", &named), format!("{want} · last try not charged"), "the tier left");
1869 }
1870
1871 #[test]
1873 fn since_dates() {
1874 let today = 20_738; assert_eq!(civil(today), (2026, 10, 12));
1876 assert_eq!(civil(0), (1970, 1, 1));
1877 for (v, want) in [
1878 ("7d", "2026-10-05"),
1879 ("2w", "2026-09-28"),
1880 ("1m", "2026-09-12"),
1881 ("1y", "2025-10-12"),
1882 ("0d", "2026-10-12"),
1883 ("2026", "2026-01-01"),
1884 ("2026-01", "2026-01-01"),
1885 ("2024-02-29", "2024-02-29"),
1886 ] {
1887 assert_eq!(since_date(v, today).as_deref(), Some(want), "{v}");
1888 }
1889 for v in ["", "d", "7", "7x", "26-01", "2026-1", "2026-00", "2026-01-32", "2026-01-01-01", "-7d", "é7d"] {
1890 assert_eq!(since_date(v, today), None, "{v}");
1891 }
1892 }
1893
1894 #[test]
1895 fn helpers() {
1896 assert_eq!(short("https://www.example.com/abc", 8), "example…");
1897 assert_eq!(ksize(999), "999");
1898 assert_eq!(ksize(1250), "1.2k");
1899 assert_eq!(cut("ąćę", 2), "ąć");
1900 let o = Out::new(vec!["= x".into()]);
1901 assert!(emit(&o, true).contains("\"bytes_out\":3"));
1902 }
1903
1904 #[test]
1907 fn redactor_masks_keys_and_their_runs() {
1908 let key = &["Ab3dEf6hIj9lMn2pQr5t".to_string()];
1909 let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
1910 assert_eq!(redact(&format!("Invalid api key: {}.", key[0]), key), "Invalid api key: ***.");
1911 assert_eq!(redact("echo dEf6hIj9lMn2 end", key), "echo *** end", "a 12-char run");
1912 assert_eq!(redact("dEf6hIj9lMn end", key), "dEf6hIj9lMn end", "11 chars: not a run");
1913 assert_eq!(redact("ąć Ab3dEf6hIj9lMn2pQr5t ąć", key), "ąć *** ąć");
1914 assert_eq!(redact("a sunflower b", &s(&["sunflower"])), "a *** b", "8-11 chars: whole value");
1915 assert_eq!(redact("x y xyz", &s(&["x", "xyz"])), "x y xyz", "too short to be a key");
1916 assert_eq!(redact("ąćęłńóśźż-ąćę", &s(&["ąćęłńóśźż-ąć"])), "***ę", "runs on char boundaries");
1917 }
1918}