1use super::*;
2
3fn 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
26fn toml_path_string(path: &Path) -> String {
36 path.display()
37 .to_string()
38 .replace('\\', "\\\\")
39 .replace('"', "\\\"")
40}
41
42fn 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, "panic = \"abort\"");
96 let _: fmt::Result = writeln!(toml, "strip = \"debuginfo\"\n");
97 let _: fmt::Result = writeln!(toml, "[package.metadata.wasm-pack.profile.release]");
98 let _: fmt::Result = writeln!(toml, "wasm-opt = false");
99 toml
100}
101
102fn is_forbidden_asset_file(path: &Path) -> bool {
112 let lower: String = path
113 .file_name()
114 .map(|s: &OsStr| s.to_string_lossy().to_ascii_lowercase())
115 .unwrap_or_default();
116 lower.ends_with(BUNDLE_JS_EXT)
117 || lower.ends_with(BUNDLE_MJS_EXT)
118 || lower.ends_with(BUNDLE_CSS_EXT)
119 || BUNDLE_SKIP_FILES
120 .iter()
121 .any(|skip: &&str| lower.eq_ignore_ascii_case(skip))
122}
123
124fn copy_public_tree_real(src: &Path, dst: &Path, is_top_level: bool) -> io::Result<()> {
136 fs::create_dir_all(dst)?;
137 for entry_res in fs::read_dir(src)? {
138 let entry: DirEntry = entry_res?;
139 let file_name: OsString = entry.file_name();
140 let name_str: Cow<'_, str> = file_name.to_string_lossy();
141 if name_str.starts_with('.') {
142 continue;
143 }
144 let path: PathBuf = entry.path();
145 if path.is_dir() {
146 if is_top_level
147 && BUNDLE_FORBIDDEN_DIRS
148 .iter()
149 .any(|f: &&str| name_str.eq_ignore_ascii_case(f))
150 {
151 continue;
152 }
153 copy_public_tree_real(&path, &dst.join(&file_name), false)?;
154 } else if path.is_file() && !is_forbidden_asset_file(&path) {
155 let target: PathBuf = dst.join(&file_name);
156 let resolved_src: PathBuf = fs::canonicalize(&path).unwrap_or(path);
157 let _: u64 = fs::copy(&resolved_src, &target)?;
158 }
159 }
160 Ok(())
161}
162
163fn copy_site_public_assets(src_dir: &Path, out_dir: &Path) -> io::Result<()> {
174 let direct_public: PathBuf = src_dir.join(BUNDLE_PUBLIC_DIR);
175 if direct_public.is_dir() {
176 return copy_public_tree_real(&direct_public, out_dir, true);
177 }
178 if let Some(parent) = src_dir.parent() {
179 let parent_public: PathBuf = parent.join(BUNDLE_PUBLIC_DIR);
180 if parent_public.is_dir() {
181 return copy_public_tree_real(&parent_public, out_dir, true);
182 }
183 }
184 Ok(())
185}
186
187pub fn transform_wasm_glue_inline(raw_js: &str, wasm_file: &str) -> String {
198 let single_pat: String = format!("new URL('{wasm_file}', import.meta.url)");
199 let double_pat: String = format!("new URL(\"{wasm_file}\", import.meta.url)");
200 let target_ref: String = format!("'./pkg/{wasm_file}'");
201 let rewritten: String = raw_js
202 .replace(&single_pat, &target_ref)
203 .replace(&double_pat, &target_ref);
204 let mut out: String = String::with_capacity(rewritten.len());
205 for line in rewritten.lines() {
206 let trimmed: &str = line.trim_start();
207 if trimmed.starts_with(BUNDLE_EXPORT_BRACE) || trimmed.starts_with(BUNDLE_EXPORT_DEFAULT) {
208 continue;
209 }
210 if let Some(rest) = line.strip_prefix(BUNDLE_EXPORT_PREFIX) {
211 out.push_str(rest);
212 } else {
213 out.push_str(line);
214 }
215 out.push('\n');
216 }
217 out
218}
219
220#[must_use]
234pub fn render_wasm_locale_shell_html(
235 lang: &str,
236 title: &str,
237 description: &str,
238 inline_glue: &str,
239 wasm_file: &str,
240) -> String {
241 let mut html: String =
242 String::with_capacity(inline_glue.len() + title.len() + description.len() + 1024);
243 html.push_str(BUNDLE_HTML_DOCTYPE_OPEN);
244 html.push_str(&escape_bundle_html(lang));
245 html.push_str(BUNDLE_HTML_HEAD_MID);
246 html.push_str(&escape_bundle_html(description));
247 html.push_str(BUNDLE_HTML_DESC_END);
248 html.push_str(&escape_bundle_html(title));
249 html.push_str(BUNDLE_HTML_STYLE_AND_BODY);
250 html.push_str(inline_glue);
251 html.push_str(BUNDLE_HTML_BOOT_PREFIX);
252 html.push_str(wasm_file);
253 html.push_str(BUNDLE_HTML_BOOT_SUFFIX);
254 html
255}
256
257fn select_locales(unique: &[DocLocaleConfig], filter: Option<&str>) -> Vec<DocLocaleConfig> {
268 let Some(raw_filter) = filter else {
269 return unique.to_vec();
270 };
271 let needle: String = raw_filter.trim().trim_matches('/').to_ascii_lowercase();
272 unique
273 .iter()
274 .filter(|loc: &&DocLocaleConfig| {
275 loc.get_dir().trim().eq_ignore_ascii_case(&needle)
276 || loc
277 .get_prefix()
278 .trim_matches('/')
279 .eq_ignore_ascii_case(&needle)
280 || loc.get_lang().trim().eq_ignore_ascii_case(&needle)
281 || loc
282 .get_label()
283 .trim()
284 .eq_ignore_ascii_case(raw_filter.trim())
285 })
286 .cloned()
287 .collect()
288}
289
290fn compile_locale_wasm_bundle(
305 site: &DocSite,
306 locale: &DocLocaleConfig,
307 locale_out: &Path,
308 builder_dir: &Path,
309 shared_target_dir: &Path,
310 release: bool,
311) -> io::Result<()> {
312 let src_dir: PathBuf = builder_dir.join(BUNDLE_SRC_DIR);
313 fs::create_dir_all(&src_dir)?;
314 let packed: PackedSiteBundle =
315 pack_site_bundle(site).map_err(|err: DocsCodecError| Error::other(err.to_string()))?;
316 fs::write(
317 src_dir.join(BUNDLE_SHELL_JSON_FILE),
318 packed.get_shell_json(),
319 )?;
320 fs::write(
321 src_dir.join(BUNDLE_BODIES_BIN_FILE),
322 packed.get_compressed_bodies(),
323 )?;
324 let safe_dir: String = slugify(locale.get_dir());
325 let suffix: &str = if safe_dir.is_empty() {
326 BUNDLE_DEFAULT_LOCALE_SUFFIX
327 } else {
328 safe_dir.as_str()
329 };
330 let bundle_name: String = format!("{BUNDLE_NAME_PREFIX}{suffix}");
331 let pkg_dir: PathBuf = locale_out.join(BUNDLE_PKG_DIR);
332 fs::create_dir_all(&pkg_dir)?;
333 let mut cmd: Command = Command::new(BUNDLE_WASM_PACK_BIN);
334 let _: &mut Command = cmd
335 .current_dir(builder_dir)
336 .env(BUNDLE_ENV_TARGET_DIR, shared_target_dir)
337 .env_remove(BUNDLE_ENV_RUSTC_WRAPPER)
338 .arg(BUNDLE_ARG_BUILD)
339 .arg(BUNDLE_ARG_TARGET)
340 .arg(BUNDLE_ARG_WEB)
341 .arg(BUNDLE_ARG_NO_TS)
342 .arg(if release {
343 DOCS_FLAG_RELEASE
344 } else {
345 BUNDLE_ARG_DEV
346 })
347 .arg(BUNDLE_ARG_OUT_DIR)
348 .arg(&pkg_dir)
349 .arg(BUNDLE_ARG_OUT_NAME)
350 .arg(&bundle_name);
351 let status: ExitStatus = cmd
352 .status()
353 .map_err(|err: Error| Error::other(format!("{BUNDLE_ERR_WASM_PACK}: {err}")))?;
354 if !status.success() {
355 return Err(Error::other(format!(
356 "{BUNDLE_ERR_WASM_PACK} (locale={} status={status})",
357 locale.get_dir()
358 )));
359 }
360 let wasm_file: String = format!("{bundle_name}{BUNDLE_BG_WASM_SUFFIX}");
361 let js_path: PathBuf = pkg_dir.join(format!("{bundle_name}{BUNDLE_JS_EXT}"));
362 let raw_js: String = fs::read_to_string(&js_path)?;
363 let inline_glue: String = transform_wasm_glue_inline(&raw_js, &wasm_file);
364 let html: String = render_wasm_locale_shell_html(
365 site.resolved_lang(),
366 site.get_title(),
367 site.get_tagline(),
368 &inline_glue,
369 &wasm_file,
370 );
371 fs::write(locale_out.join(BUNDLE_INDEX_HTML), &html)?;
372 fs::write(locale_out.join(BUNDLE_NOT_FOUND_HTML), &html)?;
373 for entry_res in fs::read_dir(&pkg_dir)? {
374 let entry: DirEntry = entry_res?;
375 let path: PathBuf = entry.path();
376 if path.is_file()
377 && path
378 .file_name()
379 .and_then(|s: &OsStr| s.to_str())
380 .is_none_or(|name: &str| name != wasm_file)
381 {
382 fs::remove_file(&path)?;
383 }
384 }
385 Ok(())
386}
387
388pub fn build_multilocale_wasm_site(
401 src_dir: &Path,
402 out_dir: &Path,
403 release: bool,
404 single_locale: Option<&str>,
405) -> io::Result<GeneratedSiteReport> {
406 let cfg: DocSiteConfig = load_site_config(src_dir)
407 .filter(|c: &DocSiteConfig| !c.get_locales().is_empty())
408 .ok_or_else(|| Error::new(ErrorKind::NotFound, BUNDLE_ERR_NO_LOCALES))?;
409 let unique: Vec<DocLocaleConfig> = unique_locales(cfg.get_locales());
410 let targets: Vec<DocLocaleConfig> = select_locales(&unique, single_locale);
411 if targets.is_empty() {
412 return Err(Error::new(
413 ErrorKind::InvalidInput,
414 BUNDLE_ERR_NO_MATCHING_LOCALE,
415 ));
416 }
417 fs::create_dir_all(out_dir)?;
418 copy_site_public_assets(src_dir, out_dir)?;
419 let abs_out: PathBuf = fs::canonicalize(out_dir).unwrap_or_else(|_| out_dir.to_path_buf());
420 let temp_root: PathBuf = env::temp_dir();
421 let builder_dir: PathBuf = temp_root.join(BUNDLE_BUILDER_DIR);
422 let shared_target_dir: PathBuf = temp_root.join(BUNDLE_TARGET_DIR);
423 fs::create_dir_all(builder_dir.join(BUNDLE_SRC_DIR))?;
424 let manifest_dir: PathBuf = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
425 let cargo_toml: String = render_wrapper_cargo_toml(&manifest_dir);
426 let cargo_toml_path: PathBuf = builder_dir.join(BUNDLE_CARGO_TOML);
427 if fs::read_to_string(&cargo_toml_path).ok().as_deref() != Some(cargo_toml.as_str()) {
428 fs::write(&cargo_toml_path, &cargo_toml)?;
429 }
430 let lib_rs_path: PathBuf = builder_dir.join(BUNDLE_SRC_DIR).join(BUNDLE_LIB_RS);
431 if fs::read_to_string(&lib_rs_path).ok().as_deref() != Some(BUNDLE_WRAPPER_LIB_RS) {
432 fs::write(&lib_rs_path, BUNDLE_WRAPPER_LIB_RS)?;
433 }
434 let mut total_pages: usize = 0;
435 for (idx, locale) in targets.iter().enumerate() {
436 let is_root_locale: bool =
437 locale.get_prefix().trim() == "/" || (single_locale.is_some() && idx == 0);
438 let locale_out: PathBuf = if is_root_locale {
439 abs_out.clone()
440 } else {
441 let sub: &str = locale.get_dir().trim().trim_matches('/');
442 abs_out.join(sub)
443 };
444 let site: DocSite = load_locale_site(src_dir, &cfg, locale, Some(&abs_out))?;
445 total_pages += site.get_pages().len();
446 compile_locale_wasm_bundle(
447 &site,
448 locale,
449 &locale_out,
450 &builder_dir,
451 &shared_target_dir,
452 release,
453 )?;
454 }
455 let generated_at: String = Utc::now().to_rfc3339();
456 Ok(GeneratedSiteReport::new(
457 total_pages,
458 generated_at,
459 out_dir.join(BUNDLE_INDEX_HTML).display().to_string(),
460 ))
461}