Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

feat(fetch): read eval scripts from stdin

ldm00d62075f74b4
diff --git a/moli/src/app.rs b/moli/src/app.rs
index ee248588d..bad461f61 100644
--- a/moli/src/app.rs
+++ b/moli/src/app.rs
@@ -3,7 +3,12 @@
mod readiness;
mod redirect_navigation;
-use std::{fmt, io::Write, sync::Arc};
+use std::{
+ fmt,
+ io::{Read, Write},
+ path::Path,
+ sync::Arc,
+};
use crate::{
cli::{Cli, Commands, normalize_args_for_compat},
@@ -42,14 +47,21 @@ pub async fn run_cli_with_config<W: Write>(
) -> Result<()> {
match cli.command {
Commands::Fetch(mut args) => {
- let eval_expression =
- if let Some(path) = args.eval_file.as_deref() {
+ let eval_expression = if let Some(path) = args.eval_file.as_deref() {
+ if path == Path::new("-") {
+ let mut expression = String::new();
+ std::io::stdin()
+ .read_to_string(&mut expression)
+ .context("failed to read --eval-file `-` from stdin")?;
+ Some(expression)
+ } else {
Some(std::fs::read_to_string(path).with_context(|| {
format!("failed to read --eval-file `{}`", path.display())
})?)
- } else {
- args.eval.take()
- };
+ }
+ } else {
+ args.eval.take()
+ };
let request = build_fetch_request(&args.url, &config)?;
if config.browser.fetch().obey_robots() {
// Checked before the browser starts so a refused fetch costs
diff --git a/moli/src/cli.rs b/moli/src/cli.rs
index f6a698c16..acbc0fa1e 100644
--- a/moli/src/cli.rs
+++ b/moli/src/cli.rs
@@ -60,8 +60,9 @@ pub struct FetchArgs {
)]
pub eval: Option<String>,
- /// Read the JavaScript expression from a UTF-8 file. This avoids command-line
- /// argument length limits for large or multiline scripts. Promises are awaited.
+ /// Read the JavaScript expression from a UTF-8 file, or from stdin when PATH
+ /// is `-`. This avoids command-line argument length limits for large or
+ /// multiline scripts. Promises are awaited.
#[arg(
long,
value_name = "PATH",
diff --git a/moli/tests/cli.rs b/moli/tests/cli.rs
index 853887077..2e9f074db 100644
--- a/moli/tests/cli.rs
+++ b/moli/tests/cli.rs
@@ -936,6 +936,24 @@ fn parses_fetch_eval_file() {
);
}
+#[test]
+fn parses_fetch_eval_file_from_stdin() {
+ let cli = Cli::try_parse_from(normalize_args_for_compat([
+ "moli",
+ "fetch",
+ "--eval-file",
+ "-",
+ "https://example.com",
+ ]))
+ .unwrap();
+
+ let Commands::Fetch(args) = cli.command else {
+ panic!("expected fetch command");
+ };
+ assert!(args.eval.is_none());
+ assert_eq!(args.eval_file.as_deref(), Some(std::path::Path::new("-")));
+}
+
#[test]
fn fetch_eval_sources_are_mutually_exclusive() {
let error = Cli::try_parse_from(normalize_args_for_compat([
diff --git a/moli/tests/fetch_cli/eval.rs b/moli/tests/fetch_cli/eval.rs
index 4a7b6e23f..2543b5007 100644
--- a/moli/tests/fetch_cli/eval.rs
+++ b/moli/tests/fetch_cli/eval.rs
@@ -3,7 +3,9 @@ use anyhow::Result;
use moli_test_support::FixtureServer;
use std::{
ffi::{OsStr, OsString},
+ io::Write,
path::Path,
+ process::{Command, Stdio},
};
fn run_eval(url: &str, expression: &str, extra_args: &[&str]) -> Result<super::Output> {
@@ -14,6 +16,32 @@ fn run_eval_file(url: &str, path: &Path, extra_args: &[&str]) -> Result<super::O
run_eval_source(url, "--eval-file", path.as_os_str(), extra_args)
}
+fn run_eval_stdin(url: &str, script: &[u8]) -> Result<std::process::Output> {
+ let mut child = Command::new(env!("CARGO_BIN_EXE_moli"))
+ .args([
+ "fetch",
+ "--log-level",
+ "error",
+ "--http-no-proxy",
+ "*",
+ "--wait-until",
+ "load",
+ "--eval-file",
+ "-",
+ url,
+ ])
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()?;
+ child
+ .stdin
+ .take()
+ .expect("piped stdin must be available")
+ .write_all(script)?;
+ Ok(child.wait_with_output()?)
+}
+
fn run_eval_source(
url: &str,
source_flag: &str,
@@ -143,6 +171,57 @@ fn eval_file_executes_large_multiline_scripts() -> Result<()> {
Ok(())
}
+#[test]
+fn eval_file_dash_executes_large_multiline_scripts_from_stdin() -> Result<()> {
+ let script = format!(
+ "/*{}*/\n\
+ const main = document.querySelector('main');\n\
+ const source = 'stdin';\n\
+ Promise.resolve({{ source, text: main.textContent.trim() }})",
+ "padding".repeat(24 * 1024),
+ );
+ assert!(script.len() > 128 * 1024);
+
+ let output = run_eval_stdin(
+ "data:text/html,<main>fixture%20stdin</main>",
+ script.as_bytes(),
+ )?;
+
+ assert!(
+ output.status.success(),
+ "stderr={}",
+ clean_output(&output.stderr)
+ );
+ let value: serde_json::Value = serde_json::from_slice(&output.stdout)?;
+ assert_eq!(
+ value,
+ serde_json::json!({ "source": "stdin", "text": "fixture stdin" })
+ );
+ Ok(())
+}
+
+#[test]
+fn eval_file_dash_rejects_invalid_utf8_before_fetching() -> Result<()> {
+ let output = run_eval_stdin(
+ "https://eval-file-stdin-must-not-fetch.invalid/",
+ b"document.title\xff",
+ )?;
+
+ let stdout = clean_output(&output.stdout);
+ let stderr = clean_output(&output.stderr);
+ assert!(!output.status.success(), "stdout={stdout}\nstderr={stderr}");
+ assert!(stdout.is_empty(), "stdout={stdout}");
+ assert!(
+ stderr.contains("failed to read --eval-file `-` from stdin"),
+ "stderr={stderr}"
+ );
+ assert!(
+ !stderr.contains("failed to fetch"),
+ "stdin must be read before starting a fetch: stderr={stderr}"
+ );
+ Ok(())
+}
+
#[test]
fn eval_file_reports_read_errors_before_fetching() -> Result<()> {
let script_file = unique_temp_file_path("eval-file-missing", "missing.js")?;