1use crate::codegen::resolve_field;
8use crate::config::E2eConfig;
9use crate::escape::sanitize_filename;
10use crate::fixture::{Fixture, FixtureGroup, HttpFixture, ValidationErrorExpectation};
11use alef_core::backend::GeneratedFile;
12use alef_core::config::ResolvedCrateConfig;
13use alef_core::hash::{self, CommentStyle};
14use alef_core::template_versions::pub_dev;
15use anyhow::Result;
16use std::cell::Cell;
17use std::fmt::Write as FmtWrite;
18use std::path::PathBuf;
19
20use super::E2eCodegen;
21use super::client;
22
23pub struct DartE2eCodegen;
25
26impl E2eCodegen for DartE2eCodegen {
27 fn generate(
28 &self,
29 groups: &[FixtureGroup],
30 e2e_config: &E2eConfig,
31 config: &ResolvedCrateConfig,
32 _type_defs: &[alef_core::ir::TypeDef],
33 ) -> Result<Vec<GeneratedFile>> {
34 let lang = self.language_name();
35 let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
36
37 let mut files = Vec::new();
38
39 let dart_pkg = e2e_config.resolve_package("dart");
41 let pkg_name = dart_pkg
42 .as_ref()
43 .and_then(|p| p.name.as_ref())
44 .cloned()
45 .unwrap_or_else(|| config.dart_pubspec_name());
46 let pkg_path = dart_pkg
47 .as_ref()
48 .and_then(|p| p.path.as_ref())
49 .cloned()
50 .unwrap_or_else(|| "../../packages/dart".to_string());
51 let pkg_version = dart_pkg
52 .as_ref()
53 .and_then(|p| p.version.as_ref())
54 .cloned()
55 .or_else(|| config.resolved_version())
56 .unwrap_or_else(|| "0.1.0".to_string());
57
58 files.push(GeneratedFile {
60 path: output_base.join("pubspec.yaml"),
61 content: render_pubspec(&pkg_name, &pkg_path, &pkg_version, e2e_config.dep_mode),
62 generated_header: false,
63 });
64
65 files.push(GeneratedFile {
68 path: output_base.join("dart_test.yaml"),
69 content: concat!(
70 "# Generated by alef — DO NOT EDIT.\n",
71 "# Run test files sequentially to avoid overwhelming the mock server with\n",
72 "# concurrent keep-alive connections.\n",
73 "concurrency: 1\n",
74 )
75 .to_string(),
76 generated_header: false,
77 });
78
79 let test_base = output_base.join("test");
80
81 for group in groups {
83 let active: Vec<&Fixture> = group
84 .fixtures
85 .iter()
86 .filter(|f| super::should_include_fixture(f, lang, e2e_config))
87 .collect();
88
89 if active.is_empty() {
90 continue;
91 }
92
93 let filename = format!("{}_test.dart", sanitize_filename(&group.category));
94 let content = render_test_file(&group.category, &active, e2e_config, lang);
95 files.push(GeneratedFile {
96 path: test_base.join(filename),
97 content,
98 generated_header: true,
99 });
100 }
101
102 Ok(files)
103 }
104
105 fn language_name(&self) -> &'static str {
106 "dart"
107 }
108}
109
110fn render_pubspec(
115 pkg_name: &str,
116 pkg_path: &str,
117 pkg_version: &str,
118 dep_mode: crate::config::DependencyMode,
119) -> String {
120 let test_ver = pub_dev::TEST_PACKAGE;
121 let http_ver = pub_dev::HTTP_PACKAGE;
122
123 let dep_block = match dep_mode {
124 crate::config::DependencyMode::Registry => {
125 format!(" {pkg_name}: ^{pkg_version}")
126 }
127 crate::config::DependencyMode::Local => {
128 format!(" {pkg_name}:\n path: {pkg_path}")
129 }
130 };
131
132 format!(
133 r#"name: e2e_dart
134version: 0.1.0
135publish_to: none
136
137environment:
138 sdk: ">=3.0.0 <4.0.0"
139
140dependencies:
141{dep_block}
142
143dev_dependencies:
144 test: {test_ver}
145 http: {http_ver}
146"#
147 )
148}
149
150fn render_test_file(category: &str, fixtures: &[&Fixture], e2e_config: &E2eConfig, lang: &str) -> String {
151 let mut out = String::new();
152 out.push_str(&hash::header(CommentStyle::DoubleSlash));
153
154 let has_http_fixtures = fixtures.iter().any(|f| f.is_http_test());
156
157 let has_batch_byte_items = fixtures.iter().any(|f| {
159 let call_config = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
160 call_config.args.iter().any(|a| {
161 a.element_type.as_deref() == Some("BatchBytesItem") && resolve_field(&f.input, &a.field).is_array()
162 })
163 });
164
165 let needs_chdir = fixtures.iter().any(|f| {
169 if f.is_http_test() {
170 return false;
171 }
172 let call_config = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
173 call_config
174 .args
175 .iter()
176 .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
177 });
178
179 let _ = writeln!(out, "import 'package:test/test.dart';");
180 let _ = writeln!(out, "import 'dart:io';");
181 if has_batch_byte_items {
182 let _ = writeln!(out, "import 'dart:typed_data';");
183 }
184 let _ = writeln!(out, "import 'package:kreuzberg/kreuzberg.dart';");
185 let _ = writeln!(
188 out,
189 "import 'package:kreuzberg/src/kreuzberg_bridge_generated/frb_generated.dart' show RustLib;"
190 );
191 if has_http_fixtures {
192 let _ = writeln!(out, "import 'dart:async';");
193 let _ = writeln!(out, "import 'dart:convert';");
194 }
195 let _ = writeln!(out);
196
197 if has_http_fixtures {
207 let _ = writeln!(out, "HttpClient _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
208 let _ = writeln!(out);
209 let _ = writeln!(out, "var _lock = Future<void>.value();");
210 let _ = writeln!(out);
211 let _ = writeln!(out, "Future<T> _serialized<T>(Future<T> Function() fn) async {{");
212 let _ = writeln!(out, " final current = _lock;");
213 let _ = writeln!(out, " final next = Completer<void>();");
214 let _ = writeln!(out, " _lock = next.future;");
215 let _ = writeln!(out, " try {{");
216 let _ = writeln!(out, " await current;");
217 let _ = writeln!(out, " return await fn();");
218 let _ = writeln!(out, " }} finally {{");
219 let _ = writeln!(out, " next.complete();");
220 let _ = writeln!(out, " }}");
221 let _ = writeln!(out, "}}");
222 let _ = writeln!(out);
223 let _ = writeln!(out, "Future<T> _withRetry<T>(Future<T> Function() fn) async {{");
226 let _ = writeln!(out, " try {{");
227 let _ = writeln!(out, " return await fn();");
228 let _ = writeln!(out, " }} on SocketException {{");
229 let _ = writeln!(out, " _httpClient.close(force: true);");
230 let _ = writeln!(out, " _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
231 let _ = writeln!(out, " return fn();");
232 let _ = writeln!(out, " }} on HttpException {{");
233 let _ = writeln!(out, " _httpClient.close(force: true);");
234 let _ = writeln!(out, " _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
235 let _ = writeln!(out, " return fn();");
236 let _ = writeln!(out, " }}");
237 let _ = writeln!(out, "}}");
238 let _ = writeln!(out);
239 }
240
241 let _ = writeln!(out, "// E2e tests for category: {category}");
242 let _ = writeln!(out, "void main() {{");
243
244 let _ = writeln!(out, " setUpAll(() async {{");
251 let _ = writeln!(out, " await RustLib.init();");
252 if needs_chdir {
253 let _ = writeln!(
254 out,
255 " final _testDocs = Platform.environment['FIXTURES_DIR'] ?? '../../test_documents';"
256 );
257 let _ = writeln!(out, " final _dir = Directory(_testDocs);");
258 let _ = writeln!(out, " if (_dir.existsSync()) Directory.current = _dir;");
259 }
260 let _ = writeln!(out, " }});");
261 let _ = writeln!(out);
262
263 if has_http_fixtures {
265 let _ = writeln!(out, " tearDownAll(() => _httpClient.close());");
266 let _ = writeln!(out);
267 }
268
269 for fixture in fixtures {
270 render_test_case(&mut out, fixture, e2e_config, lang);
271 }
272
273 let _ = writeln!(out, "}}");
274 out
275}
276
277fn render_test_case(out: &mut String, fixture: &Fixture, e2e_config: &E2eConfig, lang: &str) {
278 if let Some(http) = &fixture.http {
280 render_http_test_case(out, fixture, http);
281 return;
282 }
283
284 let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
286 let call_overrides = call_config.overrides.get(lang);
287 let mut function_name = call_overrides
288 .and_then(|o| o.function.as_ref())
289 .cloned()
290 .unwrap_or_else(|| call_config.function.clone());
291 function_name = function_name
293 .split('_')
294 .enumerate()
295 .map(|(i, part)| {
296 if i == 0 {
297 part.to_string()
298 } else {
299 let mut chars = part.chars();
300 match chars.next() {
301 None => String::new(),
302 Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
303 }
304 }
305 })
306 .collect::<Vec<_>>()
307 .join("");
308 let result_var = &call_config.result_var;
309 let description = escape_dart(&fixture.description);
310 let _is_async = call_overrides.and_then(|o| o.r#async).unwrap_or(call_config.r#async);
313
314 let file_path_for_mime: Option<&str> = call_config
322 .args
323 .iter()
324 .find(|a| a.arg_type == "file_path")
325 .and_then(|a| resolve_field(&fixture.input, &a.field).as_str());
326
327 let has_file_path_arg = call_config.args.iter().any(|a| a.arg_type == "file_path");
334 let caller_supplied_override = call_overrides.and_then(|o| o.function.as_ref()).is_some();
337 if has_file_path_arg && !caller_supplied_override {
338 function_name = match function_name.as_str() {
339 "extractFile" => "extractBytes".to_string(),
340 "extractFileSync" => "extractBytesSync".to_string(),
341 other => other.to_string(),
342 };
343 }
344
345 let mut args = Vec::new();
346 for arg_def in &call_config.args {
347 let arg_value = resolve_field(&fixture.input, &arg_def.field);
348 match arg_def.arg_type.as_str() {
349 "bytes" | "file_path" => {
350 if let serde_json::Value::String(file_path) = arg_value {
355 args.push(format!("File('{}').readAsBytesSync()", file_path));
356 }
357 }
358 "string" => {
359 match arg_value {
360 serde_json::Value::String(s) => {
361 args.push(format!("'{}'", escape_dart(s)));
362 }
363 serde_json::Value::Null
364 if arg_def.optional
365 && arg_def.name == "mime_type" =>
368 {
369 let inferred = file_path_for_mime
370 .and_then(mime_from_extension)
371 .unwrap_or("application/octet-stream");
372 args.push(format!("'{inferred}'"));
373 }
374 _ => {}
376 }
377 }
378 "json_object" => {
379 if let Some(elem_type) = &arg_def.element_type {
381 if (elem_type == "BatchBytesItem" || elem_type == "BatchFileItem") && arg_value.is_array() {
382 let dart_items = emit_dart_batch_item_array(arg_value, elem_type);
383 args.push(dart_items);
384 }
385 } else if arg_def.name == "config" {
386 if let serde_json::Value::Object(map) = &arg_value {
387 if !map.is_empty() {
391 args.push(emit_extraction_config_dart(map));
392 }
393 }
394 }
396 }
397 _ => {}
398 }
399 }
400
401 let _ = writeln!(out, " test('{description}', () async {{");
405
406 let args_str = args.join(", ");
408 let receiver_class = call_overrides
409 .and_then(|o| o.class.as_ref())
410 .cloned()
411 .unwrap_or_else(|| "KreuzbergBridge".to_string());
412
413 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
414
415 if expects_error {
416 let _ = writeln!(
421 out,
422 " await expectLater({receiver_class}.{function_name}({args_str}), throwsA(anything));"
423 );
424 } else {
425 let _ = writeln!(
426 out,
427 " final {result_var} = await {receiver_class}.{function_name}({args_str});"
428 );
429 }
430
431 let _ = writeln!(out, " }});");
432 let _ = writeln!(out);
433}
434
435fn snake_to_camel(s: &str) -> String {
437 let mut result = String::with_capacity(s.len());
438 let mut next_upper = false;
439 for ch in s.chars() {
440 if ch == '_' {
441 next_upper = true;
442 } else if next_upper {
443 result.extend(ch.to_uppercase());
444 next_upper = false;
445 } else {
446 result.push(ch);
447 }
448 }
449 result
450}
451
452fn emit_extraction_config_dart(overrides: &serde_json::Map<String, serde_json::Value>) -> String {
458 let mut field_overrides: std::collections::HashMap<String, String> = std::collections::HashMap::new();
460 for (key, val) in overrides {
461 let camel = snake_to_camel(key);
462 let dart_val = match val {
463 serde_json::Value::Bool(b) => {
464 if *b {
465 "true".to_string()
466 } else {
467 "false".to_string()
468 }
469 }
470 serde_json::Value::Number(n) => n.to_string(),
471 serde_json::Value::String(s) => format!("'{s}'"),
472 _ => continue, };
474 field_overrides.insert(camel, dart_val);
475 }
476
477 let use_cache = field_overrides.remove("useCache").unwrap_or_else(|| "true".to_string());
478 let enable_quality_processing = field_overrides
479 .remove("enableQualityProcessing")
480 .unwrap_or_else(|| "true".to_string());
481 let force_ocr = field_overrides
482 .remove("forceOcr")
483 .unwrap_or_else(|| "false".to_string());
484 let disable_ocr = field_overrides
485 .remove("disableOcr")
486 .unwrap_or_else(|| "false".to_string());
487 let include_document_structure = field_overrides
488 .remove("includeDocumentStructure")
489 .unwrap_or_else(|| "false".to_string());
490 let max_archive_depth = field_overrides
491 .remove("maxArchiveDepth")
492 .unwrap_or_else(|| "3".to_string());
493
494 format!(
495 "ExtractionConfig(useCache: {use_cache}, enableQualityProcessing: {enable_quality_processing}, forceOcr: {force_ocr}, disableOcr: {disable_ocr}, resultFormat: ResultFormat.unified, outputFormat: OutputFormat.plain(), includeDocumentStructure: {include_document_structure}, maxArchiveDepth: {max_archive_depth})"
496 )
497}
498
499struct DartTestClientRenderer {
515 in_skip: Cell<bool>,
518 is_redirect: Cell<bool>,
521}
522
523impl DartTestClientRenderer {
524 fn new(is_redirect: bool) -> Self {
525 Self {
526 in_skip: Cell::new(false),
527 is_redirect: Cell::new(is_redirect),
528 }
529 }
530}
531
532impl client::TestClientRenderer for DartTestClientRenderer {
533 fn language_name(&self) -> &'static str {
534 "dart"
535 }
536
537 fn render_test_open(&self, out: &mut String, _fn_name: &str, description: &str, skip_reason: Option<&str>) {
546 let escaped_desc = escape_dart(description);
547 if let Some(reason) = skip_reason {
548 let escaped_reason = escape_dart(reason);
549 let _ = writeln!(out, " test('{escaped_desc}', () {{");
550 let _ = writeln!(out, " markTestSkipped('{escaped_reason}');");
551 let _ = writeln!(out, " }});");
552 let _ = writeln!(out);
553 self.in_skip.set(true);
554 } else {
555 let _ = writeln!(
556 out,
557 " test('{escaped_desc}', () => _serialized(() => _withRetry(() async {{"
558 );
559 self.in_skip.set(false);
560 }
561 }
562
563 fn render_test_close(&self, out: &mut String) {
568 if self.in_skip.get() {
569 return;
571 }
572 let _ = writeln!(out, " }})));");
573 let _ = writeln!(out);
574 }
575
576 fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
586 const DART_RESTRICTED_HEADERS: &[&str] = &["content-length", "host", "transfer-encoding"];
588
589 let method = ctx.method.to_uppercase();
590 let escaped_method = escape_dart(&method);
591
592 let fixture_path = escape_dart(ctx.path);
594
595 let has_explicit_content_type = ctx.headers.keys().any(|k| k.to_lowercase() == "content-type");
597 let effective_content_type = if has_explicit_content_type {
598 ctx.headers
599 .iter()
600 .find(|(k, _)| k.to_lowercase() == "content-type")
601 .map(|(_, v)| v.as_str())
602 .unwrap_or("application/json")
603 } else if ctx.body.is_some() {
604 ctx.content_type.unwrap_or("application/json")
605 } else {
606 ""
607 };
608
609 let _ = writeln!(
610 out,
611 " final baseUrl = Platform.environment['MOCK_SERVER_URL'] ?? 'http://localhost:8080';"
612 );
613 let _ = writeln!(out, " final uri = Uri.parse('$baseUrl{fixture_path}');");
614 let _ = writeln!(
615 out,
616 " final ioReq = await _httpClient.openUrl('{escaped_method}', uri);"
617 );
618
619 if self.is_redirect.get() {
622 let _ = writeln!(out, " ioReq.followRedirects = false;");
623 }
624
625 if !effective_content_type.is_empty() {
627 let escaped_ct = escape_dart(effective_content_type);
628 let _ = writeln!(out, " ioReq.headers.set('content-type', '{escaped_ct}');");
629 }
630
631 let mut header_pairs: Vec<(&String, &String)> = ctx.headers.iter().collect();
633 header_pairs.sort_by_key(|(k, _)| k.as_str());
634 for (name, value) in &header_pairs {
635 if DART_RESTRICTED_HEADERS.contains(&name.to_lowercase().as_str()) {
636 continue;
637 }
638 if name.to_lowercase() == "content-type" {
639 continue; }
641 let escaped_name = escape_dart(&name.to_lowercase());
642 let escaped_value = escape_dart(value);
643 let _ = writeln!(out, " ioReq.headers.set('{escaped_name}', '{escaped_value}');");
644 }
645
646 if !ctx.cookies.is_empty() {
648 let mut cookie_pairs: Vec<(&String, &String)> = ctx.cookies.iter().collect();
649 cookie_pairs.sort_by_key(|(k, _)| k.as_str());
650 let cookie_str: Vec<String> = cookie_pairs.iter().map(|(k, v)| format!("{k}={v}")).collect();
651 let cookie_header = escape_dart(&cookie_str.join("; "));
652 let _ = writeln!(out, " ioReq.headers.set('cookie', '{cookie_header}');");
653 }
654
655 if let Some(body) = ctx.body {
657 let json_str = serde_json::to_string(body).unwrap_or_default();
658 let escaped = escape_dart(&json_str);
659 let _ = writeln!(out, " final bodyBytes = utf8.encode('{escaped}');");
660 let _ = writeln!(out, " ioReq.add(bodyBytes);");
661 }
662
663 let _ = writeln!(out, " final ioResp = await ioReq.close();");
664 if !self.is_redirect.get() {
668 let _ = writeln!(out, " final bodyStr = await ioResp.transform(utf8.decoder).join();");
669 };
670 }
671
672 fn render_assert_status(&self, out: &mut String, _response_var: &str, status: u16) {
673 let _ = writeln!(
674 out,
675 " expect(ioResp.statusCode, equals({status}), reason: 'status code mismatch');"
676 );
677 }
678
679 fn render_assert_header(&self, out: &mut String, _response_var: &str, name: &str, expected: &str) {
682 let escaped_name = escape_dart(&name.to_lowercase());
683 match expected {
684 "<<present>>" => {
685 let _ = writeln!(
686 out,
687 " expect(ioResp.headers.value('{escaped_name}'), isNotNull, reason: 'header {escaped_name} should be present');"
688 );
689 }
690 "<<absent>>" => {
691 let _ = writeln!(
692 out,
693 " expect(ioResp.headers.value('{escaped_name}'), isNull, reason: 'header {escaped_name} should be absent');"
694 );
695 }
696 "<<uuid>>" => {
697 let _ = writeln!(
698 out,
699 " 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');"
700 );
701 }
702 exact => {
703 let escaped_value = escape_dart(exact);
704 let _ = writeln!(
705 out,
706 " expect(ioResp.headers.value('{escaped_name}'), contains('{escaped_value}'), reason: 'header {escaped_name} mismatch');"
707 );
708 }
709 }
710 }
711
712 fn render_assert_json_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
717 match expected {
718 serde_json::Value::Object(_) | serde_json::Value::Array(_) => {
719 let json_str = serde_json::to_string(expected).unwrap_or_default();
720 let escaped = escape_dart(&json_str);
721 let _ = writeln!(out, " final bodyJson = jsonDecode(bodyStr);");
722 let _ = writeln!(out, " final expectedJson = jsonDecode('{escaped}');");
723 let _ = writeln!(
724 out,
725 " expect(bodyJson, equals(expectedJson), reason: 'body mismatch');"
726 );
727 }
728 serde_json::Value::String(s) => {
729 let escaped = escape_dart(s);
730 let _ = writeln!(
731 out,
732 " expect(bodyStr.trim(), equals('{escaped}'), reason: 'body mismatch');"
733 );
734 }
735 other => {
736 let escaped = escape_dart(&other.to_string());
737 let _ = writeln!(
738 out,
739 " expect(bodyStr.trim(), equals('{escaped}'), reason: 'body mismatch');"
740 );
741 }
742 }
743 }
744
745 fn render_assert_partial_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
748 let _ = writeln!(
749 out,
750 " final partialJson = jsonDecode(bodyStr) as Map<String, dynamic>;"
751 );
752 if let Some(obj) = expected.as_object() {
753 for (idx, (key, val)) in obj.iter().enumerate() {
754 let escaped_key = escape_dart(key);
755 let json_val = serde_json::to_string(val).unwrap_or_default();
756 let escaped_val = escape_dart(&json_val);
757 let _ = writeln!(out, " final _expectedField{idx} = jsonDecode('{escaped_val}');");
760 let _ = writeln!(
761 out,
762 " expect(partialJson['{escaped_key}'], equals(_expectedField{idx}), reason: 'partial body field \\'{escaped_key}\\' mismatch');"
763 );
764 }
765 }
766 }
767
768 fn render_assert_validation_errors(
770 &self,
771 out: &mut String,
772 _response_var: &str,
773 errors: &[ValidationErrorExpectation],
774 ) {
775 let _ = writeln!(out, " final errBody = jsonDecode(bodyStr) as Map<String, dynamic>;");
776 let _ = writeln!(out, " final errList = (errBody['errors'] ?? []) as List<dynamic>;");
777 for ve in errors {
778 let loc_dart: Vec<String> = ve.loc.iter().map(|s| format!("'{}'", escape_dart(s))).collect();
779 let loc_str = loc_dart.join(", ");
780 let escaped_msg = escape_dart(&ve.msg);
781 let _ = writeln!(
782 out,
783 " 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}');"
784 );
785 }
786 }
787}
788
789fn render_http_test_case(out: &mut String, fixture: &Fixture, http: &HttpFixture) {
796 if http.expected_response.status_code == 101 {
798 let description = escape_dart(&fixture.description);
799 let _ = writeln!(out, " test('{description}', () {{");
800 let _ = writeln!(
801 out,
802 " markTestSkipped('Skipped: Dart HttpClient cannot handle 101 Switching Protocols responses');"
803 );
804 let _ = writeln!(out, " }});");
805 let _ = writeln!(out);
806 return;
807 }
808
809 let is_redirect = http.expected_response.status_code / 100 == 3;
813 client::http_call::render_http_test(out, &DartTestClientRenderer::new(is_redirect), fixture);
814}
815
816fn mime_from_extension(path: &str) -> Option<&'static str> {
821 let ext = path.rsplit('.').next()?;
822 match ext.to_lowercase().as_str() {
823 "docx" => Some("application/vnd.openxmlformats-officedocument.wordprocessingml.document"),
824 "xlsx" => Some("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
825 "pptx" => Some("application/vnd.openxmlformats-officedocument.presentationml.presentation"),
826 "pdf" => Some("application/pdf"),
827 "txt" | "text" => Some("text/plain"),
828 "html" | "htm" => Some("text/html"),
829 "json" => Some("application/json"),
830 "xml" => Some("application/xml"),
831 "csv" => Some("text/csv"),
832 "md" | "markdown" => Some("text/markdown"),
833 "png" => Some("image/png"),
834 "jpg" | "jpeg" => Some("image/jpeg"),
835 "gif" => Some("image/gif"),
836 "zip" => Some("application/zip"),
837 "odt" => Some("application/vnd.oasis.opendocument.text"),
838 "ods" => Some("application/vnd.oasis.opendocument.spreadsheet"),
839 "odp" => Some("application/vnd.oasis.opendocument.presentation"),
840 "rtf" => Some("application/rtf"),
841 "epub" => Some("application/epub+zip"),
842 "msg" => Some("application/vnd.ms-outlook"),
843 "eml" => Some("message/rfc822"),
844 _ => None,
845 }
846}
847
848fn emit_dart_batch_item_array(arr: &serde_json::Value, elem_type: &str) -> String {
855 let items: Vec<String> = arr
856 .as_array()
857 .map(|a| a.as_slice())
858 .unwrap_or_default()
859 .iter()
860 .filter_map(|item| {
861 let obj = item.as_object()?;
862 match elem_type {
863 "BatchBytesItem" => {
864 let content_bytes = obj
865 .get("content")
866 .and_then(|v| v.as_array())
867 .map(|arr| {
868 let nums: Vec<String> =
869 arr.iter().filter_map(|v| v.as_u64().map(|n| n.to_string())).collect();
870 format!("Uint8List.fromList([{}])", nums.join(", "))
871 })
872 .unwrap_or_else(|| "Uint8List(0)".to_string());
873 let mime_type = obj
874 .get("mime_type")
875 .and_then(|v| v.as_str())
876 .unwrap_or("application/octet-stream");
877 Some(format!(
878 "BatchBytesItem(content: {content_bytes}, mimeType: '{}')",
879 escape_dart(mime_type)
880 ))
881 }
882 "BatchFileItem" => {
883 let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
884 Some(format!("BatchFileItem(path: '{}')", escape_dart(path)))
885 }
886 _ => None,
887 }
888 })
889 .collect();
890 format!("[{}]", items.join(", "))
891}
892
893fn escape_dart(s: &str) -> String {
895 s.replace('\\', "\\\\")
896 .replace('\'', "\\'")
897 .replace('\n', "\\n")
898 .replace('\r', "\\r")
899 .replace('\t', "\\t")
900 .replace('$', "\\$")
901}