Skip to content
Projects
Groups
Snippets
Help
Loading...
Sign in
Toggle navigation
N
next.js
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Alex
next.js
Commits
fb4332ff
Commit
fb4332ff
authored
Apr 02, 2026
by
Luke Sandberg
Committed by
Luke Sandberg
Apr 09, 2026
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
snappy wtf
parent
4abd123c
Hide whitespace changes
Inline
Side-by-side
Showing
16 changed files
with
346 additions
and
126 deletions
+346
-126
test-turbopack-rust-bench-test.yml
.github/workflows/test-turbopack-rust-bench-test.yml
+2
-2
app.rs
crates/next-api/src/app.rs
+7
-0
pages.rs
crates/next-api/src/pages.rs
+5
-0
project.rs
crates/next-api/src/project.rs
+18
-0
context.rs
crates/next-core/src/next_client/context.rs
+7
-1
context.rs
crates/next-core/src/next_server/context.rs
+7
-1
swc_ecma_transform_plugins.rs
.../src/next_shared/transforms/swc_ecma_transform_plugins.rs
+20
-5
project.rs
crates/next-napi-bindings/src/next_api/project.rs
+5
-0
transform.rs
crates/next-napi-bindings/src/transform.rs
+36
-9
lib.rs
crates/swc-plugin-backend-napi/src/lib.rs
+160
-72
package.json
packages/next-swc/package.json
+1
-1
generated-native.d.ts
packages/next/src/build/swc/generated-native.d.ts
+34
-26
index.ts
packages/next/src/build/swc/index.ts
+6
-1
wasm-manager.ts
packages/next/src/build/swc/wasm-manager.ts
+12
-1
wasm-worker.ts
packages/next/src/build/swc/wasm-worker.ts
+3
-1
swc_ecma_transform_plugins.rs
...cript-plugins/src/transform/swc_ecma_transform_plugins.rs
+23
-6
No files found.
.github/workflows/test-turbopack-rust-bench-test.yml
View file @
fb4332ff
...
...
@@ -49,12 +49,12 @@ jobs:
-
name
:
Build benchmarks for tests
timeout-minutes
:
120
run
:
|
cargo test --benches --workspace --release --no-fail-fast --exclude turbopack-bench --exclude next-napi-bindings --no-run
cargo test --benches --workspace --release --no-fail-fast --exclude turbopack-bench --exclude next-napi-bindings --
exclude turbopack-ecmascript-plugins --exclude next-core --
no-run
-
name
:
Run cargo test on benchmarks
timeout-minutes
:
120
run
:
|
cargo test --benches --workspace --release --no-fail-fast --exclude turbopack-bench --exclude next-napi-bindings
cargo test --benches --workspace --release --no-fail-fast --exclude turbopack-bench --exclude next-napi-bindings
--exclude turbopack-ecmascript-plugins --exclude next-core
-
name
:
Build benchmarks for tests for other bundlers
if
:
inputs.all
...
...
crates/next-api/src/app.rs
View file @
fb4332ff
...
...
@@ -188,6 +188,7 @@ impl AppProject {
self
.project
()
.next_mode
(),
self
.project
()
.next_config
(),
self
.project
()
.encryption_key
(),
*
self
.project
()
.wasm_plugin_runtime_id
()
.await
?
,
))
}
...
...
@@ -220,6 +221,7 @@ impl AppProject {
self
.project
()
.encryption_key
(),
self
.project
()
.server_compile_time_info
()
.environment
(),
self
.project
()
.client_compile_time_info
()
.environment
(),
*
self
.project
()
.wasm_plugin_runtime_id
()
.await
?
,
))
}
...
...
@@ -235,6 +237,7 @@ impl AppProject {
self
.project
()
.encryption_key
(),
self
.project
()
.edge_compile_time_info
()
.environment
(),
self
.project
()
.client_compile_time_info
()
.environment
(),
*
self
.project
()
.wasm_plugin_runtime_id
()
.await
?
,
))
}
...
...
@@ -250,6 +253,7 @@ impl AppProject {
self
.project
()
.encryption_key
(),
self
.project
()
.server_compile_time_info
()
.environment
(),
self
.project
()
.client_compile_time_info
()
.environment
(),
*
self
.project
()
.wasm_plugin_runtime_id
()
.await
?
,
))
}
...
...
@@ -265,6 +269,7 @@ impl AppProject {
self
.project
()
.encryption_key
(),
self
.project
()
.edge_compile_time_info
()
.environment
(),
self
.project
()
.client_compile_time_info
()
.environment
(),
*
self
.project
()
.wasm_plugin_runtime_id
()
.await
?
,
))
}
...
...
@@ -592,6 +597,7 @@ impl AppProject {
self
.project
()
.encryption_key
(),
self
.project
()
.server_compile_time_info
()
.environment
(),
self
.project
()
.client_compile_time_info
()
.environment
(),
*
self
.project
()
.wasm_plugin_runtime_id
()
.await
?
,
))
}
...
...
@@ -607,6 +613,7 @@ impl AppProject {
self
.project
()
.encryption_key
(),
self
.project
()
.edge_compile_time_info
()
.environment
(),
self
.project
()
.client_compile_time_info
()
.environment
(),
*
self
.project
()
.wasm_plugin_runtime_id
()
.await
?
,
))
}
...
...
crates/next-api/src/pages.rs
View file @
fb4332ff
...
...
@@ -357,6 +357,7 @@ impl PagesProject {
self
.project
()
.next_mode
(),
self
.project
()
.next_config
(),
self
.project
()
.encryption_key
(),
*
self
.project
()
.wasm_plugin_runtime_id
()
.await
?
,
))
}
...
...
@@ -444,6 +445,7 @@ impl PagesProject {
self
.project
()
.encryption_key
(),
self
.project
()
.server_compile_time_info
()
.environment
(),
self
.project
()
.client_compile_time_info
()
.environment
(),
*
self
.project
()
.wasm_plugin_runtime_id
()
.await
?
,
))
}
...
...
@@ -461,6 +463,7 @@ impl PagesProject {
self
.project
()
.encryption_key
(),
self
.project
()
.edge_compile_time_info
()
.environment
(),
self
.project
()
.client_compile_time_info
()
.environment
(),
*
self
.project
()
.wasm_plugin_runtime_id
()
.await
?
,
))
}
...
...
@@ -478,6 +481,7 @@ impl PagesProject {
self
.project
()
.encryption_key
(),
self
.project
()
.server_compile_time_info
()
.environment
(),
self
.project
()
.client_compile_time_info
()
.environment
(),
*
self
.project
()
.wasm_plugin_runtime_id
()
.await
?
,
))
}
...
...
@@ -495,6 +499,7 @@ impl PagesProject {
self
.project
()
.encryption_key
(),
self
.project
()
.edge_compile_time_info
()
.environment
(),
self
.project
()
.client_compile_time_info
()
.environment
(),
*
self
.project
()
.wasm_plugin_runtime_id
()
.await
?
,
))
}
...
...
crates/next-api/src/project.rs
View file @
fb4332ff
...
...
@@ -375,6 +375,9 @@ pub struct ProjectOptions {
/// force new filenames without changing file content. Empty string means
/// no salt.
pub
hash_salt
:
RcStr
,
/// The runtime_id from register_wasm_plugin_runtime, used to look up the
/// NAPI-based WASM plugin runtime. 0 means no runtime registered.
pub
wasm_plugin_runtime_id
:
u64
,
}
#[derive(Default)]
...
...
@@ -824,6 +827,7 @@ impl ProjectContainer {
let
is_persistent_caching_enabled
;
let
server_hmr
;
let
hash_salt
;
let
wasm_plugin_runtime_id
;
{
let
options
=
self
.options_state
.get
();
let
options
=
options
...
...
@@ -853,6 +857,7 @@ impl ProjectContainer {
is_persistent_caching_enabled
=
options
.is_persistent_caching_enabled
;
server_hmr
=
options
.server_hmr
;
hash_salt
=
options
.hash_salt
.clone
();
wasm_plugin_runtime_id
=
options
.wasm_plugin_runtime_id
;
}
let
dist_dir
=
next_config
.dist_dir
()
.owned
()
.await
?
;
...
...
@@ -884,6 +889,7 @@ impl ProjectContainer {
is_persistent_caching_enabled
,
server_hmr
,
hash_salt
,
wasm_plugin_runtime_id
,
}
.cell
())
}
...
...
@@ -991,6 +997,9 @@ pub struct Project {
/// A salt to mix into chunk and asset content hashes. Empty string means
/// no salt.
hash_salt
:
RcStr
,
/// The runtime_id from register_wasm_plugin_runtime, used to look up the
/// NAPI-based WASM plugin runtime. 0 means no runtime registered.
wasm_plugin_runtime_id
:
u64
,
}
#[turbo_tasks
::
value]
...
...
@@ -1245,6 +1254,11 @@ impl Project {
Vc
::
cell
(
self
.encryption_key
.clone
())
}
#[turbo_tasks
::
function]
pub
(
super
)
fn
wasm_plugin_runtime_id
(
&
self
)
->
Vc
<
u64
>
{
Vc
::
cell
(
self
.wasm_plugin_runtime_id
)
}
#[turbo_tasks
::
function]
pub
(
super
)
fn
no_mangling
(
&
self
)
->
Vc
<
bool
>
{
Vc
::
cell
(
self
.no_mangling
)
...
...
@@ -1942,6 +1956,7 @@ impl Project {
self
.encryption_key
(),
self
.edge_compile_time_info
()
.environment
(),
self
.client_compile_time_info
()
.environment
(),
*
self
.wasm_plugin_runtime_id
()
.await
?
,
),
get_edge_resolve_options_context
(
self
.project_path
()
.owned
()
.await
?
,
...
...
@@ -2005,6 +2020,7 @@ impl Project {
self
.encryption_key
(),
self
.server_compile_time_info
()
.environment
(),
self
.client_compile_time_info
()
.environment
(),
*
self
.wasm_plugin_runtime_id
()
.await
?
,
),
get_server_resolve_options_context
(
self
.project_path
()
.owned
()
.await
?
,
...
...
@@ -2120,6 +2136,7 @@ impl Project {
self
.encryption_key
(),
self
.server_compile_time_info
()
.environment
(),
self
.client_compile_time_info
()
.environment
(),
*
self
.wasm_plugin_runtime_id
()
.await
?
,
),
get_server_resolve_options_context
(
self
.project_path
()
.owned
()
.await
?
,
...
...
@@ -2183,6 +2200,7 @@ impl Project {
self
.encryption_key
(),
self
.edge_compile_time_info
()
.environment
(),
self
.client_compile_time_info
()
.environment
(),
*
self
.wasm_plugin_runtime_id
()
.await
?
,
),
get_edge_resolve_options_context
(
self
.project_path
()
.owned
()
.await
?
,
...
...
crates/next-core/src/next_client/context.rs
View file @
fb4332ff
...
...
@@ -233,6 +233,7 @@ pub async fn get_client_module_options_context(
mode
:
Vc
<
NextMode
>
,
next_config
:
Vc
<
NextConfig
>
,
encryption_key
:
ResolvedVc
<
RcStr
>
,
wasm_plugin_runtime_id
:
u64
,
)
->
Result
<
Vc
<
ModuleOptionsContext
>>
{
let
next_mode
=
mode
.await
?
;
let
resolve_options_context
=
get_client_resolve_options_context
(
...
...
@@ -298,7 +299,12 @@ pub async fn get_client_module_options_context(
get_next_client_transforms_rules
(
next_config
,
ty
.clone
(),
mode
,
true
,
encryption_key
)
.await
?
;
let
additional_rules
:
Vec
<
ModuleRule
>
=
vec!
[
get_swc_ecma_transform_plugin_rule
(
next_config
,
project_path
.clone
())
.await
?
,
get_swc_ecma_transform_plugin_rule
(
next_config
,
project_path
.clone
(),
wasm_plugin_runtime_id
,
)
.await
?
,
get_relay_transform_rule
(
next_config
,
project_path
.clone
())
.await
?
,
get_emotion_transform_rule
(
next_config
)
.await
?
,
get_styled_components_transform_rule
(
next_config
)
.await
?
,
...
...
crates/next-core/src/next_server/context.rs
View file @
fb4332ff
...
...
@@ -418,6 +418,7 @@ pub async fn get_server_module_options_context(
encryption_key
:
ResolvedVc
<
RcStr
>
,
environment
:
ResolvedVc
<
Environment
>
,
client_environment
:
ResolvedVc
<
Environment
>
,
wasm_plugin_runtime_id
:
u64
,
)
->
Result
<
Vc
<
ModuleOptionsContext
>>
{
let
next_mode
=
mode
.await
?
;
let
mut
next_server_rules
=
get_next_server_transforms_rules
(
...
...
@@ -537,7 +538,12 @@ pub async fn get_server_module_options_context(
get_react_remove_properties_transform_rule
(
next_config
)
.await
?
,
get_emotion_transform_rule
(
next_config
)
.await
?
,
get_relay_transform_rule
(
next_config
,
project_path
.clone
())
.await
?
,
get_swc_ecma_transform_plugin_rule
(
next_config
,
project_path
.clone
())
.await
?
,
get_swc_ecma_transform_plugin_rule
(
next_config
,
project_path
.clone
(),
wasm_plugin_runtime_id
,
)
.await
?
,
]
.into_iter
()
.flatten
()
...
...
crates/next-core/src/next_shared/transforms/swc_ecma_transform_plugins.rs
View file @
fb4332ff
...
...
@@ -12,18 +12,25 @@ use crate::next_config::NextConfig;
pub
async
fn
get_swc_ecma_transform_plugin_rule
(
next_config
:
Vc
<
NextConfig
>
,
project_path
:
FileSystemPath
,
wasm_plugin_runtime_id
:
u64
,
)
->
Result
<
Option
<
ModuleRule
>>
{
let
plugin_configs
=
next_config
.experimental_swc_plugins
()
.await
?
;
if
!
plugin_configs
.is_empty
()
{
#[cfg(feature
=
"plugin"
)]
{
let
enable_mdx_rs
=
next_config
.mdx_rs
()
.await
?
.is_some
();
get_swc_ecma_transform_rule_impl
(
project_path
,
&
plugin_configs
,
enable_mdx_rs
)
.await
get_swc_ecma_transform_rule_impl
(
project_path
,
&
plugin_configs
,
enable_mdx_rs
,
wasm_plugin_runtime_id
,
)
.await
}
#[cfg(not(feature
=
"plugin"
))]
{
let
_
=
project_path
;
// To satisfy lint
let
_
=
(
project_path
,
wasm_plugin_runtime_id
);
Ok
(
None
)
}
}
else
{
...
...
@@ -66,6 +73,7 @@ pub async fn get_swc_ecma_transform_rule_impl(
project_path
:
FileSystemPath
,
plugin_configs
:
&
[(
RcStr
,
serde_json
::
Value
)],
enable_mdx_rs
:
bool
,
wasm_plugin_runtime_id
:
u64
,
)
->
Result
<
Option
<
ModuleRule
>>
{
use
anyhow
::
bail
;
use
turbo_tasks
::
TryFlatJoinIterExt
;
...
...
@@ -147,8 +155,12 @@ pub async fn get_swc_ecma_transform_rule_impl(
};
Ok
(
Some
((
SwcPluginModule
::
new
(
name
.clone
(),
file
.content
()
.to_bytes
()
.to_vec
())
.resolved_cell
(),
SwcPluginModule
::
new
(
name
.clone
(),
file
.content
()
.to_bytes
()
.to_vec
(),
wasm_plugin_runtime_id
,
)
.resolved_cell
(),
config
.clone
(),
)))
}
...
...
@@ -157,7 +169,10 @@ pub async fn get_swc_ecma_transform_rule_impl(
.await
?
;
Ok
(
Some
(
get_ecma_transform_rule
(
Box
::
new
(
SwcEcmaTransformPluginsTransformer
::
new
(
plugins
)),
Box
::
new
(
SwcEcmaTransformPluginsTransformer
::
new
(
plugins
,
wasm_plugin_runtime_id
,
)),
enable_mdx_rs
,
EcmascriptTransformStage
::
Main
,
)))
...
...
crates/next-napi-bindings/src/next_api/project.rs
View file @
fb4332ff
...
...
@@ -221,6 +221,9 @@ pub struct NapiProjectOptions {
/// force new filenames without changing file content. Empty string means
/// no salt.
pub
hash_salt
:
RcStr
,
/// The runtime_id from registerWasmPluginRuntime, used to look up the
/// NAPI-based WASM plugin runtime. Omit or pass 0 if no plugins are used.
pub
wasm_plugin_runtime_id
:
Option
<
f64
>
,
}
/// [NapiProjectOptions] with all fields optional.
...
...
@@ -335,6 +338,7 @@ impl From<NapiProjectOptions> for ProjectOptions {
next_version
,
server_hmr
,
hash_salt
,
wasm_plugin_runtime_id
:
_wasm_plugin_runtime_id
,
}
=
val
;
ProjectOptions
{
root_path
,
...
...
@@ -360,6 +364,7 @@ impl From<NapiProjectOptions> for ProjectOptions {
next_version
,
server_hmr
:
server_hmr
.unwrap_or
(
false
),
hash_salt
,
wasm_plugin_runtime_id
:
_wasm_plugin_runtime_id
.map
(|
v
|
v
as
u64
)
.unwrap_or
(
0
),
}
}
}
...
...
crates/next-napi-bindings/src/transform.rs
View file @
fb4332ff
...
...
@@ -50,6 +50,11 @@ use swc_core::{
use
crate
::{
complete_output
,
get_compiler
,
util
::
MapErr
};
/// The runtime_id from the most recent register_wasm_plugin_runtime call.
/// Used by the webpack transform path which doesn't go through Project.
#[cfg(feature
=
"plugin"
)]
static
CURRENT_WASM_RUNTIME_ID
:
std
::
sync
::
atomic
::
AtomicU64
=
std
::
sync
::
atomic
::
AtomicU64
::
new
(
0
);
/// Input to transform
#[derive(Debug)]
pub
enum
Input
{
...
...
@@ -63,6 +68,8 @@ pub struct TransformTask {
pub
c
:
Compiler
,
pub
input
:
Input
,
pub
options
:
Buffer
,
#[cfg(feature
=
"plugin"
)]
pub
wasm_plugin_runtime_id
:
u64
,
}
fn
skip_filename
()
->
bool
{
...
...
@@ -133,11 +140,16 @@ impl Task for TransformTask {
#[cfg(feature
=
"plugin"
)]
{
options
.swc.runtime_options
=
swc_core
::
base
::
config
::
RuntimeOptions
::
default
()
.plugin_runtime
(
std
::
sync
::
Arc
::
new
(
swc_plugin_backend_napi
::
NapiRuntime
,
));
if
self
.wasm_plugin_runtime_id
!=
0
{
let
runtime
=
swc_plugin_backend_napi
::
NapiRuntime
::
from_runtime_id
(
self
.wasm_plugin_runtime_id
,
)
.map_err
(|
e
|
anyhow!
(
e
))
?
;
options
.swc.runtime_options
=
swc_core
::
base
::
config
::
RuntimeOptions
::
default
()
.plugin_runtime
(
std
::
sync
::
Arc
::
new
(
runtime
));
}
}
let
cm
=
self
.c.cm
.clone
();
...
...
@@ -227,7 +239,13 @@ pub fn transform(
Either3
::
C
(
_
)
=>
Input
::
FromFilename
,
};
let
task
=
TransformTask
{
c
,
input
,
options
};
let
task
=
TransformTask
{
c
,
input
,
options
,
#[cfg(feature
=
"plugin"
)]
wasm_plugin_runtime_id
:
CURRENT_WASM_RUNTIME_ID
.load
(
std
::
sync
::
atomic
::
Ordering
::
Relaxed
),
};
Ok
(
AsyncTask
::
with_optional_signal
(
task
,
signal
))
}
...
...
@@ -248,7 +266,13 @@ pub fn transform_sync(
Either3
::
C
(
_
)
=>
Input
::
FromFilename
,
};
let
mut
task
=
TransformTask
{
c
,
input
,
options
};
let
mut
task
=
TransformTask
{
c
,
input
,
options
,
#[cfg(feature
=
"plugin"
)]
wasm_plugin_runtime_id
:
CURRENT_WASM_RUNTIME_ID
.load
(
std
::
sync
::
atomic
::
Ordering
::
Relaxed
),
};
let
output
=
task
.compute
()
?
;
task
.resolve
(
env
,
output
)
}
...
...
@@ -263,10 +287,13 @@ fn test_deser() {
/// Register the NAPI-based WASM plugin runtime.
/// Must be called from JS before any SWC transforms that use plugins.
/// Returns the runtime_id that identifies this registration.
#[cfg(feature
=
"plugin"
)]
#[napi]
pub
fn
register_wasm_plugin_runtime
(
env
:
Env
,
js_manager
:
JsObject
)
->
napi
::
Result
<
()
>
{
swc_plugin_backend_napi
::
register_wasm_runtime
(
&
env
,
&
js_manager
)
pub
fn
register_wasm_plugin_runtime
(
env
:
Env
,
js_manager
:
JsObject
)
->
napi
::
Result
<
f64
>
{
let
runtime_id
=
swc_plugin_backend_napi
::
register_wasm_runtime
(
&
env
,
&
js_manager
)
?
;
CURRENT_WASM_RUNTIME_ID
.store
(
runtime_id
,
std
::
sync
::
atomic
::
Ordering
::
Relaxed
);
Ok
(
runtime_id
as
f64
)
}
#[test]
...
...
crates/swc-plugin-backend-napi/src/lib.rs
View file @
fb4332ff
...
...
@@ -2,7 +2,11 @@ use std::{
cell
::
UnsafeCell
,
collections
::
HashMap
,
path
::
Path
,
sync
::{
Arc
,
LazyLock
,
Mutex
,
OnceLock
,
mpsc
},
sync
::{
Arc
,
LazyLock
,
Mutex
,
RwLock
,
atomic
::{
AtomicU64
,
Ordering
},
mpsc
,
},
};
use
napi
::{
...
...
@@ -14,26 +18,60 @@ use swc_plugin_runner::runtime;
/// Identifier for cache stored in local filesystem.
const
NAPI_RUNTIME_ID
:
&
str
=
"napi-v8-v1"
;
//
/ Global TSFN for dispatching operations to the JS main thread.
//
/ Used for module compilation, instantiation, and non-hot-path memory ops.
static
WASM_TSFN
:
OnceLock
<
ThreadsafeFunction
<
WasmRequest
>>
=
OnceLock
::
new
();
//
---------------------------------------------------------------------------
//
Shared runtime state — one per register_wasm_runtime call
// ---------------------------------------------------------------------------
/// The raw napi_env pointer that registered the WASM runtime.
/// Used to assert we're never re-registered from a different environment.
static
WASM_TSFN_ENV
:
OnceLock
<
usize
>
=
OnceLock
::
new
();
/// All per-env state that was previously in global statics.
pub
struct
WasmRuntimeState
{
/// Unique ID for this runtime registration.
pub
runtime_id
:
u64
,
/// TSFN for dispatching operations to the JS main thread.
tsfn
:
ThreadsafeFunction
<
WasmRequest
>
,
/// Per-instance TSFN registry: maps instance_id → TSFN targeting the worker thread.
instance_tsfns
:
Mutex
<
HashMap
<
u64
,
Arc
<
ThreadsafeFunction
<
InstanceWork
>>>>
,
/// Per-instance host function registry: maps instance_id → Vec<Func>.
host_fns
:
Mutex
<
HashMap
<
u64
,
Arc
<
Vec
<
runtime
::
Func
>>>>
,
}
/// Global host function registry: maps instance_id → Vec<Func>.
/// Workers call back into these during WASM execution via NAPI.
static
HOST_FNS
:
LazyLock
<
Mutex
<
HashMap
<
u64
,
Arc
<
Vec
<
runtime
::
Func
>>>>>
=
LazyLock
::
new
(||
Mutex
::
new
(
HashMap
::
new
()));
impl
std
::
fmt
::
Debug
for
WasmRuntimeState
{
fn
fmt
(
&
self
,
f
:
&
mut
std
::
fmt
::
Formatter
<
'_
>
)
->
std
::
fmt
::
Result
{
f
.debug_struct
(
"WasmRuntimeState"
)
.field
(
"runtime_id"
,
&
self
.runtime_id
)
.finish_non_exhaustive
()
}
}
/// Global per-instance TSFN registry: maps instance_id → TSFN targeting the worker thread.
/// Used to dispatch transform/getDiag/memory ops to the correct worker.
static
INSTANCE_TSFNS
:
LazyLock
<
Mutex
<
HashMap
<
u64
,
Arc
<
ThreadsafeFunction
<
InstanceWork
>>>>>
=
LazyLock
::
new
(||
Mutex
::
new
(
HashMap
::
new
()));
/// Monotonically increasing runtime ID counter.
static
NEXT_RUNTIME_ID
:
AtomicU64
=
AtomicU64
::
new
(
1
);
/// Global registry of live runtime states, keyed by runtime_id.
/// Multiple runtimes can coexist (e.g. across different napi_envs in tests).
static
RUNTIMES
:
LazyLock
<
RwLock
<
HashMap
<
u64
,
Arc
<
WasmRuntimeState
>>>>
=
LazyLock
::
new
(||
RwLock
::
new
(
HashMap
::
new
()));
fn
get_runtime_state
(
runtime_id
:
u64
)
->
anyhow
::
Result
<
Arc
<
WasmRuntimeState
>>
{
RUNTIMES
.read
()
.unwrap
()
.get
(
&
runtime_id
)
.cloned
()
.ok_or_else
(||
anyhow
::
anyhow!
(
"No WASM runtime registered with id {}"
,
runtime_id
))
}
fn
get_runtime_state_napi
(
runtime_id
:
u64
)
->
napi
::
Result
<
Arc
<
WasmRuntimeState
>>
{
RUNTIMES
.read
()
.unwrap
()
.get
(
&
runtime_id
)
.cloned
()
.ok_or_else
(||
{
napi
::
Error
::
from_reason
(
format!
(
"No WASM runtime registered with id {}"
,
runtime_id
))
})
}
// ---------------------------------------------------------------------------
// Per-instance work dispatch via TSFN
(no more Condvar work queue)
// Per-instance work dispatch via TSFN
// ---------------------------------------------------------------------------
enum
InstanceWork
{
...
...
@@ -110,12 +148,13 @@ impl OptRef {
/// Dispatch work to an instance's worker thread via its TSFN and block for the result.
fn
instance_call_blocking
<
T
:
Send
+
'static
>
(
state
:
&
WasmRuntimeState
,
instance_id
:
u64
,
work
:
InstanceWork
,
rx
:
mpsc
::
Receiver
<
anyhow
::
Result
<
T
>>
,
)
->
anyhow
::
Result
<
T
>
{
let
tsfn
=
{
let
tsfns
=
INSTANCE_TSFNS
.lock
()
.unwrap
();
let
tsfns
=
state
.instance_tsfns
.lock
()
.unwrap
();
tsfns
.get
(
&
instance_id
)
.ok_or_else
(||
anyhow
::
anyhow!
(
"No TSFN for instance {}"
,
instance_id
))
?
...
...
@@ -149,10 +188,13 @@ fn instance_call_blocking<T: Send + 'static>(
#[napi_derive
::
napi]
pub
fn
wasm_worker_register_callback
(
env
:
Env
,
runtime_id
:
f64
,
instance_id
:
f64
,
ops
:
JsObject
,
)
->
napi
::
Result
<
()
>
{
let
rid
=
runtime_id
as
u64
;
let
id
=
instance_id
as
u64
;
let
state
=
get_runtime_state_napi
(
rid
)
?
;
// Extract and ref each function up front so we don't do property lookups on every call.
let
transform_fn
:
JsFunction
=
ops
.get_named_property
(
"transform"
)
?
;
...
...
@@ -318,7 +360,11 @@ pub fn wasm_worker_register_callback(
},
)
?
;
INSTANCE_TSFNS
.lock
()
.unwrap
()
.insert
(
id
,
Arc
::
new
(
tsfn
));
state
.instance_tsfns
.lock
()
.unwrap
()
.insert
(
id
,
Arc
::
new
(
tsfn
));
Ok
(())
}
...
...
@@ -333,13 +379,17 @@ pub fn wasm_worker_register_callback(
#[napi_derive
::
napi]
pub
fn
wasm_worker_dispatch_host_fn
(
env
:
Env
,
runtime_id
:
f64
,
instance_id
:
f64
,
fn_index
:
u32
,
args
:
Vec
<
i32
>
,
memory_accessor
:
JsObject
,
)
->
napi
::
Result
<
JsUnknown
>
{
let
rid
=
runtime_id
as
u64
;
let
id
=
instance_id
as
u64
;
let
fns
=
HOST_FNS
.lock
()
.unwrap
();
let
state
=
get_runtime_state_napi
(
rid
)
?
;
let
fns
=
state
.host_fns
.lock
()
.unwrap
();
let
host_functions
=
fns
.get
(
&
id
)
.ok_or_else
(||
napi
::
Error
::
from_reason
(
format!
(
"No host fns for instance {}"
,
id
)))
?
...
...
@@ -456,6 +506,8 @@ enum WasmRequest {
},
DropInstance
{
instance_id
:
u64
,
/// The runtime state, needed to clean up instance_tsfns and host_fns.
state
:
Arc
<
WasmRuntimeState
>
,
},
}
...
...
@@ -473,18 +525,10 @@ struct HostFnDescriptor {
// TSFN registration
// ---------------------------------------------------------------------------
pub
fn
register_wasm_runtime
(
env
:
&
Env
,
js_manager
:
&
JsObject
)
->
napi
::
Result
<
()
>
{
let
env_addr
=
env
.raw
()
as
usize
;
// Idempotent: skip if already registered from the same Env.
if
WASM_TSFN
.get
()
.is_some
()
{
let
registered_env
=
WASM_TSFN_ENV
.get
()
.copied
()
.unwrap_or
(
0
);
assert_eq!
(
registered_env
,
env_addr
,
"WASM runtime already registered from a different napi_env"
);
return
Ok
(());
}
/// Register the NAPI-based WASM plugin runtime.
/// Returns the runtime_id that can be used to look up this runtime later.
pub
fn
register_wasm_runtime
(
env
:
&
Env
,
js_manager
:
&
JsObject
)
->
napi
::
Result
<
u64
>
{
let
runtime_id
=
NEXT_RUNTIME_ID
.fetch_add
(
1
,
Ordering
::
Relaxed
);
let
mut
global
=
env
.get_global
()
?
;
global
.set_named_property
(
"__nextSwcWasmManager"
,
js_manager
)
?
;
...
...
@@ -510,12 +554,16 @@ pub fn register_wasm_runtime(env: &Env, js_manager: &JsObject) -> napi::Result<(
Ok
(
Vec
::
<
JsUnknown
>
::
new
())
})
?
;
WASM_TSFN
.set
(
tsfn
)
.map_err
(|
_
|
napi
::
Error
::
from_reason
(
"WASM TSFN already registered"
))
?
;
let
_
=
WASM_TSFN_ENV
.set
(
env_addr
);
let
state
=
Arc
::
new
(
WasmRuntimeState
{
runtime_id
,
tsfn
,
instance_tsfns
:
Mutex
::
new
(
HashMap
::
new
()),
host_fns
:
Mutex
::
new
(
HashMap
::
new
()),
});
Ok
(())
RUNTIMES
.write
()
.unwrap
()
.insert
(
runtime_id
,
state
);
Ok
(
runtime_id
)
}
fn
num_cpus
()
->
usize
{
...
...
@@ -556,11 +604,16 @@ fn handle_wasm_request(env: &Env, manager: &JsObject, request: WasmRequest) -> n
drop_fn
.call
(
None
,
&
[
env
.create_double
(
module_id
as
f64
)
?
.into_unknown
()])
?
;
}
WasmRequest
::
DropInstance
{
instance_id
}
=>
{
WasmRequest
::
DropInstance
{
instance_id
,
state
}
=>
{
// Send Cleanup to the worker's TSFN to unref NAPI Refs before
// we drop the TSFN (which would drop the closure and trigger
// debug_assert panics in Ref::drop).
let
tsfn
=
INSTANCE_TSFNS
.lock
()
.unwrap
()
.get
(
&
instance_id
)
.cloned
();
let
tsfn
=
state
.instance_tsfns
.lock
()
.unwrap
()
.get
(
&
instance_id
)
.cloned
();
if
let
Some
(
tsfn
)
=
&
tsfn
{
let
(
tx
,
rx
)
=
mpsc
::
sync_channel
(
1
);
...
...
@@ -574,10 +627,10 @@ fn handle_wasm_request(env: &Env, manager: &JsObject, request: WasmRequest) -> n
// Now safe to remove the TSFN — all Refs have been unref'd
drop
(
tsfn
);
INSTANCE_TSFNS
.lock
()
.unwrap
()
.remove
(
&
instance_id
);
state
.instance_tsfns
.lock
()
.unwrap
()
.remove
(
&
instance_id
);
// Clean up host functions
HOST_FNS
.lock
()
.unwrap
()
.remove
(
&
instance_id
);
state
.host_fns
.lock
()
.unwrap
()
.remove
(
&
instance_id
);
let
drop_fn
:
JsFunction
=
manager
.get_named_property
(
"dropInstance"
)
?
;
drop_fn
.call
(
...
...
@@ -590,14 +643,14 @@ fn handle_wasm_request(env: &Env, manager: &JsObject, request: WasmRequest) -> n
}
fn
tsfn_call_blocking
<
T
:
Send
+
'static
>
(
state
:
&
WasmRuntimeState
,
request_fn
:
impl
FnOnce
(
mpsc
::
SyncSender
<
T
>
)
->
WasmRequest
,
)
->
anyhow
::
Result
<
T
>
{
let
tsfn
=
WASM_TSFN
.get
()
.ok_or_else
(||
anyhow
::
anyhow!
(
"WASM TSFN not registered"
))
?
;
let
(
tx
,
rx
)
=
mpsc
::
sync_channel
(
1
);
let
request
=
request_fn
(
tx
);
let
status
=
tsfn
.call
(
Ok
(
request
),
ThreadsafeFunctionCallMode
::
Blocking
);
let
status
=
state
.tsfn
.call
(
Ok
(
request
),
ThreadsafeFunctionCallMode
::
Blocking
);
if
!
matches!
(
status
,
Status
::
Ok
)
{
anyhow
::
bail!
(
"TSFN call failed with status: {:?}"
,
status
);
}
...
...
@@ -682,8 +735,18 @@ struct NapiModuleCache {
module_id
:
u64
,
}
#[derive(Clone,
Copy,
Debug)]
pub
struct
NapiRuntime
;
#[derive(Clone,
Debug)]
pub
struct
NapiRuntime
{
state
:
Arc
<
WasmRuntimeState
>
,
}
impl
NapiRuntime
{
/// Look up a registered runtime by its ID.
pub
fn
from_runtime_id
(
runtime_id
:
u64
)
->
anyhow
::
Result
<
Self
>
{
let
state
=
get_runtime_state
(
runtime_id
)
?
;
Ok
(
NapiRuntime
{
state
})
}
}
impl
runtime
::
Runtime
for
NapiRuntime
{
fn
identifier
(
&
self
)
->
&
'static
str
{
...
...
@@ -692,8 +755,10 @@ impl runtime::Runtime for NapiRuntime {
fn
prepare_module
(
&
self
,
bytes
:
&
[
u8
])
->
anyhow
::
Result
<
runtime
::
ModuleCache
>
{
let
wasm_bytes
=
bytes
.to_vec
();
let
module_id
=
tsfn_call_blocking
(|
reply
|
WasmRequest
::
CompileModule
{
wasm_bytes
,
reply
})
??
;
let
module_id
=
tsfn_call_blocking
(
&
self
.state
,
|
reply
|
WasmRequest
::
CompileModule
{
wasm_bytes
,
reply
,
})
??
;
Ok
(
runtime
::
ModuleCache
(
Box
::
new
(
NapiModuleCache
{
module_id
,
})))
...
...
@@ -712,7 +777,10 @@ impl runtime::Runtime for NapiRuntime {
}
runtime
::
Module
::
Bytes
(
buf
)
=>
{
let
wasm_bytes
=
buf
.to_vec
();
tsfn_call_blocking
(|
reply
|
WasmRequest
::
CompileModule
{
wasm_bytes
,
reply
})
??
tsfn_call_blocking
(
&
self
.state
,
|
reply
|
WasmRequest
::
CompileModule
{
wasm_bytes
,
reply
,
})
??
}
};
...
...
@@ -731,18 +799,23 @@ impl runtime::Runtime for NapiRuntime {
// Instantiate on a worker thread via TSFN → postMessage.
// The worker will call wasmWorkerRegisterCallback to set up the per-instance TSFN.
let
instance_id
=
tsfn_call_blocking
(|
reply
|
WasmRequest
::
Instantiate
{
let
instance_id
=
tsfn_call_blocking
(
&
self
.state
,
|
reply
|
WasmRequest
::
Instantiate
{
module_id
,
host_fn_descriptors
,
reply
,
})
??
;
// Store host functions so worker can call them via NAPI.
HOST_FNS
.lock
()
.unwrap
()
.insert
(
instance_id
,
host_functions
);
self
.state
.host_fns
.lock
()
.unwrap
()
.insert
(
instance_id
,
host_functions
);
let
mut
instance
=
NapiInstance
{
instance_id
,
module_id
,
state
:
self
.state
.clone
(),
};
// The runtime contract requires calling __get_transform_plugin_core_pkg_diag
...
...
@@ -754,7 +827,7 @@ impl runtime::Runtime for NapiRuntime {
fn
clone_cache
(
&
self
,
cache
:
&
runtime
::
ModuleCache
)
->
Option
<
runtime
::
ModuleCache
>
{
let
cache
=
cache
.
0
.downcast_ref
::
<
NapiModuleCache
>
()
?
;
let
module_id
=
tsfn_call_blocking
(|
reply
|
WasmRequest
::
CloneModule
{
let
module_id
=
tsfn_call_blocking
(
&
self
.state
,
|
reply
|
WasmRequest
::
CloneModule
{
module_id
:
cache
.module_id
,
reply
,
})
...
...
@@ -781,6 +854,7 @@ impl runtime::Runtime for NapiRuntime {
struct
NapiInstance
{
instance_id
:
u64
,
module_id
:
u64
,
state
:
Arc
<
WasmRuntimeState
>
,
}
unsafe
impl
Sync
for
NapiInstance
{}
...
...
@@ -795,6 +869,7 @@ impl runtime::Instance for NapiInstance {
)
->
anyhow
::
Result
<
u32
>
{
let
(
tx
,
rx
)
=
mpsc
::
sync_channel
(
1
);
let
result
=
instance_call_blocking
(
&
self
.state
,
self
.instance_id
,
InstanceWork
::
Transform
{
program_ptr
,
...
...
@@ -815,6 +890,7 @@ impl runtime::Instance for NapiInstance {
fn
caller
(
&
mut
self
)
->
anyhow
::
Result
<
Box
<
dyn
runtime
::
Caller
<
'_
>
+
'_
>>
{
Ok
(
Box
::
new
(
TsfnCaller
{
instance_id
:
self
.instance_id
,
state
:
&
self
.state
,
}))
}
...
...
@@ -826,8 +902,12 @@ impl runtime::Instance for NapiInstance {
impl
NapiInstance
{
fn
get_diag
(
&
mut
self
)
->
anyhow
::
Result
<
u32
>
{
let
(
tx
,
rx
)
=
mpsc
::
sync_channel
(
1
);
let
result
=
instance_call_blocking
(
self
.instance_id
,
InstanceWork
::
GetDiag
{
reply
:
tx
},
rx
)
?
;
let
result
=
instance_call_blocking
(
&
self
.state
,
self
.instance_id
,
InstanceWork
::
GetDiag
{
reply
:
tx
},
rx
,
)
?
;
if
result
==
-
1
{
anyhow
::
bail!
(
"getDiag failed in worker"
);
...
...
@@ -841,22 +921,25 @@ impl Drop for NapiInstance {
// Clean up host functions synchronously so that Arc references held by
// Func closures (e.g. TransformResultHostEnvironment) are released
// before the caller tries Arc::try_unwrap on transform_result.
HOST_FNS
.lock
()
.unwrap
()
.remove
(
&
self
.instance_id
);
if
let
Some
(
tsfn
)
=
WASM_TSFN
.get
()
{
tsfn
.call
(
Ok
(
WasmRequest
::
DropInstance
{
instance_id
:
self
.instance_id
,
}),
ThreadsafeFunctionCallMode
::
NonBlocking
,
);
tsfn
.call
(
Ok
(
WasmRequest
::
DropModule
{
module_id
:
self
.module_id
,
}),
ThreadsafeFunctionCallMode
::
NonBlocking
,
);
}
self
.state
.host_fns
.lock
()
.unwrap
()
.remove
(
&
self
.instance_id
);
self
.state.tsfn
.call
(
Ok
(
WasmRequest
::
DropInstance
{
instance_id
:
self
.instance_id
,
state
:
self
.state
.clone
(),
}),
ThreadsafeFunctionCallMode
::
NonBlocking
,
);
self
.state.tsfn
.call
(
Ok
(
WasmRequest
::
DropModule
{
module_id
:
self
.module_id
,
}),
ThreadsafeFunctionCallMode
::
NonBlocking
,
);
}
}
...
...
@@ -864,15 +947,17 @@ impl Drop for NapiInstance {
// TsfnCaller: memory ops via per-instance TSFN
// ---------------------------------------------------------------------------
struct
TsfnCaller
{
struct
TsfnCaller
<
'a
>
{
instance_id
:
u64
,
state
:
&
'a
WasmRuntimeState
,
}
impl
<
'a
>
runtime
::
Caller
<
'a
>
for
TsfnCaller
{
impl
<
'a
>
runtime
::
Caller
<
'a
>
for
TsfnCaller
<
'a
>
{
fn
read_buf
(
&
self
,
ptr
:
u32
,
buf
:
&
mut
[
u8
])
->
anyhow
::
Result
<
()
>
{
let
len
=
buf
.len
()
as
u32
;
let
(
tx
,
rx
)
=
mpsc
::
sync_channel
(
1
);
let
data
=
instance_call_blocking
(
self
.state
,
self
.instance_id
,
InstanceWork
::
ReadMemory
{
ptr
,
...
...
@@ -888,6 +973,7 @@ impl<'a> runtime::Caller<'a> for TsfnCaller {
fn
write_buf
(
&
mut
self
,
ptr
:
u32
,
buf
:
&
[
u8
])
->
anyhow
::
Result
<
()
>
{
let
(
tx
,
rx
)
=
mpsc
::
sync_channel
(
1
);
instance_call_blocking
(
self
.state
,
self
.instance_id
,
InstanceWork
::
WriteMemory
{
ptr
,
...
...
@@ -901,6 +987,7 @@ impl<'a> runtime::Caller<'a> for TsfnCaller {
fn
alloc
(
&
mut
self
,
size
:
u32
)
->
anyhow
::
Result
<
u32
>
{
let
(
tx
,
rx
)
=
mpsc
::
sync_channel
(
1
);
instance_call_blocking
(
self
.state
,
self
.instance_id
,
InstanceWork
::
Alloc
{
size
,
reply
:
tx
},
rx
,
...
...
@@ -910,6 +997,7 @@ impl<'a> runtime::Caller<'a> for TsfnCaller {
fn
free
(
&
mut
self
,
ptr
:
u32
,
size
:
u32
)
->
anyhow
::
Result
<
u32
>
{
let
(
tx
,
rx
)
=
mpsc
::
sync_channel
(
1
);
instance_call_blocking
(
self
.state
,
self
.instance_id
,
InstanceWork
::
Free
{
ptr
,
...
...
packages/next-swc/package.json
View file @
fb4332ff
...
...
@@ -21,7 +21,7 @@
"rust-check-doc"
:
"RUSTDOCFLAGS='-Zunstable-options --output-format=json' cargo doc --no-deps --workspace"
,
"rust-check-fmt"
:
"cd ../..; cargo fmt -- --check"
,
"rust-check-napi"
:
"cargo check -p next-napi-bindings"
,
"test-cargo-unit"
:
"cargo nextest run --workspace --exclude next-napi-bindings --exclude turbo-tasks-macros --cargo-profile release-with-assertions --no-fail-fast"
"test-cargo-unit"
:
"cargo nextest run --workspace --exclude next-napi-bindings --exclude turbo
pack-ecmascript-plugins --exclude next-core --exclude turbo
-tasks-macros --cargo-profile release-with-assertions --no-fail-fast"
},
"napi"
:
{
"name"
:
"next-swc"
,
...
...
packages/next/src/build/swc/generated-native.d.ts
View file @
fb4332ff
...
...
@@ -21,7 +21,8 @@ export function lightningCssTransformStyleAttribute(
export
function
lightningcssFeatureNamesToMaskNapi
(
names
:
Array
<
string
>
):
number
// Optional: only available when built with the "plugin" feature.
export
function
registerWasmPluginRuntime
(
jsManager
:
object
):
void
// Returns the runtime_id that identifies this registration.
export
function
registerWasmPluginRuntime
(
jsManager
:
object
):
number
// GENERATED-TYPES-BELOW
// DO NOT MANUALLY EDIT THESE TYPES
...
...
@@ -38,30 +39,6 @@ export declare class ExternalObject<T> {
[
K
:
symbol
]:
T
}
}
export
declare
function
registerWorkerScheduler
(
creator
:
(
arg
:
NapiWorkerCreation
)
=>
any
,
terminator
:
(
arg
:
NapiWorkerTermination
)
=>
any
):
void
export
declare
function
workerCreated
(
workerId
:
number
):
void
export
interface
NapiWorkerCreation
{
options
:
NapiWorkerOptions
}
export
interface
NapiWorkerOptions
{
filename
:
RcStr
cwd
:
RcStr
}
export
interface
NapiWorkerTermination
{
options
:
NapiWorkerOptions
workerId
:
number
}
export
interface
NapiTaskMessage
{
taskId
:
number
data
:
Buffer
}
export
declare
function
recvTaskMessageInWorker
(
workerId
:
number
):
Promise
<
NapiTaskMessage
>
export
declare
function
sendTaskMessage
(
message
:
NapiTaskMessage
):
Promise
<
void
>
/**
* Called by worker after WASM instantiation to register a dispatch callback.
*
...
...
@@ -78,6 +55,7 @@ export declare function sendTaskMessage(message: NapiTaskMessage): Promise<void>
* method on `ops` and sends the result back via a sync channel.
*/
export
declare
function
wasmWorkerRegisterCallback
(
runtimeId
:
number
,
instanceId
:
number
,
ops
:
object
):
void
...
...
@@ -92,11 +70,36 @@ export declare function wasmWorkerRegisterCallback(
* - free(ptr, size) → number
*/
export
declare
function
wasmWorkerDispatchHostFn
(
runtimeId
:
number
,
instanceId
:
number
,
fnIndex
:
number
,
args
:
Array
<
number
>
,
memoryAccessor
:
object
):
unknown
export
declare
function
registerWorkerScheduler
(
creator
:
(
arg
:
NapiWorkerCreation
)
=>
any
,
terminator
:
(
arg
:
NapiWorkerTermination
)
=>
any
):
void
export
declare
function
workerCreated
(
workerId
:
number
):
void
export
interface
NapiWorkerCreation
{
options
:
NapiWorkerOptions
}
export
interface
NapiWorkerOptions
{
filename
:
RcStr
cwd
:
RcStr
}
export
interface
NapiWorkerTermination
{
options
:
NapiWorkerOptions
workerId
:
number
}
export
interface
NapiTaskMessage
{
taskId
:
number
data
:
Buffer
}
export
declare
function
recvTaskMessageInWorker
(
workerId
:
number
):
Promise
<
NapiTaskMessage
>
export
declare
function
sendTaskMessage
(
message
:
NapiTaskMessage
):
Promise
<
void
>
export
interface
NapiLocation
{
line
:
number
column
?:
number
...
...
@@ -302,6 +305,10 @@ export interface NapiProjectOptions {
* no salt.
*/
hashSalt
:
RcStr
*
The
runtime_id
from
registerWasmPluginRuntime
,
used
to
look
up
the
*
NAPI
-
based
WASM
plugin
runtime
.
Omit
or
pass
0
if
no
plugins
are
used
.
*
/
wasmPluginRuntimeId
?:
number
}
/** [NapiProjectOptions] with all fields optional. */
export
interface
NapiPartialProjectOptions
{
...
...
@@ -656,8 +663,9 @@ export declare function transformSync(
/**
* Register the NAPI-based WASM plugin runtime.
* Must be called from JS before any SWC transforms that use plugins.
* Returns the runtime_id that identifies this registration.
*/
export
declare
function
registerWasmPluginRuntime
(
jsManager
:
object
):
void
export
declare
function
registerWasmPluginRuntime
(
jsManager
:
object
):
number
export
declare
function
startTurbopackTraceServer
(
path
:
string
,
port
?:
number
|
undefined
|
null
...
...
packages/next/src/build/swc/index.ts
View file @
fb4332ff
...
...
@@ -172,6 +172,9 @@ let loadedBindings: Binding | undefined = undefined
let
downloadWasmPromise
:
any
let
swcTraceFlushGuard
:
any
let
downloadNativeBindingsPromise
:
Promise
<
void
>
|
undefined
=
undefined
// The runtime_id returned by registerWasmPluginRuntime, passed to turbopack
// project creation so it can look up the correct WASM plugin runtime.
let
wasmPluginRuntimeId
:
number
=
0
export
const
lockfilePatchPromise
:
{
cur
?:
Promise
<
void
>
}
=
{}
...
...
@@ -662,6 +665,7 @@ function bindingToApi(
path.join(options.rootPath, options.projectPath)
),
env: rustifyEnv(options.env),
wasmPluginRuntimeId: wasmPluginRuntimeId || undefined,
}
}
...
...
@@ -1743,7 +1747,8 @@ function loadNative(importPath?: string): Binding {
const { wasmManager } =
require('./wasm-manager') as typeof import('./wasm-manager')
wasmManager.setBindingsPath(bindingsPath)
bindings.registerWasmPluginRuntime(wasmManager)
wasmPluginRuntimeId = bindings.registerWasmPluginRuntime(wasmManager)
wasmManager.setRuntimeId(wasmPluginRuntimeId)
}
return loadedBindings!
...
...
packages/next/src/build/swc/wasm-manager.ts
View file @
fb4332ff
...
...
@@ -39,6 +39,9 @@ const instanceWorkerMap = new Map<number, number>()
// Path to the native .node binding, set during init
let
nativeBindingsPath
:
string
|
null
=
null
// The runtime_id from registerWasmPluginRuntime, passed to workers
let
runtimeId
:
number
=
0
// ---------------------------------------------------------------------------
// Module cache: compile once, clone to workers for free
// ---------------------------------------------------------------------------
...
...
@@ -57,7 +60,7 @@ function createWorker(): WorkerEntry {
const
workerPath
=
path
.
join
(
__dirname
,
'wasm-worker.js'
)
const
worker
=
new
Worker
(
workerPath
,
{
workerData
:
{
nativeBindingsPath
},
workerData
:
{
nativeBindingsPath
,
runtimeId
},
// Suppress the WASI warnings, this isn't a great solution
execArgv
:
[
'--no-warnings'
],
})
...
...
@@ -145,6 +148,14 @@ export const wasmManager = {
nativeBindingsPath
=
bindingsPath
},
/**
* Set the runtime_id returned by registerWasmPluginRuntime.
* Workers use this to look up the correct runtime state in NAPI calls.
*/
setRuntimeId
(
id
:
number
):
void
{
runtimeId
=
id
},
/**
* Compile a WASM module and cache it. Returns a module ID.
*/
...
...
packages/next/src/build/swc/wasm-worker.ts
View file @
fb4332ff
...
...
@@ -23,6 +23,7 @@ if (!parentPort) {
// Load native addon directly in the worker thread.
// This gives us direct NAPI access for host function callbacks.
const
bindings
=
require
(
workerData
.
nativeBindingsPath
)
const
runtimeId
:
number
=
workerData
.
runtimeId
// ---------------------------------------------------------------------------
// Instance storage — the ops object closes over the WASM instance/memory,
...
...
@@ -105,6 +106,7 @@ parentPort.on('message', (req: any) => {
throw
new
Error
(
`Instance
${
instanceId
}
not found for host fn`
)
}
return
bindings
.
wasmWorkerDispatchHostFn
(
runtimeId
,
instanceId
,
index
,
args
.
slice
(
0
,
paramCount
),
...
...
@@ -128,7 +130,7 @@ parentPort.on('message', (req: any) => {
// the instance handle and the ops interface for Rust.
const
ops
=
createInstanceOps
(
instance
,
memory
)
instances
.
set
(
instanceId
,
ops
)
bindings
.
wasmWorkerRegisterCallback
(
instanceId
,
ops
)
bindings
.
wasmWorkerRegisterCallback
(
runtimeId
,
instanceId
,
ops
)
response
=
{
result
:
instanceId
}
break
...
...
turbopack/crates/turbopack-ecmascript-plugins/src/transform/swc_ecma_transform_plugins.rs
View file @
fb4332ff
...
...
@@ -22,7 +22,7 @@ pub struct SwcPluginModule {
}
impl
SwcPluginModule
{
pub
fn
new
(
plugin_name
:
RcStr
,
plugin_bytes
:
Vec
<
u8
>
)
->
Self
{
pub
fn
new
(
plugin_name
:
RcStr
,
plugin_bytes
:
Vec
<
u8
>
,
wasm_plugin_runtime_id
:
u64
)
->
Self
{
#[cfg(feature
=
"swc_ecma_transform_plugin"
)]
{
use
swc_core
::
plugin_runner
::
plugin_module_bytes
::{
...
...
@@ -30,9 +30,12 @@ impl SwcPluginModule {
};
use
swc_plugin_backend_napi
::
NapiRuntime
;
let
runtime
=
NapiRuntime
::
from_runtime_id
(
wasm_plugin_runtime_id
)
.expect
(
"WASM plugin runtime not registered"
);
Self
{
plugin
:
CompiledPluginModuleBytes
::
from_raw_module
(
&
NapiR
untime
,
&
r
untime
,
RawPluginModuleBytes
::
new
(
plugin_name
.to_string
(),
plugin_bytes
),
),
name
:
plugin_name
,
...
...
@@ -41,7 +44,7 @@ impl SwcPluginModule {
#[cfg(not(feature
=
"swc_ecma_transform_plugin"
))]
{
let
_
=
plugin_bytes
;
let
_
=
(
plugin_bytes
,
wasm_plugin_runtime_id
)
;
Self
{
name
:
plugin_name
}
}
}
...
...
@@ -140,14 +143,20 @@ impl Issue for SwcEcmaTransformFailureIssue {
pub
struct
SwcEcmaTransformPluginsTransformer
{
#[cfg(feature
=
"swc_ecma_transform_plugin"
)]
plugins
:
Vec
<
(
turbo_tasks
::
ResolvedVc
<
SwcPluginModule
>
,
serde_json
::
Value
)
>
,
#[cfg(feature
=
"swc_ecma_transform_plugin"
)]
wasm_plugin_runtime_id
:
u64
,
}
impl
SwcEcmaTransformPluginsTransformer
{
#[cfg(feature
=
"swc_ecma_transform_plugin"
)]
pub
fn
new
(
plugins
:
Vec
<
(
turbo_tasks
::
ResolvedVc
<
SwcPluginModule
>
,
serde_json
::
Value
)
>
,
wasm_plugin_runtime_id
:
u64
,
)
->
Self
{
Self
{
plugins
}
Self
{
plugins
,
wasm_plugin_runtime_id
,
}
}
// [TODO] Due to WEB-1102 putting this module itself behind compile time feature
...
...
@@ -184,6 +193,9 @@ impl CustomTransformer for SwcEcmaTransformPluginsTransformer {
use
swc_plugin_backend_napi
::
NapiRuntime
;
use
turbo_tasks
::
TryJoinIterExt
;
let
runtime
=
NapiRuntime
::
from_runtime_id
(
self
.wasm_plugin_runtime_id
)
.expect
(
"WASM plugin runtime not registered"
);
let
plugins
=
self
.plugins
.iter
()
...
...
@@ -192,7 +204,7 @@ impl CustomTransformer for SwcEcmaTransformPluginsTransformer {
Ok
((
plugin_module
.name
.clone
(),
config
.clone
(),
Box
::
new
(
plugin_module
.plugin
.clone_module
(
&
NapiR
untime
)),
Box
::
new
(
plugin_module
.plugin
.clone_module
(
&
r
untime
)),
))
})
.try_join
()
...
...
@@ -232,8 +244,10 @@ impl CustomTransformer for SwcEcmaTransformPluginsTransformer {
ctx
:
&
TransformContext
<
'_
>
,
plugins
:
Vec
<
(
RcStr
,
serde_json
::
Value
,
Box
<
CompiledPluginModuleBytes
>
)
>
,
should_enable_comments_proxy
:
bool
,
runtime_id
:
u64
,
)
->
Result
<
Program
>
{
use
either
::
Either
;
use
swc_plugin_backend_napi
::
NapiRuntime
;
let
transform_metadata_context
=
Arc
::
new
(
TransformPluginMetadataContext
::
new
(
Some
(
ctx
.file_path_str
.to_string
()),
...
...
@@ -251,6 +265,8 @@ impl CustomTransformer for SwcEcmaTransformPluginsTransformer {
// still have to construct from raw bytes internally to perform actual
// transform.
for
(
plugin_name
,
plugin_config
,
plugin_module
)
in
plugins
{
let
runtime
=
NapiRuntime
::
from_runtime_id
(
runtime_id
)
.expect
(
"WASM plugin runtime not registered"
);
let
mut
transform_plugin_executor
=
swc_core
::
plugin_runner
::
create_plugin_transform_executor
(
ctx
.source_map
,
...
...
@@ -259,7 +275,7 @@ impl CustomTransformer for SwcEcmaTransformPluginsTransformer {
None
,
plugin_module
,
Some
(
plugin_config
),
Arc
::
new
(
NapiR
untime
),
Arc
::
new
(
r
untime
),
);
serialized_program
=
Either
::
Right
(
...
...
@@ -294,6 +310,7 @@ impl CustomTransformer for SwcEcmaTransformPluginsTransformer {
ctx
,
plugins
,
should_enable_comments_proxy
,
self
.wasm_plugin_runtime_id
,
)
{
Ok
(
program
)
=>
anyhow
::
Ok
(
program
),
Err
(
e
)
=>
{
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment