├── .cargo └── config.toml ├── .gitignore ├── .woodpecker.yml ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── example ├── .gitignore ├── Cargo.toml ├── backend │ ├── Cargo.toml │ ├── build.rs │ └── src │ │ └── main.rs └── frontend │ ├── Cargo.toml │ ├── README.md │ ├── css │ └── style.scss │ ├── index.html │ ├── src │ └── lib.rs │ └── static │ └── star.png ├── renovate.json ├── src └── lib.rs ├── tests └── bevy │ ├── .gitignore │ ├── Cargo.toml │ ├── backend │ ├── Cargo.toml │ ├── build.rs │ └── src │ │ └── main.rs │ └── frontend │ ├── Cargo.toml │ ├── css │ └── style.scss │ ├── index.html │ └── src │ └── lib.rs └── xtask ├── Cargo.toml └── src └── main.rs /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | [alias] 2 | xtask = "run --package xtask --" 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /.woodpecker.yml: -------------------------------------------------------------------------------- 1 | steps: 2 | test: 3 | image: rust 4 | environment: [CARGO_TERM_COLOR=always] 5 | commands: 6 | - rustup default stable 7 | - cargo xtask ci 8 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | Changelog 2 | ========= 3 | 4 | ## [unreleased] 5 | 6 | ## v0.2.0 7 | - Update dependencies 8 | - Migrated the repo to Codeberg with Woodpecker CI. 9 | - Fix bug where the generated javascript to call init didn't work for 10 | wasm-bindgen 0.2.85 and newer. 11 | - Simplify the cargo:rerun-if-changed paths printed by making use of cargo 12 | 1.50's ability to watch whole directories. 13 | 14 | ## v0.1.4 15 | - Fix bug where environment variables set for the workspace build 16 | would leak into build scripts in the Wasm build. 17 | 18 | ## v0.1.3 19 | - Remove requirement to have `wasm-pack` CLI installed and on the path. 20 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "web-bundler" 3 | description = "Manages the building of WebAssembly single page app frontends from a build.rs script so that they can easily be embedded into Rust API projects" 4 | version = "0.2.0" 5 | edition = "2018" 6 | repository = "https://codeberg.org/worthe-it/web-bundler" 7 | license = "MIT/Apache-2.0" 8 | keywords = ["wasm", "web"] 9 | categories = ["web-programming"] 10 | authors = [ 11 | "Justin Wernick ", 12 | "Panoptix OSS maintainers ", 13 | "Martin Kavík ", 14 | ] 15 | readme = "README.md" 16 | 17 | [dependencies] 18 | fs_extra = "1" 19 | sass-rs = "0.2" 20 | anyhow = "1" 21 | tera = "1" 22 | rand = "0.8" 23 | wasm-pack = "0.12" 24 | 25 | [workspace] 26 | members = [ 27 | "xtask", 28 | ] -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Web Bundler 2 | =========== 3 | 4 | [![crates.io](https://img.shields.io/crates/v/web-bundler.svg)](https://crates.io/crates/web-bundler) 5 | [![status-badge](https://ci.codeberg.org/api/badges/worthe-it/web-bundler/status.svg)](https://ci.codeberg.org/worthe-it/web-bundler) 6 | 7 | Manages the building of WebAssembly single page app frontends from a 8 | build.rs script so that they can easily be embedded into Rust API 9 | projects. 10 | 11 | Internally, the bundler uses 12 | [wasm-pack](https://github.com/rustwasm/wasm-pack) to do the actual 13 | webassembly compilation. 14 | 15 | ## Prerequisites 16 | 17 | From a clean Rustup-based Rust installation, there are no additional 18 | steps. Web Bundler will download and install any dependencies it 19 | needs. 20 | 21 | For Rust installations that are not done with Rustup, you will need to 22 | add the `wasm32-unknown-unknown` compilation target manually (see the 23 | [wasm-pack docs](https://rustwasm.github.io/docs/wasm-pack/prerequisites/non-rustup-setups.html) 24 | for details on how to do this). 25 | 26 | ## Running the Demo Example 27 | 28 | There is an example usage in the [example directory](./example). To 29 | run the example, open a terminal in the example directory and run 30 | `cargo run`. Then, open a web browser and navigate to 31 | . You should see a Seed web application. 32 | 33 | ## Usage 34 | 35 | Web-bundler expects you to have two projects: a frontend project using 36 | a single page app framework (like [Seed]), and a backend project using a 37 | web server framework (like [warp]). 38 | These projects should be in a common 39 | workspace. 40 | 41 | ### Changes to your frontend project 42 | 43 | 1. Update your index.html to allow templating in Javascript and CSS. 44 | 45 | Specifically, you need to add `{{ stylesheet | safe }}` to the 46 | `` section, and `{{ javascript | safe }}` to the end of the 47 | ``. Optionally, if you want to set the base url, add `` to the `` as well. 49 | 50 | See the example [frontend index.html](./example/frontend/index.html). 51 | 52 | 2. Create a root stylesheet for your app called `./css/style.scss`. 53 | 54 | This stylesheet will be compiled to CSS, and embedded directly into 55 | your index.html file. 56 | 57 | See the example [frontend style.scss](./example/frontend/css/style.scss). 58 | 59 | 3. Put all of your static assets in the `static` directory 60 | 61 | All files in the static directory will be copied directly to a static 62 | folder in the output directory. 63 | 64 | See the example [frontend static directory](./example/frontend/static/). 65 | 66 | ### Changes to your API project 67 | 68 | 1. Update your Cargo.toml to depend on your frontend project and web-bundler 69 | 70 | We depend on the frontend project in Cargo.toml so that Cargo knows to 71 | rerun build.rs whenever the frontend project changes. 72 | 73 | See the example [backend Cargo.toml](./example/backend/Cargo.toml). 74 | 75 | 2. Add a build.rs script that calls web-bundler for your frontend 76 | 77 | See the example [backend build.rs](./example/backend/build.rs). 78 | 79 | 3. Use [Rust Embed](https://lib.rs/crates/rust-embed) to embed your built frontend into your API binary 80 | 81 | See the example [backend main.rs](./example/backend/main.rs). Our 82 | example uses the [warp web server][warp]. Rust Embed also has examples for 83 | other web servers in [their repo](https://github.com/pyros2097/rust-embed/tree/master/examples). 84 | 85 | ## target and web-target directories 86 | 87 | When web-bundler compiles the frontend, it overrides the default 88 | target directory to be `web-target` instead of `target`. This is done 89 | because, if the backend and frontend are in the same workspace, Cargo 90 | will already be locking `target` while running the build.rs 91 | script. 92 | 93 | [warp]: https://github.com/seanmonstar/warp 94 | [Seed]: https://github.com/seed-rs/seed 95 | 96 | #### License 97 | 98 | 99 | Licensed under either of 100 | Apache License, Version 2.0 101 | or 102 | MIT license 103 | at your option. 104 | 105 | 106 |
107 | 108 | 109 | Unless you explicitly state otherwise, any contribution intentionally submitted 110 | for inclusion in this crate by you, as defined in the Apache-2.0 license, shall 111 | be dual licensed as above, without any additional terms or conditions. 112 | 113 | -------------------------------------------------------------------------------- /example/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /web-target 3 | -------------------------------------------------------------------------------- /example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = [ 3 | "backend", 4 | "frontend", 5 | ] 6 | 7 | [profile.release] 8 | lto = true 9 | opt-level = 'z' 10 | codegen-units = 1 11 | 12 | [profile.release.build-override] 13 | opt-level = 'z' 14 | codegen-units = 1 15 | -------------------------------------------------------------------------------- /example/backend/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "backend" 3 | version = "0.0.0" 4 | edition = "2018" 5 | 6 | [dependencies] 7 | warp = "0.3" 8 | mime_guess = "2" 9 | 10 | [dependencies.tokio] 11 | version = "1" 12 | features = ["full"] 13 | 14 | [dependencies.rust-embed] 15 | version="5" 16 | features= ["compression", "interpolate-folder-path"] 17 | 18 | # depend on the frontend project here not because we actually use it, 19 | # but because we want to trigger a rerun of the build.rs script if 20 | # anything in it changes. 21 | [build-dependencies.frontend] 22 | path = "../frontend" 23 | 24 | [build-dependencies.web-bundler] 25 | path = "../.." 26 | -------------------------------------------------------------------------------- /example/backend/build.rs: -------------------------------------------------------------------------------- 1 | use std::{env, path::PathBuf, process}; 2 | use web_bundler::WebBundlerOpt; 3 | 4 | fn main() { 5 | let out_dir = PathBuf::from(env::var("OUT_DIR").expect("expected OUT_DIR to be set by Cargo")); 6 | 7 | let opt = WebBundlerOpt { 8 | src_dir: "../frontend".into(), 9 | dist_dir: out_dir.join("ui"), 10 | tmp_dir: out_dir.join("tmp"), 11 | base_url: Some("/".into()), 12 | wasm_version: env::var("CARGO_PKG_VERSION") 13 | .expect("expected CARGO_PKG_VERSION to be set by Cargo"), 14 | release: env::var("PROFILE").expect("expected PROFILE to be set by Cargo") != "debug", 15 | workspace_root: "..".into(), 16 | additional_watch_dirs: Vec::new(), 17 | }; 18 | 19 | if let Err(why) = web_bundler::run(opt) { 20 | println!("Failed to build frontend. Error: {}", why); 21 | process::exit(1); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /example/backend/src/main.rs: -------------------------------------------------------------------------------- 1 | use rust_embed::RustEmbed; 2 | use warp::{filters::BoxedFilter, http::header::HeaderValue, path::Tail, reply::Response, Filter}; 3 | 4 | #[tokio::main] 5 | async fn main() { 6 | let routes = warp::path!("api" / ..) 7 | .and(warp::path::tail()) 8 | .map(|_| "Please pretend there's an API here.") 9 | .or(ui_routes()); 10 | 11 | warp::serve(routes).bind(([127, 0, 0, 1], 3030)).await; 12 | } 13 | 14 | #[derive(RustEmbed)] 15 | #[folder = "$OUT_DIR/ui"] 16 | struct PortalWebAssets; 17 | 18 | pub fn ui_routes() -> BoxedFilter<(impl warp::Reply,)> { 19 | let static_files = warp::get() 20 | .and(warp::path::tail()) 21 | .and_then(|path: Tail| async move { serve(path.as_str()).await }) 22 | .boxed(); 23 | 24 | let spa_mode_index = warp::get() 25 | .and(warp::path::tail()) 26 | .and_then(|path: Tail| async move { 27 | let first_path_segment = path.as_str().split('/').next(); 28 | let last_path_segment = path.as_str().split('/').last(); 29 | let is_api_path = first_path_segment == Some("api"); 30 | let is_index_html = last_path_segment == Some("index.html"); 31 | let is_file_like_path = last_path_segment 32 | .map(|segment| segment.contains('.')) 33 | .unwrap_or(false); 34 | 35 | if !is_api_path && (is_index_html || !is_file_like_path) { 36 | serve("index.html").await 37 | } else { 38 | Err(warp::reject::not_found()) 39 | } 40 | }) 41 | .boxed(); 42 | 43 | // Order is important here. Serve a file if it exists, then fall back to index.html as a default. 44 | static_files.or(spa_mode_index).boxed() 45 | } 46 | 47 | async fn serve(path: &str) -> Result { 48 | if let Some(asset) = PortalWebAssets::get(path) { 49 | let mime = mime_guess::from_path(path).first_or_octet_stream(); 50 | 51 | let mut res = Response::new(asset.into()); 52 | res.headers_mut().insert( 53 | "content-type", 54 | HeaderValue::from_str(mime.as_ref()).unwrap(), 55 | ); 56 | Ok(res) 57 | } else { 58 | Err(warp::reject::not_found()) 59 | } 60 | } 61 | 62 | #[cfg(test)] 63 | mod test { 64 | use super::*; 65 | use warp::http::status::StatusCode; 66 | 67 | #[tokio::test] 68 | async fn test_html() { 69 | let filter = ui_routes(); 70 | let response = warp::test::request().path("/").reply(&filter).await; 71 | 72 | assert_eq!(response.status(), StatusCode::OK); 73 | 74 | let response_body: String = String::from_utf8(response.body().to_vec()).unwrap(); 75 | 76 | assert!(response_body 77 | .contains("")); 78 | assert!(response_body.contains("Seed Quickstart")); 79 | 80 | assert!(response_body.contains(""#, 266 | js_path.display(), 267 | wasm_path.display() 268 | ); 269 | tera_context.insert("javascript", &javascript); 270 | 271 | tera_context.insert("base_url", opt.base_url.as_deref().unwrap_or("/")); 272 | 273 | let sass_options = sass_rs::Options { 274 | output_style: sass_rs::OutputStyle::Compressed, 275 | precision: 4, 276 | indented_syntax: true, 277 | include_paths: Vec::new(), 278 | }; 279 | let style_src_path = opt.src_dir.join("css/style.scss"); 280 | let style_css_content = sass_rs::compile_file(&style_src_path, sass_options) 281 | .map_err(|e| anyhow!("Sass compilation failed: {}", e))?; 282 | 283 | let stylesheet = format!("", style_css_content); 284 | tera_context.insert("stylesheet", &stylesheet); 285 | 286 | let index_html_content = Tera::one_off(&index_html_template, &tera_context, true)?; 287 | 288 | let dest_index_path = opt.dist_dir.join("index.html"); 289 | fs::write(&dest_index_path, index_html_content).with_context(|| { 290 | format!( 291 | "Failed to write the index.html file to {}", 292 | dest_index_path.display() 293 | ) 294 | })?; 295 | 296 | Ok(()) 297 | } 298 | 299 | fn bundle_app_wasm(opt: &WebBundlerOpt) -> Result<()> { 300 | let src_wasm = opt.tmp_dir.join("package_bg.wasm"); 301 | let dest_wasm = opt.dist_dir.join(format!("app-{}.wasm", opt.wasm_version)); 302 | fs::copy(&src_wasm, &dest_wasm).with_context(|| { 303 | format!( 304 | "Failed to copy application wasm from {} to {}", 305 | src_wasm.display(), 306 | dest_wasm.display() 307 | ) 308 | })?; 309 | 310 | let src_js = opt.tmp_dir.join("package.js"); 311 | let dest_js = opt.dist_dir.join(format!("app-{}.js", opt.wasm_version)); 312 | fs::copy(&src_js, &dest_js).with_context(|| { 313 | format!( 314 | "Failed to copy application javascript from {} to {}", 315 | src_js.display(), 316 | dest_js.display() 317 | ) 318 | })?; 319 | Ok(()) 320 | } 321 | 322 | fn bundle_js_snippets(opt: &WebBundlerOpt) -> Result<()> { 323 | let src = opt.tmp_dir.join("snippets"); 324 | let dest = &opt.dist_dir; 325 | 326 | if src.exists() { 327 | fs_extra::dir::copy(&src, &dest, &fs_extra::dir::CopyOptions::new()).with_context( 328 | || { 329 | format!( 330 | "Failed to copy js snippets from {} to {}", 331 | src.display(), 332 | dest.display() 333 | ) 334 | }, 335 | )?; 336 | } 337 | Ok(()) 338 | } 339 | -------------------------------------------------------------------------------- /tests/bevy/.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | web-target -------------------------------------------------------------------------------- /tests/bevy/Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = [ 3 | "backend", 4 | "frontend", 5 | ] 6 | 7 | [profile.release] 8 | lto = true 9 | opt-level = 'z' 10 | codegen-units = 1 11 | 12 | [profile.release.build-override] 13 | opt-level = 'z' 14 | codegen-units = 1 -------------------------------------------------------------------------------- /tests/bevy/backend/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "backend" 3 | version = "0.0.0" 4 | edition = "2018" 5 | 6 | [dependencies] 7 | warp = "0.3" 8 | mime_guess = "2" 9 | 10 | [dependencies.tokio] 11 | version = "1" 12 | features = ["full"] 13 | 14 | [dependencies.rust-embed] 15 | version="5" 16 | features= ["compression", "interpolate-folder-path"] 17 | 18 | [build-dependencies.web-bundler] 19 | path = "../../.." 20 | 21 | # depend on the frontend project here not because we actually use it, 22 | # but because we want to trigger a rerun of the build.rs script if 23 | # anything in it changes. 24 | [build-dependencies.frontend] 25 | path = "../frontend" 26 | -------------------------------------------------------------------------------- /tests/bevy/backend/build.rs: -------------------------------------------------------------------------------- 1 | use std::{env, path::PathBuf, process}; 2 | use web_bundler::WebBundlerOpt; 3 | 4 | fn main() { 5 | let out_dir = PathBuf::from(env::var("OUT_DIR").expect("expected OUT_DIR to be set by Cargo")); 6 | 7 | let opt = WebBundlerOpt { 8 | src_dir: "../frontend".into(), 9 | dist_dir: out_dir.join("ui"), 10 | tmp_dir: out_dir.join("tmp"), 11 | base_url: Some("/".into()), 12 | wasm_version: env::var("CARGO_PKG_VERSION") 13 | .expect("expected CARGO_PKG_VERSION to be set by Cargo"), 14 | release: env::var("PROFILE").expect("expected PROFILE to be set by Cargo") != "debug", 15 | workspace_root: "..".into(), 16 | additional_watch_dirs: Vec::new(), 17 | }; 18 | 19 | if let Err(why) = web_bundler::run(opt) { 20 | println!("Failed to build frontend. Error: {}", why); 21 | process::exit(1); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /tests/bevy/backend/src/main.rs: -------------------------------------------------------------------------------- 1 | use rust_embed::RustEmbed; 2 | use warp::{filters::BoxedFilter, http::header::HeaderValue, path::Tail, reply::Response, Filter}; 3 | 4 | #[tokio::main] 5 | async fn main() { 6 | let routes = warp::path!("api" / ..) 7 | .and(warp::path::tail()) 8 | .map(|_| "Please pretend there's an API here.") 9 | .or(ui_routes()); 10 | 11 | warp::serve(routes).bind(([127, 0, 0, 1], 3030)).await; 12 | } 13 | 14 | #[derive(RustEmbed)] 15 | #[folder = "$OUT_DIR/ui"] 16 | struct PortalWebAssets; 17 | 18 | pub fn ui_routes() -> BoxedFilter<(impl warp::Reply,)> { 19 | let static_files = warp::get() 20 | .and(warp::path::tail()) 21 | .and_then(|path: Tail| async move { serve(path.as_str()).await }) 22 | .boxed(); 23 | 24 | let spa_mode_index = warp::get() 25 | .and(warp::path::tail()) 26 | .and_then(|path: Tail| async move { 27 | let first_path_segment = path.as_str().split('/').next(); 28 | let last_path_segment = path.as_str().split('/').last(); 29 | let is_api_path = first_path_segment == Some("api"); 30 | let is_index_html = last_path_segment == Some("index.html"); 31 | let is_file_like_path = last_path_segment 32 | .map(|segment| segment.contains('.')) 33 | .unwrap_or(false); 34 | 35 | if !is_api_path && (is_index_html || !is_file_like_path) { 36 | serve("index.html").await 37 | } else { 38 | Err(warp::reject::not_found()) 39 | } 40 | }) 41 | .boxed(); 42 | 43 | // Order is important here. Serve a file if it exists, then fall back to index.html as a default. 44 | static_files.or(spa_mode_index).boxed() 45 | } 46 | 47 | async fn serve(path: &str) -> Result { 48 | if let Some(asset) = PortalWebAssets::get(path) { 49 | let mime = mime_guess::from_path(path).first_or_octet_stream(); 50 | 51 | let mut res = Response::new(asset.into()); 52 | res.headers_mut().insert( 53 | "content-type", 54 | HeaderValue::from_str(mime.as_ref()).unwrap(), 55 | ); 56 | Ok(res) 57 | } else { 58 | Err(warp::reject::not_found()) 59 | } 60 | } 61 | 62 | #[cfg(test)] 63 | mod test { 64 | use super::*; 65 | use warp::http::status::StatusCode; 66 | 67 | #[tokio::test] 68 | async fn test_html() { 69 | let filter = ui_routes(); 70 | let response = warp::test::request().path("/").reply(&filter).await; 71 | 72 | assert_eq!(response.status(), StatusCode::OK); 73 | 74 | let response_body: String = String::from_utf8(response.body().to_vec()).unwrap(); 75 | 76 | assert!(response_body.contains("Bevy Example")); 77 | assert!(response_body.contains("