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
3 changes: 3 additions & 0 deletions .changelog/wasm-initialize.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Fixed

- Ensure `@tailwindcss/oxide-wasm32-wasi` loads instead of hanging forever (e.g. with `NAPI_RS_FORCE_WASI=error` or in WebContainers)
4 changes: 4 additions & 0 deletions .github/workflows/prepare-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,10 @@ jobs:
env:
FEATURES_ENV: stable

# Load the packed wasm package before it is published
- name: Test wasm package
run: pnpm run test:integrations ./integrations/oxide/wasm.test.ts

- name: Run pre-publish optimizations scripts
run: node ./scripts/pre-publish-optimizations.mjs

Expand Down
4 changes: 4 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,10 @@ jobs:
env:
FEATURES_ENV: ${{ env.FEATURES_ENV }}

# Load the packed wasm package before it is published
- name: Test wasm package
run: pnpm run test:integrations ./integrations/oxide/wasm.test.ts

- name: Run pre-publish optimizations scripts
run: node ./scripts/pre-publish-optimizations.mjs

Expand Down
45 changes: 45 additions & 0 deletions crates/node/build.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,50 @@
extern crate napi_build;

use std::{env, path::PathBuf, process::Command};

fn main() {
if env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("wasi") {
setup_wasi_rustc();
}

napi_build::setup();
}

/// `napi_build` links `crt1-reactor.o` and exports `_initialize` only if it finds the file at
/// `$RUSTC/../../lib/rustlib/<target>/lib/self-contained/crt1-reactor.o`. Otherwise it only prints
/// a warning, and the `.wasm` file hangs forever when it loads.
///
/// Cargo can give a bare `rustc` in `$RUSTC` (when it finds `rustc` in the `PATH`), so point it at
/// the `rustc` of the sysroot instead, and fail the build when the file does not exist.
fn setup_wasi_rustc() {
let rustc = env::var("RUSTC").expect("RUSTC must be set by Cargo");
let target = env::var("TARGET").expect("TARGET must be set by Cargo");

let output = Command::new(&rustc)
.args(["--print", "sysroot"])
.output()
.unwrap_or_else(|err| panic!("Could not run `{rustc} --print sysroot`: {err}"));
if !output.status.success() {
panic!(
"`{rustc} --print sysroot` failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
let sysroot = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());

let crt_reactor_path = sysroot
.join("lib")
.join("rustlib")
.join(&target)
.join("lib")
.join("self-contained")
.join("crt1-reactor.o");
if !crt_reactor_path.exists() {
panic!(
"crt1-reactor.o not found at {}. Without it, the wasm module hangs when it loads. Run `rustup target add {target}`.",
crt_reactor_path.display()
);
}

env::set_var("RUSTC", sysroot.join("bin").join("rustc"));
}
67 changes: 67 additions & 0 deletions integrations/oxide/wasm.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,3 +241,70 @@ testFn(
`)
},
)

// This test doesn't read files through WASI, so it also runs on macOS, where
// the release workflow builds the wasm package. The release workflow runs it
// before it publishes.
let testFnWithoutFs = process.platform === 'win32' ? test.skip : test

testFnWithoutFs(
'`@tailwindcss/oxide` loads the wasm build without hanging when `NAPI_RS_FORCE_WASI=error` is set',
{
fs: {
'package.json': json`
{
"dependencies": {
"@tailwindcss/oxide": "workspace:^"
}
}
`,
'index.cjs': js`
let fs = require('node:fs')
let path = require('node:path')
let { Scanner } = require('@tailwindcss/oxide')

let wasi = Object.keys(require.cache).find((file) =>
file.endsWith('tailwindcss-oxide.wasi.cjs'),
)
let wasm = fs.readFileSync(
path.join(path.dirname(wasi), 'tailwindcss-oxide.wasm32-wasi.wasm'),
)
let scanner = new Scanner({ sources: [] })

console.log(
JSON.stringify({
exports: WebAssembly.Module.exports(new WebAssembly.Module(wasm)).map((e) => e.name),
candidates: scanner.scanFiles([
{ content: '<div class="flex underline">', extension: 'html' },
]),
}),
)
process.exit()
`,
},
},
async ({ expect, exec }) => {
// Without `_initialize`, the thread setup of wasi-libc never runs, and
// loading the wasm module hangs forever (this shipped in v4.3.4). See
// `crates/node/build.rs`.
//
// See the note about NODE_PATH in the tests above.
let output = await exec('node index.cjs', {
env: { NAPI_RS_FORCE_WASI: 'error', NODE_PATH: '' },
timeout: 10_000,
})

// Only parse the first line, because Node can print an
// `ExperimentalWarning` about WASI to stderr.
let { exports, candidates } = JSON.parse(output.trim().split('\n')[0])

expect(exports).toContain('_initialize')
expect(candidates).toMatchInlineSnapshot(`
[
"class",
"flex",
"underline",
]
`)
},
)
7 changes: 7 additions & 0 deletions integrations/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ interface SpawnedProcess {
interface ChildProcessOptions {
cwd?: string
env?: Record<string, string>

// Kill the command after this many milliseconds, for example when it can
// hang forever.
timeout?: number
}

interface ExecOptions {
Expand Down Expand Up @@ -208,6 +212,9 @@ export function test(
let mappedError = error as any
mappedError.cmd = originalCommand
}
if (error.killed && childProcessOptions.timeout) {
error.message += `\nKilled after ${childProcessOptions.timeout}ms`
}
if (execOptions.ignoreStdErr !== true) console.error(stderr)
if (only || debug) {
console.error(stdout)
Expand Down
Loading