Unverified Commit 20088dcd authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

build(next-swc): package WASI bindings

Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
parent e7bbe9fe
...@@ -494,7 +494,7 @@ jobs: ...@@ -494,7 +494,7 @@ jobs:
- deploy-target - deploy-target
strategy: strategy:
matrix: matrix:
target: [web, nodejs] target: [web, nodejs, wasi]
runs-on: ubuntu-latest-16-core-oss runs-on: ubuntu-latest-16-core-oss
...@@ -524,32 +524,51 @@ jobs: ...@@ -524,32 +524,51 @@ jobs:
- name: Install Rust - name: Install Rust
uses: ./.github/actions/setup-rust uses: ./.github/actions/setup-rust
with: with:
targets: wasm32-unknown-unknown targets: ${{ matrix.target == 'wasi' && 'wasm32-wasip1-threads' || 'wasm32-unknown-unknown' }}
- name: Install wasm-pack - name: Install wasm-pack
if: ${{ matrix.target != 'wasi' }}
run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh
- name: normalize versions - name: normalize versions
run: node scripts/normalize-version-bump.js run: node scripts/normalize-version-bump.js
- name: Build - name: Build wasm-bindgen package
if: ${{ matrix.target != 'wasi' }}
run: pnpm dlx turbo@${TURBO_VERSION} run build-wasm ${TURBO_ARGS} -- --target ${{ matrix.target }} run: pnpm dlx turbo@${TURBO_VERSION} run build-wasm ${TURBO_ARGS} -- --target ${{ matrix.target }}
- name: Build N-API/WASI package
if: ${{ matrix.target == 'wasi' }}
run: scripts/build-next-swc-wasi.sh
- name: Add target to folder name - name: Add target to folder name
if: ${{ matrix.target != 'wasi' }}
run: '[[ -d "crates/wasm/pkg" ]] && mv crates/wasm/pkg crates/wasm/pkg-${{ matrix.target }} || ls crates/wasm' run: '[[ -d "crates/wasm/pkg" ]] && mv crates/wasm/pkg crates/wasm/pkg-${{ matrix.target }} || ls crates/wasm'
- name: Upload turbo summary artifact - name: Upload turbo summary artifact
if: ${{ matrix.target != 'wasi' }}
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with: with:
name: turbo-run-summary-wasm-${{matrix.target}} name: turbo-run-summary-wasm-${{matrix.target}}
path: .turbo/runs path: .turbo/runs
- name: Upload swc artifact - name: Upload wasm-bindgen artifact
if: ${{ matrix.target != 'wasi' }}
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with: with:
name: wasm-binaries-${{matrix.target}} name: wasm-binaries-${{matrix.target}}
path: crates/wasm/pkg-* path: crates/wasm/pkg-*
- name: Upload N-API/WASI artifact
if: ${{ matrix.target == 'wasi' }}
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: wasm-binaries-${{matrix.target}}
path: |
packages/next-swc-wasm-wasi/*.mjs
packages/next-swc-wasm-wasi/LICENSE.emnapi
packages/next-swc-wasm-wasi/next-swc.wasm32-wasi.wasm
deploy-tarball: deploy-tarball:
if: ${{ needs.deploy-target.outputs.value != 'production' }} if: ${{ needs.deploy-target.outputs.value != 'production' }}
name: Prepare preview tarball name: Prepare preview tarball
...@@ -599,6 +618,17 @@ jobs: ...@@ -599,6 +618,17 @@ jobs:
merge-multiple: true merge-multiple: true
path: crates/wasm path: crates/wasm
- name: Move N-API/WASI artifact into its package
run: |
mkdir -p packages/next-swc-wasm-wasi
mv \
crates/wasm/LICENSE.emnapi \
crates/wasm/emnapi-core.mjs \
crates/wasm/emnapi-runtime.mjs \
crates/wasm/next-swc.wasm32-wasi.wasm \
crates/wasm/wasi-threads.mjs \
packages/next-swc-wasm-wasi/
- name: Create tarballs - name: Create tarballs
# The tarballs are published under (upload_preview_tarballs.yml) and # The tarballs are published under (upload_preview_tarballs.yml) and
# looked up by (tests via getGitInfo) the head commit of the # looked up by (tests via getGitInfo) the head commit of the
...@@ -670,6 +700,17 @@ jobs: ...@@ -670,6 +700,17 @@ jobs:
merge-multiple: true merge-multiple: true
path: crates/wasm path: crates/wasm
- name: Move N-API/WASI artifact into its package
run: |
mkdir -p packages/next-swc-wasm-wasi
mv \
crates/wasm/LICENSE.emnapi \
crates/wasm/emnapi-core.mjs \
crates/wasm/emnapi-runtime.mjs \
crates/wasm/next-swc.wasm32-wasi.wasm \
crates/wasm/wasi-threads.mjs \
packages/next-swc-wasm-wasi/
- name: Create GitHub App token - name: Create GitHub App token
id: release-app-token id: release-app-token
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
......
...@@ -649,9 +649,8 @@ jobs: ...@@ -649,9 +649,8 @@ jobs:
stepName: 'test-next-swc-wasm' stepName: 'test-next-swc-wasm'
secrets: inherit secrets: inherit
# Guards that Turbopack keeps compiling and linking for wasm, so the wasm fallback Next.js loads # Builds, packages, and tests the N-API/WASI binding used by `next build --wasi`. This is distinct
# when the native bindings are unavailable can eventually support Turbopack and not just SWC. # from the SWC-only wasm-bindgen fallback. See https://github.com/vercel/next.js/issues/96960.
# See https://github.com/vercel/next.js/issues/96960.
# #
# setup-wasi-env.sh pins the exact emnapi v2 prerelease needed for linking. # setup-wasi-env.sh pins the exact emnapi v2 prerelease needed for linking.
test-next-napi-bindings-wasi: test-next-napi-bindings-wasi:
...@@ -665,6 +664,7 @@ jobs: ...@@ -665,6 +664,7 @@ jobs:
uses: ./.github/workflows/build_reusable.yml uses: ./.github/workflows/build_reusable.yml
with: with:
needsRust: 'yes' needsRust: 'yes'
nodeVersion: '22'
skipNativeBuild: 'yes' skipNativeBuild: 'yes'
skipNativeInstall: 'yes' skipNativeInstall: 'yes'
afterBuild: | afterBuild: |
...@@ -674,16 +674,29 @@ jobs: ...@@ -674,16 +674,29 @@ jobs:
# builds so the two cannot drift; see contributing/core/building-wasm.md. # builds so the two cannot drift; see contributing/core/building-wasm.md.
source scripts/setup-wasi-env.sh source scripts/setup-wasi-env.sh
# swc's plugin host is gated off for wasm (see turbopack-ecmascript-plugins and # swc's plugin host is gated off for wasm (see turbopack-ecmascript-plugins and
# next-napi-bindings), so nothing needs patching here: the wasm32 plugin path that does not # next-napi-bindings), so nothing needs patching here: the wasm32 plugin path that does not
# compile is simply never built. # compile is simply never built.
cargo build -p next-napi-bindings --target wasm32-wasip1-threads cargo build -p next-napi-bindings --target wasm32-wasip1-threads
timeout 60 node scripts/wasi-test-host/napi-async-smoke.mjs timeout 60 node scripts/wasi-test-host/napi-async-smoke.mjs
timeout 300 node scripts/wasi-test-host/next-build-smoke.mjs
cargo build --release -p next-napi-bindings --target wasm32-wasip1-threads # Build the same stripped release artifact that is published, then exercise its error path,
# package shape, download/cache behavior, and the real Next CLI.
scripts/build-next-swc-wasi.sh
wasi_binary=packages/next-swc-wasm-wasi/next-swc.wasm32-wasi.wasm
timeout 120 node scripts/wasi-test-host/napi-async-smoke.mjs \ timeout 120 node scripts/wasi-test-host/napi-async-smoke.mjs \
target/wasm32-wasip1-threads/release/next_napi_bindings.wasm --error-path "$wasi_binary" --error-path
pack_dir="$RUNNER_TEMP/next-swc-wasm-wasi-pack"
mkdir -p "$pack_dir"
pnpm --filter @next/swc-wasm-wasi pack --pack-destination "$pack_dir"
wasi_version="$(node -p "require('./packages/next-swc-wasm-wasi/package.json').version")"
node scripts/wasi-test-host/download-wasi-package-smoke.mjs \
"$pack_dir/next-swc-wasm-wasi-$wasi_version.tgz"
timeout 300 node scripts/wasi-test-host/next-build-smoke.mjs
NEXT_TEST_WASI_DIR="$PWD/packages/next-swc-wasm-wasi" \
NEXT_TEST_MODE=start \
NEXT_SKIP_ISOLATE=1 \
node run-tests.js test/production/app-dir/next-build-wasi/next-build-wasi.test.ts
# Run the crates whose tests can execute on wasm. This needs a host that supplies the # Run the crates whose tests can execute on wasm. This needs a host that supplies the
# `env.read_custom_section` import turbo-tasks' link-time registries depend on; no stock # `env.read_custom_section` import turbo-tasks' link-time registries depend on; no stock
......
# Building Turbopack for WebAssembly # Building Turbopack for WebAssembly
Turbopack's napi bindings (`crates/next-napi-bindings`) can be compiled for Turbopack's napi bindings (`crates/next-napi-bindings`) can be compiled for
`wasm32-wasip1-threads`. This is the target that would let Turbopack run where no native binding `wasm32-wasip1-threads`. Next.js publishes that architecture-independent build as
exists — unusual CPU architectures and operating systems we do not publish artifacts for. `@next/swc-wasm-wasi` for the experimental `next build --wasi` command.
> This is distinct from the `@next/swc-wasm-*` packages, which are built with `wasm-pack` from > This is distinct from the `@next/swc-wasm-*` packages, which are built with `wasm-pack` from
> `crates/wasm` for `wasm32-unknown-unknown` and contain SWC only, not Turbopack. > `crates/wasm` for `wasm32-unknown-unknown` and contain SWC only, not Turbopack.
...@@ -15,7 +15,14 @@ provisions both. ...@@ -15,7 +15,14 @@ provisions both.
## Building on Linux ## Building on Linux
The setup script supports Linux systems directly. Source it, then build as usual: The setup script supports Linux systems directly. Use the package build for the stripped release
artifact that Next.js consumes:
```sh
scripts/build-next-swc-wasi.sh
```
For a faster development build, source the environment and invoke Cargo directly:
```sh ```sh
source scripts/setup-wasi-env.sh source scripts/setup-wasi-env.sh
...@@ -39,9 +46,9 @@ variables (`WASI_SDK_PATH`, `EMNAPI_NODE_MODULES`, `EMNAPI_LINK_DIR`, and the ...@@ -39,9 +46,9 @@ variables (`WASI_SDK_PATH`, `EMNAPI_NODE_MODULES`, `EMNAPI_LINK_DIR`, and the
`~/.cache/next-wasi-toolchain`, so re-sourcing in a new shell is fast. Set `WASI_SETUP_CACHE_DIR` to `~/.cache/next-wasi-toolchain`, so re-sourcing in a new shell is fast. Set `WASI_SETUP_CACHE_DIR` to
move the cache. move the cache.
CI sources the same script, so local and CI builds cannot drift apart. The Node host passes its CI sources the same script, so local and CI builds cannot drift apart. `next build --wasi` defaults
effective CPU allowance into WASI, which sizes the bindings' multi-threaded Tokio runtime; set the multi-threaded Tokio runtime to two workers; set `TURBO_TASKS_AVAILABLE_PARALLELISM` before
`TURBO_TASKS_AVAILABLE_PARALLELISM` before invoking the host to override it. invoking Next to override it for diagnostics.
## Building with Docker ## Building with Docker
...@@ -56,11 +63,10 @@ docker run --rm -it \ ...@@ -56,11 +63,10 @@ docker run --rm -it \
next-wasi-builder next-wasi-builder
``` ```
Inside the container, use the same commands as CI: Inside the container, use the same package build as CI:
```sh ```sh
source scripts/setup-wasi-env.sh scripts/build-next-swc-wasi.sh
cargo build -p next-napi-bindings --target wasm32-wasip1-threads
``` ```
The named volume preserves the wasi-sdk and emnapi downloads between runs. Mount a second volume at The named volume preserves the wasi-sdk and emnapi downloads between runs. Mount a second volume at
...@@ -92,14 +98,26 @@ benchmark targets, which depend on `criterion` (and so rayon) and cannot build f ...@@ -92,14 +98,26 @@ benchmark targets, which depend on `criterion` (and so rayon) and cannot build f
cargo clippy -p turbo-tasks --lib --tests --target wasm32-wasip1-threads -- -D warnings cargo clippy -p turbo-tasks --lib --tests --target wasm32-wasip1-threads -- -D warnings
``` ```
## Running a Next.js build
The CLI downloads the matching `@next/swc-wasm-wasi` version on demand and caches it with the other
SWC packages:
```sh
next build --wasi
```
This trusted build module receives host root as guest `/` so absolute project, workspace, package,
and cache paths preserve their native meaning. This is not a security sandbox.
## Known limitations ## Known limitations
- **emnapi v2 is a prerelease.** `napi-build` needs the `emnapi_create_env` / `emnapi_delete_env` - **emnapi v2 is a prerelease.** `napi-build` needs the `emnapi_create_env` / `emnapi_delete_env`
exports, which exist only in v2, so the script pins `emnapi@2.0.0-alpha.4`. Move to the stable exports, which exist only in v2, so the package build pins `emnapi@2.0.0-alpha.4`. Move to the
release once it ships. stable release once it ships.
- **A publishable N-API wasm package is not wired up yet.** CI links the raw wasm artifact, but does - Only the default Turbopack production `next build` is supported. Development/HMR, Webpack builds,
not produce an `@next/swc-wasm-wasi` package. Jest, and analyze commands do not expose a WASI mode yet.
- **The JS loader is not connected to the SWC fallback yet.** The loader hooks and module - Turbopack filesystem persistence is disabled. WASI file descriptors belong to one pthread module
initialization exist, but no published package consumes them. instance and cannot safely move to another instance during parallel persistence commits.
- Some features are unavailable on wasm and report an error when configured: SWC wasm plugins, and - Features unavailable on WASI report actionable errors: SWC wasm plugins, HTTP fetches such as
anything requiring the child-process pool. `next/font/google`, trace-server sockets, and the child-process plugin pool.
/LICENSE.emnapi
/emnapi-core.mjs
/emnapi-runtime.mjs
/next-swc.wasm32-wasi.wasm
/wasi-threads.mjs
# `@next/swc-wasm-wasi`
Architecture-independent N-API/WASI bindings used by the experimental `next build --wasi` command.
This self-contained package is downloaded on demand at the exact version of `next`; applications
should not depend on it directly. Its emnapi runtime files are copied from exact pinned versions by
the repository's WASI release build.
The module is trusted build tooling, not a security sandbox. Next.js preopens the host root so
absolute project, workspace, package-manager, and cache paths retain their native-binding meaning.
The MIT License (MIT)
Copyright (c) 2025 Vercel, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
{
"name": "@next/swc-wasm-wasi",
"version": "16.4.0-canary.33",
"description": "N-API/WASI bindings for Next.js",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/vercel/next.js",
"directory": "packages/next-swc-wasm-wasi"
},
"files": [
"LICENSE.emnapi",
"emnapi-core.mjs",
"emnapi-runtime.mjs",
"next-swc.wasm32-wasi.wasm",
"wasi-threads.mjs",
"license.md",
"README.md"
],
"engines": {
"node": ">=20.9.0"
},
"devDependencies": {
"@emnapi/core": "2.0.0-alpha.4",
"@emnapi/runtime": "2.0.0-alpha.4",
"@emnapi/wasi-threads": "2.1.0"
},
"scripts": {
"build-wasi": "bash ../../scripts/build-next-swc-wasi.sh"
},
"publishConfig": {
"access": "public"
}
}
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
"build-native": "napi build --platform -p next-napi-bindings --manifest-path ../../Cargo.toml --features image-extended --no-js -o native", "build-native": "napi build --platform -p next-napi-bindings --manifest-path ../../Cargo.toml --features image-extended --no-js -o native",
"build-native-release": "napi build --platform -p next-napi-bindings --manifest-path ../../Cargo.toml --release --features image-extended,tracing/release_max_level_trace --no-js -o native", "build-native-release": "napi build --platform -p next-napi-bindings --manifest-path ../../Cargo.toml --release --features image-extended,tracing/release_max_level_trace --no-js -o native",
"build-native-release-with-assertions": "napi build --platform -p next-napi-bindings --manifest-path ../../Cargo.toml --profile release-with-assertions --features image-extended,tracing/release_max_level_trace --no-js -o native", "build-native-release-with-assertions": "napi build --platform -p next-napi-bindings --manifest-path ../../Cargo.toml --profile release-with-assertions --features image-extended,tracing/release_max_level_trace --no-js -o native",
"build-native-wasi": "napi build --platform --target wasm32-wasip1-threads -p next-napi-bindings --manifest-path ../../Cargo.toml --no-default-features -o native", "build-native-wasi": "bash ../../scripts/build-next-swc-wasi.sh",
"build-wasm": "wasm-pack build ../../crates/wasm --scope=next", "build-wasm": "wasm-pack build ../../crates/wasm --scope=next",
"cache-build-native": "[ -d native ] && echo $(ls native)", "cache-build-native": "[ -d native ] && echo $(ls native)",
"rust-fingerprint": "node ../../scripts/rust-fingerprint.js", "rust-fingerprint": "node ../../scripts/rust-fingerprint.js",
......
...@@ -50,7 +50,7 @@ ...@@ -50,7 +50,7 @@
"build-native-wasi": { "build-native-wasi": {
"dependsOn": ["rust-fingerprint"], "dependsOn": ["rust-fingerprint"],
"inputs": ["../../target/.rust-fingerprint"], "inputs": ["../../target/.rust-fingerprint"],
"outputs": ["native/*"], "outputs": ["../next-swc-wasm-wasi/*"],
}, },
"cache-build-native": { "cache-build-native": {
"dependsOn": ["rust-fingerprint"], "dependsOn": ["rust-fingerprint"],
......
import path from 'path' import path from 'path'
import { appendFile, readFile } from 'fs/promises' import { appendFile, readFile } from 'fs/promises'
import { createRequire } from 'module'
import { pathToFileURL } from 'url' import { pathToFileURL } from 'url'
import { resolveCacheHandlerPathToFilesystem } from '../../lib/format-dynamic-import-path' import { resolveCacheHandlerPathToFilesystem } from '../../lib/format-dynamic-import-path'
import { arch, platform } from 'os' import { arch, platform } from 'os'
...@@ -169,6 +168,7 @@ let pendingBindings: Promise<Binding> | undefined ...@@ -169,6 +168,7 @@ let pendingBindings: Promise<Binding> | undefined
// The cached loaded bindings // The cached loaded bindings
let loadedBindings: Binding | undefined = undefined let loadedBindings: Binding | undefined = undefined
let downloadWasmPromise: any let downloadWasmPromise: any
let downloadWasiPromise: Promise<void> | undefined
let swcTraceFlushGuard: any let swcTraceFlushGuard: any
let downloadNativeBindingsPromise: Promise<void> | undefined = undefined let downloadNativeBindingsPromise: Promise<void> | undefined = undefined
...@@ -241,7 +241,7 @@ export async function loadBindings( ...@@ -241,7 +241,7 @@ export async function loadBindings(
} }
if (useWasiBinary) { if (useWasiBinary) {
pendingBindings = loadWasiNapiBinding() pendingBindings = loadWasiNapiWithFallback()
try { try {
loadedBindings = await pendingBindings loadedBindings = await pendingBindings
return loadedBindings return loadedBindings
...@@ -325,7 +325,41 @@ export async function loadBindings( ...@@ -325,7 +325,41 @@ export async function loadBindings(
return loadedBindings return loadedBindings
} }
async function loadWasiNapiBinding(): Promise<Binding> { async function loadWasiNapiWithFallback(): Promise<Binding> {
const packageName = '@next/swc-wasm-wasi'
const testDirectory = process.env.NEXT_TEST_WASI_DIR
if (testDirectory) return loadWasiNapiBinding()
const attempts: unknown[] = []
try {
return await loadWasiNapiBinding()
} catch (error) {
attempts.push(error)
}
const wasmDirectory = path.join(
path.dirname(require.resolve('next/package.json')),
'wasm'
)
try {
if (!downloadWasiPromise) {
downloadWasiPromise = (
require('../../lib/download-swc') as typeof import('../../lib/download-swc')
).downloadWasmSwc(nextVersion, wasmDirectory, 'wasi')
}
await downloadWasiPromise
return await loadWasiNapiBinding(wasmDirectory)
} catch (error) {
attempts.push(error)
}
throw new Error(
`Failed to load ${packageName}@${nextVersion} from the installed package or the on-demand download.`,
{ cause: new AggregateError(attempts) }
)
}
async function loadWasiNapiBinding(importPath = ''): Promise<Binding> {
const packageName = '@next/swc-wasm-wasi' const packageName = '@next/swc-wasm-wasi'
const testDirectory = process.env.NEXT_TEST_WASI_DIR const testDirectory = process.env.NEXT_TEST_WASI_DIR
let packageDirectory: string let packageDirectory: string
...@@ -333,7 +367,9 @@ async function loadWasiNapiBinding(): Promise<Binding> { ...@@ -333,7 +367,9 @@ async function loadWasiNapiBinding(): Promise<Binding> {
try { try {
packageDirectory = testDirectory packageDirectory = testDirectory
? path.resolve(testDirectory) ? path.resolve(testDirectory)
: path.dirname(require.resolve(`${packageName}/package.json`)) : importPath
? path.join(importPath, packageName)
: path.dirname(require.resolve(`${packageName}/package.json`))
} catch (error) { } catch (error) {
throw new Error( throw new Error(
`Failed to load ${packageName}@${nextVersion}: the package is not installed.`, `Failed to load ${packageName}@${nextVersion}: the package is not installed.`,
...@@ -342,28 +378,19 @@ async function loadWasiNapiBinding(): Promise<Binding> { ...@@ -342,28 +378,19 @@ async function loadWasiNapiBinding(): Promise<Binding> {
} }
const wasmPath = path.join(packageDirectory, 'next-swc.wasm32-wasi.wasm') const wasmPath = path.join(packageDirectory, 'next-swc.wasm32-wasi.wasm')
const packageRequire = createRequire(
path.join(packageDirectory, 'package.json')
)
try { try {
if (!testDirectory) { if (!testDirectory) {
checkVersionMismatch(packageRequire('./package.json')) checkVersionMismatch(require(path.join(packageDirectory, 'package.json')))
} }
const coreDirectory = path.dirname(
packageRequire.resolve('@emnapi/core/package.json')
)
const coreUrl = pathToFileURL( const coreUrl = pathToFileURL(
path.join(coreDirectory, 'dist/emnapi-core.full.js') path.join(packageDirectory, 'emnapi-core.mjs')
).href ).href
const runtimeDirectory = path.dirname(
packageRequire.resolve('@emnapi/runtime/package.json')
)
const runtimeUrl = pathToFileURL( const runtimeUrl = pathToFileURL(
path.join(runtimeDirectory, 'dist/emnapi.js') path.join(packageDirectory, 'emnapi-runtime.mjs')
).href ).href
const wasiThreadsUrl = pathToFileURL( const wasiThreadsUrl = pathToFileURL(
packageRequire.resolve('@emnapi/wasi-threads') path.join(packageDirectory, 'wasi-threads.mjs')
).href ).href
const [{ createNapiModule }, { getDefaultContext }] = await Promise.all([ const [{ createNapiModule }, { getDefaultContext }] = await Promise.all([
import(coreUrl), import(coreUrl),
......
...@@ -129,7 +129,7 @@ export async function downloadNativeNextSwc( ...@@ -129,7 +129,7 @@ export async function downloadNativeNextSwc(
export async function downloadWasmSwc( export async function downloadWasmSwc(
version: string, version: string,
wasmDirectory: string, wasmDirectory: string,
variant: 'nodejs' | 'web' = 'nodejs' variant: 'nodejs' | 'web' | 'wasi' = 'nodejs'
) { ) {
const pkgName = `@next/swc-wasm-${variant}` const pkgName = `@next/swc-wasm-${variant}`
const tarFileName = `${pkgName.substring(6)}-${version}.tgz` const tarFileName = `${pkgName.substring(6)}-${version}.tgz`
......
...@@ -1967,6 +1967,18 @@ importers: ...@@ -1967,6 +1967,18 @@ importers:
specifier: 0.13.1 specifier: 0.13.1
version: 0.13.1 version: 0.13.1
packages/next-swc-wasm-wasi:
devDependencies:
'@emnapi/core':
specifier: 2.0.0-alpha.4
version: 2.0.0-alpha.4
'@emnapi/runtime':
specifier: 2.0.0-alpha.4
version: 2.0.0-alpha.4
'@emnapi/wasi-threads':
specifier: 2.1.0
version: 2.1.0
packages/react-refresh-utils: packages/react-refresh-utils:
devDependencies: devDependencies:
react-refresh: react-refresh:
...@@ -3052,6 +3064,9 @@ packages: ...@@ -3052,6 +3064,9 @@ packages:
'@emnapi/core@1.9.2': '@emnapi/core@1.9.2':
resolution: {integrity: sha512-UC+ZhH3XtczQYfOlu3lNEkdW/p4dsJ1r/bP7H8+rhao3TTTMO1ATq/4DdIi23XuGoFY+Cz0JmCbdVl0hz9jZcA==} resolution: {integrity: sha512-UC+ZhH3XtczQYfOlu3lNEkdW/p4dsJ1r/bP7H8+rhao3TTTMO1ATq/4DdIi23XuGoFY+Cz0JmCbdVl0hz9jZcA==}
'@emnapi/core@2.0.0-alpha.4':
resolution: {integrity: sha512-KjoUR6mNvjT+z5bKMy+a5QDI+kTNTiMZi6uPKzWuWjwZGNa0UPwIVduTfeBRdf6v8Ws5fmHDh7Usf15w/ANfkg==}
'@emnapi/runtime@1.10.0': '@emnapi/runtime@1.10.0':
resolution: {integrity: sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==} resolution: {integrity: sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==}
...@@ -3064,12 +3079,18 @@ packages: ...@@ -3064,12 +3079,18 @@ packages:
'@emnapi/runtime@1.9.2': '@emnapi/runtime@1.9.2':
resolution: {integrity: sha512-3U4+MIWHImeyu1wnmVygh5WlgfYDtyf0k8AbLhMFxOipihf6nrWC4syIm/SwEeec0mNSafiiNnMJwbza/Is6Lw==} resolution: {integrity: sha512-3U4+MIWHImeyu1wnmVygh5WlgfYDtyf0k8AbLhMFxOipihf6nrWC4syIm/SwEeec0mNSafiiNnMJwbza/Is6Lw==}
'@emnapi/runtime@2.0.0-alpha.4':
resolution: {integrity: sha512-Wy1TQ99obRP3Ah7cf/OOtK1zD9t3pYTWz+G/SpAwTFMhG5hoMdlvfzBpYoHUigS/izu3q+VhYMKhJd7Ii/trpg==}
'@emnapi/wasi-threads@1.2.1': '@emnapi/wasi-threads@1.2.1':
resolution: {integrity: sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==} resolution: {integrity: sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==}
'@emnapi/wasi-threads@1.2.2': '@emnapi/wasi-threads@1.2.2':
resolution: {integrity: sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==} resolution: {integrity: sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==}
'@emnapi/wasi-threads@2.0.1':
resolution: {integrity: sha512-9DsSk+o5NBX0CCJT8s0EROGSGxjR/tKu6aBTaVyq+SjAEQH4XcdcRxPBRzsBLizTTJ49MJjF+jgu3qnO9GLQcQ==}
'@emnapi/wasi-threads@2.1.0': '@emnapi/wasi-threads@2.1.0':
resolution: {integrity: sha512-DM18NXgQ5coifswrwhFgrqeW/UiFRaLj0aLKU0cp0FoYjEfP/hj/yUeF+Hz754ViG+jQmG2HIeDCUeQsPnRwOA==} resolution: {integrity: sha512-DM18NXgQ5coifswrwhFgrqeW/UiFRaLj0aLKU0cp0FoYjEfP/hj/yUeF+Hz754ViG+jQmG2HIeDCUeQsPnRwOA==}
...@@ -20187,6 +20208,11 @@ snapshots: ...@@ -20187,6 +20208,11 @@ snapshots:
tslib: 2.8.1 tslib: 2.8.1
optional: true optional: true
'@emnapi/core@2.0.0-alpha.4':
dependencies:
'@emnapi/wasi-threads': 2.0.1
tslib: 2.8.1
'@emnapi/runtime@1.10.0': '@emnapi/runtime@1.10.0':
dependencies: dependencies:
tslib: 2.8.1 tslib: 2.8.1
...@@ -20206,6 +20232,10 @@ snapshots: ...@@ -20206,6 +20232,10 @@ snapshots:
tslib: 2.8.1 tslib: 2.8.1
optional: true optional: true
'@emnapi/runtime@2.0.0-alpha.4':
dependencies:
tslib: 2.8.1
'@emnapi/wasi-threads@1.2.1': '@emnapi/wasi-threads@1.2.1':
dependencies: dependencies:
tslib: 2.8.1 tslib: 2.8.1
...@@ -20215,6 +20245,10 @@ snapshots: ...@@ -20215,6 +20245,10 @@ snapshots:
tslib: 2.8.1 tslib: 2.8.1
optional: true optional: true
'@emnapi/wasi-threads@2.0.1':
dependencies:
tslib: 2.8.1
'@emnapi/wasi-threads@2.1.0': '@emnapi/wasi-threads@2.1.0':
dependencies: dependencies:
tslib: 2.8.1 tslib: 2.8.1
#!/usr/bin/env bash
set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$repo_root"
source scripts/setup-wasi-env.sh
output="${1:-$repo_root/packages/next-swc-wasm-wasi/next-swc.wasm32-wasi.wasm}"
input="$repo_root/target/wasm32-wasip1-threads/release/next_napi_bindings.wasm"
mkdir -p "$(dirname "$output")"
export CARGO_INCREMENTAL=0
cargo --config 'target."cfg(all())".rustflags=["-Dwarnings","-Dlinker-messages"]' \
build --release -p next-napi-bindings --target wasm32-wasip1-threads
mapfile -t link_sections < <(
"$WASI_SDK_PATH/bin/llvm-objdump" -h "$input" |
awk '$2 ~ /^\.data\.link_section\./ { print $2 }'
)
if [ "${#link_sections[@]}" -eq 0 ]; then
echo "error: the WASI binding has no turbo-tasks link sections" >&2
exit 1
fi
keep_section_args=()
for section in "${link_sections[@]}"; do
keep_section_args+=("--keep-section=$section")
done
"$WASI_SDK_PATH/bin/llvm-strip" --strip-all "${keep_section_args[@]}" \
"$input" -o "$output"
mapfile -t stripped_link_sections < <(
"$WASI_SDK_PATH/bin/llvm-objdump" -h "$output" |
awk '$2 ~ /^\.data\.link_section\./ { print $2 }'
)
if [ "${link_sections[*]}" != "${stripped_link_sections[*]}" ]; then
echo "error: stripping removed a turbo-tasks link section" >&2
exit 1
fi
output_dir="$(dirname "$output")"
cp "$EMNAPI_NODE_MODULES/@emnapi/core/LICENSE" "$output_dir/LICENSE.emnapi"
cp "$EMNAPI_NODE_MODULES/@emnapi/core/dist/emnapi-core.full.js" \
"$output_dir/emnapi-core.mjs"
cp "$EMNAPI_NODE_MODULES/@emnapi/runtime/dist/emnapi.js" \
"$output_dir/emnapi-runtime.mjs"
cp "$EMNAPI_NODE_MODULES/@emnapi/wasi-threads/dist/wasi-threads.js" \
"$output_dir/wasi-threads.mjs"
printf 'Built %s (%s bytes)\n' "$output" "$(wc -c < "$output" | xargs)"
import assert from 'node:assert/strict'
import { mkdtemp, readFile, rm } from 'node:fs/promises'
import path from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
const repoRoot = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
'../..'
)
const packageJson = JSON.parse(
await readFile(
path.join(repoRoot, 'packages/next-swc-wasm-wasi/package.json'),
'utf8'
)
)
const version = packageJson.version
const tarPath = path.resolve(
process.argv[2] ?? path.join(repoRoot, `next-swc-wasm-wasi-${version}.tgz`)
)
const scratch = await mkdtemp(
path.join(path.dirname(repoRoot), 'next-wasi-download-smoke-')
)
const originalFetch = globalThis.fetch
const originalCache = process.env.NEXT_SWC_PATH
const { downloadWasmSwc } = await import(
pathToFileURL(path.join(repoRoot, 'packages/next/dist/lib/download-swc.js'))
.href
)
async function assertExtracted(outputDirectory) {
const extractedPackage = path.join(outputDirectory, '@next/swc-wasm-wasi')
assert.equal(
JSON.parse(
await readFile(path.join(extractedPackage, 'package.json'), 'utf8')
).name,
'@next/swc-wasm-wasi'
)
assert.ok(
(await readFile(path.join(extractedPackage, 'next-swc.wasm32-wasi.wasm')))
.byteLength > 1_000_000
)
for (const runtimeFile of [
'LICENSE.emnapi',
'emnapi-core.mjs',
'emnapi-runtime.mjs',
'wasi-threads.mjs',
]) {
assert.ok(
(await readFile(path.join(extractedPackage, runtimeFile))).byteLength >
100
)
}
}
try {
const archive = await readFile(tarPath)
const cacheDirectory = path.join(scratch, 'cache')
const outputDirectory = path.join(scratch, 'downloaded')
let requestedUrl
process.env.NEXT_SWC_PATH = cacheDirectory
globalThis.fetch = async (url) => {
requestedUrl = String(url)
return new Response(archive)
}
await downloadWasmSwc(version, outputDirectory, 'wasi')
assert.match(
requestedUrl,
new RegExp(
`/@next/swc-wasm-wasi/-/swc-wasm-wasi-${version.replaceAll('.', '\\.')}.tgz$`
)
)
await assertExtracted(outputDirectory)
await rm(outputDirectory, { recursive: true, force: true })
globalThis.fetch = async () => {
throw new Error('cache hit unexpectedly fetched the package')
}
await downloadWasmSwc(version, outputDirectory, 'wasi')
await assertExtracted(outputDirectory)
process.env.NEXT_SWC_PATH = path.join(scratch, 'missing-cache')
globalThis.fetch = async () => new Response('missing', { status: 404 })
await assert.rejects(
downloadWasmSwc(version, path.join(scratch, 'missing'), 'wasi'),
/request failed with status 404/
)
process.env.NEXT_SWC_PATH = path.join(scratch, 'corrupt-cache')
globalThis.fetch = async () => new Response('not a tar archive')
await assert.rejects(
downloadWasmSwc(version, path.join(scratch, 'corrupt'), 'wasi')
)
console.log(
'@next/swc-wasm-wasi download, extraction, cache hit, missing version, and corrupt archive passed'
)
} finally {
globalThis.fetch = originalFetch
if (originalCache === undefined) delete process.env.NEXT_SWC_PATH
else process.env.NEXT_SWC_PATH = originalCache
await rm(scratch, { recursive: true, force: true })
}
...@@ -26,24 +26,9 @@ const scratchRoot = await mkdtemp( ...@@ -26,24 +26,9 @@ const scratchRoot = await mkdtemp(
path.join(path.dirname(repoRoot), 'next-wasi-build-smoke-') path.join(path.dirname(repoRoot), 'next-wasi-build-smoke-')
) )
const sitePath = path.join(scratchRoot, 'site') const sitePath = path.join(scratchRoot, 'site')
const packagePath = path.join(scratchRoot, 'wasi-package') const packagePath = path.join(repoRoot, 'packages/next-swc-wasm-wasi')
const targetLog = path.join(scratchRoot, 'targets.jsonl') const targetLog = path.join(scratchRoot, 'targets.jsonl')
const nextBin = path.join(sitePath, 'node_modules/next/dist/bin/next') const nextBin = path.join(sitePath, 'node_modules/next/dist/bin/next')
const wasmPath = path.resolve(
process.argv[2] ??
path.join(
repoRoot,
'target/wasm32-wasip1-threads/debug/next_napi_bindings.wasm'
)
)
const emnapiLinkDir = process.env.EMNAPI_LINK_DIR
assert.ok(
emnapiLinkDir,
'EMNAPI_LINK_DIR is missing; source scripts/setup-wasi-env.sh first'
)
const emnapiNodeModules = path.resolve(emnapiLinkDir, '../../..')
const require = createRequire(import.meta.url)
async function writeConfig(experimental = {}) { async function writeConfig(experimental = {}) {
await writeFile( await writeFile(
path.join(sitePath, 'next.config.ts'), path.join(sitePath, 'next.config.ts'),
...@@ -91,9 +76,6 @@ async function expectFailure(args, pattern, env) { ...@@ -91,9 +76,6 @@ async function expectFailure(args, pattern, env) {
try { try {
await mkdir(path.join(sitePath, 'app'), { recursive: true }) await mkdir(path.join(sitePath, 'app'), { recursive: true })
await mkdir(path.join(packagePath, 'node_modules/@emnapi'), {
recursive: true,
})
// The WASI filesystem resolver on Node 20.9 cannot follow the workspace's // The WASI filesystem resolver on Node 20.9 cannot follow the workspace's
// symlinked node_modules/next. Put the built package at the project's actual // symlinked node_modules/next. Put the built package at the project's actual
// resolution path while retaining the other workspace dependencies. // resolution path while retaining the other workspace dependencies.
...@@ -164,27 +146,7 @@ try { ...@@ -164,27 +146,7 @@ try {
} }
await symlink(source, path.join(sitePath, 'node_modules', name), 'dir') await symlink(source, path.join(sitePath, 'node_modules', name), 'dir')
} }
await symlink( await readFile(path.join(packagePath, 'next-swc.wasm32-wasi.wasm'))
path.join(emnapiNodeModules, '@emnapi/core'),
path.join(packagePath, 'node_modules/@emnapi/core')
)
await symlink(
path.join(emnapiNodeModules, '@emnapi/runtime'),
path.join(packagePath, 'node_modules/@emnapi/runtime')
)
await symlink(
path.dirname(require.resolve('@emnapi/wasi-threads/package.json')),
path.join(packagePath, 'node_modules/@emnapi/wasi-threads')
)
await copyFile(wasmPath, path.join(packagePath, 'next-swc.wasm32-wasi.wasm'))
await writeFile(
path.join(packagePath, 'package.json'),
JSON.stringify({
name: '@next/swc-wasm-wasi',
version: '0.0.0-test',
private: true,
})
)
await writeFile( await writeFile(
path.join(sitePath, 'package.json'), path.join(sitePath, 'package.json'),
JSON.stringify({ JSON.stringify({
......
...@@ -255,7 +255,10 @@ async function createNextInstall({ ...@@ -255,7 +255,10 @@ async function createNextInstall({
} else { } else {
pkgPaths = await packPackages(rootSpan) pkgPaths = await packPackages(rootSpan)
if (process.env.NEXT_TEST_WASM) { if (process.env.NEXT_TEST_WASI_DIR) {
// The dedicated N-API/WASI test job supplies an architecture-independent package and
// deliberately has no native addon artifact to install.
} else if (process.env.NEXT_TEST_WASM) {
const wasmPath = path.join(origRepoDir, 'crates', 'wasm', 'pkg') const wasmPath = path.join(origRepoDir, 'crates', 'wasm', 'pkg')
const hasWasmBinary = fs.existsSync( const hasWasmBinary = fs.existsSync(
path.join(wasmPath, 'package.json') path.join(wasmPath, 'package.json')
......
...@@ -144,6 +144,10 @@ export const conditions: Record<string, Condition> = { ...@@ -144,6 +144,10 @@ export const conditions: Record<string, Condition> = {
'running on Windows', 'running on Windows',
() => process.platform === 'win32' () => process.platform === 'win32'
), ),
wasiNapi: staticCondition(
'using the N-API/WASI binding (`NEXT_TEST_WASI_DIR`)',
() => Boolean(process.env.NEXT_TEST_WASI_DIR)
),
ci: staticCondition('running in CI (`NEXT_TEST_CI`)', () => ci: staticCondition('running in CI (`NEXT_TEST_CI`)', () =>
Boolean(process.env.NEXT_TEST_CI) Boolean(process.env.NEXT_TEST_CI)
), ),
......
import localFont from 'next/font/local'
import type { ReactNode } from 'react'
import './style.css'
const testFont = localFont({ src: './test-font.woff2' })
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body className={testFont.className}>{children}</body>
</html>
)
}
export default function Page() {
return <main>Built by WASI</main>
}
import { readdir } from 'node:fs/promises'
import path from 'node:path'
import { nextTestSetup } from 'e2e-utils'
// The dedicated `test next-swc wasi` job builds the release artifact before running this fixture.
// @force-gate wasiNapi
describe('next-build-wasi', () => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
const pageSource = `export default function Page() {
return <main>Built by WASI</main>
}
`
const configSource = `import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: { turbopackFileSystemCacheForBuild: true },
}
export default nextConfig
`
const wasiEnv = {
NEXT_TEST_WASI_DIR: process.env.NEXT_TEST_WASI_DIR,
NEXT_TEST_NATIVE_DIR: '/native-binding-must-not-load',
}
afterEach(async () => {
await next.patchFile('app/page.tsx', pageSource)
await next.patchFile('next.config.ts', configSource)
})
it('builds an App Router project through N-API/WASI', async () => {
const targetLog = path.join(next.testDir, 'wasi-targets.jsonl')
const { exitCode, cliOutput } = await next.build({
args: ['--wasi'],
env: {
...wasiEnv,
NEXT_TEST_WASI_TARGET_LOG: targetLog,
},
})
expect(exitCode).toBe(0)
expect(cliOutput).toContain('Running next.config.ts')
expect(cliOutput).toContain('Compiled successfully')
expect(cliOutput).toContain('Route (app)')
expect(cliOutput).toContain(
'Turbopack filesystem caching is disabled for --wasi'
)
expect(await next.hasFile('.next/BUILD_ID')).toBe(true)
expect(await next.hasFile('.next/server/app/index.html')).toBe(true)
expect(await next.readFile('.next/server/app/index.html')).toContain(
'Built by WASI'
)
const targetRecords = (await next.readFile('wasi-targets.jsonl'))
.trim()
.split('\n')
.map((line) => JSON.parse(line))
expect(targetRecords.some(({ worker }) => !worker)).toBe(true)
expect(targetRecords.some(({ worker }) => worker)).toBe(true)
expect(
targetRecords.every(({ target }) => target === 'wasm32-wasip1-threads')
).toBe(true)
const outputFiles = await readdir(path.join(next.testDir, '.next'), {
recursive: true,
})
expect(outputFiles.some((file) => file.endsWith('.sst'))).toBe(false)
})
it('reports that Google Fonts cannot make HTTP requests on WASI', async () => {
await next.patchFile(
'app/page.tsx',
`import { Inter } from 'next/font/google'
const inter = Inter({ subsets: ['latin'] })
export default function Page() {
return <main className={inter.className}>Google font on WASI</main>
}
`
)
const { exitCode, cliOutput } = await next.build({
args: ['--wasi'],
env: wasiEnv,
})
expect(exitCode).toBe(1)
expect(cliOutput).toContain(
'HTTP requests are not supported in wasm builds of Next.js'
)
})
it('reports configured SWC plugins as unsupported on WASI', async () => {
await next.patchFile(
'next.config.ts',
`import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: { swcPlugins: [['fixture-plugin', {}]] },
}
export default nextConfig
`
)
const { exitCode, cliOutput } = await next.build({
args: ['--wasi'],
env: wasiEnv,
})
expect(exitCode).toBe(1)
expect(cliOutput).toContain(
'`experimental.swcPlugins` is not supported on this platform'
)
})
})
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: { turbopackFileSystemCacheForBuild: true },
}
export default nextConfig
...@@ -16,6 +16,8 @@ pub enum FetchErrorKind { ...@@ -16,6 +16,8 @@ pub enum FetchErrorKind {
Timeout, Timeout,
Status(u16), Status(u16),
Other, Other,
#[cfg(target_family = "wasm")]
Unsupported,
} }
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
...@@ -27,6 +29,9 @@ pub struct FetchError { ...@@ -27,6 +29,9 @@ pub struct FetchError {
impl FetchError { impl FetchError {
pub(crate) fn from_reqwest_error(error: &reqwest::Error, url: &str) -> FetchError { pub(crate) fn from_reqwest_error(error: &reqwest::Error, url: &str) -> FetchError {
#[cfg(target_family = "wasm")]
let kind = FetchErrorKind::Unsupported;
#[cfg(not(target_family = "wasm"))]
let kind = if error.is_connect() { let kind = if error.is_connect() {
FetchErrorKind::Connect FetchErrorKind::Connect
} else if error.is_timeout() { } else if error.is_timeout() {
...@@ -97,6 +102,8 @@ impl Issue for FetchIssue { ...@@ -97,6 +102,8 @@ impl Issue for FetchIssue {
async fn description(&self) -> Result<Option<StyledString>> { async fn description(&self) -> Result<Option<StyledString>> {
let url = &*self.url.await?; let url = &*self.url.await?;
let kind = &*self.kind.await?; let kind = &*self.kind.await?;
#[cfg(target_family = "wasm")]
let detail = &*self.detail.await?;
Ok(Some(match kind { Ok(Some(match kind {
FetchErrorKind::Connect => StyledString::Line(vec![ FetchErrorKind::Connect => StyledString::Line(vec![
...@@ -115,6 +122,8 @@ impl Issue for FetchIssue { ...@@ -115,6 +122,8 @@ impl Issue for FetchIssue {
StyledString::Text(rcstr!("Connection timed out when requesting ")), StyledString::Text(rcstr!("Connection timed out when requesting ")),
StyledString::Code(url.clone()), StyledString::Code(url.clone()),
]), ]),
#[cfg(target_family = "wasm")]
FetchErrorKind::Unsupported => detail.clone(),
FetchErrorKind::Other => StyledString::Line(vec![ FetchErrorKind::Other => StyledString::Line(vec![
StyledString::Text(rcstr!("There was an issue requesting ")), StyledString::Text(rcstr!("There was an issue requesting ")),
StyledString::Code(url.clone()), StyledString::Code(url.clone()),
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment