File size: 13,477 Bytes
1e92f2d |
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 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 |
use std::{
process::{Command, Stdio},
str::FromStr,
};
use anyhow::{Context, Result, anyhow, bail};
use browserslist::Distrib;
use swc_core::ecma::preset_env::{Version, Versions};
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TaskInput, Vc};
use turbo_tasks_env::ProcessEnv;
use crate::target::CompileTarget;
static DEFAULT_NODEJS_VERSION: &str = "18.0.0";
#[turbo_tasks::value]
#[derive(Clone, Copy, Default, Hash, TaskInput, Debug)]
pub enum Rendering {
#[default]
None,
Client,
Server,
}
impl Rendering {
pub fn is_none(&self) -> bool {
matches!(self, Rendering::None)
}
}
#[turbo_tasks::value]
pub enum ChunkLoading {
Edge,
/// CommonJS in Node.js
NodeJs,
/// <script> and <link> tags in the browser
Dom,
}
#[turbo_tasks::value]
pub struct Environment {
// members must be private to avoid leaking non-custom types
execution: ExecutionEnvironment,
}
#[turbo_tasks::value_impl]
impl Environment {
#[turbo_tasks::function]
pub fn new(execution: ExecutionEnvironment) -> Vc<Self> {
Self::cell(Environment { execution })
}
}
#[turbo_tasks::value]
#[derive(Debug, Hash, Clone, Copy, TaskInput)]
pub enum ExecutionEnvironment {
NodeJsBuildTime(ResolvedVc<NodeJsEnvironment>),
NodeJsLambda(ResolvedVc<NodeJsEnvironment>),
EdgeWorker(ResolvedVc<EdgeWorkerEnvironment>),
Browser(ResolvedVc<BrowserEnvironment>),
// TODO allow custom trait here
Custom(u8),
}
async fn resolve_browserslist(browser_env: ResolvedVc<BrowserEnvironment>) -> Result<Vec<Distrib>> {
Ok(browserslist::resolve(
browser_env.await?.browserslist_query.split(','),
&browserslist::Opts {
ignore_unknown_versions: true,
..Default::default()
},
)?)
}
#[turbo_tasks::value_impl]
impl Environment {
#[turbo_tasks::function]
pub async fn compile_target(&self) -> Result<Vc<CompileTarget>> {
Ok(match self.execution {
ExecutionEnvironment::NodeJsBuildTime(node_env, ..)
| ExecutionEnvironment::NodeJsLambda(node_env) => *node_env.await?.compile_target,
ExecutionEnvironment::Browser(_) => CompileTarget::unknown(),
ExecutionEnvironment::EdgeWorker(_) => CompileTarget::unknown(),
ExecutionEnvironment::Custom(_) => todo!(),
})
}
#[turbo_tasks::function]
pub async fn runtime_versions(&self) -> Result<Vc<RuntimeVersions>> {
Ok(match self.execution {
ExecutionEnvironment::NodeJsBuildTime(node_env, ..)
| ExecutionEnvironment::NodeJsLambda(node_env) => node_env.runtime_versions(),
ExecutionEnvironment::Browser(browser_env) => {
let distribs = resolve_browserslist(browser_env).await?;
Vc::cell(Versions::parse_versions(distribs)?)
}
ExecutionEnvironment::EdgeWorker(edge_env) => edge_env.runtime_versions(),
ExecutionEnvironment::Custom(_) => todo!(),
})
}
#[turbo_tasks::function]
pub async fn browserslist_query(&self) -> Result<Vc<RcStr>> {
Ok(match self.execution {
ExecutionEnvironment::NodeJsBuildTime(_)
| ExecutionEnvironment::NodeJsLambda(_)
| ExecutionEnvironment::EdgeWorker(_) =>
// TODO: This is a hack, browserslist_query is only used by CSS processing for
// LightningCSS However, there is an issue where the CSS is not transitioned
// to the client which we still have to solve. It does apply the
// browserslist correctly because CSS Modules in client components is double-processed,
// once for server once for browser.
{
Vc::cell("".into())
}
ExecutionEnvironment::Browser(browser_env) => {
Vc::cell(browser_env.await?.browserslist_query.clone())
}
ExecutionEnvironment::Custom(_) => todo!(),
})
}
#[turbo_tasks::function]
pub fn node_externals(&self) -> Vc<bool> {
match self.execution {
ExecutionEnvironment::NodeJsBuildTime(..) | ExecutionEnvironment::NodeJsLambda(_) => {
Vc::cell(true)
}
ExecutionEnvironment::Browser(_) => Vc::cell(false),
ExecutionEnvironment::EdgeWorker(_) => Vc::cell(false),
ExecutionEnvironment::Custom(_) => todo!(),
}
}
#[turbo_tasks::function]
pub fn supports_esm_externals(&self) -> Vc<bool> {
match self.execution {
ExecutionEnvironment::NodeJsBuildTime(..) | ExecutionEnvironment::NodeJsLambda(_) => {
Vc::cell(true)
}
ExecutionEnvironment::Browser(_) => Vc::cell(false),
ExecutionEnvironment::EdgeWorker(_) => Vc::cell(false),
ExecutionEnvironment::Custom(_) => todo!(),
}
}
#[turbo_tasks::function]
pub fn supports_commonjs_externals(&self) -> Vc<bool> {
match self.execution {
ExecutionEnvironment::NodeJsBuildTime(..) | ExecutionEnvironment::NodeJsLambda(_) => {
Vc::cell(true)
}
ExecutionEnvironment::Browser(_) => Vc::cell(false),
ExecutionEnvironment::EdgeWorker(_) => Vc::cell(true),
ExecutionEnvironment::Custom(_) => todo!(),
}
}
#[turbo_tasks::function]
pub fn supports_wasm(&self) -> Vc<bool> {
match self.execution {
ExecutionEnvironment::NodeJsBuildTime(..) | ExecutionEnvironment::NodeJsLambda(_) => {
Vc::cell(true)
}
ExecutionEnvironment::Browser(_) => Vc::cell(false),
ExecutionEnvironment::EdgeWorker(_) => Vc::cell(false),
ExecutionEnvironment::Custom(_) => todo!(),
}
}
#[turbo_tasks::function]
pub fn resolve_extensions(&self) -> Vc<Vec<RcStr>> {
let env = self;
match env.execution {
ExecutionEnvironment::NodeJsBuildTime(..) | ExecutionEnvironment::NodeJsLambda(_) => {
Vc::cell(vec![rcstr!(".js"), rcstr!(".node"), rcstr!(".json")])
}
ExecutionEnvironment::EdgeWorker(_) | ExecutionEnvironment::Browser(_) => {
Vc::<Vec<RcStr>>::default()
}
ExecutionEnvironment::Custom(_) => todo!(),
}
}
#[turbo_tasks::function]
pub fn resolve_node_modules(&self) -> Vc<bool> {
let env = self;
match env.execution {
ExecutionEnvironment::NodeJsBuildTime(..) | ExecutionEnvironment::NodeJsLambda(_) => {
Vc::cell(true)
}
ExecutionEnvironment::EdgeWorker(_) | ExecutionEnvironment::Browser(_) => {
Vc::cell(false)
}
ExecutionEnvironment::Custom(_) => todo!(),
}
}
#[turbo_tasks::function]
pub fn resolve_conditions(&self) -> Vc<Vec<RcStr>> {
let env = self;
match env.execution {
ExecutionEnvironment::NodeJsBuildTime(..) | ExecutionEnvironment::NodeJsLambda(_) => {
Vc::cell(vec![rcstr!("node")])
}
ExecutionEnvironment::Browser(_) => Vc::<Vec<RcStr>>::default(),
ExecutionEnvironment::EdgeWorker(_) => {
Vc::cell(vec![rcstr!("edge-light"), rcstr!("worker")])
}
ExecutionEnvironment::Custom(_) => todo!(),
}
}
#[turbo_tasks::function]
pub async fn cwd(&self) -> Result<Vc<Option<RcStr>>> {
let env = self;
Ok(match env.execution {
ExecutionEnvironment::NodeJsBuildTime(env)
| ExecutionEnvironment::NodeJsLambda(env) => *env.await?.cwd,
_ => Vc::cell(None),
})
}
#[turbo_tasks::function]
pub fn rendering(&self) -> Vc<Rendering> {
let env = self;
match env.execution {
ExecutionEnvironment::NodeJsBuildTime(_) | ExecutionEnvironment::NodeJsLambda(_) => {
Rendering::Server.cell()
}
ExecutionEnvironment::EdgeWorker(_) => Rendering::Server.cell(),
ExecutionEnvironment::Browser(_) => Rendering::Client.cell(),
_ => Rendering::None.cell(),
}
}
#[turbo_tasks::function]
pub fn chunk_loading(&self) -> Vc<ChunkLoading> {
let env = self;
match env.execution {
ExecutionEnvironment::NodeJsBuildTime(_) | ExecutionEnvironment::NodeJsLambda(_) => {
ChunkLoading::NodeJs.cell()
}
ExecutionEnvironment::EdgeWorker(_) => ChunkLoading::Edge.cell(),
ExecutionEnvironment::Browser(_) => ChunkLoading::Dom.cell(),
ExecutionEnvironment::Custom(_) => todo!(),
}
}
}
pub enum NodeEnvironmentType {
Server,
}
#[turbo_tasks::value(shared)]
pub struct NodeJsEnvironment {
pub compile_target: ResolvedVc<CompileTarget>,
pub node_version: ResolvedVc<NodeJsVersion>,
// user specified process.cwd
pub cwd: ResolvedVc<Option<RcStr>>,
}
impl Default for NodeJsEnvironment {
fn default() -> Self {
NodeJsEnvironment {
compile_target: CompileTarget::current_raw().resolved_cell(),
node_version: NodeJsVersion::default().resolved_cell(),
cwd: ResolvedVc::cell(None),
}
}
}
#[turbo_tasks::value_impl]
impl NodeJsEnvironment {
#[turbo_tasks::function]
pub async fn runtime_versions(&self) -> Result<Vc<RuntimeVersions>> {
let str = match *self.node_version.await? {
NodeJsVersion::Current(process_env) => get_current_nodejs_version(*process_env),
NodeJsVersion::Static(version) => *version,
}
.await?;
Ok(Vc::cell(Versions {
node: Some(
Version::from_str(&str)
.map_err(|_| anyhow!("Failed to parse Node.js version: '{}'", str))?,
),
..Default::default()
}))
}
#[turbo_tasks::function]
pub async fn current(process_env: ResolvedVc<Box<dyn ProcessEnv>>) -> Result<Vc<Self>> {
Ok(Self::cell(NodeJsEnvironment {
compile_target: CompileTarget::current().to_resolved().await?,
node_version: NodeJsVersion::cell(NodeJsVersion::Current(process_env))
.to_resolved()
.await?,
cwd: ResolvedVc::cell(None),
}))
}
}
#[turbo_tasks::value(shared)]
pub enum NodeJsVersion {
/// Use the version of Node.js that is available from the environment (via `node --version`)
Current(ResolvedVc<Box<dyn ProcessEnv>>),
/// Use the specified version of Node.js.
Static(ResolvedVc<RcStr>),
}
impl Default for NodeJsVersion {
fn default() -> Self {
NodeJsVersion::Static(ResolvedVc::cell(DEFAULT_NODEJS_VERSION.into()))
}
}
#[turbo_tasks::value(shared)]
pub struct BrowserEnvironment {
pub dom: bool,
pub web_worker: bool,
pub service_worker: bool,
pub browserslist_query: RcStr,
}
#[turbo_tasks::value(shared)]
pub struct EdgeWorkerEnvironment {
// This isn't actually the Edge's worker environment, but we have to use some kind of version
// for transpiling ECMAScript features. No tool supports Edge Workers as a separate
// environment.
pub node_version: ResolvedVc<NodeJsVersion>,
}
#[turbo_tasks::value_impl]
impl EdgeWorkerEnvironment {
#[turbo_tasks::function]
pub async fn runtime_versions(&self) -> Result<Vc<RuntimeVersions>> {
let str = match *self.node_version.await? {
NodeJsVersion::Current(process_env) => get_current_nodejs_version(*process_env),
NodeJsVersion::Static(version) => *version,
}
.await?;
Ok(Vc::cell(Versions {
node: Some(
Version::from_str(&str).map_err(|_| anyhow!("Node.js version parse error"))?,
),
..Default::default()
}))
}
}
// TODO preset_env_base::Version implements Serialize/Deserialize incorrectly
#[turbo_tasks::value(transparent, serialization = "none")]
pub struct RuntimeVersions(#[turbo_tasks(trace_ignore)] pub Versions);
#[turbo_tasks::function]
pub async fn get_current_nodejs_version(env: Vc<Box<dyn ProcessEnv>>) -> Result<Vc<RcStr>> {
let path_read = env.read(rcstr!("PATH")).await?;
let path = path_read.as_ref().context("env must have PATH")?;
let mut cmd = Command::new("node");
cmd.arg("--version");
cmd.env_clear();
cmd.env("PATH", path);
cmd.stdin(Stdio::piped());
cmd.stdout(Stdio::piped());
let output = cmd.output()?;
if !output.status.success() {
bail!(
"'node --version' command failed{}{}",
output
.status
.code()
.map(|c| format!(" with exit code {c}"))
.unwrap_or_default(),
String::from_utf8(output.stderr)
.map(|stderr| format!(": {stderr}"))
.unwrap_or_default()
);
}
let version = String::from_utf8(output.stdout)
.context("failed to parse 'node --version' output as utf8")?;
if let Some(version_number) = version.strip_prefix("v") {
Ok(Vc::cell(version_number.trim().into()))
} else {
bail!(
"Expected 'node --version' to return a version starting with 'v', but received: '{}'",
version
)
}
}
|