Skip to content

Commit

Permalink
WASM
Browse files Browse the repository at this point in the history
  • Loading branch information
mischnic committed Nov 9, 2021
1 parent 29a487f commit bef6f7f
Show file tree
Hide file tree
Showing 8 changed files with 172 additions and 41 deletions.
5 changes: 3 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
node_modules
target
*.node
node_modules/
target/
pkg/
6 changes: 6 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"bracketSpacing": false,
"endOfLine": "lf",
"singleQuote": true,
"trailingComma": "all"
}
96 changes: 96 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 15 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ edition = "2018"
crate-type = ["cdylib"]

[dependencies]
napi = { version = "1", features = ["serde-json"] }
napi-derive = "1"
serde = { version = "1.0.123", features = ["derive"] }
serde_bytes = "0.11.5"
cssparser = "0.28.1"
Expand All @@ -23,5 +21,18 @@ bitflags = "*"
[target.'cfg(target_os = "macos")'.dependencies]
jemallocator = { version = "0.3.2", features = ["disable_initial_exec_tls"] }

[build-dependencies]
napi-build = { version = "1" }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
napi = { version = "1", features = ["serde-json"] }
napi-derive = "1"

[target.'cfg(target_arch = "wasm32")'.dependencies]
js-sys = "0.3"
serde-wasm-bindgen = "0.3.0"
wasm-bindgen = "0.2"

[target.'cfg(not(target_arch = "wasm32"))'.build-dependencies]
napi-build = "1"

[profile.release]
lto = true
opt-level = 's'
2 changes: 2 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#[cfg(not(target_arch = "wasm32"))]
extern crate napi_build;

fn main() {
#[cfg(not(target_arch = "wasm32"))]
napi_build::setup();
}
19 changes: 3 additions & 16 deletions native.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,8 @@ if (process.platform === 'linux') {
}

let name = `parcel-css.${parts.join('-')}.node`;
if (process.env.PARCEL_BUILD_ENV === 'production') {
module.exports = require(`./${name}`);
} else if (process.env.PARCEL_SWC_WASM) {
const {transform} = require('./wasm/dist-node/parcel_js_swc_wasm.js');

module.exports.transform = function(config) {
let result = transform(config);
return {
...result,
// Hydrate Uint8Array into Buffer
code: Buffer.from(result.code.buffer),
};
};
} else if (require('fs').existsSync(require('path').join(__dirname, name))) {
module.exports = require(`./${name}`);
if (process.env.CSS_TRANSFORMER_WASM) {
module.exports = require(`./pkg`);
} else {
module.exports = require(`self-published/${name}`);
module.exports = require(`./${name}`);
}
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@
},
"scripts": {
"build": "napi build --platform",
"build-release": "napi build --platform --release"
"build-release": "napi build --platform --release",
"wasm:build": "wasm-pack build --target nodejs",
"wasm:build-release": "wasm-pack build --target nodejs --release"
}
}
62 changes: 44 additions & 18 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
extern crate napi;
#[macro_use]
extern crate napi_derive;
extern crate serde;
extern crate serde_bytes;
extern crate cssparser;
Expand All @@ -24,7 +21,6 @@ mod printer;
mod traits;
mod macros;

use napi::{CallContext, JsObject, JsBuffer};
use serde::{Deserialize, Serialize};
use cssparser::{Parser, ParserInput, RuleListParser};
use crate::traits::ToCss;
Expand All @@ -36,25 +32,62 @@ use std::collections::HashMap;

use parser::TopLevelRuleParser;

#[derive(Serialize, Debug, Deserialize)]
struct Config {
filename: String,
#[serde(with = "serde_bytes")]
code: Vec<u8>,
targets: Option<Browsers>
// ---------------------------------------------

#[cfg(target_arch = "wasm32")]
use serde_wasm_bindgen::{from_value};
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;

#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
pub fn transform(config_val: JsValue) -> Result<JsValue, JsValue> {
let config: Config = from_value(config_val).map_err(JsValue::from)?;

let code = unsafe { std::str::from_utf8_unchecked(&config.code) };

Ok(compile(code, true, config.targets).into())
}

// ---------------------------------------------

#[cfg(not(target_arch = "wasm32"))]
extern crate napi;
#[cfg(not(target_arch = "wasm32"))]
#[macro_use]
extern crate napi_derive;
#[cfg(not(target_arch = "wasm32"))]
use napi::{CallContext, JsObject, JsBuffer};

#[cfg(not(target_arch = "wasm32"))]
#[js_function(1)]
fn transform(ctx: CallContext) -> napi::Result<JsBuffer> {
let opts = ctx.get::<JsObject>(0)?;
let config: Config = ctx.env.from_js_value(opts)?;

let code = unsafe { std::str::from_utf8_unchecked(&config.code) };
let res = compile(code, true, config.targets);

Ok(ctx.env.create_buffer_with_data(res.into_bytes())?.into_raw())
}

#[cfg(not(target_arch = "wasm32"))]
#[module_exports]
fn init(mut exports: JsObject) -> napi::Result<()> {
exports.create_named_method("transform", transform)?;

Ok(())
}

// ---------------------------------------------

#[derive(Serialize, Debug, Deserialize)]
struct Config {
pub filename: String,
#[serde(with = "serde_bytes")]
pub code: Vec<u8>,
pub targets: Option<Browsers>
}

fn compile(code: &str, minify: bool, targets: Option<Browsers>) -> String {
let mut input = ParserInput::new(&code);
let mut parser = Parser::new(&mut input);
Expand Down Expand Up @@ -178,13 +211,6 @@ fn compile(code: &str, minify: bool, targets: Option<Browsers>) -> String {
dest
}

#[module_exports]
fn init(mut exports: JsObject) -> napi::Result<()> {
exports.create_named_method("transform", transform)?;

Ok(())
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down

0 comments on commit bef6f7f

Please sign in to comment.