-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathtransformer.rs
More file actions
236 lines (221 loc) · 8.44 KB
/
Copy pathtransformer.rs
File metadata and controls
236 lines (221 loc) · 8.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
use napi::{Env, JsObject, JsUnknown};
use napi_derive::napi;
#[napi]
pub fn transform(opts: JsObject, env: Env) -> napi::Result<JsUnknown> {
let config: parcel_js_swc_core::Config = env.from_js_value(opts)?;
let result = parcel_js_swc_core::transform(config, None)?;
env.to_js_value(&result)
}
#[cfg(not(target_arch = "wasm32"))]
mod native_only {
use super::*;
use crossbeam_channel::{Receiver, Sender};
use indexmap::IndexMap;
use napi::{
threadsafe_function::{ThreadSafeCallContext, ThreadsafeFunctionCallMode},
JsBoolean, JsFunction, JsNumber, JsString, ValueType,
};
use parcel_js_swc_core::{JsValue, SourceLocation};
use std::sync::Arc;
// Allocate a single channel per thread to communicate with the JS thread.
thread_local! {
static CHANNEL: (Sender<Result<JsValue, String>>, Receiver<Result<JsValue, String>>) = crossbeam_channel::unbounded();
}
struct CallMacroMessage {
src: String,
export: String,
args: Vec<JsValue>,
loc: SourceLocation,
}
#[napi]
pub fn transform_async(opts: JsObject, env: Env) -> napi::Result<JsObject> {
let call_macro_tsfn = if opts.has_named_property("callMacro")? {
let func = opts.get_named_property::<JsUnknown>("callMacro")?;
if let Ok(func) = func.try_into() {
Some(env.create_threadsafe_function(
&func,
0,
|ctx: ThreadSafeCallContext<CallMacroMessage>| {
let src = ctx.env.create_string(&ctx.value.src)?.into_unknown();
let export = ctx.env.create_string(&ctx.value.export)?.into_unknown();
let args = js_value_to_napi(JsValue::Array(ctx.value.args), ctx.env)?;
let loc = ctx.env.to_js_value(&ctx.value.loc)?.into_unknown();
Ok(vec![src, export, args, loc])
},
)?)
} else {
None
}
} else {
None
};
let config: parcel_js_swc_core::Config = env.from_js_value(opts)?;
let (deferred, promise) = env.create_deferred()?;
// Get around Env not being Send. See safety note below.
let unsafe_env = env.raw() as usize;
rayon::spawn(move || {
let res = parcel_js_swc_core::transform(
config,
if let Some(tsfn) = call_macro_tsfn {
Some(Arc::new(move |src, export, args, loc| {
CHANNEL.with(|channel| {
// Call JS function to run the macro.
let tx = channel.0.clone();
tsfn.call_with_return_value(
Ok(CallMacroMessage {
src,
export,
args,
loc,
}),
ThreadsafeFunctionCallMode::Blocking,
move |v: JsUnknown| {
// When the JS function returns, await the promise, and send the result
// through the channel back to the native thread.
// SAFETY: this function is called from the JS thread.
await_promise(unsafe { Env::from_raw(unsafe_env as _) }, v, tx)?;
Ok(())
},
);
// Lock the transformer thread until the JS thread returns a result.
channel.1.recv().expect("receive failure")
})
}))
} else {
None
},
);
match res {
Ok(result) => deferred.resolve(move |env| env.to_js_value(&result)),
Err(err) => deferred.reject(err.into()),
}
});
Ok(promise)
}
/// Convert a JsValue macro argument from the transformer to a napi value.
fn js_value_to_napi(value: JsValue, env: Env) -> napi::Result<napi::JsUnknown> {
match value {
JsValue::Undefined => Ok(env.get_undefined()?.into_unknown()),
JsValue::Null => Ok(env.get_null()?.into_unknown()),
JsValue::Bool(b) => Ok(env.get_boolean(b)?.into_unknown()),
JsValue::Number(n) => Ok(env.create_double(n)?.into_unknown()),
JsValue::String(s) => Ok(env.create_string_from_std(s)?.into_unknown()),
JsValue::Regex { source, flags } => {
let regexp_class: JsFunction = env.get_global()?.get_named_property("RegExp")?;
let source = env.create_string_from_std(source)?;
let flags = env.create_string_from_std(flags)?;
let re = regexp_class.new_instance(&[source, flags])?;
Ok(re.into_unknown())
}
JsValue::Array(arr) => {
let mut res = env.create_array(arr.len() as u32)?;
for (i, val) in arr.into_iter().enumerate() {
res.set(i as u32, js_value_to_napi(val, env)?)?;
}
Ok(res.coerce_to_object()?.into_unknown())
}
JsValue::Object(obj) => {
let mut res = env.create_object()?;
for (k, v) in obj {
res.set_named_property(&k, js_value_to_napi(v, env)?)?;
}
Ok(res.into_unknown())
}
JsValue::Function(_) => {
// Functions can only be returned from macros, not passed in.
unreachable!()
}
}
}
/// Convert a napi value returned as a result of a macro to a JsValue for the transformer.
fn napi_to_js_value(value: napi::JsUnknown, env: Env) -> napi::Result<JsValue> {
match value.get_type()? {
ValueType::Undefined => Ok(JsValue::Undefined),
ValueType::Null => Ok(JsValue::Null),
ValueType::Number => Ok(JsValue::Number(
unsafe { value.cast::<JsNumber>() }.get_double()?,
)),
ValueType::Boolean => Ok(JsValue::Bool(
unsafe { value.cast::<JsBoolean>() }.get_value()?,
)),
ValueType::String => Ok(JsValue::String(
unsafe { value.cast::<JsString>() }
.into_utf8()?
.into_owned()?,
)),
ValueType::Object => {
let obj = unsafe { value.cast::<JsObject>() };
if obj.is_array()? {
let len = obj.get_array_length()?;
let mut arr = Vec::with_capacity(len as usize);
for i in 0..len {
let elem = napi_to_js_value(obj.get_element(i)?, env)?;
arr.push(elem);
}
Ok(JsValue::Array(arr))
} else {
let regexp_class: JsFunction = env.get_global()?.get_named_property("RegExp")?;
if obj.instanceof(regexp_class)? {
let source: JsString = obj.get_named_property("source")?;
let flags: JsString = obj.get_named_property("flags")?;
return Ok(JsValue::Regex {
source: source.into_utf8()?.into_owned()?,
flags: flags.into_utf8()?.into_owned()?,
});
}
let names = obj.get_property_names()?;
let len = names.get_array_length()?;
let mut props = IndexMap::with_capacity(len as usize);
for i in 0..len {
let prop = names.get_element::<JsString>(i)?;
let name = prop.into_utf8()?.into_owned()?;
let value = napi_to_js_value(obj.get_property(prop)?, env)?;
props.insert(name, value);
}
Ok(JsValue::Object(props))
}
}
ValueType::Function => {
let f = unsafe { value.cast::<JsFunction>() };
let source = f.coerce_to_string()?.into_utf8()?.into_owned()?;
Ok(JsValue::Function(source))
}
ValueType::Symbol | ValueType::External | ValueType::Unknown => Err(napi::Error::new(
napi::Status::GenericFailure,
"Could not convert value returned from macro to AST.",
)),
}
}
fn await_promise(
env: Env,
result: JsUnknown,
tx: Sender<Result<JsValue, String>>,
) -> napi::Result<()> {
// If the result is a promise, wait for it to resolve, and send the result to the channel.
// Otherwise, send the result immediately.
if result.is_promise()? {
let result: JsObject = result.try_into()?;
let then: JsFunction = result.get_named_property("then")?;
let tx2 = tx.clone();
let cb = env.create_function_from_closure("callback", move |ctx| {
let res = napi_to_js_value(ctx.get::<JsUnknown>(0)?, env)?;
tx.send(Ok(res)).expect("send failure");
ctx.env.get_undefined()
})?;
let eb = env.create_function_from_closure("error_callback", move |ctx| {
let res = ctx.get::<JsUnknown>(0)?;
let message = match napi_to_js_value(res, env)? {
JsValue::String(s) => s,
_ => "Unknown error".into(),
};
tx2.send(Err(message)).expect("send failure");
ctx.env.get_undefined()
})?;
then.call(Some(&result), &[cb, eb])?;
} else {
tx.send(Ok(napi_to_js_value(result, env)?))
.expect("send failure");
}
Ok(())
}
}