1use crate::codegen::resolve_field;
8use crate::config::E2eConfig;
9use crate::escape::sanitize_filename;
10use crate::field_access::FieldResolver;
11use crate::fixture::{Assertion, Fixture, FixtureGroup, HttpFixture, ValidationErrorExpectation};
12use alef_core::backend::GeneratedFile;
13use alef_core::config::ResolvedCrateConfig;
14use alef_core::hash::{self, CommentStyle};
15use alef_core::template_versions::pub_dev;
16use anyhow::Result;
17use heck::ToLowerCamelCase;
18use std::cell::Cell;
19use std::collections::HashMap;
20use std::fmt::Write as FmtWrite;
21use std::path::PathBuf;
22
23use super::E2eCodegen;
24use super::client;
25
26pub struct DartE2eCodegen;
28
29impl E2eCodegen for DartE2eCodegen {
30 fn generate(
31 &self,
32 groups: &[FixtureGroup],
33 e2e_config: &E2eConfig,
34 config: &ResolvedCrateConfig,
35 type_defs: &[alef_core::ir::TypeDef],
36 enums: &[alef_core::ir::EnumDef],
37 ) -> Result<Vec<GeneratedFile>> {
38 let lang = self.language_name();
39 let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
40
41 let mut files = Vec::new();
42
43 let dart_pkg = e2e_config.resolve_package("dart");
45 let pkg_name = dart_pkg
46 .as_ref()
47 .and_then(|p| p.name.as_ref())
48 .cloned()
49 .unwrap_or_else(|| config.dart_pubspec_name());
50 let pkg_path = dart_pkg
51 .as_ref()
52 .and_then(|p| p.path.as_ref())
53 .cloned()
54 .unwrap_or_else(|| "../../packages/dart".to_string());
55 let pkg_version = dart_pkg
56 .as_ref()
57 .and_then(|p| p.version.as_ref())
58 .cloned()
59 .or_else(|| config.resolved_version())
60 .unwrap_or_else(|| "0.1.0".to_string());
61
62 files.push(GeneratedFile {
64 path: output_base.join("pubspec.yaml"),
65 content: render_pubspec(&pkg_name, &pkg_path, &pkg_version, e2e_config.dep_mode),
66 generated_header: false,
67 });
68
69 files.push(GeneratedFile {
72 path: output_base.join("dart_test.yaml"),
73 content: concat!(
74 "# Generated by alef — DO NOT EDIT.\n",
75 "# Run test files sequentially to avoid overwhelming the mock server with\n",
76 "# concurrent keep-alive connections.\n",
77 "concurrency: 1\n",
78 )
79 .to_string(),
80 generated_header: false,
81 });
82
83 let test_base = output_base.join("test");
84
85 let bridge_class = config.dart_bridge_class_name();
87
88 let frb_module_name = config.name.replace('-', "_");
92
93 let dart_stub_methods: std::collections::HashSet<String> = config
98 .dart
99 .as_ref()
100 .map(|d| d.stub_methods.iter().cloned().collect())
101 .unwrap_or_default();
102
103 let dart_first_class_map = build_dart_first_class_map(type_defs, enums, e2e_config);
106
107 for group in groups {
108 let active: Vec<&Fixture> = group
109 .fixtures
110 .iter()
111 .filter(|f| super::should_include_fixture(f, lang, e2e_config))
112 .filter(|f| {
113 let call_config = e2e_config.resolve_call_for_fixture(
114 f.call.as_deref(),
115 &f.id,
116 &f.resolved_category(),
117 &f.tags,
118 &f.input,
119 );
120 let resolved_function = call_config
121 .overrides
122 .get(lang)
123 .and_then(|o| o.function.as_ref())
124 .cloned()
125 .unwrap_or_else(|| call_config.function.clone());
126 !dart_stub_methods.contains(&resolved_function)
127 })
128 .collect();
129
130 if active.is_empty() {
131 continue;
132 }
133
134 let filename = format!("{}_test.dart", sanitize_filename(&group.category));
135 let content = render_test_file(
136 &group.category,
137 &active,
138 e2e_config,
139 lang,
140 &pkg_name,
141 &frb_module_name,
142 &bridge_class,
143 &dart_first_class_map,
144 );
145 files.push(GeneratedFile {
146 path: test_base.join(filename),
147 content,
148 generated_header: true,
149 });
150 }
151
152 Ok(files)
153 }
154
155 fn language_name(&self) -> &'static str {
156 "dart"
157 }
158}
159
160fn render_pubspec(
165 pkg_name: &str,
166 pkg_path: &str,
167 pkg_version: &str,
168 dep_mode: crate::config::DependencyMode,
169) -> String {
170 let test_ver = pub_dev::TEST_PACKAGE;
171 let http_ver = pub_dev::HTTP_PACKAGE;
172
173 let dep_block = match dep_mode {
174 crate::config::DependencyMode::Registry => {
175 let constraint = if pkg_version.starts_with('^')
177 || pkg_version.starts_with('~')
178 || pkg_version.starts_with('>')
179 || pkg_version.starts_with('<')
180 || pkg_version.starts_with('=')
181 {
182 pkg_version.to_string()
183 } else {
184 format!("^{pkg_version}")
185 };
186 format!(" {pkg_name}: {constraint}")
187 }
188 crate::config::DependencyMode::Local => {
189 format!(" {pkg_name}:\n path: {pkg_path}")
190 }
191 };
192
193 let sdk = alef_core::template_versions::toolchain::DART_SDK_CONSTRAINT;
194 format!(
195 r#"name: e2e_dart
196version: 0.1.0
197publish_to: none
198
199environment:
200 sdk: "{sdk}"
201
202dependencies:
203{dep_block}
204
205dev_dependencies:
206 test: {test_ver}
207 http: {http_ver}
208"#
209 )
210}
211
212#[allow(clippy::too_many_arguments)]
213fn render_test_file(
214 category: &str,
215 fixtures: &[&Fixture],
216 e2e_config: &E2eConfig,
217 lang: &str,
218 pkg_name: &str,
219 frb_module_name: &str,
220 bridge_class: &str,
221 dart_first_class_map: &crate::field_access::DartFirstClassMap,
222) -> String {
223 let mut out = String::new();
224 out.push_str(&hash::header(CommentStyle::DoubleSlash));
225 out.push_str("// ignore_for_file: unused_local_variable\n\n");
229
230 let has_http_fixtures = fixtures.iter().any(|f| f.is_http_test());
232
233 let has_batch_byte_items = fixtures.iter().any(|f| {
235 let call_config =
236 e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
237 call_config.args.iter().any(|a| {
238 a.element_type.as_deref() == Some("BatchBytesItem") && resolve_field(&f.input, &a.field).is_array()
239 })
240 });
241
242 let needs_chdir = fixtures.iter().any(|f| {
246 if f.is_http_test() {
247 return false;
248 }
249 let call_config =
250 e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
251 call_config
252 .args
253 .iter()
254 .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
255 });
256
257 let has_handle_args = fixtures.iter().any(|f| {
263 if f.is_http_test() {
264 return false;
265 }
266 let call_config =
267 e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
268 call_config
269 .args
270 .iter()
271 .any(|a| a.arg_type == "json_object" && super::resolve_field(&f.input, &a.field).is_array())
272 });
273
274 let lang_client_factory = e2e_config
280 .call
281 .overrides
282 .get(lang)
283 .and_then(|o| o.client_factory.as_deref())
284 .is_some();
285 let has_mock_url_refs = lang_client_factory
286 || fixtures.iter().any(|f| {
287 if f.is_http_test() {
288 return false;
289 }
290 let call_config = e2e_config.resolve_call_for_fixture(
291 f.call.as_deref(),
292 &f.id,
293 &f.resolved_category(),
294 &f.tags,
295 &f.input,
296 );
297 if call_config.args.iter().any(|a| a.arg_type == "mock_url") {
298 return true;
299 }
300 call_config
301 .overrides
302 .get(lang)
303 .and_then(|o| o.client_factory.as_deref())
304 .is_some()
305 });
306
307 let _ = writeln!(out, "import 'package:test/test.dart';");
308 if has_http_fixtures || needs_chdir || has_mock_url_refs {
313 let _ = writeln!(out, "import 'dart:io';");
314 }
315 if has_batch_byte_items {
316 let _ = writeln!(out, "import 'dart:typed_data';");
317 }
318 let _ = writeln!(out, "import 'package:{pkg_name}/{pkg_name}.dart';");
319 let _ = writeln!(
325 out,
326 "import 'package:{pkg_name}/src/{frb_module_name}_bridge_generated/frb_generated.dart' show RustLib;"
327 );
328 if has_http_fixtures {
329 let _ = writeln!(out, "import 'dart:async';");
330 }
331 if has_http_fixtures || has_handle_args {
333 let _ = writeln!(out, "import 'dart:convert';");
334 }
335 let _ = writeln!(out);
336
337 if has_http_fixtures {
347 let _ = writeln!(out, "HttpClient _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
348 let _ = writeln!(out);
349 let _ = writeln!(out, "var _lock = Future<void>.value();");
350 let _ = writeln!(out);
351 let _ = writeln!(out, "Future<T> _serialized<T>(Future<T> Function() fn) async {{");
352 let _ = writeln!(out, " final current = _lock;");
353 let _ = writeln!(out, " final next = Completer<void>();");
354 let _ = writeln!(out, " _lock = next.future;");
355 let _ = writeln!(out, " try {{");
356 let _ = writeln!(out, " await current;");
357 let _ = writeln!(out, " return await fn();");
358 let _ = writeln!(out, " }} finally {{");
359 let _ = writeln!(out, " next.complete();");
360 let _ = writeln!(out, " }}");
361 let _ = writeln!(out, "}}");
362 let _ = writeln!(out);
363 let _ = writeln!(out, "Future<T> _withRetry<T>(Future<T> Function() fn) async {{");
366 let _ = writeln!(out, " try {{");
367 let _ = writeln!(out, " return await fn();");
368 let _ = writeln!(out, " }} on SocketException {{");
369 let _ = writeln!(out, " _httpClient.close(force: true);");
370 let _ = writeln!(out, " _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
371 let _ = writeln!(out, " return fn();");
372 let _ = writeln!(out, " }} on HttpException {{");
373 let _ = writeln!(out, " _httpClient.close(force: true);");
374 let _ = writeln!(out, " _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
375 let _ = writeln!(out, " return fn();");
376 let _ = writeln!(out, " }}");
377 let _ = writeln!(out, "}}");
378 let _ = writeln!(out);
379 }
380
381 let _ = writeln!(out, "// E2e tests for category: {category}");
382 let _ = writeln!(out);
383
384 let _ = writeln!(out, "String _alefE2eText(Object? value) {{");
390 let _ = writeln!(out, " if (value == null) return '';");
391 let _ = writeln!(
392 out,
393 " // Check if it's an enum by examining its toString representation."
394 );
395 let _ = writeln!(out, " final str = value.toString();");
396 let _ = writeln!(out, " if (str.contains('.')) {{");
397 let _ = writeln!(
398 out,
399 " // Enum.toString() returns 'EnumName.variantName'. Extract the variant name."
400 );
401 let _ = writeln!(out, " final parts = str.split('.');");
402 let _ = writeln!(out, " if (parts.length == 2) {{");
403 let _ = writeln!(out, " final variantName = parts[1];");
404 let _ = writeln!(
405 out,
406 " // Convert camelCase variant names to snake_case for serde compatibility."
407 );
408 let _ = writeln!(out, " // E.g. 'toolCalls' -> 'tool_calls', 'stop' -> 'stop'.");
409 let _ = writeln!(out, " return _camelToSnake(variantName);");
410 let _ = writeln!(out, " }}");
411 let _ = writeln!(out, " }}");
412 let _ = writeln!(out, " return str;");
413 let _ = writeln!(out, "}}");
414 let _ = writeln!(out);
415
416 let _ = writeln!(out, "String _camelToSnake(String camel) {{");
418 let _ = writeln!(out, " final buffer = StringBuffer();");
419 let _ = writeln!(out, " for (int i = 0; i < camel.length; i++) {{");
420 let _ = writeln!(out, " final char = camel[i];");
421 let _ = writeln!(out, " if (char.contains(RegExp(r'[A-Z]'))) {{");
422 let _ = writeln!(out, " if (i > 0) buffer.write('_');");
423 let _ = writeln!(out, " buffer.write(char.toLowerCase());");
424 let _ = writeln!(out, " }} else {{");
425 let _ = writeln!(out, " buffer.write(char);");
426 let _ = writeln!(out, " }}");
427 let _ = writeln!(out, " }}");
428 let _ = writeln!(out, " return buffer.toString();");
429 let _ = writeln!(out, "}}");
430 let _ = writeln!(out);
431
432 let _ = writeln!(out, "void main() {{");
433
434 let _ = writeln!(out, " setUpAll(() async {{");
441 let _ = writeln!(out, " await RustLib.init();");
442 if needs_chdir {
443 let test_docs_path = e2e_config.test_documents_relative_from(0);
444 let _ = writeln!(
445 out,
446 " final _testDocs = Platform.environment['FIXTURES_DIR'] ?? '{test_docs_path}';"
447 );
448 let _ = writeln!(out, " final _dir = Directory(_testDocs);");
449 let _ = writeln!(out, " if (_dir.existsSync()) Directory.current = _dir;");
450 }
451 let _ = writeln!(out, " }});");
452 let _ = writeln!(out);
453
454 if has_http_fixtures {
456 let _ = writeln!(out, " tearDownAll(() => _httpClient.close());");
457 let _ = writeln!(out);
458 }
459
460 for fixture in fixtures {
461 render_test_case(&mut out, fixture, e2e_config, lang, bridge_class, dart_first_class_map);
462 }
463
464 let _ = writeln!(out, "}}");
465 out
466}
467
468fn render_test_case(
469 out: &mut String,
470 fixture: &Fixture,
471 e2e_config: &E2eConfig,
472 lang: &str,
473 bridge_class: &str,
474 dart_first_class_map: &crate::field_access::DartFirstClassMap,
475) {
476 if let Some(http) = &fixture.http {
478 render_http_test_case(out, fixture, http);
479 return;
480 }
481
482 let call_config = e2e_config.resolve_call_for_fixture(
484 fixture.call.as_deref(),
485 &fixture.id,
486 &fixture.resolved_category(),
487 &fixture.tags,
488 &fixture.input,
489 );
490 let call_field_resolver = FieldResolver::new_with_dart_first_class(
492 e2e_config.effective_fields(call_config),
493 e2e_config.effective_fields_optional(call_config),
494 e2e_config.effective_result_fields(call_config),
495 e2e_config.effective_fields_array(call_config),
496 e2e_config.effective_fields_method_calls(call_config),
497 &HashMap::new(),
498 dart_first_class_map.clone(),
499 )
500 .with_dart_root_type(dart_call_result_type(call_config).or_else(|| dart_first_class_map.root_type.clone()));
501 let field_resolver = &call_field_resolver;
502 let enum_fields_base = e2e_config.effective_fields_enum(call_config);
503
504 let effective_enum_fields: std::collections::HashSet<String> = {
509 let dart_overrides = call_config.overrides.get("dart");
510 if let Some(overrides) = dart_overrides {
511 let mut merged = enum_fields_base.clone();
512 merged.extend(overrides.enum_fields.keys().cloned());
513 merged
514 } else {
515 enum_fields_base.clone()
516 }
517 };
518 let enum_fields = &effective_enum_fields;
519 let call_overrides = call_config.overrides.get(lang);
520 let mut function_name = call_overrides
521 .and_then(|o| o.function.as_ref())
522 .cloned()
523 .unwrap_or_else(|| call_config.function.clone());
524 function_name = function_name
526 .split('_')
527 .enumerate()
528 .map(|(i, part)| {
529 if i == 0 {
530 part.to_string()
531 } else {
532 let mut chars = part.chars();
533 match chars.next() {
534 None => String::new(),
535 Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
536 }
537 }
538 })
539 .collect::<Vec<_>>()
540 .join("");
541 let result_var = &call_config.result_var;
542 let description = escape_dart(&fixture.description);
543 let fixture_id = &fixture.id;
544 let _is_async = call_overrides.and_then(|o| o.r#async).unwrap_or(call_config.r#async);
547
548 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
549 let is_streaming = crate::codegen::streaming_assertions::resolve_is_streaming(fixture, call_config.streaming);
550 let result_is_simple = call_overrides.is_some_and(|o| o.result_is_simple) || call_config.result_is_simple;
555
556 let options_type: Option<&str> = call_overrides.and_then(|o| o.options_type.as_deref());
563 let options_via: &str = call_overrides
564 .and_then(|o| o.options_via.as_deref())
565 .unwrap_or("kwargs");
566
567 let file_path_for_mime: Option<&str> = call_config
575 .args
576 .iter()
577 .find(|a| a.arg_type == "file_path")
578 .and_then(|a| resolve_field(&fixture.input, &a.field).as_str());
579
580 let has_file_path_arg = call_config.args.iter().any(|a| a.arg_type == "file_path");
587 let caller_supplied_override = call_overrides.and_then(|o| o.function.as_ref()).is_some();
590 if has_file_path_arg && !caller_supplied_override {
591 function_name = match function_name.as_str() {
592 "extractFile" => "extractBytes".to_string(),
593 "extractFileSync" => "extractBytesSync".to_string(),
594 other => other.to_string(),
595 };
596 }
597
598 let client_factory_for_args: Option<&str> =
605 call_overrides.and_then(|o| o.client_factory.as_deref()).or_else(|| {
606 e2e_config
607 .call
608 .overrides
609 .get(lang)
610 .and_then(|o| o.client_factory.as_deref())
611 });
612
613 let mut setup_lines: Vec<String> = Vec::new();
616 let mut args = Vec::new();
617
618 for arg_def in &call_config.args {
619 match arg_def.arg_type.as_str() {
620 "mock_url" => {
621 let name = arg_def.name.clone();
622 if fixture.has_host_root_route() {
623 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
624 setup_lines.push(format!(
625 r#"final {name} = Platform.environment["{env_key}"] ?? (Platform.environment["MOCK_SERVER_URL"]! + "/fixtures/{fixture_id}");"#
626 ));
627 } else {
628 setup_lines.push(format!(
629 r#"final {name} = "${{Platform.environment["MOCK_SERVER_URL"] ?? "http://localhost:8080"}}/fixtures/{fixture_id}";"#
630 ));
631 }
632 args.push(name);
633 continue;
634 }
635 "handle" => {
636 let name = arg_def.name.clone();
637 let field = arg_def.field.strip_prefix("input.").unwrap_or(&arg_def.field);
638 let config_value = fixture.input.get(field).cloned().unwrap_or(serde_json::Value::Null);
639 let create_fn = {
641 let mut chars = name.chars();
642 let pascal = match chars.next() {
643 None => String::new(),
644 Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
645 };
646 format!("create{pascal}")
647 };
648 if config_value.is_null()
649 || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
650 {
651 setup_lines.push(format!("final {name} = await {bridge_class}.{create_fn}();"));
652 } else {
653 let json_str = serde_json::to_string(&config_value).unwrap_or_default();
654 let config_var = format!("{name}Config");
655 setup_lines.push(format!(
660 "final {config_var} = await createCrawlConfigFromJson(json: r'{json_str}');"
661 ));
662 setup_lines.push(format!(
664 "final {name} = await {bridge_class}.{create_fn}(config: {config_var});"
665 ));
666 }
667 args.push(name);
668 continue;
669 }
670 "mock_url_list" => {
671 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
676 let field = arg_def.field.strip_prefix("input.").unwrap_or(&arg_def.field);
677 let val = fixture.input.get(field).unwrap_or(&serde_json::Value::Null);
678
679 let paths: Vec<String> = if let Some(arr) = val.as_array() {
680 arr.iter()
681 .filter_map(|v| v.as_str())
682 .map(|s| format!("'{}'", escape_dart(s)))
683 .collect()
684 } else {
685 Vec::new()
686 };
687
688 let var_name = &arg_def.name;
689 let paths_literal = paths.join(", ");
690
691 setup_lines.push(format!(
692 r#"final {var_name}Base = Platform.environment["{env_key}"] ?? (Platform.environment["MOCK_SERVER_URL"] ?? "http://localhost:8080") + "/fixtures/{fixture_id}";"#
693 ));
694 setup_lines.push(format!(
695 r#"final {var_name} = <String>[{paths_literal}].map((p) => p.startsWith('http') ? p : {var_name}Base + p).toList();"#
696 ));
697
698 args.push(var_name.to_string());
699 continue;
700 }
701 _ => {}
702 }
703
704 let arg_value = resolve_field(&fixture.input, &arg_def.field);
705 match arg_def.arg_type.as_str() {
706 "bytes" | "file_path" => {
707 if let serde_json::Value::String(file_path) = arg_value {
712 args.push(format!("File('{}').readAsBytesSync()", file_path));
713 }
714 }
715 "string" => {
716 let dart_param_name = snake_to_camel(&arg_def.name);
731 let mime_type_is_positional = arg_def.name == "mime_type" && client_factory_for_args.is_none();
741 match arg_value {
742 serde_json::Value::String(s) => {
743 let literal = format!("'{}'", escape_dart(s));
744 if (arg_def.optional || client_factory_for_args.is_some()) && !mime_type_is_positional {
750 args.push(format!("{dart_param_name}: {literal}"));
751 } else {
752 args.push(literal);
753 }
754 }
755 serde_json::Value::Null
756 if arg_def.optional
757 && arg_def.name == "mime_type" =>
760 {
761 let inferred = file_path_for_mime
762 .and_then(mime_from_extension)
763 .unwrap_or("application/octet-stream");
764 if mime_type_is_positional {
767 args.push(format!("'{inferred}'"));
768 } else {
769 args.push(format!("{dart_param_name}: '{inferred}'"));
770 }
771 }
772 _ => {}
774 }
775 }
776 "json_object" => {
777 if let Some(elem_type) = &arg_def.element_type {
779 if (elem_type == "BatchBytesItem" || elem_type == "BatchFileItem") && arg_value.is_array() {
780 let dart_items = emit_dart_batch_item_array(arg_value, elem_type);
781 args.push(dart_items);
782 } else if elem_type == "String" && arg_value.is_array() {
783 let items: Vec<String> = arg_value
790 .as_array()
791 .unwrap()
792 .iter()
793 .filter_map(|v| v.as_str())
794 .map(|s| format!("'{}'", escape_dart(s)))
795 .collect();
796 args.push(format!("<String>[{}]", items.join(", ")));
797 }
798 } else if options_via == "from_json" {
799 if let Some(opts_type) = options_type {
809 if !arg_value.is_null() {
810 let json_str = serde_json::to_string(&arg_value).unwrap_or_default();
811 let escaped_json = escape_dart(&json_str);
814 let var_name = format!("_{}", arg_def.name);
815 let dart_fn = type_name_to_create_from_json_dart(opts_type);
816 setup_lines.push(format!("final {var_name} = await {dart_fn}(json: '{escaped_json}');"));
817 args.push(format!("req: {var_name}"));
820 }
821 }
822 } else if arg_def.name == "config" {
823 if let serde_json::Value::Object(map) = &arg_value {
824 if !map.is_empty() {
825 let explicit_options =
834 options_type.is_some_and(|t| t != "ExtractionConfig" && t != "FileExtractionConfig");
835 let has_non_scalar = map.values().any(|v| {
836 matches!(
837 v,
838 serde_json::Value::String(_)
839 | serde_json::Value::Object(_)
840 | serde_json::Value::Array(_)
841 )
842 });
843 if explicit_options || has_non_scalar {
844 let opts_type = options_type.unwrap_or("ExtractionConfig");
845 let json_str = serde_json::to_string(&arg_value).unwrap_or_default();
846 let escaped_json = escape_dart(&json_str);
847 let var_name = format!("_{}", arg_def.name);
848 let dart_fn = type_name_to_create_from_json_dart(opts_type);
849 setup_lines
850 .push(format!("final {var_name} = await {dart_fn}(json: '{escaped_json}');"));
851 args.push(var_name);
852 } else {
853 args.push(emit_extraction_config_dart(map));
859 }
860 } else {
861 if let Some(opts_type) = options_type {
867 let var_name = format!("_{}", arg_def.name);
868 let dart_fn = type_name_to_create_from_json_dart(opts_type);
869 setup_lines.push(format!("final {var_name} = await {dart_fn}(json: '{{}}');"));
870 args.push(var_name);
871 }
872 }
873 }
874 } else if arg_value.is_array() {
876 let json_str = serde_json::to_string(&arg_value).unwrap_or_default();
879 let var_name = arg_def.name.clone();
880 setup_lines.push(format!(
881 "final {var_name} = (jsonDecode(r'{json_str}') as List<dynamic>).cast<String>();"
882 ));
883 args.push(var_name);
884 } else if let serde_json::Value::Object(map) = &arg_value {
885 if !map.is_empty() {
899 if let Some(opts_type) = options_type {
900 let json_str = serde_json::to_string(&arg_value).unwrap_or_default();
901 let escaped_json = escape_dart(&json_str);
902 let dart_param_name = snake_to_camel(&arg_def.name);
903 let var_name = format!("_{}", arg_def.name);
904 let dart_fn = type_name_to_create_from_json_dart(opts_type);
905 if fixture.visitor.is_some() {
906 setup_lines.push(format!(
907 "final {var_name} = await {dart_fn}WithVisitor(json: '{escaped_json}', visitor: _visitor);"
908 ));
909 } else {
910 setup_lines
911 .push(format!("final {var_name} = await {dart_fn}(json: '{escaped_json}');"));
912 }
913 if arg_def.optional {
914 args.push(format!("{dart_param_name}: {var_name}"));
915 } else {
916 args.push(var_name);
917 }
918 }
919 }
920 }
921 }
922 _ => {}
923 }
924 }
925
926 if let Some(visitor_spec) = &fixture.visitor {
941 let mut visitor_setup: Vec<String> = Vec::new();
942 let _ = super::dart_visitors::build_dart_visitor(&mut visitor_setup, visitor_spec);
943 for line in visitor_setup.into_iter().rev() {
946 setup_lines.insert(0, line);
947 }
948
949 let already_has_options = args.iter().any(|a| a.starts_with("options:") || a == "_options");
953 if !already_has_options {
954 if let Some(opts_type) = options_type {
955 let dart_fn = type_name_to_create_from_json_dart(opts_type);
956 setup_lines.push(format!(
957 "final _options = await {dart_fn}WithVisitor(json: '{{}}', visitor: _visitor);"
958 ));
959 args.push("options: _options".to_string());
960 }
961 }
962 }
963
964 let client_factory: Option<&str> = call_overrides.and_then(|o| o.client_factory.as_deref()).or_else(|| {
968 e2e_config
969 .call
970 .overrides
971 .get(lang)
972 .and_then(|o| o.client_factory.as_deref())
973 });
974
975 let client_factory_camel: Option<String> = client_factory.map(|f| {
977 f.split('_')
978 .enumerate()
979 .map(|(i, part)| {
980 if i == 0 {
981 part.to_string()
982 } else {
983 let mut chars = part.chars();
984 match chars.next() {
985 None => String::new(),
986 Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
987 }
988 }
989 })
990 .collect::<Vec<_>>()
991 .join("")
992 });
993
994 let _ = writeln!(out, " test('{description}', () async {{");
998
999 let args_str = args.join(", ");
1000 let receiver_class = call_overrides
1001 .and_then(|o| o.class.as_ref())
1002 .cloned()
1003 .unwrap_or_else(|| bridge_class.to_string());
1004
1005 let (receiver, extra_setup): (String, Option<String>) = if let Some(factory) = &client_factory_camel {
1009 let has_mock_url = call_config.args.iter().any(|a| a.arg_type == "mock_url");
1010 let mock_url_setup = if !has_mock_url {
1011 if fixture.has_host_root_route() {
1013 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1014 Some(format!(
1015 "final _mockUrl = Platform.environment[\"{env_key}\"] ?? (Platform.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{fixture_id}\");"
1016 ))
1017 } else {
1018 Some(format!(
1019 r#"final _mockUrl = "${{Platform.environment["MOCK_SERVER_URL"] ?? "http://localhost:8080"}}/fixtures/{fixture_id}";"#
1020 ))
1021 }
1022 } else {
1023 None
1024 };
1025 let url_expr = if has_mock_url {
1026 call_config
1029 .args
1030 .iter()
1031 .find(|a| a.arg_type == "mock_url")
1032 .map(|a| a.name.clone())
1033 .unwrap_or_else(|| "_mockUrl".to_string())
1034 } else {
1035 "_mockUrl".to_string()
1036 };
1037 let create_line = format!("final _client = await {receiver_class}.{factory}('test-key', baseUrl: {url_expr});");
1038 let full_setup = if let Some(url_line) = mock_url_setup {
1039 Some(format!("{url_line}\n {create_line}"))
1040 } else {
1041 Some(create_line)
1042 };
1043 ("_client".to_string(), full_setup)
1044 } else {
1045 (receiver_class.clone(), None)
1046 };
1047
1048 if expects_error && (!setup_lines.is_empty() || extra_setup.is_some()) {
1049 let _ = writeln!(out, " await expectLater(() async {{");
1053 for line in &setup_lines {
1054 let _ = writeln!(out, " {line}");
1055 }
1056 if let Some(extra) = &extra_setup {
1057 for line in extra.lines() {
1058 let _ = writeln!(out, " {line}");
1059 }
1060 }
1061 if is_streaming {
1062 let _ = writeln!(out, " return {receiver}.{function_name}({args_str}).toList();");
1063 } else {
1064 let _ = writeln!(out, " return {receiver}.{function_name}({args_str});");
1065 }
1066 let _ = writeln!(out, " }}(), throwsA(anything));");
1067 } else if expects_error {
1068 if let Some(extra) = &extra_setup {
1070 for line in extra.lines() {
1071 let _ = writeln!(out, " {line}");
1072 }
1073 }
1074 if is_streaming {
1075 let _ = writeln!(
1076 out,
1077 " await expectLater({receiver}.{function_name}({args_str}).toList(), throwsA(anything));"
1078 );
1079 } else {
1080 let _ = writeln!(
1081 out,
1082 " await expectLater({receiver}.{function_name}({args_str}), throwsA(anything));"
1083 );
1084 }
1085 } else {
1086 for line in &setup_lines {
1087 let _ = writeln!(out, " {line}");
1088 }
1089 if let Some(extra) = &extra_setup {
1090 for line in extra.lines() {
1091 let _ = writeln!(out, " {line}");
1092 }
1093 }
1094 if is_streaming {
1095 let _ = writeln!(
1096 out,
1097 " final {result_var} = await {receiver}.{function_name}({args_str}).toList();"
1098 );
1099 } else {
1100 let _ = writeln!(
1101 out,
1102 " final {result_var} = await {receiver}.{function_name}({args_str});"
1103 );
1104 }
1105 for assertion in &fixture.assertions {
1106 if is_streaming {
1107 render_streaming_assertion_dart(out, assertion, result_var);
1108 } else {
1109 render_assertion_dart(
1110 out,
1111 assertion,
1112 result_var,
1113 result_is_simple,
1114 field_resolver,
1115 enum_fields,
1116 );
1117 }
1118 }
1119 }
1120
1121 let _ = writeln!(out, " }});");
1122 let _ = writeln!(out);
1123}
1124
1125fn dart_length_expr(field_accessor: &str, field: Option<&str>, field_resolver: &FieldResolver) -> String {
1133 let is_optional = field
1134 .map(|f| {
1135 let resolved = field_resolver.resolve(f);
1136 field_resolver.is_optional(f) || field_resolver.is_optional(resolved)
1137 })
1138 .unwrap_or(false);
1139 if is_optional {
1140 format!("{field_accessor}?.length ?? 0")
1141 } else {
1142 format!("{field_accessor}.length")
1143 }
1144}
1145
1146fn dart_format_value(val: &serde_json::Value) -> String {
1147 match val {
1148 serde_json::Value::String(s) => format!("'{}'", escape_dart(s)),
1149 serde_json::Value::Bool(b) => b.to_string(),
1150 serde_json::Value::Number(n) => n.to_string(),
1151 serde_json::Value::Null => "null".to_string(),
1152 other => format!("'{}'", escape_dart(&other.to_string())),
1153 }
1154}
1155
1156fn render_assertion_dart(
1167 out: &mut String,
1168 assertion: &Assertion,
1169 result_var: &str,
1170 result_is_simple: bool,
1171 field_resolver: &FieldResolver,
1172 enum_fields: &std::collections::HashSet<String>,
1173) {
1174 if !result_is_simple {
1178 if let Some(f) = assertion.field.as_deref() {
1179 let head = f.split("[].").next().unwrap_or(f);
1182 if !head.is_empty() && !field_resolver.is_valid_for_result(head) {
1183 let _ = writeln!(out, " // skipped: field '{f}' not available on dart result type");
1184 return;
1185 }
1186 }
1187 }
1188
1189 if let Some(f) = assertion.field.as_deref() {
1195 if !f.is_empty() && field_resolver.tagged_union_split(f).is_some() {
1196 let _ = writeln!(
1197 out,
1198 " // skipped: field '{f}' crosses a tagged-union variant boundary (not expressible in Dart)"
1199 );
1200 return;
1201 }
1202 }
1203
1204 if let Some(f) = assertion.field.as_deref() {
1206 if let Some(dot) = f.find("[].") {
1207 let resolved_full = field_resolver.resolve(f);
1212 let (array_part, elem_part) = match resolved_full.find("[].") {
1213 Some(rdot) => (&resolved_full[..rdot], &resolved_full[rdot + 3..]),
1214 None => (&f[..dot], &f[dot + 3..]),
1217 };
1218 let array_accessor = if array_part.is_empty() {
1219 result_var.to_string()
1220 } else {
1221 field_resolver.accessor(array_part, "dart", result_var)
1222 };
1223 let elem_accessor = field_to_dart_accessor(elem_part);
1224 match assertion.assertion_type.as_str() {
1225 "contains" => {
1226 if let Some(expected) = &assertion.value {
1227 let dart_val = dart_format_value(expected);
1228 let _ = writeln!(
1229 out,
1230 " expect({array_accessor}.any((e) => e.{elem_accessor}.toString().contains({dart_val})), isTrue);"
1231 );
1232 }
1233 }
1234 "contains_all" => {
1235 if let Some(values) = &assertion.values {
1236 for val in values {
1237 let dart_val = dart_format_value(val);
1238 let _ = writeln!(
1239 out,
1240 " expect({array_accessor}.any((e) => e.{elem_accessor}.toString().contains({dart_val})), isTrue);"
1241 );
1242 }
1243 }
1244 }
1245 "not_contains" => {
1246 if let Some(expected) = &assertion.value {
1247 let dart_val = dart_format_value(expected);
1248 let _ = writeln!(
1249 out,
1250 " expect({array_accessor}.any((e) => e.{elem_accessor}.toString().contains({dart_val})), isFalse);"
1251 );
1252 } else if let Some(values) = &assertion.values {
1253 for val in values {
1254 let dart_val = dart_format_value(val);
1255 let _ = writeln!(
1256 out,
1257 " expect({array_accessor}.any((e) => e.{elem_accessor}.toString().contains({dart_val})), isFalse);"
1258 );
1259 }
1260 }
1261 }
1262 "not_empty" => {
1263 let _ = writeln!(
1264 out,
1265 " expect({array_accessor}.any((e) => e.{elem_accessor}.toString().isNotEmpty), isTrue);"
1266 );
1267 }
1268 other => {
1269 let _ = writeln!(
1270 out,
1271 " // skipped: unsupported traversal assertion '{other}' on '{f}'"
1272 );
1273 }
1274 }
1275 return;
1276 }
1277 }
1278
1279 let field_accessor = if result_is_simple {
1280 result_var.to_string()
1284 } else {
1285 match assertion.field.as_deref() {
1286 Some(f) if !f.is_empty() => field_resolver.accessor(f, "dart", result_var),
1291 _ => result_var.to_string(),
1292 }
1293 };
1294
1295 let format_value = |val: &serde_json::Value| -> String { dart_format_value(val) };
1296
1297 match assertion.assertion_type.as_str() {
1298 "equals" | "field_equals" => {
1299 if let Some(expected) = &assertion.value {
1300 let dart_val = format_value(expected);
1301 let is_enum_field = assertion
1304 .field
1305 .as_deref()
1306 .map(|f| {
1307 let resolved = field_resolver.resolve(f);
1308 enum_fields.contains(f) || enum_fields.contains(resolved)
1309 })
1310 .unwrap_or(false);
1311
1312 if expected.is_string() {
1316 if is_enum_field {
1317 let _ = writeln!(
1320 out,
1321 " expect(_alefE2eText({field_accessor}).trim(), equals({dart_val}.toString().trim()));"
1322 );
1323 } else {
1324 let safe_accessor = if result_is_simple && assertion.field.is_none() {
1327 format!("({field_accessor} ?? '').toString().trim()")
1328 } else {
1329 format!("{field_accessor}.toString().trim()")
1330 };
1331 let _ = writeln!(
1332 out,
1333 " expect({safe_accessor}, equals({dart_val}.toString().trim()));"
1334 );
1335 }
1336 } else {
1337 let _ = writeln!(out, " expect({field_accessor}, equals({dart_val}));");
1338 }
1339 } else {
1340 let _ = writeln!(
1341 out,
1342 " // skipped: '{}' assertion missing value",
1343 assertion.assertion_type
1344 );
1345 }
1346 }
1347 "not_equals" => {
1348 if let Some(expected) = &assertion.value {
1349 let dart_val = format_value(expected);
1350 let is_enum_field = assertion
1352 .field
1353 .as_deref()
1354 .map(|f| {
1355 let resolved = field_resolver.resolve(f);
1356 enum_fields.contains(f) || enum_fields.contains(resolved)
1357 })
1358 .unwrap_or(false);
1359
1360 if expected.is_string() {
1361 if is_enum_field {
1362 let _ = writeln!(
1363 out,
1364 " expect(_alefE2eText({field_accessor}).trim(), isNot(equals({dart_val}.toString().trim())));"
1365 );
1366 } else {
1367 let safe_accessor = if result_is_simple && assertion.field.is_none() {
1370 format!("({field_accessor} ?? '').toString().trim()")
1371 } else {
1372 format!("{field_accessor}.toString().trim()")
1373 };
1374 let _ = writeln!(
1375 out,
1376 " expect({safe_accessor}, isNot(equals({dart_val}.toString().trim())));"
1377 );
1378 }
1379 } else {
1380 let _ = writeln!(out, " expect({field_accessor}, isNot(equals({dart_val})));");
1381 }
1382 }
1383 }
1384 "contains" => {
1385 if let Some(expected) = &assertion.value {
1386 let dart_val = format_value(expected);
1387 let aggregator = dart_stringy_aggregator_contains_assert(
1392 assertion.field.as_deref(),
1393 result_var,
1394 field_resolver,
1395 &dart_val,
1396 );
1397 if let Some(line) = aggregator {
1398 let _ = writeln!(out, "{line}");
1399 } else {
1400 let _ = writeln!(out, " expect({field_accessor}, contains({dart_val}));");
1401 }
1402 } else {
1403 let _ = writeln!(out, " // skipped: 'contains' assertion missing value");
1404 }
1405 }
1406 "contains_all" => {
1407 if let Some(values) = &assertion.values {
1408 for val in values {
1409 let dart_val = format_value(val);
1410 let _ = writeln!(out, " expect({field_accessor}, contains({dart_val}));");
1411 }
1412 }
1413 }
1414 "contains_any" => {
1415 if let Some(values) = &assertion.values {
1416 let checks: Vec<String> = values
1417 .iter()
1418 .map(|v| {
1419 let dart_val = format_value(v);
1420 format!("{field_accessor}.contains({dart_val})")
1421 })
1422 .collect();
1423 let joined = checks.join(" || ");
1424 let _ = writeln!(out, " expect({joined}, isTrue);");
1425 }
1426 }
1427 "not_contains" => {
1428 if let Some(expected) = &assertion.value {
1429 let dart_val = format_value(expected);
1430 let _ = writeln!(out, " expect({field_accessor}, isNot(contains({dart_val})));");
1431 } else if let Some(values) = &assertion.values {
1432 for val in values {
1433 let dart_val = format_value(val);
1434 let _ = writeln!(out, " expect({field_accessor}, isNot(contains({dart_val})));");
1435 }
1436 }
1437 }
1438 "not_empty" => {
1439 let is_collection = assertion.field.as_deref().is_some_and(|f| {
1444 let resolved = field_resolver.resolve(f);
1445 field_resolver.is_array(f) || field_resolver.is_array(resolved)
1446 });
1447 if is_collection {
1448 let _ = writeln!(out, " expect({field_accessor}, isNotEmpty);");
1449 } else {
1450 let _ = writeln!(out, " expect({field_accessor}, isNotNull);");
1451 }
1452 }
1453 "is_empty" => {
1454 let _ = writeln!(out, " expect({field_accessor}, anyOf(isNull, isEmpty));");
1458 }
1459 "starts_with" => {
1460 if let Some(expected) = &assertion.value {
1461 let dart_val = format_value(expected);
1462 let _ = writeln!(out, " expect({field_accessor}, startsWith({dart_val}));");
1463 }
1464 }
1465 "ends_with" => {
1466 if let Some(expected) = &assertion.value {
1467 let dart_val = format_value(expected);
1468 let _ = writeln!(out, " expect({field_accessor}, endsWith({dart_val}));");
1469 }
1470 }
1471 "min_length" => {
1472 if let Some(val) = &assertion.value {
1473 if let Some(n) = val.as_u64() {
1474 let length_expr = dart_length_expr(&field_accessor, assertion.field.as_deref(), field_resolver);
1475 let _ = writeln!(out, " expect({length_expr}, greaterThanOrEqualTo({n}));");
1476 }
1477 }
1478 }
1479 "max_length" => {
1480 if let Some(val) = &assertion.value {
1481 if let Some(n) = val.as_u64() {
1482 let length_expr = dart_length_expr(&field_accessor, assertion.field.as_deref(), field_resolver);
1483 let _ = writeln!(out, " expect({length_expr}, lessThanOrEqualTo({n}));");
1484 }
1485 }
1486 }
1487 "count_equals" => {
1488 if let Some(val) = &assertion.value {
1489 if let Some(n) = val.as_u64() {
1490 let length_expr = dart_length_expr(&field_accessor, assertion.field.as_deref(), field_resolver);
1491 let _ = writeln!(out, " expect({length_expr}, equals({n}));");
1492 }
1493 }
1494 }
1495 "count_min" => {
1496 if let Some(val) = &assertion.value {
1497 if let Some(n) = val.as_u64() {
1498 let length_expr = dart_length_expr(&field_accessor, assertion.field.as_deref(), field_resolver);
1499 let _ = writeln!(out, " expect({length_expr}, greaterThanOrEqualTo({n}));");
1500 }
1501 }
1502 }
1503 "matches_regex" => {
1504 if let Some(expected) = &assertion.value {
1505 let dart_val = format_value(expected);
1506 let _ = writeln!(out, " expect({field_accessor}, matches(RegExp({dart_val})));");
1507 }
1508 }
1509 "is_true" => {
1510 let _ = writeln!(out, " expect({field_accessor}, isTrue);");
1511 }
1512 "is_false" => {
1513 let _ = writeln!(out, " expect({field_accessor}, isFalse);");
1514 }
1515 "greater_than" => {
1516 if let Some(val) = &assertion.value {
1517 let dart_val = format_value(val);
1518 let _ = writeln!(out, " expect({field_accessor}, greaterThan({dart_val}));");
1519 }
1520 }
1521 "less_than" => {
1522 if let Some(val) = &assertion.value {
1523 let dart_val = format_value(val);
1524 let _ = writeln!(out, " expect({field_accessor}, lessThan({dart_val}));");
1525 }
1526 }
1527 "greater_than_or_equal" => {
1528 if let Some(val) = &assertion.value {
1529 let dart_val = format_value(val);
1530 let _ = writeln!(out, " expect({field_accessor}, greaterThanOrEqualTo({dart_val}));");
1531 }
1532 }
1533 "less_than_or_equal" => {
1534 if let Some(val) = &assertion.value {
1535 let dart_val = format_value(val);
1536 let _ = writeln!(out, " expect({field_accessor}, lessThanOrEqualTo({dart_val}));");
1537 }
1538 }
1539 "not_null" => {
1540 let _ = writeln!(out, " expect({field_accessor}, isNotNull);");
1541 }
1542 "not_error" => {
1543 }
1550 "error" => {
1551 }
1553 "method_result" => {
1554 if let Some(method) = &assertion.method {
1555 let dart_method = method.to_lower_camel_case();
1556 let check = assertion.check.as_deref().unwrap_or("not_null");
1557 let method_call = format!("{field_accessor}.{dart_method}()");
1558 match check {
1559 "equals" => {
1560 if let Some(expected) = &assertion.value {
1561 let dart_val = format_value(expected);
1562 let _ = writeln!(out, " expect({method_call}, equals({dart_val}));");
1563 }
1564 }
1565 "is_true" => {
1566 let _ = writeln!(out, " expect({method_call}, isTrue);");
1567 }
1568 "is_false" => {
1569 let _ = writeln!(out, " expect({method_call}, isFalse);");
1570 }
1571 "greater_than_or_equal" => {
1572 if let Some(val) = &assertion.value {
1573 let dart_val = format_value(val);
1574 let _ = writeln!(out, " expect({method_call}, greaterThanOrEqualTo({dart_val}));");
1575 }
1576 }
1577 "count_min" => {
1578 if let Some(val) = &assertion.value {
1579 if let Some(n) = val.as_u64() {
1580 let _ = writeln!(out, " expect({method_call}.length, greaterThanOrEqualTo({n}));");
1581 }
1582 }
1583 }
1584 _ => {
1585 let _ = writeln!(out, " expect({method_call}, isNotNull);");
1586 }
1587 }
1588 }
1589 }
1590 other => {
1591 let _ = writeln!(out, " // skipped: unknown assertion type '{other}'");
1592 }
1593 }
1594}
1595
1596fn render_streaming_assertion_dart(out: &mut String, assertion: &Assertion, result_var: &str) {
1607 match assertion.assertion_type.as_str() {
1608 "not_error" => {
1609 let _ = writeln!(out, " expect({result_var}, isNotNull);");
1613 }
1614 "count_min" if assertion.field.as_deref() == Some("chunks") => {
1615 if let Some(serde_json::Value::Number(n)) = &assertion.value {
1616 let _ = writeln!(out, " expect({result_var}.length, greaterThanOrEqualTo({n}));");
1617 }
1618 }
1619 "equals" if assertion.field.as_deref() == Some("stream_content") => {
1620 if let Some(serde_json::Value::String(expected)) = &assertion.value {
1621 let escaped = escape_dart(expected);
1622 let _ = writeln!(
1623 out,
1624 " final _content = {result_var}.map((c) => c.choices.firstOrNull?.delta.content ?? '').join();"
1625 );
1626 let _ = writeln!(out, " expect(_content, equals('{escaped}'));");
1627 }
1628 }
1629 other => {
1630 let _ = writeln!(out, " // skipped streaming assertion: '{other}'");
1631 }
1632 }
1633}
1634
1635fn snake_to_camel(s: &str) -> String {
1637 let mut result = String::with_capacity(s.len());
1638 let mut next_upper = false;
1639 for ch in s.chars() {
1640 if ch == '_' {
1641 next_upper = true;
1642 } else if next_upper {
1643 result.extend(ch.to_uppercase());
1644 next_upper = false;
1645 } else {
1646 result.push(ch);
1647 }
1648 }
1649 result
1650}
1651
1652fn field_to_dart_accessor(path: &str) -> String {
1665 let mut result = String::with_capacity(path.len());
1666 for (i, segment) in path.split('.').enumerate() {
1667 if i > 0 {
1668 result.push('.');
1669 }
1670 if let Some(bracket_pos) = segment.find('[') {
1676 let name = &segment[..bracket_pos];
1677 let bracket = &segment[bracket_pos..];
1678 result.push_str(&name.to_lower_camel_case());
1679 result.push('!');
1680 result.push_str(bracket);
1681 } else {
1682 result.push_str(&segment.to_lower_camel_case());
1683 }
1684 }
1685 result
1686}
1687
1688fn emit_extraction_config_dart(overrides: &serde_json::Map<String, serde_json::Value>) -> String {
1694 let mut field_overrides: std::collections::HashMap<String, String> = std::collections::HashMap::new();
1696 for (key, val) in overrides {
1697 let camel = snake_to_camel(key);
1698 let dart_val = match val {
1699 serde_json::Value::Bool(b) => {
1700 if *b {
1701 "true".to_string()
1702 } else {
1703 "false".to_string()
1704 }
1705 }
1706 serde_json::Value::Number(n) => n.to_string(),
1707 serde_json::Value::String(s) => format!("'{s}'"),
1708 _ => continue, };
1710 field_overrides.insert(camel, dart_val);
1711 }
1712
1713 let use_cache = field_overrides.remove("useCache").unwrap_or_else(|| "true".to_string());
1714 let enable_quality_processing = field_overrides
1715 .remove("enableQualityProcessing")
1716 .unwrap_or_else(|| "true".to_string());
1717 let force_ocr = field_overrides
1718 .remove("forceOcr")
1719 .unwrap_or_else(|| "false".to_string());
1720 let disable_ocr = field_overrides
1721 .remove("disableOcr")
1722 .unwrap_or_else(|| "false".to_string());
1723 let include_document_structure = field_overrides
1724 .remove("includeDocumentStructure")
1725 .unwrap_or_else(|| "false".to_string());
1726 let use_layout_for_markdown = field_overrides
1727 .remove("useLayoutForMarkdown")
1728 .unwrap_or_else(|| "false".to_string());
1729 let max_archive_depth = field_overrides
1730 .remove("maxArchiveDepth")
1731 .unwrap_or_else(|| "3".to_string());
1732
1733 format!(
1734 "ExtractionConfig(useCache: {use_cache}, enableQualityProcessing: {enable_quality_processing}, forceOcr: {force_ocr}, disableOcr: {disable_ocr}, resultFormat: ResultFormat.unified, outputFormat: OutputFormat.plain(), includeDocumentStructure: {include_document_structure}, useLayoutForMarkdown: {use_layout_for_markdown}, maxArchiveDepth: {max_archive_depth})"
1735 )
1736}
1737
1738struct DartTestClientRenderer {
1754 in_skip: Cell<bool>,
1757 is_redirect: Cell<bool>,
1760}
1761
1762impl DartTestClientRenderer {
1763 fn new(is_redirect: bool) -> Self {
1764 Self {
1765 in_skip: Cell::new(false),
1766 is_redirect: Cell::new(is_redirect),
1767 }
1768 }
1769}
1770
1771impl client::TestClientRenderer for DartTestClientRenderer {
1772 fn language_name(&self) -> &'static str {
1773 "dart"
1774 }
1775
1776 fn render_test_open(&self, out: &mut String, _fn_name: &str, description: &str, skip_reason: Option<&str>) {
1785 let escaped_desc = escape_dart(description);
1786 if let Some(reason) = skip_reason {
1787 let escaped_reason = escape_dart(reason);
1788 let _ = writeln!(out, " test('{escaped_desc}', () {{");
1789 let _ = writeln!(out, " markTestSkipped('{escaped_reason}');");
1790 let _ = writeln!(out, " }});");
1791 let _ = writeln!(out);
1792 self.in_skip.set(true);
1793 } else {
1794 let _ = writeln!(
1795 out,
1796 " test('{escaped_desc}', () => _serialized(() => _withRetry(() async {{"
1797 );
1798 self.in_skip.set(false);
1799 }
1800 }
1801
1802 fn render_test_close(&self, out: &mut String) {
1807 if self.in_skip.get() {
1808 return;
1810 }
1811 let _ = writeln!(out, " }})));");
1812 let _ = writeln!(out);
1813 }
1814
1815 fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
1825 const DART_RESTRICTED_HEADERS: &[&str] = &["content-length", "host", "transfer-encoding"];
1827
1828 let method = ctx.method.to_uppercase();
1829 let escaped_method = escape_dart(&method);
1830
1831 let fixture_path = escape_dart(ctx.path);
1833
1834 let has_explicit_content_type = ctx.headers.keys().any(|k| k.to_lowercase() == "content-type");
1836 let effective_content_type = if has_explicit_content_type {
1837 ctx.headers
1838 .iter()
1839 .find(|(k, _)| k.to_lowercase() == "content-type")
1840 .map(|(_, v)| v.as_str())
1841 .unwrap_or("application/json")
1842 } else if ctx.body.is_some() {
1843 ctx.content_type.unwrap_or("application/json")
1844 } else {
1845 ""
1846 };
1847
1848 let _ = writeln!(
1849 out,
1850 " final baseUrl = Platform.environment['MOCK_SERVER_URL'] ?? 'http://localhost:8080';"
1851 );
1852 let _ = writeln!(out, " final uri = Uri.parse('$baseUrl{fixture_path}');");
1853 let _ = writeln!(
1854 out,
1855 " final ioReq = await _httpClient.openUrl('{escaped_method}', uri);"
1856 );
1857
1858 if self.is_redirect.get() {
1861 let _ = writeln!(out, " ioReq.followRedirects = false;");
1862 }
1863
1864 if !effective_content_type.is_empty() {
1866 let escaped_ct = escape_dart(effective_content_type);
1867 let _ = writeln!(out, " ioReq.headers.set('content-type', '{escaped_ct}');");
1868 }
1869
1870 let mut header_pairs: Vec<(&String, &String)> = ctx.headers.iter().collect();
1872 header_pairs.sort_by_key(|(k, _)| k.as_str());
1873 for (name, value) in &header_pairs {
1874 if DART_RESTRICTED_HEADERS.contains(&name.to_lowercase().as_str()) {
1875 continue;
1876 }
1877 if name.to_lowercase() == "content-type" {
1878 continue; }
1880 let escaped_name = escape_dart(&name.to_lowercase());
1881 let escaped_value = escape_dart(value);
1882 let _ = writeln!(out, " ioReq.headers.set('{escaped_name}', '{escaped_value}');");
1883 }
1884
1885 if !ctx.cookies.is_empty() {
1887 let mut cookie_pairs: Vec<(&String, &String)> = ctx.cookies.iter().collect();
1888 cookie_pairs.sort_by_key(|(k, _)| k.as_str());
1889 let cookie_str: Vec<String> = cookie_pairs.iter().map(|(k, v)| format!("{k}={v}")).collect();
1890 let cookie_header = escape_dart(&cookie_str.join("; "));
1891 let _ = writeln!(out, " ioReq.headers.set('cookie', '{cookie_header}');");
1892 }
1893
1894 if let Some(body) = ctx.body {
1896 let json_str = serde_json::to_string(body).unwrap_or_default();
1897 let escaped = escape_dart(&json_str);
1898 let _ = writeln!(out, " final bodyBytes = utf8.encode('{escaped}');");
1899 let _ = writeln!(out, " ioReq.add(bodyBytes);");
1900 }
1901
1902 let _ = writeln!(out, " final ioResp = await ioReq.close();");
1903 if !self.is_redirect.get() {
1907 let _ = writeln!(out, " final bodyStr = await ioResp.transform(utf8.decoder).join();");
1908 };
1909 }
1910
1911 fn render_assert_status(&self, out: &mut String, _response_var: &str, status: u16) {
1912 let _ = writeln!(
1913 out,
1914 " expect(ioResp.statusCode, equals({status}), reason: 'status code mismatch');"
1915 );
1916 }
1917
1918 fn render_assert_header(&self, out: &mut String, _response_var: &str, name: &str, expected: &str) {
1921 let escaped_name = escape_dart(&name.to_lowercase());
1922 match expected {
1923 "<<present>>" => {
1924 let _ = writeln!(
1925 out,
1926 " expect(ioResp.headers.value('{escaped_name}'), isNotNull, reason: 'header {escaped_name} should be present');"
1927 );
1928 }
1929 "<<absent>>" => {
1930 let _ = writeln!(
1931 out,
1932 " expect(ioResp.headers.value('{escaped_name}'), isNull, reason: 'header {escaped_name} should be absent');"
1933 );
1934 }
1935 "<<uuid>>" => {
1936 let _ = writeln!(
1937 out,
1938 " expect(ioResp.headers.value('{escaped_name}'), matches(RegExp(r'^[0-9a-f]{{8}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{12}}$')), reason: 'header {escaped_name} should be a UUID');"
1939 );
1940 }
1941 exact => {
1942 let escaped_value = escape_dart(exact);
1943 let _ = writeln!(
1944 out,
1945 " expect(ioResp.headers.value('{escaped_name}'), contains('{escaped_value}'), reason: 'header {escaped_name} mismatch');"
1946 );
1947 }
1948 }
1949 }
1950
1951 fn render_assert_json_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
1956 match expected {
1957 serde_json::Value::Object(_) | serde_json::Value::Array(_) => {
1958 let json_str = serde_json::to_string(expected).unwrap_or_default();
1959 let escaped = escape_dart(&json_str);
1960 let _ = writeln!(out, " final bodyJson = jsonDecode(bodyStr);");
1961 let _ = writeln!(out, " final expectedJson = jsonDecode('{escaped}');");
1962 let _ = writeln!(
1963 out,
1964 " expect(bodyJson, equals(expectedJson), reason: 'body mismatch');"
1965 );
1966 }
1967 serde_json::Value::String(s) => {
1968 let escaped = escape_dart(s);
1969 let _ = writeln!(
1970 out,
1971 " expect(bodyStr.trim(), equals('{escaped}'), reason: 'body mismatch');"
1972 );
1973 }
1974 other => {
1975 let escaped = escape_dart(&other.to_string());
1976 let _ = writeln!(
1977 out,
1978 " expect(bodyStr.trim(), equals('{escaped}'), reason: 'body mismatch');"
1979 );
1980 }
1981 }
1982 }
1983
1984 fn render_assert_partial_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
1987 let _ = writeln!(
1988 out,
1989 " final partialJson = jsonDecode(bodyStr) as Map<String, dynamic>;"
1990 );
1991 if let Some(obj) = expected.as_object() {
1992 for (idx, (key, val)) in obj.iter().enumerate() {
1993 let escaped_key = escape_dart(key);
1994 let json_val = serde_json::to_string(val).unwrap_or_default();
1995 let escaped_val = escape_dart(&json_val);
1996 let _ = writeln!(out, " final _expectedField{idx} = jsonDecode('{escaped_val}');");
1999 let _ = writeln!(
2000 out,
2001 " expect(partialJson['{escaped_key}'], equals(_expectedField{idx}), reason: 'partial body field \\'{escaped_key}\\' mismatch');"
2002 );
2003 }
2004 }
2005 }
2006
2007 fn render_assert_validation_errors(
2009 &self,
2010 out: &mut String,
2011 _response_var: &str,
2012 errors: &[ValidationErrorExpectation],
2013 ) {
2014 let _ = writeln!(out, " final errBody = jsonDecode(bodyStr) as Map<String, dynamic>;");
2015 let _ = writeln!(out, " final errList = (errBody['errors'] ?? []) as List<dynamic>;");
2016 for ve in errors {
2017 let loc_dart: Vec<String> = ve.loc.iter().map(|s| format!("'{}'", escape_dart(s))).collect();
2018 let loc_str = loc_dart.join(", ");
2019 let escaped_msg = escape_dart(&ve.msg);
2020 let _ = writeln!(
2021 out,
2022 " expect(errList.any((e) => e is Map && (e['loc'] as List?)?.join(',') == [{loc_str}].join(',') && (e['msg'] as String? ?? '').contains('{escaped_msg}')), isTrue, reason: 'validation error not found: {escaped_msg}');"
2023 );
2024 }
2025 }
2026}
2027
2028fn render_http_test_case(out: &mut String, fixture: &Fixture, http: &HttpFixture) {
2035 if http.expected_response.status_code == 101 {
2037 let description = escape_dart(&fixture.description);
2038 let _ = writeln!(out, " test('{description}', () {{");
2039 let _ = writeln!(
2040 out,
2041 " markTestSkipped('Skipped: Dart HttpClient cannot handle 101 Switching Protocols responses');"
2042 );
2043 let _ = writeln!(out, " }});");
2044 let _ = writeln!(out);
2045 return;
2046 }
2047
2048 let is_redirect = http.expected_response.status_code / 100 == 3;
2052 client::http_call::render_http_test(out, &DartTestClientRenderer::new(is_redirect), fixture);
2053}
2054
2055fn mime_from_extension(path: &str) -> Option<&'static str> {
2060 let ext = path.rsplit('.').next()?;
2061 match ext.to_lowercase().as_str() {
2062 "docx" => Some("application/vnd.openxmlformats-officedocument.wordprocessingml.document"),
2063 "xlsx" => Some("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
2064 "pptx" => Some("application/vnd.openxmlformats-officedocument.presentationml.presentation"),
2065 "pdf" => Some("application/pdf"),
2066 "txt" | "text" => Some("text/plain"),
2067 "html" | "htm" => Some("text/html"),
2068 "json" => Some("application/json"),
2069 "xml" => Some("application/xml"),
2070 "csv" => Some("text/csv"),
2071 "md" | "markdown" => Some("text/markdown"),
2072 "png" => Some("image/png"),
2073 "jpg" | "jpeg" => Some("image/jpeg"),
2074 "gif" => Some("image/gif"),
2075 "zip" => Some("application/zip"),
2076 "odt" => Some("application/vnd.oasis.opendocument.text"),
2077 "ods" => Some("application/vnd.oasis.opendocument.spreadsheet"),
2078 "odp" => Some("application/vnd.oasis.opendocument.presentation"),
2079 "rtf" => Some("application/rtf"),
2080 "epub" => Some("application/epub+zip"),
2081 "msg" => Some("application/vnd.ms-outlook"),
2082 "eml" => Some("message/rfc822"),
2083 _ => None,
2084 }
2085}
2086
2087fn emit_dart_batch_item_array(arr: &serde_json::Value, elem_type: &str) -> String {
2094 let items: Vec<String> = arr
2095 .as_array()
2096 .map(|a| a.as_slice())
2097 .unwrap_or_default()
2098 .iter()
2099 .filter_map(|item| {
2100 let obj = item.as_object()?;
2101 match elem_type {
2102 "BatchBytesItem" => {
2103 let content_bytes = obj
2104 .get("content")
2105 .and_then(|v| v.as_array())
2106 .map(|arr| {
2107 let nums: Vec<String> =
2108 arr.iter().filter_map(|v| v.as_u64().map(|n| n.to_string())).collect();
2109 format!("Uint8List.fromList([{}])", nums.join(", "))
2110 })
2111 .unwrap_or_else(|| "Uint8List(0)".to_string());
2112 let mime_type = obj
2113 .get("mime_type")
2114 .and_then(|v| v.as_str())
2115 .unwrap_or("application/octet-stream");
2116 Some(format!(
2117 "BatchBytesItem(content: {content_bytes}, mimeType: '{}')",
2118 escape_dart(mime_type)
2119 ))
2120 }
2121 "BatchFileItem" => {
2122 let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
2123 Some(format!("BatchFileItem(path: '{}')", escape_dart(path)))
2124 }
2125 _ => None,
2126 }
2127 })
2128 .collect();
2129 format!("[{}]", items.join(", "))
2130}
2131
2132fn dart_stringy_aggregator_contains_assert(
2156 field: Option<&str>,
2157 result_var: &str,
2158 field_resolver: &crate::field_access::FieldResolver,
2159 dart_val: &str,
2160) -> Option<String> {
2161 use crate::field_access::StringyFieldKind;
2162 let field = field?;
2163 let resolved = field_resolver.resolve(field);
2164
2165 if resolved.contains('.') || resolved.contains('[') {
2167 return None;
2168 }
2169
2170 if !field_resolver.is_array(field) && !field_resolver.is_array(resolved) {
2173 return None;
2174 }
2175
2176 let array_accessor = field_resolver.accessor(field, "dart", result_var);
2177
2178 let root_type = field_resolver.dart_root_type().cloned();
2181 if let Some(elem_type) = field_resolver.dart_advance(root_type.as_deref(), resolved) {
2182 if let Some(stringy) = field_resolver.dart_stringy_fields(&elem_type) {
2183 if stringy.len() >= 2 {
2186 let mut texts_lines: Vec<String> = Vec::new();
2192 for sf in stringy {
2193 let call = sf.name.to_lower_camel_case();
2194 match sf.kind {
2195 StringyFieldKind::Plain => {
2196 texts_lines.push(format!(" texts.add(item.{call}.toString());"));
2197 }
2198 StringyFieldKind::Optional => {
2199 texts_lines.push(format!(
2200 " final v_{call} = item.{call};\n if (v_{call} != null) texts.add(v_{call}.toString());"
2201 ));
2202 }
2203 StringyFieldKind::Vec => {
2204 texts_lines.push(format!(
2205 " texts.addAll(item.{call}.map((e) => e.toString()));"
2206 ));
2207 }
2208 }
2209 }
2210 let texts_block = texts_lines.join("\n");
2211 return Some(format!(
2215 " expect({array_accessor}.where((item) {{\n final texts = <String>[];\n{texts_block}\n return texts.any((t) => t.toLowerCase().contains(({dart_val}).toString().toLowerCase()));\n }}).isEmpty, isFalse);"
2216 ));
2217 }
2218 }
2219 }
2220
2221 Some(format!(
2226 " expect({array_accessor}.where((item) => item.toString().toLowerCase().contains(({dart_val}).toString().toLowerCase())).isEmpty, isFalse);"
2227 ))
2228}
2229
2230fn dart_call_result_type(call_config: &alef_core::config::e2e::CallConfig) -> Option<String> {
2238 const LOOKUP_LANGS: &[&str] = &["c", "csharp", "java", "kotlin", "go", "php"];
2239 for lang in LOOKUP_LANGS {
2240 if let Some(o) = call_config.overrides.get(*lang)
2241 && let Some(rt) = o.result_type.as_deref()
2242 && !rt.is_empty()
2243 {
2244 return Some(rt.to_string());
2245 }
2246 }
2247 None
2248}
2249
2250pub(super) fn escape_dart(s: &str) -> String {
2252 s.replace('\\', "\\\\")
2253 .replace('\'', "\\'")
2254 .replace('\n', "\\n")
2255 .replace('\r', "\\r")
2256 .replace('\t', "\\t")
2257 .replace('$', "\\$")
2258}
2259
2260fn type_name_to_create_from_json_dart(type_name: &str) -> String {
2268 let mut snake = String::with_capacity(type_name.len() + 8);
2270 for (i, ch) in type_name.char_indices() {
2271 if ch.is_uppercase() {
2272 if i > 0 {
2273 snake.push('_');
2274 }
2275 snake.extend(ch.to_lowercase());
2276 } else {
2277 snake.push(ch);
2278 }
2279 }
2280 let rust_fn = format!("create_{snake}_from_json");
2283 rust_fn
2285 .split('_')
2286 .enumerate()
2287 .map(|(i, part)| {
2288 if i == 0 {
2289 part.to_string()
2290 } else {
2291 let mut chars = part.chars();
2292 match chars.next() {
2293 None => String::new(),
2294 Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
2295 }
2296 }
2297 })
2298 .collect::<Vec<_>>()
2299 .join("")
2300}
2301
2302fn build_dart_first_class_map(
2307 type_defs: &[alef_core::ir::TypeDef],
2308 enum_defs: &[alef_core::ir::EnumDef],
2309 e2e_config: &crate::config::E2eConfig,
2310) -> crate::field_access::DartFirstClassMap {
2311 use crate::field_access::{StringyField, StringyFieldKind};
2312 use alef_core::ir::TypeRef;
2313
2314 let mut field_types: std::collections::HashMap<String, std::collections::HashMap<String, String>> =
2315 std::collections::HashMap::new();
2316
2317 fn inner_named(ty: &TypeRef) -> Option<String> {
2318 match ty {
2319 TypeRef::Named(n) => Some(n.clone()),
2320 TypeRef::Optional(inner) | TypeRef::Vec(inner) => inner_named(inner),
2321 _ => None,
2322 }
2323 }
2324
2325 let enum_names: std::collections::HashSet<&str> = enum_defs.iter().map(|e| e.name.as_str()).collect();
2326 let classify_stringy = |ty: &TypeRef, field_optional: bool| -> Option<StringyFieldKind> {
2327 match ty {
2328 TypeRef::String => Some(if field_optional {
2329 StringyFieldKind::Optional
2330 } else {
2331 StringyFieldKind::Plain
2332 }),
2333 TypeRef::Named(name) if enum_names.contains(name.as_str()) => Some(if field_optional {
2334 StringyFieldKind::Optional
2335 } else {
2336 StringyFieldKind::Plain
2337 }),
2338 TypeRef::Optional(inner) => match inner.as_ref() {
2339 TypeRef::String => Some(StringyFieldKind::Optional),
2340 TypeRef::Named(name) if enum_names.contains(name.as_str()) => Some(StringyFieldKind::Optional),
2341 _ => None,
2342 },
2343 TypeRef::Vec(inner) => match inner.as_ref() {
2344 TypeRef::String => Some(StringyFieldKind::Vec),
2345 TypeRef::Named(name) if enum_names.contains(name.as_str()) => Some(StringyFieldKind::Vec),
2346 _ => None,
2347 },
2348 _ => None,
2349 }
2350 };
2351
2352 let mut stringy_fields_by_type: std::collections::HashMap<String, Vec<StringyField>> =
2353 std::collections::HashMap::new();
2354 for td in type_defs {
2355 let mut td_field_types: std::collections::HashMap<String, String> = std::collections::HashMap::new();
2356 let mut td_stringy: Vec<StringyField> = Vec::new();
2357 for f in &td.fields {
2358 if let Some(named) = inner_named(&f.ty) {
2359 td_field_types.insert(f.name.clone(), named);
2360 }
2361 if f.binding_excluded {
2362 continue;
2363 }
2364 if let Some(kind) = classify_stringy(&f.ty, f.optional) {
2365 td_stringy.push(StringyField {
2366 name: f.name.clone(),
2367 kind,
2368 });
2369 }
2370 }
2371 if !td_field_types.is_empty() {
2372 field_types.insert(td.name.clone(), td_field_types);
2373 }
2374 if !td_stringy.is_empty() {
2375 stringy_fields_by_type.insert(td.name.clone(), td_stringy);
2376 }
2377 }
2378
2379 let root_type = if e2e_config.result_fields.is_empty() {
2382 None
2383 } else {
2384 let matches: Vec<&alef_core::ir::TypeDef> = type_defs
2385 .iter()
2386 .filter(|td| {
2387 let names: std::collections::HashSet<&str> = td.fields.iter().map(|f| f.name.as_str()).collect();
2388 e2e_config.result_fields.iter().all(|rf| names.contains(rf.as_str()))
2389 })
2390 .collect();
2391 if matches.len() == 1 {
2392 Some(matches[0].name.clone())
2393 } else {
2394 None
2395 }
2396 };
2397
2398 crate::field_access::DartFirstClassMap {
2399 field_types,
2400 root_type,
2401 stringy_fields_by_type,
2402 }
2403}