|
| 1 | +"""Validate and finish the generated Multilingual WASM bundle.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import argparse |
| 6 | +import shutil |
| 7 | +from pathlib import Path |
| 8 | + |
| 9 | + |
| 10 | +REQUIRED_FILES = ( |
| 11 | + "module.wasm", |
| 12 | + "abi_manifest.json", |
| 13 | + "host_shim.mjs", |
| 14 | +) |
| 15 | + |
| 16 | + |
| 17 | +def print_listing(out_dir: Path) -> None: |
| 18 | + """Print a compact directory listing for CI logs.""" |
| 19 | + print(f"Generated bundle contents in {out_dir}:") |
| 20 | + if not out_dir.exists(): |
| 21 | + print(" <missing directory>") |
| 22 | + return |
| 23 | + for path in sorted(out_dir.iterdir()): |
| 24 | + if path.is_file(): |
| 25 | + print(f" {path.name} ({path.stat().st_size} bytes)") |
| 26 | + else: |
| 27 | + print(f" {path.name}/") |
| 28 | + |
| 29 | + |
| 30 | +def ensure_host_shim_mjs(out_dir: Path) -> None: |
| 31 | + """Create the ESM host shim expected by the browser loader.""" |
| 32 | + js_path = out_dir / "host_shim.js" |
| 33 | + mjs_path = out_dir / "host_shim.mjs" |
| 34 | + if not mjs_path.exists() and js_path.exists(): |
| 35 | + shutil.copyfile(js_path, mjs_path) |
| 36 | + print(f"Created {mjs_path} from {js_path}") |
| 37 | + |
| 38 | + |
| 39 | +def ensure_wasm_from_wat(out_dir: Path) -> None: |
| 40 | + """Compile module.wat when a toolchain emits WAT but not WASM.""" |
| 41 | + wasm_path = out_dir / "module.wasm" |
| 42 | + wat_path = out_dir / "module.wat" |
| 43 | + if wasm_path.exists() or not wat_path.exists(): |
| 44 | + return |
| 45 | + |
| 46 | + try: |
| 47 | + from wasmtime import wat2wasm # pylint: disable=import-outside-toplevel |
| 48 | + except Exception as exc: # pragma: no cover - only hit in CI dependency breakage |
| 49 | + raise RuntimeError( |
| 50 | + "module.wasm is missing and wasmtime.wat2wasm is unavailable" |
| 51 | + ) from exc |
| 52 | + |
| 53 | + wasm_path.write_bytes(wat2wasm(wat_path.read_text(encoding="utf-8"))) |
| 54 | + print(f"Created {wasm_path} from {wat_path}") |
| 55 | + |
| 56 | + |
| 57 | +def validate(out_dir: Path) -> None: |
| 58 | + """Fail if the generated bundle is missing files consumed by the app.""" |
| 59 | + missing = [name for name in REQUIRED_FILES if not (out_dir / name).is_file()] |
| 60 | + if missing: |
| 61 | + print_listing(out_dir) |
| 62 | + raise SystemExit(f"Missing generated WASM bundle file(s): {', '.join(missing)}") |
| 63 | + |
| 64 | + |
| 65 | +def main() -> None: |
| 66 | + """Run bundle completion and validation.""" |
| 67 | + parser = argparse.ArgumentParser() |
| 68 | + parser.add_argument("out_dir", type=Path) |
| 69 | + args = parser.parse_args() |
| 70 | + |
| 71 | + out_dir = args.out_dir |
| 72 | + ensure_host_shim_mjs(out_dir) |
| 73 | + ensure_wasm_from_wat(out_dir) |
| 74 | + print_listing(out_dir) |
| 75 | + validate(out_dir) |
| 76 | + |
| 77 | + |
| 78 | +if __name__ == "__main__": |
| 79 | + main() |
0 commit comments