Skip to main content

finlight/
params.rs

1//! Request parameters.
2//!
3//! Only what you set is sent: the SDK adds no defaults (no `languages`, no `to`, no `limit`),
4//! and an empty search sends exactly `{}`. Values of vocabularies are not checked locally;
5//! the server answers unknown values with a `ValidationFailed` error that lists the allowed ones.
6//! Only the shape is checked, before any request: `limit` 1 to 100, `languages` not empty,
7//! `min_relevance` 0 to 1, at most 3 `include` blocks, `q` at most 200 characters, `mic` at
8//! most 32, 1 to 10 company ids of at least 1.
9
10use std::time::SystemTime;
11
12use serde::Deserialize;
13use serde_json::{Map, Value};
14
15use crate::error::{Error, Result};
16use crate::time::{format_date, format_utc_millis};
17use crate::version::PAYLOAD_VERSION;
18use crate::vocab::{
19    CompanyRole, EventDirection, EventType, Importance, IncludeBlock, OrderBy, SortOrder,
20    SourceType,
21};
22
23/// A `from` or `to` value.
24///
25/// A `SystemTime` goes out as UTC ISO 8601 with milliseconds (`2026-11-01T00:00:00.000Z`),
26/// a date as `YYYY-MM-DD`, and a string unchanged. A time without a zone cannot be expressed.
27#[derive(Debug, Clone, PartialEq, Eq)]
28#[non_exhaustive]
29pub enum DateInput {
30    /// An instant.
31    Time(SystemTime),
32    /// A calendar date.
33    Date {
34        /// Year (0 to 9999).
35        year: i32,
36        /// Month (1 to 12).
37        month: u32,
38        /// Day of the month.
39        day: u32,
40    },
41    /// A string sent unchanged.
42    Text(String),
43}
44
45impl DateInput {
46    /// A calendar date, sent as `YYYY-MM-DD`.
47    pub fn date(year: i32, month: u32, day: u32) -> Self {
48        DateInput::Date { year, month, day }
49    }
50
51    fn to_wire(&self, key: &str) -> Result<String> {
52        match self {
53            DateInput::Time(t) => format_utc_millis(*t).ok_or_else(|| {
54                Error::validation(
55                    format!("{key} is outside the years 0000 to 9999"),
56                    Some(key),
57                )
58            }),
59            DateInput::Date { year, month, day } => format_date(*year, *month, *day)
60                .ok_or_else(|| Error::validation(format!("{key} is not a valid date"), Some(key))),
61            DateInput::Text(s) => Ok(s.clone()),
62        }
63    }
64}
65
66impl From<SystemTime> for DateInput {
67    fn from(value: SystemTime) -> Self {
68        DateInput::Time(value)
69    }
70}
71
72impl From<&str> for DateInput {
73    fn from(value: &str) -> Self {
74        DateInput::Text(value.to_owned())
75    }
76}
77
78impl From<String> for DateInput {
79    fn from(value: String) -> Self {
80        DateInput::Text(value)
81    }
82}
83
84impl<'de> Deserialize<'de> for DateInput {
85    fn deserialize<D: serde::Deserializer<'de>>(
86        deserializer: D,
87    ) -> std::result::Result<Self, D::Error> {
88        Ok(DateInput::Text(String::deserialize(deserializer)?))
89    }
90}
91
92fn strings<I, S>(values: I) -> Vec<String>
93where
94    I: IntoIterator<Item = S>,
95    S: Into<String>,
96{
97    values.into_iter().map(Into::into).collect()
98}
99
100fn vocab<T, I, S>(values: I) -> Vec<T>
101where
102    I: IntoIterator<Item = S>,
103    S: Into<T>,
104{
105    values.into_iter().map(Into::into).collect()
106}
107
108macro_rules! string_setters {
109    ($( $(#[$m:meta])* $name:ident ),* $(,)?) => {
110        $(
111            $(#[$m])*
112            pub fn $name(mut self, value: impl Into<String>) -> Self {
113                self.$name = Some(value.into());
114                self
115            }
116        )*
117    };
118}
119
120macro_rules! list_setters {
121    ($( $(#[$m:meta])* $name:ident ),* $(,)?) => {
122        $(
123            $(#[$m])*
124            pub fn $name<I, S>(mut self, values: I) -> Self
125            where
126                I: IntoIterator<Item = S>,
127                S: Into<String>,
128            {
129                self.$name = Some(strings(values));
130                self
131            }
132        )*
133    };
134}
135
136macro_rules! vocab_list_setters {
137    ($( $(#[$m:meta])* $name:ident : $ty:ty ),* $(,)?) => {
138        $(
139            $(#[$m])*
140            pub fn $name<I, S>(mut self, values: I) -> Self
141            where
142                I: IntoIterator<Item = S>,
143                S: Into<$ty>,
144            {
145                self.$name = Some(vocab(values));
146                self
147            }
148        )*
149    };
150}
151
152macro_rules! bool_setters {
153    ($( $(#[$m:meta])* $name:ident ),* $(,)?) => {
154        $(
155            $(#[$m])*
156            pub fn $name(mut self, value: bool) -> Self {
157                self.$name = Some(value);
158                self
159            }
160        )*
161    };
162}
163
164fn from_json_error(err: serde_json::Error, what: &str) -> Error {
165    let text = err.to_string();
166    if let Some(rest) = text.strip_prefix("unknown field `") {
167        let key = rest.split('`').next().unwrap_or_default();
168        return Error::validation(
169            format!(
170                "unknown {what} parameter \"{key}\"; the server would ignore it silently. \
171                 See https://docs.finlight.me for the v3 parameters."
172            ),
173            Some(key),
174        );
175    }
176    Error::validation(format!("invalid {what} parameters: {text}"), None)
177}
178
179fn check_include(include: &Option<Vec<IncludeBlock>>) -> Result<Option<Vec<IncludeBlock>>> {
180    match include {
181        Some(list) if list.len() > 3 => Err(Error::validation(
182            "include takes at most 3 values",
183            Some("include"),
184        )),
185        Some(list) if list.is_empty() => Ok(None),
186        other => Ok(other.clone()),
187    }
188}
189
190fn put_str(map: &mut Map<String, Value>, key: &str, value: &Option<String>) {
191    if let Some(v) = value {
192        map.insert(key.to_owned(), Value::String(v.clone()));
193    }
194}
195
196fn put_list<T: AsRef<str>>(map: &mut Map<String, Value>, key: &str, value: &Option<Vec<T>>) {
197    if let Some(list) = value {
198        map.insert(
199            key.to_owned(),
200            Value::Array(
201                list.iter()
202                    .map(|v| Value::String(v.as_ref().to_owned()))
203                    .collect(),
204            ),
205        );
206    }
207}
208
209fn put_bool(map: &mut Map<String, Value>, key: &str, value: Option<bool>) {
210    if let Some(v) = value {
211        map.insert(key.to_owned(), Value::Bool(v));
212    }
213}
214
215/// Parameters of `articles().search()` and `articles().search_all()`.
216///
217/// ```
218/// use finlight::{IncludeBlock, SearchParams};
219/// let params = SearchParams::new()
220///     .query("ticker:NVDA")
221///     .languages(["en"])
222///     .include([IncludeBlock::COMPANIES, IncludeBlock::EVENTS])
223///     .limit(10);
224/// ```
225#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
226#[serde(rename_all = "camelCase", deny_unknown_fields)]
227#[non_exhaustive]
228pub struct SearchParams {
229    /// Query language, e.g. `ticker:AAPL AND eventType:earnings`.
230    pub query: Option<String>,
231    /// Only these source domains.
232    pub sources: Option<Vec<String>>,
233    /// Non-default sources added to the default pool.
234    pub opt_in_sources: Option<Vec<String>>,
235    /// Source domains left out.
236    pub exclude_sources: Option<Vec<String>>,
237    /// Only sources of these types. Articles of unclassified sources never match.
238    pub source_types: Option<Vec<SourceType>>,
239    /// Source types left out. Articles of unclassified sources are kept.
240    pub exclude_source_types: Option<Vec<SourceType>>,
241    /// Lower bound of the `order_by` timestamp.
242    pub from: Option<DateInput>,
243    /// Upper bound of the `order_by` timestamp.
244    pub to: Option<DateInput>,
245    /// ISO 639-1 codes; not empty. The server default is `["en"]`.
246    pub languages: Option<Vec<String>>,
247    /// Tickers (`SYMBOL`, `SYMBOL@MIC`, vendor notations).
248    pub tickers: Option<Vec<String>>,
249    /// Geographic focus of the story (ISO alpha-2).
250    pub countries: Option<Vec<String>>,
251    /// Categories.
252    pub categories: Option<Vec<String>>,
253    /// `true` keeps only articles with scraped content.
254    pub has_content: Option<bool>,
255    /// Company roles (same company as `tickers` and `min_relevance`).
256    pub roles: Option<Vec<CompanyRole>>,
257    /// Minimum relevance, 0 to 1.
258    pub min_relevance: Option<f64>,
259    /// Event types (same event as `event_directions` and `min_importance`).
260    pub event_types: Option<Vec<EventType>>,
261    /// Event directions.
262    pub event_directions: Option<Vec<EventDirection>>,
263    /// Minimum event importance.
264    pub min_importance: Option<Importance>,
265    /// GICS sectors.
266    pub sectors: Option<Vec<String>>,
267    /// Company domicile (ISO alpha-2).
268    pub company_countries: Option<Vec<String>>,
269    /// Primary-listing MICs.
270    pub exchanges: Option<Vec<String>>,
271    /// Sort timestamp (and the timestamp `from` and `to` apply to).
272    pub order_by: Option<OrderBy>,
273    /// Sort direction.
274    pub order: Option<SortOrder>,
275    /// Page size, 1 to 100. The server default is 20.
276    pub limit: Option<u32>,
277    /// `pagination.next_cursor` of the previous page.
278    pub cursor: Option<String>,
279    /// Extra blocks (at most 3).
280    pub include: Option<Vec<IncludeBlock>>,
281}
282
283impl SearchParams {
284    /// Empty parameters (an empty search sends `{}`).
285    pub fn new() -> Self {
286        Self::default()
287    }
288
289    /// Reads parameters from a JSON object with the wire keys (`eventTypes`, `orderBy`, ...).
290    /// An unknown key is rejected with `Error::Validation` naming it.
291    pub fn from_json(json: &str) -> Result<Self> {
292        serde_json::from_str(json).map_err(|e| from_json_error(e, "search"))
293    }
294
295    string_setters! {
296        /// Query language.
297        query,
298        /// Cursor of the previous page.
299        cursor,
300    }
301
302    list_setters! {
303        /// Only these source domains.
304        sources,
305        /// Non-default sources added to the default pool.
306        opt_in_sources,
307        /// Source domains left out.
308        exclude_sources,
309        /// ISO 639-1 codes.
310        languages,
311        /// Tickers.
312        tickers,
313        /// Story countries.
314        countries,
315        /// Categories.
316        categories,
317        /// GICS sectors.
318        sectors,
319        /// Company domicile countries.
320        company_countries,
321        /// Primary-listing MICs.
322        exchanges,
323    }
324
325    vocab_list_setters! {
326        /// Only sources of these types (`SourceType::NEWSWIRE`, ...).
327        source_types: SourceType,
328        /// Source types left out.
329        exclude_source_types: SourceType,
330        /// Company roles.
331        roles: CompanyRole,
332        /// Event types.
333        event_types: EventType,
334        /// Event directions.
335        event_directions: EventDirection,
336        /// Extra blocks.
337        include: IncludeBlock,
338    }
339
340    bool_setters! {
341        /// Only articles with scraped content.
342        has_content,
343    }
344
345    /// Lower bound (a `SystemTime`, `DateInput::date(..)` or a string).
346    pub fn from(mut self, value: impl Into<DateInput>) -> Self {
347        self.from = Some(value.into());
348        self
349    }
350
351    /// Upper bound.
352    pub fn to(mut self, value: impl Into<DateInput>) -> Self {
353        self.to = Some(value.into());
354        self
355    }
356
357    /// Minimum relevance, 0 to 1.
358    pub fn min_relevance(mut self, value: f64) -> Self {
359        self.min_relevance = Some(value);
360        self
361    }
362
363    /// Minimum event importance.
364    pub fn min_importance(mut self, value: impl Into<Importance>) -> Self {
365        self.min_importance = Some(value.into());
366        self
367    }
368
369    /// Sort timestamp.
370    pub fn order_by(mut self, value: impl Into<OrderBy>) -> Self {
371        self.order_by = Some(value.into());
372        self
373    }
374
375    /// Sort direction.
376    pub fn order(mut self, value: impl Into<SortOrder>) -> Self {
377        self.order = Some(value.into());
378        self
379    }
380
381    /// Page size, 1 to 100.
382    pub fn limit(mut self, value: u32) -> Self {
383        self.limit = Some(value);
384        self
385    }
386
387    /// Checks the shape and builds the JSON body from the fixed key list.
388    pub(crate) fn to_body(&self) -> Result<Map<String, Value>> {
389        let mut m = Map::new();
390        put_str(&mut m, "query", &self.query);
391        put_list(&mut m, "sources", &self.sources);
392        put_list(&mut m, "optInSources", &self.opt_in_sources);
393        put_list(&mut m, "excludeSources", &self.exclude_sources);
394        put_list(&mut m, "sourceTypes", &self.source_types);
395        put_list(&mut m, "excludeSourceTypes", &self.exclude_source_types);
396        if let Some(from) = &self.from {
397            m.insert("from".into(), Value::String(from.to_wire("from")?));
398        }
399        if let Some(to) = &self.to {
400            m.insert("to".into(), Value::String(to.to_wire("to")?));
401        }
402        if let Some(languages) = &self.languages {
403            if languages.is_empty() {
404                return Err(Error::validation(
405                    "languages must not be empty; leave it out for the server default",
406                    Some("languages"),
407                ));
408            }
409        }
410        put_list(&mut m, "languages", &self.languages);
411        put_list(&mut m, "tickers", &self.tickers);
412        put_list(&mut m, "countries", &self.countries);
413        put_list(&mut m, "categories", &self.categories);
414        put_bool(&mut m, "hasContent", self.has_content);
415        put_list(&mut m, "roles", &self.roles);
416        if let Some(v) = self.min_relevance {
417            if !v.is_finite() || !(0.0..=1.0).contains(&v) {
418                return Err(Error::validation(
419                    "minRelevance must be between 0 and 1",
420                    Some("minRelevance"),
421                ));
422            }
423            let number = serde_json::Number::from_f64(v).ok_or_else(|| {
424                Error::validation("minRelevance must be a finite number", Some("minRelevance"))
425            })?;
426            m.insert("minRelevance".into(), Value::Number(number));
427        }
428        put_list(&mut m, "eventTypes", &self.event_types);
429        put_list(&mut m, "eventDirections", &self.event_directions);
430        if let Some(v) = &self.min_importance {
431            m.insert("minImportance".into(), Value::String(v.as_str().to_owned()));
432        }
433        put_list(&mut m, "sectors", &self.sectors);
434        put_list(&mut m, "companyCountries", &self.company_countries);
435        put_list(&mut m, "exchanges", &self.exchanges);
436        if let Some(v) = &self.order_by {
437            m.insert("orderBy".into(), Value::String(v.as_str().to_owned()));
438        }
439        if let Some(v) = &self.order {
440            m.insert("order".into(), Value::String(v.as_str().to_owned()));
441        }
442        if let Some(limit) = self.limit {
443            if !(1..=100).contains(&limit) {
444                return Err(Error::validation(
445                    "limit must be between 1 and 100",
446                    Some("limit"),
447                ));
448            }
449            m.insert("limit".into(), Value::from(limit));
450        }
451        if let Some(cursor) = &self.cursor {
452            if cursor.is_empty() {
453                return Err(Error::validation(
454                    "cursor must not be empty",
455                    Some("cursor"),
456                ));
457            }
458            m.insert("cursor".into(), Value::String(cursor.clone()));
459        }
460        put_list(&mut m, "include", &check_include(&self.include)?);
461        Ok(m)
462    }
463}
464
465/// Options of `articles().get()` and `articles().get_by_link()`.
466#[derive(Debug, Clone, Default, PartialEq, Eq)]
467#[non_exhaustive]
468pub struct GetArticleOptions {
469    /// Extra blocks (at most 3).
470    pub include: Option<Vec<IncludeBlock>>,
471}
472
473impl GetArticleOptions {
474    /// No extra blocks.
475    pub fn new() -> Self {
476        Self::default()
477    }
478
479    /// Extra blocks.
480    pub fn include<I, S>(mut self, values: I) -> Self
481    where
482        I: IntoIterator<Item = S>,
483        S: Into<IncludeBlock>,
484    {
485        self.include = Some(vocab(values));
486        self
487    }
488
489    pub(crate) fn include_query(&self) -> Result<Option<String>> {
490        Ok(check_include(&self.include)?.map(|list| {
491            list.iter()
492                .map(IncludeBlock::as_str)
493                .collect::<Vec<_>>()
494                .join(",")
495        }))
496    }
497}
498
499/// Parameters of `companies().search()`.
500#[derive(Debug, Clone, PartialEq, Eq)]
501#[non_exhaustive]
502pub struct CompanySearchParams {
503    /// Ticker, name, alias, ISIN, `XNAS:AMD` or a vendor notation; at most 200 characters.
504    pub q: String,
505    /// MIC or alias that narrows the hits; at most 32 characters.
506    pub mic: Option<String>,
507}
508
509impl CompanySearchParams {
510    /// Search for `q`.
511    pub fn new(q: impl Into<String>) -> Self {
512        CompanySearchParams {
513            q: q.into(),
514            mic: None,
515        }
516    }
517
518    /// Narrow the hits to an exchange.
519    pub fn mic(mut self, value: impl Into<String>) -> Self {
520        self.mic = Some(value.into());
521        self
522    }
523
524    pub(crate) fn to_query(&self) -> Result<Vec<(&'static str, String)>> {
525        let q_len = self.q.chars().count();
526        // The server trims q: empty or only whitespace is "neither q nor ids", a 400 that costs a credit.
527        if self.q.trim().is_empty() {
528            return Err(Error::validation("q must not be empty", Some("q")));
529        }
530        if q_len > 200 {
531            return Err(Error::validation(
532                "q must be at most 200 characters",
533                Some("q"),
534            ));
535        }
536        let mut query = vec![("q", self.q.clone())];
537        if let Some(mic) = &self.mic {
538            let len = mic.chars().count();
539            if len == 0 {
540                return Err(Error::validation("mic must not be empty", Some("mic")));
541            }
542            if len > 32 {
543                return Err(Error::validation(
544                    "mic must be at most 32 characters",
545                    Some("mic"),
546                ));
547            }
548            query.push(("mic", mic.clone()));
549        }
550        Ok(query)
551    }
552}
553
554pub(crate) fn check_company_id(id: i64, name: &str) -> Result<i64> {
555    if !(1..=(1i64 << 53) - 1).contains(&id) {
556        return Err(Error::validation(
557            format!("{name} must be an integer from 1 to 2^53-1"),
558            Some(name),
559        ));
560    }
561    Ok(id)
562}
563
564pub(crate) fn company_ids_query(ids: &[i64]) -> Result<String> {
565    if ids.is_empty() || ids.len() > 10 {
566        return Err(Error::validation("ids takes 1 to 10 values", Some("ids")));
567    }
568    let mut out = Vec::with_capacity(ids.len());
569    for id in ids {
570        out.push(check_company_id(*id, "ids")?.to_string());
571    }
572    Ok(out.join(","))
573}
574
575/// Options of `articles().search_all()`.
576#[derive(Debug, Clone, Default, PartialEq, Eq)]
577#[non_exhaustive]
578pub struct SearchAllOptions {
579    /// Page limit; default `Config::max_pages` (10).
580    pub max_pages: Option<u32>,
581}
582
583impl SearchAllOptions {
584    /// Default options.
585    pub fn new() -> Self {
586        Self::default()
587    }
588
589    /// Page limit.
590    pub fn max_pages(mut self, value: u32) -> Self {
591        self.max_pages = Some(value);
592        self
593    }
594}
595
596/// Subscribe parameters of the enriched stream (`client.stream()`).
597///
598/// Streams keep the subscription vocabulary: one `language`, no flat event or role filters
599/// (use `query`, e.g. `eventType:mna`).
600#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
601#[serde(rename_all = "camelCase", deny_unknown_fields)]
602#[non_exhaustive]
603pub struct StreamParams {
604    /// Query (lenient stream grammar).
605    pub query: Option<String>,
606    /// Only these source domains.
607    pub sources: Option<Vec<String>>,
608    /// Source domains left out.
609    pub exclude_sources: Option<Vec<String>>,
610    /// Non-default sources added.
611    pub opt_in_sources: Option<Vec<String>>,
612    /// One language (ISO 639-1); the server default is `en`.
613    pub language: Option<String>,
614    /// Tickers.
615    pub tickers: Option<Vec<String>>,
616    /// Story countries.
617    pub countries: Option<Vec<String>>,
618    /// Categories.
619    pub categories: Option<Vec<String>>,
620    /// Only sources of these types. Articles of unclassified sources never match.
621    pub source_types: Option<Vec<SourceType>>,
622    /// Source types left out. Articles of unclassified sources are kept.
623    pub exclude_source_types: Option<Vec<SourceType>>,
624    /// Leave out articles without content.
625    pub exclude_empty_content: Option<bool>,
626    /// Without it the server never sends `article.updated`.
627    pub include_updates: Option<bool>,
628    /// Extra blocks (at most 3).
629    pub include: Option<Vec<IncludeBlock>>,
630}
631
632impl StreamParams {
633    /// Empty parameters.
634    pub fn new() -> Self {
635        Self::default()
636    }
637
638    /// Reads parameters from a JSON object with the wire keys; unknown keys are rejected.
639    pub fn from_json(json: &str) -> Result<Self> {
640        serde_json::from_str(json).map_err(|e| from_json_error(e, "stream"))
641    }
642
643    string_setters! {
644        /// Query.
645        query,
646        /// One language.
647        language,
648    }
649
650    list_setters! {
651        /// Only these source domains.
652        sources,
653        /// Source domains left out.
654        exclude_sources,
655        /// Non-default sources added.
656        opt_in_sources,
657        /// Tickers.
658        tickers,
659        /// Story countries.
660        countries,
661        /// Categories.
662        categories,
663    }
664
665    vocab_list_setters! {
666        /// Only sources of these types (`SourceType::NEWSWIRE`, ...).
667        source_types: SourceType,
668        /// Source types left out.
669        exclude_source_types: SourceType,
670        /// Extra blocks.
671        include: IncludeBlock,
672    }
673
674    bool_setters! {
675        /// Leave out articles without content.
676        exclude_empty_content,
677        /// Also deliver `article.updated`.
678        include_updates,
679    }
680
681    pub(crate) fn to_frame(&self) -> Result<Map<String, Value>> {
682        let mut m = Map::new();
683        m.insert("payloadVersion".into(), Value::from(PAYLOAD_VERSION));
684        put_list(&mut m, "include", &check_include(&self.include)?);
685        put_str(&mut m, "query", &self.query);
686        put_list(&mut m, "sources", &self.sources);
687        put_list(&mut m, "excludeSources", &self.exclude_sources);
688        put_list(&mut m, "optInSources", &self.opt_in_sources);
689        put_str(&mut m, "language", &self.language);
690        put_list(&mut m, "tickers", &self.tickers);
691        put_list(&mut m, "countries", &self.countries);
692        put_list(&mut m, "categories", &self.categories);
693        put_list(&mut m, "sourceTypes", &self.source_types);
694        put_list(&mut m, "excludeSourceTypes", &self.exclude_source_types);
695        put_bool(&mut m, "excludeEmptyContent", self.exclude_empty_content);
696        put_bool(&mut m, "includeUpdates", self.include_updates);
697        Ok(m)
698    }
699}
700
701/// Subscribe parameters of the raw stream (`client.raw_stream()`). Raw has no `include`:
702/// it delivers the article skeleton only.
703#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
704#[serde(rename_all = "camelCase", deny_unknown_fields)]
705#[non_exhaustive]
706pub struct RawStreamParams {
707    /// Query.
708    pub query: Option<String>,
709    /// Only these source domains.
710    pub sources: Option<Vec<String>>,
711    /// Source domains left out.
712    pub exclude_sources: Option<Vec<String>>,
713    /// Only sources of these types. Articles of unclassified sources never match.
714    pub source_types: Option<Vec<SourceType>>,
715    /// Source types left out. Articles of unclassified sources are kept.
716    pub exclude_source_types: Option<Vec<SourceType>>,
717    /// One language.
718    pub language: Option<String>,
719    /// Also deliver `article.updated`.
720    pub include_updates: Option<bool>,
721}
722
723impl RawStreamParams {
724    /// Empty parameters.
725    pub fn new() -> Self {
726        Self::default()
727    }
728
729    /// Reads parameters from a JSON object with the wire keys; unknown keys (`include` too)
730    /// are rejected.
731    pub fn from_json(json: &str) -> Result<Self> {
732        serde_json::from_str(json).map_err(|e| {
733            let err = from_json_error(e, "raw stream");
734            match &err {
735                Error::Validation(v) if v.param() == Some("include") => Error::validation(
736                    "raw streams have no include: raw delivers the article skeleton only",
737                    Some("include"),
738                ),
739                _ => err,
740            }
741        })
742    }
743
744    string_setters! {
745        /// Query.
746        query,
747        /// One language.
748        language,
749    }
750
751    list_setters! {
752        /// Only these source domains.
753        sources,
754        /// Source domains left out.
755        exclude_sources,
756    }
757
758    vocab_list_setters! {
759        /// Only sources of these types (`SourceType::NEWSWIRE`, ...).
760        source_types: SourceType,
761        /// Source types left out.
762        exclude_source_types: SourceType,
763    }
764
765    bool_setters! {
766        /// Also deliver `article.updated`.
767        include_updates,
768    }
769
770    pub(crate) fn to_frame(&self) -> Map<String, Value> {
771        let mut m = Map::new();
772        m.insert("payloadVersion".into(), Value::from(PAYLOAD_VERSION));
773        put_str(&mut m, "query", &self.query);
774        put_list(&mut m, "sources", &self.sources);
775        put_list(&mut m, "excludeSources", &self.exclude_sources);
776        put_list(&mut m, "sourceTypes", &self.source_types);
777        put_list(&mut m, "excludeSourceTypes", &self.exclude_source_types);
778        put_str(&mut m, "language", &self.language);
779        put_bool(&mut m, "includeUpdates", self.include_updates);
780        m
781    }
782}
783
784/// Percent-encodes a query component like `encodeURIComponent`.
785pub(crate) fn encode_component(value: &str) -> String {
786    let mut out = String::with_capacity(value.len());
787    for b in value.bytes() {
788        match b {
789            b'A'..=b'Z'
790            | b'a'..=b'z'
791            | b'0'..=b'9'
792            | b'-'
793            | b'_'
794            | b'.'
795            | b'!'
796            | b'~'
797            | b'*'
798            | b'\''
799            | b'('
800            | b')' => out.push(b as char),
801            _ => out.push_str(&format!("%{b:02X}")),
802        }
803    }
804    out
805}
806
807/// Encodes query pairs. Lists are joined with commas into one parameter (never `key[]=`).
808pub(crate) fn encode_query(pairs: &[(&str, String)]) -> String {
809    pairs
810        .iter()
811        .map(|(k, v)| format!("{}={}", encode_component(k), encode_component(v)))
812        .collect::<Vec<_>>()
813        .join("&")
814}