1use crate::codegen::resolve_field;
7use crate::config::E2eConfig;
8use crate::escape::{ruby_string_literal, ruby_template_to_interpolation, sanitize_filename, sanitize_ident};
9use crate::field_access::FieldResolver;
10use crate::fixture::{
11 Assertion, CallbackAction, Fixture, FixtureGroup, TemplateReturnForm, ValidationErrorExpectation,
12};
13use alef_core::backend::GeneratedFile;
14use alef_core::config::ResolvedCrateConfig;
15use alef_core::hash::{self, CommentStyle};
16use alef_core::template_versions as tv;
17use anyhow::Result;
18use heck::ToSnakeCase;
19use std::collections::{HashMap, HashSet};
20use std::fmt::Write as FmtWrite;
21use std::path::PathBuf;
22
23use super::E2eCodegen;
24use super::client;
25
26pub struct RubyCodegen;
28
29impl E2eCodegen for RubyCodegen {
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 call = &e2e_config.call;
45 let overrides = call.overrides.get(lang);
46 let module_path = overrides
47 .and_then(|o| o.module.as_ref())
48 .cloned()
49 .unwrap_or_else(|| call.module.clone());
50 let class_name = overrides.and_then(|o| o.class.as_ref()).cloned();
51 let options_type = overrides.and_then(|o| o.options_type.clone());
52 let empty_enum_fields = HashMap::new();
53 let enum_fields = overrides.map(|o| &o.enum_fields).unwrap_or(&empty_enum_fields);
54 let result_is_simple = call.result_is_simple || overrides.is_some_and(|o| o.result_is_simple);
55
56 let ruby_pkg = e2e_config.resolve_package("ruby");
58 let gem_name = ruby_pkg
59 .as_ref()
60 .and_then(|p| p.name.as_ref())
61 .cloned()
62 .unwrap_or_else(|| config.name.replace('-', "_"));
63 let gem_path = ruby_pkg
64 .as_ref()
65 .and_then(|p| p.path.as_ref())
66 .cloned()
67 .unwrap_or_else(|| "../../packages/ruby".to_string());
68 let gem_version = ruby_pkg
69 .as_ref()
70 .and_then(|p| p.version.as_ref())
71 .cloned()
72 .or_else(|| config.resolved_version())
73 .unwrap_or_else(|| "0.1.0".to_string());
74
75 files.push(GeneratedFile {
77 path: output_base.join("Gemfile"),
78 content: render_gemfile(&gem_name, &gem_path, &gem_version, e2e_config.dep_mode),
79 generated_header: false,
80 });
81
82 files.push(GeneratedFile {
84 path: output_base.join(".rubocop.yaml"),
85 content: render_rubocop_yaml(),
86 generated_header: false,
87 });
88
89 let has_http_fixtures = groups
91 .iter()
92 .flat_map(|g| g.fixtures.iter())
93 .any(|f| f.needs_mock_server());
94
95 let has_file_fixtures = groups.iter().flat_map(|g| g.fixtures.iter()).any(|f| {
97 let cc = e2e_config.resolve_call_for_fixture(
98 f.call.as_deref(),
99 &f.id,
100 &f.resolved_category(),
101 &f.tags,
102 &f.input,
103 );
104 cc.args
105 .iter()
106 .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
107 });
108
109 if has_file_fixtures || has_http_fixtures {
111 files.push(GeneratedFile {
112 path: output_base.join("spec").join("spec_helper.rb"),
113 content: render_spec_helper(
114 has_file_fixtures,
115 has_http_fixtures,
116 &e2e_config.test_documents_relative_from(1),
117 ),
118 generated_header: true,
119 });
120 }
121
122 let spec_base = output_base.join("spec");
124
125 for group in groups {
126 let active: Vec<&Fixture> = group
127 .fixtures
128 .iter()
129 .filter(|f| super::should_include_fixture(f, lang, e2e_config))
130 .collect();
131
132 if active.is_empty() {
133 continue;
134 }
135
136 let has_any_output = active.iter().any(|f| {
138 if f.is_http_test() {
140 return true;
141 }
142 let cc = e2e_config.resolve_call_for_fixture(
143 f.call.as_deref(),
144 &f.id,
145 &f.resolved_category(),
146 &f.tags,
147 &f.input,
148 );
149 let fr = FieldResolver::new(
150 e2e_config.effective_fields(cc),
151 e2e_config.effective_fields_optional(cc),
152 e2e_config.effective_result_fields(cc),
153 e2e_config.effective_fields_array(cc),
154 &std::collections::HashSet::new(),
155 );
156 let expects_error = f.assertions.iter().any(|a| a.assertion_type == "error");
157 let has_not_error = f.assertions.iter().any(|a| a.assertion_type == "not_error");
158 expects_error || has_not_error || has_usable_assertion(f, &fr, result_is_simple)
159 });
160 if !has_any_output {
161 continue;
162 }
163
164 let filename = format!("{}_spec.rb", sanitize_filename(&group.category));
165 let content = render_spec_file(
166 &group.category,
167 &active,
168 &module_path,
169 class_name.as_deref(),
170 &gem_name,
171 options_type.as_deref(),
172 enum_fields,
173 result_is_simple,
174 e2e_config,
175 has_file_fixtures || has_http_fixtures,
176 &config.adapters,
177 );
178 files.push(GeneratedFile {
179 path: spec_base.join(filename),
180 content,
181 generated_header: true,
182 });
183 }
184
185 Ok(files)
186 }
187
188 fn language_name(&self) -> &'static str {
189 "ruby"
190 }
191}
192
193fn render_gemfile(
198 gem_name: &str,
199 gem_path: &str,
200 gem_version: &str,
201 dep_mode: crate::config::DependencyMode,
202) -> String {
203 let gem_line = match dep_mode {
204 crate::config::DependencyMode::Registry => format!("gem '{gem_name}', '{gem_version}'"),
205 crate::config::DependencyMode::Local => format!("gem '{gem_name}', path: '{gem_path}'"),
206 };
207 crate::template_env::render(
208 "ruby/Gemfile.jinja",
209 minijinja::context! {
210 gem_line => gem_line,
211 rspec => tv::gem::RSPEC_E2E,
212 rubocop => tv::gem::RUBOCOP_E2E,
213 rubocop_rspec => tv::gem::RUBOCOP_RSPEC_E2E,
214 faraday => tv::gem::FARADAY,
215 },
216 )
217}
218
219fn render_spec_helper(has_file_fixtures: bool, has_http_fixtures: bool, test_documents_path: &str) -> String {
220 let header = hash::header(CommentStyle::Hash);
221 let mut out = header;
222 out.push_str("# frozen_string_literal: true\n");
223
224 if has_file_fixtures {
225 let _ = writeln!(out);
226 let _ = writeln!(
227 out,
228 "# Change to the configured test-documents directory so that fixture file paths like"
229 );
230 let _ = writeln!(
231 out,
232 "# \"pdf/fake_memo.pdf\" resolve correctly when running rspec from e2e/ruby/."
233 );
234 let _ = writeln!(
235 out,
236 "# spec_helper.rb lives in e2e/ruby/spec/; the fixtures dir resolves three directories up."
237 );
238 let _ = writeln!(
239 out,
240 "_test_documents = File.expand_path('{test_documents_path}', __dir__)"
241 );
242 let _ = writeln!(out, "Dir.chdir(_test_documents) if Dir.exist?(_test_documents)");
243 }
244
245 if has_http_fixtures {
246 out.push_str(
247 r#"
248require 'json'
249require 'open3'
250
251# Spawn the mock-server binary and set MOCK_SERVER_URL for all tests.
252RSpec.configure do |config|
253 config.before(:suite) do
254 bin = File.expand_path('../../rust/target/release/mock-server', __dir__)
255 fixtures_dir = File.expand_path('../../../fixtures', __dir__)
256 unless File.exist?(bin)
257 warn "mock-server binary not found at #{bin} — run: cargo build --manifest-path e2e/rust/Cargo.toml --bin mock-server --release"
258 end
259 stdin, stdout, _stderr, _wait = Open3.popen3(bin, fixtures_dir)
260 # Read startup lines: MOCK_SERVER_URL= then optional MOCK_SERVERS=.
261 url = nil
262 8.times do
263 line = stdout.readline.strip rescue break
264 if line.start_with?('MOCK_SERVER_URL=')
265 url = line.split('=', 2).last
266 ENV['MOCK_SERVER_URL'] = url
267 elsif line.start_with?('MOCK_SERVERS=')
268 json_val = line.split('=', 2).last
269 ENV['MOCK_SERVERS'] = json_val
270 JSON.parse(json_val).each do |fid, furl|
271 ENV["MOCK_SERVER_#{fid.upcase}"] = furl
272 end
273 break
274 elsif url
275 break
276 end
277 end
278 # Drain stdout in background.
279 Thread.new { stdout.read }
280 # Store stdin so we can close it on teardown.
281 @_mock_server_stdin = stdin
282 end
283
284 config.after(:suite) do
285 @_mock_server_stdin&.close
286 end
287end
288"#,
289 );
290 }
291
292 out
293}
294
295fn render_rubocop_yaml() -> String {
296 crate::template_env::render("ruby/rubocop.yml.jinja", minijinja::context! {})
297}
298
299#[allow(clippy::too_many_arguments)]
300fn render_spec_file(
301 category: &str,
302 fixtures: &[&Fixture],
303 module_path: &str,
304 class_name: Option<&str>,
305 gem_name: &str,
306 options_type: Option<&str>,
307 enum_fields: &HashMap<String, String>,
308 result_is_simple: bool,
309 e2e_config: &E2eConfig,
310 needs_spec_helper: bool,
311 adapters: &[alef_core::config::extras::AdapterConfig],
312) -> String {
313 let client_factory = e2e_config
315 .call
316 .overrides
317 .get("ruby")
318 .and_then(|o| o.client_factory.as_deref());
319
320 let require_name = if module_path.is_empty() { gem_name } else { module_path };
322 let mut requires = vec![require_name.replace('-', "_"), "json".to_string()];
323
324 let has_http = fixtures.iter().any(|f| f.is_http_test());
325 if needs_spec_helper || has_http {
326 requires.push("spec_helper".to_string());
327 }
328
329 let ruby_module = ruby_module_name(module_path);
331 let call_receiver = class_name.map(|s| s.to_string()).unwrap_or_else(|| ruby_module.clone());
332
333 let has_array_contains = fixtures.iter().any(|fixture| {
335 let cc = e2e_config.resolve_call_for_fixture(
336 fixture.call.as_deref(),
337 &fixture.id,
338 &fixture.resolved_category(),
339 &fixture.tags,
340 &fixture.input,
341 );
342 let fr = FieldResolver::new(
343 e2e_config.effective_fields(cc),
344 e2e_config.effective_fields_optional(cc),
345 e2e_config.effective_result_fields(cc),
346 e2e_config.effective_fields_array(cc),
347 &std::collections::HashSet::new(),
348 );
349 fixture.assertions.iter().any(|a| {
350 matches!(a.assertion_type.as_str(), "contains" | "contains_all" | "not_contains")
351 && a.field
352 .as_deref()
353 .is_some_and(|f| !f.is_empty() && fr.is_array(fr.resolve(f)))
354 })
355 });
356
357 let mut examples = Vec::new();
359 for fixture in fixtures {
360 if fixture.http.is_some() {
361 let mut out = String::new();
363 render_http_example(&mut out, fixture);
364 examples.push(out);
365 } else {
366 let fixture_call = e2e_config.resolve_call_for_fixture(
368 fixture.call.as_deref(),
369 &fixture.id,
370 &fixture.resolved_category(),
371 &fixture.tags,
372 &fixture.input,
373 );
374 let fixture_call_resolver = FieldResolver::new(
376 e2e_config.effective_fields(fixture_call),
377 e2e_config.effective_fields_optional(fixture_call),
378 e2e_config.effective_result_fields(fixture_call),
379 e2e_config.effective_fields_array(fixture_call),
380 &std::collections::HashSet::new(),
381 );
382 let field_resolver = &fixture_call_resolver;
383 let fixture_call_overrides = fixture_call.overrides.get("ruby");
384 let raw_function_name = fixture_call_overrides
385 .and_then(|o| o.function.as_ref())
386 .cloned()
387 .unwrap_or_else(|| fixture_call.function.clone());
388
389 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
390 let has_not_error = fixture.assertions.iter().any(|a| a.assertion_type == "not_error");
391 let has_usable = has_usable_assertion(fixture, field_resolver, result_is_simple);
392 let is_streaming = raw_function_name == "chat_stream";
393
394 if !expects_error && !has_usable && !has_not_error && !is_streaming && fixture.assertions.is_empty() {
399 let test_name = sanitize_ident(&fixture.id);
400 let description = fixture.description.replace('\'', "\\'");
401 let mut out = String::new();
402 out.push_str(&format!(" it '{test_name}: {description}' do\n"));
403 out.push_str(" skip 'Fixture has no assertions to validate'\n");
404 out.push_str(" end\n");
405 examples.push(out);
406 } else {
407 let fixture_function_name = if is_streaming {
411 raw_function_name
412 } else if fixture_call.r#async && !raw_function_name.ends_with("_async") {
413 format!("{raw_function_name}_async")
414 } else {
415 raw_function_name
416 };
417 let fixture_result_var = &fixture_call.result_var;
418 let fixture_args = &fixture_call.args;
419 let fixture_client_factory = fixture_call_overrides
420 .and_then(|o| o.client_factory.as_deref())
421 .or(client_factory);
422 let fixture_options_type = fixture_call_overrides
423 .and_then(|o| o.options_type.as_deref())
424 .or(options_type);
425
426 let fixture_extra_args: Vec<String> =
427 fixture_call_overrides.map(|o| o.extra_args.clone()).unwrap_or_default();
428 let fixture_result_is_simple =
431 fixture_call.result_is_simple || fixture_call_overrides.is_some_and(|o| o.result_is_simple);
432 let fixture_enum_fields: &HashMap<String, String> =
436 fixture_call_overrides.map(|o| &o.enum_fields).unwrap_or(enum_fields);
437 let adapter_req_type_owned: Option<String> = adapters
438 .iter()
439 .find(|a| a.name == fixture_call.function.as_str())
440 .and_then(|a| a.request_type.as_deref())
441 .map(|rt| rt.rsplit("::").next().unwrap_or(rt).to_string());
442 let example = if is_streaming {
443 render_chat_stream_example(
444 fixture,
445 &fixture_function_name,
446 &call_receiver,
447 &ruby_module,
448 fixture_args,
449 fixture_options_type,
450 fixture_enum_fields,
451 e2e_config,
452 fixture_client_factory,
453 &fixture_extra_args,
454 adapter_req_type_owned.as_deref(),
455 )
456 } else {
457 render_example(
458 fixture,
459 &fixture_function_name,
460 &call_receiver,
461 &ruby_module,
462 fixture_result_var,
463 fixture_args,
464 field_resolver,
465 fixture_options_type,
466 fixture_enum_fields,
467 e2e_config.effective_fields_enum(fixture_call),
468 fixture_result_is_simple,
469 fixture_call.returns_void,
470 e2e_config,
471 fixture_client_factory,
472 &fixture_extra_args,
473 adapter_req_type_owned.as_deref(),
474 )
475 };
476 examples.push(example);
477 }
478 }
479 }
480
481 let header = hash::header(CommentStyle::Hash);
482 crate::template_env::render(
483 "ruby/test_file.jinja",
484 minijinja::context! {
485 category => category,
486 requires => requires,
487 has_array_contains => has_array_contains,
488 has_http => has_http,
489 examples => examples,
490 header => header,
491 },
492 )
493}
494
495fn has_usable_assertion(fixture: &Fixture, field_resolver: &FieldResolver, result_is_simple: bool) -> bool {
498 fixture.assertions.iter().any(|a| {
499 if a.assertion_type == "not_error" || a.assertion_type == "error" {
501 return false;
502 }
503 if let Some(f) = &a.field {
505 if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
506 return false;
507 }
508 if result_is_simple {
510 let f_lower = f.to_lowercase();
511 if !f.is_empty()
512 && f_lower != "content"
513 && (f_lower.starts_with("metadata")
514 || f_lower.starts_with("document")
515 || f_lower.starts_with("structure"))
516 {
517 return false;
518 }
519 }
520 }
521 true
522 })
523}
524
525struct RubyTestClientRenderer;
533
534impl client::TestClientRenderer for RubyTestClientRenderer {
535 fn language_name(&self) -> &'static str {
536 "ruby"
537 }
538
539 fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
545 let escaped_description = description.replace('\'', "\\'");
546 let rendered = crate::template_env::render(
547 "ruby/http_test.jinja",
548 minijinja::context! {
549 fn_name => fn_name,
550 description => escaped_description,
551 skip_reason => skip_reason,
552 },
553 );
554 out.push_str(&rendered);
555 }
556
557 fn render_test_close(&self, out: &mut String) {
559 let rendered = crate::template_env::render("ruby/http_test_close.jinja", minijinja::context! {});
560 out.push_str(&rendered);
561 }
562
563 fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
565 let method = ctx.method.to_uppercase();
566 let method_class = http_method_class(&method);
567
568 let has_body = ctx
569 .body
570 .is_some_and(|b| !matches!(b, serde_json::Value::String(s) if s.is_empty()));
571
572 let ruby_body = if has_body {
573 json_to_ruby(ctx.body.unwrap())
574 } else {
575 String::new()
576 };
577
578 let headers: Vec<minijinja::Value> = ctx
579 .headers
580 .iter()
581 .filter(|(k, _)| {
582 !(has_body && k.to_lowercase() == "content-type")
584 })
585 .map(|(k, v)| {
586 minijinja::context! {
587 key_literal => ruby_string_literal(k),
588 value_literal => ruby_string_literal(v),
589 }
590 })
591 .collect();
592
593 let rendered = crate::template_env::render(
594 "ruby/http_request.jinja",
595 minijinja::context! {
596 method_class => method_class,
597 path => ctx.path,
598 has_body => has_body,
599 ruby_body => ruby_body,
600 headers => headers,
601 response_var => ctx.response_var,
602 },
603 );
604 out.push_str(&rendered);
605 }
606
607 fn render_assert_status(&self, out: &mut String, response_var: &str, status: u16) {
612 out.push_str(&format!(" expect({response_var}.code.to_i).to eq({status})\n"));
613 }
614
615 fn render_assert_header(&self, out: &mut String, response_var: &str, name: &str, expected: &str) {
619 let header_key = name.to_lowercase();
620 let header_expr = format!("{response_var}[{}]", ruby_string_literal(&header_key));
621 let assertion = match expected {
622 "<<present>>" => {
623 format!(" expect({header_expr}).not_to be_nil\n")
624 }
625 "<<absent>>" => {
626 format!(" expect({header_expr}).to be_nil\n")
627 }
628 "<<uuid>>" => {
629 format!(
630 " expect({header_expr}).to match(/\\A[0-9a-f]{{8}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{12}}\\z/i)\n"
631 )
632 }
633 literal => {
634 let ruby_val = ruby_string_literal(literal);
635 format!(" expect({header_expr}).to eq({ruby_val})\n")
636 }
637 };
638 out.push_str(&assertion);
639 }
640
641 fn render_assert_json_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
646 match expected {
647 serde_json::Value::String(s) => {
648 let ruby_val = ruby_string_literal(s);
649 out.push_str(&format!(" expect({response_var}.body).to eq({ruby_val})\n"));
650 }
651 _ => {
652 let ruby_val = json_to_ruby(expected);
653 out.push_str(&format!(
654 " _body = {response_var}.body && !{response_var}.body.empty? ? JSON.parse({response_var}.body) : nil\n"
655 ));
656 out.push_str(&format!(" expect(_body).to eq({ruby_val})\n"));
657 }
658 }
659 }
660
661 fn render_assert_partial_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
663 if let Some(obj) = expected.as_object() {
664 out.push_str(&format!(" _body = JSON.parse({response_var}.body)\n"));
665 for (key, val) in obj {
666 let ruby_key = ruby_string_literal(key);
667 let ruby_val = json_to_ruby(val);
668 out.push_str(&format!(" expect(_body[{ruby_key}]).to eq({ruby_val})\n"));
669 }
670 }
671 }
672
673 fn render_assert_validation_errors(
676 &self,
677 out: &mut String,
678 response_var: &str,
679 errors: &[ValidationErrorExpectation],
680 ) {
681 for err in errors {
682 let msg_lit = ruby_string_literal(&err.msg);
683 out.push_str(&format!(" _body = JSON.parse({response_var}.body)\n"));
684 out.push_str(" _errors = _body['errors'] || []\n");
685 out.push_str(&format!(
686 " expect(_errors.map {{ |e| e['msg'] }}).to include({msg_lit})\n"
687 ));
688 }
689 }
690}
691
692fn render_http_example(out: &mut String, fixture: &Fixture) {
698 if fixture
702 .http
703 .as_ref()
704 .is_some_and(|h| h.expected_response.status_code == 101)
705 {
706 if let Some(http) = fixture.http.as_ref() {
707 let description = fixture.description.replace('\'', "\\'");
708 let method = http.request.method.to_uppercase();
709 let path = &http.request.path;
710 let rendered = crate::template_env::render(
711 "ruby/http_101_skip.jinja",
712 minijinja::context! {
713 method => method,
714 path => path,
715 description => description,
716 },
717 );
718 out.push_str(&rendered);
719 }
720 return;
721 }
722
723 client::http_call::render_http_test(out, &RubyTestClientRenderer, fixture);
724}
725
726fn http_method_class(method: &str) -> String {
729 let mut chars = method.chars();
730 match chars.next() {
731 None => String::new(),
732 Some(first) => first.to_uppercase().collect::<String>() + &chars.as_str().to_lowercase(),
733 }
734}
735
736#[allow(clippy::too_many_arguments)]
748fn render_chat_stream_example(
749 fixture: &Fixture,
750 function_name: &str,
751 call_receiver: &str,
752 module_name: &str,
753 args: &[crate::config::ArgMapping],
754 options_type: Option<&str>,
755 enum_fields: &HashMap<String, String>,
756 e2e_config: &E2eConfig,
757 client_factory: Option<&str>,
758 extra_args: &[String],
759 adapter_request_type: Option<&str>,
760) -> String {
761 let test_name = sanitize_ident(&fixture.id);
762 let description = fixture.description.replace('\'', "\\'");
763 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
764 let fixture_id = fixture.id.clone();
765
766 let (mut setup_lines, args_str) = build_args_and_setup(
767 &fixture.input,
768 args,
769 call_receiver,
770 module_name,
771 options_type,
772 enum_fields,
773 false,
774 fixture,
775 adapter_request_type,
776 );
777
778 let mut final_args = args_str;
779 if !extra_args.is_empty() {
780 let extra_str = extra_args.join(", ");
781 if final_args.is_empty() {
782 final_args = extra_str;
783 } else {
784 final_args = format!("{final_args}, {extra_str}");
785 }
786 }
787
788 let mut needs_finish_reason = false;
791 let mut needs_tool_calls_json = false;
792 let mut needs_tool_calls_0_function_name = false;
793 let mut needs_total_tokens = false;
794 for a in &fixture.assertions {
795 if let Some(f) = a.field.as_deref() {
796 match f {
797 "finish_reason" => needs_finish_reason = true,
798 "tool_calls" => needs_tool_calls_json = true,
799 "tool_calls[0].function.name" => needs_tool_calls_0_function_name = true,
800 "usage.total_tokens" => needs_total_tokens = true,
801 _ => {}
802 }
803 }
804 }
805
806 let mut out = String::new();
807 out.push_str(&format!(" it '{test_name}: {description}' do\n"));
808
809 let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
811 let api_key_var = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
812 if let Some(cf) = client_factory {
813 if has_mock && let Some(key_var) = api_key_var {
814 let mock_url_expr = format!("\"#{{ENV['MOCK_SERVER_URL']}}/fixtures/{fixture_id}\"");
815 out.push_str(&format!(" api_key = ENV['{key_var}']\n"));
816 out.push_str(" if api_key && !api_key.empty?\n");
817 out.push_str(&format!(
818 " warn \"{test_name}: using real API ({key_var} is set)\"\n"
819 ));
820 out.push_str(&format!(" client = {call_receiver}.{cf}(api_key)\n"));
821 out.push_str(" else\n");
822 out.push_str(&format!(
823 " warn \"{test_name}: using mock server ({key_var} not set)\"\n"
824 ));
825 out.push_str(&format!(" mock_url = {mock_url_expr}\n"));
826 out.push_str(&format!(" client = {call_receiver}.{cf}('test-key', mock_url)\n"));
827 out.push_str(" end\n");
828 } else if has_mock {
829 let base_url_expr = if fixture.has_host_root_route() {
830 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
831 format!("(ENV.fetch('{env_key}', nil) || ENV.fetch('MOCK_SERVER_URL') + '/fixtures/{fixture_id}')")
832 } else {
833 format!("ENV.fetch('MOCK_SERVER_URL') + '/fixtures/{fixture_id}'")
834 };
835 out.push_str(&format!(
836 " client = {call_receiver}.{cf}('test-key', {base_url_expr})\n"
837 ));
838 } else if let Some(key_var) = api_key_var {
839 out.push_str(&format!(" api_key = ENV['{key_var}']\n"));
840 out.push_str(&format!(" skip '{key_var} not set' unless api_key\n"));
841 out.push_str(&format!(" client = {call_receiver}.{cf}(api_key)\n"));
842 } else {
843 out.push_str(&format!(" client = {call_receiver}.{cf}('test-key')\n"));
844 }
845 }
846
847 if let Some(visitor_spec) = &fixture.visitor {
849 let _ = build_ruby_visitor(&mut setup_lines, visitor_spec);
850 }
851 for line in &setup_lines {
852 out.push_str(&format!(" {line}\n"));
853 }
854
855 let call_expr = if client_factory.is_some() {
856 format!("client.{function_name}({final_args})")
857 } else {
858 format!("{call_receiver}.{function_name}({final_args})")
859 };
860
861 if expects_error {
862 out.push_str(&format!(" expect {{ {call_expr} {{ |_chunk| }} }}.to raise_error\n"));
863 out.push_str(" end\n");
864 return out;
865 }
866
867 out.push_str(" chunks = []\n");
869 out.push_str(" stream_content = ''.dup\n");
870 out.push_str(" stream_complete = false\n");
871 if needs_finish_reason {
872 out.push_str(" last_finish_reason = nil\n");
873 }
874 if needs_tool_calls_json {
875 out.push_str(" tool_calls_json = nil\n");
876 }
877 if needs_tool_calls_0_function_name {
878 out.push_str(" tool_calls_0_function_name = nil\n");
879 }
880 if needs_total_tokens {
881 out.push_str(" total_tokens = nil\n");
882 }
883 out.push_str(&format!(" {call_expr} do |chunk|\n"));
884 out.push_str(" chunks << chunk\n");
885 out.push_str(" choice = chunk.choices && chunk.choices[0]\n");
886 out.push_str(" if choice\n");
887 out.push_str(" delta = choice.delta\n");
888 out.push_str(" if delta && delta.content\n");
889 out.push_str(" stream_content << delta.content\n");
890 out.push_str(" end\n");
891 if needs_finish_reason {
892 out.push_str(" if choice.finish_reason\n");
893 out.push_str(" last_finish_reason = choice.finish_reason.to_s\n");
894 out.push_str(" end\n");
895 }
896 if needs_tool_calls_json || needs_tool_calls_0_function_name {
897 out.push_str(" tcs = delta && delta.tool_calls\n");
898 out.push_str(" if tcs && !tcs.empty?\n");
899 if needs_tool_calls_json {
900 out.push_str(
901 " tool_calls_json ||= tcs.map { |tc| { 'function' => { 'name' => (tc.function && tc.function.name rescue nil) } } }.to_json\n",
902 );
903 }
904 if needs_tool_calls_0_function_name {
905 out.push_str(
906 " tool_calls_0_function_name ||= (tcs[0].function && tcs[0].function.name rescue nil)\n",
907 );
908 }
909 out.push_str(" end\n");
910 }
911 out.push_str(" end\n");
912 if needs_total_tokens {
913 out.push_str(" if chunk.usage && chunk.usage.total_tokens\n");
914 out.push_str(" total_tokens = chunk.usage.total_tokens\n");
915 out.push_str(" end\n");
916 }
917 out.push_str(" end\n");
918 out.push_str(" stream_complete = true\n");
919
920 for assertion in &fixture.assertions {
922 emit_chat_stream_assertion(&mut out, assertion, e2e_config);
923 }
924
925 if !fixture
928 .assertions
929 .iter()
930 .any(|a| a.field.as_deref() == Some("stream_complete"))
931 {
932 out.push_str(" expect(stream_complete).to be(true)\n");
933 }
934
935 out.push_str(" end\n");
936 out
937}
938
939fn emit_chat_stream_assertion(out: &mut String, assertion: &Assertion, _e2e_config: &E2eConfig) {
944 let atype = assertion.assertion_type.as_str();
945 if atype == "not_error" || atype == "error" {
946 return;
947 }
948 let field = assertion.field.as_deref().unwrap_or("");
949
950 enum Kind {
951 Chunks,
952 Bool,
953 Str,
954 IntTokens,
955 Json,
956 Unsupported,
957 }
958
959 let (expr, kind) = match field {
960 "chunks" => ("chunks", Kind::Chunks),
961 "stream_content" => ("stream_content", Kind::Str),
962 "stream_complete" => ("stream_complete", Kind::Bool),
963 "no_chunks_after_done" => ("stream_complete", Kind::Bool),
964 "finish_reason" => ("last_finish_reason", Kind::Str),
965 "tool_calls" => ("tool_calls_json", Kind::Json),
966 "tool_calls[0].function.name" => ("tool_calls_0_function_name", Kind::Str),
967 "usage.total_tokens" => ("total_tokens", Kind::IntTokens),
968 _ => ("", Kind::Unsupported),
969 };
970
971 if matches!(kind, Kind::Unsupported) {
972 out.push_str(&format!(
973 " # skipped: streaming assertion on unsupported field '{field}'\n"
974 ));
975 return;
976 }
977
978 match (atype, &kind) {
979 ("count_min", Kind::Chunks) => {
980 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
981 out.push_str(&format!(" expect({expr}.length).to be >= {n}\n"));
982 }
983 }
984 ("count_equals", Kind::Chunks) => {
985 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
986 out.push_str(&format!(" expect({expr}.length).to eq({n})\n"));
987 }
988 }
989 ("equals", Kind::Str) => {
990 if let Some(val) = &assertion.value {
991 let rb_val = json_to_ruby(val);
992 out.push_str(&format!(" expect({expr}.to_s.strip).to eq({rb_val}.strip)\n"));
996 }
997 }
998 ("contains", Kind::Str) => {
999 if let Some(val) = &assertion.value {
1000 let rb_val = json_to_ruby(val);
1001 out.push_str(&format!(" expect({expr}.to_s).to include({rb_val})\n"));
1002 }
1003 }
1004 ("not_empty", Kind::Str) => {
1005 out.push_str(&format!(" expect({expr}.to_s).not_to be_empty\n"));
1006 }
1007 ("not_empty", Kind::Json) => {
1008 out.push_str(&format!(" expect({expr}).not_to be_nil\n"));
1009 }
1010 ("is_empty", Kind::Str) => {
1011 out.push_str(&format!(" expect({expr}.to_s).to be_empty\n"));
1012 }
1013 ("is_true", Kind::Bool) => {
1014 out.push_str(&format!(" expect({expr}).to be(true)\n"));
1015 }
1016 ("is_false", Kind::Bool) => {
1017 out.push_str(&format!(" expect({expr}).to be(false)\n"));
1018 }
1019 ("greater_than_or_equal", Kind::IntTokens) => {
1020 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1021 out.push_str(&format!(" expect({expr}).to be >= {n}\n"));
1022 }
1023 }
1024 ("equals", Kind::IntTokens) => {
1025 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1026 out.push_str(&format!(" expect({expr}).to eq({n})\n"));
1027 }
1028 }
1029 _ => {
1030 out.push_str(&format!(
1031 " # skipped: streaming assertion '{atype}' on field '{field}' not supported\n"
1032 ));
1033 }
1034 }
1035}
1036
1037#[allow(clippy::too_many_arguments)]
1042fn render_example(
1043 fixture: &Fixture,
1044 function_name: &str,
1045 call_receiver: &str,
1046 module_name: &str,
1047 result_var: &str,
1048 args: &[crate::config::ArgMapping],
1049 field_resolver: &FieldResolver,
1050 options_type: Option<&str>,
1051 enum_fields: &HashMap<String, String>,
1052 fields_enum: &HashSet<String>,
1053 result_is_simple: bool,
1054 returns_void: bool,
1055 e2e_config: &E2eConfig,
1056 client_factory: Option<&str>,
1057 extra_args: &[String],
1058 adapter_request_type: Option<&str>,
1059) -> String {
1060 let test_name = sanitize_ident(&fixture.id);
1061 let description = fixture.description.replace('\'', "\\'");
1062 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
1063 let fixture_id = fixture.id.clone();
1064
1065 let (mut setup_lines, args_str) = build_args_and_setup(
1066 &fixture.input,
1067 args,
1068 call_receiver,
1069 module_name,
1070 options_type,
1071 enum_fields,
1072 result_is_simple,
1073 fixture,
1074 adapter_request_type,
1075 );
1076
1077 let mut visitor_arg = String::new();
1079 if let Some(visitor_spec) = &fixture.visitor {
1080 visitor_arg = build_ruby_visitor(&mut setup_lines, visitor_spec);
1081 }
1082
1083 let mut final_args = if visitor_arg.is_empty() {
1084 args_str
1085 } else if args_str.is_empty() {
1086 visitor_arg
1087 } else {
1088 format!("{args_str}, {visitor_arg}")
1089 };
1090
1091 if !extra_args.is_empty() {
1093 let extra_str = extra_args.join(", ");
1094 if final_args.is_empty() {
1095 final_args = extra_str;
1096 } else {
1097 final_args = format!("{final_args}, {extra_str}");
1098 }
1099 }
1100
1101 let call_expr = if client_factory.is_some() {
1103 format!("client.{function_name}({final_args})")
1104 } else {
1105 format!("{call_receiver}.{function_name}({final_args})")
1106 };
1107
1108 let has_usable = has_usable_assertion(fixture, field_resolver, result_is_simple);
1110
1111 let mut assertions_rendered = String::new();
1113 for assertion in &fixture.assertions {
1114 render_assertion(
1115 &mut assertions_rendered,
1116 assertion,
1117 result_var,
1118 field_resolver,
1119 result_is_simple,
1120 e2e_config,
1121 fields_enum,
1122 enum_fields,
1123 );
1124 }
1125
1126 let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
1127 let api_key_var = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
1128 let has_mock_and_key = has_mock && api_key_var.is_some();
1129 let has_not_error = fixture.assertions.iter().any(|a| a.assertion_type == "not_error");
1130 let is_only_not_error = has_not_error && !has_usable && !expects_error;
1131
1132 let is_clear_op = function_name.ends_with("_clear");
1134 let post_clear_list_call = if is_clear_op {
1135 let list_fn = function_name.replace("_clear", "_list");
1136 format!("{}.{}()", call_receiver, list_fn)
1137 } else {
1138 String::new()
1139 };
1140
1141 crate::template_env::render(
1142 "ruby/test_function.jinja",
1143 minijinja::context! {
1144 test_name => test_name,
1145 description => description,
1146 expects_error => expects_error,
1147 setup_lines => setup_lines,
1148 call_expr => call_expr,
1149 result_var => result_var,
1150 assertions_rendered => assertions_rendered,
1151 has_usable => has_usable,
1152 returns_void => returns_void,
1153 client_factory => client_factory,
1154 fixture_id => fixture_id,
1155 call_receiver => call_receiver,
1156 has_mock => has_mock,
1157 api_key_var => api_key_var,
1158 has_mock_and_key => has_mock_and_key,
1159 is_only_not_error => is_only_not_error,
1160 is_clear_op => is_clear_op,
1161 post_clear_list_call => post_clear_list_call,
1162 },
1163 )
1164}
1165
1166fn emit_ruby_batch_item_array(arr: &serde_json::Value, elem_type: &str, module_name: &str) -> String {
1171 if let Some(items) = arr.as_array() {
1172 let item_strs: Vec<String> = items
1173 .iter()
1174 .filter_map(|item| {
1175 if let Some(obj) = item.as_object() {
1176 match elem_type {
1177 "BatchBytesItem" => {
1178 let content = obj.get("content").and_then(|v| v.as_array());
1179 let mime_type = obj.get("mime_type").and_then(|v| v.as_str()).unwrap_or("text/plain");
1180 let config = obj.get("config");
1181 let content_code = if let Some(arr) = content {
1182 let bytes: Vec<String> =
1183 arr.iter().filter_map(|v| v.as_u64().map(|n| n.to_string())).collect();
1184 format!("[{}]", bytes.join(", "))
1186 } else {
1187 "[]".to_string()
1188 };
1189 let config_arg = if let Some(cfg) = config {
1190 if cfg.is_null() {
1191 "nil".to_string()
1192 } else {
1193 json_to_ruby(cfg)
1194 }
1195 } else {
1196 "nil".to_string()
1197 };
1198 Some(format!(
1199 "{}::{}.new(content: {}, mime_type: \"{}\", config: {})",
1200 module_name, elem_type, content_code, mime_type, config_arg
1201 ))
1202 }
1203 "BatchFileItem" => {
1204 let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
1205 let config = obj.get("config");
1206 let config_arg = if let Some(cfg) = config {
1207 if cfg.is_null() {
1208 "nil".to_string()
1209 } else {
1210 json_to_ruby(cfg)
1211 }
1212 } else {
1213 "nil".to_string()
1214 };
1215 Some(format!(
1216 "{}::{}.new(path: \"{}\", config: {})",
1217 module_name, elem_type, path, config_arg
1218 ))
1219 }
1220 _ => {
1221 Some(json_to_ruby(&serde_json::Value::Object(obj.clone())))
1224 }
1225 }
1226 } else {
1227 None
1228 }
1229 })
1230 .collect();
1231 format!("[{}]", item_strs.join(", "))
1232 } else {
1233 "[]".to_string()
1234 }
1235}
1236
1237#[allow(clippy::too_many_arguments)]
1238fn build_args_and_setup(
1239 input: &serde_json::Value,
1240 args: &[crate::config::ArgMapping],
1241 call_receiver: &str,
1242 module_name: &str,
1243 options_type: Option<&str>,
1244 enum_fields: &HashMap<String, String>,
1245 result_is_simple: bool,
1246 fixture: &crate::fixture::Fixture,
1247 adapter_request_type: Option<&str>,
1248) -> (Vec<String>, String) {
1249 let fixture_id = &fixture.id;
1250 if args.is_empty() {
1251 return (Vec::new(), String::new());
1255 }
1256
1257 let mut setup_lines: Vec<String> = Vec::new();
1258 let mut parts: Vec<String> = Vec::new();
1259 let mut skipped_optional_count: usize = 0;
1262
1263 for arg in args {
1264 if arg.arg_type == "mock_url" {
1265 for _ in 0..skipped_optional_count {
1267 parts.push("nil".to_string());
1268 }
1269 skipped_optional_count = 0;
1270 if fixture.has_host_root_route() {
1271 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1272 setup_lines.push(format!(
1273 "{} = ENV.fetch('{env_key}', nil) || \"#{{ENV.fetch('MOCK_SERVER_URL')}}/fixtures/{fixture_id}\"",
1274 arg.name,
1275 ));
1276 } else {
1277 setup_lines.push(format!(
1278 "{} = \"#{{ENV.fetch('MOCK_SERVER_URL')}}/fixtures/{fixture_id}\"",
1279 arg.name,
1280 ));
1281 }
1282 if let Some(req_type) = adapter_request_type {
1283 let req_var = format!("{}_req", arg.name);
1284 let mod_qualifier = ruby_module_name(module_name);
1286 setup_lines.push(format!(
1287 "{req_var} = {mod_qualifier}::{req_type}.new(url: {})",
1288 arg.name
1289 ));
1290 parts.push(req_var);
1291 } else {
1292 parts.push(arg.name.clone());
1293 }
1294 continue;
1295 }
1296
1297 if arg.arg_type == "mock_url_list" {
1298 for _ in 0..skipped_optional_count {
1306 parts.push("nil".to_string());
1307 }
1308 skipped_optional_count = 0;
1309 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1310 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1311 let val = input.get(field).unwrap_or(&serde_json::Value::Null);
1312 let paths: Vec<String> = if let Some(arr) = val.as_array() {
1313 arr.iter().filter_map(|v| v.as_str().map(ruby_string_literal)).collect()
1314 } else {
1315 Vec::new()
1316 };
1317 let paths_literal = paths.join(", ");
1318 let name = &arg.name;
1319 setup_lines.push(format!(
1320 "{name}_base = ENV.fetch('{env_key}', nil) || \"#{{ENV.fetch('MOCK_SERVER_URL')}}/fixtures/{fixture_id}\""
1321 ));
1322 setup_lines.push(format!(
1323 "{name} = [{paths_literal}].map {{ |p| p.start_with?('http') ? p : \"#{{{name}_base}}#{{p}}\" }}"
1324 ));
1325 parts.push(name.clone());
1326 continue;
1327 }
1328
1329 if arg.arg_type == "bytes" {
1331 for _ in 0..skipped_optional_count {
1333 parts.push("nil".to_string());
1334 }
1335 skipped_optional_count = 0;
1336 let resolved = resolve_field(input, &arg.field);
1337 if let Some(s) = resolved.as_str() {
1338 if is_file_path(s) {
1339 setup_lines.push(format!("{} = File.read(\"{}\").bytes", arg.name, s));
1341 } else if is_base64(s) {
1342 setup_lines.push(format!("{} = Base64.decode64(\"{}\").bytes", arg.name, s));
1344 } else {
1345 let escaped = ruby_string_literal(s);
1347 setup_lines.push(format!("{} = {}.b.bytes", arg.name, escaped));
1348 }
1349 parts.push(arg.name.clone());
1350 } else {
1351 parts.push("nil".to_string());
1352 }
1353 continue;
1354 }
1355
1356 if arg.arg_type == "file_path" {
1358 for _ in 0..skipped_optional_count {
1360 parts.push("nil".to_string());
1361 }
1362 skipped_optional_count = 0;
1363 let resolved = resolve_field(input, &arg.field);
1364 if let Some(s) = resolved.as_str() {
1365 let escaped = ruby_string_literal(s);
1366 parts.push(escaped);
1367 } else if arg.optional {
1368 skipped_optional_count += 1;
1369 continue;
1370 } else {
1371 parts.push("''".to_string());
1372 }
1373 continue;
1374 }
1375
1376 if arg.arg_type == "handle" {
1377 for _ in 0..skipped_optional_count {
1379 parts.push("nil".to_string());
1380 }
1381 skipped_optional_count = 0;
1382 let constructor_name = format!("create_{}", arg.name.to_snake_case());
1384 let config_value = resolve_field(input, &arg.field);
1385 if config_value.is_null()
1386 || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
1387 {
1388 setup_lines.push(format!("{} = {call_receiver}.{constructor_name}(nil)", arg.name,));
1389 } else {
1390 let literal = json_to_ruby(config_value);
1391 let name = &arg.name;
1392 setup_lines.push(format!("{name}_config = {literal}"));
1393 setup_lines.push(format!(
1394 "{} = {call_receiver}.{constructor_name}({name}_config.to_json)",
1395 arg.name,
1396 name = name,
1397 ));
1398 }
1399 parts.push(arg.name.clone());
1400 continue;
1401 }
1402
1403 let resolved = resolve_field(input, &arg.field);
1404 let val = if resolved.is_null() { None } else { Some(resolved) };
1405 match val {
1406 None | Some(serde_json::Value::Null) if arg.optional => {
1407 skipped_optional_count += 1;
1409 continue;
1410 }
1411 None | Some(serde_json::Value::Null) => {
1412 for _ in 0..skipped_optional_count {
1414 parts.push("nil".to_string());
1415 }
1416 skipped_optional_count = 0;
1417 let default_val = match arg.arg_type.as_str() {
1418 "string" => "''".to_string(),
1419 "int" | "integer" => "0".to_string(),
1420 "float" | "number" => "0.0".to_string(),
1421 "bool" | "boolean" => "false".to_string(),
1422 _ => "nil".to_string(),
1423 };
1424 parts.push(default_val);
1425 }
1426 Some(v) => {
1427 for _ in 0..skipped_optional_count {
1429 parts.push("nil".to_string());
1430 }
1431 skipped_optional_count = 0;
1432 if arg.arg_type == "json_object" && !v.is_null() {
1435 if let Some(elem_type) = &arg.element_type {
1437 if v.is_array() {
1438 if elem_type == "BatchBytesItem" || elem_type == "BatchFileItem" {
1439 parts.push(emit_ruby_batch_item_array(v, elem_type, module_name));
1440 } else {
1441 if let Some(arr) = v.as_array() {
1443 let items: Vec<String> = arr
1444 .iter()
1445 .filter_map(|item| {
1446 item.as_object()
1447 .map(|obj| json_to_ruby(&serde_json::Value::Object(obj.clone())))
1448 })
1449 .collect();
1450 parts.push(format!("[{}]", items.join(", ")));
1451 } else {
1452 parts.push("[]".to_string());
1453 }
1454 }
1455 continue;
1456 }
1457 }
1458 if let (Some(opts_type), Some(obj)) = (options_type, v.as_object()) {
1460 let kwargs: Vec<String> = obj
1461 .iter()
1462 .filter_map(|(k, vv)| {
1463 if let Some(s) = vv.as_str() {
1465 if s.is_empty() {
1466 return None; }
1468 if enum_fields.contains_key(k) {
1470 let snake_key = k.to_snake_case();
1471 let snake_val = s.to_snake_case();
1472 return Some(format!("{snake_key}: '{snake_val}'"));
1473 }
1474 }
1475 let snake_key = k.to_snake_case();
1476 let rb_val = json_to_ruby(vv);
1477 Some(format!("{snake_key}: {rb_val}"))
1478 })
1479 .collect();
1480 if result_is_simple {
1481 parts.push(format!("{{{}}}", kwargs.join(", ")));
1482 } else {
1483 parts.push(format!("{opts_type}.new({})", kwargs.join(", ")));
1484 }
1485 continue;
1486 }
1487 }
1488 parts.push(json_to_ruby(v));
1489 }
1490 }
1491 }
1492
1493 (setup_lines, parts.join(", "))
1494}
1495
1496#[allow(clippy::too_many_arguments)]
1497fn render_assertion(
1498 out: &mut String,
1499 assertion: &Assertion,
1500 result_var: &str,
1501 field_resolver: &FieldResolver,
1502 result_is_simple: bool,
1503 e2e_config: &E2eConfig,
1504 fields_enum: &HashSet<String>,
1505 per_call_enum_fields: &HashMap<String, String>,
1506) {
1507 if result_is_simple {
1511 if let Some(f) = &assertion.field {
1512 if !f.is_empty() {
1513 match assertion.assertion_type.as_str() {
1514 "not_empty" => {
1515 out.push_str(&format!(" expect({result_var}.to_s).not_to be_empty\n"));
1516 return;
1517 }
1518 "is_empty" => {
1519 out.push_str(&format!(" expect({result_var}.to_s).to be_empty\n"));
1520 return;
1521 }
1522 "count_equals" => {
1523 if let Some(val) = &assertion.value {
1524 let rb_val = json_to_ruby(val);
1525 out.push_str(&format!(" expect({result_var}.length).to eq({rb_val})\n"));
1526 }
1527 return;
1528 }
1529 "count_min" => {
1530 if let Some(val) = &assertion.value {
1531 let rb_val = json_to_ruby(val);
1532 out.push_str(&format!(" expect({result_var}.length).to be >= {rb_val}\n"));
1533 }
1534 return;
1535 }
1536 _ => {
1537 out.push_str(&format!(
1538 " # skipped: field '{f}' not applicable for simple result type\n"
1539 ));
1540 return;
1541 }
1542 }
1543 }
1544 }
1545 }
1546 if let Some(f) = &assertion.field {
1549 if f.contains("metadata.format.") && f.contains(".") {
1552 out.push_str(&format!(
1553 " # skipped: enum variant accessor '{f}' not available on Ruby (serialized to Hash)\n"
1554 ));
1555 return;
1556 }
1557
1558 if f == "metadata.format" {
1561 out.push_str(" # skipped: metadata.format enum field serialization differs in Ruby\n");
1562 return;
1563 }
1564
1565 match f.as_str() {
1566 "chunks_have_content" => {
1567 let pred = format!("({result_var}.chunks || []).all? {{ |c| c.content && !c.content.empty? }}");
1568 match assertion.assertion_type.as_str() {
1569 "is_true" => {
1570 out.push_str(&format!(" expect({pred}).to be(true)\n"));
1571 }
1572 "is_false" => {
1573 out.push_str(&format!(" expect({pred}).to be(false)\n"));
1574 }
1575 _ => {
1576 out.push_str(&format!(
1577 " # skipped: unsupported assertion type on synthetic field '{f}'\n"
1578 ));
1579 }
1580 }
1581 return;
1582 }
1583 "chunks_have_heading_context" | "first_chunk_starts_with_heading" => {
1584 out.push_str(&format!(
1585 " # skipped: synthetic field '{f}' not available on Ruby Chunk binding\n"
1586 ));
1587 return;
1588 }
1589 "chunks_have_embeddings" => {
1590 let pred =
1591 format!("({result_var}.chunks || []).all? {{ |c| !c.embedding.nil? && !c.embedding.empty? }}");
1592 match assertion.assertion_type.as_str() {
1593 "is_true" => {
1594 out.push_str(&format!(" expect({pred}).to be(true)\n"));
1595 }
1596 "is_false" => {
1597 out.push_str(&format!(" expect({pred}).to be(false)\n"));
1598 }
1599 _ => {
1600 out.push_str(&format!(
1601 " # skipped: unsupported assertion type on synthetic field '{f}'\n"
1602 ));
1603 }
1604 }
1605 return;
1606 }
1607 "embeddings" => {
1611 match assertion.assertion_type.as_str() {
1612 "count_equals" => {
1613 if let Some(val) = &assertion.value {
1614 let rb_val = json_to_ruby(val);
1615 out.push_str(&format!(" expect({result_var}.length).to eq({rb_val})\n"));
1616 }
1617 }
1618 "count_min" => {
1619 if let Some(val) = &assertion.value {
1620 let rb_val = json_to_ruby(val);
1621 out.push_str(&format!(" expect({result_var}.length).to be >= {rb_val}\n"));
1622 }
1623 }
1624 "not_empty" => {
1625 out.push_str(&format!(" expect({result_var}).not_to be_empty\n"));
1626 }
1627 "is_empty" => {
1628 out.push_str(&format!(" expect({result_var}).to be_empty\n"));
1629 }
1630 _ => {
1631 out.push_str(" # skipped: unsupported assertion type on synthetic field 'embeddings'\n");
1632 }
1633 }
1634 return;
1635 }
1636 "embedding_dimensions" => {
1637 let expr = format!("({result_var}.empty? ? 0 : {result_var}[0].length)");
1638 match assertion.assertion_type.as_str() {
1639 "equals" => {
1640 if let Some(val) = &assertion.value {
1641 let rb_val = json_to_ruby(val);
1642 out.push_str(&format!(" expect({expr}).to eq({rb_val})\n"));
1643 }
1644 }
1645 "greater_than" => {
1646 if let Some(val) = &assertion.value {
1647 let rb_val = json_to_ruby(val);
1648 out.push_str(&format!(" expect({expr}).to be > {rb_val}\n"));
1649 }
1650 }
1651 _ => {
1652 out.push_str(
1653 " # skipped: unsupported assertion type on synthetic field 'embedding_dimensions'\n",
1654 );
1655 }
1656 }
1657 return;
1658 }
1659 "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
1660 let pred = match f.as_str() {
1661 "embeddings_valid" => {
1662 format!("{result_var}.all? {{ |e| !e.empty? }}")
1663 }
1664 "embeddings_finite" => {
1665 format!("{result_var}.all? {{ |e| e.all? {{ |v| v.finite? }} }}")
1666 }
1667 "embeddings_non_zero" => {
1668 format!("{result_var}.all? {{ |e| e.any? {{ |v| v != 0.0 }} }}")
1669 }
1670 "embeddings_normalized" => {
1671 format!("{result_var}.all? {{ |e| n = e.sum {{ |v| v * v }}; (n - 1.0).abs < 1e-3 }}")
1672 }
1673 _ => unreachable!(),
1674 };
1675 match assertion.assertion_type.as_str() {
1676 "is_true" => {
1677 out.push_str(&format!(" expect({pred}).to be(true)\n"));
1678 }
1679 "is_false" => {
1680 out.push_str(&format!(" expect({pred}).to be(false)\n"));
1681 }
1682 _ => {
1683 out.push_str(&format!(
1684 " # skipped: unsupported assertion type on synthetic field '{f}'\n"
1685 ));
1686 }
1687 }
1688 return;
1689 }
1690 "keywords" | "keywords_count" => {
1693 out.push_str(&format!(
1694 " # skipped: field '{f}' not available on Ruby ExtractionResult\n"
1695 ));
1696 return;
1697 }
1698 _ => {}
1699 }
1700 }
1701
1702 if let Some(f) = &assertion.field {
1704 if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1705 out.push_str(&format!(" # skipped: field '{f}' not available on result type\n"));
1706 return;
1707 }
1708 }
1709
1710 if result_is_simple {
1712 if let Some(f) = &assertion.field {
1713 let f_lower = f.to_lowercase();
1714 if !f.is_empty()
1715 && f_lower != "content"
1716 && (f_lower.starts_with("metadata")
1717 || f_lower.starts_with("document")
1718 || f_lower.starts_with("structure"))
1719 {
1720 return;
1721 }
1722 }
1723 }
1724
1725 let field_expr = match &assertion.field {
1729 Some(f) if !f.is_empty() && (!result_is_simple || !f.eq_ignore_ascii_case("content")) => {
1730 field_resolver.accessor(f, "ruby", result_var)
1731 }
1732 _ => result_var.to_string(),
1733 };
1734
1735 let field_is_enum = assertion.field.as_deref().filter(|f| !f.is_empty()).is_some_and(|f| {
1743 let resolved = field_resolver.resolve(f);
1744 fields_enum.contains(f)
1745 || fields_enum.contains(resolved)
1746 || per_call_enum_fields.contains_key(f)
1747 || per_call_enum_fields.contains_key(resolved)
1748 });
1749 let expected_is_string = assertion.value.as_ref().is_some_and(|v| v.is_string());
1755 let stripped_field_expr = if result_is_simple && expected_is_string {
1756 format!("{field_expr}.to_s.strip")
1757 } else if field_is_enum {
1758 format!("{field_expr}.to_s")
1759 } else {
1760 field_expr.clone()
1761 };
1762
1763 let field_is_array = assertion
1766 .field
1767 .as_deref()
1768 .filter(|f| !f.is_empty())
1769 .is_some_and(|f| field_resolver.is_array(field_resolver.resolve(f)));
1770
1771 match assertion.assertion_type.as_str() {
1772 "equals" => {
1773 if let Some(expected) = &assertion.value {
1774 let is_boolean_val = expected.as_bool().is_some();
1775 let bool_val = expected
1776 .as_bool()
1777 .map(|b| if b { "true" } else { "false" })
1778 .unwrap_or("");
1779 let rb_val = json_to_ruby(expected);
1780 let cmp_expr = if expected.is_string() && !field_is_enum {
1784 format!("{stripped_field_expr}.to_s.strip")
1785 } else {
1786 stripped_field_expr.clone()
1787 };
1788 let cmp_expected = if expected.is_string() && !field_is_enum {
1789 format!("{rb_val}.strip")
1790 } else {
1791 rb_val
1792 };
1793
1794 let rendered = crate::template_env::render(
1795 "ruby/assertion.jinja",
1796 minijinja::context! {
1797 assertion_type => "equals",
1798 stripped_field_expr => cmp_expr,
1799 is_boolean_val => is_boolean_val,
1800 bool_val => bool_val,
1801 expected_val => cmp_expected,
1802 },
1803 );
1804 out.push_str(&rendered);
1805 }
1806 }
1807 "contains" => {
1808 if let Some(expected) = &assertion.value {
1809 let rb_val = json_to_ruby(expected);
1810 let rendered = crate::template_env::render(
1811 "ruby/assertion.jinja",
1812 minijinja::context! {
1813 assertion_type => "contains",
1814 field_expr => field_expr.clone(),
1815 field_is_array => field_is_array && expected.is_string(),
1816 expected_val => rb_val,
1817 },
1818 );
1819 out.push_str(&rendered);
1820 }
1821 }
1822 "contains_all" => {
1823 if let Some(values) = &assertion.values {
1824 let values_list: Vec<String> = values.iter().map(json_to_ruby).collect();
1825 let rendered = crate::template_env::render(
1826 "ruby/assertion.jinja",
1827 minijinja::context! {
1828 assertion_type => "contains_all",
1829 field_expr => field_expr.clone(),
1830 field_is_array => field_is_array,
1831 values_list => values_list,
1832 },
1833 );
1834 out.push_str(&rendered);
1835 }
1836 }
1837 "not_contains" => {
1838 if let Some(expected) = &assertion.value {
1839 let rb_val = json_to_ruby(expected);
1840 let rendered = crate::template_env::render(
1841 "ruby/assertion.jinja",
1842 minijinja::context! {
1843 assertion_type => "not_contains",
1844 field_expr => field_expr.clone(),
1845 field_is_array => field_is_array && expected.is_string(),
1846 expected_val => rb_val,
1847 },
1848 );
1849 out.push_str(&rendered);
1850 }
1851 }
1852 "not_empty" => {
1853 let rendered = crate::template_env::render(
1854 "ruby/assertion.jinja",
1855 minijinja::context! {
1856 assertion_type => "not_empty",
1857 field_expr => field_expr.clone(),
1858 },
1859 );
1860 out.push_str(&rendered);
1861 }
1862 "is_empty" => {
1863 let rendered = crate::template_env::render(
1864 "ruby/assertion.jinja",
1865 minijinja::context! {
1866 assertion_type => "is_empty",
1867 field_expr => field_expr.clone(),
1868 },
1869 );
1870 out.push_str(&rendered);
1871 }
1872 "contains_any" => {
1873 if let Some(values) = &assertion.values {
1874 let items: Vec<String> = values.iter().map(json_to_ruby).collect();
1875 let rendered = crate::template_env::render(
1876 "ruby/assertion.jinja",
1877 minijinja::context! {
1878 assertion_type => "contains_any",
1879 field_expr => field_expr.clone(),
1880 values_list => items,
1881 },
1882 );
1883 out.push_str(&rendered);
1884 }
1885 }
1886 "greater_than" => {
1887 if let Some(val) = &assertion.value {
1888 let rb_val = json_to_ruby(val);
1889 let rendered = crate::template_env::render(
1890 "ruby/assertion.jinja",
1891 minijinja::context! {
1892 assertion_type => "greater_than",
1893 field_expr => field_expr.clone(),
1894 expected_val => rb_val,
1895 },
1896 );
1897 out.push_str(&rendered);
1898 }
1899 }
1900 "less_than" => {
1901 if let Some(val) = &assertion.value {
1902 let rb_val = json_to_ruby(val);
1903 let rendered = crate::template_env::render(
1904 "ruby/assertion.jinja",
1905 minijinja::context! {
1906 assertion_type => "less_than",
1907 field_expr => field_expr.clone(),
1908 expected_val => rb_val,
1909 },
1910 );
1911 out.push_str(&rendered);
1912 }
1913 }
1914 "greater_than_or_equal" => {
1915 if let Some(val) = &assertion.value {
1916 let rb_val = json_to_ruby(val);
1917 let rendered = crate::template_env::render(
1918 "ruby/assertion.jinja",
1919 minijinja::context! {
1920 assertion_type => "greater_than_or_equal",
1921 field_expr => field_expr.clone(),
1922 expected_val => rb_val,
1923 },
1924 );
1925 out.push_str(&rendered);
1926 }
1927 }
1928 "less_than_or_equal" => {
1929 if let Some(val) = &assertion.value {
1930 let rb_val = json_to_ruby(val);
1931 let rendered = crate::template_env::render(
1932 "ruby/assertion.jinja",
1933 minijinja::context! {
1934 assertion_type => "less_than_or_equal",
1935 field_expr => field_expr.clone(),
1936 expected_val => rb_val,
1937 },
1938 );
1939 out.push_str(&rendered);
1940 }
1941 }
1942 "starts_with" => {
1943 if let Some(expected) = &assertion.value {
1944 let rb_val = json_to_ruby(expected);
1945 let rendered = crate::template_env::render(
1946 "ruby/assertion.jinja",
1947 minijinja::context! {
1948 assertion_type => "starts_with",
1949 field_expr => field_expr.clone(),
1950 expected_val => rb_val,
1951 },
1952 );
1953 out.push_str(&rendered);
1954 }
1955 }
1956 "ends_with" => {
1957 if let Some(expected) = &assertion.value {
1958 let rb_val = json_to_ruby(expected);
1959 let rendered = crate::template_env::render(
1960 "ruby/assertion.jinja",
1961 minijinja::context! {
1962 assertion_type => "ends_with",
1963 field_expr => field_expr.clone(),
1964 expected_val => rb_val,
1965 },
1966 );
1967 out.push_str(&rendered);
1968 }
1969 }
1970 "min_length" | "max_length" | "count_min" | "count_equals" => {
1971 if let Some(val) = &assertion.value {
1972 if let Some(n) = val.as_u64() {
1973 let rendered = crate::template_env::render(
1974 "ruby/assertion.jinja",
1975 minijinja::context! {
1976 assertion_type => assertion.assertion_type.as_str(),
1977 field_expr => field_expr.clone(),
1978 check_n => n,
1979 },
1980 );
1981 out.push_str(&rendered);
1982 }
1983 }
1984 }
1985 "is_true" => {
1986 let rendered = crate::template_env::render(
1987 "ruby/assertion.jinja",
1988 minijinja::context! {
1989 assertion_type => "is_true",
1990 field_expr => field_expr.clone(),
1991 },
1992 );
1993 out.push_str(&rendered);
1994 }
1995 "is_false" => {
1996 let rendered = crate::template_env::render(
1997 "ruby/assertion.jinja",
1998 minijinja::context! {
1999 assertion_type => "is_false",
2000 field_expr => field_expr.clone(),
2001 },
2002 );
2003 out.push_str(&rendered);
2004 }
2005 "method_result" => {
2006 if let Some(method_name) = &assertion.method {
2007 let lang = "ruby";
2009 let call = &e2e_config.call;
2010 let overrides = call.overrides.get(lang);
2011 let module_path = overrides
2012 .and_then(|o| o.module.as_ref())
2013 .cloned()
2014 .unwrap_or_else(|| call.module.clone());
2015 let call_receiver = ruby_module_name(&module_path);
2016
2017 let call_expr =
2018 build_ruby_method_call(&call_receiver, result_var, method_name, assertion.args.as_ref());
2019 let check = assertion.check.as_deref().unwrap_or("is_true");
2020
2021 let (check_val_str, is_boolean_check, bool_check_val, check_n_val) = match check {
2022 "equals" => {
2023 if let Some(val) = &assertion.value {
2024 let is_bool = val.as_bool().is_some();
2025 let bool_str = val.as_bool().map(|b| if b { "true" } else { "false" }).unwrap_or("");
2026 let rb_val = json_to_ruby(val);
2027 (rb_val, is_bool, bool_str.to_string(), 0)
2028 } else {
2029 (String::new(), false, String::new(), 0)
2030 }
2031 }
2032 "greater_than_or_equal" => {
2033 if let Some(val) = &assertion.value {
2034 (json_to_ruby(val), false, String::new(), 0)
2035 } else {
2036 (String::new(), false, String::new(), 0)
2037 }
2038 }
2039 "count_min" => {
2040 if let Some(val) = &assertion.value {
2041 let n = val.as_u64().unwrap_or(0);
2042 (String::new(), false, String::new(), n)
2043 } else {
2044 (String::new(), false, String::new(), 0)
2045 }
2046 }
2047 "contains" => {
2048 if let Some(val) = &assertion.value {
2049 (json_to_ruby(val), false, String::new(), 0)
2050 } else {
2051 (String::new(), false, String::new(), 0)
2052 }
2053 }
2054 _ => (String::new(), false, String::new(), 0),
2055 };
2056
2057 let rendered = crate::template_env::render(
2058 "ruby/assertion.jinja",
2059 minijinja::context! {
2060 assertion_type => "method_result",
2061 call_expr => call_expr,
2062 check => check,
2063 check_val => check_val_str,
2064 is_boolean_check => is_boolean_check,
2065 bool_check_val => bool_check_val,
2066 check_n => check_n_val,
2067 },
2068 );
2069 out.push_str(&rendered);
2070 } else {
2071 panic!("Ruby e2e generator: method_result assertion missing 'method' field");
2072 }
2073 }
2074 "matches_regex" => {
2075 if let Some(expected) = &assertion.value {
2076 let rb_val = json_to_ruby(expected);
2077 let rendered = crate::template_env::render(
2078 "ruby/assertion.jinja",
2079 minijinja::context! {
2080 assertion_type => "matches_regex",
2081 field_expr => field_expr.clone(),
2082 expected_val => rb_val,
2083 },
2084 );
2085 out.push_str(&rendered);
2086 }
2087 }
2088 "not_error" => {
2089 }
2091 "error" => {
2092 }
2094 other => {
2095 panic!("Ruby e2e generator: unsupported assertion type: {other}");
2096 }
2097 }
2098}
2099
2100fn build_ruby_method_call(
2103 call_receiver: &str,
2104 result_var: &str,
2105 method_name: &str,
2106 args: Option<&serde_json::Value>,
2107) -> String {
2108 match method_name {
2109 "root_child_count" => format!("{result_var}.root_node.child_count"),
2110 "root_node_type" => format!("{result_var}.root_node.type"),
2111 "named_children_count" => format!("{result_var}.root_node.named_child_count"),
2112 "has_error_nodes" => format!("{call_receiver}.tree_has_error_nodes({result_var})"),
2113 "error_count" | "tree_error_count" => format!("{call_receiver}.tree_error_count({result_var})"),
2114 "tree_to_sexp" => format!("{call_receiver}.tree_to_sexp({result_var})"),
2115 "contains_node_type" => {
2116 let node_type = args
2117 .and_then(|a| a.get("node_type"))
2118 .and_then(|v| v.as_str())
2119 .unwrap_or("");
2120 format!("{call_receiver}.tree_contains_node_type({result_var}, \"{node_type}\")")
2121 }
2122 "find_nodes_by_type" => {
2123 let node_type = args
2124 .and_then(|a| a.get("node_type"))
2125 .and_then(|v| v.as_str())
2126 .unwrap_or("");
2127 format!("{call_receiver}.find_nodes_by_type({result_var}, \"{node_type}\")")
2128 }
2129 "run_query" => {
2130 let query_source = args
2131 .and_then(|a| a.get("query_source"))
2132 .and_then(|v| v.as_str())
2133 .unwrap_or("");
2134 let language = args
2135 .and_then(|a| a.get("language"))
2136 .and_then(|v| v.as_str())
2137 .unwrap_or("");
2138 format!("{call_receiver}.run_query({result_var}, \"{language}\", \"{query_source}\", source)")
2139 }
2140 _ => format!("{result_var}.{method_name}"),
2141 }
2142}
2143
2144fn ruby_module_name(module_path: &str) -> String {
2147 use heck::ToUpperCamelCase;
2148 module_path.to_upper_camel_case()
2149}
2150
2151fn json_to_ruby(value: &serde_json::Value) -> String {
2153 match value {
2154 serde_json::Value::String(s) => ruby_string_literal(s),
2155 serde_json::Value::Bool(true) => "true".to_string(),
2156 serde_json::Value::Bool(false) => "false".to_string(),
2157 serde_json::Value::Number(n) => n.to_string(),
2158 serde_json::Value::Null => "nil".to_string(),
2159 serde_json::Value::Array(arr) => {
2160 let items: Vec<String> = arr.iter().map(json_to_ruby).collect();
2161 format!("[{}]", items.join(", "))
2162 }
2163 serde_json::Value::Object(map) => {
2164 let items: Vec<String> = map
2165 .iter()
2166 .map(|(k, v)| format!("{} => {}", ruby_string_literal(k), json_to_ruby(v)))
2167 .collect();
2168 format!("{{ {} }}", items.join(", "))
2169 }
2170 }
2171}
2172
2173fn build_ruby_visitor(setup_lines: &mut Vec<String>, visitor_spec: &crate::fixture::VisitorSpec) -> String {
2179 setup_lines.push("visitor = Class.new do".to_string());
2180 for (method_name, action) in &visitor_spec.callbacks {
2181 emit_ruby_visitor_method(setup_lines, method_name, action);
2182 }
2183 setup_lines.push("end.new".to_string());
2184 "visitor".to_string()
2185}
2186
2187fn emit_ruby_visitor_method(setup_lines: &mut Vec<String>, method_name: &str, action: &CallbackAction) {
2189 let params = match method_name {
2190 "visit_link" => "ctx, href, text, title",
2191 "visit_image" => "ctx, src, alt, title",
2192 "visit_heading" => "ctx, level, text, id",
2193 "visit_code_block" => "ctx, lang, code",
2194 "visit_code_inline"
2195 | "visit_strong"
2196 | "visit_emphasis"
2197 | "visit_strikethrough"
2198 | "visit_underline"
2199 | "visit_subscript"
2200 | "visit_superscript"
2201 | "visit_mark"
2202 | "visit_button"
2203 | "visit_summary"
2204 | "visit_figcaption"
2205 | "visit_definition_term"
2206 | "visit_definition_description" => "ctx, text",
2207 "visit_text" => "ctx, text",
2208 "visit_list_item" => "ctx, ordered, marker, text",
2209 "visit_blockquote" => "ctx, content, depth",
2210 "visit_table_row" => "ctx, cells, is_header",
2211 "visit_custom_element" => "ctx, tag_name, html",
2212 "visit_form" => "ctx, action_url, method",
2213 "visit_input" => "ctx, input_type, name, value",
2214 "visit_audio" | "visit_video" | "visit_iframe" => "ctx, src",
2215 "visit_details" => "ctx, is_open",
2216 "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => "ctx, output",
2217 "visit_list_start" => "ctx, ordered",
2218 "visit_list_end" => "ctx, ordered, output",
2219 _ => "ctx",
2220 };
2221
2222 let (action_type, action_value, return_form) = match action {
2224 CallbackAction::Skip => ("skip", String::new(), "dict"),
2225 CallbackAction::Continue => ("continue", String::new(), "dict"),
2226 CallbackAction::PreserveHtml => ("preserve_html", String::new(), "dict"),
2227 CallbackAction::Custom { output } => {
2228 let escaped = ruby_string_literal(output);
2229 ("custom", escaped, "dict")
2230 }
2231 CallbackAction::CustomTemplate { template, return_form } => {
2232 let interpolated = ruby_template_to_interpolation(template);
2233 let form = match return_form {
2234 TemplateReturnForm::Dict => "dict",
2235 TemplateReturnForm::BareString => "bare_string",
2236 };
2237 ("custom_template", format!("\"{interpolated}\""), form)
2238 }
2239 };
2240
2241 let rendered = crate::template_env::render(
2242 "ruby/visitor_method.jinja",
2243 minijinja::context! {
2244 method_name => method_name,
2245 params => params,
2246 action_type => action_type,
2247 action_value => action_value,
2248 return_form => return_form,
2249 },
2250 );
2251 for line in rendered.lines() {
2252 setup_lines.push(line.to_string());
2253 }
2254}
2255
2256fn is_file_path(s: &str) -> bool {
2261 if s.starts_with('<') || s.starts_with('{') || s.starts_with('[') || s.contains(' ') {
2262 return false;
2263 }
2264
2265 let first = s.chars().next().unwrap_or('\0');
2266 if first.is_ascii_alphanumeric() || first == '_' {
2267 if let Some(slash_pos) = s.find('/') {
2268 if slash_pos > 0 {
2269 let after_slash = &s[slash_pos + 1..];
2270 if after_slash.contains('.') && !after_slash.is_empty() {
2271 return true;
2272 }
2273 }
2274 }
2275 }
2276
2277 false
2278}
2279
2280fn is_base64(s: &str) -> bool {
2283 if s.starts_with('<') || s.starts_with('{') || s.starts_with('[') || s.contains(' ') {
2284 return false;
2285 }
2286
2287 if is_file_path(s) {
2288 return false;
2289 }
2290
2291 true
2292}