Skip to content

Commit

Permalink
Minify wasm-run, refactored cli opts
Browse files Browse the repository at this point in the history
  • Loading branch information
sfisol committed Aug 2, 2024
1 parent 3ecd523 commit c7d9411
Show file tree
Hide file tree
Showing 26 changed files with 547 additions and 2,463 deletions.
8 changes: 5 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
Cargo.lock
/target
.vscode
/build
/demo_build
/examples/build
.vscode
/node_modules
/package-lock.json
/target
Cargo.lock
6 changes: 4 additions & 2 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<!-- markdownlint-configure-file { "no-duplicate-heading": { "siblings_only": true } } -->

<!-- markdownlint-disable-next-line first-line-h1 -->
## 0.6.0 Unreleased
## 0.6.0 - 2024-08-02

### Added

Expand All @@ -11,7 +11,9 @@
* `JsJson` implementation for unit type `()`
* All http methods in `FetchMethod`
* `history_replace` method in `Driver`
* vertigo-cli: `add-watch-path` to `watch` command
* Minification of `wasm_run.js`
* vertigo-cli: `--add-watch-path` to `watch` command
* vertigo-cli: `--wasm-run-source-map` to `build` and `watch` command

### Fixed

Expand Down
25 changes: 5 additions & 20 deletions Makefile.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,12 @@ script = [

[tasks.demo-watch]
script = [
'cargo run --bin vertigo -- watch vertigo-demo --dest-dir=demo_build --env ws_chat=ws://127.0.0.1:3333/ws'
'cargo run --bin vertigo -- watch vertigo-demo --dest-dir=demo_build --wasm-run-source-map --env ws_chat=ws://127.0.0.1:3333/ws'
]

[tasks.demo-start]
script = [
"cargo run --bin vertigo -- build vertigo-demo --dest-dir=demo_build",
"cargo run --bin vertigo -- build vertigo-demo --dest-dir=demo_build --wasm-run-source-map",
"cargo run --bin vertigo -- serve --dest-dir=demo_build --env ws_chat=ws://127.0.0.1:3333/ws"
]

Expand All @@ -70,27 +70,12 @@ script = [
'cargo run --bin vertigo -- watch vertigo-example-trafficlights --dest-dir=examples/build/trafficlights',
]

# JavaScript dev builds

[tasks.internal-run-ts]
private = true
command = "npx"
args = [ "-p", "typescript", "tsc",
"--strict",
"--noUnusedLocals", "--noUnusedParameters", "--noUncheckedIndexedAccess",
"--noEmitOnError",
"--lib", "es6,dom,esnext",
"--target", "esnext",
"--module", "es6",
"--outDir", "crates/vertigo/src/driver_module/src_js_build",
"crates/vertigo/src/driver_module/src_js/index.ts",
]
# JavaScript dev build

[tasks.build-js]
dependencies = [ "internal-run-ts" ]
script = [
"npx rollup crates/vertigo/src/driver_module/src_js_build/index.js --file crates/vertigo/src/driver_module/wasm_run.js",
"rm -rf crates/vertigo/src/driver_module/src_js_build",
"npm install",
"npx rollup -c",
]

[tasks.lint]
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ A reactive Real-DOM library with SSR for Rust
[![crates.io](https://img.shields.io/crates/v/vertigo)](https://crates.io/crates/vertigo)
[![Documentation](https://docs.rs/vertigo/badge.svg)](https://docs.rs/vertigo)
![MIT or Apache 2.0 licensed](https://img.shields.io/crates/l/vertigo.svg)
[![Dependency Status](https://deps.rs/crate/vertigo/0.5.0/status.svg)](https://deps.rs/crate/vertigo/0.5.0)
[![Dependency Status](https://deps.rs/crate/vertigo/0.6.0/status.svg)](https://deps.rs/crate/vertigo/0.6.0)
[![CI](https://github.com/vertigo-web/vertigo/actions/workflows/pipeline.yaml/badge.svg)](https://github.com/vertigo-web/vertigo/actions/workflows/pipeline.yaml)
[![downloads](https://img.shields.io/crates/d/vertigo.svg)](https://crates.io/crates/vertigo)

Expand All @@ -25,7 +25,7 @@ Go to **[TUTORIAL](https://github.com/vertigo-web/vertigo/blob/master/tutorial.m
Dependencies:

```toml
vertigo = "0.5"
vertigo = "0.6"
```

Example 1:
Expand Down
18 changes: 14 additions & 4 deletions crates/vertigo-cli/src/build/build_opts.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,33 @@
use clap::Args;
use std::path::PathBuf;

use crate::commons::models::CommonOpts;

use super::wasm_path::WasmPath;

#[derive(Args, Debug, Clone)]
pub struct BuildOpts {
#[clap(flatten)]
pub common: CommonOpts,
#[clap(flatten)]
pub inner: BuildOptsInner,
}

#[derive(Args, Debug, Clone)]
pub struct BuildOptsInner {
pub package_name: Option<String>,
#[arg(long, default_value_t = {"./build".to_string()})]
pub dest_dir: String,
#[arg(long, default_value_t = {"/build".to_string()})]
pub public_path: String,
#[arg(short, long)]
pub disable_wasm_opt: bool,
#[arg(long)]
pub wasm_run_source_map: bool,
}

impl BuildOpts {
pub fn public_path_to(&self, path: impl Into<String>) -> String {
let path = path.into();
format!("{}/{path}", self.public_path)
format!("{}/{path}", self.inner.public_path)
}

pub fn new_path_in_static_make(&self, path: &[&str]) -> WasmPath {
Expand All @@ -36,6 +46,6 @@ impl BuildOpts {
}

pub fn get_dest_dir(&self) -> WasmPath {
WasmPath::new(PathBuf::from(self.dest_dir.as_str()))
WasmPath::new(PathBuf::from(self.common.dest_dir.as_str()))
}
}
125 changes: 125 additions & 0 deletions crates/vertigo-cli/src/build/build_run.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
use std::path::PathBuf;

use crate::commons::models::IndexModel;

use super::{
build_opts::BuildOpts,
cargo_build::run_cargo_build,
cargo_workspace::{get_workspace, Workspace},
wasm_opt::run_wasm_opt,
wasm_path::WasmPath,
check_env::check_env,
find_target::{find_package_rlib_in_target, find_wasm_in_target},
};

pub fn run(opts: BuildOpts) -> Result<(), i32> {
let ws = get_workspace().expect("Can't read workspace");

run_with_ws(opts, &ws)
}

pub fn run_with_ws(opts: BuildOpts, ws: &Workspace) -> Result<(), i32> {
let package_name = match opts.inner.package_name.as_deref() {
Some(name) => name.to_string(),
None => match ws.infer_package_name() {
Some(name) => {
log::info!("Inferred package name = {}", name);
name
}
None => {
log::error!(
"Can't find vertigo project in {} (no cdylib member)",
ws.get_root_dir()
);
return Err(-1);
}
},
};

check_env()?;

let dest_dir = WasmPath::new(PathBuf::from(&opts.common.dest_dir));

// Clean destination

dest_dir.remove_dir_all();
dest_dir.create_dir_all();

// Delete rlibs to re-generate static files

find_package_rlib_in_target(&package_name).remove_file();

// Run build

let target_path = match run_cargo_build(&package_name, &opts.inner.public_path, ws) {
Ok(path) => path,
Err(_) => return Err(-2),
};

// Get wasm_run.js and index.template.html from vertigo build

let vertigo_statics_dir = target_path.join("static");

let run_script_content = std::fs::read(vertigo_statics_dir.join("wasm_run.js"))
.expect("No wasm_run in statics directory");

let run_script_hash_name = opts
.new_path_in_static_make(&["wasm_run.js"])
.save_with_hash(&run_script_content);

if opts.inner.wasm_run_source_map {
let run_script_sourcemap_content = std::fs::read_to_string(vertigo_statics_dir.join("wasm_run.js.map"))
.expect("No wasm_run sourcemap in statics directory")
// Replace original script filename in sourcemap with the hashed one
.replace("wasm_run.js", &run_script_hash_name);

opts
.new_path_in_static_make(&["wasm_run.js.map"])
.save(&run_script_sourcemap_content.into_bytes());
}

// Copy .wasm to destination

let wasm_path_target = find_wasm_in_target(&package_name);
let wasm_path = opts.new_path_in_static_from(&wasm_path_target);

// Optimize .wasm

let wasm_path_hash =
if !opts.inner.disable_wasm_opt && run_wasm_opt(&wasm_path_target, &wasm_path) {
// optimized
let wasm_path_hash = wasm_path.save_with_hash(wasm_path.read().as_slice());
wasm_path.remove_file();
wasm_path_hash
} else {
// copy without optimization
let wasm_content = wasm_path_target.read();
wasm_path.save_with_hash(wasm_content.as_slice())
};

// Generate index.json in destination

let index = IndexModel {
run_js: opts.public_path_to(run_script_hash_name),
wasm: opts.public_path_to(wasm_path_hash),
};

let index_content = serde_json::to_string_pretty(&index).unwrap();
opts.new_path_in_static_make(&["index.json"])
.save(index_content.as_bytes());

// Copy statics generated by dom macro invocations

if let Ok(dir) = std::fs::read_dir(vertigo_statics_dir.join("included")) {
dir.for_each(|entry| {
if let Ok(entry) = entry {
let src_file_path = WasmPath::new(entry.path());
let content = src_file_path.read();
let dest_file_path = opts.new_path_in_static_from(&src_file_path);
dest_file_path.save(&content);
}
});
}

Ok(())
}
113 changes: 4 additions & 109 deletions crates/vertigo-cli/src/build/mod.rs
Original file line number Diff line number Diff line change
@@ -1,117 +1,12 @@
pub mod build_opts;
mod build_opts;
mod build_run;
mod cargo_build;
mod check_env;
mod find_target;
mod wasm_opt;
//TODO: To be eventually moved to separate 'commons' lib
mod cargo_workspace;
mod wasm_path;

use std::path::PathBuf;
use wasm_path::WasmPath;

use crate::commons::models::IndexModel;
pub use build_opts::BuildOpts;

pub use build_opts::{BuildOpts, BuildOptsInner};
pub use build_run::{run, run_with_ws};
pub use cargo_workspace::{get_workspace, Workspace};

pub fn run(opts: BuildOpts) -> Result<(), i32> {
let ws = get_workspace().expect("Can't read workspace");

run_with_ws(opts, &ws)
}

pub fn run_with_ws(opts: BuildOpts, ws: &Workspace) -> Result<(), i32> {
let package_name = match opts.package_name.as_deref() {
Some(name) => name.to_string(),
None => match ws.infer_package_name() {
Some(name) => {
log::info!("Inferred package name = {}", name);
name
}
None => {
log::error!(
"Can't find vertigo project in {} (no cdylib member)",
ws.get_root_dir()
);
return Err(-1);
}
},
};

check_env::check_env()?;

let dest_dir = WasmPath::new(PathBuf::from(&opts.dest_dir));

// Clean destination

dest_dir.remove_dir_all();
dest_dir.create_dir_all();

// Delete rlibs to re-generate static files

find_target::find_package_rlib_in_target(&package_name).remove_file();

// Run build

let target_path = match cargo_build::run_cargo_build(&package_name, &opts.public_path, ws) {
Ok(path) => path,
Err(_) => return Err(-2),
};

// Get wasm_run.js and index.template.html from vertigo build

let vertigo_statics_dir = target_path.join("static");

let run_script_content = std::fs::read(vertigo_statics_dir.join("wasm_run.js"))
.expect("No wasm_run in statics directory");

let run_script_hash_name = opts
.new_path_in_static_make(&["wasm_run.js"])
.save_with_hash(&run_script_content);

// Copy .wasm to destination

let wasm_path_target = find_target::find_wasm_in_target(&package_name);
let wasm_path = opts.new_path_in_static_from(&wasm_path_target);

// Optimize .wasm

let wasm_path_hash =
if !opts.disable_wasm_opt && wasm_opt::run_wasm_opt(&wasm_path_target, &wasm_path) {
// optimized
let wasm_path_hash = wasm_path.save_with_hash(wasm_path.read().as_slice());
wasm_path.remove_file();
wasm_path_hash
} else {
// copy without optimization
let wasm_content = wasm_path_target.read();
wasm_path.save_with_hash(wasm_content.as_slice())
};

// Generate index.json in destination

let index = IndexModel {
run_js: opts.public_path_to(run_script_hash_name),
wasm: opts.public_path_to(wasm_path_hash),
};

let index_content = serde_json::to_string_pretty(&index).unwrap();
opts.new_path_in_static_make(&["index.json"])
.save(index_content.as_bytes());

// Copy statics generated by dom macro invocations

if let Ok(dir) = std::fs::read_dir(vertigo_statics_dir.join("included")) {
dir.for_each(|entry| {
if let Ok(entry) = entry {
let src_file_path = WasmPath::new(entry.path());
let content = src_file_path.read();
let dest_file_path = opts.new_path_in_static_from(&src_file_path);
dest_file_path.save(&content);
}
});
}

Ok(())
}
Loading

0 comments on commit c7d9411

Please sign in to comment.