Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 28 additions & 3 deletions lib/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
});
Expand All @@ -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 }) {
Expand Down
9 changes: 7 additions & 2 deletions lib/rg.mjs
Original file line number Diff line number Diff line change
@@ -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);
Expand Down
Loading