Skip to content
Open
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/oxide-browser-build.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Added

- Add a single-threaded browser build to `@tailwindcss/oxide-wasm32-wasi` that scans an in-memory filesystem without `SharedArrayBuffer` or COOP/COEP headers
2 changes: 1 addition & 1 deletion .github/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pnpm install

# Install Rust toolchain and WASM targets
rustup default stable
rustup target add wasm32-wasip1-threads
rustup target add wasm32-wasip1 wasm32-wasip1-threads

# Build the project
pnpm build
Expand Down
4 changes: 3 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,12 @@ jobs:
./crates/node/tailwindcss-oxide.wasi.cjs
./crates/node/wasi-worker-browser.mjs
./crates/node/wasi-worker.mjs
./crates/node/npm/wasm32-wasi/*.wasm
./crates/node/npm/wasm32-wasi/index.d.ts
key: ${{ runner.os }}-oxide-${{ hashFiles('./crates/**/*') }}

- name: Setup WASM target
run: rustup target add wasm32-wasip1-threads
run: rustup target add wasm32-wasip1 wasm32-wasip1-threads

- name: Install dependencies
run: pnpm install --frozen-lockfile
Expand Down
4 changes: 3 additions & 1 deletion .github/workflows/integration-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,12 @@ jobs:
./crates/node/tailwindcss-oxide.wasi.cjs
./crates/node/wasi-worker-browser.mjs
./crates/node/wasi-worker.mjs
./crates/node/npm/wasm32-wasi/*.wasm
./crates/node/npm/wasm32-wasi/index.d.ts
key: ${{ runner.os }}-oxide-${{ hashFiles('./crates/**/*') }}

- name: Setup WASM target
run: rustup target add wasm32-wasip1-threads
run: rustup target add wasm32-wasip1 wasm32-wasip1-threads

- name: Install dependencies
run: pnpm install
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/prepare-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ jobs:
package-manager-cache: false

- name: Setup WASM target
run: rustup target add wasm32-wasip1-threads
run: rustup target add wasm32-wasip1 wasm32-wasip1-threads

