browserslist/lib.rs
1//! **oxc-browserslist** is a Rust-based implementation of [Browserslist](https://github.com/browserslist/browserslist).
2//!
3//! ## Introduction
4//!
5//! This library bundles Can I Use data, Electron versions list and Node.js releases list,
6//! so it won't and doesn't need to access any data files.
7//!
8//! Except several non-widely/non-frequently used features,
9//! this library works as same as the JavaScript-based
10//! implementation [Browserslist](https://github.com/browserslist/browserslist).
11//!
12//! ## Usage
13//!
14//! It provides a simple API for querying which accepts a sequence of strings and options [`Opts`],
15//! then returns the result.
16//!
17//! ```
18//! use browserslist::{Distrib, Opts, resolve, Error};
19//!
20//! let distribs = resolve(&["ie <= 6"], &Opts::default()).unwrap();
21//! assert_eq!(distribs[0].name(), "ie");
22//! assert_eq!(distribs[0].version(), "6");
23//! assert_eq!(distribs[1].name(), "ie");
24//! assert_eq!(distribs[1].version(), "5.5");
25//!
26//! assert_eq!(
27//! resolve(&["yuru 1.0"], &Opts::default()),
28//! Err(Error::BrowserNotFound(String::from("yuru")))
29//! );
30//! ```
31//!
32//! The result isn't a list of strings, instead, it's a tuple struct called [`Distrib`].
33//! If you need to retrieve something like JavaScript-based implementation of
34//! [Browserslist](https://github.com/browserslist/browserslist),
35//! you can convert them to strings:
36//!
37//! ```
38//! use browserslist::{Distrib, Opts, resolve, Error};
39//!
40//! let distribs = resolve(&["ie <= 6"], &Opts::default()).unwrap();
41//! assert_eq!(
42//! distribs.into_iter().map(|d| d.to_string()).collect::<Vec<_>>(),
43//! vec![String::from("ie 6"), String::from("ie 5.5")]
44//! );
45//! ```
46//!
47//! ## WebAssembly
48//!
49//! This crate can be compiled as WebAssembly, without configuring any features manually.
50//!
51//! Please note that browser and Deno can run WebAssembly,
52//! but those environments aren't Node.js,
53//! so you will receive an error when querying `current node` in those environments.
54
55pub use error::Error;
56pub use opts::Opts;
57use parser::parse_browserslist_query;
58pub use queries::Distrib;
59pub use semver::Version;
60#[cfg(all(feature = "wasm_bindgen", target_arch = "wasm32"))]
61pub use wasm::browserslist;
62
63#[cfg(not(target_arch = "wasm32"))]
64mod config;
65mod data;
66mod error;
67mod generated;
68mod opts;
69mod parser;
70mod queries;
71mod semver;
72#[cfg(test)]
73mod test;
74#[cfg(all(feature = "wasm_bindgen", target_arch = "wasm32"))]
75mod wasm;
76
77/// Resolve browserslist queries.
78///
79/// This is a low-level API.
80/// If you want to load queries from configuration file and
81/// resolve them automatically,
82/// use the higher-level API [`execute`] instead.
83///
84/// ```
85/// use browserslist::{Distrib, Opts, resolve};
86///
87/// let distribs = resolve(&["ie <= 6"], &Opts::default()).unwrap();
88/// assert_eq!(distribs[0].name(), "ie");
89/// assert_eq!(distribs[0].version(), "6");
90/// assert_eq!(distribs[1].name(), "ie");
91/// assert_eq!(distribs[1].version(), "5.5");
92/// ```
93pub fn resolve<S>(queries: &[S], opts: &Opts) -> Result<Vec<Distrib>, Error>
94where
95 S: AsRef<str>,
96{
97 match queries.len() {
98 1 => _resolve(queries[0].as_ref(), opts),
99 _ => {
100 // Pre-calculate capacity to avoid reallocations
101 let total_len: usize = queries.iter().map(|q| q.as_ref().len() + 1).sum();
102 let mut s = String::with_capacity(total_len);
103 for (i, q) in queries.iter().enumerate() {
104 if i > 0 {
105 s.push(',');
106 }
107 s.push_str(q.as_ref());
108 }
109 _resolve(&s, opts)
110 }
111 }
112}
113
114// reduce generic monomorphization
115fn _resolve(query: &str, opts: &Opts) -> Result<Vec<Distrib>, Error> {
116 let queries = parse_browserslist_query(query)?;
117 let mut distribs = vec![];
118 for (i, current) in queries.1.into_iter().enumerate() {
119 if i == 0 && current.negated {
120 return handle_first_negated_error(current.raw.to_string());
121 }
122
123 let dist = queries::query(current.atom, opts)?;
124 apply_query_operation(&mut distribs, dist, current.negated, current.is_and);
125 }
126
127 sort_and_dedup_distribs(&mut distribs);
128 Ok(distribs)
129}
130
131// Separate function to reduce _resolve size and improve inlining decisions
132fn apply_query_operation(
133 distribs: &mut Vec<Distrib>,
134 dist: Vec<Distrib>,
135 negated: bool,
136 is_and: bool,
137) {
138 if negated {
139 distribs.retain(|d| !dist.contains(d));
140 } else if is_and {
141 distribs.retain(|d| dist.contains(d));
142 } else {
143 distribs.extend(dist);
144 }
145}
146
147// Optimized sorting that parses versions only once
148fn sort_and_dedup_distribs(distribs: &mut Vec<Distrib>) {
149 if distribs.is_empty() {
150 return;
151 }
152
153 // Use sort_by_cached_key to parse each version only once
154 distribs.sort_by_cached_key(|d| {
155 let version = d.version().parse::<semver::Version>().unwrap_or_default();
156 (d.name().to_string(), std::cmp::Reverse(version))
157 });
158
159 // Dedup in place
160 distribs.dedup();
161}
162
163// Cold path for error handling
164#[cold]
165fn handle_first_negated_error(raw: String) -> Result<Vec<Distrib>, Error> {
166 Err(Error::NotAtFirst(raw))
167}
168
169#[cfg(not(target_arch = "wasm32"))]
170/// Load queries from configuration with environment information,
171/// then resolve those queries.
172///
173/// If you want to resolve custom queries (not from configuration file),
174/// use the lower-level API [`resolve`] instead.
175///
176/// ```
177/// use browserslist::{Opts, execute};
178///
179/// // when no config found, it use `defaults` query
180/// assert!(!execute(&Opts::default()).unwrap().is_empty());
181/// ```
182pub fn execute(opts: &Opts) -> Result<Vec<Distrib>, Error> {
183 resolve(&config::load(opts)?, opts)
184}