Skip to content

feat(cli): support non-threaded WASI targets - #3353

Merged
Brooooooklyn merged 40 commits into
mainfrom
feat/non-threaded-wasi
Jul 21, 2026
Merged

Brooooooklyn merged 40 commits into
mainfrom
feat/non-threaded-wasi

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Jun 26, 2026 •

Copy link
Copy Markdown
Member

Note

Restacked (2026-07-13). The base PR #3352 was rebuilt from scratch as a minimal additive SPI (see its description). This branch was rebased onto the new base: the 13 feature commits replayed with zero crates/napi changes, plus three adaptation commits — examples/custom-async-runtime is now carried in this PR (the new base no longer ships it) and drives its own executor; tests asserting removed old-base machinery were dropped with notes; explicit-shutdown assertions follow the new self-healing lifecycle (a napi dispatch after shutdown restarts the backend; the drained Tokio runtime refills on the next environment registration).

Napi-side capabilities the old base provided that tests no longer assert (candidates for follow-up PRs): env-cleanup preparation hook (dispose-time promise settlement on threadless WASI), TSFN exception-identity hardening, graceful rejection of built-in tokio async exports on threadless WASI, wasm wrap-slot sharing. crates/build now uses --export-if-defined for napi_prepare_wasm_env_cleanup until the hook lands.

Summary

Add first-class non-threaded wasm32-wasip1 support to napi-build and the
napi-rs CLI, including production-hardened Node, browser, and deferred workerd
loaders.

This PR is stacked on #3352 so async addons can register a cooperative backend
instead of relying on Tokio/Rust threads.

Stack status

Build behavior

For wasm32-wasip1:

  • link emnapi's non-atomic libemnapi-basic.a;
  • omit threaded async-worker exports and -pthread flags;
  • use the wasm32-wasip1 WASI SDK sysroot;
  • emit Node, browser, and deferred workerd loaders without worker creation.

The existing threaded WASI path continues to use
libemnapi-basic-mt.a and its worker exports.

Deferred lifecycle API

The workerd loader exposes:

  • instantiate(module) for a module-local singleton;
  • createInstance(module) for independently owned instances;
  • dispose(): Promise<void> for deterministic singleton and retained rollback
    cleanup;
  • WasiInstance.dispose(): Promise<void> for deterministic independent cleanup.

Lifecycle ownership is explicit and failure-safe:

  • singleton creation and disposal are ordered without republishing stopped
    exports;
  • every retained failed-initialization context is drained, including contexts
    registered while a cleanup batch is pending;
  • one public disposal attempts a context at most once;
  • automatic beforeExit cleanup reports only failures from cleanup it starts,
    not a public batch it merely joins;
  • failed listener registration is retried with a bounded deferred policy;
  • suppressDestroy() failure still establishes rollback ownership;
  • hostile thenables and throwing then getters cannot strand lifecycle state;
  • recursive module lifecycle calls reject with
    ERR_NAPI_WASI_LIFECYCLE_REENTRY instead of forming promise cycles;
  • eager CommonJS contexts remain live across repeated beforeExit cycles and
    receive best-effort terminal cleanup.

The adversarial lifecycle coverage is in examples/napi; no
MODULE_COUNT_TEST_LOCK or synthetic scheduler lock is used.

Packaging and DX

  • Threaded and threadless WASI flavors have distinct package and artifact
    identities.
  • Direct flavor packages ship declarations beside their actual loaders.
  • Root /workerd, /wasm, and /wasm.wasm facades work with npm, isolated
    pnpm installs, Yarn PnP, Vite SSR, and Wrangler's extension-sensitive Wasm
    handling.
  • Generated lifecycle exports are idempotent and remove stale duplicate
    assignments.
  • Artifact reconciliation, pre-publish validation, rename transactions, engine
    constraints, and dual-flavor regeneration are deterministic.

Validation

Passed locally across the current #3352/#3353 stack:

  • pure custom-runtime suite: 147 unit tests plus API and registration tests
  • combined async-runtime,tokio_rt suite: 94 unit tests plus feature-selection tests
  • real native addon lifecycle suite: 15 passed, 1 WASI-only test skipped
  • lifecycle coverage runs in ordinary Node processes; no MODULE_COUNT_TEST_LOCK is used
  • CI=1 YARN_ENABLE_HARDENED_MODE=1 yarn test:cli (365 passed)
  • focused examples/napi WASI lifecycle and regeneration tests (10 passed)
  • rebased native value snapshot suite (166 passed, 1 skipped)
  • cargo test -p napi-build --locked (3 passed)
  • cargo fmt --all -- --check
  • yarn lint
  • Prettier checks for the edited source and generated deferred artifacts
  • git diff --check
  • WASI SDK 33 threaded and threadless regeneration
  • byte-identical generated artifacts on a second regeneration
  • real generated-loader hostile lifecycle process under
    --unhandled-rejections=strict

Two adversarial review passes were completed after the lifecycle changes; the
last pass found no new actionable issue.

Dependencies

Tracking


Note

High Risk
Large changes to WASM/WASI loader generation, lifecycle/disposal semantics, and packaging touch every consumer path; emnapi v2 alpha and raised Node engine floors are breaking for older environments.

Overview
Introduces first-class threadless wasm32-wasip1 alongside existing threaded WASI, with flavor-specific loaders, npm identities, and build/link flags (non-pthread emnapi archives, deferred workerd entry, no worker scripts for threadless).

CLI build and packaging now emit richer WASI artifacts: metadata-prefixed bindings, .d.cts loader typings, browser.js / root facades, NAPI_RS_WASI_FLAVOR-aware index chains, and Symbol.for('napi.rs.wasi.dispose') plus deferred instantiate / createInstance / dispose lifecycle in generated loaders (init rollback, worker termination, re-entry guards). artifacts and create-npm-dirs were reworked for transactional reconciliation, duplicate/missing artifact checks, stale flavor cleanup, and WASI packages without misleading cpu/os fields.

Dependencies and requirements: bumps @napi-rs/cli to emnapi 2.0.0-alpha.3, raises supported Node to ^20.17.0 || ^22.13.0 || >=23.5.0, and documents WASI targets in cli/docs/wasi.md. cli.mjs loads TypeScript directly in source checkouts.

CI: new test-custom-async-runtime-wasi job (native + WASI + browser + workerd + public-surface tests); unit-test timeout increased to 20 minutes on Windows.

Reviewed by Cursor Bugbot for commit b487f53. Bugbot is set up for automated code reviews on this repo. Configure here.

Summary by CodeRabbit

  • New Features
    • Expanded WASI support across threaded and threadless targets with flavor-aware loading and richer generated loader/export surfaces.
    • Added a complete custom async-runtime example (native, WASI, browser, and Workers) plus stronger WASI “public surface” end-to-end testing.
  • Bug Fixes
    • Improved disposal, cleanup, and rollback behavior during WASM/WASI initialization failures, including safer lifecycle handling.
  • Documentation
    • Updated CLI Node.js requirements and significantly expanded WASI loader/target documentation, including disposal semantics.
  • Chores / CI
    • Increased unit-test timeout and added CI coverage for the custom async runtime on wasm32-wasip1, with broader WASI/WASM browser/Workerd runs.

@coderabbitai

coderabbitai Bot commented Jun 26, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The PR adds canonical WASI target handling, transactional CLI filesystem workflows, generated loader disposal and rollback, richer TypeScript declaration generation, emnapi v2 integration, a custom async runtime example, and CI coverage across native, WASI, browser, and Workerd environments.

Changes

WASI runtime, packaging, and type generation

