From 2956958bee5a6f83b5dbd06eaa4a09f4a5236587 Mon Sep 17 00:00:00 2001 From: jonathanpv Date: Sun, 5 Apr 2026 20:04:30 -0500 Subject: [PATCH] Support WebContainers in CLI and WASI runtime --- lib/index.mjs | 31 ++++++++++++++++++++++++++++--- lib/rg.mjs | 9 +++++++-- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/lib/index.mjs b/lib/index.mjs index 24703c5..cca1d9c 100644 --- a/lib/index.mjs +++ b/lib/index.mjs @@ -7,8 +7,7 @@ export async function ripgrep(args = [], options = {}) { env = process.env, preopens = { ".": process.cwd() }, returnOnExit = true, - nodeWasi = process.env.ZIGREP_NODE_WASI === "1" || - (!("Bun" in globalThis) && !("Deno" in globalThis)), + nodeWasi = getDefaultNodeWasi(), } = options; // ripgrep's TTY auto-detection doesn't work through WASI preview1, so it @@ -21,9 +20,10 @@ export async function ripgrep(args = [], options = {}) { args = ["--color=ansi", ...args]; } - const wasi = await (nodeWasi ? createNodeWasi : createWasiShim)({ + const wasi = await createWasiRuntime({ args, env, + nodeWasi, preopens, returnOnExit, }); @@ -47,6 +47,31 @@ function getRgWasmModule() { return rgWasmModulePromise; } +function getDefaultNodeWasi() { + if (process.env.ZIGREP_NODE_WASI === "1") return true; + if (process.env.ZIGREP_NODE_WASI === "0") return false; + return !("Bun" in globalThis) && !("Deno" in globalThis); +} + +async function createWasiRuntime({ + args, + env, + nodeWasi, + preopens, + returnOnExit, +}) { + const config = { args, env, preopens, returnOnExit }; + if (!nodeWasi) return createWasiShim(config); + + try { + return await createNodeWasi(config); + } catch { + // Browser-hosted Node environments can expose `node:wasi` but still fail + // at construction or start-up. Fall back to the portable JS shim. + return createWasiShim(config); + } +} + // Custom WASI preview1 shim (see `_wasi.mjs`). Lazy-imported so consumers // that only touch `rgPath` don't pay for loading it. async function createWasiShim({ args, env, preopens, returnOnExit }) { diff --git a/lib/rg.mjs b/lib/rg.mjs index 547014e..5faeeb8 100755 --- a/lib/rg.mjs +++ b/lib/rg.mjs @@ -1,7 +1,12 @@ #!/usr/bin/env node -import module from "node:module"; -module.enableCompileCache?.(); +try { + const { enableCompileCache } = await import("node:module"); + enableCompileCache?.(); +} catch { + // Some Node-compatible hosts implement enough ESM to run us but not enough + // of Node's module compile cache internals to make this safe. +} const { ripgrep } = await import("./index.mjs"); let argv = process.argv.slice(2);