1#![cfg(feature = "cli")]
2
3use std::env;
4use std::fs;
5use std::path::{Path, PathBuf};
6use std::process::Command;
7
8use anyhow::{Context, Result, anyhow, bail};
9use clap::Args;
10use serde_json::Value as JsonValue;
11use wasmtime::component::{Component, Linker, Val};
12use wasmtime::{Engine, Store};
13use wasmtime_wasi::{ResourceTable, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};
14
15use crate::abi::{self, AbiError};
16use crate::cmd::component_world::{canonical_component_world, is_fallback_world};
17use crate::cmd::flow::{
18 FlowUpdateResult, manifest_component_id, resolve_operation, update_with_manifest,
19};
20use crate::cmd::i18n;
21use crate::config::{
22 ConfigInferenceOptions, ConfigSchemaSource, load_manifest_with_schema, resolve_manifest_path,
23};
24use crate::describe::{DescribePayload, from_wit_world};
25use crate::embedded_descriptor::embed_and_verify_wasm;
26use crate::parse_manifest;
27use crate::path_safety::normalize_under_root;
28use crate::schema_quality::{SchemaQualityMode, validate_operation_schemas};
29use greentic_types::cbor::canonical;
30use greentic_types::schemas::component::v0_6_0::ComponentDescribe;
31
32const DEFAULT_MANIFEST: &str = "component.manifest.json";
33
34#[derive(Args, Debug, Clone)]
35pub struct BuildArgs {
36 #[arg(long = "manifest", value_name = "PATH", default_value = DEFAULT_MANIFEST)]
38 pub manifest: PathBuf,
39 #[arg(long = "cargo", value_name = "PATH")]
41 pub cargo_bin: Option<PathBuf>,
42 #[arg(long = "no-flow")]
44 pub no_flow: bool,
45 #[arg(long = "no-infer-config")]
47 pub no_infer_config: bool,
48 #[arg(long = "no-write-schema")]
50 pub no_write_schema: bool,
51 #[arg(long = "force-write-schema")]
53 pub force_write_schema: bool,
54 #[arg(long = "no-validate")]
56 pub no_validate: bool,
57 #[arg(long = "json")]
59 pub json: bool,
60 #[arg(long)]
62 pub permissive: bool,
63}
64
65#[derive(Debug, serde::Serialize)]
66struct BuildSummary {
67 manifest: PathBuf,
68 wasm_path: PathBuf,
69 wasm_hash: String,
70 config_source: ConfigSchemaSource,
71 schema_written: bool,
72 #[serde(skip_serializing_if = "Option::is_none")]
73 flows: Option<FlowUpdateResult>,
74}
75
76pub fn run(args: BuildArgs) -> Result<()> {
77 let manifest_path = resolve_manifest_path(&args.manifest);
78 let cwd = env::current_dir().context("failed to read current directory")?;
79 let manifest_path = if manifest_path.is_absolute() {
80 manifest_path
81 } else {
82 cwd.join(manifest_path)
83 };
84 if !manifest_path.exists() {
85 bail!(
86 "{}",
87 i18n::tr_lit("manifest not found at {}").replacen(
88 "{}",
89 &manifest_path.display().to_string(),
90 1
91 )
92 );
93 }
94 let cargo_bin = args
95 .cargo_bin
96 .clone()
97 .or_else(|| env::var_os("CARGO").map(PathBuf::from))
98 .unwrap_or_else(|| PathBuf::from("cargo"));
99 let inference_opts = ConfigInferenceOptions {
100 allow_infer: !args.no_infer_config,
101 write_schema: !args.no_write_schema,
102 force_write_schema: args.force_write_schema,
103 validate: !args.no_validate,
104 };
105 println!(
106 "Using manifest at {} (cargo: {})",
107 manifest_path.display(),
108 cargo_bin.display()
109 );
110
111 let config = load_manifest_with_schema(&manifest_path, &inference_opts)?;
112 let mode = if args.permissive {
113 SchemaQualityMode::Permissive
114 } else {
115 SchemaQualityMode::Strict
116 };
117 let manifest_component = parse_manifest(
118 &serde_json::to_string(&config.manifest)
119 .context("failed to serialize manifest for schema validation")?,
120 )
121 .context("failed to parse manifest for schema validation")?;
122 let schema_warnings = validate_operation_schemas(&manifest_component, mode)?;
123 for warning in schema_warnings {
124 eprintln!("warning[W_OP_SCHEMA_EMPTY]: {}", warning.message);
125 }
126 let component_id = manifest_component_id(&config.manifest)?;
127 let _operation = resolve_operation(&config.manifest, component_id)?;
128 let flow_outcome = if args.no_flow {
129 None
130 } else {
131 Some(update_with_manifest(&config)?)
132 };
133
134 let mut manifest_to_write = flow_outcome
135 .as_ref()
136 .map(|outcome| outcome.manifest.clone())
137 .unwrap_or_else(|| config.manifest.clone());
138 let canonical_manifest = parse_manifest(
139 &serde_json::to_string(&manifest_to_write)
140 .context("failed to serialize manifest for embedded descriptor")?,
141 )
142 .context("failed to parse canonical manifest for embedded descriptor")?;
143
144 let manifest_dir = manifest_path.parent().unwrap_or_else(|| Path::new("."));
145 build_wasm(manifest_dir, &cargo_bin, &manifest_to_write)?;
146 check_canonical_world_export(manifest_dir, &manifest_to_write)?;
147 let wasm_path_for_embedding = resolve_wasm_path(manifest_dir, &manifest_to_write)?;
148 embed_and_verify_wasm(&wasm_path_for_embedding, &canonical_manifest)
149 .context("failed to embed canonical manifest into built wasm")?;
150
151 if !config.persist_schema {
152 manifest_to_write
153 .as_object_mut()
154 .map(|obj| obj.remove("config_schema"));
155 }
156 let (wasm_path, wasm_hash) = update_manifest_hashes(manifest_dir, &mut manifest_to_write)?;
157 emit_describe_artifacts(manifest_dir, &manifest_to_write, &wasm_path)?;
158 write_manifest(&manifest_path, &manifest_to_write)?;
159
160 if args.json {
161 let payload = BuildSummary {
162 manifest: manifest_path.clone(),
163 wasm_path,
164 wasm_hash,
165 config_source: config.source,
166 schema_written: config.schema_written && config.persist_schema,
167 flows: flow_outcome.as_ref().map(|outcome| outcome.result),
168 };
169 serde_json::to_writer_pretty(std::io::stdout(), &payload)?;
170 println!();
171 } else {
172 println!("Built wasm artifact at {}", wasm_path.display());
173 println!("Updated {} hashes (blake3)", manifest_path.display());
174 if config.schema_written && config.persist_schema {
175 println!(
176 "Updated {} with inferred config_schema ({:?})",
177 manifest_path.display(),
178 config.source
179 );
180 }
181 if let Some(outcome) = flow_outcome {
182 let flows = outcome.result;
183 println!(
184 "Flows updated (default: {}, custom: {})",
185 flows.default_updated, flows.custom_updated
186 );
187 } else {
188 println!("Flow regeneration skipped (--no-flow)");
189 }
190 }
191
192 Ok(())
193}
194
195fn build_wasm(manifest_dir: &Path, cargo_bin: &Path, manifest: &JsonValue) -> Result<()> {
196 let resolved_world = manifest.get("world").and_then(|v| v.as_str()).unwrap_or("");
197 if resolved_world.is_empty() {
198 println!("Resolved manifest world: <missing>");
199 } else {
200 println!("Resolved manifest world: {resolved_world}");
201 }
202 let require_component = resolved_world.contains("component@0.6.0");
203
204 if require_component {
205 if cargo_component_available(cargo_bin) {
206 println!(
207 "Running cargo component build via {} in {}",
208 cargo_bin.display(),
209 manifest_dir.display()
210 );
211 let mut cmd = Command::new(cargo_bin);
214 if let Some(flags) = resolved_wasm_rustflags() {
215 cmd.env("RUSTFLAGS", sanitize_wasm_rustflags(&flags));
216 }
217 cmd.arg("component").arg("build");
218 maybe_add_offline_flag(&mut cmd);
219 let status = cmd
220 .arg("--target")
221 .arg("wasm32-wasip2")
222 .arg("--release")
223 .current_dir(manifest_dir)
224 .status()
225 .with_context(|| {
226 format!(
227 "failed to run cargo component build via {}",
228 cargo_bin.display()
229 )
230 })?;
231 if !status.success() {
232 bail!(
233 "cargo component build --target wasm32-wasip2 --release failed with status {}",
234 status
235 );
236 }
237 return Ok(());
238 }
239 bail!(
240 "component@0.6.0 manifests require cargo-component; install it with `cargo install cargo-component --locked`"
241 );
242 }
243
244 println!(
245 "Running cargo build via {} in {}",
246 cargo_bin.display(),
247 manifest_dir.display()
248 );
249 let mut cmd = Command::new(cargo_bin);
252 if let Some(flags) = resolved_wasm_rustflags() {
253 cmd.env("RUSTFLAGS", sanitize_wasm_rustflags(&flags));
254 }
255 cmd.arg("build");
256 maybe_add_offline_flag(&mut cmd);
257 let status = cmd
258 .arg("--target")
259 .arg("wasm32-wasip2")
260 .arg("--release")
261 .current_dir(manifest_dir)
262 .status()
263 .with_context(|| format!("failed to run cargo build via {}", cargo_bin.display()))?;
264
265 if !status.success() {
266 bail!(
267 "cargo build --target wasm32-wasip2 --release failed with status {}",
268 status
269 );
270 }
271 Ok(())
272}
273
274fn cargo_component_available(cargo_bin: &Path) -> bool {
275 Command::new(cargo_bin)
278 .arg("component")
279 .arg("--version")
280 .status()
281 .map(|status| status.success())
282 .unwrap_or(false)
283}
284
285fn maybe_add_offline_flag(cmd: &mut Command) {
286 if cargo_offline_requested() {
287 cmd.arg("--offline");
288 }
289}
290
291fn cargo_offline_requested() -> bool {
292 env_truthy(env::var_os("CARGO_NET_OFFLINE").as_deref())
293}
294
295fn env_truthy(value: Option<&std::ffi::OsStr>) -> bool {
296 value
297 .and_then(|raw| raw.to_str())
298 .map(|raw| {
299 matches!(
300 raw.trim().to_ascii_lowercase().as_str(),
301 "1" | "true" | "yes" | "on"
302 )
303 })
304 .unwrap_or(false)
305}
306
307fn resolved_wasm_rustflags() -> Option<String> {
309 env::var("WASM_RUSTFLAGS")
310 .ok()
311 .or_else(|| env::var("RUSTFLAGS").ok())
312}
313
314fn sanitize_wasm_rustflags(flags: &str) -> String {
316 flags
317 .replace("-Wl,", "")
318 .replace("-C link-arg=--no-keep-memory", "")
319 .replace("-C link-arg=--threads=1", "")
320 .split_whitespace()
321 .collect::<Vec<_>>()
322 .join(" ")
323}
324
325fn check_canonical_world_export(manifest_dir: &Path, manifest: &JsonValue) -> Result<()> {
326 if env::var_os("GREENTIC_SKIP_NODE_EXPORT_CHECK").is_some() {
327 println!("World export check skipped (GREENTIC_SKIP_NODE_EXPORT_CHECK=1)");
328 return Ok(());
329 }
330 let wasm_path = resolve_wasm_path(manifest_dir, manifest)?;
331 let canonical_world = canonical_component_world();
332 match abi::check_world_base(&wasm_path, canonical_world) {
333 Ok(exported) => println!("Exported world: {exported}"),
334 Err(err) => match err {
335 AbiError::WorldMismatch { expected, found } if is_fallback_world(&found) => {
336 println!("Exported world: {expected} (compatible fallback export: {found})");
337 }
338 err => {
339 return Err(err)
340 .with_context(|| format!("component must export world {canonical_world}"));
341 }
342 },
343 }
344 Ok(())
345}
346
347fn update_manifest_hashes(
348 manifest_dir: &Path,
349 manifest: &mut JsonValue,
350) -> Result<(PathBuf, String)> {
351 let artifact_path = resolve_wasm_path(manifest_dir, manifest)?;
352 let wasm_bytes = fs::read(&artifact_path)
353 .with_context(|| format!("failed to read wasm at {}", artifact_path.display()))?;
354 let digest = blake3::hash(&wasm_bytes).to_hex().to_string();
355
356 manifest["artifacts"]["component_wasm"] =
357 JsonValue::String(path_string_relative(manifest_dir, &artifact_path)?);
358 manifest["hashes"]["component_wasm"] = JsonValue::String(format!("blake3:{digest}"));
359
360 Ok((artifact_path, format!("blake3:{digest}")))
361}
362
363fn path_string_relative(base: &Path, target: &Path) -> Result<String> {
364 let rel = pathdiff::diff_paths(target, base).unwrap_or_else(|| target.to_path_buf());
365 rel.to_str()
366 .map(|s| s.to_string())
367 .ok_or_else(|| anyhow!("failed to stringify path {}", target.display()))
368}
369
370fn resolve_wasm_path(manifest_dir: &Path, manifest: &JsonValue) -> Result<PathBuf> {
371 let manifest_root = manifest_dir
372 .canonicalize()
373 .with_context(|| format!("failed to canonicalize {}", manifest_dir.display()))?;
374 let candidate = manifest
375 .get("artifacts")
376 .and_then(|a| a.get("component_wasm"))
377 .and_then(|v| v.as_str())
378 .map(PathBuf::from)
379 .unwrap_or_else(|| {
380 let raw_name = manifest
381 .get("name")
382 .and_then(|v| v.as_str())
383 .or_else(|| manifest.get("id").and_then(|v| v.as_str()))
384 .unwrap_or("component");
385 let sanitized = raw_name.replace(['-', '.'], "_");
386 manifest_dir.join(format!("target/wasm32-wasip2/release/{sanitized}.wasm"))
387 });
388 if candidate.exists() {
389 let normalized = normalize_under_root(&manifest_root, &candidate).or_else(|_| {
390 if candidate.is_absolute() {
391 candidate
392 .canonicalize()
393 .with_context(|| format!("failed to canonicalize {}", candidate.display()))
394 } else {
395 normalize_under_root(&manifest_root, &candidate)
396 }
397 })?;
398 return Ok(normalized);
399 }
400
401 if let Some(cargo_target_dir) = env::var_os("CARGO_TARGET_DIR") {
402 let relative = candidate
403 .strip_prefix(manifest_dir)
404 .unwrap_or(&candidate)
405 .to_path_buf();
406 if relative.starts_with("target") {
407 let alt =
408 PathBuf::from(cargo_target_dir).join(relative.strip_prefix("target").unwrap());
409 if alt.exists() {
410 return alt
411 .canonicalize()
412 .with_context(|| format!("failed to canonicalize {}", alt.display()));
413 }
414 }
415 }
416
417 let normalized = normalize_under_root(&manifest_root, &candidate).or_else(|_| {
418 if candidate.is_absolute() {
419 candidate
420 .canonicalize()
421 .with_context(|| format!("failed to canonicalize {}", candidate.display()))
422 } else {
423 normalize_under_root(&manifest_root, &candidate)
424 }
425 })?;
426 Ok(normalized)
427}
428
429fn write_manifest(manifest_path: &Path, manifest: &JsonValue) -> Result<()> {
430 let formatted = serde_json::to_string_pretty(manifest)?;
431 fs::write(manifest_path, formatted + "\n")
432 .with_context(|| format!("failed to write {}", manifest_path.display()))
433}
434
435fn emit_describe_artifacts(
436 manifest_dir: &Path,
437 manifest: &JsonValue,
438 wasm_path: &Path,
439) -> Result<()> {
440 let abi_version = read_abi_version(manifest_dir);
441 let require_describe = abi_version.as_deref() == Some("0.6.0");
442 let manifest_model = parse_manifest(
443 &serde_json::to_string(manifest).context("failed to serialize manifest for describe")?,
444 )
445 .context("failed to parse manifest for describe")?;
446
447 let describe_bytes = match call_describe(wasm_path) {
448 Ok(bytes) => bytes,
449 Err(err) => {
450 if require_describe {
451 match from_wit_world(wasm_path, manifest_model.world.as_str()) {
452 Ok(payload) => {
453 write_wit_describe_artifacts(
454 manifest_dir,
455 manifest,
456 wasm_path,
457 abi_version.as_deref(),
458 &payload,
459 )?;
460 eprintln!(
461 "warning: describe export unavailable, emitted WIT-derived describe.json instead ({err})"
462 );
463 return Ok(());
464 }
465 Err(wit_err) => {
466 return Err(anyhow!(
467 "describe failed: {err}; WIT fallback failed: {wit_err}"
468 ));
469 }
470 }
471 }
472 eprintln!("warning: skipping describe artifacts ({err})");
473 return Ok(());
474 }
475 };
476
477 let payload = strip_self_describe_tag(&describe_bytes);
478 let canonical_bytes = canonical::canonicalize_allow_floats(payload)
479 .map_err(|err| anyhow!("describe canonicalization failed: {err}"))?;
480 let describe: ComponentDescribe = canonical::from_cbor(&canonical_bytes)
481 .map_err(|err| anyhow!("describe decode failed: {err}"))?;
482
483 let dist_dir = manifest_dir.join("dist");
484 fs::create_dir_all(&dist_dir)
485 .with_context(|| format!("failed to create {}", dist_dir.display()))?;
486
487 let (name, abi_underscore) = artifact_basename(manifest, wasm_path, abi_version.as_deref());
488 let base = format!("{name}__{abi_underscore}");
489 let describe_cbor_path = dist_dir.join(format!("{base}.describe.cbor"));
490 fs::write(&describe_cbor_path, &canonical_bytes)
491 .with_context(|| format!("failed to write {}", describe_cbor_path.display()))?;
492
493 let describe_json_path = dist_dir.join(format!("{base}.describe.json"));
494 let json = serde_json::to_string_pretty(&describe)?;
495 fs::write(&describe_json_path, json + "\n")
496 .with_context(|| format!("failed to write {}", describe_json_path.display()))?;
497
498 let wasm_out = dist_dir.join(format!("{base}.wasm"));
499 if wasm_out != wasm_path {
500 let _ = fs::copy(wasm_path, &wasm_out);
501 }
502
503 Ok(())
504}
505
506fn write_wit_describe_artifacts(
507 manifest_dir: &Path,
508 manifest: &JsonValue,
509 wasm_path: &Path,
510 abi_version: Option<&str>,
511 payload: &DescribePayload,
512) -> Result<()> {
513 let dist_dir = manifest_dir.join("dist");
514 fs::create_dir_all(&dist_dir)
515 .with_context(|| format!("failed to create {}", dist_dir.display()))?;
516
517 let (name, abi_underscore) = artifact_basename(manifest, wasm_path, abi_version);
518 let base = format!("{name}__{abi_underscore}");
519 let describe_cbor_path = dist_dir.join(format!("{base}.describe.cbor"));
520 let cbor = canonical::to_canonical_cbor_allow_floats(payload)
521 .map_err(|err| anyhow!("describe fallback canonicalization failed: {err}"))?;
522 fs::write(&describe_cbor_path, cbor)
523 .with_context(|| format!("failed to write {}", describe_cbor_path.display()))?;
524
525 let describe_json_path = dist_dir.join(format!("{base}.describe.json"));
526 let json = serde_json::to_string_pretty(payload)?;
527 fs::write(&describe_json_path, json + "\n")
528 .with_context(|| format!("failed to write {}", describe_json_path.display()))?;
529
530 let wasm_out = dist_dir.join(format!("{base}.wasm"));
531 if wasm_out != wasm_path {
532 let _ = fs::copy(wasm_path, &wasm_out);
533 }
534
535 Ok(())
536}
537
538fn read_abi_version(manifest_dir: &Path) -> Option<String> {
539 let cargo_path = manifest_dir.join("Cargo.toml");
540 let contents = fs::read_to_string(cargo_path).ok()?;
541 let doc: toml::Value = toml::from_str(&contents).ok()?;
542 doc.get("package")
543 .and_then(|pkg| pkg.get("metadata"))
544 .and_then(|meta| meta.get("greentic"))
545 .and_then(|g| g.get("abi_version"))
546 .and_then(|v| v.as_str())
547 .map(|s| s.to_string())
548}
549
550fn artifact_basename(
551 manifest: &JsonValue,
552 wasm_path: &Path,
553 abi_version: Option<&str>,
554) -> (String, String) {
555 let name = manifest
556 .get("name")
557 .and_then(|v| v.as_str())
558 .or_else(|| manifest.get("id").and_then(|v| v.as_str()))
559 .map(sanitize_name)
560 .unwrap_or_else(|| {
561 wasm_path
562 .file_stem()
563 .and_then(|s| s.to_str())
564 .map(sanitize_name)
565 .unwrap_or_else(|| "component".to_string())
566 });
567 let abi = abi_version.unwrap_or("0.6.0").replace('.', "_");
568 (name, abi)
569}
570
571fn sanitize_name(raw: &str) -> String {
572 raw.chars()
573 .map(|ch| {
574 if ch.is_ascii_alphanumeric() || ch == '-' {
575 ch
576 } else {
577 '_'
578 }
579 })
580 .collect::<String>()
581 .trim_matches('_')
582 .to_string()
583}
584
585fn call_describe(wasm_path: &Path) -> Result<Vec<u8>> {
586 let mut config = wasmtime::Config::new();
587 config.wasm_component_model(true);
588 let engine = Engine::new(&config).map_err(|err| anyhow!("failed to create engine: {err}"))?;
589 let component = Component::from_file(&engine, wasm_path)
590 .map_err(|err| anyhow!("failed to load component {}: {err}", wasm_path.display()))?;
591 let mut linker = Linker::new(&engine);
592 wasmtime_wasi::p2::add_to_linker_sync(&mut linker)
593 .map_err(|err| anyhow!("failed to add wasi: {err}"))?;
594 let mut store = Store::new(&engine, BuildWasi::new()?);
595 let instance = linker
596 .instantiate(&mut store, &component)
597 .map_err(|err| anyhow!("failed to instantiate component: {err}"))?;
598 let instance_index = resolve_interface_index(&instance, &mut store, "component-descriptor")
599 .ok_or_else(|| anyhow!("missing export interface component-descriptor"))?;
600 let func_index = instance
601 .get_export_index(&mut store, Some(&instance_index), "describe")
602 .ok_or_else(|| anyhow!("missing export component-descriptor.describe"))?;
603 let func = instance
604 .get_func(&mut store, func_index)
605 .ok_or_else(|| anyhow!("describe export is not callable"))?;
606 let mut results = vec![Val::Bool(false); func.ty(&mut store).results().len()];
607 func.call(&mut store, &[], &mut results)
608 .map_err(|err| anyhow!("describe call failed: {err}"))?;
609 let val = results
610 .first()
611 .ok_or_else(|| anyhow!("describe returned no value"))?;
612 val_to_bytes(val).map_err(|err| anyhow!(err))
613}
614
615fn resolve_interface_index(
616 instance: &wasmtime::component::Instance,
617 store: &mut Store<BuildWasi>,
618 interface: &str,
619) -> Option<wasmtime::component::ComponentExportIndex> {
620 for candidate in interface_candidates(interface) {
621 if let Some(index) = instance.get_export_index(&mut *store, None, &candidate) {
622 return Some(index);
623 }
624 }
625 None
626}
627
628fn interface_candidates(interface: &str) -> [String; 3] {
629 [
630 interface.to_string(),
631 format!("greentic:component/{interface}@0.6.0"),
632 format!("greentic:component/{interface}"),
633 ]
634}
635
636fn val_to_bytes(val: &Val) -> Result<Vec<u8>, String> {
637 match val {
638 Val::List(items) => {
639 let mut out = Vec::with_capacity(items.len());
640 for item in items {
641 match item {
642 Val::U8(byte) => out.push(*byte),
643 _ => return Err("expected list<u8>".to_string()),
644 }
645 }
646 Ok(out)
647 }
648 _ => Err("expected list<u8>".to_string()),
649 }
650}
651
652fn strip_self_describe_tag(bytes: &[u8]) -> &[u8] {
653 const SELF_DESCRIBE_TAG: [u8; 3] = [0xd9, 0xd9, 0xf7];
654 if bytes.starts_with(&SELF_DESCRIBE_TAG) {
655 &bytes[SELF_DESCRIBE_TAG.len()..]
656 } else {
657 bytes
658 }
659}
660
661struct BuildWasi {
662 ctx: WasiCtx,
663 table: ResourceTable,
664}
665
666impl BuildWasi {
667 fn new() -> Result<Self> {
668 let ctx = WasiCtxBuilder::new().build();
669 Ok(Self {
670 ctx,
671 table: ResourceTable::new(),
672 })
673 }
674}
675
676impl WasiView for BuildWasi {
677 fn ctx(&mut self) -> WasiCtxView<'_> {
678 WasiCtxView {
679 ctx: &mut self.ctx,
680 table: &mut self.table,
681 }
682 }
683}
684
685#[cfg(test)]
686mod tests {
687 use std::ffi::OsStr;
688 use std::path::Path;
689
690 use serde_json::json;
691 use wasmtime::component::Val;
692
693 use super::{
694 env_truthy, path_string_relative, resolve_wasm_path, sanitize_name,
695 sanitize_wasm_rustflags, strip_self_describe_tag, val_to_bytes,
696 };
697
698 #[test]
699 fn sanitize_name_preserves_hyphens_for_dist_artifacts() {
700 assert_eq!(
701 sanitize_name("wizard-smoke-advanced"),
702 "wizard-smoke-advanced"
703 );
704 assert_eq!(
705 sanitize_name("wizard_smoke_advanced"),
706 "wizard_smoke_advanced"
707 );
708 }
709
710 #[test]
711 fn env_truthy_accepts_common_true_spellings() {
712 for value in ["1", "true", "TRUE", " yes ", "on"] {
713 assert!(
714 env_truthy(Some(OsStr::new(value))),
715 "{value} should be truthy"
716 );
717 }
718 }
719
720 #[test]
721 fn env_truthy_rejects_falsey_and_missing_values() {
722 for value in [
723 None,
724 Some(OsStr::new("0")),
725 Some(OsStr::new("false")),
726 Some(OsStr::new("")),
727 ] {
728 assert!(!env_truthy(value));
729 }
730 }
731
732 #[test]
733 fn sanitize_wasm_rustflags_drops_unsupported_linker_args() {
734 let sanitized = sanitize_wasm_rustflags(
735 "-C opt-level=z -Wl,--export-table -C link-arg=--no-keep-memory -C link-arg=--threads=1",
736 );
737
738 assert_eq!(sanitized, "-C opt-level=z --export-table");
739 }
740
741 #[test]
742 fn path_string_relative_prefers_relative_path() {
743 let base = Path::new("/tmp/project");
744 let target = Path::new("/tmp/project/dist/component.wasm");
745
746 let relative = path_string_relative(base, target).expect("relative path");
747
748 assert_eq!(relative, "dist/component.wasm");
749 }
750
751 #[test]
752 fn resolve_wasm_path_uses_default_target_location_when_manifest_omits_artifact() {
753 let dir = tempfile::tempdir().expect("tempdir");
754 let target = dir
755 .path()
756 .join("target/wasm32-wasip2/release/com_greentic_demo.wasm");
757 std::fs::create_dir_all(target.parent().expect("target parent"))
758 .expect("create target dir");
759 std::fs::write(&target, b"wasm").expect("write wasm");
760
761 let manifest = json!({
762 "id": "com.greentic.demo"
763 });
764
765 let resolved = resolve_wasm_path(dir.path(), &manifest).expect("resolve default wasm path");
766 assert_eq!(resolved, target.canonicalize().expect("canonical target"));
767 }
768
769 #[test]
770 fn val_to_bytes_rejects_non_byte_lists() {
771 let err = val_to_bytes(&Val::List(vec![Val::String("oops".to_string())]))
772 .expect_err("non-u8 list should fail");
773 assert_eq!(err, "expected list<u8>");
774 }
775
776 #[test]
777 fn strip_self_describe_tag_removes_only_known_prefix() {
778 let tagged = [0xd9, 0xd9, 0xf7, 0x01, 0x02];
779 assert_eq!(strip_self_describe_tag(&tagged), &[0x01, 0x02]);
780 assert_eq!(strip_self_describe_tag(&[0x01, 0x02]), &[0x01, 0x02]);
781 }
782}