1#![forbid(unsafe_code)]
2
3use std::collections::BTreeSet;
4use std::ffi::OsStr;
5use std::fs;
6use std::path::{Path, PathBuf};
7use std::process::Command;
8
9use anyhow::{Context, Result, anyhow};
10use clap::{ArgAction, Parser, ValueEnum};
11use regex::Regex;
12use semver::Version;
13use serde::Serialize;
14use serde_json::json;
15use tempfile::TempDir;
16use tracing::info;
17use walkdir::WalkDir;
18
19use crate::build;
20
21#[derive(Debug, Clone, ValueEnum)]
22pub enum GuiPackKind {
23 Layout,
24 Auth,
25 Feature,
26 Skin,
27 Telemetry,
28}
29
30#[derive(Debug, Clone, Parser)]
31pub struct Args {
32 #[arg(long = "pack-kind", value_enum)]
34 pub pack_kind: GuiPackKind,
35
36 #[arg(long = "id")]
38 pub pack_id: String,
39
40 #[arg(long = "version")]
42 pub version: String,
43
44 #[arg(long = "pack-manifest-kind", default_value = "application")]
46 pub pack_manifest_kind: String,
47
48 #[arg(long = "publisher", default_value = "greentic.gui")]
50 pub publisher: String,
51
52 #[arg(long)]
54 pub name: Option<String>,
55
56 #[arg(long = "repo-url", conflicts_with_all = ["dir", "assets_dir"])]
58 pub repo_url: Option<String>,
59
60 #[arg(long, requires = "repo_url", default_value = "main")]
62 pub branch: String,
63
64 #[arg(long, conflicts_with_all = ["repo_url", "assets_dir"])]
66 pub dir: Option<PathBuf>,
67
68 #[arg(long = "assets-dir", conflicts_with_all = ["repo_url", "dir"])]
70 pub assets_dir: Option<PathBuf>,
71
72 #[arg(long = "package-dir")]
74 pub package_dir: Option<PathBuf>,
75
76 #[arg(long = "install-cmd")]
78 pub install_cmd: Option<String>,
79
80 #[arg(long = "build-cmd")]
82 pub build_cmd: Option<String>,
83
84 #[arg(long = "build-dir")]
86 pub build_dir: Option<PathBuf>,
87
88 #[arg(long = "spa")]
90 pub spa: Option<bool>,
91
92 #[arg(long = "route", action = ArgAction::Append)]
94 pub routes: Vec<String>,
95
96 #[arg(long = "routes", value_name = "ROUTES")]
98 pub routes_flat: Option<String>,
99
100 #[arg(long = "out", alias = "output", value_name = "FILE")]
102 pub out: PathBuf,
103}
104
105struct ConvertOptions {
106 pack_kind: GuiPackKind,
107 pack_id: String,
108 version: Version,
109 pack_manifest_kind: String,
110 publisher: String,
111 name: Option<String>,
112 source: Source,
113 package_dir: Option<PathBuf>,
114 install_cmd: Option<String>,
115 build_cmd: Option<String>,
116 build_dir: Option<PathBuf>,
117 spa: Option<bool>,
118 routes: Vec<RouteOverride>,
119 out: PathBuf,
120}
121
122#[derive(Debug, Clone)]
123enum Source {
124 Repo { url: String, branch: String },
125 Dir(PathBuf),
126 AssetsDir(PathBuf),
127}
128
129#[derive(Debug, Clone)]
130struct RouteOverride {
131 path: String,
132 html: PathBuf,
133}
134
135#[derive(Debug, Serialize)]
136struct Summary {
137 pack_id: String,
138 version: String,
139 pack_kind: String,
140 gui_kind: String,
141 out: String,
142 routes: Vec<String>,
143 assets_copied: usize,
144}
145
146pub async fn handle(
147 args: Args,
148 json_out: bool,
149 runtime: &crate::runtime::RuntimeContext,
150) -> Result<()> {
151 let opts = ConvertOptions::try_from(args)?;
152 let staging = TempDir::new().context("failed to create staging dir")?;
153 let staging_root = staging.path();
154 let pack_root = staging_root
155 .canonicalize()
156 .context("failed to canonicalize staging dir")?;
157
158 let mut _clone_guard: Option<TempDir> = None;
159 let source_root = match &opts.source {
160 Source::Repo { url, branch } => {
161 runtime.require_online("git clone (packc gui loveable-convert --repo-url)")?;
162 let (temp, repo_dir) = clone_repo(url, branch)?;
163 let path = repo_dir
164 .canonicalize()
165 .context("failed to canonicalize cloned repo")?;
166 _clone_guard = Some(temp);
167 path
168 }
169 Source::Dir(p) => p.canonicalize().context("failed to canonicalize --dir")?,
170 Source::AssetsDir(p) => p
171 .canonicalize()
172 .context("failed to canonicalize --assets-dir")?,
173 };
174
175 let build_root = opts
176 .package_dir
177 .as_ref()
178 .map(|p| source_root.join(p))
179 .unwrap_or_else(|| source_root.clone());
180
181 let assets_dir = match opts.source {
182 Source::AssetsDir(_) => build_root,
183 _ => {
184 runtime.require_online("install/build GUI assets")?;
185 build_assets(&build_root, &opts)?
186 }
187 };
188
189 let assets_dir = assets_dir
190 .canonicalize()
191 .with_context(|| format!("failed to canonicalize assets dir {}", assets_dir.display()))?;
192
193 let staging_assets = staging_root.join("gui").join("assets");
194 let copied = copy_assets(&assets_dir, &staging_assets)?;
195
196 let gui_manifest = build_gui_manifest(&opts, &staging_assets)?;
197 write_gui_manifest(&pack_root.join("gui").join("manifest.json"), &gui_manifest)?;
198
199 write_pack_manifest(&opts, &pack_root, copied)?;
200
201 let build_opts = build::BuildOptions {
202 pack_dir: pack_root.clone(),
203 component_out: None,
204 manifest_out: pack_root.join("dist").join("manifest.cbor"),
205 sbom_out: None,
206 gtpack_out: Some(opts.out.clone()),
207 lock_path: pack_root.join("pack.lock.json"),
208 bundle: build::BundleMode::Cache,
209 dry_run: false,
210 secrets_req: None,
211 default_secret_scope: None,
212 allow_oci_tags: false,
213 require_component_manifests: false,
214 runtime: runtime.clone(),
215 skip_update: false,
216 };
217 build::run(&build_opts).await?;
218
219 if json_out {
220 let summary = Summary {
221 pack_id: opts.pack_id.clone(),
222 version: opts.version.to_string(),
223 pack_kind: opts.pack_manifest_kind.clone(),
224 gui_kind: gui_kind_string(&opts.pack_kind),
225 out: opts.out.display().to_string(),
226 routes: extract_route_strings(&gui_manifest),
227 assets_copied: copied,
228 };
229 println!("{}", serde_json::to_string_pretty(&summary)?);
230 } else {
231 info!(
232 pack_id = %opts.pack_id,
233 version = %opts.version,
234 gui_kind = gui_kind_string(&opts.pack_kind),
235 out = %opts.out.display(),
236 assets = copied,
237 "gui pack conversion complete"
238 );
239 }
240
241 Ok(())
242}
243
244impl TryFrom<Args> for ConvertOptions {
245 type Error = anyhow::Error;
246
247 fn try_from(args: Args) -> Result<Self> {
248 if args.assets_dir.is_some() && args.package_dir.is_some() {
249 return Err(anyhow!(
250 "--package-dir cannot be combined with --assets-dir (assets are already built)"
251 ));
252 }
253
254 let source = if let Some(url) = args.repo_url {
255 Source::Repo {
256 url,
257 branch: args.branch,
258 }
259 } else if let Some(dir) = args.dir {
260 Source::Dir(dir)
261 } else if let Some(assets) = args.assets_dir {
262 Source::AssetsDir(assets)
263 } else {
264 return Err(anyhow!(
265 "one of --repo-url, --dir, or --assets-dir must be provided"
266 ));
267 };
268
269 let routes = parse_routes(&args.routes, args.routes_flat.as_deref())?;
270 let version =
271 Version::parse(&args.version).context("invalid --version (expected semver)")?;
272 let out = if args.out.is_absolute() {
273 args.out
274 } else {
275 std::env::current_dir()
276 .context("failed to resolve current dir")?
277 .join(args.out)
278 };
279
280 Ok(Self {
281 pack_kind: args.pack_kind,
282 pack_id: args.pack_id,
283 version,
284 pack_manifest_kind: args.pack_manifest_kind.to_ascii_lowercase(),
285 publisher: args.publisher,
286 name: args.name,
287 source,
288 package_dir: args.package_dir,
289 install_cmd: args.install_cmd,
290 build_cmd: args.build_cmd,
291 build_dir: args.build_dir,
292 spa: args.spa,
293 routes,
294 out,
295 })
296 }
297}
298
299fn parse_routes(explicit: &[String], flat: Option<&str>) -> Result<Vec<RouteOverride>> {
300 let mut entries = Vec::new();
301
302 for raw in explicit {
303 entries.push(parse_route_entry(raw)?);
304 }
305
306 if let Some(flat_raw) = flat {
307 for part in flat_raw.split(',') {
308 if part.trim().is_empty() {
309 continue;
310 }
311 entries.push(parse_route_entry(part.trim())?);
312 }
313 }
314
315 Ok(entries)
316}
317
318fn parse_route_entry(raw: &str) -> Result<RouteOverride> {
319 let mut parts = raw.splitn(2, ':');
320 let path = parts
321 .next()
322 .ok_or_else(|| anyhow!("invalid route entry: {}", raw))?;
323 let html = parts
324 .next()
325 .ok_or_else(|| anyhow!("route entry must be path:html => {}", raw))?;
326
327 let path = path.trim().to_string();
328 if !path.starts_with('/') {
329 return Err(anyhow!("route path must start with '/': {}", path));
330 }
331
332 let html_path = PathBuf::from(html.trim());
333 if html_path.is_absolute() {
334 return Err(anyhow!(
335 "route html path must be relative to gui/assets: {}",
336 html
337 ));
338 }
339
340 Ok(RouteOverride {
341 path,
342 html: html_path,
343 })
344}
345
346fn clone_repo(url: &str, branch: &str) -> Result<(TempDir, PathBuf)> {
347 let temp = TempDir::new().context("failed to create temp dir for clone")?;
348 let target = temp.path().join("repo");
349
350 let status = Command::new("git")
351 .arg("clone")
352 .arg("--branch")
353 .arg(branch)
354 .arg("--depth")
355 .arg("1")
356 .arg(url)
357 .arg(&target)
358 .status()
359 .with_context(|| format!("failed to execute git clone for {}", url))?;
360
361 if !status.success() {
362 return Err(anyhow!("git clone failed with status {}", status));
363 }
364
365 Ok((temp, target))
366}
367
368fn build_assets(build_root: &Path, opts: &ConvertOptions) -> Result<PathBuf> {
369 let install_cmd = opts
370 .install_cmd
371 .clone()
372 .unwrap_or_else(|| default_install_command(build_root));
373 let build_cmd = opts
374 .build_cmd
375 .clone()
376 .unwrap_or_else(|| "npm run build".to_string());
377
378 run_shell(&install_cmd, build_root, "install dependencies")?;
379 run_shell(&build_cmd, build_root, "build GUI assets")?;
380
381 if let Some(dir) = &opts.build_dir {
382 return Ok(build_root.join(dir));
383 }
384
385 let dist = build_root.join("dist");
386 if dist.is_dir() {
387 return Ok(dist);
388 }
389
390 let build = build_root.join("build");
391 if build.is_dir() {
392 return Ok(build);
393 }
394
395 Err(anyhow!(
396 "unable to detect build output; specify --build-dir"
397 ))
398}
399
400fn default_install_command(root: &Path) -> String {
401 if root.join("pnpm-lock.yaml").exists() {
402 "pnpm install".to_string()
403 } else if root.join("yarn.lock").exists() {
404 "yarn install".to_string()
405 } else {
406 "npm install".to_string()
407 }
408}
409
410fn run_shell(cmd: &str, cwd: &Path, why: &str) -> Result<()> {
411 info!(command = %cmd, cwd = %cwd.display(), "running {}", why);
412 let status = Command::new("sh")
413 .arg("-c")
414 .arg(cmd)
415 .current_dir(cwd)
416 .status()
417 .with_context(|| format!("failed to run command: {}", cmd))?;
418
419 if !status.success() {
420 return Err(anyhow!("command failed ({}) with status {}", why, status));
421 }
422
423 Ok(())
424}
425
426fn copy_assets(src: &Path, dest: &Path) -> Result<usize> {
427 let mut count = 0usize;
428 for entry in WalkDir::new(src)
429 .into_iter()
430 .filter_map(Result::ok)
431 .filter(|e| e.file_type().is_file())
432 {
433 let rel = entry
434 .path()
435 .strip_prefix(src)
436 .expect("walkdir provided prefix");
437 let target = dest.join(rel);
438 if let Some(parent) = target.parent() {
439 fs::create_dir_all(parent)
440 .with_context(|| format!("failed to create {}", parent.display()))?;
441 }
442 fs::copy(entry.path(), &target).with_context(|| {
443 format!(
444 "failed to copy {} to {}",
445 entry.path().display(),
446 target.display()
447 )
448 })?;
449 count += 1;
450 }
451
452 Ok(count)
453}
454
455fn build_gui_manifest(opts: &ConvertOptions, assets_root: &Path) -> Result<serde_json::Value> {
456 let html_files = discover_html_files(assets_root);
457 if html_files.is_empty()
458 && !matches!(opts.pack_kind, GuiPackKind::Skin | GuiPackKind::Telemetry)
459 {
460 return Err(anyhow!(
461 "no HTML files found in assets dir {}",
462 assets_root.display()
463 ));
464 }
465
466 match opts.pack_kind {
467 GuiPackKind::Layout => {
468 let entry = select_entrypoint(&html_files);
469 let spa = opts.spa.unwrap_or_else(|| infer_spa(&html_files, &entry));
470 Ok(json!({
471 "kind": "gui-layout",
472 "layout": {
473 "slots": ["header","menu","main","footer"],
474 "entrypoint_html": format!("gui/assets/{}", to_unix_path(&entry)),
475 "spa": spa,
476 "slot_selectors": {
477 "header": "#app-header",
478 "menu": "#app-menu",
479 "main": "#app-main",
480 "footer": "#app-footer"
481 }
482 }
483 }))
484 }
485 GuiPackKind::Auth => {
486 let routes = build_auth_routes(&html_files);
487 Ok(json!({
488 "kind": "gui-auth",
489 "routes": routes,
490 "ui_bindings": {
491 "login_form_selector": "#login-form",
492 "login_buttons": [
493 { "provider": "microsoft", "selector": "#login-ms" },
494 { "provider": "google", "selector": "#login-google" }
495 ]
496 }
497 }))
498 }
499 GuiPackKind::Feature => {
500 let routes = build_feature_routes(opts, &html_files);
501 let workers = detect_workers(assets_root, &html_files)?;
502 Ok(json!({
503 "kind": "gui-feature",
504 "routes": routes,
505 "digital_workers": workers,
506 "fragments": []
507 }))
508 }
509 GuiPackKind::Skin => {
510 let theme_css_path = find_theme_css(assets_root);
511 let theme_css = theme_css_path.map(|p| format!("gui/assets/{}", to_unix_path(&p)));
512 Ok(json!({
513 "kind": "gui-skin",
514 "skin": {
515 "theme_css": theme_css
516 }
517 }))
518 }
519 GuiPackKind::Telemetry => Ok(json!({
520 "kind": "gui-telemetry",
521 "telemetry": {}
522 })),
523 }
524}
525
526fn write_gui_manifest(path: &Path, value: &serde_json::Value) -> Result<()> {
527 if let Some(parent) = path.parent() {
528 fs::create_dir_all(parent)
529 .with_context(|| format!("failed to create {}", parent.display()))?;
530 }
531 let data = serde_json::to_vec_pretty(value)?;
532 fs::write(path, data).with_context(|| format!("failed to write {}", path.display()))
533}
534
535#[derive(Debug, Serialize)]
536struct PackManifestYaml<'a> {
537 pack_id: &'a str,
538 version: &'a str,
539 kind: &'a str,
540 publisher: &'a str,
541 #[serde(skip_serializing_if = "Vec::is_empty")]
542 components: Vec<()>,
543 #[serde(skip_serializing_if = "Vec::is_empty")]
544 dependencies: Vec<()>,
545 #[serde(skip_serializing_if = "Vec::is_empty")]
546 flows: Vec<()>,
547 assets: Vec<AssetEntry>,
548 #[serde(skip_serializing_if = "Option::is_none")]
549 name: Option<&'a str>,
550}
551
552#[derive(Debug, Serialize)]
553struct AssetEntry {
554 path: String,
555}
556
557fn write_pack_manifest(opts: &ConvertOptions, root: &Path, assets_copied: usize) -> Result<()> {
558 if assets_copied == 0 {
559 return Err(anyhow!("no assets copied; cannot build GUI pack"));
560 }
561
562 let mut assets = Vec::new();
563 assets.push(AssetEntry {
564 path: "gui/manifest.json".to_string(),
565 });
566
567 let assets_root = root.join("gui").join("assets");
568 for entry in WalkDir::new(&assets_root)
569 .into_iter()
570 .filter_map(Result::ok)
571 .filter(|e| e.file_type().is_file())
572 {
573 let rel = entry.path().strip_prefix(root).expect("walkdir prefix");
574 assets.push(AssetEntry {
575 path: to_unix_path(rel),
576 });
577 }
578
579 assets.sort_by(|a, b| a.path.cmp(&b.path));
580
581 let yaml = PackManifestYaml {
582 pack_id: &opts.pack_id,
583 version: &opts.version.to_string(),
584 kind: &opts.pack_manifest_kind,
585 publisher: &opts.publisher,
586 components: Vec::new(),
587 dependencies: Vec::new(),
588 flows: Vec::new(),
589 assets,
590 name: opts.name.as_deref(),
591 };
592
593 let manifest_path = root.join("pack.yaml");
594 let contents = serde_yaml_bw::to_string(&yaml)?;
595 fs::write(&manifest_path, contents)
596 .with_context(|| format!("failed to write {}", manifest_path.display()))?;
597
598 Ok(())
599}
600
601fn discover_html_files(assets_root: &Path) -> Vec<PathBuf> {
602 WalkDir::new(assets_root)
603 .into_iter()
604 .filter_map(Result::ok)
605 .filter(|e| e.file_type().is_file())
606 .filter(|e| {
607 e.path()
608 .extension()
609 .map(|ext| ext == "html")
610 .unwrap_or(false)
611 })
612 .map(|e| {
613 e.path()
614 .strip_prefix(assets_root)
615 .unwrap_or(e.path())
616 .to_path_buf()
617 })
618 .collect()
619}
620
621fn select_entrypoint(html_files: &[PathBuf]) -> PathBuf {
622 html_files
623 .iter()
624 .find(|p| p.file_name().map(|n| n == "index.html").unwrap_or(false))
625 .cloned()
626 .unwrap_or_else(|| html_files[0].clone())
627}
628
629fn infer_spa(html_files: &[PathBuf], entry: &Path) -> bool {
630 let real_pages = html_files.iter().filter(|p| is_real_page(p)).count();
631 real_pages <= 1
632 && entry
633 .file_name()
634 .map(|n| n == "index.html")
635 .unwrap_or(false)
636}
637
638fn is_real_page(path: &Path) -> bool {
639 let ignore = ["404", "robots"];
640 path.extension().map(|ext| ext == "html").unwrap_or(false)
641 && !ignore
642 .iter()
643 .any(|ig| path.file_stem().and_then(OsStr::to_str) == Some(ig))
644}
645
646fn build_auth_routes(html_files: &[PathBuf]) -> Vec<serde_json::Value> {
647 let mut routes = Vec::new();
648 let login = html_files
649 .iter()
650 .find(|p| p.file_name().and_then(OsStr::to_str) == Some("login.html"))
651 .or_else(|| html_files.first());
652
653 if let Some(login) = login {
654 routes.push(json!({
655 "path": "/login",
656 "html": format!("gui/assets/{}", to_unix_path(login)),
657 "public": true
658 }));
659 }
660
661 routes
662}
663
664fn build_feature_routes(opts: &ConvertOptions, html_files: &[PathBuf]) -> Vec<serde_json::Value> {
665 if !opts.routes.is_empty() {
666 return opts
667 .routes
668 .iter()
669 .map(|r| {
670 json!({
671 "path": r.path,
672 "html": format!("gui/assets/{}", to_unix_path(&r.html)),
673 "authenticated": true
674 })
675 })
676 .collect();
677 }
678
679 let entry = select_entrypoint(html_files);
680 let spa = opts.spa.unwrap_or_else(|| infer_spa(html_files, &entry));
681
682 let mut routes = Vec::new();
683 if spa {
684 routes.push(json!({
685 "path": "/",
686 "html": format!("gui/assets/{}", to_unix_path(&entry)),
687 "authenticated": true
688 }));
689 return routes;
690 }
691
692 for page in html_files.iter().filter(|p| is_real_page(p)) {
693 let route = route_from_path(page);
694 routes.push(json!({
695 "path": route,
696 "html": format!("gui/assets/{}", to_unix_path(page)),
697 "authenticated": true
698 }));
699 }
700
701 routes
702}
703
704fn route_from_path(path: &Path) -> String {
705 let mut parts = Vec::new();
706 if let Some(parent) = path.parent()
707 && parent != Path::new("")
708 {
709 parts.push(to_unix_path(parent));
710 }
711 if path.file_stem().and_then(OsStr::to_str) != Some("index") {
712 parts.push(
713 path.file_stem()
714 .and_then(OsStr::to_str)
715 .unwrap_or_default()
716 .to_string(),
717 );
718 }
719
720 let combined = parts.join("/");
721 if combined.is_empty() {
722 "/".to_string()
723 } else if combined.starts_with('/') {
724 combined
725 } else {
726 format!("/{}", combined)
727 }
728}
729
730fn detect_workers(assets_root: &Path, html_files: &[PathBuf]) -> Result<Vec<serde_json::Value>> {
731 let worker_re = Regex::new(r#"data-greentic-worker\s*=\s*"([^"]+)""#)?;
732 let slot_re = Regex::new(r#"data-greentic-worker-slot\s*=\s*"([^"]+)""#)?;
733 let mut seen = BTreeSet::new();
734 let mut workers = Vec::new();
735
736 for rel in html_files {
737 let abs = assets_root.join(rel);
738 let contents = fs::read_to_string(&abs).with_context(|| {
739 format!(
740 "failed to read HTML for worker detection: {}",
741 abs.display()
742 )
743 })?;
744
745 for caps in worker_re.captures_iter(&contents) {
746 let worker_id = caps
747 .get(1)
748 .map(|m| m.as_str().to_string())
749 .unwrap_or_default();
750 if worker_id.is_empty() || !seen.insert(worker_id.clone()) {
751 continue;
752 }
753
754 let slot = slot_re
755 .captures(&contents)
756 .and_then(|c| c.get(1))
757 .map(|m| m.as_str().to_string());
758
759 let selector = slot
760 .as_ref()
761 .map(|s| format!("#{}", s))
762 .unwrap_or_else(|| format!(r#"[data-greentic-worker="{}"]"#, worker_id));
763
764 workers.push(json!({
765 "id": worker_id.split('.').next_back().unwrap_or(&worker_id),
766 "worker_id": worker_id,
767 "attach": { "mode": "selector", "selector": selector },
768 "routes": ["/*"]
769 }));
770 }
771 }
772
773 Ok(workers)
774}
775
776fn extract_route_strings(manifest: &serde_json::Value) -> Vec<String> {
777 manifest
778 .get("routes")
779 .and_then(|r| r.as_array())
780 .map(|arr| {
781 arr.iter()
782 .filter_map(|r| {
783 r.get("path")
784 .and_then(|p| p.as_str())
785 .map(|s| s.to_string())
786 })
787 .collect()
788 })
789 .unwrap_or_default()
790}
791
792fn to_unix_path(path: &Path) -> String {
793 path.iter()
794 .map(|p| p.to_string_lossy())
795 .collect::<Vec<_>>()
796 .join("/")
797}
798
799fn gui_kind_string(kind: &GuiPackKind) -> String {
800 match kind {
801 GuiPackKind::Layout => "gui-layout",
802 GuiPackKind::Auth => "gui-auth",
803 GuiPackKind::Feature => "gui-feature",
804 GuiPackKind::Skin => "gui-skin",
805 GuiPackKind::Telemetry => "gui-telemetry",
806 }
807 .to_string()
808}
809
810fn find_theme_css(assets_root: &Path) -> Option<PathBuf> {
811 let candidates = ["theme.css", "styles.css"];
812 for candidate in candidates {
813 let path = assets_root.join(candidate);
814 if path.exists() {
815 return Some(PathBuf::from(candidate));
816 }
817 }
818 None
819}