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}
559
560fn default_result_var() -> String {
561    "result".to_string()
562}
563
564fn default_returns_result() -> bool {
565    false
566}
567
568/// Condition for auto-selecting a named call config when the fixture matches.
569///
570/// When a fixture does not specify `"call"`, the codegen normally uses the default
571/// `[e2e.call]`.  A `SelectWhen` condition on a named call allows automatic routing
572/// based on the fixture's id, category, tags, or input shape.  All set fields must
573/// match (logical AND); a condition with no fields set never matches.
574///
575/// ```toml
576/// [e2e.calls.batch_scrape]
577/// select_when = { input_has = "batch_urls" }
578///
579/// [e2e.calls.crawl]
580/// select_when = { category = "crawl" }
581///
582/// [e2e.calls.batch_crawl_stream]
583/// select_when = { category = "stream", id_prefix = "batch_crawl_stream" }
584/// ```
585#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
586pub struct SelectWhen {
587    /// Match when the fixture's resolved category equals this string.
588    #[serde(default)]
589    pub category: Option<String>,
590    /// Match when the fixture's id starts with this prefix.
591    #[serde(default)]
592    pub id_prefix: Option<String>,
593    /// Match when the fixture's id matches this simple glob.
594    ///
595    /// Only `*` (matches any run of characters) is supported. Use `id_prefix`
596    /// for plain prefix matches.
597    #[serde(default)]
598    pub id_glob: Option<String>,
599    /// Match when the fixture's tags include this tag.
600    #[serde(default)]
601    pub tag: Option<String>,
602    /// Match when the fixture's input object contains this key with a non-null value.
603    #[serde(default)]
604    pub input_has: Option<String>,
605}
606
607impl SelectWhen {
608    /// Returns true when every set discriminator matches the fixture.
609    ///
610    /// A `SelectWhen` with all fields `None` returns `false` — at least one
611    /// discriminator must be set for the condition to fire.
612    pub fn matches(
613        &self,
614        fixture_id: &str,
615        fixture_category: &str,
616        fixture_tags: &[String],
617        fixture_input: &serde_json::Value,
618    ) -> bool {
619        let any_set = self.category.is_some()
620            || self.id_prefix.is_some()
621            || self.id_glob.is_some()
622            || self.tag.is_some()
623            || self.input_has.is_some();
624        if !any_set {
625            return false;
626        }
627        if let Some(cat) = &self.category
628            && cat.as_str() != fixture_category
629        {
630            return false;
631        }
632        if let Some(prefix) = &self.id_prefix
633            && !fixture_id.starts_with(prefix.as_str())
634        {
635            return false;
636        }
637        if let Some(glob) = &self.id_glob
638            && !glob_matches(glob, fixture_id)
639        {
640            return false;
641        }
642        if let Some(tag) = &self.tag
643            && !fixture_tags.iter().any(|t| t == tag)
644        {
645            return false;
646        }
647        if let Some(key) = &self.input_has {
648            let val = fixture_input.get(key.as_str()).unwrap_or(&serde_json::Value::Null);
649            if val.is_null() {
650                return false;
651            }
652        }
653        true
654    }
655}
656
657/// Minimal glob matcher supporting `*` (greedy any-run) only.
658fn glob_matches(pattern: &str, text: &str) -> bool {
659    if !pattern.contains('*') {
660        return pattern == text;
661    }
662    let parts: Vec<&str> = pattern.split('*').collect();
663    let mut cursor = 0usize;
664    for (idx, part) in parts.iter().enumerate() {
665        if part.is_empty() {
666            continue;
667        }
668        if idx == 0 {
669            if !text[cursor..].starts_with(part) {
670                return false;
671            }
672            cursor += part.len();
673        } else if idx + 1 == parts.len() && !pattern.ends_with('*') {
674            return text[cursor..].ends_with(part);
675        } else {
676            match text[cursor..].find(part) {
677                Some(pos) => cursor += pos + part.len(),
678                None => return false,
679            }
680        }
681    }
682    true
683}
684
685/// Maps a fixture input field to a function argument.
686#[derive(Debug, Clone, Serialize, Deserialize)]
687pub struct ArgMapping {
688    /// Argument name in the function signature.
689    pub name: String,
690    /// JSON field path in the fixture's `input` object.
691    pub field: String,
692    /// Type hint for code generation.
693    #[serde(rename = "type", default = "default_arg_type")]
694    pub arg_type: String,
695    /// Whether this argument is optional.
696    #[serde(default)]
697    pub optional: bool,
698    /// When `true`, the Rust codegen passes this argument by value (owned) rather than
699    /// by reference. Use for `Vec<T>` parameters that do not accept `&Vec<T>`.
700    #[serde(default)]
701    pub owned: bool,
702    /// For `json_object` args targeting `&[T]` Rust parameters, set to the element type
703    /// (e.g. `"f32"`, `"String"`) so the codegen emits `Vec<element_type>` annotation.
704    #[serde(default)]
705    pub element_type: Option<String>,
706    /// Override the Go slice element type for `json_object` array args.
707    ///
708    /// When set, the Go e2e codegen uses this as the element type instead of the default
709    /// derived from `element_type`. Use Go-idiomatic type names including the import alias
710    /// prefix where needed, e.g. `"kreuzberg.BatchBytesItem"` or `"string"`.
711    #[serde(default)]
712    pub go_type: Option<String>,
713}
714
715fn default_arg_type() -> String {
716    "string".to_string()
717}
718
719/// Per-language override for function call configuration.
720#[derive(Debug, Clone, Serialize, Deserialize, Default)]
721pub struct CallOverride {
722    /// Override the module/import path.
723    #[serde(default)]
724    pub module: Option<String>,
725    /// Override the function name.
726    #[serde(default)]
727    pub function: Option<String>,
728    /// Maps canonical argument names to language-specific argument names.
729    ///
730    /// Used when a language binding uses a different parameter name than the
731    /// canonical `args` list in `CallConfig`. For example, if the canonical
732    /// arg name is `doc` but the Python binding uses `html`, specify:
733    ///
734    /// ```toml
735    /// [e2e.call.overrides.python]
736    /// arg_name_map = { doc = "html" }
737    /// ```
738    ///
739    /// The key is the canonical name (from `args[].name`) and the value is the
740    /// name to use when emitting the keyword argument in generated tests.
741    #[serde(default)]
742    pub arg_name_map: HashMap<String, String>,
743    /// Override the crate name (Rust only).
744    #[serde(default)]
745    pub crate_name: Option<String>,
746    /// Override the class name (Java/C# only).
747    #[serde(default)]
748    pub class: Option<String>,
749    /// Import alias (Go only, e.g., `htmd`).
750    #[serde(default)]
751    pub alias: Option<String>,
752    /// C header file name (C only).
753    #[serde(default)]
754    pub header: Option<String>,
755    /// FFI symbol prefix (C only).
756    #[serde(default)]
757    pub prefix: Option<String>,
758    /// For json_object args: the constructor to use instead of raw dict/object.
759    /// E.g., "ConversionOptions" — generates `ConversionOptions(**options)` in Python,
760    /// `new ConversionOptions(options)` in TypeScript.
761    #[serde(default)]
762    pub options_type: Option<String>,
763    /// How to pass json_object args: "kwargs" (default), "dict", "json", or "from_json".
764    ///
765    /// - `"kwargs"`: construct `OptionsType(key=val, ...)` (requires `options_type`).
766    /// - `"dict"`: pass as a plain dict/object literal `{"key": "val"}`.
767    /// - `"json"`: pass via `json.loads('...')` / `JSON.parse('...')`.
768    /// - `"from_json"`: call `OptionsType.from_json('...')` (Python only, PyO3 native types).
769    #[serde(default)]
770    pub options_via: Option<String>,
771    /// Module to import `options_type` from when `options_via = "from_json"`.
772    ///
773    /// When set, a separate `from {from_json_module} import {options_type}` line
774    /// is emitted instead of including the type in the main module import.
775    /// E.g., `"liter_llm._internal_bindings"` for PyO3 native types.
776    #[serde(default)]
777    pub from_json_module: Option<String>,
778    /// Override whether the call is async for this language.
779    ///
780    /// When set, takes precedence over the call-level `async` flag.
781    /// Useful when a language binding uses a different async model — for example,
782    /// a Python binding that returns a sync iterator from a function marked
783    /// `async = true` at the call level.
784    #[serde(default, rename = "async")]
785    pub r#async: Option<bool>,
786    /// Maps fixture option field names to their enum type names.
787    /// E.g., `{"headingStyle": "HeadingStyle", "codeBlockStyle": "CodeBlockStyle"}`.
788    /// The generator imports these types and maps string values to enum constants.
789    #[serde(default)]
790    pub enum_fields: HashMap<String, String>,
791    /// Maps result-type field names to their enum type names for assertion routing.
792    /// Per-call so e.g. `BatchObject.status` (enum) and `ResponseObject.status` (string)
793    /// can be disambiguated.
794    #[serde(default)]
795    pub assert_enum_fields: HashMap<String, String>,
796    /// Module to import enum types from (if different from the main module).
797    /// E.g., "html_to_markdown._html_to_markdown" for PyO3 native enums.
798    #[serde(default)]
799    pub enum_module: Option<String>,
800    /// Maps nested fixture object field names to their C# type names.
801    /// Used to generate `JsonSerializer.Deserialize<NestedType>(...)` for nested objects.
802    /// E.g., `{"preprocessing": "PreprocessingOptions"}`.
803    #[serde(default)]
804    pub nested_types: HashMap<String, String>,
805    /// When `false`, nested config builder results are passed directly to builder methods
806    /// without wrapping in `Optional.of(...)`. Set to `false` for bindings where nested
807    /// option types are non-optional (e.g., html-to-markdown Java).
808    /// Defaults to `true` for backward compatibility.
809    #[serde(default = "default_true")]
810    pub nested_types_optional: bool,
811    /// When `true`, the function returns a simple type (e.g., `String`) rather
812    /// than a struct.  Generators that would normally emit `result.content`
813    /// (or equivalent field access) will use the result variable directly.
814    #[serde(default)]
815    pub result_is_simple: bool,
816    /// When `true` (and combined with `result_is_simple`), the simple result is
817    /// a slice/array type (e.g., `[]string` in Go, `Vec<String>` in Rust).
818    /// The Go generator uses `strings.Join(value, " ")` for `contains` assertions
819    /// instead of `string(value)`.
820    #[serde(default)]
821    pub result_is_array: bool,
822    /// When `true`, the function returns `Vec<T>` rather than a single value.
823    /// Field-path assertions are emitted as `.iter().all(|r| <accessor>)` so
824    /// every element is checked. (Rust generator.)
825    #[serde(default)]
826    pub result_is_vec: bool,
827    /// When `true`, the function returns a raw byte array (e.g., `byte[]` in Java,
828    /// `[]byte` in Go). Used by generators to select the correct length accessor
829    /// (field `.length` vs method `.length()`).
830    #[serde(default)]
831    pub result_is_bytes: bool,
832    /// When `true`, the function returns `Option<T>`. The result is unwrapped
833    /// before any non-`is_none`/`is_some` assertion runs; `is_empty`/`not_empty`
834    /// assertions map to `is_none()`/`is_some()`. (Rust generator.)
835    #[serde(default)]
836    pub result_is_option: bool,
837    /// When `true`, the R generator emits the call result directly without wrapping
838    /// in `jsonlite::fromJSON()`. Use when the R binding already returns a native
839    /// R list (`Robj`) rather than a JSON string. Field-path assertions still use
840    /// `result$field` accessor syntax (i.e. `result_is_simple` behaviour is NOT
841    /// implied — only the JSON parse wrapper is suppressed). (R generator only.)
842    #[serde(default)]
843    pub result_is_r_list: bool,
844    /// When `true`, the Zig generator treats the result as a `[]u8` JSON string
845    /// representing a struct value (e.g., `ExtractionResult` serialized via the
846    /// FFI `_to_json` helper). The generator parses the JSON with
847    /// `std.json.parseFromSlice(std.json.Value, ...)` before emitting field
848    /// assertions, traversing the dynamic JSON object for each field path.
849    /// (Zig generator only.)
850    #[serde(default)]
851    pub result_is_json_struct: bool,
852    /// When `true`, the Rust generator wraps the `json_object` argument expression
853    /// in `Some(...).clone()` to match an owned `Option<T>` parameter slot rather
854    /// than passing `&options`. (Rust generator only.)
855    #[serde(default)]
856    pub wrap_options_in_some: bool,
857    /// Trailing positional arguments appended verbatim after the configured
858    /// `args`. Used when the target function takes additional positional slots
859    /// (e.g. visitor) the fixture cannot supply directly. (Rust generator only.)
860    #[serde(default)]
861    pub extra_args: Vec<String>,
862    /// Per-rust override of the call-level `returns_result`. When set, takes
863    /// precedence over `CallConfig.returns_result` for the Rust generator only.
864    /// Useful when one binding is fallible while others are not.
865    #[serde(default)]
866    pub returns_result: Option<bool>,
867    /// Maps handle config field names to their Python type constructor names.
868    ///
869    /// When the handle config object contains a nested dict-valued field, the
870    /// generator will wrap it in the specified type using keyword arguments.
871    /// E.g., `{"browser": "BrowserConfig"}` generates `BrowserConfig(mode="auto")`
872    /// instead of `{"mode": "auto"}`.
873    #[serde(default)]
874    pub handle_nested_types: HashMap<String, String>,
875    /// Handle config fields whose type constructor takes a single dict argument
876    /// instead of keyword arguments.
877    ///
878    /// E.g., `["auth"]` means `AuthConfig({"type": "basic", ...})` instead of
879    /// `AuthConfig(type="basic", ...)`.
880    #[serde(default)]
881    pub handle_dict_types: HashSet<String>,
882    /// Elixir struct module name for the handle config argument.
883    ///
884    /// When set, the generated Elixir handle config uses struct literal syntax
885    /// (`%Module.StructType{key: val}`) instead of a plain string-keyed map.
886    /// Rustler `NifStruct` requires a proper Elixir struct — plain maps are rejected.
887    ///
888    /// E.g., `"CrawlConfig"` generates `%Kreuzcrawl.CrawlConfig{download_assets: true}`.
889    #[serde(default)]
890    pub handle_struct_type: Option<String>,
891    /// Handle config fields whose list values are Elixir atoms (Rustler NifUnitEnum).
892    ///
893    /// When a config field is a `Vec<EnumType>` in Rust, the Elixir side must pass
894    /// a list of atoms (e.g., `[:image, :document]`) not strings (`["image"]`).
895    /// List the field names here so the generator emits atom literals instead of strings.
896    ///
897    /// E.g., `["asset_types"]` generates `asset_types: [:image]` instead of `["image"]`.
898    #[serde(default)]
899    pub handle_atom_list_fields: HashSet<String>,
900    /// WASM config class name for handle args (WASM generator only).
901    ///
902    /// When set, handle args are constructed using `ConfigType.default()` + setters
903    /// instead of passing a plain JS object (which fails `_assertClass` validation).
904    ///
905    /// E.g., `"WasmCrawlConfig"` generates:
906    /// ```js
907    /// const engineConfig = WasmCrawlConfig.default();
908    /// engineConfig.maxDepth = 1;
909    /// const engine = createEngine(engineConfig);
910    /// ```
911    #[serde(default)]
912    pub handle_config_type: Option<String>,
913    /// PHP client factory method name (PHP generator only).
914    ///
915    /// When set, the generated PHP test instantiates a client via
916    /// `ClassName::factory_method('test-key')` and calls methods on the instance
917    /// instead of using static facade calls.
918    ///
919    /// E.g., `"createClient"` generates:
920    /// ```php
921    /// $client = LiterLlm::createClient('test-key');
922    /// $result = $client->chat($request);
923    /// ```
924    #[serde(default)]
925    pub php_client_factory: Option<String>,
926    /// Client factory function name for instance-method languages (WASM, etc.).
927    ///
928    /// When set, the generated test imports this function, creates a client,
929    /// and calls API methods on the instance instead of as top-level functions.
930    ///
931    /// E.g., `"createClient"` generates:
932    /// ```typescript
933    /// import { createClient } from 'pkg';
934    /// const client = createClient('test-key');
935    /// const result = await client.chat(request);
936    /// ```
937    #[serde(default)]
938    pub client_factory: Option<String>,
939    /// Verbatim trailing arguments appended after the fixed `("test-key", ...)` pair
940    /// when calling the `client_factory` function.
941    ///
942    /// Use this when the factory function takes additional positional parameters
943    /// beyond the API key and optional base URL that the generator would otherwise
944    /// emit.  Each element is emitted verbatim, separated by `, `.
945    ///
946    /// Example — Gleam `create_client` takes five positional arguments:
947    /// `(api_key, base_url, timeout_secs, max_retries, model_hint)`.  Set:
948    /// ```toml
949    /// [e2e.call.overrides.gleam]
950    /// client_factory = "create_client"
951    /// client_factory_trailing_args = ["option.None", "option.None", "option.None"]
952    /// ```
953    /// to produce `create_client("test-key", option.Some(url), option.None, option.None, option.None)`.
954    #[serde(default)]
955    pub client_factory_trailing_args: Vec<String>,
956    /// Fields on the options object that require `BigInt()` wrapping (WASM only).
957    ///
958    /// `wasm_bindgen` maps Rust `u64`/`i64` to JavaScript `BigInt`. Numeric
959    /// values assigned to these setters must be wrapped with `BigInt(n)`.
960    ///
961    /// List camelCase field names, e.g.:
962    /// ```toml
963    /// [e2e.call.overrides.wasm]
964    /// bigint_fields = ["maxTokens", "seed"]
965    /// ```
966    #[serde(default)]
967    pub bigint_fields: Vec<String>,
968    /// Static CLI arguments appended to every invocation (brew/CLI generator only).
969    ///
970    /// E.g., `["--format", "json"]` appends `--format json` to every CLI call.
971    #[serde(default)]
972    pub cli_args: Vec<String>,
973    /// Maps fixture config field names to CLI flag names (brew/CLI generator only).
974    ///
975    /// E.g., `{"output_format": "--format"}` generates `--format <value>` from
976    /// the fixture's `output_format` input field.
977    #[serde(default)]
978    pub cli_flags: HashMap<String, String>,
979    /// C FFI opaque result type name (C only).
980    ///
981    /// The PascalCase name of the result struct, without the prefix.
982    /// E.g., `"ChatCompletionResponse"` for `LiterllmChatCompletionResponse*`.
983    /// If not set, defaults to the function name in PascalCase.
984    #[serde(default)]
985    pub result_type: Option<String>,
986    /// Override the argument order for this language binding.
987    ///
988    /// Lists argument names from `args` in the order they should be passed
989    /// to the target function. Useful when a language binding reorders parameters
990    /// relative to the canonical `args` list in `CallConfig`.
991    ///
992    /// E.g., if `args = [path, mime_type, config]` but the Node.js binding
993    /// takes `(path, config, mime_type?)`, specify:
994    /// ```toml
995    /// [e2e.call.overrides.node]
996    /// arg_order = ["path", "config", "mime_type"]
997    /// ```
998    #[serde(default)]
999    pub arg_order: Vec<String>,
1000    /// When `true`, `json_object` args with an `options_type` are passed as a
1001    /// pointer (`*OptionsType`) rather than a value.  Use for Go bindings where
1002    /// the options parameter is `*ConversionOptions` (nil-able pointer) rather
1003    /// than a plain struct.
1004    ///
1005    /// Absent options are passed as `nil`; present options are unmarshalled into
1006    /// a local variable and passed as `&optionsVar`.
1007    #[serde(default)]
1008    pub options_ptr: bool,
1009    /// Alternative function name to use when the fixture includes a `visitor`.
1010    ///
1011    /// Some bindings expose two entry points: `Convert(html, opts)` for the
1012    /// plain case and `ConvertWithVisitor(html, opts, visitor)` when a visitor
1013    /// is involved.  Set this to the visitor-accepting function name so the
1014    /// generator can pick the right symbol automatically.
1015    ///
1016    /// E.g., `"ConvertWithVisitor"` makes the Go generator emit:
1017    /// ```go
1018    /// result, err := htmd.ConvertWithVisitor(html, nil, visitor)
1019    /// ```
1020    /// instead of `htmd.Convert(html, nil, visitor)` (which would not compile).
1021    #[serde(default)]
1022    pub visitor_function: Option<String>,
1023    /// Rust trait names to import when `client_factory` is set (Rust generator only).
1024    ///
1025    /// When `client_factory` is set, the generated test creates a client object and
1026    /// calls methods on it. Those methods are defined on traits (e.g. `LlmClient`,
1027    /// `FileClient`) that must be in scope. List the trait names here and the Rust
1028    /// generator will emit `use {module}::{trait_name};` for each.
1029    ///
1030    /// E.g.:
1031    /// ```toml
1032    /// [e2e.call.overrides.rust]
1033    /// client_factory = "create_client"
1034    /// trait_imports = ["LlmClient", "FileClient", "BatchClient", "ResponseClient"]
1035    /// ```
1036    #[serde(default)]
1037    pub trait_imports: Vec<String>,
1038    /// Raw C return type, used verbatim instead of `{PREFIX}Type*` (C only).
1039    ///
1040    /// Valid values: `"char*"`, `"int32_t"`, `"uintptr_t"`.
1041    /// When set, the C generator skips options handle construction and uses the
1042    /// raw type directly. Free logic is adjusted accordingly.
1043    #[serde(default)]
1044    pub raw_c_result_type: Option<String>,
1045    /// Free function for raw `char*` C results (C only).
1046    ///
1047    /// Defaults to `{prefix}_free_string` when unset and `raw_c_result_type == "char*"`.
1048    #[serde(default)]
1049    pub c_free_fn: Option<String>,
1050    /// C FFI engine factory pattern (C only).
1051    ///
1052    /// When set, the C generator wraps each test call in a
1053    /// `{prefix}_create_engine(config)` / `{prefix}_crawl_engine_handle_free(engine)`
1054    /// prologue/epilogue using the named config type as the "arg 0" handle type.
1055    ///
1056    /// The value is the PascalCase config type name (without prefix), e.g.
1057    /// `"CrawlConfig"`. The generator will emit:
1058    /// ```c
1059    /// KCRAWLCrawlConfig* config_handle = kcrawl_crawl_config_from_json("{json}");
1060    /// KCRAWLCrawlEngineHandle* engine = kcrawl_create_engine(config_handle);
1061    /// kcrawl_crawl_config_free(config_handle);
1062    /// KCRAWLScrapeResult* result = kcrawl_scrape(engine, url);
1063    /// // ... assertions ...
1064    /// kcrawl_scrape_result_free(result);
1065    /// kcrawl_crawl_engine_handle_free(engine);
1066    /// ```
1067    #[serde(default)]
1068    pub c_engine_factory: Option<String>,
1069    /// Fields in a `json_object` arg that must be wrapped in `java.nio.file.Path.of()`
1070    /// (Java generator only).
1071    ///
1072    /// E.g., `["cache_dir"]` wraps the string value of `cache_dir` so the builder
1073    /// receives `java.nio.file.Path.of("/tmp/dir")` instead of a plain string.
1074    #[serde(default)]
1075    pub path_fields: Vec<String>,
1076    /// Trait name for the visitor pattern (Rust e2e tests only).
1077    ///
1078    /// When a fixture declares a `visitor` block, the Rust e2e generator emits
1079    /// `impl <trait_name> for _TestVisitor { ... }` and imports the trait from
1080    /// `{module}::visitor`. When unset, no visitor block is emitted and fixtures
1081    /// that declare a visitor will cause a codegen error.
1082    ///
1083    /// E.g., `"HtmlVisitor"` generates:
1084    /// ```rust,ignore
1085    /// use html_to_markdown_rs::visitor::{HtmlVisitor, NodeContext, VisitResult};
1086    /// // ...
1087    /// impl HtmlVisitor for _TestVisitor { ... }
1088    /// ```
1089    #[serde(default)]
1090    pub visitor_trait: Option<String>,
1091    /// Maps result field paths to their wasm-bindgen enum class names.
1092    ///
1093    /// wasm-bindgen exposes Rust enums as numeric discriminants in JavaScript
1094    /// (`WasmFinishReason.Stop === 0`), not string variants. When an `equals`
1095    /// assertion targets a field listed here, the WASM generator emits
1096    /// `expect(result.choices[0].finishReason).toBe(WasmFinishReason.Stop)`
1097    /// instead of attempting `(value ?? "").trim()`.
1098    ///
1099    /// The fixture's expected string value is converted to PascalCase to look
1100    /// up the variant (e.g. `"tool_calls"` -> `ToolCalls`).
1101    ///
1102    /// Example:
1103    /// ```toml
1104    /// [e2e.calls.chat.overrides.wasm]
1105    /// result_enum_fields = { "choices[0].finish_reason" = "WasmFinishReason", "status" = "WasmBatchStatus" }
1106    /// ```
1107    #[serde(default)]
1108    pub result_enum_fields: HashMap<String, String>,
1109    /// When `true`, indicates that the result is a pointer type (e.g., `*string` in Go,
1110    /// `*T` in Rust). The Go codegen will dereference it. When `false` (Go only), the
1111    /// result is a value type and should not be dereferenced.
1112    ///
1113    /// Used to distinguish between functions that return `(value, error)` where value
1114    /// is a scalar (string, uint, bool) as-is vs. those that return pointers.
1115    /// Defaults to `true` for backward compatibility with existing fixtures.
1116    #[serde(default = "default_true")]
1117    pub result_is_pointer: bool,
1118    /// Per-language override mirroring `CallConfig.result_element_is_string`.
1119    ///
1120    /// Set this on a per-language override when only one host's binding exposes
1121    /// the result as a native string array; otherwise prefer the call-level flag.
1122    #[serde(default)]
1123    pub result_element_is_string: bool,
1124    /// Maps array-typed result fields to the method name on each element that
1125    /// yields a string used in `contains` / `contains_all` assertions.
1126    ///
1127    /// Used when the array element is an opaque struct (e.g., a swift-bridge
1128    /// `type X;` declaration) and the element's "name" accessor is not the
1129    /// default `as_str` — for instance, `StructureItem` exposes `kind() -> String`
1130    /// instead of `as_str()`. The codegen consults this map when emitting
1131    /// `.map { $0.<accessor>().toString() }` so the closure compiles.
1132    ///
1133    /// Example:
1134    /// ```toml
1135    /// [e2e.call.overrides.swift]
1136    /// result_field_accessor = { "structure" = "kind" }
1137    /// ```
1138    #[serde(default)]
1139    pub result_field_accessor: HashMap<String, String>,
1140}
1141
1142fn default_true() -> bool {
1143    true
1144}
1145
1146/// Per-language package reference configuration.
1147#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1148pub struct PackageRef {
1149    /// Package/crate/gem/module name.
1150    #[serde(default)]
1151    pub name: Option<String>,
1152    /// Relative path from e2e/{lang}/ to the package.
1153    #[serde(default)]
1154    pub path: Option<String>,
1155    /// Go module path.
1156    #[serde(default)]
1157    pub module: Option<String>,
1158    /// Package version (e.g., for go.mod require directives).
1159    #[serde(default)]
1160    pub version: Option<String>,
1161}
1162
1163#[cfg(test)]
1164mod tests {
1165    use super::*;
1166
1167    fn empty_e2e_with_test_documents(dir: &str) -> E2eConfig {
1168        E2eConfig {
1169            test_documents_dir: dir.to_string(),
1170            ..Default::default()
1171        }
1172    }
1173
1174    #[test]
1175    fn test_documents_dir_default_is_test_documents() {
1176        let cfg: E2eConfig = toml::from_str("[call]\nfunction = \"f\"\n").expect("minimal TOML must deserialize");
1177        assert_eq!(cfg.test_documents_dir, "test_documents");
1178    }
1179
1180    #[test]
1181    fn test_documents_dir_explicit_override_wins() {
1182        let cfg: E2eConfig = toml::from_str("test_documents_dir = \"fixture_files\"\n[call]\nfunction = \"f\"\n")
1183            .expect("explicit override must deserialize");
1184        assert_eq!(cfg.test_documents_dir, "fixture_files");
1185    }
1186
1187    #[test]
1188    fn test_documents_relative_from_at_lang_root_returns_two_dots_up() {
1189        let cfg = empty_e2e_with_test_documents("test_documents");
1190        assert_eq!(cfg.test_documents_relative_from(0), "../../test_documents");
1191    }
1192
1193    #[test]
1194    fn test_documents_relative_from_at_spec_depth_returns_three_dots_up() {
1195        let cfg = empty_e2e_with_test_documents("test_documents");
1196        assert_eq!(cfg.test_documents_relative_from(1), "../../../test_documents");
1197    }
1198
1199    #[test]
1200    fn test_documents_relative_from_at_two_subdirs_deep_returns_four_dots_up() {
1201        let cfg = empty_e2e_with_test_documents("test_documents");
1202        assert_eq!(cfg.test_documents_relative_from(2), "../../../../test_documents");
1203    }
1204
1205    #[test]
1206    fn test_documents_relative_uses_configured_dir_name() {
1207        let cfg = empty_e2e_with_test_documents("fixture_files");
1208        assert_eq!(cfg.test_documents_relative_from(0), "../../fixture_files");
1209        assert_eq!(cfg.test_documents_relative_from(1), "../../../fixture_files");
1210    }
1211
1212    #[test]
1213    fn select_when_with_no_discriminators_never_matches() {
1214        let sel = SelectWhen::default();
1215        assert!(!sel.matches("any_id", "any_category", &[], &serde_json::Value::Null));
1216    }
1217
1218    #[test]
1219    fn select_when_input_has_matches_non_null_key() {
1220        let sel = SelectWhen {
1221            input_has: Some("batch_urls".to_string()),
1222            ..Default::default()
1223        };
1224        let input = serde_json::json!({ "batch_urls": [] });
1225        assert!(sel.matches("fid", "cat", &[], &input));
1226        let empty_input = serde_json::json!({ "url": "x" });
1227        assert!(!sel.matches("fid", "cat", &[], &empty_input));
1228    }
1229
1230    #[test]
1231    fn select_when_category_matches_exactly() {
1232        let sel = SelectWhen {
1233            category: Some("crawl".to_string()),
1234            ..Default::default()
1235        };
1236        assert!(sel.matches("any_id", "crawl", &[], &serde_json::Value::Null));
1237        assert!(!sel.matches("any_id", "scrape", &[], &serde_json::Value::Null));
1238    }
1239
1240    #[test]
1241    fn select_when_id_prefix_matches() {
1242        let sel = SelectWhen {
1243            id_prefix: Some("batch_crawl_".to_string()),
1244            ..Default::default()
1245        };
1246        assert!(sel.matches("batch_crawl_events", "any", &[], &serde_json::Value::Null));
1247        assert!(!sel.matches("batch_scrape_basic", "any", &[], &serde_json::Value::Null));
1248    }
1249
1250    #[test]
1251    fn select_when_id_glob_handles_star() {
1252        let sel = SelectWhen {
1253            id_glob: Some("crawl_stream*".to_string()),
1254            ..Default::default()
1255        };
1256        assert!(sel.matches("crawl_stream_basic", "any", &[], &serde_json::Value::Null));
1257        assert!(!sel.matches("batch_crawl_stream", "any", &[], &serde_json::Value::Null));
1258    }
1259
1260    #[test]
1261    fn select_when_tag_matches_any_tag_in_list() {
1262        let sel = SelectWhen {
1263            tag: Some("streaming".to_string()),
1264            ..Default::default()
1265        };
1266        let tags = vec!["smoke".to_string(), "streaming".to_string()];
1267        assert!(sel.matches("fid", "cat", &tags, &serde_json::Value::Null));
1268        assert!(!sel.matches("fid", "cat", &["smoke".to_string()], &serde_json::Value::Null));
1269    }
1270
1271    #[test]
1272    fn select_when_multiple_discriminators_anded() {
1273        let sel = SelectWhen {
1274            category: Some("stream".to_string()),
1275            id_prefix: Some("batch_crawl_stream".to_string()),
1276            ..Default::default()
1277        };
1278        assert!(sel.matches("batch_crawl_stream_events", "stream", &[], &serde_json::Value::Null));
1279        // Wrong category fails even though prefix matches
1280        assert!(!sel.matches("batch_crawl_stream_events", "crawl", &[], &serde_json::Value::Null));
1281        // Wrong prefix fails even though category matches
1282        assert!(!sel.matches("crawl_stream_basic", "stream", &[], &serde_json::Value::Null));
1283    }
1284
1285    #[test]
1286    fn select_when_deserializes_legacy_input_has_only() {
1287        let toml_src = r#"
1288            [call]
1289            function = "scrape"
1290
1291            [calls.batch_scrape]
1292            function = "batch_scrape"
1293            select_when = { input_has = "batch_urls" }
1294        "#;
1295        let cfg: E2eConfig = toml::from_str(toml_src).expect("legacy input_has must deserialize");
1296        let sel = cfg.calls["batch_scrape"].select_when.as_ref().unwrap();
1297        assert_eq!(sel.input_has.as_deref(), Some("batch_urls"));
1298        assert!(sel.category.is_none());
1299        assert!(sel.id_prefix.is_none());
1300    }
1301
1302    #[test]
1303    fn select_when_deserializes_compound_discriminators() {
1304        let toml_src = r#"
1305            [call]
1306            function = "scrape"
1307
1308            [calls.batch_crawl_stream]
1309            function = "batch_crawl_stream"
1310            select_when = { category = "stream", id_prefix = "batch_crawl_stream" }
1311        "#;
1312        let cfg: E2eConfig = toml::from_str(toml_src).expect("compound select_when must deserialize");
1313        let sel = cfg.calls["batch_crawl_stream"].select_when.as_ref().unwrap();
1314        assert_eq!(sel.category.as_deref(), Some("stream"));
1315        assert_eq!(sel.id_prefix.as_deref(), Some("batch_crawl_stream"));
1316    }
1317
1318    #[test]
1319    fn resolve_call_for_fixture_routes_by_category_then_falls_back() {
1320        let mut calls = HashMap::new();
1321        calls.insert(
1322            "crawl".to_string(),
1323            CallConfig {
1324                function: "crawl".to_string(),
1325                select_when: Some(SelectWhen {
1326                    category: Some("crawl".to_string()),
1327                    ..Default::default()
1328                }),
1329                ..Default::default()
1330            },
1331        );
1332        let cfg = E2eConfig {
1333            call: CallConfig {
1334                function: "scrape".to_string(),
1335                ..Default::default()
1336            },
1337            calls,
1338            ..Default::default()
1339        };
1340        let input = serde_json::json!({ "url": "https://example.com" });
1341        let resolved = cfg.resolve_call_for_fixture(None, "crawl_basic", "crawl", &[], &input);
1342        assert_eq!(resolved.function, "crawl");
1343        let resolved = cfg.resolve_call_for_fixture(None, "scrape_basic", "scrape", &[], &input);
1344        assert_eq!(resolved.function, "scrape");
1345    }
1346
1347    // --- effective_* resolver helpers ---
1348
1349    #[test]
1350    fn effective_result_fields_returns_global_when_call_is_empty() {
1351        let mut global = HashSet::new();
1352        global.insert("url".to_string());
1353        let cfg = E2eConfig {
1354            result_fields: global.clone(),
1355            ..Default::default()
1356        };
1357        let call = CallConfig::default();
1358        assert_eq!(cfg.effective_result_fields(&call), &global);
1359    }
1360
1361    #[test]
1362    fn effective_result_fields_call_override_wins_over_global() {
1363        let mut global = HashSet::new();
1364        global.insert("url".to_string());
1365        let mut per_call = HashSet::new();
1366        per_call.insert("pages".to_string());
1367        per_call.insert("final_url".to_string());
1368        let cfg = E2eConfig {
1369            result_fields: global,
1370            ..Default::default()
1371        };
1372        let call = CallConfig {
1373            result_fields: per_call.clone(),
1374            ..Default::default()
1375        };
1376        assert_eq!(cfg.effective_result_fields(&call), &per_call);
1377    }
1378
1379    #[test]
1380    fn effective_fields_returns_global_when_call_is_empty() {
1381        let mut global = HashMap::new();
1382        global.insert("metadata.title".to_string(), "metadata.document.title".to_string());
1383        let cfg = E2eConfig {
1384            fields: global.clone(),
1385            ..Default::default()
1386        };
1387        let call = CallConfig::default();
1388        assert_eq!(cfg.effective_fields(&call), &global);
1389    }
1390
1391    #[test]
1392    fn effective_fields_call_override_wins_over_global() {
1393        let mut global = HashMap::new();
1394        global.insert("a".to_string(), "b".to_string());
1395        let mut per_call = HashMap::new();
1396        per_call.insert("x".to_string(), "y".to_string());
1397        let cfg = E2eConfig {
1398            fields: global,
1399            ..Default::default()
1400        };
1401        let call = CallConfig {
1402            fields: per_call.clone(),
1403            ..Default::default()
1404        };
1405        assert_eq!(cfg.effective_fields(&call), &per_call);
1406    }
1407
1408    #[test]
1409    fn effective_fields_optional_returns_global_when_call_is_empty() {
1410        let mut global = HashSet::new();
1411        global.insert("segments".to_string());
1412        let cfg = E2eConfig {
1413            fields_optional: global.clone(),
1414            ..Default::default()
1415        };
1416        let call = CallConfig::default();
1417        assert_eq!(cfg.effective_fields_optional(&call), &global);
1418    }
1419
1420    #[test]
1421    fn effective_fields_optional_call_override_wins_over_global() {
1422        let mut global = HashSet::new();
1423        global.insert("segments".to_string());
1424        let mut per_call = HashSet::new();
1425        per_call.insert("pages".to_string());
1426        let cfg = E2eConfig {
1427            fields_optional: global,
1428            ..Default::default()
1429        };
1430        let call = CallConfig {
1431            fields_optional: per_call.clone(),
1432            ..Default::default()
1433        };
1434        assert_eq!(cfg.effective_fields_optional(&call), &per_call);
1435    }
1436
1437    #[test]
1438    fn effective_fields_array_returns_global_when_call_is_empty() {
1439        let mut global = HashSet::new();
1440        global.insert("choices".to_string());
1441        let cfg = E2eConfig {
1442            fields_array: global.clone(),
1443            ..Default::default()
1444        };
1445        let call = CallConfig::default();
1446        assert_eq!(cfg.effective_fields_array(&call), &global);
1447    }
1448
1449    #[test]
1450    fn effective_fields_array_call_override_wins_over_global() {
1451        let mut global = HashSet::new();
1452        global.insert("choices".to_string());
1453        let mut per_call = HashSet::new();
1454        per_call.insert("pages".to_string());
1455        let cfg = E2eConfig {
1456            fields_array: global,
1457            ..Default::default()
1458        };
1459        let call = CallConfig {
1460            fields_array: per_call.clone(),
1461            ..Default::default()
1462        };
1463        assert_eq!(cfg.effective_fields_array(&call), &per_call);
1464    }
1465
1466    #[test]
1467    fn effective_fields_method_calls_returns_global_when_call_is_empty() {
1468        let mut global = HashSet::new();
1469        global.insert("metadata.format".to_string());
1470        let cfg = E2eConfig {
1471            fields_method_calls: global.clone(),
1472            ..Default::default()
1473        };
1474        let call = CallConfig::default();
1475        assert_eq!(cfg.effective_fields_method_calls(&call), &global);
1476    }
1477
1478    #[test]
1479    fn effective_fields_method_calls_call_override_wins_over_global() {
1480        let mut global = HashSet::new();
1481        global.insert("metadata.format".to_string());
1482        let mut per_call = HashSet::new();
1483        per_call.insert("pages.status".to_string());
1484        let cfg = E2eConfig {
1485            fields_method_calls: global,
1486            ..Default::default()
1487        };
1488        let call = CallConfig {
1489            fields_method_calls: per_call.clone(),
1490            ..Default::default()
1491        };
1492        assert_eq!(cfg.effective_fields_method_calls(&call), &per_call);
1493    }
1494
1495    #[test]
1496    fn effective_fields_enum_returns_global_when_call_is_empty() {
1497        let mut global = HashSet::new();
1498        global.insert("choices.finish_reason".to_string());
1499        let cfg = E2eConfig {
1500            fields_enum: global.clone(),
1501            ..Default::default()
1502        };
1503        let call = CallConfig::default();
1504        assert_eq!(cfg.effective_fields_enum(&call), &global);
1505    }
1506
1507    #[test]
1508    fn effective_fields_enum_call_override_wins_over_global() {
1509        let mut global = HashSet::new();
1510        global.insert("choices.finish_reason".to_string());
1511        let mut per_call = HashSet::new();
1512        per_call.insert("assets.category".to_string());
1513        let cfg = E2eConfig {
1514            fields_enum: global,
1515            ..Default::default()
1516        };
1517        let call = CallConfig {
1518            fields_enum: per_call.clone(),
1519            ..Default::default()
1520        };
1521        assert_eq!(cfg.effective_fields_enum(&call), &per_call);
1522    }
1523
1524    #[test]
1525    fn effective_fields_c_types_returns_global_when_call_is_empty() {
1526        let mut global = HashMap::new();
1527        global.insert("conversion_result.metadata".to_string(), "HtmlMetadata".to_string());
1528        let cfg = E2eConfig {
1529            fields_c_types: global.clone(),
1530            ..Default::default()
1531        };
1532        let call = CallConfig::default();
1533        assert_eq!(cfg.effective_fields_c_types(&call), &global);
1534    }
1535
1536    #[test]
1537    fn effective_fields_c_types_call_override_wins_over_global() {
1538        let mut global = HashMap::new();
1539        global.insert("conversion_result.metadata".to_string(), "HtmlMetadata".to_string());
1540        let mut per_call = HashMap::new();
1541        per_call.insert("crawl_result.pages".to_string(), "PageResult".to_string());
1542        let cfg = E2eConfig {
1543            fields_c_types: global,
1544            ..Default::default()
1545        };
1546        let call = CallConfig {
1547            fields_c_types: per_call.clone(),
1548            ..Default::default()
1549        };
1550        assert_eq!(cfg.effective_fields_c_types(&call), &per_call);
1551    }
1552
1553    #[test]
1554    fn effective_resolver_helpers_deserialize_from_toml() {
1555        let toml = r#"
1556[call]
1557function = "scrape"
1558result_fields = ["url", "markdown"]
1559fields_enum = ["status"]
1560
1561[call.fields]
1562"meta.title" = "meta.document.title"
1563
1564[call.fields_c_types]
1565"scrape_result.meta" = "MetaResult"
1566"#;
1567        let cfg: E2eConfig = toml::from_str(toml).expect("must deserialize");
1568        let call = &cfg.call;
1569        assert!(cfg.effective_result_fields(call).contains("url"));
1570        assert!(cfg.effective_result_fields(call).contains("markdown"));
1571        assert!(cfg.effective_fields_enum(call).contains("status"));
1572        assert_eq!(
1573            cfg.effective_fields(call).get("meta.title").map(String::as_str),
1574            Some("meta.document.title")
1575        );
1576        assert_eq!(
1577            cfg.effective_fields_c_types(call)
1578                .get("scrape_result.meta")
1579                .map(String::as_str),
1580            Some("MetaResult")
1581        );
1582    }
1583}