From 4f6bd30c4583f8eafe13ba57cfd1a8394b9e3013 Mon Sep 17 00:00:00 2001 From: Joshua Gugun Siagian Date: Tue, 10 Nov 2026 00:18:39 +0700 Subject: [PATCH 1/3] Add a single-threaded browser build of `@tailwindcss/oxide` The threaded WASI build needs `SharedArrayBuffer`, which browsers only expose on cross-origin isolated pages (COOP/COEP headers). Add a separate `wasm32-wasip1` build for browsers that runs on the calling thread and scans an in-memory filesystem (memfs). - `scripts/build-browser.mjs` builds it with Cargo directly, since the pinned NAPI CLI only builds `wasm32-wasip1-threads`. It reads the artifact path from Cargo and checks that the module links against the memory `browser.mjs` creates. - `build.rs` links emnapi's single-threaded archive for this target. - `@tailwindcss/oxide-wasm32-wasi` points `browser` at the new `browser.mjs`, ships its types, and no longer ships the unused threaded browser loader. - `@tailwindcss/oxide` gets a `browser` entry that re-exports it. - CI, release workflows and CONTRIBUTING.md install `wasm32-wasip1`. Co-Authored-By: Claude Opus 5.5 --- .changelog/oxide-browser-build.md | 3 + .github/CONTRIBUTING.md | 2 +- .github/workflows/ci.yml | 4 +- .github/workflows/integration-tests.yml | 4 +- .github/workflows/prepare-release.yml | 2 +- .github/workflows/release.yml | 2 +- crates/node/browser.d.mts | 2 + crates/node/browser.mjs | 3 + crates/node/build.rs | 40 ++++- crates/node/npm/wasm32-wasi/README.md | 28 +++- crates/node/npm/wasm32-wasi/browser.d.mts | 12 ++ crates/node/npm/wasm32-wasi/browser.mjs | 35 +++++ crates/node/npm/wasm32-wasi/package.json | 11 +- crates/node/package.json | 9 +- crates/node/playwright.config.ts | 13 ++ crates/node/scripts/build-browser.mjs | 63 ++++++++ crates/node/scripts/move-artifacts.mjs | 3 +- crates/node/tests/browser.spec.ts | 174 ++++++++++++++++++++++ crates/node/tests/fixtures/browser.mjs | 2 + integrations/oxide/wasm.test.ts | 49 ++++++ package.json | 2 +- turbo.json | 15 +- 22 files changed, 461 insertions(+), 17 deletions(-) create mode 100644 .changelog/oxide-browser-build.md create mode 100644 crates/node/browser.d.mts create mode 100644 crates/node/browser.mjs create mode 100644 crates/node/npm/wasm32-wasi/browser.d.mts create mode 100644 crates/node/npm/wasm32-wasi/browser.mjs create mode 100644 crates/node/playwright.config.ts create mode 100644 crates/node/scripts/build-browser.mjs create mode 100644 crates/node/tests/browser.spec.ts create mode 100644 crates/node/tests/fixtures/browser.mjs diff --git a/.changelog/oxide-browser-build.md b/.changelog/oxide-browser-build.md new file mode 100644 index 000000000000..bf9767bbf663 --- /dev/null +++ b/.changelog/oxide-browser-build.md @@ -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 diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index dd72b7a27863..f999bdaae8e8 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -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 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c96b35937a4d..85b32fa46c6b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/.github/workflows/integration-tests.yml b/.github/workflows/integration-tests.yml index a98015c71089..06e8daa95505 100644 --- a/.github/workflows/integration-tests.yml +++ b/.github/workflows/integration-tests.yml @@ -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 diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml index d1f970e02772..03c25f39d317 100644 --- a/.github/workflows/prepare-release.yml +++ b/.github/workflows/prepare-release.yml @@ -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 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b5c0a8440241..0c8ecb74fc5b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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 diff --git a/crates/node/browser.d.mts b/crates/node/browser.d.mts new file mode 100644 index 000000000000..6a6761dd33c0 --- /dev/null +++ b/crates/node/browser.d.mts @@ -0,0 +1,2 @@ +export * from '@tailwindcss/oxide-wasm32-wasi/browser.mjs' +export { default } from '@tailwindcss/oxide-wasm32-wasi/browser.mjs' diff --git a/crates/node/browser.mjs b/crates/node/browser.mjs new file mode 100644 index 000000000000..47a6ac4ee7bf --- /dev/null +++ b/crates/node/browser.mjs @@ -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' diff --git a/crates/node/build.rs b/crates/node/build.rs index 0d4b192ba277..ef99174afca8 100644 --- a/crates/node/build.rs +++ b/crates/node/build.rs @@ -3,6 +3,11 @@ 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(); } @@ -10,13 +15,45 @@ fn main() { 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", + "-zstack-size=64000000", + "--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//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"); @@ -47,4 +84,5 @@ fn setup_wasi_rustc() { } env::set_var("RUSTC", sysroot.join("bin").join("rustc")); + crt_reactor_path } diff --git a/crates/node/npm/wasm32-wasi/README.md b/crates/node/npm/wasm32-wasi/README.md index 2a536814969d..68aa82cdea36 100644 --- a/crates/node/npm/wasm32-wasi/README.md +++ b/crates/node/npm/wasm32-wasi/README.md @@ -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: '
', extension: 'html' }]) // ['class', 'flex'] + +// Or write files to memfs and scan them +__fs.mkdirSync('/src', { recursive: true }) +__fs.writeFileSync('/src/index.html', '
') + +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. diff --git a/crates/node/npm/wasm32-wasi/browser.d.mts b/crates/node/npm/wasm32-wasi/browser.d.mts new file mode 100644 index 000000000000..1abd26b86abd --- /dev/null +++ b/crates/node/npm/wasm32-wasi/browser.d.mts @@ -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 + +/** The memfs volume backing `__fs`. */ +export declare const __volume: Record + +declare const _default: typeof binding +export default _default diff --git a/crates/node/npm/wasm32-wasi/browser.mjs b/crates/node/npm/wasm32-wasi/browser.mjs new file mode 100644 index 000000000000..f18c859db286 --- /dev/null +++ b/crates/node/npm/wasm32-wasi/browser.mjs @@ -0,0 +1,35 @@ +import { getDefaultContext, instantiateNapiModuleSync, 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 = 2048 +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}`) + +let { napiModule } = instantiateNapiModuleSync(await response.arrayBuffer(), { + 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 diff --git a/crates/node/npm/wasm32-wasi/package.json b/crates/node/npm/wasm32-wasi/package.json index 1385ed72ccbe..7aec257b2640 100644 --- a/crates/node/npm/wasm32-wasi/package.json +++ b/crates/node/npm/wasm32-wasi/package.json @@ -2,12 +2,15 @@ "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", - "wasi-worker-browser.mjs" + "wasi-worker.mjs" ], "license": "MIT", "engines": { @@ -22,7 +25,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", diff --git a/crates/node/package.json b/crates/node/package.json index 2eff27ae4034..865220b2e636 100644 --- a/crates/node/package.json +++ b/crates/node/package.json @@ -7,6 +7,7 @@ "directory": "crates/node" }, "main": "index.js", + "browser": "./browser.mjs", "types": "index.d.ts", "napi": { "binaryName": "tailwindcss-oxide", @@ -44,6 +45,8 @@ }, "files": [ "index.js", + "browser.mjs", + "browser.d.mts", "index.d.ts" ], "publishConfig": { @@ -51,12 +54,14 @@ "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" }, diff --git a/crates/node/playwright.config.ts b/crates/node/playwright.config.ts new file mode 100644 index 000000000000..aebd48c0ecb9 --- /dev/null +++ b/crates/node/playwright.config.ts @@ -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 } }]), + ], +}) diff --git a/crates/node/scripts/build-browser.mjs b/crates/node/scripts/build-browser.mjs new file mode 100644 index 000000000000..8c1721b630b1 --- /dev/null +++ b/crates/node/scripts/build-browser.mjs @@ -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`) diff --git a/crates/node/scripts/move-artifacts.mjs b/crates/node/scripts/move-artifacts.mjs index faf4728efc0a..0bf016f63de7 100644 --- a/crates/node/scripts/move-artifacts.mjs +++ b/crates/node/scripts/move-artifacts.mjs @@ -22,9 +22,8 @@ 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', - 'tailwindcss-oxide.wasi-browser.js': 'tailwindcss-oxide.wasi-browser.js', + 'index.d.ts': 'index.d.ts', 'tailwindcss-oxide.wasi.cjs': 'tailwindcss-oxide.wasi.cjs', - 'wasi-worker-browser.mjs': 'wasi-worker-browser.mjs', 'wasi-worker.mjs': 'wasi-worker.mjs', } for (let file of await fs.readdir(tailwindcssOxideRoot)) { diff --git a/crates/node/tests/browser.spec.ts b/crates/node/tests/browser.spec.ts new file mode 100644 index 000000000000..e2961d751bb7 --- /dev/null +++ b/crates/node/tests/browser.spec.ts @@ -0,0 +1,174 @@ +import { expect, test } from '@playwright/test' +import { once } from 'node:events' +import { mkdtemp, readFile, rm } from 'node:fs/promises' +import { createServer, type Server } from 'node:http' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { build } from 'tsup' + +let server: Server +let output: string +let origin: string + +test.beforeAll(async () => { + output = await mkdtemp(path.join(tmpdir(), 'oxide-browser-')) + await build({ + entry: { browser: path.join(__dirname, 'fixtures/browser.mjs') }, + outDir: output, + format: ['esm'], + platform: 'browser', + target: 'esnext', + noExternal: [/.*/], + config: false, + silent: true, + }) + + let script = await readFile(path.join(output, 'browser.mjs')) + let wasm = await readFile( + path.join(__dirname, '../npm/wasm32-wasi/tailwindcss-oxide.browser.wasm'), + ) + // Deliberately serve without COOP/COEP: this is the deployment we need to support. + server = createServer((req, res) => { + if (req.url === '/browser.mjs') { + res.setHeader('Content-Type', 'text/javascript') + res.end(script) + } else if (req.url === '/tailwindcss-oxide.browser.wasm') { + res.setHeader('Content-Type', 'application/wasm') + res.end(wasm) + } else if (req.url === '/worker.mjs') { + res.setHeader('Content-Type', 'text/javascript') + res.end(` + import { Scanner } from './browser.mjs' + let scanner = new Scanner({ sources: [] }) + postMessage({ + sharedArrayBuffer: typeof SharedArrayBuffer, + candidates: scanner.scanFiles([{ content: 'flex grid', extension: 'html' }]), + }) + `) + } else { + res.setHeader('Content-Type', 'text/html') + res.end('Oxide browser test') + } + }) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + let address = server.address() + if (!address || typeof address === 'string') throw new Error('Missing server address') + origin = `http://127.0.0.1:${address.port}` +}) + +test.afterAll(async () => { + if (server) await new Promise((resolve) => server.close(() => resolve())) + if (output) await rm(output, { recursive: true, force: true }) +}) + +test.beforeEach(async ({ page }) => { + await page.goto(origin) + expect(await page.evaluate(() => crossOriginIsolated)).toBe(false) + expect(await page.evaluate(() => typeof SharedArrayBuffer)).toBe('undefined') +}) + +test('extracts candidates and UTF-16 positions without shared memory or workers', async ({ + page, +}) => { + await page.addInitScript(() => { + globalThis.Worker = class { + constructor() { + throw new Error('The single-threaded browser build must not create workers') + } + } as unknown as typeof Worker + }) + await page.reload() + + let result = await page.evaluate(async () => { + let { Scanner } = await import('/browser.mjs') + let scanner = new Scanner({ sources: [] }) + return { + candidates: scanner.scanFiles([ + { content: '
', extension: 'html' }, + ]), + incremental: scanner.scanFiles([{ content: '
', extension: 'html' }]), + positions: scanner.getCandidatesWithPositions({ content: '😀 flex', extension: 'html' }), + } + }) + expect(result).toEqual({ + candidates: ['class', 'flex', 'underline'], + incremental: ['grid'], + positions: [{ candidate: 'flex', position: 3 }], + }) +}) + +test('discovers memfs files and tracks incremental changes', async ({ page }) => { + let result = await page.evaluate(async () => { + let { Scanner, __fs, __volume } = await import('/browser.mjs') + __volume.fromJSON({ '/src/index.html': '
' }) + let scanner = new Scanner({ + sources: [{ base: '/src', pattern: '**/*', negated: false }], + }) + function scan() { + return { + candidates: scanner.scan(), + files: scanner.files.sort(), + scannedFiles: scanner.scannedFiles.sort(), + } + } + let initial = scan() + let unchanged = scan() + __fs.writeFileSync('/src/index.html', '
') + __fs.utimesSync('/src/index.html', new Date(), new Date(Date.now() + 2000)) + let changed = scan() + __fs.mkdirSync('/src/nested') + __fs.writeFileSync('/src/nested/index.html', '
') + let added = scan() + return { + initial, + unchanged, + changed, + added, + sources: scanner.normalizedSources, + globs: scanner.globs, + } + }) + + expect(result).toEqual({ + initial: { + candidates: ['class', 'flex'], + files: ['/src/index.html'], + scannedFiles: ['/src/index.html'], + }, + unchanged: { candidates: ['class', 'flex'], files: ['/src/index.html'], scannedFiles: [] }, + changed: { + candidates: ['class', 'flex', 'grid'], + files: ['/src/index.html'], + scannedFiles: ['/src/index.html'], + }, + added: { + candidates: ['class', 'flex', 'grid', 'underline'], + files: ['/src/index.html', '/src/nested/index.html'], + scannedFiles: ['/src/nested/index.html'], + }, + sources: [{ base: '/src', pattern: '**/*' }], + globs: [ + { base: '/src', pattern: '*' }, + { base: '/src/nested', pattern: expect.stringContaining('html') }, + ], + }) +}) + +test('can run in an application-owned worker without isolation', async ({ page }) => { + let result = await page.evaluate( + () => + new Promise((resolve, reject) => { + let worker = new Worker('/worker.mjs', { type: 'module' }) + worker.onmessage = ({ data }) => { + worker.terminate() + resolve(data) + } + worker.onerror = (event) => { + worker.terminate() + reject(new Error(event.message)) + } + }), + ) + expect(result).toEqual({ sharedArrayBuffer: 'undefined', candidates: ['flex', 'grid'] }) +}) diff --git a/crates/node/tests/fixtures/browser.mjs b/crates/node/tests/fixtures/browser.mjs new file mode 100644 index 000000000000..0db4c270c64f --- /dev/null +++ b/crates/node/tests/fixtures/browser.mjs @@ -0,0 +1,2 @@ +// Resolve the package directory's browser field, just as a consuming application would. +export { Scanner, __fs, __volume } from '../..' diff --git a/integrations/oxide/wasm.test.ts b/integrations/oxide/wasm.test.ts index f60bbfeef6af..3ee95a2ee554 100644 --- a/integrations/oxide/wasm.test.ts +++ b/integrations/oxide/wasm.test.ts @@ -11,6 +11,55 @@ import { css, js, json, test, yaml } from '../utils' let testFn = process.platform === 'linux' ? test : test.skip +test( + 'the packed browser build scans memfs without SharedArrayBuffer', + { + fs: { + 'package.json': json` + { + "dependencies": { + "@tailwindcss/oxide-wasm32-wasi": "workspace:^" + } + } + `, + 'index.mjs': js` + import { readFile } from 'node:fs/promises' + import { fileURLToPath } from 'node:url' + + // Serve the browser loader's relative WASM URL without a browser server. + globalThis.fetch = async (url) => new Response(await readFile(fileURLToPath(url))) + globalThis.SharedArrayBuffer = undefined + + let { Scanner, __fs } = await import('@tailwindcss/oxide-wasm32-wasi/browser.mjs') + + __fs.mkdirSync('/src') + __fs.writeFileSync('/src/index.html', '
') + + let scanner = new Scanner({ + sources: [{ base: '/src', pattern: '**/*', negated: false }], + }) + let initial = scanner.scan() + scanner.scan() + + console.log( + JSON.stringify({ + initial, + unchanged: scanner.scannedFiles, + incremental: scanner.scanFiles([{ content: 'flex grid', extension: 'html' }]), + }), + ) + `, + }, + }, + async ({ expect, exec }) => { + expect(JSON.parse(await exec('node index.mjs', { timeout: 10_000 }))).toEqual({ + initial: ['class', 'flex', 'underline'], + unchanged: [], + incremental: ['grid'], + }) + }, +) + testFn( '@tailwindcss/oxide-wasm32-wasi can be loaded into a Node.js process', { diff --git a/package.json b/package.json index 92bfe7c8c949..5feb110f471b 100644 --- a/package.json +++ b/package.json @@ -39,7 +39,7 @@ "dev": "turbo dev --filter=!./playgrounds/*", "test": "cargo test && vitest run --hideSkippedTests", "test:integrations": "vitest --root=./integrations", - "test:ui": "pnpm run --filter=tailwindcss test:ui && pnpm run --filter=@tailwindcss/browser test:ui", + "test:ui": "pnpm run --filter=tailwindcss test:ui && pnpm run --filter=@tailwindcss/browser test:ui && pnpm run --filter=@tailwindcss/oxide test:ui", "tdd": "vitest --hideSkippedTests", "bench": "vitest bench", "version-packages": "node ./scripts/version-packages.mjs", diff --git a/turbo.json b/turbo.json index e3452efaeabc..97fe011a2637 100644 --- a/turbo.json +++ b/turbo.json @@ -4,10 +4,23 @@ "tasks": { "@tailwindcss/oxide#build": { "dependsOn": ["^build"], - "outputs": ["./index.d.ts", "./index.js", "./*.node"], + "outputs": [ + "./index.d.ts", + "./index.js", + "./*.node", + "./*.wasm", + "./tailwindcss-oxide.wasi*", + "./wasi-worker*", + "./npm/wasm32-wasi/*.wasm", + "./npm/wasm32-wasi/index.d.ts", + "./npm/wasm32-wasi/tailwindcss-oxide.wasi*", + "./npm/wasm32-wasi/wasi-worker*" + ], "inputs": [ "./src/**/*", "./build.rs", + "./scripts/**/*", + "./npm/wasm32-wasi/browser.mjs", "./package.json", "./Cargo.toml", "./.cargo/config.toml", From c46573bdc397e6369a3afb1c90a447f2ac65517a Mon Sep 17 00:00:00 2001 From: Joshua Gugun Siagian Date: Tue, 10 Nov 2026 00:59:37 +0700 Subject: [PATCH 2/3] Keep publishing the threaded browser loader Code that imports `tailwindcss-oxide.wasi-browser.js` by path, for example on cross-origin isolated pages, keeps working. Document it as an opt-in for parallel scanning. Co-Authored-By: Claude Opus 5.5 --- crates/node/npm/wasm32-wasi/README.md | 2 ++ crates/node/npm/wasm32-wasi/package.json | 4 +++- crates/node/scripts/move-artifacts.mjs | 2 ++ 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/node/npm/wasm32-wasi/README.md b/crates/node/npm/wasm32-wasi/README.md index 68aa82cdea36..fc6eebf48eb8 100644 --- a/crates/node/npm/wasm32-wasi/README.md +++ b/crates/node/npm/wasm32-wasi/README.md @@ -26,4 +26,6 @@ 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. +On cross-origin isolated pages (COOP/COEP headers), import `@tailwindcss/oxide-wasm32-wasi/tailwindcss-oxide.wasi-browser.js` instead to scan in parallel on the threaded build. It uses `SharedArrayBuffer` and Web Workers, and the bundler must also serve `wasi-worker-browser.mjs`. + Scanning is synchronous. For larger inputs, run it in a module worker to keep the UI responsive. diff --git a/crates/node/npm/wasm32-wasi/package.json b/crates/node/npm/wasm32-wasi/package.json index 7aec257b2640..8f148a22b713 100644 --- a/crates/node/npm/wasm32-wasi/package.json +++ b/crates/node/npm/wasm32-wasi/package.json @@ -10,7 +10,9 @@ "browser.d.mts", "index.d.ts", "tailwindcss-oxide.wasi.cjs", - "wasi-worker.mjs" + "tailwindcss-oxide.wasi-browser.js", + "wasi-worker.mjs", + "wasi-worker-browser.mjs" ], "license": "MIT", "engines": { diff --git a/crates/node/scripts/move-artifacts.mjs b/crates/node/scripts/move-artifacts.mjs index 0bf016f63de7..67e213be71ca 100644 --- a/crates/node/scripts/move-artifacts.mjs +++ b/crates/node/scripts/move-artifacts.mjs @@ -23,7 +23,9 @@ 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', 'wasi-worker.mjs': 'wasi-worker.mjs', } for (let file of await fs.readdir(tailwindcssOxideRoot)) { From 79a81b238d1408452715317bdc003c3340a1352e Mon Sep 17 00:00:00 2001 From: Joshua Gugun Siagian Date: Tue, 10 Nov 2026 01:25:42 +0700 Subject: [PATCH 3/3] Load the browser build asynchronously and shrink its memory - Instantiate with `instantiateNapiModule`, so compiling doesn't block the page, and Chrome's 8 MB limit on synchronous main-thread compiles doesn't apply. - Use an 8 MB stack instead of napi's 64 MB, and start with 16 MB of memory instead of 128 MB. Memory grows on demand. - Stop recommending the threaded browser loader in the README: its `scan()` hangs when it reads more than one file from memfs, because the workers' file reads wait on the blocked calling thread. Co-Authored-By: Claude Opus 5.5 --- crates/node/build.rs | 3 ++- crates/node/npm/wasm32-wasi/README.md | 2 -- crates/node/npm/wasm32-wasi/browser.mjs | 8 +++++--- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/crates/node/build.rs b/crates/node/build.rs index ef99174afca8..8147dc66ff7b 100644 --- a/crates/node/build.rs +++ b/crates/node/build.rs @@ -38,7 +38,8 @@ fn setup_browser() { "--import-memory", "--import-undefined", "--max-memory=4294967296", - "-zstack-size=64000000", + // 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}"); diff --git a/crates/node/npm/wasm32-wasi/README.md b/crates/node/npm/wasm32-wasi/README.md index fc6eebf48eb8..68aa82cdea36 100644 --- a/crates/node/npm/wasm32-wasi/README.md +++ b/crates/node/npm/wasm32-wasi/README.md @@ -26,6 +26,4 @@ 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. -On cross-origin isolated pages (COOP/COEP headers), import `@tailwindcss/oxide-wasm32-wasi/tailwindcss-oxide.wasi-browser.js` instead to scan in parallel on the threaded build. It uses `SharedArrayBuffer` and Web Workers, and the bundler must also serve `wasi-worker-browser.mjs`. - Scanning is synchronous. For larger inputs, run it in a module worker to keep the UI responsive. diff --git a/crates/node/npm/wasm32-wasi/browser.mjs b/crates/node/npm/wasm32-wasi/browser.mjs index f18c859db286..ca6fc13d8840 100644 --- a/crates/node/npm/wasm32-wasi/browser.mjs +++ b/crates/node/npm/wasm32-wasi/browser.mjs @@ -1,4 +1,4 @@ -import { getDefaultContext, instantiateNapiModuleSync, WASI } from '@napi-rs/wasm-runtime' +import { getDefaultContext, instantiateNapiModule, WASI } from '@napi-rs/wasm-runtime' import { memfs } from '@napi-rs/wasm-runtime/fs' export const { fs: __fs, vol: __volume } = memfs() @@ -11,12 +11,14 @@ let wasi = new WASI({ // 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 = 2048 +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}`) -let { napiModule } = instantiateNapiModuleSync(await response.arrayBuffer(), { +// 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,