spider_client/shapes/
request.rs

1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3
4/// Structure representing the Chunking algorithm dictionary.
5#[derive(Debug, Deserialize, Serialize, Clone)]
6pub struct ChunkingAlgDict {
7    /// The chunking algorithm to use, defined as a specific type.
8    pub r#type: ChunkingType,
9    /// The amount to chunk by.
10    pub value: i32,
11}
12
13// The nested structures
14#[derive(Serialize, Deserialize, Debug, Clone, Default)]
15pub struct Timeout {
16    /// The seconds up to 60.
17    pub secs: u64,
18    /// The nanoseconds.
19    pub nanos: u32,
20}
21
22#[derive(Serialize, Deserialize, Debug, Clone)]
23pub struct IdleNetwork {
24    /// The timeout to wait until.
25    pub timeout: Timeout,
26}
27
28
29/// Represents various web automation actions.
30#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
31pub enum WebAutomation {
32    /// Runs custom JavaScript code.
33    Evaluate(String),
34    /// Clicks on an element.
35    Click(String),
36    /// Clicks on all elements.
37    ClickAll(String),
38    /// Clicks on all elements.
39    ClickAllClickable(),
40    /// Clicks at the position x and y coordinates.
41    ClickPoint {
42        /// The horizontal (X) coordinate.
43        x: f64,
44        /// The vertical (Y) coordinate.
45        y: f64,
46    },
47    Type { 
48        /// The value to type.
49        value: String,
50        /// The click modifier.
51        modifier: Option<i64> 
52    },
53    /// Waits for a fixed duration in milliseconds.
54    Wait(u64),
55    /// Waits for the next navigation event.
56    WaitForNavigation,
57    /// Wait for dom updates to stop.
58    WaitForDom {
59        /// The selector of the element to wait for updates.
60        selector: Option<String>,
61        ///  The timeout to wait for in ms.
62        timeout: u32,
63    },
64    /// Waits for an element to appear.
65    WaitFor(String),
66    /// Waits for an element to appear with a timeout.
67    WaitForWithTimeout {
68        /// The selector of the element to wait for updates.
69        selector: String,
70        ///  The timeout to wait for in ms.
71        timeout: u64,
72    },
73    /// Waits for an element to appear and then clicks on it.
74    WaitForAndClick(String),
75    /// Scrolls the screen in the horizontal axis by a specified amount in pixels.
76    ScrollX(i32),
77    /// Scrolls the screen in the vertical axis by a specified amount in pixels.
78    ScrollY(i32),
79    /// Fills an input element with a specified value.
80    Fill {
81        /// The selector of the input element to fill.
82        selector: String,
83        ///  The value to fill the input element with.
84        value: String,
85    },
86    /// Scrolls the page until the end.
87    InfiniteScroll(u32),
88    /// Perform a screenshot on the page - fullscreen and omit background for params.
89    Screenshot {
90        /// Take a full page screenshot.
91        full_page: bool,
92        /// Omit the background.
93        omit_background: bool,
94        /// The output file to store the screenshot.
95        output: String,
96    },
97    /// Only continue to the next automation if the prior step was valid. Use this intermediate after a step to break out of the chain.
98    ValidateChain,
99}
100
101#[derive(Default, Serialize, Deserialize, Debug, Clone)]
102#[serde(tag = "type", rename_all = "PascalCase")]
103pub enum RedirectPolicy {
104    Loose,
105    #[default]
106    Strict,
107}
108
109pub type WebAutomationMap = std::collections::HashMap<String, Vec<WebAutomation>>;
110pub type ExecutionScriptsMap = std::collections::HashMap<String, String>;
111
112#[derive(Serialize, Deserialize, Debug, Clone)]
113pub struct Selector {
114    /// The timeout to wait until.
115    pub timeout: Timeout,
116    /// The selector to wait for.
117    pub selector: String,
118}
119
120#[derive(Serialize, Deserialize, Debug, Clone, Default)]
121pub struct Delay {
122    /// The timeout to wait until.
123    pub timeout: Timeout,
124}
125
126/// Default as true.
127fn default_some_true() -> Option<bool> {
128    Some(true)
129}
130
131#[derive(Serialize, Deserialize, Debug, Clone, Default)]
132pub struct WaitFor {
133    /// Wait until idle networks with a timeout of idleness.
134    pub idle_network: Option<IdleNetwork>,
135    /// Wait until a selector exist. Can determine if a selector exist after executing all js and network events.
136    pub selector: Option<Selector>,
137    /// Wait for the dom to update
138    pub dom: Option<Selector>,
139    /// Wait until a hard delay.
140    pub delay: Option<Delay>,
141    /// Wait until page navigation happen. Default is true.
142    #[serde(default = "default_some_true")]
143    pub page_navigations: Option<bool>,
144}
145
146/// Query request to get a document.
147#[derive(Serialize, Deserialize, Debug, Clone, Default)]
148pub struct QueryRequest {
149    /// The exact website url.
150    pub url: Option<String>,
151    /// The website domain.
152    pub domain: Option<String>,
153    /// The path of the resource.
154    pub pathname: Option<String>,
155}
156
157/// Enum representing different types of Chunking.
158#[derive(Default, Debug, Deserialize, Serialize, Clone)]
159#[serde(rename_all = "lowercase")]
160pub enum ChunkingType {
161    #[default]
162    /// By the word count.
163    ByWords,
164    /// By the line count.
165    ByLines,
166    /// By the char length.
167    ByCharacterLength,
168    /// By sentence.
169    BySentence,
170}
171
172#[derive(Default, Debug, Deserialize, Serialize, Clone)]
173/// View port handling for chrome.
174pub struct Viewport {
175    /// Device screen Width
176    pub width: u32,
177    /// Device screen size
178    pub height: u32,
179    /// Device scale factor
180    pub device_scale_factor: Option<f64>,
181    /// Emulating Mobile?
182    pub emulating_mobile: bool,
183    /// Use landscape mode instead of portrait.
184    pub is_landscape: bool,
185    /// Touch screen device?
186    pub has_touch: bool,
187}
188
189// Define the CSSSelector struct
190#[derive(Debug, Clone, Default, Deserialize, Serialize)]
191pub struct CSSSelector {
192    /// The name of the selector group
193    pub name: String,
194    /// A vector of CSS selectors
195    pub selectors: Vec<String>,
196}
197
198// Define the CSSExtractionMap type
199pub type CSSExtractionMap = HashMap<String, Vec<CSSSelector>>;
200
201/// Represents the settings for a webhook configuration
202#[derive(Debug, Default, Deserialize, Serialize, Clone)]
203pub struct WebhookSettings {
204    /// The destination where the webhook information will be sent
205    destination: String,
206    /// Trigger an action when all credits are depleted
207    on_credits_depleted: bool,
208    /// Trigger an action when half of the credits are depleted
209    on_credits_half_depleted: bool,
210    /// Trigger an action on a website status update event
211    on_website_status: bool,
212    /// Send information about a new page find (such as links and bytes)
213    on_find: bool,
214    /// Handle the metadata of a found page
215    on_find_metadata: bool,
216}
217
218/// Proxy pool selection for outbound request routing.
219/// Choose a pool based on your use case (e.g., stealth, speed, or stability).
220///
221/// - 'residential'         → cost-effective entry-level residential pool
222/// - 'residential_fast'    → faster residential pool for higher throughput
223/// - 'residential_static'  → static residential IPs, rotated daily
224/// - 'residential_premium' → low-latency premium IPs
225/// - 'residential_core'    → balanced plan (quality vs. cost)
226/// - 'residential_plus'    → largest and highest quality core pool
227/// - 'mobile'              → 4G/5G mobile proxies for maximum evasion
228/// - 'isp'                 → ISP-grade datacenters
229#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, Hash)]
230pub enum ProxyType {
231    /// Cost-effective entry-level residential pool.
232    #[serde(rename = "residential")]
233    Residential,
234    /// 4G / 5G mobile proxies for maximum stealth and evasion.
235    #[serde(rename = "mobile")]
236    Mobile,
237    /// ISP-grade residential routing (alias: `datacenter`).
238    #[serde(rename = "isp", alias = "datacenter")]
239    #[default]
240    Isp
241}
242
243/// List of proxies.
244pub const PROXY_TYPE_LIST: [ProxyType; 3] = [
245    ProxyType::Residential,
246    ProxyType::Isp,
247    ProxyType::Mobile
248];
249
250impl ProxyType {
251    /// Get the canonical string representation of the proxy type.
252    pub fn as_str(&self) -> &'static str {
253        match self {
254            ProxyType::Residential => "residential",
255            ProxyType::Mobile => "mobile",
256            ProxyType::Isp => "isp"
257        }
258    }
259}
260
261/// Send multiple return formats.
262#[derive(Debug, Deserialize, Serialize, Clone)]
263#[serde(untagged)]
264pub enum ReturnFormatHandling {
265    /// A single return item.
266    Single(ReturnFormat),
267    /// Multiple return formats.
268    Multi(std::collections::HashSet<ReturnFormat>),
269}
270
271impl Default for ReturnFormatHandling {
272    fn default() -> ReturnFormatHandling {
273        ReturnFormatHandling::Single(ReturnFormat::Raw)
274    }
275}
276
277#[derive(Debug, Default, Deserialize, Serialize, Clone)]
278pub struct EventTracker {
279    /// The responses received.
280    pub responses: Option<bool>,
281    /// The request sent.
282    pub requests: Option<bool>,
283    /// Track the automation events with data changes and screenshots.
284    pub automation: Option<bool>,
285}
286
287/// Structure representing request parameters.
288#[derive(Debug, Default, Deserialize, Serialize, Clone)]
289pub struct RequestParams {
290    #[serde(default)]
291    /// The URL to be crawled.
292    pub url: Option<String>,
293    #[serde(default)]
294    /// The type of request to be made.
295    pub request: Option<RequestType>,
296    #[serde(default)]
297    /// The maximum number of pages the crawler should visit.
298    pub limit: Option<u32>,
299    #[serde(default)]
300    /// The format in which the result should be returned.
301    pub return_format: Option<ReturnFormatHandling>,
302    /// The country code for request
303    pub country_code: Option<String>,
304    #[serde(default)]
305    /// Specifies whether to only visit the top-level domain.
306    pub tld: Option<bool>,
307    #[serde(default)]
308    /// The depth of the crawl.
309    pub depth: Option<u32>,
310    #[serde(default)]
311    /// Specifies whether the request should be cached.
312    pub cache: Option<bool>,
313    #[serde(default)]
314    /// Perform an infinite scroll on the page as new content arises. The request param also needs to be set to 'chrome' or 'smart'.
315    pub scroll: Option<u32>,
316    #[serde(default)]
317    /// The budget for various resources.
318    pub budget: Option<HashMap<String, u32>>,
319    #[serde(default)]
320    /// The blacklist routes to ignore. This can be a Regex string pattern.
321    pub blacklist: Option<Vec<String>>,
322    #[serde(default)]
323    /// The whitelist routes to only crawl. This can be a Regex string pattern and used with black_listing.
324    pub whitelist: Option<Vec<String>>,
325    #[serde(default)]
326    /// The locale to be used during the crawl.
327    pub locale: Option<String>,
328    #[serde(default)]
329    /// The cookies to be set for the request, formatted as a single string.
330    pub cookies: Option<String>,
331    #[serde(default)]
332    /// Specifies whether to use stealth techniques to avoid detection.
333    pub stealth: Option<bool>,
334    #[serde(default)]
335    /// The headers to be used for the request.
336    pub headers: Option<HashMap<String, String>>,
337    #[serde(default)]
338    /// Specifies whether to send data via webhooks.
339    pub webhooks: Option<WebhookSettings>,
340    #[serde(default)]
341    /// Specifies whether to include metadata in the response.
342    pub metadata: Option<bool>,
343    #[serde(default)]
344    /// The dimensions of the viewport.
345    pub viewport: Option<Viewport>,
346    #[serde(default)]
347    /// The encoding to be used for the request.
348    pub encoding: Option<String>,
349    #[serde(default)]
350    /// Specifies whether to include subdomains in the crawl.
351    pub subdomains: Option<bool>,
352    #[serde(default)]
353    /// The user agent string to be used for the request.
354    pub user_agent: Option<String>,
355    #[serde(default)]
356    /// Specifies whether to use fingerprinting protection.
357    pub fingerprint: Option<bool>,
358    #[serde(default)]
359    /// Specifies whether to perform the request without using storage.
360    pub storageless: Option<bool>,
361    #[serde(default)]
362    /// Specifies whether readability optimizations should be applied.
363    pub readability: Option<bool>,
364    #[serde(default)]
365    /// Specifies whether to use a proxy for the request. [Deprecated]: use the 'proxy' param instead.
366    pub proxy_enabled: Option<bool>,
367    #[serde(default)]
368    /// Specifies whether to respect the site's robots.txt file.
369    pub respect_robots: Option<bool>,
370    #[serde(default)]
371    /// CSS selector to be used to filter the content.
372    pub root_selector: Option<String>,
373    #[serde(default)]
374    /// Specifies whether to load all resources of the crawl target.
375    pub full_resources: Option<bool>,
376    #[serde(default)]
377    /// The text string to extract data from.
378    pub text: Option<String>,
379    #[serde(default)]
380    /// Specifies whether to use the sitemap links.
381    pub sitemap: Option<bool>,
382    #[serde(default)]
383    /// External domains to include the crawl.
384    pub external_domains: Option<Vec<String>>,
385    #[serde(default)]
386    /// Returns the OpenAI embeddings for the title and description. Other values, such as keywords, may also be included. Requires the `metadata` parameter to be set to `true`.
387    pub return_embeddings: Option<bool>,
388    #[serde(default)]
389    /// Returns the HTTP response headers.
390    pub return_headers: Option<bool>,
391    #[serde(default)]
392    /// Returns the link(s) found on the page that match the crawler query.
393    pub return_page_links: Option<bool>,
394    #[serde(default)]
395    /// Returns the HTTP response cookies.
396    pub return_cookies: Option<bool>,
397    #[serde(default)]
398    /// The timeout for the request, in seconds.
399    pub request_timeout: Option<u8>,
400    #[serde(default)]
401    /// Specifies whether to run the request in the background.
402    pub run_in_background: Option<bool>,
403    #[serde(default)]
404    /// Specifies whether to skip configuration checks.
405    pub skip_config_checks: Option<bool>,
406    #[serde(default)]
407    /// Use CSS query selectors to scrape contents from the web page. Set the paths and the CSS extraction object map to perform extractions per path or page.
408    pub css_extraction_map: Option<CSSExtractionMap>,
409    #[serde(default)]
410    /// The chunking algorithm to use.
411    pub chunking_alg: Option<ChunkingAlgDict>,
412    #[serde(default)]
413    /// Disable request interception when running 'request' as 'chrome' or 'smart'. This can help when the page uses 3rd party or external scripts to load content.
414    pub disable_intercept: Option<bool>,
415    #[serde(default)]
416    /// The wait for events on the page. You need to make your `request` `chrome` or `smart`.
417    pub wait_for: Option<WaitFor>,
418    #[serde(default)]
419    /// Perform custom Javascript tasks on a url or url path. You need to make your `request` `chrome` or `smart`
420    pub execution_scripts: Option<ExecutionScriptsMap>,
421    #[serde(default)]
422    /// Perform web automated tasks on a url or url path. You need to make your `request` `chrome` or `smart`
423    pub automation_scripts: Option<WebAutomationMap>,
424    #[serde(default)]
425    /// The redirect policy for HTTP request. Set the value to Loose to allow all.
426    pub redirect_policy: Option<RedirectPolicy>,
427    #[serde(default)]
428    /// Track the request sent and responses received for `chrome` or `smart`. The responses will track the bytes used and the requests will have the monotime sent.
429    pub event_tracker: Option<EventTracker>,
430    #[serde(default)]
431    /// The timeout to stop the crawl.
432    pub crawl_timeout: Option<Timeout>,
433    #[serde(default)]
434    /// Evaluates given script in every frame upon creation (before loading frame's scripts).
435    pub evaluate_on_new_document: Option<Box<String>>,
436    #[serde(default)]
437    /// Runs the request using lite_mode:Lite mode reduces data transfer costs by 50%, with trade-offs in speed, accuracy,
438    /// geo-targeting, and reliability. It’s best suited for non-urgent data collection or when
439    /// targeting websites with minimal anti-bot protections.
440    pub lite_mode: Option<bool>,
441    #[serde(default)]
442    /// The proxy to use for request.
443    pub proxy: Option<ProxyType>,
444    #[serde(default)]
445    /// Use a remote proxy at ~50% reduced cost for file downloads.
446    /// This requires a user-supplied static IP proxy endpoint.
447    pub remote_proxy: Option<String>,
448    #[serde(default)]
449    /// Set the maximum number of credits to use per page.
450    /// Credits are measured in decimal units, where 10,000 credits equal one dollar (100 credits per penny).
451    /// Credit limiting only applies to request that are Javascript rendered using smart_mode or chrome for the 'request' type.
452    pub max_credits_per_page: Option<f64>,
453}
454
455
456#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
457#[serde(rename_all = "lowercase")]
458pub enum TBS {
459    #[serde(rename = "qdr:h")]
460    PastHour,
461    #[serde(rename = "qdr:d")]
462    Past24Hours,
463    #[serde(rename = "qdr:w")]
464    PastWeek,
465    #[serde(rename = "qdr:m")]
466    PastMonth,
467    #[serde(rename = "qdr:y")]
468    PastYear,
469}
470
471/// The engine to use.
472#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
473pub enum Engine {
474    /// Google
475    Google,
476    /// Brave
477    Brave,
478    /// All
479    #[default]
480    All
481}
482
483/// The structure representing request parameters for a search request.
484#[derive(Debug, Default, Deserialize, Serialize, Clone)]
485pub struct SearchRequestParams {
486    /// The base request parameters.
487    #[serde(default, flatten)]
488    pub base: RequestParams,
489    // The search request.
490    pub search: String,
491    /// The search limit.
492    pub search_limit: Option<u32>,
493    // Fetch the page content. Defaults to true.
494    pub fetch_page_content: Option<bool>,
495    /// The search location of the request
496    pub location: Option<String>,
497    /// The country code of the request
498    pub country: Option<crate::shapes::country_codes::CountryCode>,
499    /// The language code of the request.
500    pub language: Option<String>,
501    /// The number of search results
502    pub num: Option<u32>,
503    /// The time period range.
504    pub tbs: Option<TBS>,
505    /// The page of the search results.
506    pub page: Option<u32>,
507    /// The websites limit if a list is sent from text or urls comma split. This helps automatic configuration of the system.
508    pub website_limit: Option<u32>,
509    /// Prioritize speed over output quantity.
510    pub quick_search: Option<bool>,
511    /// Auto paginate pages ( up to 100 pages ).
512    pub auto_pagination: Option<bool>,
513    /// The search engine to use.
514    pub engine: Option<Engine>
515}
516
517/// Structure representing request parameters for transforming files.
518#[derive(Debug, Default, Deserialize, Serialize, Clone)]
519pub struct TransformParams {
520    #[serde(default)]
521    /// The format in which the result should be returned.
522    pub return_format: Option<ReturnFormat>,
523    #[serde(default)]
524    /// Specifies whether readability optimizations should be applied.
525    pub readability: Option<bool>,
526    #[serde(default)]
527    /// Clean the markdown or text for AI.
528    pub clean: Option<bool>,
529    #[serde(default)]
530    /// Clean the markdown or text for AI removing footers, navigation, and more.
531    pub clean_full: Option<bool>,
532    /// The data being transformed.
533    pub data: Vec<Resource>,
534}
535
536#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Default)]
537/// Transformation resource to use.
538pub struct Resource {
539    #[serde(default)]
540    /// the html to transform
541    pub html: Option<bytes::Bytes>,
542    #[serde(default)]
543    /// the content to transform
544    pub content: Option<bytes::Bytes>,
545    #[serde(default)]
546    /// the url of the html incase of readability to improve transformations.
547    pub url: Option<String>,
548    #[serde(default)]
549    /// the language of the resource.
550    pub lang: Option<String>,
551}
552
553/// the request type to perform
554#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
555#[serde(rename_all = "lowercase")]
556pub enum RequestType {
557    /// Default HTTP request
558    Http,
559    /// Chrome browser rendering
560    Chrome,
561    #[default]
562    /// Smart mode defaulting to HTTP and using Chrome when needed.
563    SmartMode,
564}
565
566/// Enum representing different return formats.
567#[derive(Default, Debug, Deserialize, Serialize, Clone, PartialEq, Eq, Hash)]
568#[serde(rename_all = "lowercase")]
569pub enum ReturnFormat {
570    #[default]
571    /// The default return format of the resource.
572    Raw,
573    /// Return the response as Markdown.
574    Markdown,
575    /// Return the response as Commonmark.
576    Commonmark,
577    /// Return the response as Html2text.
578    Html2text,
579    /// Return the response as Text.
580    Text,
581    /// Returns a screenshot as Base64Url
582    Screenshot,
583    /// Return the response as XML.
584    Xml,
585    /// Return the response as Bytes.
586    Bytes,
587}