Skip to main content

alef_e2e/codegen/
wasm.rs

1//! WebAssembly e2e test generator using vitest.
2//!
3//! Reuses the TypeScript test renderer for both HTTP and non-HTTP fixtures,
4//! configured with the `@kreuzberg/wasm` (or equivalent) package as the import
5//! path and `wasm` as the language key for skip/override resolution. Adds
6//! wasm-specific scaffolding: vite-plugin-wasm + top-level-await for vitest,
7//! a `setup.ts` chdir to `test_documents/` so file_path fixtures resolve, and
8//! a `globalSetup.ts` that spawns the mock-server for HTTP fixtures.
9
10use crate::config::E2eConfig;
11use crate::escape::sanitize_filename;
12use crate::field_access::FieldResolver;
13use crate::fixture::{Fixture, FixtureGroup};
14use alef_core::backend::GeneratedFile;
15use alef_core::config::ResolvedCrateConfig;
16use alef_core::hash::{self, CommentStyle};
17use alef_core::template_versions as tv;
18use anyhow::Result;
19use std::fmt::Write as FmtWrite;
20use std::path::PathBuf;
21
22use super::E2eCodegen;
23
24/// WebAssembly e2e code generator.
25pub struct WasmCodegen;
26
27impl E2eCodegen for WasmCodegen {
28    fn generate(
29        &self,
30        groups: &[FixtureGroup],
31        e2e_config: &E2eConfig,
32        config: &ResolvedCrateConfig,
33        type_defs: &[alef_core::ir::TypeDef],
34    ) -> Result<Vec<GeneratedFile>> {
35        let lang = self.language_name();
36        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
37        let tests_base = output_base.join("tests");
38
39        let mut files = Vec::new();
40
41        // Resolve call config with wasm-specific overrides.
42        let call = &e2e_config.call;
43        let overrides = call.overrides.get(lang);
44        let module_path = overrides
45            .and_then(|o| o.module.as_ref())
46            .cloned()
47            .unwrap_or_else(|| call.module.clone());
48        let function_name = overrides
49            .and_then(|o| o.function.as_ref())
50            .cloned()
51            .unwrap_or_else(|| snake_to_camel(&call.function));
52        let client_factory = overrides.and_then(|o| o.client_factory.as_deref());
53
54        // Resolve package config — defaults to a co-located pkg/ directory shipped
55        // by `wasm-pack build` next to the wasm crate.
56        // When `[crates.output] wasm` is set explicitly, derive the pkg path from
57        // that value so that renamed WASM crates resolve correctly without any
58        // hardcoded special cases.
59        let wasm_pkg = e2e_config.resolve_package("wasm");
60        let pkg_path = wasm_pkg
61            .as_ref()
62            .and_then(|p| p.path.as_ref())
63            .cloned()
64            .unwrap_or_else(|| config.wasm_crate_path());
65        let pkg_name = wasm_pkg
66            .as_ref()
67            .and_then(|p| p.name.as_ref())
68            .cloned()
69            .unwrap_or_else(|| {
70                // Default: derive from WASM crate name (config.name + "-wasm")
71                // wasm-pack transforms the crate name to the package name by replacing
72                // dashes with the crate separator in Cargo (e.g., kreuzberg-wasm -> kreuzberg_wasm).
73                // However, the published npm package might use the module name, which is typically
74                // the crate name without "-wasm". Fall back to the module path.
75                module_path.clone()
76            });
77        let pkg_version = wasm_pkg
78            .as_ref()
79            .and_then(|p| p.version.as_ref())
80            .cloned()
81            .or_else(|| config.resolved_version())
82            .unwrap_or_else(|| "0.1.0".to_string());
83
84        // Determine which auxiliary scaffolding files we need based on the active
85        // fixture set. Doing this once up front lets us emit a self-contained vitest
86        // config that wires only the setup files we'll actually generate.
87        let active_per_group: Vec<Vec<&Fixture>> = groups
88            .iter()
89            .map(|group| {
90                group
91                    .fixtures
92                    .iter()
93                    .filter(|f| super::should_include_fixture(f, lang, e2e_config))
94                    // Honor per-call `skip_languages`: when the resolved call's
95                    // `skip_languages` contains `wasm`, the wasm binding doesn't
96                    // export that function and any test file referencing it
97                    // would fail TS resolution. Drop the fixture entirely.
98                    .filter(|f| {
99                        let cc = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
100                        !cc.skip_languages.iter().any(|l| l == lang)
101                    })
102                    .filter(|f| {
103                        // Node fetch (undici) rejects pre-set Content-Length that
104                        // doesn't match the real body length — skip fixtures that
105                        // intentionally send a mismatched header.
106                        f.http.as_ref().is_none_or(|h| {
107                            !h.request
108                                .headers
109                                .iter()
110                                .any(|(k, _)| k.eq_ignore_ascii_case("content-length"))
111                        })
112                    })
113                    .filter(|f| {
114                        // Node fetch only supports a fixed set of HTTP methods;
115                        // TRACE and CONNECT throw before reaching the server.
116                        f.http.as_ref().is_none_or(|h| {
117                            let m = h.request.method.to_ascii_uppercase();
118                            m != "TRACE" && m != "CONNECT"
119                        })
120                    })
121                    .collect()
122            })
123            .collect();
124
125        let any_fixtures = active_per_group.iter().flat_map(|g| g.iter());
126        let has_http_fixtures = any_fixtures.clone().any(|f| f.is_http_test());
127        // file_path / bytes args are read off disk by the generated code at runtime;
128        // we add a setup.ts chdir to test_documents so relative paths resolve.
129        let has_file_fixtures = active_per_group.iter().flatten().any(|f| {
130            let cc = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
131            cc.args
132                .iter()
133                .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
134        });
135
136        // Generate package.json — adds vite-plugin-wasm + top-level-await on top
137        // of the standard vitest dev deps so that `import init, { … } from
138        // '@kreuzberg/wasm'` resolves and instantiates the wasm module before tests
139        // run.
140        files.push(GeneratedFile {
141            path: output_base.join("package.json"),
142            content: render_package_json(&pkg_name, &pkg_path, &pkg_version, e2e_config.dep_mode),
143            generated_header: false,
144        });
145
146        // Generate vitest.config.ts — needs vite-plugin-wasm + topLevelAwait, plus
147        // optional globalSetup (for HTTP fixtures and any function-call test that
148        // hits the mock server via MOCK_SERVER_URL) and setupFiles (for chdir).
149        // Function-call e2e tests construct request URLs via
150        // `${process.env.MOCK_SERVER_URL}/fixtures/<id>`, so the mock server must
151        // be running and the env var set even when no raw HTTP fixtures exist.
152        let needs_global_setup = has_http_fixtures;
153        files.push(GeneratedFile {
154            path: output_base.join("vitest.config.ts"),
155            content: render_vitest_config(needs_global_setup, has_file_fixtures),
156            generated_header: true,
157        });
158
159        // Generate globalSetup.ts when any fixture requires the mock server —
160        // either an HTTP fixture (the original consumer) or any function-call
161        // fixture that interpolates `${process.env.MOCK_SERVER_URL}` into a
162        // base URL. It spawns the rust mock-server binary.
163        if needs_global_setup {
164            files.push(GeneratedFile {
165                path: output_base.join("globalSetup.ts"),
166                content: render_global_setup(),
167                generated_header: true,
168            });
169        }
170
171        // Generate setup.ts when any active fixture takes a file_path / bytes arg.
172        // This chdir's to test_documents/ so relative fixture paths resolve.
173        if has_file_fixtures {
174            files.push(GeneratedFile {
175                path: output_base.join("setup.ts"),
176                content: render_file_setup(&e2e_config.test_documents_dir),
177                generated_header: true,
178            });
179        }
180
181        // Generate tsconfig.json — prevents Vite from walking up to a project-level
182        // tsconfig and pulling in unrelated compiler options.
183        files.push(GeneratedFile {
184            path: output_base.join("tsconfig.json"),
185            content: render_tsconfig(),
186            generated_header: false,
187        });
188
189        // Resolve options_type from override (e.g. `WasmExtractionConfig`).
190        let options_type = overrides.and_then(|o| o.options_type.clone());
191        let field_resolver = FieldResolver::new(
192            &e2e_config.fields,
193            &e2e_config.fields_optional,
194            &e2e_config.result_fields,
195            &e2e_config.fields_array,
196            &std::collections::HashSet::new(),
197        );
198
199        // Generate test files per category. We delegate the per-fixture rendering
200        // to the typescript codegen (`render_test_file`), which already handles
201        // both HTTP and function-call fixtures correctly. Passing `lang = "wasm"`
202        // routes per-fixture override resolution and skip checks through the wasm
203        // language key. We then inject Node.js WASM initialization code to load
204        // the WASM binary from the pkg directory using fs.readFileSync.
205        for (group, active) in groups.iter().zip(active_per_group.iter()) {
206            if active.is_empty() {
207                continue;
208            }
209            let filename = format!("{}.test.ts", sanitize_filename(&group.category));
210            let content = super::typescript::render_test_file(
211                lang,
212                &group.category,
213                active,
214                &module_path,
215                &pkg_name,
216                &function_name,
217                &e2e_config.call.args,
218                options_type.as_deref(),
219                &field_resolver,
220                client_factory,
221                e2e_config,
222                type_defs,
223            );
224
225            // The local `pkg/` directory produced by `wasm-pack build --target nodejs`
226            // is already a Node-friendly self-initializing CJS module — `pkg/package.json`
227            // sets `"main"` to the JS entry, so test files can import the package by name
228            // (`from "<pkg_name>"`) with no subpath. The historical `dist-node` rewrite
229            // assumed a multi-distribution layout (`dist/`, `dist-node/`, `dist-web/`)
230            // that the alef-managed `wasm-pack build` does not produce; it is therefore
231            // intentionally absent here.
232            let _ = (&pkg_path, &config.name); // keep variables alive for future use
233
234            files.push(GeneratedFile {
235                path: tests_base.join(filename),
236                content,
237                generated_header: true,
238            });
239        }
240
241        Ok(files)
242    }
243
244    fn language_name(&self) -> &'static str {
245        "wasm"
246    }
247}
248
249fn snake_to_camel(s: &str) -> String {
250    let mut out = String::with_capacity(s.len());
251    let mut upper_next = false;
252    for ch in s.chars() {
253        if ch == '_' {
254            upper_next = true;
255        } else if upper_next {
256            out.push(ch.to_ascii_uppercase());
257            upper_next = false;
258        } else {
259            out.push(ch);
260        }
261    }
262    out
263}
264
265fn render_package_json(
266    pkg_name: &str,
267    pkg_path: &str,
268    pkg_version: &str,
269    dep_mode: crate::config::DependencyMode,
270) -> String {
271    let dep_value = match dep_mode {
272        crate::config::DependencyMode::Registry => pkg_version.to_string(),
273        crate::config::DependencyMode::Local => format!("file:{pkg_path}"),
274    };
275    crate::template_env::render(
276        "wasm/package.json.jinja",
277        minijinja::context! {
278            pkg_name => pkg_name,
279            dep_value => dep_value,
280            rollup => tv::npm::ROLLUP,
281            vite_plugin_wasm => tv::npm::VITE_PLUGIN_WASM,
282            vitest => tv::npm::VITEST,
283        },
284    )
285}
286
287fn render_vitest_config(with_global_setup: bool, with_file_setup: bool) -> String {
288    let header = hash::header(CommentStyle::DoubleSlash);
289    crate::template_env::render(
290        "wasm/vitest.config.ts.jinja",
291        minijinja::context! {
292            header => header,
293            with_global_setup => with_global_setup,
294            with_file_setup => with_file_setup,
295        },
296    )
297}
298
299fn render_file_setup(test_documents_dir: &str) -> String {
300    let header = hash::header(CommentStyle::DoubleSlash);
301    let mut out = header;
302    out.push_str("import { fileURLToPath } from 'url';\n");
303    out.push_str("import { dirname, join } from 'path';\n\n");
304    out.push_str(
305        "// Change to the configured test-documents directory so that fixture file paths like\n",
306    );
307    out.push_str("// \"pdf/fake_memo.pdf\" resolve correctly when vitest runs from e2e/wasm/.\n");
308    out.push_str("// setup.ts lives in e2e/wasm/; the fixtures dir lives at the repository root,\n");
309    out.push_str("// two directories up: e2e/wasm/ -> e2e/ -> repo root.\n");
310    out.push_str("const __filename = fileURLToPath(import.meta.url);\n");
311    out.push_str("const __dirname = dirname(__filename);\n");
312    let _ = writeln!(
313        out,
314        "const testDocumentsDir = join(__dirname, '..', '..', '{test_documents_dir}');"
315    );
316    out.push_str("process.chdir(testDocumentsDir);\n");
317    out
318}
319
320fn render_global_setup() -> String {
321    let header = hash::header(CommentStyle::DoubleSlash);
322    crate::template_env::render(
323        "wasm/globalSetup.ts.jinja",
324        minijinja::context! {
325            header => header,
326        },
327    )
328}
329
330fn render_tsconfig() -> String {
331    crate::template_env::render("wasm/tsconfig.jinja", minijinja::context! {})
332}
333
334// The historical `inject_wasm_init` post-processor rewrote test imports to a
335// `<pkg>/dist-node` subpath. It was removed because the alef-managed
336// `wasm-pack build --target nodejs` artifact is a flat self-initializing CJS
337// module — its `package.json` already sets `"main"` to the JS entry, so the
338// emitted `import … from "<pkg>"` resolves directly.