Layer / File(s) Summary
Target and declaration contracts
cli/src/utils/*, crates/backend/src/typegen*, cli/src/api/build.ts
WASI aliases, Cargo metadata, Node engine ranges, Buffer provenance, iterator declarations, and batched type-definition processing are updated.
Transactional artifact and publication workflows
cli/src/utils/misc.ts, cli/src/api/{build,artifacts,create-npm-dirs,new,pre-publish,rename}.ts
Build, artifact collection, package generation, publication, and rename operations use path validation, staging, reconciliation, journaling, and atomic commits.
Generated WASI loaders
cli/src/api/templates/*, examples/napi/*, wasm-runtime/*
WASI loaders support flavor-aware fallback, emnapi plugins, explicit contexts, worker cleanup, disposal symbols, rollback, deferred instantiation, and structured load errors.
Custom async runtime and validation
examples/custom-async-runtime/*, examples/napi/wasi-public-surface/*, .github/workflows/test-release.yaml
A custom runtime and its native, WASI, browser, Workerd, and public-surface tests are added, with a CI job and final-gate dependency.
Runtime and documentation integration
crates/napi/*, crates/build/src/wasi.rs, cli/docs/*, cli/README.md, package manifests
WASM cleanup-hook dispatch, sysroot/archive resolution, emnapi v2 versions and exports, Node requirements, WASI lifecycle documentation, and package metadata are updated.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related issues

Possibly related PRs

Sequence Diagram(s)

sequenceDiagram
  participant CI
  participant NapiCli
  participant WasmBuilder
  participant GeneratedLoader
  participant Runtime
  CI->>NapiCli: build WASI artifacts
  NapiCli->>WasmBuilder: configure target and emnapi archive
  WasmBuilder->>GeneratedLoader: emit loader and declarations
  GeneratedLoader->>Runtime: instantiate with plugins and memory
  Runtime-->>GeneratedLoader: expose N-API binding
  CI->>GeneratedLoader: run lifecycle tests
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.88% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and accurately summarizes the main change: adding non-threaded WASI target support in the CLI.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/non-threaded-wasi

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai

coderabbitai Bot commented Jun 26, 2026

Copy link
Copy Markdown

Caution

Review failed

An error occurred during the review process. Please try again later.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/non-threaded-wasi

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Brooooooklyn
Brooooooklyn force-pushed the feat/non-threaded-wasi branch from 85c3211 to a38e9d9 Compare June 30, 2026 01:25
@Brooooooklyn
Brooooooklyn force-pushed the feat/custom-async-runtime-backend branch from adae24d to b6ec867 Compare July 2, 2026 02:45
@Brooooooklyn
Brooooooklyn force-pushed the feat/non-threaded-wasi branch 6 times, most recently from d187a6d to 6c13247 Compare July 2, 2026 13:27
@Brooooooklyn
Brooooooklyn force-pushed the feat/custom-async-runtime-backend branch from 7cc8af8 to 5cb591f Compare July 5, 2026 11:08
@Brooooooklyn
Brooooooklyn force-pushed the feat/non-threaded-wasi branch 10 times, most recently from 42d51a1 to af4fa14 Compare July 6, 2026 02:48
@Brooooooklyn
Brooooooklyn force-pushed the feat/custom-async-runtime-backend branch from 34f3722 to e2bc651 Compare July 6, 2026 02:48
@Brooooooklyn
Brooooooklyn force-pushed the feat/non-threaded-wasi branch 5 times, most recently from 8cba580 to 13e8b55 Compare July 6, 2026 06:09
@Brooooooklyn
Brooooooklyn force-pushed the feat/custom-async-runtime-backend branch from e5f9e6f to d182579 Compare July 6, 2026 13:05
Brooooooklyn and others added 6 commits July 21, 2026 13:41
…them

The failed-snapshot cleanup guard verified ownership with an lstat of the
destination pathname and then unlinked the same pathname — a TOCTOU window
the code itself documented as a known limitation: a successor swapped onto
the pathname between the two syscalls was deleted even though the
transaction never owned it.

Close the window with the subsystem's existing retire idiom
(retireExactFileSystemTransactionPath /
restoreUnexpectedFileSystemTransactionRetirement): atomically rename the
leftover to a unique process-private sibling, revalidate the retired entry
against the recorded 64-bit decimal-string identity, and unlink only a
revalidated match — the retired name is unreachable to other writers, so
the unlink deletes exactly the revalidated inode. A mismatched entry is
hard-linked back to the destination, or preserved at the retired name when
an even newer successor already reoccupied the pathname.

The race window is covered deterministically in tests through the
onBeforeRetire seam, which swaps a distinct inode onto the pathname between
the ownership pre-check and the retirement rename.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
emnapi v1 @emnapi/core and @emnapi/runtime do not list ./package.json in
their export maps, so the package.json subpath require threw a bare
ERR_PACKAGE_PATH_NOT_EXPORTED before the descriptive version-mismatch
error could fire for stale installs. Try the package.json subpath first
(works on the pinned 2.0.0-alpha.3) and fall back to the module's own
version export (works on v1).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
…asi job

The job only builds and tests; it never pushes, so the checkout token
does not need to persist in the local git config (zizmor artipacked).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
…rebase onto main

Main added the type-tag surface (#3405); the rebase text-merged its
export lines into the threaded WASI loaders but could not update the
embedded artifact-metadata export lists, the wasip1 flavor loaders, or
the binary AVA snapshot. Regenerated via yarn regenerate and a native
values.spec.ts snapshot update so every flavor exports TypeTagA,
TypeTagB and makeTypeTagA consistently.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
…loor

restrictWasiNodeEngine fell back to the entire WASI-supported range when
the declared engines.node was valid but disjoint from it (e.g. ">=21 <22"
or "<20"), so create-npm-dirs and pre-publish published metadata claiming
support for Node.js versions the package explicitly excluded. Fail with an
error naming both ranges instead. Malformed ranges still fall back to the
WASI floor.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
…I_BINDING

The d\.[ct]s branch only matched literal d.ts/d.cs, so the generated
binary.wasi.d.cts / binary.wasip1.d.cts loader typings (already listed in
WASI_CI_ARTIFACT_PATTERNS and written to .gitattributes by this file) were
neither skipped by copyDirectory nor stripped by
updateGeneratedWasiAttributes. Use the d\.[cm]?ts idiom shared with
TYPE_DEF_FILE.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@cursor

cursor Bot commented Jul 21, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_0adddda9-8712-4806-917b-3567152b1d1b)

This was referenced Jul 21, 2026
@github-actions github-actions Bot mentioned this pull request Sep 10, 2026
@github-actions github-actions Bot mentioned this pull request Sep 16, 2026
This was referenced Sep 20, 2026
@github-actions github-actions Bot mentioned this pull request Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant