Skip to main content

alef_core/config/
e2e.rs

1//! E2E test generation configuration types.
2
3use crate::config::manifest_extras::ManifestExtras;
4use serde::{Deserialize, Serialize};
5use std::collections::{HashMap, HashSet};
6
7/// Controls whether generated e2e test projects reference the package under
8/// test via a local path (for development) or a registry version string
9/// (for standalone `test_apps` that consumers can run without the monorepo).
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
11#[serde(rename_all = "lowercase")]
12pub enum DependencyMode {
13    /// Local path dependency (default) — used during normal e2e development.
14    #[default]
15    Local,
16    /// Registry dependency — generates standalone test apps that pull the
17    /// package from its published registry (PyPI, npm, crates.io, etc.).
18    Registry,
19}
20
21/// Configuration for registry-mode e2e generation (`alef e2e generate --registry`).
22#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct RegistryConfig {
24    /// Output directory for registry-mode test apps (default: "test_apps").
25    #[serde(default = "default_test_apps_dir")]
26    pub output: String,
27    /// Per-language package overrides used only in registry mode.
28    /// Merged on top of the base `[e2e.packages]` entries.
29    #[serde(default)]
30    pub packages: HashMap<String, PackageRef>,
31    /// When non-empty, only fixture categories in this list are included in
32    /// registry-mode generation (useful for shipping a curated subset).
33    #[serde(default)]
34    pub categories: Vec<String>,
35    /// GitHub repository URL for downloading prebuilt artifacts (e.g., FFI
36    /// shared libraries) from GitHub Releases.
37    ///
38    /// Falls back to `[scaffold] repository` when not set, then to
39    /// `https://github.com/kreuzberg-dev/{crate.name}`.
40    #[serde(default)]
41    pub github_repo: Option<String>,
42}
43
44impl Default for RegistryConfig {
45    fn default() -> Self {
46        Self {
47            output: default_test_apps_dir(),
48            packages: HashMap::new(),
49            categories: Vec::new(),
50            github_repo: None,
51        }
52    }
53}
54
55fn default_test_apps_dir() -> String {
56    "test_apps".to_string()
57}
58
59/// Root e2e configuration from `[e2e]` section of alef.toml.
60#[derive(Debug, Clone, Serialize, Deserialize)]
61pub struct E2eConfig {
62    /// Directory containing fixture JSON files (default: "fixtures").
63    #[serde(default = "default_fixtures_dir")]
64    pub fixtures: String,
65    /// Output directory for generated e2e test projects (default: "e2e").
66    #[serde(default = "default_output_dir")]
67    pub output: String,
68    /// Repo-root-relative directory holding binary file fixtures referenced by
69    /// `file_path` / `bytes` fixture args (default: "test_documents").
70    ///
71    /// Backends that emit chdir / setup hooks for file-based fixtures resolve
72    /// the relative path from the test-emission directory via
73    /// [`E2eConfig::test_documents_relative_from`]. The default matches the
74    /// kreuzberg convention; downstream crates whose fixtures don't reference
75    /// files (e.g. liter-llm, which uses pure mock-server fixtures) can leave
76    /// the default in place — backends conditionally emit the setup only when
77    /// fixtures actually need it.
78    #[serde(default = "default_test_documents_dir")]
79    pub test_documents_dir: String,
80    /// Languages to generate e2e tests for. Defaults to top-level `languages` list.
81    #[serde(default)]
82    pub languages: Vec<String>,
83    /// Default function call configuration.
84    pub call: CallConfig,
85    /// Named additional call configurations for multi-function testing.
86    /// Fixtures reference these via the `call` field, e.g. `"call": "embed"`.
87    #[serde(default)]
88    pub calls: HashMap<String, CallConfig>,
89    /// Per-language package reference overrides.
90    #[serde(default)]
91    pub packages: HashMap<String, PackageRef>,
92    /// Per-language extra dependencies to splice into the e2e harness's
93    /// language-native manifest (`e2e/<lang>/package.json` for node/wasm,
94    /// `e2e/python/pyproject.toml` for Python, etc.). Distinct from the
95    /// Rust-binding `extra_dependencies` knob — this one targets the
96    /// host-language test-harness manifest. Keys are canonical language
97    /// names (`node`, `wasm`, `python`, …).
98    #[serde(default)]
99    pub harness_extras: HashMap<String, ManifestExtras>,
100    /// Per-language formatter commands.
101    #[serde(default)]
102    pub format: HashMap<String, String>,
103    /// Field path aliases: maps fixture field paths to actual API struct paths.
104    /// E.g., "metadata.title" -> "metadata.document.title"
105    /// Supports struct access (foo.bar), map access (foo[key]), direct fields.
106    #[serde(default)]
107    pub fields: HashMap<String, String>,
108    /// Fields that are Optional/nullable in the return type.
109    /// Rust generators use .as_deref().unwrap_or("") for strings, .is_some() for structs.
110    #[serde(default)]
111    pub fields_optional: HashSet<String>,
112    /// Fields that are arrays/Vecs on the result type.
113    /// When a fixture path like `json_ld.name` traverses an array field, the
114    /// accessor adds `[0]` (or language equivalent) to index into the first element.
115    #[serde(default)]
116    pub fields_array: HashSet<String>,
117    /// Fields where the accessor is a method call (appends `()`) rather than a field access.
118    /// Rust-specific: Java always uses `()`, Python/PHP use field access.
119    /// Listed as the full resolved field path (after alias resolution).
120    /// E.g., `"metadata.format.excel"` means `.excel` should be emitted as `.excel()`.
121    #[serde(default)]
122    pub fields_method_calls: HashSet<String>,
123    /// Known top-level fields on the result type.
124    ///
125    /// When non-empty, assertions whose resolved field path starts with a
126    /// segment that is NOT in this set are emitted as comments (skipped)
127    /// instead of executable assertions.  This prevents broken assertions
128    /// when fixtures reference fields from a different operation (e.g.,
129    /// `batch.completed_count` on a `ScrapeResult`).
130    #[serde(default)]
131    pub result_fields: HashSet<String>,
132    /// Fixture categories excluded from cross-language e2e codegen.
133    ///
134    /// Fixtures whose resolved category matches an entry in this set are
135    /// skipped by every per-language e2e generator — no test is emitted at
136    /// all (no skip directive, no commented-out body). The fixture files stay
137    /// on disk and remain available to Rust integration tests inside the
138    /// consumer crate's own `tests/` directory.
139    ///
140    /// Use this to keep fixtures that exercise internal middleware (cache,
141    /// proxy, budget, hooks, etc.) out of bindings whose public surface does
142    /// not expose those layers.
143    ///
144    /// Example:
145    /// ```toml
146    /// [e2e]
147    /// exclude_categories = ["cache", "proxy", "budget", "hooks"]
148    /// ```
149    #[serde(default)]
150    pub exclude_categories: HashSet<String>,
151    /// C FFI accessor type chain: maps `"{parent_snake_type}.{field}"` to the
152    /// PascalCase return type name (without prefix).
153    ///
154    /// Used by the C e2e generator to emit chained FFI accessor calls for
155    /// nested field paths. The root type is always `conversion_result`.
156    ///
157    /// Example:
158    /// ```toml
159    /// [e2e.fields_c_types]
160    /// "conversion_result.metadata" = "HtmlMetadata"
161    /// "html_metadata.document" = "DocumentMetadata"
162    /// ```
163    #[serde(default)]
164    pub fields_c_types: HashMap<String, String>,
165    /// Fields whose resolved type is an enum in the generated bindings.
166    ///
167    /// When a `contains` / `contains_all` / etc. assertion targets one of these
168    /// fields, language generators that cannot call `.contains()` directly on an
169    /// enum (e.g., Java) will emit a string-conversion call first.  For Java,
170    /// the generated assertion calls `.getValue()` on the enum — the `@JsonValue`
171    /// method that all alef-generated Java enums expose — to obtain the lowercase
172    /// serde string before performing the string comparison.
173    ///
174    /// Both the raw fixture field path (before alias resolution) and the resolved
175    /// path (after alias resolution via `[e2e.fields]`) are accepted, so you can
176    /// use either form:
177    ///
178    /// ```toml
179    /// # Raw fixture field:
180    /// fields_enum = ["links[].link_type", "assets[].category"]
181    /// # …or the resolved (aliased) field name:
182    /// fields_enum = ["links[].link_type", "assets[].asset_category"]
183    /// ```
184    #[serde(default)]
185    pub fields_enum: HashSet<String>,
186    /// Dependency mode: `Local` (default) or `Registry`.
187    /// Set at runtime via `--registry` CLI flag; not serialized from TOML.
188    #[serde(skip)]
189    pub dep_mode: DependencyMode,
190    /// Registry-mode configuration from `[e2e.registry]`.
191    #[serde(default)]
192    pub registry: RegistryConfig,
193}
194
195impl E2eConfig {
196    /// Resolve the call config for a fixture. Uses the named call if specified,
197    /// otherwise falls back to the default `[e2e.call]`.
198    pub fn resolve_call(&self, call_name: Option<&str>) -> &CallConfig {
199        match call_name {
200            Some(name) => self.calls.get(name).unwrap_or(&self.call),
201            None => &self.call,
202        }
203    }
204
205    /// Resolve the call config for a fixture, applying `select_when` auto-routing.
206    ///
207    /// When the fixture has an explicit `call` name, that named config is returned
208    /// (same as [`resolve_call`]).  When the fixture has no explicit call, the method
209    /// scans named calls for a [`SelectWhen`] condition that matches the fixture's
210    /// shape (id, category, tags, input) and returns the first match.  If no condition
211    /// matches, it falls back to the default `[e2e.call]`.
212    ///
213    /// All non-`None` discriminators on a `SelectWhen` must match (logical AND) for
214    /// the condition to fire. A `SelectWhen` with every field `None` never matches —
215    /// at least one discriminator must be set.
216    pub fn resolve_call_for_fixture(
217        &self,
218        call_name: Option<&str>,
219        fixture_id: &str,
220        fixture_category: &str,
221        fixture_tags: &[String],
222        fixture_input: &serde_json::Value,
223    ) -> &CallConfig {
224        if let Some(name) = call_name {
225            return self.calls.get(name).unwrap_or(&self.call);
226        }
227        // Auto-route by select_when condition. Deterministic order: sort by call name.
228        let mut names: Vec<&String> = self.calls.keys().collect();
229        names.sort();
230        for name in names {
231            let call_config = &self.calls[name];
232            if let Some(sel) = &call_config.select_when {
233                if sel.matches(fixture_id, fixture_category, fixture_tags, fixture_input) {
234                    return call_config;
235                }
236            }
237        }
238        &self.call
239    }
240
241    /// Resolve the effective package reference for a language.
242    ///
243    /// In registry mode, entries from `[e2e.registry.packages]` are merged on
244    /// top of the base `[e2e.packages]` — registry overrides win for any field
245    /// that is `Some`.
246    pub fn resolve_package(&self, lang: &str) -> Option<PackageRef> {
247        let base = self.packages.get(lang);
248        if self.dep_mode == DependencyMode::Registry {
249            let reg = self.registry.packages.get(lang);
250            match (base, reg) {
251                (Some(b), Some(r)) => Some(PackageRef {
252                    name: r.name.clone().or_else(|| b.name.clone()),
253                    path: r.path.clone().or_else(|| b.path.clone()),
254                    module: r.module.clone().or_else(|| b.module.clone()),
255                    version: r.version.clone().or_else(|| b.version.clone()),
256                }),
257                (None, Some(r)) => Some(r.clone()),
258                (Some(b), None) => Some(b.clone()),
259                (None, None) => None,
260            }
261        } else {
262            base.cloned()
263        }
264    }
265
266    /// Return the effective `result_fields` for `call`.
267    ///
268    /// Returns `call.result_fields` when non-empty, otherwise the global
269    /// `self.result_fields`.
270    pub fn effective_result_fields<'a>(&'a self, call: &'a CallConfig) -> &'a HashSet<String> {
271        if !call.result_fields.is_empty() {
272            &call.result_fields
273        } else {
274            &self.result_fields
275        }
276    }
277
278    /// Return the effective `fields` alias map for `call`.
279    pub fn effective_fields<'a>(&'a self, call: &'a CallConfig) -> &'a HashMap<String, String> {
280        if !call.fields.is_empty() {
281            &call.fields
282        } else {
283            &self.fields
284        }
285    }
286
287    /// Return the effective `fields_optional` for `call`.
288    pub fn effective_fields_optional<'a>(&'a self, call: &'a CallConfig) -> &'a HashSet<String> {
289        if !call.fields_optional.is_empty() {
290            &call.fields_optional
291        } else {
292            &self.fields_optional
293        }
294    }
295
296    /// Return the effective `fields_array` for `call`.
297    pub fn effective_fields_array<'a>(&'a self, call: &'a CallConfig) -> &'a HashSet<String> {
298        if !call.fields_array.is_empty() {
299            &call.fields_array
300        } else {
301            &self.fields_array
302        }
303    }
304
305    /// Return the effective `fields_method_calls` for `call`.
306    pub fn effective_fields_method_calls<'a>(&'a self, call: &'a CallConfig) -> &'a HashSet<String> {
307        if !call.fields_method_calls.is_empty() {
308            &call.fields_method_calls
309        } else {
310            &self.fields_method_calls
311        }
312    }
313
314    /// Return the effective `fields_enum` for `call`.
315    pub fn effective_fields_enum<'a>(&'a self, call: &'a CallConfig) -> &'a HashSet<String> {
316        if !call.fields_enum.is_empty() {
317            &call.fields_enum
318        } else {
319            &self.fields_enum
320        }
321    }
322
323    /// Return the effective `fields_c_types` for `call`.
324    pub fn effective_fields_c_types<'a>(&'a self, call: &'a CallConfig) -> &'a HashMap<String, String> {
325        if !call.fields_c_types.is_empty() {
326            &call.fields_c_types
327        } else {
328            &self.fields_c_types
329        }
330    }
331
332    /// Return the effective output directory: `registry.output` in registry
333    /// mode, `output` otherwise.
334    pub fn effective_output(&self) -> &str {
335        if self.dep_mode == DependencyMode::Registry {
336            &self.registry.output
337        } else {
338            &self.output
339        }
340    }
341
342    /// Relative path from a backend's emission directory to the
343    /// `test_documents_dir` at the repo root.
344    ///
345    /// `emission_depth` counts the number of additional `../` segments needed
346    /// to reach `<output>/<lang>/` from where the file is being emitted:
347    ///
348    /// * `0` — emitted directly at `e2e/<lang>/` (e.g. dart, zig `build.zig`)
349    /// * `1` — emitted at `e2e/<lang>/<sub>/` (e.g. ruby `spec/`, R `tests/`)
350    /// * `2` — emitted at `e2e/<lang>/<sub1>/<sub2>/`
351    ///
352    /// The base prefix is two segments above `<output>/<lang>/` (i.e.
353    /// `../../`), matching the canonical layout where `<output>` (default
354    /// `"e2e"`) sits at the repo root next to the configured
355    /// `test_documents_dir`.
356    pub fn test_documents_relative_from(&self, emission_depth: usize) -> String {
357        let mut up = String::from("../../");
358        for _ in 0..emission_depth {
359            up.push_str("../");
360        }
361        format!("{up}{}", self.test_documents_dir)
362    }
363}
364
365fn default_fixtures_dir() -> String {
366    "fixtures".to_string()
367}
368
369fn default_output_dir() -> String {
370    "e2e".to_string()
371}
372
373fn default_test_documents_dir() -> String {
374    "test_documents".to_string()
375}
376
377/// Hand-rolled `Default` so the `test_documents_dir` field receives its
378/// `default_test_documents_dir()` value (`"test_documents"`) when callers use
379/// `..Default::default()` to construct an `E2eConfig` literally rather than
380/// going through `serde::Deserialize`. Without this, `derive(Default)` would
381/// fall back to `String::default()` (i.e. the empty string), and any backend
382/// computing `test_documents_relative_from(0)` would emit `"../../"` (no dir
383/// component), breaking generated chdir hooks.
384impl Default for E2eConfig {
385    fn default() -> Self {
386        Self {
387            fixtures: default_fixtures_dir(),
388            output: default_output_dir(),
389            test_documents_dir: default_test_documents_dir(),
390            languages: Vec::new(),
391            call: CallConfig::default(),
392            calls: HashMap::new(),
393            packages: HashMap::new(),
394            harness_extras: HashMap::new(),
395            format: HashMap::new(),
396            fields: HashMap::new(),
397            fields_optional: HashSet::new(),
398            fields_array: HashSet::new(),
399            fields_method_calls: HashSet::new(),
400            result_fields: HashSet::new(),
401            exclude_categories: HashSet::new(),
402            fields_c_types: HashMap::new(),
403            fields_enum: HashSet::new(),
404            dep_mode: DependencyMode::default(),
405            registry: RegistryConfig::default(),
406        }
407    }
408}
409
410/// Configuration for the function call in each test.
411#[derive(Debug, Clone, Serialize, Deserialize, Default)]
412pub struct CallConfig {
413    /// Per-call override for `result_fields`.
414    ///
415    /// When non-empty, this set replaces the global `[e2e].result_fields` for
416    /// fixtures routed to this call.  Use this when different API functions return
417    /// differently-shaped structs so each call can gate its own field set.
418    ///
419    /// Example:
420    /// ```toml
421    /// [e2e.calls.crawl]
422    /// result_fields = ["pages", "final_url", "stayed_on_domain"]
423    /// ```
424    #[serde(default)]
425    pub result_fields: HashSet<String>,
426    /// Per-call override for `[e2e].fields` alias map.
427    ///
428    /// When non-empty, replaces (not merges with) the global `fields` map for
429    /// fixtures routed to this call.
430    #[serde(default)]
431    pub fields: HashMap<String, String>,
432    /// Per-call override for `[e2e].fields_optional`.
433    #[serde(default)]
434    pub fields_optional: HashSet<String>,
435    /// Per-call override for `[e2e].fields_array`.
436    #[serde(default)]
437    pub fields_array: HashSet<String>,
438    /// Per-call override for `[e2e].fields_method_calls`.
439    #[serde(default)]
440    pub fields_method_calls: HashSet<String>,
441    /// Per-call override for `[e2e].fields_enum`.
442    #[serde(default)]
443    pub fields_enum: HashSet<String>,
444    /// Per-call override for `[e2e].fields_c_types`.
445    #[serde(default)]
446    pub fields_c_types: HashMap<String, String>,
447    /// The function name (alef applies language naming conventions).
448    #[serde(default)]
449    pub function: String,
450    /// The module/package where the function lives.
451    #[serde(default)]
452    pub module: String,
453    /// Variable name for the return value (default: "result").
454    #[serde(default = "default_result_var")]
455    pub result_var: String,
456    /// Whether the function is async.
457    #[serde(default)]
458    pub r#async: bool,
459    /// HTTP endpoint path for mock server routing (e.g., `"/v1/chat/completions"`).
460    ///
461    /// Required when fixtures use `mock_response`. The Rust e2e generator uses
462    /// this to build the `MockRoute` that the mock server matches against.
463    #[serde(default)]
464    pub path: Option<String>,
465    /// HTTP method for mock server routing (default: `"POST"`).
466    ///
467    /// Used together with `path` when building `MockRoute` entries.
468    #[serde(default)]
469    pub method: Option<String>,
470    /// How fixture `input` fields map to function arguments.
471    #[serde(default)]
472    pub args: Vec<ArgMapping>,
473    /// Per-language overrides for module/function/etc.
474    #[serde(default)]
475    pub overrides: HashMap<String, CallOverride>,
476    /// Whether the function returns `Result<T, E>` in its native binding.
477    /// Defaults to `true`. When `false`, generators that distinguish Result-returning
478    /// from non-Result-returning calls (currently Rust) will skip the
479    /// `.expect("should succeed")` unwrap and bind the raw return value directly.
480    #[serde(default = "default_returns_result")]
481    pub returns_result: bool,
482    /// Whether the function returns only an error/unit — i.e., `Result<(), E>`.
483    ///
484    /// When combined with `returns_result = true`, Go generators emit `err := func()`
485    /// (single return value) rather than `_, err := func()` (two return values).
486    /// This is needed for functions like `validate_host` that return only `error` in Go.
487    #[serde(default)]
488    pub returns_void: bool,
489    /// skip_languages
490    #[serde(default)]
491    pub skip_languages: Vec<String>,
492    /// When `true`, the function returns a primitive (e.g. `String`, `bool`,
493    /// `i32`) rather than a struct.  Generators that would otherwise emit
494    /// `result.<field>` will fall back to the bare result variable.
495    ///
496    /// This is a property of the Rust core's return type and therefore identical
497    /// across every binding — set it on the call, not in per-language overrides.
498    /// The same flag is also accepted under `[e2e.calls.<name>.overrides.<lang>]`
499    /// for backwards compatibility, but the call-level value takes precedence.
500    #[serde(default)]
501    pub result_is_simple: bool,
502    /// When `true`, the function returns `Vec<T>` / `Array<T>`.  Generators that
503    /// support per-element field assertions (rust, csharp) iterate or index into
504    /// the result; the typescript codegen indexes `[0]` to mirror csharp.
505    ///
506    /// As with `result_is_simple`, this is a Rust-side property — set it on the
507    /// call, not on per-language overrides. Per-language overrides remain
508    /// supported for backwards compatibility.
509    #[serde(default)]
510    pub result_is_vec: bool,
511    /// When `true` (combined with `result_is_simple`), the simple return is a
512    /// slice/array (e.g., `Vec<String>` → `string[]` in TS).
513    #[serde(default)]
514    pub result_is_array: bool,
515    /// When `true`, the function returns a raw byte array (`Vec<u8>` →
516    /// `Uint8Array` / `[]byte` / `byte[]`).
517    #[serde(default)]
518    pub result_is_bytes: bool,
519    /// Three-valued opt-in/out for streaming-virtual-field auto-detection.
520    ///
521    /// - `Some(true)`: force streaming semantics regardless of fixture shape.
522    /// - `Some(false)`: disable streaming auto-detection — assertions referencing
523    ///   fields like `chunks` / `chunks.length` / `tool_calls` / `finish_reason`
524    ///   are treated as plain field accessors on the result, not streaming
525    ///   adapters. Use this when your API has a `chunks` field that is a regular
526    ///   list (not an async stream).
527    /// - `None` (default): auto-detect — treat as streaming when either the
528    ///   fixture provides a streaming `mock_response` or any assertion references
529    ///   a hard-coded streaming-virtual-field name.
530    #[serde(default)]
531    pub streaming: Option<bool>,
532    /// When `true`, the function returns `Option<T>`.
533    #[serde(default)]
534    pub result_is_option: bool,
535    /// When `true` (combined with `result_is_simple` + `result_is_array`),
536    /// signals that the result is `Vec<String>` returned to the host as a
537    /// native string array (e.g., Swift `[String]`) rather than an opaque
538    /// `RustVec<RustString>` requiring `.asStr().toString()` per element.
539    ///
540    /// Generators that emit per-element coercion for opaque RustVec types
541    /// (currently Swift) drop the coercion and operate on the elements as
542    /// native strings when this flag is set.
543    #[serde(default)]
544    pub result_element_is_string: bool,
545    /// Automatic fixture-routing condition.
546    ///
547    /// When set, a fixture whose `call` field is `None` is routed to this named call config
548    /// if the condition is satisfied.  This avoids the need to tag every fixture with
549    /// `"call": "batch_scrape"` when the fixture shape already identifies the call.
550    ///
551    /// Example (`alef.toml`):
552    /// ```toml
553    /// [e2e.calls.batch_scrape]
554    /// select_when = { input_has = "batch_urls" }
555    /// ```
556    #[serde(default)]
557    pub select_when: Option<SelectWhen>,
558    /// Call-level constructor type for `json_object` config args.
559    ///
560    /// This is the type of the function's config parameter (e.g. `EmbeddingConfig`
561    /// vs `ExtractionConfig`) and is therefore identical across every binding — set
562    /// it on the call, not in per-language overrides. Per-language overrides
563    /// (`[e2e.calls.<name>.overrides.<lang>].options_type`) still take precedence
564    /// when a binding exposes a language-specific wrapper type (e.g. `JsExtractionConfig`).
565    #[serde(default)]
566    pub options_type: Option<String>,
567}
568
569fn default_result_var() -> String {
570    "result".to_string()
571}
572
573fn default_returns_result() -> bool {
574    false
575}
576
577/// Condition for auto-selecting a named call config when the fixture matches.
578///
579/// When a fixture does not specify `"call"`, the codegen normally uses the default
580/// `[e2e.call]`.  A `SelectWhen` condition on a named call allows automatic routing
581/// based on the fixture's id, category, tags, or input shape.  All set fields must
582/// match (logical AND); a condition with no fields set never matches.
583///
584/// ```toml
585/// [e2e.calls.batch_scrape]
586/// select_when = { input_has = "batch_urls" }
587///
588/// [e2e.calls.crawl]
589/// select_when = { category = "crawl" }
590///
591/// [e2e.calls.batch_crawl_stream]
592/// select_when = { category = "stream", id_prefix = "batch_crawl_stream" }
593/// ```
594#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
595pub struct SelectWhen {
596    /// Match when the fixture's resolved category equals this string.
597    #[serde(default)]
598    pub category: Option<String>,
599    /// Match when the fixture's id starts with this prefix.
600    #[serde(default)]
601    pub id_prefix: Option<String>,
602    /// Match when the fixture's id matches this simple glob.
603    ///
604    /// Only `*` (matches any run of characters) is supported. Use `id_prefix`
605    /// for plain prefix matches.
606    #[serde(default)]
607    pub id_glob: Option<String>,
608    /// Match when the fixture's tags include this tag.
609    #[serde(default)]
610    pub tag: Option<String>,
611    /// Match when the fixture's input object contains this key with a non-null value.
612    #[serde(default)]
613    pub input_has: Option<String>,
614}
615
616impl SelectWhen {
617    /// Returns true when every set discriminator matches the fixture.
618    ///
619    /// A `SelectWhen` with all fields `None` returns `false` — at least one
620    /// discriminator must be set for the condition to fire.
621    pub fn matches(
622        &self,
623        fixture_id: &str,
624        fixture_category: &str,
625        fixture_tags: &[String],
626        fixture_input: &serde_json::Value,
627    ) -> bool {
628        let any_set = self.category.is_some()
629            || self.id_prefix.is_some()
630            || self.id_glob.is_some()
631            || self.tag.is_some()
632            || self.input_has.is_some();
633        if !any_set {
634            return false;
635        }
636        if let Some(cat) = &self.category
637            && cat.as_str() != fixture_category
638        {
639            return false;
640        }
641        if let Some(prefix) = &self.id_prefix
642            && !fixture_id.starts_with(prefix.as_str())
643        {
644            return false;
645        }
646        if let Some(glob) = &self.id_glob
647            && !glob_matches(glob, fixture_id)
648        {
649            return false;
650        }
651        if let Some(tag) = &self.tag
652            && !fixture_tags.iter().any(|t| t == tag)
653        {
654            return false;
655        }
656        if let Some(key) = &self.input_has {
657            let val = fixture_input.get(key.as_str()).unwrap_or(&serde_json::Value::Null);
658            if val.is_null() {
659                return false;
660            }
661        }
662        true
663    }
664}
665
666/// Minimal glob matcher supporting `*` (greedy any-run) only.
667fn glob_matches(pattern: &str, text: &str) -> bool {
668    if !pattern.contains('*') {
669        return pattern == text;
670    }
671    let parts: Vec<&str> = pattern.split('*').collect();
672    let mut cursor = 0usize;
673    for (idx, part) in parts.iter().enumerate() {
674        if part.is_empty() {
675            continue;
676        }
677        if idx == 0 {
678            if !text[cursor..].starts_with(part) {
679                return false;
680            }
681            cursor += part.len();
682        } else if idx + 1 == parts.len() && !pattern.ends_with('*') {
683            return text[cursor..].ends_with(part);
684        } else {
685            match text[cursor..].find(part) {
686                Some(pos) => cursor += pos + part.len(),
687                None => return false,
688            }
689        }
690    }
691    true
692}
693
694/// Maps a fixture input field to a function argument.
695#[derive(Debug, Clone, Serialize, Deserialize)]
696pub struct ArgMapping {
697    /// Argument name in the function signature.
698    pub name: String,
699    /// JSON field path in the fixture's `input` object.
700    pub field: String,
701    /// Type hint for code generation.
702    #[serde(rename = "type", default = "default_arg_type")]
703    pub arg_type: String,
704    /// Whether this argument is optional.
705    #[serde(default)]
706    pub optional: bool,
707    /// When `true`, the Rust codegen passes this argument by value (owned) rather than
708    /// by reference. Use for `Vec<T>` parameters that do not accept `&Vec<T>`.
709    #[serde(default)]
710    pub owned: bool,
711    /// For `json_object` args targeting `&[T]` Rust parameters, set to the element type
712    /// (e.g. `"f32"`, `"String"`) so the codegen emits `Vec<element_type>` annotation.
713    #[serde(default)]
714    pub element_type: Option<String>,
715    /// Override the Go slice element type for `json_object` array args.
716    ///
717    /// When set, the Go e2e codegen uses this as the element type instead of the default
718    /// derived from `element_type`. Use Go-idiomatic type names including the import alias
719    /// prefix where needed, e.g. `"kreuzberg.BatchBytesItem"` or `"string"`.
720    #[serde(default)]
721    pub go_type: Option<String>,
722}
723
724fn default_arg_type() -> String {
725    "string".to_string()
726}
727
728/// Per-language override for function call configuration.
729#[derive(Debug, Clone, Serialize, Deserialize, Default)]
730pub struct CallOverride {
731    /// Override the module/import path.
732    #[serde(default)]
733    pub module: Option<String>,
734    /// Override the function name.
735    #[serde(default)]
736    pub function: Option<String>,
737    /// Maps canonical argument names to language-specific argument names.
738    ///
739    /// Used when a language binding uses a different parameter name than the
740    /// canonical `args` list in `CallConfig`. For example, if the canonical
741    /// arg name is `doc` but the Python binding uses `html`, specify:
742    ///
743    /// ```toml
744    /// [e2e.call.overrides.python]
745    /// arg_name_map = { doc = "html" }
746    /// ```
747    ///
748    /// The key is the canonical name (from `args[].name`) and the value is the
749    /// name to use when emitting the keyword argument in generated tests.
750    #[serde(default)]
751    pub arg_name_map: HashMap<String, String>,
752    /// Override the crate name (Rust only).
753    #[serde(default)]
754    pub crate_name: Option<String>,
755    /// Override the class name (Java/C# only).
756    #[serde(default)]
757    pub class: Option<String>,
758    /// Import alias (Go only, e.g., `htmd`).
759    #[serde(default)]
760    pub alias: Option<String>,
761    /// C header file name (C only).
762    #[serde(default)]
763    pub header: Option<String>,
764    /// FFI symbol prefix (C only).
765    #[serde(default)]
766    pub prefix: Option<String>,
767    /// For json_object args: the constructor to use instead of raw dict/object.
768    /// E.g., "ConversionOptions" — generates `ConversionOptions(**options)` in Python,
769    /// `new ConversionOptions(options)` in TypeScript.
770    #[serde(default)]
771    pub options_type: Option<String>,
772    /// How to pass json_object args: "kwargs" (default), "dict", "json", or "from_json".
773    ///
774    /// - `"kwargs"`: construct `OptionsType(key=val, ...)` (requires `options_type`).
775    /// - `"dict"`: pass as a plain dict/object literal `{"key": "val"}`.
776    /// - `"json"`: pass via `json.loads('...')` / `JSON.parse('...')`.
777    /// - `"from_json"`: call `OptionsType.from_json('...')` (Python only, PyO3 native types).
778    #[serde(default)]
779    pub options_via: Option<String>,
780    /// Module to import `options_type` from when `options_via = "from_json"`.
781    ///
782    /// When set, a separate `from {from_json_module} import {options_type}` line
783    /// is emitted instead of including the type in the main module import.
784    /// E.g., `"liter_llm._internal_bindings"` for PyO3 native types.
785    #[serde(default)]
786    pub from_json_module: Option<String>,
787    /// Override whether the call is async for this language.
788    ///
789    /// When set, takes precedence over the call-level `async` flag.
790    /// Useful when a language binding uses a different async model — for example,
791    /// a Python binding that returns a sync iterator from a function marked
792    /// `async = true` at the call level.
793    #[serde(default, rename = "async")]
794    pub r#async: Option<bool>,
795    /// Maps fixture option field names to their enum type names.
796    /// E.g., `{"headingStyle": "HeadingStyle", "codeBlockStyle": "CodeBlockStyle"}`.
797    /// The generator imports these types and maps string values to enum constants.
798    #[serde(default)]
799    pub enum_fields: HashMap<String, String>,
800    /// Maps result-type field names to their enum type names for assertion routing.
801    /// Per-call so e.g. `BatchObject.status` (enum) and `ResponseObject.status` (string)
802    /// can be disambiguated.
803    #[serde(default)]
804    pub assert_enum_fields: HashMap<String, String>,
805    /// Module to import enum types from (if different from the main module).
806    /// E.g., "html_to_markdown._html_to_markdown" for PyO3 native enums.
807    #[serde(default)]
808    pub enum_module: Option<String>,
809    /// Maps nested fixture object field names to their C# type names.
810    /// Used to generate `JsonSerializer.Deserialize<NestedType>(...)` for nested objects.
811    /// E.g., `{"preprocessing": "PreprocessingOptions"}`.
812    #[serde(default)]
813    pub nested_types: HashMap<String, String>,
814    /// When `false`, nested config builder results are passed directly to builder methods
815    /// without wrapping in `Optional.of(...)`. Set to `false` for bindings where nested
816    /// option types are non-optional (e.g., html-to-markdown Java).
817    /// Defaults to `true` for backward compatibility.
818    #[serde(default = "default_true")]
819    pub nested_types_optional: bool,
820    /// When `true`, the function returns a simple type (e.g., `String`) rather
821    /// than a struct.  Generators that would normally emit `result.content`
822    /// (or equivalent field access) will use the result variable directly.
823    #[serde(default)]
824    pub result_is_simple: bool,
825    /// When `true` (and combined with `result_is_simple`), the simple result is
826    /// a slice/array type (e.g., `[]string` in Go, `Vec<String>` in Rust).
827    /// The Go generator uses `strings.Join(value, " ")` for `contains` assertions
828    /// instead of `string(value)`.
829    #[serde(default)]
830    pub result_is_array: bool,
831    /// When `true`, the function returns `Vec<T>` rather than a single value.
832    /// Field-path assertions are emitted as `.iter().all(|r| <accessor>)` so
833    /// every element is checked. (Rust generator.)
834    #[serde(default)]
835    pub result_is_vec: bool,
836    /// When `true`, the function returns a raw byte array (e.g., `byte[]` in Java,
837    /// `[]byte` in Go). Used by generators to select the correct length accessor
838    /// (field `.length` vs method `.length()`).
839    #[serde(default)]
840    pub result_is_bytes: bool,
841    /// When `true`, the function returns `Option<T>`. The result is unwrapped
842    /// before any non-`is_none`/`is_some` assertion runs; `is_empty`/`not_empty`
843    /// assertions map to `is_none()`/`is_some()`. (Rust generator.)
844    #[serde(default)]
845    pub result_is_option: bool,
846    /// When `true`, the R generator emits the call result directly without wrapping
847    /// in `jsonlite::fromJSON()`. Use when the R binding already returns a native
848    /// R list (`Robj`) rather than a JSON string. Field-path assertions still use
849    /// `result$field` accessor syntax (i.e. `result_is_simple` behaviour is NOT
850    /// implied — only the JSON parse wrapper is suppressed). (R generator only.)
851    #[serde(default)]
852    pub result_is_r_list: bool,
853    /// When `true`, the Zig generator treats the result as a `[]u8` JSON string
854    /// representing a struct value (e.g., `ExtractionResult` serialized via the
855    /// FFI `_to_json` helper). The generator parses the JSON with
856    /// `std.json.parseFromSlice(std.json.Value, ...)` before emitting field
857    /// assertions, traversing the dynamic JSON object for each field path.
858    /// (Zig generator only.)
859    #[serde(default)]
860    pub result_is_json_struct: bool,
861    /// When `true`, the Rust generator wraps the `json_object` argument expression
862    /// in `Some(...).clone()` to match an owned `Option<T>` parameter slot rather
863    /// than passing `&options`. (Rust generator only.)
864    #[serde(default)]
865    pub wrap_options_in_some: bool,
866    /// Trailing positional arguments appended verbatim after the configured
867    /// `args`. Used when the target function takes additional positional slots
868    /// (e.g. visitor) the fixture cannot supply directly. (Rust generator only.)
869    #[serde(default)]
870    pub extra_args: Vec<String>,
871    /// Per-rust override of the call-level `returns_result`. When set, takes
872    /// precedence over `CallConfig.returns_result` for the Rust generator only.
873    /// Useful when one binding is fallible while others are not.
874    #[serde(default)]
875    pub returns_result: Option<bool>,
876    /// Maps handle config field names to their Python type constructor names.
877    ///
878    /// When the handle config object contains a nested dict-valued field, the
879    /// generator will wrap it in the specified type using keyword arguments.
880    /// E.g., `{"browser": "BrowserConfig"}` generates `BrowserConfig(mode="auto")`
881    /// instead of `{"mode": "auto"}`.
882    #[serde(default)]
883    pub handle_nested_types: HashMap<String, String>,
884    /// Handle config fields whose type constructor takes a single dict argument
885    /// instead of keyword arguments.
886    ///
887    /// E.g., `["auth"]` means `AuthConfig({"type": "basic", ...})` instead of
888    /// `AuthConfig(type="basic", ...)`.
889    #[serde(default)]
890    pub handle_dict_types: HashSet<String>,
891    /// Elixir struct module name for the handle config argument.
892    ///
893    /// When set, the generated Elixir handle config uses struct literal syntax
894    /// (`%Module.StructType{key: val}`) instead of a plain string-keyed map.
895    /// Rustler `NifStruct` requires a proper Elixir struct — plain maps are rejected.
896    ///
897    /// E.g., `"CrawlConfig"` generates `%Kreuzcrawl.CrawlConfig{download_assets: true}`.
898    #[serde(default)]
899    pub handle_struct_type: Option<String>,
900    /// Handle config fields whose list values are Elixir atoms (Rustler NifUnitEnum).
901    ///
902    /// When a config field is a `Vec<EnumType>` in Rust, the Elixir side must pass
903    /// a list of atoms (e.g., `[:image, :document]`) not strings (`["image"]`).
904    /// List the field names here so the generator emits atom literals instead of strings.
905    ///
906    /// E.g., `["asset_types"]` generates `asset_types: [:image]` instead of `["image"]`.
907    #[serde(default)]
908    pub handle_atom_list_fields: HashSet<String>,
909    /// WASM config class name for handle args (WASM generator only).
910    ///
911    /// When set, handle args are constructed using `ConfigType.default()` + setters
912    /// instead of passing a plain JS object (which fails `_assertClass` validation).
913    ///
914    /// E.g., `"WasmCrawlConfig"` generates:
915    /// ```js
916    /// const engineConfig = WasmCrawlConfig.default();
917    /// engineConfig.maxDepth = 1;
918    /// const engine = createEngine(engineConfig);
919    /// ```
920    #[serde(default)]
921    pub handle_config_type: Option<String>,
922    /// PHP client factory method name (PHP generator only).
923    ///
924    /// When set, the generated PHP test instantiates a client via
925    /// `ClassName::factory_method('test-key')` and calls methods on the instance
926    /// instead of using static facade calls.
927    ///
928    /// E.g., `"createClient"` generates:
929    /// ```php
930    /// $client = LiterLlm::createClient('test-key');
931    /// $result = $client->chat($request);
932    /// ```
933    #[serde(default)]
934    pub php_client_factory: Option<String>,
935    /// Client factory function name for instance-method languages (WASM, etc.).
936    ///
937    /// When set, the generated test imports this function, creates a client,
938    /// and calls API methods on the instance instead of as top-level functions.
939    ///
940    /// E.g., `"createClient"` generates:
941    /// ```typescript
942    /// import { createClient } from 'pkg';
943    /// const client = createClient('test-key');
944    /// const result = await client.chat(request);
945    /// ```
946    #[serde(default)]
947    pub client_factory: Option<String>,
948    /// Verbatim trailing arguments appended after the fixed `("test-key", ...)` pair
949    /// when calling the `client_factory` function.
950    ///
951    /// Use this when the factory function takes additional positional parameters
952    /// beyond the API key and optional base URL that the generator would otherwise
953    /// emit.  Each element is emitted verbatim, separated by `, `.
954    ///
955    /// Example — Gleam `create_client` takes five positional arguments:
956    /// `(api_key, base_url, timeout_secs, max_retries, model_hint)`.  Set:
957    /// ```toml
958    /// [e2e.call.overrides.gleam]
959    /// client_factory = "create_client"
960    /// client_factory_trailing_args = ["option.None", "option.None", "option.None"]
961    /// ```
962    /// to produce `create_client("test-key", option.Some(url), option.None, option.None, option.None)`.
963    #[serde(default)]
964    pub client_factory_trailing_args: Vec<String>,
965    /// Fields on the options object that require `BigInt()` wrapping (WASM only).
966    ///
967    /// `wasm_bindgen` maps Rust `u64`/`i64` to JavaScript `BigInt`. Numeric
968    /// values assigned to these setters must be wrapped with `BigInt(n)`.
969    ///
970    /// List camelCase field names, e.g.:
971    /// ```toml
972    /// [e2e.call.overrides.wasm]
973    /// bigint_fields = ["maxTokens", "seed"]
974    /// ```
975    #[serde(default)]
976    pub bigint_fields: Vec<String>,
977    /// Static CLI arguments appended to every invocation (brew/CLI generator only).
978    ///
979    /// E.g., `["--format", "json"]` appends `--format json` to every CLI call.
980    #[serde(default)]
981    pub cli_args: Vec<String>,
982    /// Maps fixture config field names to CLI flag names (brew/CLI generator only).
983    ///
984    /// E.g., `{"output_format": "--format"}` generates `--format <value>` from
985    /// the fixture's `output_format` input field.
986    #[serde(default)]
987    pub cli_flags: HashMap<String, String>,
988    /// C FFI opaque result type name (C only).
989    ///
990    /// The PascalCase name of the result struct, without the prefix.
991    /// E.g., `"ChatCompletionResponse"` for `LiterllmChatCompletionResponse*`.
992    /// If not set, defaults to the function name in PascalCase.
993    #[serde(default)]
994    pub result_type: Option<String>,
995    /// Override the argument order for this language binding.
996    ///
997    /// Lists argument names from `args` in the order they should be passed
998    /// to the target function. Useful when a language binding reorders parameters
999    /// relative to the canonical `args` list in `CallConfig`.
1000    ///
1001    /// E.g., if `args = [path, mime_type, config]` but the Node.js binding
1002    /// takes `(path, config, mime_type?)`, specify:
1003    /// ```toml
1004    /// [e2e.call.overrides.node]
1005    /// arg_order = ["path", "config", "mime_type"]
1006    /// ```
1007    #[serde(default)]
1008    pub arg_order: Vec<String>,
1009    /// When `true`, `json_object` args with an `options_type` are passed as a
1010    /// pointer (`*OptionsType`) rather than a value.  Use for Go bindings where
1011    /// the options parameter is `*ConversionOptions` (nil-able pointer) rather
1012    /// than a plain struct.
1013    ///
1014    /// Absent options are passed as `nil`; present options are unmarshalled into
1015    /// a local variable and passed as `&optionsVar`.
1016    #[serde(default)]
1017    pub options_ptr: bool,
1018    /// Alternative function name to use when the fixture includes a `visitor`.
1019    ///
1020    /// Some bindings expose two entry points: `Convert(html, opts)` for the
1021    /// plain case and `ConvertWithVisitor(html, opts, visitor)` when a visitor
1022    /// is involved.  Set this to the visitor-accepting function name so the
1023    /// generator can pick the right symbol automatically.
1024    ///
1025    /// E.g., `"ConvertWithVisitor"` makes the Go generator emit:
1026    /// ```go
1027    /// result, err := htmd.ConvertWithVisitor(html, nil, visitor)
1028    /// ```
1029    /// instead of `htmd.Convert(html, nil, visitor)` (which would not compile).
1030    #[serde(default)]
1031    pub visitor_function: Option<String>,
1032    /// Rust trait names to import when `client_factory` is set (Rust generator only).
1033    ///
1034    /// When `client_factory` is set, the generated test creates a client object and
1035    /// calls methods on it. Those methods are defined on traits (e.g. `LlmClient`,
1036    /// `FileClient`) that must be in scope. List the trait names here and the Rust
1037    /// generator will emit `use {module}::{trait_name};` for each.
1038    ///
1039    /// E.g.:
1040    /// ```toml
1041    /// [e2e.call.overrides.rust]
1042    /// client_factory = "create_client"
1043    /// trait_imports = ["LlmClient", "FileClient", "BatchClient", "ResponseClient"]
1044    /// ```
1045    #[serde(default)]
1046    pub trait_imports: Vec<String>,
1047    /// Raw C return type, used verbatim instead of `{PREFIX}Type*` (C only).
1048    ///
1049    /// Valid values: `"char*"`, `"int32_t"`, `"uintptr_t"`.
1050    /// When set, the C generator skips options handle construction and uses the
1051    /// raw type directly. Free logic is adjusted accordingly.
1052    #[serde(default)]
1053    pub raw_c_result_type: Option<String>,
1054    /// Free function for raw `char*` C results (C only).
1055    ///
1056    /// Defaults to `{prefix}_free_string` when unset and `raw_c_result_type == "char*"`.
1057    #[serde(default)]
1058    pub c_free_fn: Option<String>,
1059    /// C FFI engine factory pattern (C only).
1060    ///
1061    /// When set, the C generator wraps each test call in a
1062    /// `{prefix}_create_engine(config)` / `{prefix}_crawl_engine_handle_free(engine)`
1063    /// prologue/epilogue using the named config type as the "arg 0" handle type.
1064    ///
1065    /// The value is the PascalCase config type name (without prefix), e.g.
1066    /// `"CrawlConfig"`. The generator will emit:
1067    /// ```c
1068    /// KCRAWLCrawlConfig* config_handle = kcrawl_crawl_config_from_json("{json}");
1069    /// KCRAWLCrawlEngineHandle* engine = kcrawl_create_engine(config_handle);
1070    /// kcrawl_crawl_config_free(config_handle);
1071    /// KCRAWLScrapeResult* result = kcrawl_scrape(engine, url);
1072    /// // ... assertions ...
1073    /// kcrawl_scrape_result_free(result);
1074    /// kcrawl_crawl_engine_handle_free(engine);
1075    /// ```
1076    #[serde(default)]
1077    pub c_engine_factory: Option<String>,
1078    /// Fields in a `json_object` arg that must be wrapped in `java.nio.file.Path.of()`
1079    /// (Java generator only).
1080    ///
1081    /// E.g., `["cache_dir"]` wraps the string value of `cache_dir` so the builder
1082    /// receives `java.nio.file.Path.of("/tmp/dir")` instead of a plain string.
1083    #[serde(default)]
1084    pub path_fields: Vec<String>,
1085    /// Trait name for the visitor pattern (Rust e2e tests only).
1086    ///
1087    /// When a fixture declares a `visitor` block, the Rust e2e generator emits
1088    /// `impl <trait_name> for _TestVisitor { ... }` and imports the trait from
1089    /// `{module}::visitor`. When unset, no visitor block is emitted and fixtures
1090    /// that declare a visitor will cause a codegen error.
1091    ///
1092    /// E.g., `"HtmlVisitor"` generates:
1093    /// ```rust,ignore
1094    /// use html_to_markdown_rs::visitor::{HtmlVisitor, NodeContext, VisitResult};
1095    /// // ...
1096    /// impl HtmlVisitor for _TestVisitor { ... }
1097    /// ```
1098    #[serde(default)]
1099    pub visitor_trait: Option<String>,
1100    /// Maps result field paths to their wasm-bindgen enum class names.
1101    ///
1102    /// wasm-bindgen exposes Rust enums as numeric discriminants in JavaScript
1103    /// (`WasmFinishReason.Stop === 0`), not string variants. When an `equals`
1104    /// assertion targets a field listed here, the WASM generator emits
1105    /// `expect(result.choices[0].finishReason).toBe(WasmFinishReason.Stop)`
1106    /// instead of attempting `(value ?? "").trim()`.
1107    ///
1108    /// The fixture's expected string value is converted to PascalCase to look
1109    /// up the variant (e.g. `"tool_calls"` -> `ToolCalls`).
1110    ///
1111    /// Example:
1112    /// ```toml
1113    /// [e2e.calls.chat.overrides.wasm]
1114    /// result_enum_fields = { "choices[0].finish_reason" = "WasmFinishReason", "status" = "WasmBatchStatus" }
1115    /// ```
1116    #[serde(default)]
1117    pub result_enum_fields: HashMap<String, String>,
1118    /// When `true`, indicates that the result is a pointer type (e.g., `*string` in Go,
1119    /// `*T` in Rust). The Go codegen will dereference it. When `false` (Go only), the
1120    /// result is a value type and should not be dereferenced.
1121    ///
1122    /// Used to distinguish between functions that return `(value, error)` where value
1123    /// is a scalar (string, uint, bool) as-is vs. those that return pointers.
1124    /// Defaults to `true` for backward compatibility with existing fixtures.
1125    #[serde(default = "default_true")]
1126    pub result_is_pointer: bool,
1127    /// Per-language override mirroring `CallConfig.result_element_is_string`.
1128    ///
1129    /// Set this on a per-language override when only one host's binding exposes
1130    /// the result as a native string array; otherwise prefer the call-level flag.
1131    #[serde(default)]
1132    pub result_element_is_string: bool,
1133    /// Maps array-typed result fields to the method name on each element that
1134    /// yields a string used in `contains` / `contains_all` assertions.
1135    ///
1136    /// Used when the array element is an opaque struct (e.g., a swift-bridge
1137    /// `type X;` declaration) and the element's "name" accessor is not the
1138    /// default `as_str` — for instance, `StructureItem` exposes `kind() -> String`
1139    /// instead of `as_str()`. The codegen consults this map when emitting
1140    /// `.map { $0.<accessor>().toString() }` so the closure compiles.
1141    ///
1142    /// Example:
1143    /// ```toml
1144    /// [e2e.call.overrides.swift]
1145    /// result_field_accessor = { "structure" = "kind" }
1146    /// ```
1147    #[serde(default)]
1148    pub result_field_accessor: HashMap<String, String>,
1149    /// Argument indices (0-based) that should be passed without labels in Swift
1150    /// (i.e., using `(_` parameter syntax instead of `name:`).
1151    ///
1152    /// Swift allows unnamed first parameters: `func f(_ x: Int)` vs `func f(x: Int)`.
1153    /// When the generated test call should match this signature, list the indices here.
1154    ///
1155    /// E.g., `[0]` for a single unnamed first parameter:
1156    /// ```toml
1157    /// [e2e.call.overrides.swift]
1158    /// unnamed_arg_indices = [0]
1159    /// ```
1160    /// generates `f(contentVec)` instead of `f(content: contentVec)`.
1161    #[serde(default)]
1162    pub unnamed_arg_indices: Vec<usize>,
1163}
1164
1165fn default_true() -> bool {
1166    true
1167}
1168
1169/// Per-language package reference configuration.
1170#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1171pub struct PackageRef {
1172    /// Package/crate/gem/module name.
1173    #[serde(default)]
1174    pub name: Option<String>,
1175    /// Relative path from e2e/{lang}/ to the package.
1176    #[serde(default)]
1177    pub path: Option<String>,
1178    /// Go module path.
1179    #[serde(default)]
1180    pub module: Option<String>,
1181    /// Package version (e.g., for go.mod require directives).
1182    #[serde(default)]
1183    pub version: Option<String>,
1184}
1185
1186#[cfg(test)]
1187mod tests {
1188    use super::*;
1189
1190    fn empty_e2e_with_test_documents(dir: &str) -> E2eConfig {
1191        E2eConfig {
1192            test_documents_dir: dir.to_string(),
1193            ..Default::default()
1194        }
1195    }
1196
1197    #[test]
1198    fn test_documents_dir_default_is_test_documents() {
1199        let cfg: E2eConfig = toml::from_str("[call]\nfunction = \"f\"\n").expect("minimal TOML must deserialize");
1200        assert_eq!(cfg.test_documents_dir, "test_documents");
1201    }
1202
1203    #[test]
1204    fn test_documents_dir_explicit_override_wins() {
1205        let cfg: E2eConfig = toml::from_str("test_documents_dir = \"fixture_files\"\n[call]\nfunction = \"f\"\n")
1206            .expect("explicit override must deserialize");
1207        assert_eq!(cfg.test_documents_dir, "fixture_files");
1208    }
1209
1210    #[test]
1211    fn test_documents_relative_from_at_lang_root_returns_two_dots_up() {
1212        let cfg = empty_e2e_with_test_documents("test_documents");
1213        assert_eq!(cfg.test_documents_relative_from(0), "../../test_documents");
1214    }
1215
1216    #[test]
1217    fn test_documents_relative_from_at_spec_depth_returns_three_dots_up() {
1218        let cfg = empty_e2e_with_test_documents("test_documents");
1219        assert_eq!(cfg.test_documents_relative_from(1), "../../../test_documents");
1220    }
1221
1222    #[test]
1223    fn test_documents_relative_from_at_two_subdirs_deep_returns_four_dots_up() {
1224        let cfg = empty_e2e_with_test_documents("test_documents");
1225        assert_eq!(cfg.test_documents_relative_from(2), "../../../../test_documents");
1226    }
1227
1228    #[test]
1229    fn test_documents_relative_uses_configured_dir_name() {
1230        let cfg = empty_e2e_with_test_documents("fixture_files");
1231        assert_eq!(cfg.test_documents_relative_from(0), "../../fixture_files");
1232        assert_eq!(cfg.test_documents_relative_from(1), "../../../fixture_files");
1233    }
1234
1235    #[test]
1236    fn select_when_with_no_discriminators_never_matches() {
1237        let sel = SelectWhen::default();
1238        assert!(!sel.matches("any_id", "any_category", &[], &serde_json::Value::Null));
1239    }
1240
1241    #[test]
1242    fn select_when_input_has_matches_non_null_key() {
1243        let sel = SelectWhen {
1244            input_has: Some("batch_urls".to_string()),
1245            ..Default::default()
1246        };
1247        let input = serde_json::json!({ "batch_urls": [] });
1248        assert!(sel.matches("fid", "cat", &[], &input));
1249        let empty_input = serde_json::json!({ "url": "x" });
1250        assert!(!sel.matches("fid", "cat", &[], &empty_input));
1251    }
1252
1253    #[test]
1254    fn select_when_category_matches_exactly() {
1255        let sel = SelectWhen {
1256            category: Some("crawl".to_string()),
1257            ..Default::default()
1258        };
1259        assert!(sel.matches("any_id", "crawl", &[], &serde_json::Value::Null));
1260        assert!(!sel.matches("any_id", "scrape", &[], &serde_json::Value::Null));
1261    }
1262
1263    #[test]
1264    fn select_when_id_prefix_matches() {
1265        let sel = SelectWhen {
1266            id_prefix: Some("batch_crawl_".to_string()),
1267            ..Default::default()
1268        };
1269        assert!(sel.matches("batch_crawl_events", "any", &[], &serde_json::Value::Null));
1270        assert!(!sel.matches("batch_scrape_basic", "any", &[], &serde_json::Value::Null));
1271    }
1272
1273    #[test]
1274    fn select_when_id_glob_handles_star() {
1275        let sel = SelectWhen {
1276            id_glob: Some("crawl_stream*".to_string()),
1277            ..Default::default()
1278        };
1279        assert!(sel.matches("crawl_stream_basic", "any", &[], &serde_json::Value::Null));
1280        assert!(!sel.matches("batch_crawl_stream", "any", &[], &serde_json::Value::Null));
1281    }
1282
1283    #[test]
1284    fn select_when_tag_matches_any_tag_in_list() {
1285        let sel = SelectWhen {
1286            tag: Some("streaming".to_string()),
1287            ..Default::default()
1288        };
1289        let tags = vec!["smoke".to_string(), "streaming".to_string()];
1290        assert!(sel.matches("fid", "cat", &tags, &serde_json::Value::Null));
1291        assert!(!sel.matches("fid", "cat", &["smoke".to_string()], &serde_json::Value::Null));
1292    }
1293
1294    #[test]
1295    fn select_when_multiple_discriminators_anded() {
1296        let sel = SelectWhen {
1297            category: Some("stream".to_string()),
1298            id_prefix: Some("batch_crawl_stream".to_string()),
1299            ..Default::default()
1300        };
1301        assert!(sel.matches("batch_crawl_stream_events", "stream", &[], &serde_json::Value::Null));
1302        // Wrong category fails even though prefix matches
1303        assert!(!sel.matches("batch_crawl_stream_events", "crawl", &[], &serde_json::Value::Null));
1304        // Wrong prefix fails even though category matches
1305        assert!(!sel.matches("crawl_stream_basic", "stream", &[], &serde_json::Value::Null));
1306    }
1307
1308    #[test]
1309    fn select_when_deserializes_legacy_input_has_only() {
1310        let toml_src = r#"
1311            [call]
1312            function = "scrape"
1313
1314            [calls.batch_scrape]
1315            function = "batch_scrape"
1316            select_when = { input_has = "batch_urls" }
1317        "#;
1318        let cfg: E2eConfig = toml::from_str(toml_src).expect("legacy input_has must deserialize");
1319        let sel = cfg.calls["batch_scrape"].select_when.as_ref().unwrap();
1320        assert_eq!(sel.input_has.as_deref(), Some("batch_urls"));
1321        assert!(sel.category.is_none());
1322        assert!(sel.id_prefix.is_none());
1323    }
1324
1325    #[test]
1326    fn select_when_deserializes_compound_discriminators() {
1327        let toml_src = r#"
1328            [call]
1329            function = "scrape"
1330
1331            [calls.batch_crawl_stream]
1332            function = "batch_crawl_stream"
1333            select_when = { category = "stream", id_prefix = "batch_crawl_stream" }
1334        "#;
1335        let cfg: E2eConfig = toml::from_str(toml_src).expect("compound select_when must deserialize");
1336        let sel = cfg.calls["batch_crawl_stream"].select_when.as_ref().unwrap();
1337        assert_eq!(sel.category.as_deref(), Some("stream"));
1338        assert_eq!(sel.id_prefix.as_deref(), Some("batch_crawl_stream"));
1339    }
1340
1341    #[test]
1342    fn resolve_call_for_fixture_routes_by_category_then_falls_back() {
1343        let mut calls = HashMap::new();
1344        calls.insert(
1345            "crawl".to_string(),
1346            CallConfig {
1347                function: "crawl".to_string(),
1348                select_when: Some(SelectWhen {
1349                    category: Some("crawl".to_string()),
1350                    ..Default::default()
1351                }),
1352                ..Default::default()
1353            },
1354        );
1355        let cfg = E2eConfig {
1356            call: CallConfig {
1357                function: "scrape".to_string(),
1358                ..Default::default()
1359            },
1360            calls,
1361            ..Default::default()
1362        };
1363        let input = serde_json::json!({ "url": "https://example.com" });
1364        let resolved = cfg.resolve_call_for_fixture(None, "crawl_basic", "crawl", &[], &input);
1365        assert_eq!(resolved.function, "crawl");
1366        let resolved = cfg.resolve_call_for_fixture(None, "scrape_basic", "scrape", &[], &input);
1367        assert_eq!(resolved.function, "scrape");
1368    }
1369
1370    // --- effective_* resolver helpers ---
1371
1372    #[test]
1373    fn effective_result_fields_returns_global_when_call_is_empty() {
1374        let mut global = HashSet::new();
1375        global.insert("url".to_string());
1376        let cfg = E2eConfig {
1377            result_fields: global.clone(),
1378            ..Default::default()
1379        };
1380        let call = CallConfig::default();
1381        assert_eq!(cfg.effective_result_fields(&call), &global);
1382    }
1383
1384    #[test]
1385    fn effective_result_fields_call_override_wins_over_global() {
1386        let mut global = HashSet::new();
1387        global.insert("url".to_string());
1388        let mut per_call = HashSet::new();
1389        per_call.insert("pages".to_string());
1390        per_call.insert("final_url".to_string());
1391        let cfg = E2eConfig {
1392            result_fields: global,
1393            ..Default::default()
1394        };
1395        let call = CallConfig {
1396            result_fields: per_call.clone(),
1397            ..Default::default()
1398        };
1399        assert_eq!(cfg.effective_result_fields(&call), &per_call);
1400    }
1401
1402    #[test]
1403    fn effective_fields_returns_global_when_call_is_empty() {
1404        let mut global = HashMap::new();
1405        global.insert("metadata.title".to_string(), "metadata.document.title".to_string());
1406        let cfg = E2eConfig {
1407            fields: global.clone(),
1408            ..Default::default()
1409        };
1410        let call = CallConfig::default();
1411        assert_eq!(cfg.effective_fields(&call), &global);
1412    }
1413
1414    #[test]
1415    fn effective_fields_call_override_wins_over_global() {
1416        let mut global = HashMap::new();
1417        global.insert("a".to_string(), "b".to_string());
1418        let mut per_call = HashMap::new();
1419        per_call.insert("x".to_string(), "y".to_string());
1420        let cfg = E2eConfig {
1421            fields: global,
1422            ..Default::default()
1423        };
1424        let call = CallConfig {
1425            fields: per_call.clone(),
1426            ..Default::default()
1427        };
1428        assert_eq!(cfg.effective_fields(&call), &per_call);
1429    }
1430
1431    #[test]
1432    fn effective_fields_optional_returns_global_when_call_is_empty() {
1433        let mut global = HashSet::new();
1434        global.insert("segments".to_string());
1435        let cfg = E2eConfig {
1436            fields_optional: global.clone(),
1437            ..Default::default()
1438        };
1439        let call = CallConfig::default();
1440        assert_eq!(cfg.effective_fields_optional(&call), &global);
1441    }
1442
1443    #[test]
1444    fn effective_fields_optional_call_override_wins_over_global() {
1445        let mut global = HashSet::new();
1446        global.insert("segments".to_string());
1447        let mut per_call = HashSet::new();
1448        per_call.insert("pages".to_string());
1449        let cfg = E2eConfig {
1450            fields_optional: global,
1451            ..Default::default()
1452        };
1453        let call = CallConfig {
1454            fields_optional: per_call.clone(),
1455            ..Default::default()
1456        };
1457        assert_eq!(cfg.effective_fields_optional(&call), &per_call);
1458    }
1459
1460    #[test]
1461    fn effective_fields_array_returns_global_when_call_is_empty() {
1462        let mut global = HashSet::new();
1463        global.insert("choices".to_string());
1464        let cfg = E2eConfig {
1465            fields_array: global.clone(),
1466            ..Default::default()
1467        };
1468        let call = CallConfig::default();
1469        assert_eq!(cfg.effective_fields_array(&call), &global);
1470    }
1471
1472    #[test]
1473    fn effective_fields_array_call_override_wins_over_global() {
1474        let mut global = HashSet::new();
1475        global.insert("choices".to_string());
1476        let mut per_call = HashSet::new();
1477        per_call.insert("pages".to_string());
1478        let cfg = E2eConfig {
1479            fields_array: global,
1480            ..Default::default()
1481        };
1482        let call = CallConfig {
1483            fields_array: per_call.clone(),
1484            ..Default::default()
1485        };
1486        assert_eq!(cfg.effective_fields_array(&call), &per_call);
1487    }
1488
1489    #[test]
1490    fn effective_fields_method_calls_returns_global_when_call_is_empty() {
1491        let mut global = HashSet::new();
1492        global.insert("metadata.format".to_string());
1493        let cfg = E2eConfig {
1494            fields_method_calls: global.clone(),
1495            ..Default::default()
1496        };
1497        let call = CallConfig::default();
1498        assert_eq!(cfg.effective_fields_method_calls(&call), &global);
1499    }
1500
1501    #[test]
1502    fn effective_fields_method_calls_call_override_wins_over_global() {
1503        let mut global = HashSet::new();
1504        global.insert("metadata.format".to_string());
1505        let mut per_call = HashSet::new();
1506        per_call.insert("pages.status".to_string());
1507        let cfg = E2eConfig {
1508            fields_method_calls: global,
1509            ..Default::default()
1510        };
1511        let call = CallConfig {
1512            fields_method_calls: per_call.clone(),
1513            ..Default::default()
1514        };
1515        assert_eq!(cfg.effective_fields_method_calls(&call), &per_call);
1516    }
1517
1518    #[test]
1519    fn effective_fields_enum_returns_global_when_call_is_empty() {
1520        let mut global = HashSet::new();
1521        global.insert("choices.finish_reason".to_string());
1522        let cfg = E2eConfig {
1523            fields_enum: global.clone(),
1524            ..Default::default()
1525        };
1526        let call = CallConfig::default();
1527        assert_eq!(cfg.effective_fields_enum(&call), &global);
1528    }
1529
1530    #[test]
1531    fn effective_fields_enum_call_override_wins_over_global() {
1532        let mut global = HashSet::new();
1533        global.insert("choices.finish_reason".to_string());
1534        let mut per_call = HashSet::new();
1535        per_call.insert("assets.category".to_string());
1536        let cfg = E2eConfig {
1537            fields_enum: global,
1538            ..Default::default()
1539        };
1540        let call = CallConfig {
1541            fields_enum: per_call.clone(),
1542            ..Default::default()
1543        };
1544        assert_eq!(cfg.effective_fields_enum(&call), &per_call);
1545    }
1546
1547    #[test]
1548    fn effective_fields_c_types_returns_global_when_call_is_empty() {
1549        let mut global = HashMap::new();
1550        global.insert("conversion_result.metadata".to_string(), "HtmlMetadata".to_string());
1551        let cfg = E2eConfig {
1552            fields_c_types: global.clone(),
1553            ..Default::default()
1554        };
1555        let call = CallConfig::default();
1556        assert_eq!(cfg.effective_fields_c_types(&call), &global);
1557    }
1558
1559    #[test]
1560    fn effective_fields_c_types_call_override_wins_over_global() {
1561        let mut global = HashMap::new();
1562        global.insert("conversion_result.metadata".to_string(), "HtmlMetadata".to_string());
1563        let mut per_call = HashMap::new();
1564        per_call.insert("crawl_result.pages".to_string(), "PageResult".to_string());
1565        let cfg = E2eConfig {
1566            fields_c_types: global,
1567            ..Default::default()
1568        };
1569        let call = CallConfig {
1570            fields_c_types: per_call.clone(),
1571            ..Default::default()
1572        };
1573        assert_eq!(cfg.effective_fields_c_types(&call), &per_call);
1574    }
1575
1576    #[test]
1577    fn effective_resolver_helpers_deserialize_from_toml() {
1578        let toml = r#"
1579[call]
1580function = "scrape"
1581result_fields = ["url", "markdown"]
1582fields_enum = ["status"]
1583
1584[call.fields]
1585"meta.title" = "meta.document.title"
1586
1587[call.fields_c_types]
1588"scrape_result.meta" = "MetaResult"
1589"#;
1590        let cfg: E2eConfig = toml::from_str(toml).expect("must deserialize");
1591        let call = &cfg.call;
1592        assert!(cfg.effective_result_fields(call).contains("url"));
1593        assert!(cfg.effective_result_fields(call).contains("markdown"));
1594        assert!(cfg.effective_fields_enum(call).contains("status"));
1595        assert_eq!(
1596            cfg.effective_fields(call).get("meta.title").map(String::as_str),
1597            Some("meta.document.title")
1598        );
1599        assert_eq!(
1600            cfg.effective_fields_c_types(call)
1601                .get("scrape_result.meta")
1602                .map(String::as_str),
1603            Some("MetaResult")
1604        );
1605    }
1606}