use super::*;
fn escape_bundle_html(raw: &str) -> String {
let mut out: String = String::with_capacity(raw.len());
for ch in raw.chars() {
match ch {
'&' => out.push_str(BUNDLE_ESC_AMP),
'<' => out.push_str(BUNDLE_ESC_LT),
'>' => out.push_str(BUNDLE_ESC_GT),
'"' => out.push_str(BUNDLE_ESC_QUOT),
_ => out.push(ch),
}
}
out
}
fn toml_path_string(path: &Path) -> String {
path.display()
.to_string()
.replace('\\', "\\\\")
.replace('"', "\\\"")
}
fn render_wrapper_cargo_toml(manifest_dir: &Path) -> String {
let pkg_ver: &str = env!("CARGO_PKG_VERSION");
let has_local_crate: bool = manifest_dir.join(BUNDLE_CARGO_TOML).is_file();
let workspace_root: Option<&Path> = manifest_dir.parent().filter(|parent: &&Path| {
parent.join(BUNDLE_CARGO_TOML).is_file()
&& parent
.join(BUNDLE_DIR_CORE)
.join(BUNDLE_CARGO_TOML)
.is_file()
&& parent.join(BUNDLE_DIR_UI).join(BUNDLE_CARGO_TOML).is_file()
});
let mut toml: String = String::with_capacity(1024);
let _: fmt::Result = writeln!(toml, "[workspace]\n");
let _: fmt::Result = writeln!(toml, "[package]");
let _: fmt::Result = writeln!(toml, "name = \"{BUNDLE_CRATE_NAME}\"");
let _: fmt::Result = writeln!(toml, "version = \"{pkg_ver}\"");
let _: fmt::Result = writeln!(toml, "edition = \"2024\"\n");
let _: fmt::Result = writeln!(toml, "[lib]");
let _: fmt::Result = writeln!(toml, "crate-type = [\"cdylib\"]\n");
let _: fmt::Result = writeln!(toml, "[dependencies]");
if has_local_crate {
let docs_path: String = toml_path_string(manifest_dir);
let _: fmt::Result = writeln!(toml, "euv-docs = {{ path = \"{docs_path}\" }}");
} else {
let _: fmt::Result = writeln!(toml, "euv-docs = \"={pkg_ver}\"");
}
let _: fmt::Result = writeln!(toml, "wasm-bindgen = \"{BUNDLE_WASM_BINDGEN_VER}\"\n");
if let Some(ws_root) = workspace_root {
let root_p: String = toml_path_string(ws_root);
let core_p: String = toml_path_string(&ws_root.join(BUNDLE_DIR_CORE));
let macros_p: String = toml_path_string(&ws_root.join(BUNDLE_DIR_MACROS));
let ui_p: String = toml_path_string(&ws_root.join(BUNDLE_DIR_UI));
let docs_p: String = toml_path_string(manifest_dir);
let _: fmt::Result = writeln!(toml, "[patch.crates-io]");
let _: fmt::Result = writeln!(toml, "euv = {{ path = \"{root_p}\" }}");
let _: fmt::Result = writeln!(toml, "euv-core = {{ path = \"{core_p}\" }}");
let _: fmt::Result = writeln!(toml, "euv-macros = {{ path = \"{macros_p}\" }}");
let _: fmt::Result = writeln!(toml, "euv-ui = {{ path = \"{ui_p}\" }}");
let _: fmt::Result = writeln!(toml, "euv-docs = {{ path = \"{docs_p}\" }}\n");
}
let _: fmt::Result = writeln!(toml, "[profile.release]");
let _: fmt::Result = writeln!(toml, "opt-level = \"z\"");
let _: fmt::Result = writeln!(toml, "lto = true");
let _: fmt::Result = writeln!(toml, "codegen-units = 1");
let _: fmt::Result = writeln!(toml, "panic = \"abort\"");
let _: fmt::Result = writeln!(toml, "strip = \"debuginfo\"\n");
let _: fmt::Result = writeln!(toml, "[package.metadata.wasm-pack.profile.release]");
let _: fmt::Result = writeln!(toml, "wasm-opt = false");
toml
}
fn is_forbidden_asset_file(path: &Path) -> bool {
let lower: String = path
.file_name()
.map(|s: &OsStr| s.to_string_lossy().to_ascii_lowercase())
.unwrap_or_default();
lower.ends_with(BUNDLE_JS_EXT)
|| lower.ends_with(BUNDLE_MJS_EXT)
|| lower.ends_with(BUNDLE_CSS_EXT)
|| BUNDLE_SKIP_FILES
.iter()
.any(|skip: &&str| lower.eq_ignore_ascii_case(skip))
}
fn copy_public_tree_real(src: &Path, dst: &Path, is_top_level: bool) -> io::Result<()> {
fs::create_dir_all(dst)?;
for entry_res in fs::read_dir(src)? {
let entry: DirEntry = entry_res?;
let file_name: OsString = entry.file_name();
let name_str: Cow<'_, str> = file_name.to_string_lossy();
if name_str.starts_with('.') {
continue;
}
let path: PathBuf = entry.path();
if path.is_dir() {
if is_top_level
&& BUNDLE_FORBIDDEN_DIRS
.iter()
.any(|f: &&str| name_str.eq_ignore_ascii_case(f))
{
continue;
}
copy_public_tree_real(&path, &dst.join(&file_name), false)?;
} else if path.is_file() && !is_forbidden_asset_file(&path) {
let target: PathBuf = dst.join(&file_name);
let resolved_src: PathBuf = fs::canonicalize(&path).unwrap_or(path);
let _: u64 = fs::copy(&resolved_src, &target)?;
}
}
Ok(())
}
fn copy_site_public_assets(src_dir: &Path, out_dir: &Path) -> io::Result<()> {
let direct_public: PathBuf = src_dir.join(BUNDLE_PUBLIC_DIR);
if direct_public.is_dir() {
return copy_public_tree_real(&direct_public, out_dir, true);
}
if let Some(parent) = src_dir.parent() {
let parent_public: PathBuf = parent.join(BUNDLE_PUBLIC_DIR);
if parent_public.is_dir() {
return copy_public_tree_real(&parent_public, out_dir, true);
}
}
Ok(())
}
pub fn transform_wasm_glue_inline(raw_js: &str, wasm_file: &str) -> String {
let single_pat: String = format!("new URL('{wasm_file}', import.meta.url)");
let double_pat: String = format!("new URL(\"{wasm_file}\", import.meta.url)");
let target_ref: String = format!("'./pkg/{wasm_file}'");
let rewritten: String = raw_js
.replace(&single_pat, &target_ref)
.replace(&double_pat, &target_ref);
let mut out: String = String::with_capacity(rewritten.len());
for line in rewritten.lines() {
let trimmed: &str = line.trim_start();
if trimmed.starts_with(BUNDLE_EXPORT_BRACE) || trimmed.starts_with(BUNDLE_EXPORT_DEFAULT) {
continue;
}
if let Some(rest) = line.strip_prefix(BUNDLE_EXPORT_PREFIX) {
out.push_str(rest);
} else {
out.push_str(line);
}
out.push('\n');
}
out
}
#[must_use]
pub fn render_wasm_locale_shell_html(
lang: &str,
title: &str,
description: &str,
inline_glue: &str,
wasm_file: &str,
) -> String {
let safe_title: String = escape_bundle_html(title);
let mut html: String = String::with_capacity(
inline_glue.len()
+ safe_title.len() * 2
+ description.len()
+ EUV_BRAND_LOGO_DATA_URI.len() * 3
+ 4096,
);
html.push_str(BUNDLE_HTML_DOCTYPE_OPEN);
html.push_str(&escape_bundle_html(lang));
html.push_str(BUNDLE_HTML_HEAD_MID);
html.push_str(&escape_bundle_html(description));
html.push_str(BUNDLE_HTML_DESC_END);
html.push_str(EUV_BRAND_LOGO_DATA_URI);
html.push_str(BUNDLE_HTML_ICON_MID);
html.push_str(EUV_BRAND_LOGO_DATA_URI);
html.push_str(BUNDLE_HTML_TITLE_OPEN);
html.push_str(&safe_title);
html.push_str(BUNDLE_HTML_STYLE_AND_BODY);
html.push_str(EUV_BRAND_LOGO_DATA_URI);
html.push_str(BUNDLE_HTML_LOGO_END);
html.push_str(&safe_title);
html.push_str(BUNDLE_HTML_LOADER_END);
html.push_str(inline_glue);
html.push_str(BUNDLE_HTML_BOOT_PREFIX);
html.push_str(wasm_file);
html.push_str(BUNDLE_HTML_BOOT_SUFFIX);
html
}
fn select_locales(unique: &[DocLocaleConfig], filter: Option<&str>) -> Vec<DocLocaleConfig> {
let Some(raw_filter) = filter else {
return unique.to_vec();
};
let needle: String = raw_filter.trim().trim_matches('/').to_ascii_lowercase();
unique
.iter()
.filter(|loc: &&DocLocaleConfig| {
loc.get_dir().trim().eq_ignore_ascii_case(&needle)
|| loc
.get_prefix()
.trim_matches('/')
.eq_ignore_ascii_case(&needle)
|| loc.get_lang().trim().eq_ignore_ascii_case(&needle)
|| loc
.get_label()
.trim()
.eq_ignore_ascii_case(raw_filter.trim())
})
.cloned()
.collect()
}
fn compile_locale_wasm_bundle(
site: &DocSite,
locale: &DocLocaleConfig,
locale_out: &Path,
builder_dir: &Path,
shared_target_dir: &Path,
release: bool,
) -> io::Result<()> {
let src_dir: PathBuf = builder_dir.join(BUNDLE_SRC_DIR);
fs::create_dir_all(&src_dir)?;
let packed: PackedSiteBundle =
pack_site_bundle(site).map_err(|err: DocsCodecError| Error::other(err.to_string()))?;
fs::write(
src_dir.join(BUNDLE_SHELL_JSON_FILE),
packed.get_shell_json(),
)?;
fs::write(
src_dir.join(BUNDLE_BODIES_BIN_FILE),
packed.get_compressed_bodies(),
)?;
let safe_dir: String = slugify(locale.get_dir());
let suffix: &str = if safe_dir.is_empty() {
BUNDLE_DEFAULT_LOCALE_SUFFIX
} else {
safe_dir.as_str()
};
let bundle_name: String = format!("{BUNDLE_NAME_PREFIX}{suffix}");
let pkg_dir: PathBuf = locale_out.join(BUNDLE_PKG_DIR);
fs::create_dir_all(&pkg_dir)?;
let mut cmd: Command = Command::new(BUNDLE_WASM_PACK_BIN);
let _: &mut Command = cmd
.current_dir(builder_dir)
.env(BUNDLE_ENV_TARGET_DIR, shared_target_dir)
.env_remove(BUNDLE_ENV_RUSTC_WRAPPER)
.arg(BUNDLE_ARG_BUILD)
.arg(BUNDLE_ARG_TARGET)
.arg(BUNDLE_ARG_WEB)
.arg(BUNDLE_ARG_NO_TS)
.arg(if release {
DOCS_FLAG_RELEASE
} else {
BUNDLE_ARG_DEV
})
.arg(BUNDLE_ARG_OUT_DIR)
.arg(&pkg_dir)
.arg(BUNDLE_ARG_OUT_NAME)
.arg(&bundle_name);
let status: ExitStatus = cmd
.status()
.map_err(|err: Error| Error::other(format!("{BUNDLE_ERR_WASM_PACK}: {err}")))?;
if !status.success() {
return Err(Error::other(format!(
"{BUNDLE_ERR_WASM_PACK} (locale={} status={status})",
locale.get_dir()
)));
}
let wasm_file: String = format!("{bundle_name}{BUNDLE_BG_WASM_SUFFIX}");
let js_path: PathBuf = pkg_dir.join(format!("{bundle_name}{BUNDLE_JS_EXT}"));
let raw_js: String = fs::read_to_string(&js_path)?;
let inline_glue: String = transform_wasm_glue_inline(&raw_js, &wasm_file);
let html: String = render_wasm_locale_shell_html(
site.resolved_lang(),
site.get_title(),
site.get_tagline(),
&inline_glue,
&wasm_file,
);
fs::write(locale_out.join(BUNDLE_INDEX_HTML), &html)?;
fs::write(locale_out.join(BUNDLE_NOT_FOUND_HTML), &html)?;
for entry_res in fs::read_dir(&pkg_dir)? {
let entry: DirEntry = entry_res?;
let path: PathBuf = entry.path();
if path.is_file()
&& path
.file_name()
.and_then(|s: &OsStr| s.to_str())
.is_none_or(|name: &str| name != wasm_file)
{
fs::remove_file(&path)?;
}
}
Ok(())
}
pub fn build_multilocale_wasm_site(
src_dir: &Path,
out_dir: &Path,
release: bool,
single_locale: Option<&str>,
) -> io::Result<GeneratedSiteReport> {
let cfg: DocSiteConfig = load_site_config(src_dir)
.filter(|c: &DocSiteConfig| !c.get_locales().is_empty())
.ok_or_else(|| Error::new(ErrorKind::NotFound, BUNDLE_ERR_NO_LOCALES))?;
let unique: Vec<DocLocaleConfig> = unique_locales(cfg.get_locales());
let targets: Vec<DocLocaleConfig> = select_locales(&unique, single_locale);
if targets.is_empty() {
return Err(Error::new(
ErrorKind::InvalidInput,
BUNDLE_ERR_NO_MATCHING_LOCALE,
));
}
fs::create_dir_all(out_dir)?;
copy_site_public_assets(src_dir, out_dir)?;
let abs_out: PathBuf = fs::canonicalize(out_dir).unwrap_or_else(|_| out_dir.to_path_buf());
let temp_root: PathBuf = env::temp_dir();
let builder_dir: PathBuf = temp_root.join(BUNDLE_BUILDER_DIR);
let shared_target_dir: PathBuf = temp_root.join(BUNDLE_TARGET_DIR);
fs::create_dir_all(builder_dir.join(BUNDLE_SRC_DIR))?;
let manifest_dir: PathBuf = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let cargo_toml: String = render_wrapper_cargo_toml(&manifest_dir);
let cargo_toml_path: PathBuf = builder_dir.join(BUNDLE_CARGO_TOML);
if fs::read_to_string(&cargo_toml_path).ok().as_deref() != Some(cargo_toml.as_str()) {
fs::write(&cargo_toml_path, &cargo_toml)?;
}
let lib_rs_path: PathBuf = builder_dir.join(BUNDLE_SRC_DIR).join(BUNDLE_LIB_RS);
if fs::read_to_string(&lib_rs_path).ok().as_deref() != Some(BUNDLE_WRAPPER_LIB_RS) {
fs::write(&lib_rs_path, BUNDLE_WRAPPER_LIB_RS)?;
}
let mut total_pages: usize = 0;
for (idx, locale) in targets.iter().enumerate() {
let is_root_locale: bool =
locale.get_prefix().trim() == "/" || (single_locale.is_some() && idx == 0);
let locale_out: PathBuf = if is_root_locale {
abs_out.clone()
} else {
let sub: &str = locale.get_dir().trim().trim_matches('/');
abs_out.join(sub)
};
let site: DocSite = load_locale_site(src_dir, &cfg, locale, Some(&abs_out))?;
total_pages += site.get_pages().len();
compile_locale_wasm_bundle(
&site,
locale,
&locale_out,
&builder_dir,
&shared_target_dir,
release,
)?;
}
let generated_at: String = Utc::now().to_rfc3339();
Ok(GeneratedSiteReport::new(
total_pages,
generated_at,
out_dir.join(BUNDLE_INDEX_HTML).display().to_string(),
))
}