Skip to main content

euv_docs/bundle/
fn.rs

1use super::*;
2
3/// Escapes minimal HTML attribute/text characters (`&`, `<`, `>`, `"`) for generated WASM shell HTML.
4///
5/// # Arguments
6///
7/// - `&str` - Raw UTF-8 string.
8///
9/// # Returns
10///
11/// - `String` - Escaped HTML-safe string.
12fn escape_bundle_html(raw: &str) -> String {
13    let mut out: String = String::with_capacity(raw.len());
14    for ch in raw.chars() {
15        match ch {
16            '&' => out.push_str(BUNDLE_ESC_AMP),
17            '<' => out.push_str(BUNDLE_ESC_LT),
18            '>' => out.push_str(BUNDLE_ESC_GT),
19            '"' => out.push_str(BUNDLE_ESC_QUOT),
20            _ => out.push(ch),
21        }
22    }
23    out
24}
25
26/// Escapes a filesystem path for inclusion inside a TOML double-quoted string literal.
27///
28/// # Arguments
29///
30/// - `&Path` - Filesystem path.
31///
32/// # Returns
33///
34/// - `String` - TOML-escaped path string.
35fn toml_path_string(path: &Path) -> String {
36    path.display()
37        .to_string()
38        .replace('\\', "\\\\")
39        .replace('"', "\\\"")
40}
41
42/// Generates the standalone wrapper crate `Cargo.toml` referencing the active `euv-docs` source or published crate version.
43///
44/// # Arguments
45///
46/// - `&Path` - Local `euv-docs` crate manifest directory resolved at compile time.
47///
48/// # Returns
49///
50/// - `String` - Complete standalone wrapper `Cargo.toml` contents.
51fn render_wrapper_cargo_toml(manifest_dir: &Path) -> String {
52    let pkg_ver: &str = env!("CARGO_PKG_VERSION");
53    let has_local_crate: bool = manifest_dir.join(BUNDLE_CARGO_TOML).is_file();
54    let workspace_root: Option<&Path> = manifest_dir.parent().filter(|parent: &&Path| {
55        parent.join(BUNDLE_CARGO_TOML).is_file()
56            && parent
57                .join(BUNDLE_DIR_CORE)
58                .join(BUNDLE_CARGO_TOML)
59                .is_file()
60            && parent.join(BUNDLE_DIR_UI).join(BUNDLE_CARGO_TOML).is_file()
61    });
62    let mut toml: String = String::with_capacity(1024);
63    let _: fmt::Result = writeln!(toml, "[workspace]\n");
64    let _: fmt::Result = writeln!(toml, "[package]");
65    let _: fmt::Result = writeln!(toml, "name = \"{BUNDLE_CRATE_NAME}\"");
66    let _: fmt::Result = writeln!(toml, "version = \"{pkg_ver}\"");
67    let _: fmt::Result = writeln!(toml, "edition = \"2024\"\n");
68    let _: fmt::Result = writeln!(toml, "[lib]");
69    let _: fmt::Result = writeln!(toml, "crate-type = [\"cdylib\"]\n");
70    let _: fmt::Result = writeln!(toml, "[dependencies]");
71    if has_local_crate {
72        let docs_path: String = toml_path_string(manifest_dir);
73        let _: fmt::Result = writeln!(toml, "euv-docs = {{ path = \"{docs_path}\" }}");
74    } else {
75        let _: fmt::Result = writeln!(toml, "euv-docs = \"={pkg_ver}\"");
76    }
77    let _: fmt::Result = writeln!(toml, "wasm-bindgen = \"{BUNDLE_WASM_BINDGEN_VER}\"\n");
78    if let Some(ws_root) = workspace_root {
79        let root_p: String = toml_path_string(ws_root);
80        let core_p: String = toml_path_string(&ws_root.join(BUNDLE_DIR_CORE));
81        let macros_p: String = toml_path_string(&ws_root.join(BUNDLE_DIR_MACROS));
82        let ui_p: String = toml_path_string(&ws_root.join(BUNDLE_DIR_UI));
83        let docs_p: String = toml_path_string(manifest_dir);
84        let _: fmt::Result = writeln!(toml, "[patch.crates-io]");
85        let _: fmt::Result = writeln!(toml, "euv = {{ path = \"{root_p}\" }}");
86        let _: fmt::Result = writeln!(toml, "euv-core = {{ path = \"{core_p}\" }}");
87        let _: fmt::Result = writeln!(toml, "euv-macros = {{ path = \"{macros_p}\" }}");
88        let _: fmt::Result = writeln!(toml, "euv-ui = {{ path = \"{ui_p}\" }}");
89        let _: fmt::Result = writeln!(toml, "euv-docs = {{ path = \"{docs_p}\" }}\n");
90    }
91    let _: fmt::Result = writeln!(toml, "[profile.release]");
92    let _: fmt::Result = writeln!(toml, "opt-level = \"z\"");
93    let _: fmt::Result = writeln!(toml, "lto = true");
94    let _: fmt::Result = writeln!(toml, "codegen-units = 1");
95    let _: fmt::Result = writeln!(toml, "strip = \"debuginfo\"\n");
96    let _: fmt::Result = writeln!(toml, "[package.metadata.wasm-pack.profile.release]");
97    let _: fmt::Result = writeln!(toml, "wasm-opt = false");
98    toml
99}
100
101/// Checks whether a filename carries a forbidden external script or stylesheet suffix (`.js`, `.mjs`, `.css`).
102///
103/// # Arguments
104///
105/// - `&Path` - Candidate file path.
106///
107/// # Returns
108///
109/// - `bool` - `true` when the file must be excluded from the zero-JS/zero-CSS artifact tree.
110fn is_forbidden_asset_file(path: &Path) -> bool {
111    let lower: String = path
112        .file_name()
113        .map(|s: &OsStr| s.to_string_lossy().to_ascii_lowercase())
114        .unwrap_or_default();
115    lower.ends_with(BUNDLE_JS_EXT)
116        || lower.ends_with(BUNDLE_MJS_EXT)
117        || lower.ends_with(BUNDLE_CSS_EXT)
118        || BUNDLE_SKIP_FILES
119            .iter()
120            .any(|skip: &&str| lower.eq_ignore_ascii_case(skip))
121}
122
123/// Recursively copies `src` into `dst`, dereferencing directory and file symlinks into real files while omitting forbidden script/CSS/font trees.
124///
125/// # Arguments
126///
127/// - `&Path` - Source directory (may be a symlink).
128/// - `&Path` - Destination directory.
129/// - `bool` - Whether this call is at the top level of `public/`.
130///
131/// # Returns
132///
133/// - `io::Result<()>` - Copy result.
134fn copy_public_tree_real(src: &Path, dst: &Path, is_top_level: bool) -> io::Result<()> {
135    fs::create_dir_all(dst)?;
136    for entry_res in fs::read_dir(src)? {
137        let entry: DirEntry = entry_res?;
138        let file_name: OsString = entry.file_name();
139        let name_str: Cow<'_, str> = file_name.to_string_lossy();
140        if name_str.starts_with('.') {
141            continue;
142        }
143        let path: PathBuf = entry.path();
144        if path.is_dir() {
145            if is_top_level
146                && BUNDLE_FORBIDDEN_DIRS
147                    .iter()
148                    .any(|f: &&str| name_str.eq_ignore_ascii_case(f))
149            {
150                continue;
151            }
152            copy_public_tree_real(&path, &dst.join(&file_name), false)?;
153        } else if path.is_file() && !is_forbidden_asset_file(&path) {
154            let target: PathBuf = dst.join(&file_name);
155            let resolved_src: PathBuf = fs::canonicalize(&path).unwrap_or(path);
156            let _: u64 = fs::copy(&resolved_src, &target)?;
157        }
158    }
159    Ok(())
160}
161
162/// Copies `<src_dir>/public/` (or fallback `<src_dir>/../public/`) into `out_dir/` as real non-symlink files.
163///
164/// # Arguments
165///
166/// - `&Path` - Documentation Markdown source directory.
167/// - `&Path` - Root build output directory.
168///
169/// # Returns
170///
171/// - `io::Result<()>` - Copy result.
172fn copy_site_public_assets(src_dir: &Path, out_dir: &Path) -> io::Result<()> {
173    let direct_public: PathBuf = src_dir.join(BUNDLE_PUBLIC_DIR);
174    if direct_public.is_dir() {
175        return copy_public_tree_real(&direct_public, out_dir, true);
176    }
177    if let Some(parent) = src_dir.parent() {
178        let parent_public: PathBuf = parent.join(BUNDLE_PUBLIC_DIR);
179        if parent_public.is_dir() {
180            return copy_public_tree_real(&parent_public, out_dir, true);
181        }
182    }
183    Ok(())
184}
185
186/// Strips ES module `export` statements from `wasm-bindgen`'s generated glue script and rewrites the `.wasm` URL to `./pkg/<wasm_file>`.
187///
188/// # Arguments
189///
190/// - `&str` - Raw `wasm-bindgen` web-target JS glue contents.
191/// - `&str` - Exact `<name>_bg.wasm` filename.
192///
193/// # Returns
194///
195/// - `String` - Clean inline ES module script ready to embed inside `<script type="module">`.
196pub fn transform_wasm_glue_inline(raw_js: &str, wasm_file: &str) -> String {
197    let single_pat: String = format!("new URL('{wasm_file}', import.meta.url)");
198    let double_pat: String = format!("new URL(\"{wasm_file}\", import.meta.url)");
199    let target_ref: String = format!("'./pkg/{wasm_file}'");
200    let rewritten: String = raw_js
201        .replace(&single_pat, &target_ref)
202        .replace(&double_pat, &target_ref);
203    let mut out: String = String::with_capacity(rewritten.len());
204    for line in rewritten.lines() {
205        let trimmed: &str = line.trim_start();
206        if trimmed.starts_with(BUNDLE_EXPORT_BRACE) || trimmed.starts_with(BUNDLE_EXPORT_DEFAULT) {
207            continue;
208        }
209        if let Some(rest) = line.strip_prefix(BUNDLE_EXPORT_PREFIX) {
210            out.push_str(rest);
211        } else {
212            out.push_str(line);
213        }
214        out.push('\n');
215    }
216    out
217}
218
219/// Renders the self-contained zero-JS-file, zero-CSS-file `index.html` / `404.html` shell for a single locale WASM bundle.
220///
221/// # Arguments
222///
223/// - `&str` - BCP 47 HTML language code (for example `"zh-CN"`, `"en-US"`).
224/// - `&str` - Localized site title.
225/// - `&str` - Localized site description meta content.
226/// - `&str` - Transformed inline `wasm-bindgen` loader script.
227/// - `&str` - Exact `<name>_bg.wasm` filename inside `./pkg/`.
228///
229/// # Returns
230///
231/// - `String` - Complete HTML document referencing `./pkg/<wasm_file>` with zero external `.js` or `.css` assets.
232#[must_use]
233pub fn render_wasm_locale_shell_html(
234    lang: &str,
235    title: &str,
236    description: &str,
237    inline_glue: &str,
238    wasm_file: &str,
239) -> String {
240    let mut html: String =
241        String::with_capacity(inline_glue.len() + title.len() + description.len() + 1024);
242    html.push_str(BUNDLE_HTML_DOCTYPE_OPEN);
243    html.push_str(&escape_bundle_html(lang));
244    html.push_str(BUNDLE_HTML_HEAD_MID);
245    html.push_str(&escape_bundle_html(description));
246    html.push_str(BUNDLE_HTML_DESC_END);
247    html.push_str(&escape_bundle_html(title));
248    html.push_str(BUNDLE_HTML_STYLE_AND_BODY);
249    html.push_str(inline_glue);
250    html.push_str(BUNDLE_HTML_BOOT_PREFIX);
251    html.push_str(wasm_file);
252    html.push_str(BUNDLE_HTML_BOOT_SUFFIX);
253    html
254}
255
256/// Selects unique locales matching an optional `--locale` filter (prefix, dir, lang, or label).
257///
258/// # Arguments
259///
260/// - `&[DocLocaleConfig]` - Deduplicated locale entries.
261/// - `Option<&str>` - Optional user filter string.
262///
263/// # Returns
264///
265/// - `Vec<DocLocaleConfig>` - Locales scheduled for compilation.
266fn select_locales(unique: &[DocLocaleConfig], filter: Option<&str>) -> Vec<DocLocaleConfig> {
267    let Some(raw_filter) = filter else {
268        return unique.to_vec();
269    };
270    let needle: String = raw_filter.trim().trim_matches('/').to_ascii_lowercase();
271    unique
272        .iter()
273        .filter(|loc: &&DocLocaleConfig| {
274            loc.get_dir().trim().eq_ignore_ascii_case(&needle)
275                || loc
276                    .get_prefix()
277                    .trim_matches('/')
278                    .eq_ignore_ascii_case(&needle)
279                || loc.get_lang().trim().eq_ignore_ascii_case(&needle)
280                || loc
281                    .get_label()
282                    .trim()
283                    .eq_ignore_ascii_case(raw_filter.trim())
284        })
285        .cloned()
286        .collect()
287}
288
289/// Compiles one locale `DocSite` into an independent zero-JS/zero-CSS `euv` + `euv-ui` WebAssembly bundle inside `locale_out`.
290///
291/// # Arguments
292///
293/// - `&DocSite` - Loaded documentation site for this locale.
294/// - `&DocLocaleConfig` - Active locale configuration.
295/// - `&Path` - Output directory for this locale (`<out>/` for root or `<out>/<dir>/`).
296/// - `&Path` - Shared wrapper crate working directory.
297/// - `&Path` - Shared `CARGO_TARGET_DIR` caching compiled `wasm32` dependencies across locales.
298/// - `bool` - When `true`, compiles with `wasm-pack --release`; otherwise `--dev`.
299///
300/// # Returns
301///
302/// - `io::Result<()>` - Build result.
303fn compile_locale_wasm_bundle(
304    site: &DocSite,
305    locale: &DocLocaleConfig,
306    locale_out: &Path,
307    builder_dir: &Path,
308    shared_target_dir: &Path,
309    release: bool,
310) -> io::Result<()> {
311    let src_dir: PathBuf = builder_dir.join(BUNDLE_SRC_DIR);
312    fs::create_dir_all(&src_dir)?;
313    let bundle_json: String =
314        to_string(site).map_err(|err: serde_json::Error| Error::other(err.to_string()))?;
315    fs::write(src_dir.join(BUNDLE_JSON_FILE), &bundle_json)?;
316    let safe_dir: String = slugify(locale.get_dir());
317    let suffix: &str = if safe_dir.is_empty() {
318        BUNDLE_DEFAULT_LOCALE_SUFFIX
319    } else {
320        safe_dir.as_str()
321    };
322    let bundle_name: String = format!("{BUNDLE_NAME_PREFIX}{suffix}");
323    let pkg_dir: PathBuf = locale_out.join(BUNDLE_PKG_DIR);
324    fs::create_dir_all(&pkg_dir)?;
325    let mut cmd: Command = Command::new(BUNDLE_WASM_PACK_BIN);
326    let _: &mut Command = cmd
327        .current_dir(builder_dir)
328        .env(BUNDLE_ENV_TARGET_DIR, shared_target_dir)
329        .env_remove(BUNDLE_ENV_RUSTC_WRAPPER)
330        .arg(BUNDLE_ARG_BUILD)
331        .arg(BUNDLE_ARG_TARGET)
332        .arg(BUNDLE_ARG_WEB)
333        .arg(BUNDLE_ARG_NO_TS)
334        .arg(if release {
335            DOCS_FLAG_RELEASE
336        } else {
337            BUNDLE_ARG_DEV
338        })
339        .arg(BUNDLE_ARG_OUT_DIR)
340        .arg(&pkg_dir)
341        .arg(BUNDLE_ARG_OUT_NAME)
342        .arg(&bundle_name);
343    let status: ExitStatus = cmd
344        .status()
345        .map_err(|err: Error| Error::other(format!("{BUNDLE_ERR_WASM_PACK}: {err}")))?;
346    if !status.success() {
347        return Err(Error::other(format!(
348            "{BUNDLE_ERR_WASM_PACK} (locale={} status={status})",
349            locale.get_dir()
350        )));
351    }
352    let wasm_file: String = format!("{bundle_name}{BUNDLE_BG_WASM_SUFFIX}");
353    let js_path: PathBuf = pkg_dir.join(format!("{bundle_name}{BUNDLE_JS_EXT}"));
354    let raw_js: String = fs::read_to_string(&js_path)?;
355    let inline_glue: String = transform_wasm_glue_inline(&raw_js, &wasm_file);
356    let html: String = render_wasm_locale_shell_html(
357        site.resolved_lang(),
358        site.get_title(),
359        site.get_tagline(),
360        &inline_glue,
361        &wasm_file,
362    );
363    fs::write(locale_out.join(BUNDLE_INDEX_HTML), &html)?;
364    fs::write(locale_out.join(BUNDLE_NOT_FOUND_HTML), &html)?;
365    for entry_res in fs::read_dir(&pkg_dir)? {
366        let entry: DirEntry = entry_res?;
367        let path: PathBuf = entry.path();
368        if path.is_file()
369            && path
370                .file_name()
371                .and_then(|s: &OsStr| s.to_str())
372                .is_none_or(|name: &str| name != wasm_file)
373        {
374            fs::remove_file(&path)?;
375        }
376    }
377    Ok(())
378}
379
380/// Builds a complete multi-locale zero-JS/zero-CSS `euv` + `euv-ui` WebAssembly documentation site into `out_dir`.
381///
382/// # Arguments
383///
384/// - `&Path` - Root Markdown source directory (e.g. `docs/`).
385/// - `&Path` - Destination artifact output directory.
386/// - `bool` - When `true`, builds optimized release WASM bundles (`--release`).
387/// - `Option<&str>` - Optional single-locale filter (`dir`, `prefix`, `lang`, or `label`).
388///
389/// # Returns
390///
391/// - `io::Result<GeneratedSiteReport>` - Summary of total built pages and output index path.
392pub fn build_multilocale_wasm_site(
393    src_dir: &Path,
394    out_dir: &Path,
395    release: bool,
396    single_locale: Option<&str>,
397) -> io::Result<GeneratedSiteReport> {
398    let cfg: DocSiteConfig = load_site_config(src_dir)
399        .filter(|c: &DocSiteConfig| !c.get_locales().is_empty())
400        .ok_or_else(|| Error::new(ErrorKind::NotFound, BUNDLE_ERR_NO_LOCALES))?;
401    let unique: Vec<DocLocaleConfig> = unique_locales(cfg.get_locales());
402    let targets: Vec<DocLocaleConfig> = select_locales(&unique, single_locale);
403    if targets.is_empty() {
404        return Err(Error::new(
405            ErrorKind::InvalidInput,
406            BUNDLE_ERR_NO_MATCHING_LOCALE,
407        ));
408    }
409    fs::create_dir_all(out_dir)?;
410    copy_site_public_assets(src_dir, out_dir)?;
411    let abs_out: PathBuf = fs::canonicalize(out_dir).unwrap_or_else(|_| out_dir.to_path_buf());
412    let temp_root: PathBuf = env::temp_dir();
413    let builder_dir: PathBuf = temp_root.join(BUNDLE_BUILDER_DIR);
414    let shared_target_dir: PathBuf = temp_root.join(BUNDLE_TARGET_DIR);
415    fs::create_dir_all(builder_dir.join(BUNDLE_SRC_DIR))?;
416    let manifest_dir: PathBuf = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
417    let cargo_toml: String = render_wrapper_cargo_toml(&manifest_dir);
418    let cargo_toml_path: PathBuf = builder_dir.join(BUNDLE_CARGO_TOML);
419    if fs::read_to_string(&cargo_toml_path).ok().as_deref() != Some(cargo_toml.as_str()) {
420        fs::write(&cargo_toml_path, &cargo_toml)?;
421    }
422    let lib_rs_path: PathBuf = builder_dir.join(BUNDLE_SRC_DIR).join(BUNDLE_LIB_RS);
423    if fs::read_to_string(&lib_rs_path).ok().as_deref() != Some(BUNDLE_WRAPPER_LIB_RS) {
424        fs::write(&lib_rs_path, BUNDLE_WRAPPER_LIB_RS)?;
425    }
426    let mut total_pages: usize = 0;
427    for (idx, locale) in targets.iter().enumerate() {
428        let is_root_locale: bool =
429            locale.get_prefix().trim() == "/" || (single_locale.is_some() && idx == 0);
430        let locale_out: PathBuf = if is_root_locale {
431            abs_out.clone()
432        } else {
433            let sub: &str = locale.get_dir().trim().trim_matches('/');
434            abs_out.join(sub)
435        };
436        let site: DocSite = load_locale_site(src_dir, &cfg, locale, Some(&abs_out))?;
437        total_pages += site.get_pages().len();
438        compile_locale_wasm_bundle(
439            &site,
440            locale,
441            &locale_out,
442            &builder_dir,
443            &shared_target_dir,
444            release,
445        )?;
446    }
447    let generated_at: String = Utc::now().to_rfc3339();
448    Ok(GeneratedSiteReport::new(
449        total_pages,
450        generated_at,
451        out_dir.join(BUNDLE_INDEX_HTML).display().to_string(),
452    ))
453}