- name: Install dependencies
run: pnpm --filter=!./playgrounds/* install --frozen-lockfile
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ jobs:
fi

- name: Setup WASM target
run: rustup target add wasm32-wasip1-threads
run: rustup target add wasm32-wasip1 wasm32-wasip1-threads

- name: Install dependencies
run: pnpm --filter=!./playgrounds/* install --frozen-lockfile
Expand Down
2 changes: 2 additions & 0 deletions crates/node/browser.d.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from '@tailwindcss/oxide-wasm32-wasi/browser.mjs'
export { default } from '@tailwindcss/oxide-wasm32-wasi/browser.mjs'
3 changes: 3 additions & 0 deletions crates/node/browser.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// A bare import would resolve to the Node.js loader in resolvers that ignore the `browser` field.
export * from '@tailwindcss/oxide-wasm32-wasi/browser.mjs'
export { default } from '@tailwindcss/oxide-wasm32-wasi/browser.mjs'
41 changes: 40 additions & 1 deletion crates/node/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,58 @@ extern crate napi_build;
use std::{env, path::PathBuf, process::Command};

fn main() {
if env::var("TARGET").as_deref() == Ok("wasm32-wasip1") {
setup_browser();
return;
}

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

napi_build::setup();
}

/// The pinned napi-build only configures the threaded WASI target. Browser builds must link
/// emnapi's single-threaded archive and must not import shared memory or worker entry points.
fn setup_browser() {
println!("cargo:rerun-if-env-changed=EMNAPI_LINK_DIR");
// Unset for `cargo check`, `cargo clippy` and rust-analyzer, which don't link.
let Ok(link_dir) = env::var("EMNAPI_LINK_DIR") else {
println!("cargo:warning=EMNAPI_LINK_DIR is not set; use `pnpm run build:browser`");
return;
};

let reactor = setup_wasi_rustc();
println!("cargo:rustc-link-search={link_dir}");
println!("cargo:rustc-link-lib=static=emnapi-basic");

for arg in [
"--export=malloc",
"--export=free",
"--export=napi_register_wasm_v1",
"--export-if-defined=node_api_module_get_api_version_v1",
"--export-table",
"--import-memory",
"--import-undefined",
"--max-memory=4294967296",
// 8 MB, like a native main thread. The threaded build uses napi's 64 MB.
"-zstack-size=8388608",
"--export=_initialize",
] {
println!("cargo:rustc-link-arg={arg}");
}

println!("cargo:rustc-link-arg={}", reactor.display());
}

/// `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() {
fn setup_wasi_rustc() -> PathBuf {
let rustc = env::var("RUSTC").expect("RUSTC must be set by Cargo");
let target = env::var("TARGET").expect("TARGET must be set by Cargo");

Expand Down Expand Up @@ -47,4 +85,5 @@ fn setup_wasi_rustc() {
}

env::set_var("RUSTC", sysroot.join("bin").join("rustc"));
crt_reactor_path
}
28 changes: 27 additions & 1 deletion crates/node/npm/wasm32-wasi/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,29 @@
# `@tailwindcss/oxide-wasm32-wasi`

This is the **wasm32-wasip1-threads** build of `@tailwindcss/oxide`
The WebAssembly build of `@tailwindcss/oxide`.

- **Node.js** loads the threaded `wasm32-wasip1-threads` build.
- **Browsers** load `browser.mjs`, a single-threaded `wasm32-wasip1` build that needs no `SharedArrayBuffer`, workers, or COOP/COEP headers.

## Browser usage

The browser build scans an in-memory filesystem, not the user's disk. Its entry also exports `__fs` and `__volume`, the [memfs](https://github.com/streamich/memfs) filesystem and volume.

```js
import { Scanner, __fs } from '@tailwindcss/oxide-wasm32-wasi/browser.mjs'

// Scan content directly
let scanner = new Scanner({})
scanner.scanFiles([{ content: '<div class="flex">', extension: 'html' }]) // ['class', 'flex']

// Or write files to memfs and scan them
__fs.mkdirSync('/src', { recursive: true })
__fs.writeFileSync('/src/index.html', '<div class="grid">')

let fsScanner = new Scanner({ sources: [{ base: '/src', pattern: '**/*', negated: false }] })
fsScanner.scan() // ['class', 'grid']
```

The bundler must support ESM, top-level `await`, and `new URL('…', import.meta.url)` asset references. With bundlers that don't (such as esbuild), copy `tailwindcss-oxide.browser.wasm` next to the bundled JavaScript.

Scanning is synchronous. For larger inputs, run it in a module worker to keep the UI responsive.
12 changes: 12 additions & 0 deletions crates/node/npm/wasm32-wasi/browser.d.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import * as binding from './index.js'

export * from './index.js'

/** The memfs `fs` the browser build scans, with a Node.js `fs`-like API. */
export declare const __fs: Record<string, any>

/** The memfs volume backing `__fs`. */
export declare const __volume: Record<string, any>

declare const _default: typeof binding
export default _default
37 changes: 37 additions & 0 deletions crates/node/npm/wasm32-wasi/browser.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { getDefaultContext, instantiateNapiModule, WASI } from '@napi-rs/wasm-runtime'
import { memfs } from '@napi-rs/wasm-runtime/fs'

export const { fs: __fs, vol: __volume } = memfs()

let wasi = new WASI({
version: 'preview1',
fs: __fs,
preopens: { '/': '/' },
})

// Non-shared memory, so no SharedArrayBuffer is needed. `scripts/build-browser.mjs` reads this
// constant to check that the module fits.
const INITIAL_MEMORY_PAGES = 256
let memory = new WebAssembly.Memory({ initial: INITIAL_MEMORY_PAGES, maximum: 65536 })
let response = await fetch(new URL('./tailwindcss-oxide.browser.wasm', import.meta.url))
if (!response.ok) throw new Error(`Failed to load Oxide WebAssembly: ${response.status}`)

// Compile asynchronously, so loading doesn't block the page (Chrome also rejects synchronous
// compiles of modules over 8 MB on the main thread).
let { napiModule } = await instantiateNapiModule(response, {
context: getDefaultContext(),
wasi,
asyncWorkPoolSize: 0,
overwriteImports(imports) {
imports.env = { ...imports.env, ...imports.napi, ...imports.emnapi, memory }
return imports
},
beforeInit({ instance }) {
for (let name of Object.keys(instance.exports)) {
if (name.startsWith('__napi_register__')) instance.exports[name]()
}
},
})

export const { Scanner } = napiModule.exports
export default napiModule.exports
7 changes: 6 additions & 1 deletion crates/node/npm/wasm32-wasi/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,13 @@
"name": "@tailwindcss/oxide-wasm32-wasi",
"version": "4.3.5",
"main": "tailwindcss-oxide.wasi.cjs",
"types": "index.d.ts",
"files": [
"tailwindcss-oxide.wasm32-wasi.wasm",
"tailwindcss-oxide.browser.wasm",
"browser.mjs",
"browser.d.mts",
"index.d.ts",
"tailwindcss-oxide.wasi.cjs",
"tailwindcss-oxide.wasi-browser.js",
"wasi-worker.mjs",
Expand All @@ -22,7 +27,7 @@
"url": "git+https://github.com/tailwindlabs/tailwindcss.git",
"directory": "crates/node"
},
"browser": "tailwindcss-oxide.wasi-browser.js",
"browser": "browser.mjs",
"dependencies": {
"@napi-rs/wasm-runtime": "^1.2.2",
"@emnapi/core": "^1.11.3",
Expand Down
9 changes: 7 additions & 2 deletions crates/node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"directory": "crates/node"
},
"main": "index.js",
"browser": "./browser.mjs",
"types": "index.d.ts",
"napi": {
"binaryName": "tailwindcss-oxide",
Expand Down Expand Up @@ -44,19 +45,23 @@
},
"files": [
"index.js",
"browser.mjs",
"browser.d.mts",
"index.d.ts"
],
"publishConfig": {
"provenance": true,
"access": "public"
},
"scripts": {
"build": "pnpm run build:platform && pnpm run build:wasm",
"build": "pnpm run build:platform && pnpm run build:wasm && pnpm run build:browser",
"build:platform": "napi build --platform --release",
"postbuild:platform": "node ./scripts/move-artifacts.mjs",
"build:wasm": "napi build --release --target wasm32-wasip1-threads",
"postbuild:wasm": "node ./scripts/move-artifacts.mjs",
"dev": "cargo watch --quiet --shell 'npm run build'",
"build:browser": "node ./scripts/build-browser.mjs",
"test:ui": "playwright test",
"dev": "cargo watch --quiet --shell 'npm run build:platform'",
"build:debug": "napi build --platform",
"version": "napi version"
},
Expand Down
13 changes: 13 additions & 0 deletions crates/node/playwright.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { defineConfig } from '@playwright/test'

export default defineConfig({
testDir: './tests',
forbidOnly: !!process.env.CI,
projects: [
{ name: 'chromium', use: { browserName: 'chromium' } },
{ name: 'firefox', use: { browserName: 'firefox' } },
...(process.platform === 'win32'
? []
: [{ name: 'webkit', use: { browserName: 'webkit' as const } }]),
],
})
63 changes: 63 additions & 0 deletions crates/node/scripts/build-browser.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { spawnSync } from 'node:child_process'
import fs from 'node:fs/promises'
import { fileURLToPath } from 'node:url'

// The pinned NAPI CLI only supports wasm32-wasip1-threads. Build the same bindings with
// Cargo directly so browsers can use them without shared memory or cross-origin isolation.
let root = fileURLToPath(new URL('../../../', import.meta.url))
let linkDir = fileURLToPath(new URL('./lib/wasm32-wasip1', import.meta.resolve('emnapi')))
let result = spawnSync(
'cargo',
[
'build',
'--release',
'--locked',
'--package',
'tailwind-oxide',
'--target',
'wasm32-wasip1',
'--message-format=json-render-diagnostics',
],
{
cwd: root,
stdio: ['inherit', 'pipe', 'inherit'],
encoding: 'utf8',
maxBuffer: 256 * 1024 * 1024,
env: { ...process.env, EMNAPI_LINK_DIR: linkDir },
},
)
if (result.error) throw result.error
if (result.status !== 0) process.exit(result.status ?? 1)

// Read the artifact path from Cargo, since its target directory can be configured elsewhere.
let wasmPaths = result.stdout
.split('\n')
.filter((line) => line.startsWith('{'))
.map((line) => JSON.parse(line))
.filter((message) => message.reason === 'compiler-artifact')
.filter((message) => message.target.kind.includes('cdylib'))
.flatMap((message) => message.filenames.filter((file) => file.endsWith('.wasm')))
if (wasmPaths.length !== 1) {
throw new Error(`Expected one .wasm artifact from Cargo, got: ${JSON.stringify(wasmPaths)}`)
}
let wasm = await fs.readFile(wasmPaths[0])

// Link the module against the memory `browser.mjs` creates, so a module that needs more memory
// (or shared memory) fails the build instead of failing in every browser.
let loader = await fs.readFile(new URL('../npm/wasm32-wasi/browser.mjs', import.meta.url), 'utf8')
let initial = Number(loader.match(/const INITIAL_MEMORY_PAGES = (\d+)/)?.[1])
let module = new WebAssembly.Module(wasm)
let imports = {}
for (let { module: namespace, name, kind } of WebAssembly.Module.imports(module)) {
imports[namespace] ??= {}
imports[namespace][name] =
kind === 'memory' ? new WebAssembly.Memory({ initial, maximum: 65536 }) : () => {}
}
if (!imports.env?.memory) throw new Error('The browser build must import `env.memory`')
new WebAssembly.Instance(module, imports)

await fs.writeFile(
new URL('../npm/wasm32-wasi/tailwindcss-oxide.browser.wasm', import.meta.url),
wasm,
)
console.log(`Copied ${wasmPaths[0]} to npm/wasm32-wasi/tailwindcss-oxide.browser.wasm`)
1 change: 1 addition & 0 deletions crates/node/scripts/move-artifacts.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ for (let file of await fs.readdir(tailwindcssOxideRoot)) {
let wasmArtifacts = {
'tailwindcss-oxide.debug.wasm': 'tailwindcss-oxide.wasm32-wasi.debug.wasm',
'tailwindcss-oxide.wasm': 'tailwindcss-oxide.wasm32-wasi.wasm',
'index.d.ts': 'index.d.ts',
'tailwindcss-oxide.wasi-browser.js': 'tailwindcss-oxide.wasi-browser.js',
'tailwindcss-oxide.wasi.cjs': 'tailwindcss-oxide.wasi.cjs',
'wasi-worker-browser.mjs': 'wasi-worker-browser.mjs',
Expand Down
Loading