Unverified Commit 63560954 authored by Donny/강동윤's avatar Donny/강동윤 Committed by GitHub

chore: Update swc (#39965)

This PR updates SWC crates to https://github.com/swc-project/swc/commit/f2a0eef4f19332058f1263c29c222eae8fd25317

---


 - Closes #17056
Co-authored-by: 's avatarJiachi Liu <inbox@huozhi.im>
Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent 03eb4b1d
...@@ -9,7 +9,7 @@ name: Build, test, and deploy ...@@ -9,7 +9,7 @@ name: Build, test, and deploy
env: env:
NAPI_CLI_VERSION: 2.7.0 NAPI_CLI_VERSION: 2.7.0
TURBO_VERSION: 1.3.2-canary.1 TURBO_VERSION: 1.3.2-canary.1
RUST_TOOLCHAIN: nightly-2022-02-23 RUST_TOOLCHAIN: nightly-2022-06-12
PNPM_VERSION: 7.2.1 PNPM_VERSION: 7.2.1
jobs: jobs:
......
...@@ -70,7 +70,7 @@ ...@@ -70,7 +70,7 @@
"@svgr/webpack": "5.5.0", "@svgr/webpack": "5.5.0",
"@swc/cli": "0.1.55", "@swc/cli": "0.1.55",
"@swc/core": "1.2.203", "@swc/core": "1.2.203",
"@swc/helpers": "0.4.2", "@swc/helpers": "0.4.11",
"@testing-library/react": "13.0.0", "@testing-library/react": "13.0.0",
"@types/cheerio": "0.22.16", "@types/cheerio": "0.22.16",
"@types/fs-extra": "8.1.0", "@types/fs-extra": "8.1.0",
......
This diff is collapsed.
...@@ -9,7 +9,7 @@ crate-type = ["cdylib", "rlib"] ...@@ -9,7 +9,7 @@ crate-type = ["cdylib", "rlib"]
[features] [features]
plugin = [ plugin = [
"swc/plugin" "swc_core/plugin_transform_host_native"
] ]
[dependencies] [dependencies]
...@@ -26,18 +26,27 @@ swc_emotion = {path="../emotion"} ...@@ -26,18 +26,27 @@ swc_emotion = {path="../emotion"}
styled_components = {path="../styled_components"} styled_components = {path="../styled_components"}
styled_jsx = {path="../styled_jsx"} styled_jsx = {path="../styled_jsx"}
modularize_imports = {path="../modularize_imports"} modularize_imports = {path="../modularize_imports"}
swc = "0.214.9"
swc_atoms = "0.4.8"
swc_common = { version = "0.27.11", features = ["concurrent", "sourcemap", "plugin_transform_schema_v1"] }
swc_ecma_loader = { version = "0.39.4", features = ["node", "lru"] }
swc_ecmascript = { version = "0.189.4", features = ["codegen", "minifier", "optimization", "parser", "react", "transforms", "typescript", "utils", "visit"] }
swc_plugin_runner = { version = "0.71.15", optional = true, default-features = false, features = ["plugin_transform_schema_v1"] }
swc_cached = "0.3.5"
tracing = { version = "0.1.32", features = ["release_max_level_info"] } tracing = { version = "0.1.32", features = ["release_max_level_info"] }
wasmer = { version = "2.3.0", optional = true, default-features = false }
wasmer-wasi = { version = "2.3.0", optional = true, default-features = false } swc_core = { version = "0.20.4", features = [
"common_concurrent",
"ecma_ast",
"ecma_visit",
"ecma_loader_node",
"ecma_loader_lru",
"ecma_utils",
"ecma_minifier",
"ecma_transforms",
"__ecma_transforms",
"ecma_transforms_react",
"ecma_transforms_typescript",
"ecma_parser",
"ecma_parser_typescript",
"cached",
"base"
] }
[dev-dependencies] [dev-dependencies]
swc_ecma_transforms_testing = "0.105.5" swc_core = { version = "0.20.4", features = ["testing_transform"] }
testing = "0.29.4" testing = "0.29.4"
walkdir = "2.3.2" walkdir = "2.3.2"
use swc_atoms::JsWord; use swc_core::{
use swc_ecmascript::ast::{ ecma::ast::{Ident, JSXAttr, JSXAttrName, JSXAttrOrSpread, JSXElementName, JSXOpeningElement},
Ident, JSXAttr, JSXAttrName, JSXAttrOrSpread, JSXElementName, JSXOpeningElement, ecma::atoms::JsWord,
ecma::visit::Fold,
}; };
use swc_ecmascript::visit::Fold;
pub fn amp_attributes() -> impl Fold { pub fn amp_attributes() -> impl Fold {
AmpAttributePatcher::default() AmpAttributePatcher::default()
......
use swc_ecmascript::{ use swc_core::{
ast::*, ecma::ast::*,
visit::{Visit, VisitWith}, ecma::visit::{Visit, VisitWith},
}; };
pub(crate) fn contains_cjs(m: &Module) -> bool { pub(crate) fn contains_cjs(m: &Module) -> bool {
......
use swc_common::errors::HANDLER; use swc_core::{
use swc_common::pass::Optional; common::errors::HANDLER,
use swc_ecmascript::ast::ExportAll; ecma::ast::ExportAll,
use swc_ecmascript::visit::{noop_fold_type, Fold}; ecma::transforms::base::pass::Optional,
ecma::visit::{noop_fold_type, Fold},
};
pub fn disallow_re_export_all_in_page(is_page_file: bool) -> impl Fold { pub fn disallow_re_export_all_in_page(is_page_file: bool) -> impl Fold {
Optional::new(DisallowReExportAllInPage, is_page_file) Optional::new(DisallowReExportAllInPage, is_page_file)
......
use swc_atoms::JsWord; use swc_core::{
use swc_common::DUMMY_SP; common::DUMMY_SP,
use swc_ecmascript::ast::{ ecma::ast::{
ArrayPat, Callee, Decl, Expr, Ident, ImportDecl, ImportSpecifier, KeyValuePatProp, Number, ArrayPat, Callee, Decl, Expr, Ident, ImportDecl, ImportSpecifier, KeyValuePatProp, Number,
ObjectPat, ObjectPatProp, Pat, PropName, VarDecl, VarDeclarator, ObjectPat, ObjectPatProp, Pat, PropName, VarDecl, VarDeclarator,
},
ecma::atoms::JsWord,
ecma::visit::{Fold, FoldWith},
}; };
use swc_ecmascript::visit::{Fold, FoldWith};
pub fn hook_optimizer() -> impl Fold { pub fn hook_optimizer() -> impl Fold {
HookOptimizer::default() HookOptimizer::default()
...@@ -72,7 +74,7 @@ impl HookOptimizer { ...@@ -72,7 +74,7 @@ impl HookOptimizer {
} = &decl; } = &decl;
let init_clone = init.clone(); let init_clone = init.clone();
if let Pat::Array(a) = name { if let Pat::Array(a) = name {
if let Expr::Call(c) = &*init.as_deref().unwrap() { if let Expr::Call(c) = init.as_deref().unwrap() {
if let Callee::Expr(i) = &c.callee { if let Callee::Expr(i) = &c.callee {
if let Expr::Ident(Ident { sym, .. }) = &**i { if let Expr::Ident(Ident { sym, .. }) = &**i {
if self.hooks.contains(sym) { if self.hooks.contains(sym) {
......
...@@ -36,14 +36,15 @@ use serde::Deserialize; ...@@ -36,14 +36,15 @@ use serde::Deserialize;
use std::cell::RefCell; use std::cell::RefCell;
use std::rc::Rc; use std::rc::Rc;
use std::{path::PathBuf, sync::Arc}; use std::{path::PathBuf, sync::Arc};
use swc::config::ModuleConfig;
use swc_common::comments::Comments; use swc_core::{
use swc_common::{self, chain, pass::Optional}; base::config::ModuleConfig,
use swc_common::{FileName, SourceFile, SourceMap}; common::{chain, comments::Comments, pass::Optional, FileName, SourceFile, SourceMap},
use swc_ecmascript::ast::EsVersion; ecma::ast::EsVersion,
use swc_ecmascript::parser::parse_file_as_module; ecma::parser::parse_file_as_module,
use swc_ecmascript::transforms::pass::noop; ecma::transforms::base::pass::noop,
use swc_ecmascript::visit::Fold; ecma::visit::Fold,
};
pub mod amp_attributes; pub mod amp_attributes;
mod auto_cjs; mod auto_cjs;
...@@ -63,7 +64,7 @@ mod top_level_binding_collector; ...@@ -63,7 +64,7 @@ mod top_level_binding_collector;
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct TransformOptions { pub struct TransformOptions {
#[serde(flatten)] #[serde(flatten)]
pub swc: swc::config::Options, pub swc: swc_core::base::config::Options,
#[serde(default)] #[serde(default)]
pub disable_next_ssg: bool, pub disable_next_ssg: bool,
......
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use pathdiff::diff_paths; use pathdiff::diff_paths;
use swc_atoms::js_word;
use swc_common::errors::HANDLER; use swc_core::{
use swc_common::{FileName, DUMMY_SP}; common::{errors::HANDLER, FileName, DUMMY_SP},
use swc_ecmascript::ast::{ ecma::ast::{
ArrayLit, ArrowExpr, BinExpr, BinaryOp, BlockStmtOrExpr, Bool, CallExpr, Callee, Expr, ArrayLit, ArrowExpr, BinExpr, BinaryOp, BlockStmtOrExpr, Bool, CallExpr, Callee, Expr,
ExprOrSpread, Id, Ident, ImportDecl, ImportSpecifier, KeyValueProp, Lit, MemberExpr, ExprOrSpread, Id, Ident, ImportDecl, ImportSpecifier, KeyValueProp, Lit, MemberExpr,
MemberProp, Null, ObjectLit, Prop, PropName, PropOrSpread, Str, Tpl, MemberProp, Null, ObjectLit, Prop, PropName, PropOrSpread, Str, Tpl,
},
ecma::atoms::js_word,
ecma::utils::ExprFactory,
ecma::visit::{Fold, FoldWith},
}; };
use swc_ecmascript::utils::ExprFactory;
use swc_ecmascript::visit::{Fold, FoldWith};
pub fn next_dynamic( pub fn next_dynamic(
is_development: bool, is_development: bool,
......
...@@ -3,12 +3,16 @@ use fxhash::FxHashSet; ...@@ -3,12 +3,16 @@ use fxhash::FxHashSet;
use std::cell::RefCell; use std::cell::RefCell;
use std::mem::take; use std::mem::take;
use std::rc::Rc; use std::rc::Rc;
use swc_common::errors::HANDLER;
use swc_common::pass::{Repeat, Repeated}; use swc_core::{
use swc_common::DUMMY_SP; common::{
use swc_ecmascript::ast::*; errors::HANDLER,
use swc_ecmascript::visit::FoldWith; pass::{Repeat, Repeated},
use swc_ecmascript::visit::{noop_fold_type, Fold}; DUMMY_SP,
},
ecma::ast::*,
ecma::visit::{noop_fold_type, Fold, FoldWith},
};
static SSG_EXPORTS: &[&str; 3] = &["getStaticProps", "getStaticPaths", "getServerSideProps"]; static SSG_EXPORTS: &[&str; 3] = &["getStaticProps", "getStaticPaths", "getServerSideProps"];
......
use chrono::Utc; use chrono::Utc;
use swc_common::errors::HANDLER;
use swc_common::{Span, DUMMY_SP}; use swc_core::{
use swc_ecmascript::ast::*; common::{errors::HANDLER, Span, DUMMY_SP},
use swc_ecmascript::visit::{Fold, FoldWith}; ecma::ast::*,
ecma::visit::{Fold, FoldWith},
};
pub fn page_config(is_development: bool, is_page_file: bool) -> impl Fold { pub fn page_config(is_development: bool, is_page_file: bool) -> impl Fold {
PageConfig { PageConfig {
......
use regex::Regex; use regex::Regex;
use serde::Deserialize; use serde::Deserialize;
use swc_ecmascript::ast::*;
use swc_ecmascript::visit::{noop_fold_type, Fold, FoldWith}; use swc_core::{
ecma::ast::*,
ecma::visit::{noop_fold_type, Fold, FoldWith},
};
#[derive(Clone, Debug, Deserialize)] #[derive(Clone, Debug, Deserialize)]
#[serde(untagged)] #[serde(untagged)]
......
...@@ -2,12 +2,14 @@ use once_cell::sync::Lazy; ...@@ -2,12 +2,14 @@ use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use serde::Deserialize; use serde::Deserialize;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use swc_atoms::JsWord;
use swc_common::errors::HANDLER; use swc_core::{
use swc_common::FileName; common::{errors::HANDLER, FileName},
use swc_ecmascript::ast::*; ecma::ast::*,
use swc_ecmascript::utils::{quote_ident, ExprFactory}; ecma::atoms::JsWord,
use swc_ecmascript::visit::{Fold, FoldWith}; ecma::utils::{quote_ident, ExprFactory},
ecma::visit::{Fold, FoldWith},
};
#[derive(Copy, Clone, Debug, Deserialize)] #[derive(Copy, Clone, Debug, Deserialize)]
#[serde(rename_all = "lowercase")] #[serde(rename_all = "lowercase")]
......
use serde::Deserialize; use serde::Deserialize;
use swc_atoms::JsWord;
use swc_common::collections::AHashSet; use swc_core::{
use swc_common::DUMMY_SP; common::{collections::AHashSet, DUMMY_SP},
use swc_ecmascript::ast::*; ecma::ast::*,
use swc_ecmascript::visit::{noop_fold_type, Fold, FoldWith}; ecma::atoms::JsWord,
ecma::visit::{noop_fold_type, Fold, FoldWith},
};
use crate::top_level_binding_collector::collect_top_level_decls; use crate::top_level_binding_collector::collect_top_level_decls;
......
use serde::Deserialize; use serde::Deserialize;
use swc_atoms::js_word;
use swc_atoms::JsWord; use swc_core::{
use swc_common::Mark; common::Mark,
use swc_ecmascript::ast::*; ecma::ast::*,
use swc_ecmascript::transforms::optimization::simplify::dce::{dce, Config as DCEConfig}; ecma::atoms::{js_word, JsWord},
use swc_ecmascript::visit::{Fold, FoldWith}; ecma::transforms::optimization::simplify::dce::{dce, Config as DCEConfig},
ecma::visit::{Fold, FoldWith},
};
#[derive(Clone, Debug, Deserialize)] #[derive(Clone, Debug, Deserialize)]
pub struct Config { pub struct Config {
......
use std::hash::Hash; use std::hash::Hash;
use swc_common::{collections::AHashSet, SyntaxContext};
use swc_ecmascript::{ use swc_core::{
ast::{ common::{collections::AHashSet, SyntaxContext},
ecma::ast::{
ClassDecl, FnDecl, Ident, ImportDefaultSpecifier, ImportNamedSpecifier, ClassDecl, FnDecl, Ident, ImportDefaultSpecifier, ImportNamedSpecifier,
ImportStarAsSpecifier, ModuleItem, ObjectPatProp, Param, Pat, Stmt, VarDeclarator, ImportStarAsSpecifier, ModuleItem, ObjectPatProp, Param, Pat, Stmt, VarDeclarator,
}, },
utils::ident::IdentLike, ecma::utils::ident::IdentLike,
visit::{noop_visit_type, Visit, VisitWith}, ecma::visit::{noop_visit_type, Visit, VisitWith},
}; };
// Modified from swc_ecma_utils/src/lib.rs:BindingCollector. // Modified from swc_ecma_utils/src/lib.rs:BindingCollector.
......
...@@ -3,9 +3,11 @@ use next_swc::{ ...@@ -3,9 +3,11 @@ use next_swc::{
next_ssg::next_ssg, next_ssg::next_ssg,
}; };
use std::path::PathBuf; use std::path::PathBuf;
use swc_common::FileName; use swc_core::{
use swc_ecma_transforms_testing::test_fixture_allowing_error; common::FileName,
use swc_ecmascript::parser::{EsConfig, Syntax}; ecma::parser::{EsConfig, Syntax},
ecma::transforms::testing::test_fixture_allowing_error,
};
use testing::fixture; use testing::fixture;
fn syntax() -> Syntax { fn syntax() -> Syntax {
......
...@@ -9,11 +9,11 @@ use next_swc::{ ...@@ -9,11 +9,11 @@ use next_swc::{
shake_exports::{shake_exports, Config as ShakeExportsConfig}, shake_exports::{shake_exports, Config as ShakeExportsConfig},
}; };
use std::path::PathBuf; use std::path::PathBuf;
use swc_common::{chain, comments::SingleThreadedComments, FileName, Mark}; use swc_core::{
use swc_ecma_transforms_testing::{test, test_fixture}; common::{chain, comments::SingleThreadedComments, FileName, Mark},
use swc_ecmascript::{ ecma::parser::{EsConfig, Syntax},
parser::{EsConfig, Syntax}, ecma::transforms::react::jsx,
transforms::react::jsx, ecma::transforms::testing::{test, test_fixture},
}; };
use testing::fixture; use testing::fixture;
...@@ -86,7 +86,7 @@ fn next_ssg_fixture(input: PathBuf) { ...@@ -86,7 +86,7 @@ fn next_ssg_fixture(input: PathBuf) {
let jsx = jsx::<SingleThreadedComments>( let jsx = jsx::<SingleThreadedComments>(
tr.cm.clone(), tr.cm.clone(),
None, None,
swc_ecmascript::transforms::react::Options { swc_core::ecma::transforms::react::Options {
next: false.into(), next: false.into(),
runtime: None, runtime: None,
import_source: Some("".into()), import_source: Some("".into()),
......
use next_swc::{custom_before_pass, TransformOptions}; use next_swc::{custom_before_pass, TransformOptions};
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use swc::Compiler; use swc_core::{
use swc_ecmascript::{ base::Compiler,
parser::{Syntax, TsConfig}, ecma::parser::{Syntax, TsConfig},
transforms::pass::noop, ecma::transforms::base::pass::noop,
}; };
use testing::{NormalizedOutput, Tester}; use testing::{NormalizedOutput, Tester};
...@@ -28,14 +28,14 @@ fn test(input: &Path, minify: bool) { ...@@ -28,14 +28,14 @@ fn test(input: &Path, minify: bool) {
let fm = cm.load_file(input).expect("failed to load file"); let fm = cm.load_file(input).expect("failed to load file");
let options = TransformOptions { let options = TransformOptions {
swc: swc::config::Options { swc: swc_core::base::config::Options {
swcrc: true, swcrc: true,
output_path: Some(output.clone()), output_path: Some(output.clone()),
config: swc::config::Config { config: swc_core::base::config::Config {
is_module: swc::config::IsModule::Bool(true), is_module: swc_core::base::config::IsModule::Bool(true),
jsc: swc::config::JscConfig { jsc: swc_core::base::config::JscConfig {
minify: if minify { minify: if minify {
Some(assert_json("{ \"compress\": true, \"mangle\": true }")) Some(assert_json("{ \"compress\": true, \"mangle\": true }"))
} else { } else {
......
function n(n, t) { function t(t, r) {
(null == t || t > n.length) && (t = n.length); (null == r || r > t.length) && (r = t.length);
for(var r = 0, e = new Array(t); r < t; r++)e[r] = n[r]; for(var n = 0, e = new Array(r); n < r; n++)e[n] = t[n];
return e; return e;
} }
import t from "other"; import r from "other";
(function(t, r) { (function(r, n) {
return function(n) { return function(t) {
if (Array.isArray(n)) return n; if (Array.isArray(t)) return t;
}(t) || function(n, t) { }(r) || function(t, r) {
var r, e, o = null == n ? null : "undefined" != typeof Symbol && n[Symbol.iterator] || n["@@iterator"]; var n, e, o = null == t ? null : "undefined" != typeof Symbol && t[Symbol.iterator] || t["@@iterator"];
if (null != o) { if (null != o) {
var u = [], l = !0, f = !1; var u = [], l = !0, i = !1;
try { try {
for(o = o.call(n); !(l = (r = o.next()).done) && (u.push(r.value), !t || u.length !== t); l = !0); for(o = o.call(t); !(l = (n = o.next()).done) && (u.push(n.value), !r || u.length !== r); l = !0);
} catch (i) { } catch (a) {
f = !0, e = i; i = !0, e = a;
} finally{ } finally{
try { try {
l || null == o.return || o.return(); l || null == o.return || o.return();
} finally{ } finally{
if (f) throw e; if (i) throw e;
} }
} }
return u; return u;
} }
}(t, r) || function t(r, e) { }(r, n) || function(r, n) {
if (r) { if (r) {
if ("string" == typeof r) return n(r, e); if ("string" == typeof r) return t(r, n);
var o = Object.prototype.toString.call(r).slice(8, -1); var e = Object.prototype.toString.call(r).slice(8, -1);
if ("Object" === o && r.constructor && (o = r.constructor.name), "Map" === o || "Set" === o) return Array.from(o); if ("Object" === e && r.constructor && (e = r.constructor.name), "Map" === e || "Set" === e) return Array.from(e);
if ("Arguments" === o || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o)) return n(r, e); if ("Arguments" === e || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(e)) return t(r, n);
} }
}(t, r) || function() { }(r, n) || function() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}(); }();
})(t, 1)[0]; })(r, 1)[0];
var r = function() {
"use strict";
!function(n, t) {
if (!(n instanceof t)) throw new TypeError("Cannot call a class as a function");
}(this, r);
};
export var __N_SSG = !0; export var __N_SSG = !0;
export default function e() { export default function n() {
return React.createElement("div", null); return React.createElement("div", null);
}; };
...@@ -5,9 +5,12 @@ use std::sync::Arc; ...@@ -5,9 +5,12 @@ use std::sync::Arc;
use fxhash::FxHashSet; use fxhash::FxHashSet;
use next_swc::next_ssg::next_ssg; use next_swc::next_ssg::next_ssg;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use swc::{try_with_handler, Compiler};
use swc_common::{FileName, FilePathMapping, SourceMap}; use swc_core::{
use swc_ecmascript::transforms::pass::noop; base::{try_with_handler, Compiler},
common::{FileName, FilePathMapping, SourceMap},
ecma::transforms::base::pass::noop,
};
static COMPILER: Lazy<Arc<Compiler>> = Lazy::new(|| { static COMPILER: Lazy<Arc<Compiler>> = Lazy::new(|| {
let cm = Arc::new(SourceMap::new(FilePathMapping::empty())); let cm = Arc::new(SourceMap::new(FilePathMapping::empty()));
......
...@@ -18,14 +18,10 @@ radix_fmt = "1" ...@@ -18,14 +18,10 @@ radix_fmt = "1"
regex = "1.5" regex = "1.5"
serde = "1" serde = "1"
sourcemap = "6.0.1" sourcemap = "6.0.1"
swc_atoms = "0.4.8"
swc_common = { version = "0.27.11", features = ["concurrent", "sourcemap"] }
swc_ecmascript = { version = "0.189.4", features = ["codegen", "utils", "visit"] }
swc_trace_macro = "0.1.2"
tracing = { version = "0.1.32", features = ["release_max_level_info"] } tracing = { version = "0.1.32", features = ["release_max_level_info"] }
swc_core = { version = "0.20.4", features = ["common_concurrent", "ecma_ast","ecma_codegen", "ecma_utils", "ecma_visit", "trace_macro"] }
[dev-dependencies] [dev-dependencies]
swc_ecma_transforms_testing = "0.105.5" swc_core = { version = "0.20.4", features = ["testing_transform", "ecma_transforms_react"] }
testing = "0.29.4" testing = "0.29.4"
serde_json = "1" serde_json = "1"
swc_ecma_transforms_react = "0.141.4"
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use swc_atoms::JsWord;
use swc_common::collections::AHashMap; use swc_core::{common::collections::AHashMap, ecma::atoms::JsWord};
use crate::{EmotionModuleConfig, ExportItem}; use crate::{EmotionModuleConfig, ExportItem};
...@@ -31,7 +31,7 @@ pub(crate) fn expand_import_map( ...@@ -31,7 +31,7 @@ pub(crate) fn expand_import_map(
.for_each(|(local_export_name, Config { canonical_import })| { .for_each(|(local_export_name, Config { canonical_import })| {
let ImportItem(package_name, export_name) = canonical_import; let ImportItem(package_name, export_name) = canonical_import;
if &*package_name == "@emotion/react" && &*export_name == "jsx" { if &**package_name == "@emotion/react" && &**export_name == "jsx" {
return; return;
} }
......
...@@ -8,23 +8,21 @@ use once_cell::sync::Lazy; ...@@ -8,23 +8,21 @@ use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sourcemap::{RawToken, SourceMap as RawSourcemap}; use sourcemap::{RawToken, SourceMap as RawSourcemap};
use swc_atoms::JsWord; use swc_core::{
use swc_common::comments::Comments; common::{comments::Comments, util::take::Take, BytePos, SourceMapperDyn, DUMMY_SP},
use swc_common::util::take::Take; ecma::utils::ExprFactory,
use swc_common::{BytePos, SourceMapperDyn, DUMMY_SP}; ecma::visit::{Fold, FoldWith},
use swc_ecmascript::ast::{ ecma::{
ArrayLit, CallExpr, JSXAttr, JSXAttrName, JSXAttrOrSpread, JSXAttrValue, JSXElementName, ast::{
JSXExpr, JSXExprContainer, JSXObject, ModuleExportName, SourceMapperExt, ArrayLit, CallExpr, Callee, Expr, ExprOrSpread, Id, Ident, ImportDecl, ImportSpecifier,
}; JSXAttr, JSXAttrName, JSXAttrOrSpread, JSXAttrValue, JSXElement, JSXElementName,
use swc_ecmascript::utils::ExprFactory; JSXExpr, JSXExprContainer, JSXObject, KeyValueProp, MemberProp, ModuleExportName,
use swc_ecmascript::{ ObjectLit, Pat, Prop, PropName, PropOrSpread, SourceMapperExt, Tpl, VarDeclarator,
ast::{ },
Callee, Expr, ExprOrSpread, Id, Ident, ImportDecl, ImportSpecifier, JSXElement, atoms::JsWord,
KeyValueProp, MemberProp, ObjectLit, Pat, Prop, PropName, PropOrSpread, Tpl, VarDeclarator,
}, },
visit::{Fold, FoldWith}, trace_macro::swc_trace,
}; };
use swc_trace_macro::swc_trace;
mod hash; mod hash;
mod import_map; mod import_map;
......
use std::path::PathBuf; use std::path::PathBuf;
use swc_common::{chain, comments::SingleThreadedComments, Mark}; use swc_core::{
use swc_ecma_transforms_testing::test_fixture; common::{chain, comments::SingleThreadedComments, Mark},
use swc_ecmascript::parser::{Syntax, TsConfig}; ecma::parser::{Syntax, TsConfig},
ecma::transforms::react::{jsx, Runtime},
ecma::transforms::testing::test_fixture,
};
use swc_emotion::EmotionOptions; use swc_emotion::EmotionOptions;
use testing::fixture; use testing::fixture;
...@@ -12,7 +15,6 @@ fn ts_syntax() -> Syntax { ...@@ -12,7 +15,6 @@ fn ts_syntax() -> Syntax {
..Default::default() ..Default::default()
}) })
} }
use swc_ecma_transforms_react::{jsx, Runtime};
#[fixture("tests/fixture/**/input.tsx")] #[fixture("tests/fixture/**/input.tsx")]
fn next_emotion_fixture(input: PathBuf) { fn next_emotion_fixture(input: PathBuf) {
...@@ -24,7 +26,7 @@ fn next_emotion_fixture(input: PathBuf) { ...@@ -24,7 +26,7 @@ fn next_emotion_fixture(input: PathBuf) {
let jsx = jsx::<SingleThreadedComments>( let jsx = jsx::<SingleThreadedComments>(
tr.cm.clone(), tr.cm.clone(),
Some(tr.comments.as_ref().clone()), Some(tr.comments.as_ref().clone()),
swc_ecmascript::transforms::react::Options { swc_core::ecma::transforms::react::Options {
next: false.into(), next: false.into(),
runtime: Some(Runtime::Automatic), runtime: Some(Runtime::Automatic),
throw_if_namespace: false.into(), throw_if_namespace: false.into(),
......
...@@ -15,9 +15,8 @@ handlebars = "4.2.1" ...@@ -15,9 +15,8 @@ handlebars = "4.2.1"
once_cell = "1.13.0" once_cell = "1.13.0"
regex = "1.5" regex = "1.5"
serde = "1" serde = "1"
swc_cached = "0.3.5" swc_core = { version = "0.20.4", features = ["cached", "ecma_ast", "ecma_visit"] }
swc_ecmascript = { version = "0.189.4", features = ["visit"] }
[dev-dependencies] [dev-dependencies]
swc_ecma_transforms_testing = "0.105.5" swc_core = { version = "0.20.4", features = ["testing_transform"] }
testing = "0.29.4" testing = "0.29.4"
...@@ -5,9 +5,12 @@ use handlebars::{Context, Handlebars, Helper, HelperResult, Output, RenderContex ...@@ -5,9 +5,12 @@ use handlebars::{Context, Handlebars, Helper, HelperResult, Output, RenderContex
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use regex::{Captures, Regex}; use regex::{Captures, Regex};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use swc_cached::regex::CachedRegex;
use swc_ecmascript::ast::*; use swc_core::{
use swc_ecmascript::visit::{noop_fold_type, Fold}; cached::regex::CachedRegex,
ecma::ast::*,
ecma::visit::{noop_fold_type, Fold},
};
static DUP_SLASH_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"//").unwrap()); static DUP_SLASH_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"//").unwrap());
......
use std::path::PathBuf; use std::path::PathBuf;
use modularize_imports::{modularize_imports, PackageConfig}; use modularize_imports::{modularize_imports, PackageConfig};
use swc_ecma_transforms_testing::test_fixture; use swc_core::{
use swc_ecmascript::parser::{EsConfig, Syntax}; ecma::parser::{EsConfig, Syntax},
ecma::transforms::testing::test_fixture,
};
use testing::fixture; use testing::fixture;
fn syntax() -> Syntax { fn syntax() -> Syntax {
......
...@@ -14,10 +14,7 @@ default = [] ...@@ -14,10 +14,7 @@ default = []
# this is due to some of transitive dependencies have features cannot be enabled at the same time # this is due to some of transitive dependencies have features cannot be enabled at the same time
# (i.e wasmer/default vs wasmer/js-default) while cargo merges all the features at once. # (i.e wasmer/default vs wasmer/js-default) while cargo merges all the features at once.
plugin = [ plugin = [
"swc/plugin", "swc_core/plugin_transform_host_native",
"swc_plugin_runner/default",
"wasmer/default",
"wasmer-wasi/default",
"next-swc/plugin" "next-swc/plugin"
] ]
sentry_native_tls = ["_sentry_native_tls"] sentry_native_tls = ["_sentry_native_tls"]
...@@ -33,20 +30,30 @@ next-swc = {version = "0.0.0", path = "../core"} ...@@ -33,20 +30,30 @@ next-swc = {version = "0.0.0", path = "../core"}
once_cell = "1.13.0" once_cell = "1.13.0"
serde = "1" serde = "1"
serde_json = "1" serde_json = "1"
swc = "0.214.9" swc_core = { version = "0.20.4", features = [
swc_atoms = "0.4.8" "allocator_node",
swc_bundler = { version = "0.177.4", features = ["concurrent"] } "base_concurrent", # concurrent?
swc_common = { version = "0.27.11", features = ["concurrent", "sourcemap"] } "common_concurrent",
swc_ecma_loader = { version = "0.39.4", features = ["node", "lru"] } "ecma_ast",
swc_ecmascript = { version = "0.189.4", features = ["codegen", "minifier", "optimization", "parser", "react", "transforms", "typescript", "utils", "visit"] } "ecma_loader_node",
swc_plugin_runner = { version = "0.71.15", optional = true } "ecma_loader_lru",
swc_node_base = "0.5.5" "bundler",
"bundler_concurrent",
"ecma_codegen",
"ecma_minifier",
"ecma_parser",
"ecma_parser_typescript",
"ecma_transforms",
"ecma_transforms_optimization",
"ecma_transforms_react",
"ecma_transforms_typescript",
"ecma_utils",
"ecma_visit"
] }
tracing = { version = "0.1.32", features = ["release_max_level_info"] } tracing = { version = "0.1.32", features = ["release_max_level_info"] }
tracing-futures = "0.2.5" tracing-futures = "0.2.5"
tracing-subscriber = "0.3.9" tracing-subscriber = "0.3.9"
tracing-chrome = "0.5.0" tracing-chrome = "0.5.0"
wasmer = { version = "2.3.0", optional = true, default-features = false }
wasmer-wasi = { version = "2.3.0", optional = true, default-features = false }
# There are few build targets we can't use native-tls which default features rely on, # There are few build targets we can't use native-tls which default features rely on,
# allow to specify alternative (rustls) instead via features. # allow to specify alternative (rustls) instead via features.
# Note to opt in rustls default-features should be disabled # Note to opt in rustls default-features should be disabled
......
...@@ -7,22 +7,22 @@ use napi::{CallContext, JsObject, Task}; ...@@ -7,22 +7,22 @@ use napi::{CallContext, JsObject, Task};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use serde::Deserialize; use serde::Deserialize;
use std::{collections::HashMap, path::PathBuf, sync::Arc}; use std::{collections::HashMap, path::PathBuf, sync::Arc};
use swc::{config::SourceMapsConfig, try_with_handler, TransformOutput}; use swc_core::{
use swc_atoms::JsWord; base::{config::SourceMapsConfig, try_with_handler, TransformOutput},
use swc_bundler::{Bundler, ModuleData, ModuleRecord}; bundler::{Bundler, ModuleData, ModuleRecord},
use swc_common::{ common::{
collections::AHashMap, collections::AHashMap,
errors::{ColorConfig, Handler}, errors::{ColorConfig, Handler},
BytePos, FileName, SourceMap, Span, BytePos, FileName, SourceMap, Span,
}; },
use swc_ecma_loader::{ ecma::ast::*,
resolvers::{lru::CachingResolver, node::NodeModulesResolver}, ecma::atoms::JsWord,
TargetEnv, NODE_BUILTINS, ecma::loader::{
}; resolvers::{lru::CachingResolver, node::NodeModulesResolver},
use swc_ecmascript::{ TargetEnv, NODE_BUILTINS,
ast::*, },
parser::{lexer::Lexer, EsConfig, Parser, StringInput, Syntax}, ecma::parser::{lexer::Lexer, EsConfig, Parser, StringInput, Syntax},
visit::{noop_visit_type, Visit, VisitWith}, ecma::visit::{noop_visit_type, Visit, VisitWith},
}; };
#[js_function(1)] #[js_function(1)]
...@@ -44,7 +44,7 @@ struct BundleOption { ...@@ -44,7 +44,7 @@ struct BundleOption {
} }
struct BundleTask { struct BundleTask {
c: Arc<swc::Compiler>, c: Arc<swc_core::base::Compiler>,
config: String, config: String,
} }
...@@ -58,7 +58,7 @@ impl Task for BundleTask { ...@@ -58,7 +58,7 @@ impl Task for BundleTask {
try_with_handler( try_with_handler(
self.c.cm.clone(), self.c.cm.clone(),
swc::HandlerOpts { swc_core::base::HandlerOpts {
color: ColorConfig::Never, color: ColorConfig::Never,
skip_filename: true, skip_filename: true,
}, },
...@@ -79,11 +79,11 @@ impl Task for BundleTask { ...@@ -79,11 +79,11 @@ impl Task for BundleTask {
handler, handler,
}, },
make_resolver(), make_resolver(),
swc_bundler::Config { swc_core::bundler::Config {
require: true, require: true,
disable_inliner: false, disable_inliner: false,
external_modules: builtins, external_modules: builtins,
module: swc_bundler::ModuleType::Es, module: swc_core::bundler::ModuleType::Es,
..Default::default() ..Default::default()
}, },
Box::new(CustomHook), Box::new(CustomHook),
...@@ -156,7 +156,7 @@ struct CustomLoader<'a> { ...@@ -156,7 +156,7 @@ struct CustomLoader<'a> {
cm: Arc<SourceMap>, cm: Arc<SourceMap>,
} }
impl swc_bundler::Load for CustomLoader<'_> { impl swc_core::bundler::Load for CustomLoader<'_> {
fn load(&self, f: &FileName) -> Result<ModuleData, Error> { fn load(&self, f: &FileName) -> Result<ModuleData, Error> {
let fm = match f { let fm = match f {
FileName::Real(path) => self.cm.load_file(path)?, FileName::Real(path) => self.cm.load_file(path)?,
...@@ -188,7 +188,7 @@ impl swc_bundler::Load for CustomLoader<'_> { ...@@ -188,7 +188,7 @@ impl swc_bundler::Load for CustomLoader<'_> {
struct CustomHook; struct CustomHook;
impl swc_bundler::Hook for CustomHook { impl swc_core::bundler::Hook for CustomHook {
fn get_import_meta_props( fn get_import_meta_props(
&self, &self,
_span: Span, _span: Span,
......
...@@ -32,14 +32,16 @@ DEALINGS IN THE SOFTWARE. ...@@ -32,14 +32,16 @@ DEALINGS IN THE SOFTWARE.
#[macro_use] #[macro_use]
extern crate napi_derive; extern crate napi_derive;
/// Explicit extern crate to use allocator. /// Explicit extern crate to use allocator.
extern crate swc_node_base; extern crate swc_core;
use backtrace::Backtrace; use backtrace::Backtrace;
use fxhash::FxHashSet; use fxhash::FxHashSet;
use napi::{CallContext, Env, JsObject, JsUndefined}; use napi::{CallContext, Env, JsObject, JsUndefined};
use std::{env, panic::set_hook, sync::Arc}; use std::{env, panic::set_hook, sync::Arc};
use swc::{Compiler, TransformOutput}; use swc_core::{
use swc_common::{self, sync::Lazy, FilePathMapping, SourceMap}; base::{Compiler, TransformOutput},
common::{sync::Lazy, FilePathMapping, SourceMap},
};
mod bundle; mod bundle;
mod minify; mod minify;
......
...@@ -33,13 +33,15 @@ use fxhash::FxHashMap; ...@@ -33,13 +33,15 @@ use fxhash::FxHashMap;
use napi::{CallContext, JsObject, Task}; use napi::{CallContext, JsObject, Task};
use serde::Deserialize; use serde::Deserialize;
use std::sync::Arc; use std::sync::Arc;
use swc::{config::JsMinifyOptions, try_with_handler, TransformOutput}; use swc_core::{
use swc_common::{errors::ColorConfig, sync::Lrc, FileName, SourceFile, SourceMap}; base::{config::JsMinifyOptions, try_with_handler, TransformOutput},
common::{errors::ColorConfig, sync::Lrc, FileName, SourceFile, SourceMap},
};
struct MinifyTask { struct MinifyTask {
c: Arc<swc::Compiler>, c: Arc<swc_core::base::Compiler>,
code: MinifyTarget, code: MinifyTarget,
opts: swc::config::JsMinifyOptions, opts: swc_core::base::config::JsMinifyOptions,
} }
#[derive(Deserialize)] #[derive(Deserialize)]
...@@ -78,7 +80,7 @@ impl Task for MinifyTask { ...@@ -78,7 +80,7 @@ impl Task for MinifyTask {
fn compute(&mut self) -> napi::Result<Self::Output> { fn compute(&mut self) -> napi::Result<Self::Output> {
try_with_handler( try_with_handler(
self.c.cm.clone(), self.c.cm.clone(),
swc::HandlerOpts { swc_core::base::HandlerOpts {
color: ColorConfig::Never, color: ColorConfig::Never,
skip_filename: true, skip_filename: true,
}, },
...@@ -125,7 +127,7 @@ pub fn minify_sync(cx: CallContext) -> napi::Result<JsObject> { ...@@ -125,7 +127,7 @@ pub fn minify_sync(cx: CallContext) -> napi::Result<JsObject> {
let output = try_with_handler( let output = try_with_handler(
c.cm.clone(), c.cm.clone(),
swc::HandlerOpts { swc_core::base::HandlerOpts {
color: ColorConfig::Never, color: ColorConfig::Never,
skip_filename: true, skip_filename: true,
}, },
......
...@@ -2,8 +2,10 @@ use crate::util::{deserialize_json, CtxtExt, MapErr}; ...@@ -2,8 +2,10 @@ use crate::util::{deserialize_json, CtxtExt, MapErr};
use anyhow::Context as _; use anyhow::Context as _;
use napi::{CallContext, Either, Env, JsObject, JsString, JsUndefined, Task}; use napi::{CallContext, Either, Env, JsObject, JsString, JsUndefined, Task};
use std::sync::Arc; use std::sync::Arc;
use swc::{config::ParseOptions, try_with_handler}; use swc_core::{
use swc_common::{comments::Comments, errors::ColorConfig, FileName, FilePathMapping, SourceMap}; base::{config::ParseOptions, try_with_handler},
common::{comments::Comments, errors::ColorConfig, FileName, FilePathMapping, SourceMap},
};
pub struct ParseTask { pub struct ParseTask {
pub filename: FileName, pub filename: FileName,
...@@ -20,7 +22,7 @@ impl Task for ParseTask { ...@@ -20,7 +22,7 @@ impl Task for ParseTask {
type JsValue = JsString; type JsValue = JsString;
fn compute(&mut self) -> napi::Result<Self::Output> { fn compute(&mut self) -> napi::Result<Self::Output> {
let c = swc::Compiler::new(Arc::new(SourceMap::new(FilePathMapping::empty()))); let c = swc_core::base::Compiler::new(Arc::new(SourceMap::new(FilePathMapping::empty())));
let options: ParseOptions = deserialize_json(&self.options).convert_err()?; let options: ParseOptions = deserialize_json(&self.options).convert_err()?;
let comments = c.comments().clone(); let comments = c.comments().clone();
...@@ -33,7 +35,7 @@ impl Task for ParseTask { ...@@ -33,7 +35,7 @@ impl Task for ParseTask {
c.cm.new_source_file(self.filename.clone(), self.src.clone()); c.cm.new_source_file(self.filename.clone(), self.src.clone());
let program = try_with_handler( let program = try_with_handler(
c.cm.clone(), c.cm.clone(),
swc::HandlerOpts { swc_core::base::HandlerOpts {
color: ColorConfig::Never, color: ColorConfig::Never,
skip_filename: false, skip_filename: false,
}, },
......
...@@ -42,9 +42,11 @@ use std::{ ...@@ -42,9 +42,11 @@ use std::{
rc::Rc, rc::Rc,
sync::Arc, sync::Arc,
}; };
use swc::{try_with_handler, Compiler, TransformOutput}; use swc_core::{
use swc_common::{errors::ColorConfig, FileName}; base::{try_with_handler, Compiler, TransformOutput},
use swc_ecmascript::transforms::pass::noop; common::{errors::ColorConfig, FileName},
ecma::transforms::base::pass::noop,
};
/// Input to transform /// Input to transform
#[derive(Debug)] #[derive(Debug)]
...@@ -70,7 +72,7 @@ impl Task for TransformTask { ...@@ -70,7 +72,7 @@ impl Task for TransformTask {
let res = catch_unwind(AssertUnwindSafe(|| { let res = catch_unwind(AssertUnwindSafe(|| {
try_with_handler( try_with_handler(
self.c.cm.clone(), self.c.cm.clone(),
swc::HandlerOpts { swc_core::base::HandlerOpts {
color: ColorConfig::Never, color: ColorConfig::Never,
skip_filename: true, skip_filename: true,
}, },
......
...@@ -15,13 +15,19 @@ Inflector = "0.11.4" ...@@ -15,13 +15,19 @@ Inflector = "0.11.4"
once_cell = "1.13.0" once_cell = "1.13.0"
regex = {version = "1.5.4", features = ["std", "perf"], default-features = false} regex = {version = "1.5.4", features = ["std", "perf"], default-features = false}
serde = {version = "1.0.130", features = ["derive"]} serde = {version = "1.0.130", features = ["derive"]}
swc_atoms = "0.4.8"
swc_common = { version = "0.27.11", features = ["concurrent"] }
swc_ecmascript = { version = "0.189.4", features = ["utils", "visit"] }
tracing = "0.1.32" tracing = "0.1.32"
swc_core = { version = "0.20.4", features = [
"common_concurrent",
"ecma_ast",
"ecma_utils",
"ecma_visit"
] }
[dev-dependencies] [dev-dependencies]
serde_json = "1" serde_json = "1"
swc_ecma_transforms_testing = "0.105.5"
swc_ecmascript = { version = "0.189.4", features = ["parser", "transforms"] }
testing = "0.29.4" testing = "0.29.4"
swc_core = { version = "0.20.4", features = [
"ecma_parser",
"ecma_transforms",
"testing_transform"
] }
...@@ -8,9 +8,11 @@ pub use crate::{ ...@@ -8,9 +8,11 @@ pub use crate::{
}; };
use serde::Deserialize; use serde::Deserialize;
use std::{cell::RefCell, rc::Rc}; use std::{cell::RefCell, rc::Rc};
use swc_atoms::JsWord; use swc_core::{
use swc_common::{chain, pass::Optional, FileName}; common::{chain, pass::Optional, FileName},
use swc_ecmascript::visit::{Fold, VisitMut}; ecma::atoms::JsWord,
ecma::visit::{Fold, VisitMut},
};
mod css; mod css;
mod utils; mod utils;
......
use super::State; use super::State;
use crate::Config; use crate::Config;
use std::{cell::RefCell, rc::Rc}; use std::{cell::RefCell, rc::Rc};
use swc_ecmascript::{ use swc_core::{
ast::*, ecma::ast::*,
visit::{as_folder, noop_visit_mut_type, noop_visit_type, Fold, Visit, VisitMut, VisitWith}, ecma::visit::{
as_folder, noop_visit_mut_type, noop_visit_type, Fold, Visit, VisitMut, VisitWith,
},
}; };
pub fn analyzer(config: Rc<Config>, state: Rc<RefCell<State>>) -> impl VisitMut + Fold { pub fn analyzer(config: Rc<Config>, state: Rc<RefCell<State>>) -> impl VisitMut + Fold {
......
pub use self::analyzer::{analyze, analyzer}; pub use self::analyzer::{analyze, analyzer};
use std::{borrow::Cow, cell::RefCell}; use std::{borrow::Cow, cell::RefCell};
use swc_atoms::js_word; use swc_core::{
use swc_common::{collections::AHashMap, SyntaxContext}; common::{collections::AHashMap, SyntaxContext},
use swc_ecmascript::ast::*; ecma::ast::*,
ecma::atoms::js_word,
};
mod analyzer; mod analyzer;
...@@ -310,7 +312,11 @@ impl State { ...@@ -310,7 +312,11 @@ impl State {
} }
pub fn prefix_leading_digit(s: &str) -> Cow<str> { pub fn prefix_leading_digit(s: &str) -> Cow<str> {
if s.chars().next().map(|c| c.is_digit(10)).unwrap_or(false) { if s.chars()
.next()
.map(|c| c.is_ascii_digit())
.unwrap_or(false)
{
Cow::Owned(format!("sc-{}", s)) Cow::Owned(format!("sc-{}", s))
} else { } else {
Cow::Borrowed(s) Cow::Borrowed(s)
......
...@@ -5,12 +5,12 @@ use crate::{ ...@@ -5,12 +5,12 @@ use crate::{
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use std::{cell::RefCell, convert::TryInto, path::Path, rc::Rc}; use std::{cell::RefCell, convert::TryInto, path::Path, rc::Rc};
use swc_atoms::{js_word, JsWord}; use swc_core::{
use swc_common::{util::take::Take, FileName, DUMMY_SP}; common::{util::take::Take, FileName, DUMMY_SP},
use swc_ecmascript::{ ecma::ast::*,
ast::*, ecma::atoms::{js_word, JsWord},
utils::{quote_ident, ExprFactory}, ecma::utils::{quote_ident, ExprFactory},
visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith}, ecma::visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith},
}; };
use tracing::{debug, span, trace, Level}; use tracing::{debug, span, trace, Level};
......
use swc_common::collections::AHashSet; use swc_core::{
use swc_ecmascript::{ common::collections::AHashSet,
ast::{ ecma::ast::{
ArrowExpr, ClassDecl, FnDecl, Function, Id, ImportDefaultSpecifier, ImportNamedSpecifier, ArrowExpr, ClassDecl, FnDecl, Function, Id, ImportDefaultSpecifier, ImportNamedSpecifier,
ImportStarAsSpecifier, ObjectPatProp, Pat, VarDeclarator, ImportStarAsSpecifier, ObjectPatProp, Pat, VarDeclarator,
}, },
visit::{noop_visit_type, Visit, VisitWith}, ecma::visit::{noop_visit_type, Visit, VisitWith},
}; };
// Modified from swc_ecma_utils/src/lib.rs:BindingCollector. // Modified from swc_ecma_utils/src/lib.rs:BindingCollector.
......
...@@ -8,16 +8,16 @@ use crate::State; ...@@ -8,16 +8,16 @@ use crate::State;
use inflector::Inflector; use inflector::Inflector;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use swc_atoms::{js_word, JsWord}; use swc_core::{
use swc_common::{ common::{
collections::{AHashMap, AHashSet}, collections::{AHashMap, AHashSet},
util::take::Take, util::take::Take,
Spanned, DUMMY_SP, Spanned, DUMMY_SP,
}; },
use swc_ecmascript::{ ecma::ast::*,
ast::*, ecma::atoms::{js_word, JsWord},
utils::{prepend_stmt, private_ident, quote_ident, ExprFactory}, ecma::utils::{prepend_stmt, private_ident, quote_ident, ExprFactory},
visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith}, ecma::visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith},
}; };
use crate::utils::{get_prop_key_as_expr, get_prop_name, get_prop_name2}; use crate::utils::{get_prop_key_as_expr, get_prop_name, get_prop_name2};
......
...@@ -2,11 +2,11 @@ ...@@ -2,11 +2,11 @@
use std::{fs::read_to_string, path::PathBuf}; use std::{fs::read_to_string, path::PathBuf};
use styled_components::{styled_components, Config}; use styled_components::{styled_components, Config};
use swc_common::{chain, Mark}; use swc_core::{
use swc_ecma_transforms_testing::test_fixture; common::{chain, Mark},
use swc_ecmascript::{ ecma::parser::{EsConfig, Syntax},
parser::{EsConfig, Syntax}, ecma::transforms::base::resolver,
transforms::resolver, ecma::transforms::testing::test_fixture,
}; };
#[testing::fixture("tests/fixtures/**/code.js")] #[testing::fixture("tests/fixtures/**/code.js")]
......
...@@ -11,12 +11,23 @@ version = "0.15.0" ...@@ -11,12 +11,23 @@ version = "0.15.0"
[dependencies] [dependencies]
easy-error = "1.0.0" easy-error = "1.0.0"
swc_common = { version = "0.27.11", features = ["concurrent", "sourcemap"] }
swc_css = "0.120.0"
swc_css_prefixer = "0.117.0"
swc_ecmascript = { version = "0.189.4", features = ["parser", "minifier", "utils", "visit"] }
tracing = "0.1.32" tracing = "0.1.32"
swc_core = { version = "0.20.4", features = [
"common_concurrent",
"css_ast",
"css_codegen",
"css_parser",
"css_prefixer",
"css_visit",
"ecma_parser",
"ecma_minifier",
"ecma_utils",
"ecma_visit"
] }
[dev-dependencies] [dev-dependencies]
swc_ecma_transforms_testing = "0.105.5"
testing = "0.29.4" testing = "0.29.4"
swc_core = { version = "0.20.4", features = [
"testing_transform"
] }
...@@ -3,16 +3,17 @@ use std::collections::hash_map::DefaultHasher; ...@@ -3,16 +3,17 @@ use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use std::mem::take; use std::mem::take;
use std::sync::Arc; use std::sync::Arc;
use swc_common::errors::HANDLER;
use swc_common::{collections::AHashSet, FileName, SourceMap, Span, DUMMY_SP}; use swc_core::{
use swc_ecmascript::ast::*; common::{collections::AHashSet, errors::HANDLER, FileName, SourceMap, Span, DUMMY_SP},
use swc_ecmascript::minifier::{ ecma::ast::*,
eval::{EvalResult, Evaluator}, ecma::minifier::{
marks::Marks, eval::{EvalResult, Evaluator},
marks::Marks,
},
ecma::utils::{collect_decls, drop_span, prepend_stmt, private_ident},
ecma::visit::{Fold, FoldWith},
}; };
use swc_ecmascript::utils::{collect_decls, prepend_stmt};
use swc_ecmascript::utils::{drop_span, private_ident};
use swc_ecmascript::visit::{Fold, FoldWith};
//use external::external_styles; //use external::external_styles;
use transform_css::transform_css; use transform_css::transform_css;
...@@ -173,7 +174,7 @@ impl Fold for StyledJSXTransformer { ...@@ -173,7 +174,7 @@ impl Fold for StyledJSXTransformer {
if let JSXElementName::Ident(Ident { sym, span, .. }) = &el.name { if let JSXElementName::Ident(Ident { sym, span, .. }) = &el.name {
if sym != "style" if sym != "style"
&& sym != self.style_import_name.as_ref().unwrap() && sym != self.style_import_name.as_ref().unwrap()
&& (!is_capitalized(&*sym) && (!is_capitalized(&**sym)
|| self || self
.nearest_scope_bindings .nearest_scope_bindings
.contains(&(sym.clone(), span.ctxt))) .contains(&(sym.clone(), span.ctxt)))
...@@ -535,13 +536,13 @@ impl StyledJSXTransformer { ...@@ -535,13 +536,13 @@ impl StyledJSXTransformer {
} }
} }
return JSXStyle::Local(LocalStyle { JSXStyle::Local(LocalStyle {
hash: format!("{:x}", hasher.finish()), hash: format!("{:x}", hasher.finish()),
css, css,
css_span, css_span,
is_dynamic, is_dynamic,
expressions, expressions,
}); })
} }
fn replace_jsx_style(&mut self, el: &JSXElement) -> Result<JSXElement, Error> { fn replace_jsx_style(&mut self, el: &JSXElement) -> Result<JSXElement, Error> {
......
use easy_error::{bail, Error}; use easy_error::{bail, Error};
use std::panic; use std::panic;
use std::sync::Arc; use std::sync::Arc;
use swc_common::errors::HANDLER;
use swc_common::util::take::Take;
use swc_common::{source_map::Pos, BytePos, Span, SyntaxContext, DUMMY_SP};
use swc_common::{SourceMap, Spanned};
use swc_css::ast::*;
use swc_css::codegen::{
writer::basic::{BasicCssWriter, BasicCssWriterConfig},
CodeGenerator, CodegenConfig, Emit,
};
use swc_css::parser::{parse_str, parse_tokens, parser::ParserConfig};
use swc_css::visit::{VisitMut, VisitMutWith};
use swc_css_prefixer::prefixer;
use swc_ecmascript::ast::{Expr, Tpl, TplElement};
use swc_ecmascript::parser::StringInput;
use tracing::{debug, trace}; use tracing::{debug, trace};
use swc_core::{
common::{
errors::HANDLER, source_map::Pos, util::take::Take, BytePos, SourceMap, Span, Spanned,
SyntaxContext, DUMMY_SP,
},
css::prefixer::prefixer,
css::{
ast::*,
codegen::{
writer::basic::{BasicCssWriter, BasicCssWriterConfig},
CodeGenerator, CodegenConfig, Emit,
},
parser::{parse_str, parse_tokens, parser::ParserConfig},
visit::{VisitMut, VisitMutWith},
},
ecma::ast::{Expr, Tpl, TplElement},
ecma::parser::StringInput,
};
use super::{hash_string, string_literal_expr, LocalStyle}; use super::{hash_string, string_literal_expr, LocalStyle};
pub fn transform_css( pub fn transform_css(
...@@ -110,7 +115,7 @@ pub fn transform_css( ...@@ -110,7 +115,7 @@ pub fn transform_css(
/// Returns `(length, value)` /// Returns `(length, value)`
fn read_number(s: &str) -> (usize, usize) { fn read_number(s: &str) -> (usize, usize) {
for (idx, c) in s.char_indices() { for (idx, c) in s.char_indices() {
if c.is_digit(10) { if c.is_ascii_digit() {
continue; continue;
} }
...@@ -219,6 +224,12 @@ impl Namespacer { ...@@ -219,6 +224,12 @@ impl Namespacer {
to_tokens(v).tokens to_tokens(v).tokens
} }
PseudoClassSelectorChildren::CompoundSelector(v) => to_tokens(v).tokens, PseudoClassSelectorChildren::CompoundSelector(v) => to_tokens(v).tokens,
PseudoClassSelectorChildren::ForgivingSelectorList(v) => {
to_tokens(v).tokens
}
PseudoClassSelectorChildren::ForgivingRelativeSelectorList(v) => {
to_tokens(v).tokens
}
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
...@@ -501,7 +512,7 @@ where ...@@ -501,7 +512,7 @@ where
} }
let span = node.span(); let span = node.span();
let lexer = swc_css::parser::lexer::Lexer::new( let lexer = swc_core::css::parser::lexer::Lexer::new(
StringInput::new(&s, span.lo, span.hi), StringInput::new(&s, span.lo, span.hi),
ParserConfig { ParserConfig {
allow_wrong_line_comments: true, allow_wrong_line_comments: true,
......
use std::collections::hash_map::DefaultHasher; use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher; use std::hash::Hasher;
use swc_common::DUMMY_SP; use swc_core::{common::DUMMY_SP, ecma::ast::*};
use swc_ecmascript::ast::*;
use super::{ExternalStyle, JSXStyle, LocalStyle}; use super::{ExternalStyle, JSXStyle, LocalStyle};
......
use std::path::PathBuf; use std::path::PathBuf;
use styled_jsx::styled_jsx; use styled_jsx::styled_jsx;
use swc_common::{chain, FileName, Mark, Span, DUMMY_SP}; use swc_core::{
use swc_ecma_transforms_testing::{test_fixture, test_fixture_allowing_error}; common::{chain, FileName, Mark, Span, DUMMY_SP},
use swc_ecmascript::{ ecma::parser::{EsConfig, Syntax},
parser::{EsConfig, Syntax}, ecma::transforms::base::resolver,
transforms::resolver, ecma::transforms::testing::{test_fixture, test_fixture_allowing_error},
}; };
use testing::fixture; use testing::fixture;
...@@ -60,7 +60,7 @@ fn styled_jsx_fixture(input: PathBuf) { ...@@ -60,7 +60,7 @@ fn styled_jsx_fixture(input: PathBuf) {
} }
pub struct DropSpan; pub struct DropSpan;
impl swc_ecmascript::visit::VisitMut for DropSpan { impl swc_core::ecma::visit::VisitMut for DropSpan {
fn visit_mut_span(&mut self, span: &mut Span) { fn visit_mut_span(&mut self, span: &mut Span) {
*span = DUMMY_SP *span = DUMMY_SP
} }
......
...@@ -6,7 +6,7 @@ export default function IndexPage() { ...@@ -6,7 +6,7 @@ export default function IndexPage() {
<_JSXStyle id={"bbdada4ef17d18ef"}>{"@supports(display:flex){h1{color:hotpink}}"}</_JSXStyle> <_JSXStyle id={"bbdada4ef17d18ef"}>{"@supports((display:flex)or (display:-webkit-box)or (display:-webkit-flex)or (display:-moz-box)or (display:-ms-flexbox)){h1{color:hotpink}}"}</_JSXStyle>
</div>; </div>;
}; };
...@@ -8,12 +8,12 @@ version = "0.0.0" ...@@ -8,12 +8,12 @@ version = "0.0.0"
crate-type = ["cdylib"] crate-type = ["cdylib"]
[features] [features]
default = ["swc_v1"]
swc_v1 = []
plugin = [ plugin = [
"swc/plugin", "getrandom/js",
"swc_plugin_runner/memory_cache", "swc_core/plugin_transform_host_js"
"wasmer/js-default",
"wasmer-wasi/js-default",
"getrandom/js"
] ]
[dependencies] [dependencies]
...@@ -25,14 +25,23 @@ parking_lot_core = "=0.8.0" ...@@ -25,14 +25,23 @@ parking_lot_core = "=0.8.0"
path-clean = "0.1" path-clean = "0.1"
serde = {version = "1", features = ["derive"]} serde = {version = "1", features = ["derive"]}
serde_json = "1" serde_json = "1"
swc = "0.214.9"
swc_common = { version = "0.27.11", features = ["concurrent", "sourcemap"] }
swc_ecmascript = { version = "0.189.4", features = ["codegen", "minifier", "optimization", "parser", "react", "transforms", "typescript", "utils", "visit"] }
swc_plugin_runner = { version = "0.71.15", default-features = false, optional = true }
tracing = { version = "0.1.32", features = ["release_max_level_off"] } tracing = { version = "0.1.32", features = ["release_max_level_off"] }
wasm-bindgen = {version = "0.2", features = ["serde-serialize", "enable-interning"]} wasm-bindgen = {version = "0.2", features = ["serde-serialize", "enable-interning"]}
wasm-bindgen-futures = "0.4.8" wasm-bindgen-futures = "0.4.8"
wasmer = { version = "2.3.0", optional = true, default-features = false }
wasmer-wasi = { version = "2.3.0", optional = true, default-features = false }
getrandom = { version = "0.2.5", optional = true, default-features = false } getrandom = { version = "0.2.5", optional = true, default-features = false }
js-sys = "0.3.59" js-sys = "0.3.59"
swc_core = { version = "0.20.4", features = [
"common_concurrent",
"binding_macro_wasm",
"ecma_codegen",
"ecma_minifier",
"ecma_transforms",
"ecma_transforms_typescript",
"ecma_transforms_optimization",
"ecma_transforms_react",
"ecma_parser",
"ecma_parser_typescript",
"ecma_utils",
"ecma_visit"
] }
...@@ -3,12 +3,15 @@ use js_sys::JsString; ...@@ -3,12 +3,15 @@ use js_sys::JsString;
use next_swc::{custom_before_pass, TransformOptions}; use next_swc::{custom_before_pass, TransformOptions};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use std::sync::Arc; use std::sync::Arc;
use swc::{config::JsMinifyOptions, config::ParseOptions, try_with_handler, Compiler};
use swc_common::{comments::Comments, errors::ColorConfig, FileName, FilePathMapping, SourceMap};
use swc_ecmascript::transforms::pass::noop;
use wasm_bindgen::{prelude::*, JsCast}; use wasm_bindgen::{prelude::*, JsCast};
use wasm_bindgen_futures::future_to_promise; use wasm_bindgen_futures::future_to_promise;
use swc_core::{
base::{config::JsMinifyOptions, config::ParseOptions, try_with_handler, Compiler},
common::{comments::Comments, errors::ColorConfig, FileName, FilePathMapping, SourceMap},
ecma::transforms::base::pass::noop,
};
fn convert_err(err: Error) -> JsValue { fn convert_err(err: Error) -> JsValue {
format!("{:?}", err).into() format!("{:?}", err).into()
} }
...@@ -21,7 +24,7 @@ pub fn minify_sync(s: JsString, opts: JsValue) -> Result<JsValue, JsValue> { ...@@ -21,7 +24,7 @@ pub fn minify_sync(s: JsString, opts: JsValue) -> Result<JsValue, JsValue> {
try_with_handler( try_with_handler(
c.cm.clone(), c.cm.clone(),
swc::HandlerOpts { swc_core::base::HandlerOpts {
color: ColorConfig::Never, color: ColorConfig::Never,
skip_filename: false, skip_filename: false,
}, },
...@@ -54,7 +57,7 @@ pub fn transform_sync(s: JsValue, opts: JsValue) -> Result<JsValue, JsValue> { ...@@ -54,7 +57,7 @@ pub fn transform_sync(s: JsValue, opts: JsValue) -> Result<JsValue, JsValue> {
try_with_handler( try_with_handler(
c.cm.clone(), c.cm.clone(),
swc::HandlerOpts { swc_core::base::HandlerOpts {
color: ColorConfig::Never, color: ColorConfig::Never,
skip_filename: false, skip_filename: false,
}, },
...@@ -112,11 +115,11 @@ pub fn transform(s: JsValue, opts: JsValue) -> js_sys::Promise { ...@@ -112,11 +115,11 @@ pub fn transform(s: JsValue, opts: JsValue) -> js_sys::Promise {
pub fn parse_sync(s: JsString, opts: JsValue) -> Result<JsValue, JsValue> { pub fn parse_sync(s: JsString, opts: JsValue) -> Result<JsValue, JsValue> {
console_error_panic_hook::set_once(); console_error_panic_hook::set_once();
let c = swc::Compiler::new(Arc::new(SourceMap::new(FilePathMapping::empty()))); let c = swc_core::base::Compiler::new(Arc::new(SourceMap::new(FilePathMapping::empty())));
try_with_handler( try_with_handler(
c.cm.clone(), c.cm.clone(),
swc::HandlerOpts { swc_core::base::HandlerOpts {
..Default::default() ..Default::default()
}, },
|handler| { |handler| {
......
nightly-2022-02-23 nightly-2022-06-12
\ No newline at end of file \ No newline at end of file
...@@ -71,7 +71,7 @@ ...@@ -71,7 +71,7 @@
}, },
"dependencies": { "dependencies": {
"@next/env": "12.2.6-canary.8", "@next/env": "12.2.6-canary.8",
"@swc/helpers": "0.4.3", "@swc/helpers": "0.4.11",
"caniuse-lite": "^1.0.30001332", "caniuse-lite": "^1.0.30001332",
"postcss": "8.4.14", "postcss": "8.4.14",
"styled-jsx": "5.0.5", "styled-jsx": "5.0.5",
......
This diff is collapsed.
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