Skip to main content

proa_cli/
scaffold.rs

1// Copyright Proa Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{
5    env, fs,
6    path::{Path, PathBuf},
7};
8
9use anyhow::{bail, Context, Result};
10use clap::ValueEnum;
11use serde::Serialize;
12use sha2::{Digest, Sha256};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, ValueEnum)]
15pub enum DryRunFormat {
16    Text,
17    Json,
18}
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, ValueEnum)]
21pub enum ServerIntegration {
22    Axum,
23    None,
24}
25
26impl std::fmt::Display for ServerIntegration {
27    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28        match self {
29            Self::Axum => f.write_str("axum"),
30            Self::None => f.write_str("none"),
31        }
32    }
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, ValueEnum)]
36pub enum DocsIntegration {
37    None,
38    #[value(name = "proa_docs")]
39    ProaDocs,
40}
41
42impl std::fmt::Display for DocsIntegration {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        match self {
45            Self::None => f.write_str("none"),
46            Self::ProaDocs => f.write_str("proa_docs"),
47        }
48    }
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, ValueEnum)]
52pub enum DeployTarget {
53    None,
54    Coolify,
55}
56
57impl std::fmt::Display for DeployTarget {
58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        match self {
60            Self::None => f.write_str("none"),
61            Self::Coolify => f.write_str("coolify"),
62        }
63    }
64}
65
66pub struct NewSiteArgs {
67    pub name: String,
68    pub template: String,
69    pub destination: Option<PathBuf>,
70    pub copy: Option<String>,
71    pub empty: bool,
72    pub server: ServerIntegration,
73    pub tailwind: bool,
74    pub no_tailwind: bool,
75    pub docs: DocsIntegration,
76    pub blog: bool,
77    pub no_blog: bool,
78    pub deploy: DeployTarget,
79    pub skip_install: bool,
80    pub no_git: bool,
81    pub agents_md: bool,
82    pub no_agents_md: bool,
83    pub dry_run: Option<DryRunFormat>,
84    pub force: bool,
85    pub yes: bool,
86}
87
88pub struct NewSiteOptions {
89    pub name: String,
90    pub root: PathBuf,
91    pub template: String,
92    pub empty: bool,
93    pub server: ServerIntegration,
94    pub tailwind: bool,
95    pub docs: DocsIntegration,
96    pub blog: bool,
97    pub deploy: DeployTarget,
98    pub skip_install: bool,
99    pub no_git: bool,
100    pub agents_md: bool,
101    pub dry_run: Option<DryRunFormat>,
102    pub force: bool,
103    pub yes: bool,
104}
105
106impl NewSiteOptions {
107    pub fn from_args(args: NewSiteArgs) -> Result<Self> {
108        if args.copy.is_some() {
109            bail!("--copy is reserved for template copying but is not implemented yet");
110        }
111        if args.tailwind && args.no_tailwind {
112            bail!("--tailwind and --no-tailwind cannot be combined");
113        }
114        if args.blog && args.no_blog {
115            bail!("--blog and --no-blog cannot be combined");
116        }
117        if args.agents_md && args.no_agents_md {
118            bail!("--agents-md and --no-agents-md cannot be combined");
119        }
120        if args.deploy == DeployTarget::Coolify && args.server != ServerIntegration::Axum {
121            bail!("--deploy coolify requires --server axum");
122        }
123        if args.empty && args.deploy != DeployTarget::None {
124            bail!("--empty cannot be combined with --deploy");
125        }
126
127        let destination = args.destination.unwrap_or(env::current_dir()?);
128        let name_path = PathBuf::from(&args.name);
129        let root = if name_path.is_absolute() {
130            name_path
131        } else {
132            destination.join(name_path)
133        };
134
135        let mut docs = args.docs;
136        let mut blog = args.blog;
137        let mut tailwind = !args.no_tailwind;
138        let mut agents_md = !args.no_agents_md;
139
140        if args.empty {
141            docs = DocsIntegration::None;
142            blog = false;
143            tailwind = false;
144            agents_md = false;
145        }
146
147        Ok(Self {
148            name: args.name,
149            root,
150            template: args.template,
151            empty: args.empty,
152            server: args.server,
153            tailwind,
154            docs,
155            blog,
156            deploy: args.deploy,
157            skip_install: args.skip_install,
158            no_git: args.no_git,
159            agents_md,
160            dry_run: args.dry_run,
161            force: args.force,
162            yes: args.yes,
163        })
164    }
165}
166
167pub struct GenerateComponentOptions {
168    pub name: String,
169    pub root: Option<PathBuf>,
170    pub folder: bool,
171    pub recipe: bool,
172    pub children: bool,
173    pub asynchronous: bool,
174    pub markdown: bool,
175    pub no_test: bool,
176    pub dry_run: Option<DryRunFormat>,
177    pub force: bool,
178}
179
180pub struct GenerateLayoutOptions {
181    pub name: String,
182    pub root: Option<PathBuf>,
183    pub document: bool,
184    pub section: bool,
185    pub replace_root: bool,
186    pub dry_run: Option<DryRunFormat>,
187    pub force: bool,
188}
189
190pub struct GenerateDataOptions {
191    pub name: String,
192    pub root: Option<PathBuf>,
193    pub dry_run: Option<DryRunFormat>,
194    pub force: bool,
195}
196
197#[derive(Debug, Default, Serialize)]
198pub struct ScaffoldPlan {
199    pub root: PathBuf,
200    pub operations: Vec<PlanOperation>,
201    pub warnings: Vec<String>,
202    pub follow_up: Vec<String>,
203}
204
205#[derive(Debug, Clone, Serialize)]
206#[serde(tag = "action", rename_all = "snake_case")]
207pub enum PlanOperation {
208    WriteFile {
209        path: PathBuf,
210        description: String,
211        bytes: usize,
212        #[serde(skip)]
213        content: String,
214    },
215    AppendLine {
216        path: PathBuf,
217        description: String,
218        line: String,
219    },
220}
221
222#[derive(Debug, Serialize)]
223pub struct SiteCheckReport {
224    pub root: PathBuf,
225    pub errors: Vec<String>,
226    pub warnings: Vec<String>,
227}
228
229#[derive(Debug, Serialize)]
230pub struct RouteInfo {
231    pub method: &'static str,
232    pub path: String,
233    pub kind: &'static str,
234    pub representations: String,
235    pub file: PathBuf,
236}
237
238pub fn new_site(options: NewSiteOptions) -> Result<()> {
239    new_site_with_tailwind_ready(options, false)
240}
241
242pub(crate) fn new_site_with_tailwind_ready(
243    options: NewSiteOptions,
244    tailwind_ready: bool,
245) -> Result<()> {
246    let mut plan = ScaffoldPlan::new(options.root.clone());
247    let project_name = package_name(
248        options
249            .root
250            .file_name()
251            .and_then(|name| name.to_str())
252            .unwrap_or(&options.name),
253    );
254    let title = title_case(&project_name);
255    let has_docs = options.docs == DocsIntegration::ProaDocs;
256    let has_blog = options.blog;
257    let has_axum = options.server == ServerIntegration::Axum;
258    // Font wiring needs the generated crate root (src/main.rs) to include the
259    // build-generated module, so it is tied to the Axum integration.
260    let has_fonts = !options.empty && has_axum;
261    let has_coolify = options.deploy == DeployTarget::Coolify;
262
263    if options.template != "basic" && options.template != "marketing" && options.template != "docs"
264    {
265        plan.warnings.push(format!(
266            "unknown template `{}`; using the basic site shape",
267            options.template
268        ));
269    }
270
271    plan.write_file(
272        options.root.join("Cargo.toml"),
273        cargo_toml(&project_name, &options),
274    );
275    plan.write_file(
276        options.root.join(crate::config::CONFIG_FILE),
277        crate::config::generated_project_config(options.tailwind)?,
278    );
279    plan.write_file(
280        options.root.join(crate::config::LOCK_FILE),
281        crate::config::generated_component_lock()?,
282    );
283    plan.write_file(options.root.join(".cargo/config.toml"), cargo_config_toml());
284    plan.write_file(options.root.join("scripts/dev.sh"), dev_script());
285    plan.write_file(options.root.join("scripts/build.sh"), build_script());
286    plan.write_file(
287        options.root.join("scripts/watch-lock.sh"),
288        watch_lock_script(),
289    );
290    plan.write_file(
291        options.root.join("README.md"),
292        readme(&project_name, options.deploy),
293    );
294    plan.write_file(options.root.join(".gitignore"), gitignore());
295    if options.agents_md {
296        plan.write_file(options.root.join("AGENTS.md"), agents_md());
297    }
298
299    plan.write_file(options.root.join("src/components/mod.rs"), components_mod());
300    plan.write_file(
301        options.root.join("src/layouts/mod.rs"),
302        "pub mod root;\n".to_string(),
303    );
304    plan.write_file(options.root.join("src/layouts/root.rs"), root_layout());
305    plan.write_file(
306        options.root.join("src/data/mod.rs"),
307        "pub mod nav;\npub mod routes;\n".to_string(),
308    );
309    plan.write_file(options.root.join("src/data/nav.rs"), nav_data());
310    plan.write_file(
311        options.root.join("src/data/routes.rs"),
312        routes_data(has_docs, has_blog),
313    );
314    plan.write_file(
315        options.root.join("src/pages/mod.rs"),
316        pages_mod(has_docs, has_blog),
317    );
318    plan.write_file(
319        options.root.join("src/pages/home.rs"),
320        home_page(&title, has_axum),
321    );
322    plan.write_file(options.root.join("public/favicon.svg"), favicon_svg());
323
324    if has_axum {
325        plan.write_file(
326            options.root.join("src/main.rs"),
327            main_rs(has_fonts, has_docs, has_blog),
328        );
329        plan.write_file(
330            options.root.join("src/static_assets.rs"),
331            static_assets_rs(has_fonts),
332        );
333    } else {
334        plan.follow_up
335            .push("wire src/pages::home::render() into your custom server integration".to_string());
336    }
337
338    if options.tailwind {
339        plan.write_file(options.root.join("styles/input.css"), tailwind_input_css());
340        plan.write_file(
341            options.root.join("public/styles.css"),
342            generated_styles_placeholder(),
343        );
344        if !tailwind_ready {
345            plan.follow_up.push(
346                "install Tailwind CSS CLI v4 with the Proa installer (`--tailwind-only`) or Homebrew (`brew install tailwindcss`) before building assets".to_string(),
347            );
348        }
349        plan.follow_up
350            .push("run bash scripts/dev.sh to build assets and start the server".to_string());
351    } else {
352        plan.write_file(options.root.join("public/styles.css"), plain_css());
353    }
354
355    if has_docs {
356        plan.write_file(options.root.join("src/docs/index.mdx"), docs_index());
357        plan.write_file(
358            options.root.join("src/docs/getting-started.mdx"),
359            docs_getting_started(),
360        );
361        plan.write_file(options.root.join("src/pages/docs.rs"), docs_page(has_axum));
362    }
363
364    if has_blog {
365        plan.write_file(
366            options.root.join("src/blog/first-post.mdx"),
367            blog_first_post(),
368        );
369        plan.write_file(options.root.join("src/pages/blog.rs"), blog_page(has_axum));
370    }
371
372    if has_fonts || has_docs || has_blog {
373        plan.write_file(
374            options.root.join("build.rs"),
375            build_rs(has_fonts, has_docs, has_blog),
376        );
377    }
378
379    if has_coolify {
380        plan.write_file(options.root.join("Dockerfile"), dockerfile(&project_name));
381        plan.write_file(options.root.join(".dockerignore"), dockerignore());
382        plan.write_file(
383            options.root.join("coolify.env.example"),
384            coolify_env_example(),
385        );
386        plan.write_file(
387            options.root.join("COOLIFY.md"),
388            coolify_readme(&project_name),
389        );
390        plan.follow_up.push(
391            "configure Coolify with Dockerfile build, port 3000, and /healthz health check"
392                .to_string(),
393        );
394        plan.follow_up.push(
395            "set up wildcard DNS and Coolify Preview Deployments for pull request URLs".to_string(),
396        );
397    }
398
399    if !options.skip_install {
400        plan.follow_up
401            .push("run proa build before deploying".to_string());
402    }
403    if options.no_git {
404        plan.warnings
405            .push("git initialization skipped by --no-git".to_string());
406    }
407
408    finish_plan(plan, options.dry_run, options.force)
409}
410
411pub fn generate_component(options: GenerateComponentOptions) -> Result<()> {
412    let root = resolve_root(options.root)?;
413    let target = ModuleTarget::new(&root, "components", &options.name)?;
414    let struct_name = pascal_case(&target.leaf);
415    let data_attr = format!("data-{}", kebab_case(&target.leaf));
416    let mut plan = ScaffoldPlan::new(root.clone());
417
418    target.plan_mod_updates(&mut plan);
419
420    if options.folder || options.recipe {
421        let dir = target.file_path.with_extension("");
422        plan.write_file(
423            dir.join("mod.rs"),
424            if options.recipe {
425                format!(
426                    "mod {};\nmod recipe;\n\npub use {}::{};\npub use recipe::{}Recipe;\n",
427                    target.leaf, target.leaf, struct_name, struct_name
428                )
429            } else {
430                format!(
431                    "mod {};\n\npub use {}::{};\n",
432                    target.leaf, target.leaf, struct_name
433                )
434            },
435        );
436        plan.write_file(
437            dir.join(format!("{}.rs", target.leaf)),
438            component_source(
439                &struct_name,
440                &data_attr,
441                options.children,
442                options.asynchronous,
443                options.markdown,
444                options.recipe,
445                !options.no_test,
446            ),
447        );
448        if options.recipe {
449            plan.write_file(dir.join("recipe.rs"), component_recipe_source(&struct_name));
450        }
451    } else {
452        plan.write_file(
453            target.file_path,
454            component_source(
455                &struct_name,
456                &data_attr,
457                options.children,
458                options.asynchronous,
459                options.markdown,
460                false,
461                !options.no_test,
462            ),
463        );
464    }
465
466    finish_plan(plan, options.dry_run, options.force)
467}
468
469pub fn generate_layout(options: GenerateLayoutOptions) -> Result<()> {
470    if options.document && options.section {
471        bail!("--document and --section cannot be combined");
472    }
473
474    let root = resolve_root(options.root)?;
475    let target = ModuleTarget::new(&root, "layouts", &options.name)?;
476    let struct_name = format!("{}Layout", pascal_case(&target.leaf));
477    let mut plan = ScaffoldPlan::new(root.clone());
478
479    if options.document {
480        let mut current_roots = Vec::new();
481        let layouts = root.join("src/layouts");
482        if layouts.is_dir() {
483            for path in rust_files(&layouts)? {
484                if path != target.file_path
485                    && fs::read_to_string(&path)
486                        .unwrap_or_default()
487                        .contains("// proa:document-root")
488                {
489                    current_roots.push(path);
490                }
491            }
492        }
493        if !current_roots.is_empty() && !options.replace_root {
494            bail!(
495                "a document root is already marked at {}; rerun with --replace-root",
496                display_rel(&root, &current_roots[0])
497            );
498        }
499        for path in current_roots {
500            let source = fs::read_to_string(&path)?
501                .replace("// proa:document-root", "// proa:document-layout");
502            plan.write_file(path, source);
503        }
504    }
505
506    target.plan_mod_updates(&mut plan);
507    let source = if options.document {
508        document_layout_source(&struct_name)
509    } else {
510        section_layout_source(&struct_name)
511    };
512    plan.write_file(target.file_path, source);
513
514    finish_plan(plan, options.dry_run, options.force || options.replace_root)
515}
516
517pub fn generate_data(options: GenerateDataOptions) -> Result<()> {
518    let root = resolve_root(options.root)?;
519    let target = ModuleTarget::new(&root, "static_data", &options.name)?;
520    let mut plan = ScaffoldPlan::new(root);
521
522    target.plan_mod_updates(&mut plan);
523    plan.write_file(target.file_path, data_source(&target.leaf));
524
525    finish_plan(plan, options.dry_run, options.force)
526}
527
528pub fn site_check(root: Option<PathBuf>) -> Result<SiteCheckReport> {
529    let root = resolve_root(root)?;
530    let mut report = SiteCheckReport {
531        root: root.clone(),
532        errors: Vec::new(),
533        warnings: Vec::new(),
534    };
535
536    let config_value = fs::read_to_string(root.join(crate::config::CONFIG_FILE))
537        .ok()
538        .and_then(|source| serde_json::from_str::<serde_json::Value>(&source).ok());
539    let application_first = config_value
540        .as_ref()
541        .and_then(|value| value.get("application"))
542        .is_some();
543    let template = config_value
544        .as_ref()
545        .and_then(|value| value.pointer("/application/template"))
546        .and_then(serde_json::Value::as_str)
547        .unwrap_or("")
548        .to_string();
549    let origin_template = template == "origin";
550    let required: &[&str] = if origin_template {
551        &[
552            "src/lib.rs",
553            "src/main.rs",
554            "src/components/mod.rs",
555            "src/layouts/mod.rs",
556            "public/styles.css",
557        ]
558    } else if application_first {
559        &[
560            "src/pages/mod.rs",
561            "src/components/mod.rs",
562            "src/layouts/mod.rs",
563            "src/endpoints/mod.rs",
564            "src/routes.rs",
565            "src/app.rs",
566            "src/config.rs",
567            "src/error.rs",
568            "src/static_assets.rs",
569        ]
570    } else {
571        &[
572            "src/pages/mod.rs",
573            "src/components/mod.rs",
574            "src/layouts/mod.rs",
575            "src/data/mod.rs",
576        ]
577    };
578    for rel in required {
579        if !root.join(rel).exists() {
580            report.errors.push(format!("missing {rel}"));
581        }
582    }
583
584    if root.join("src/islands").exists() {
585        report
586            .errors
587            .push("src/islands should not be generated for this site convention".to_string());
588    }
589
590    if application_first {
591        // Capability checks follow application code after users replace starter pages.
592        let sources = rust_files(&root.join("src"))?
593            .into_iter()
594            .map(fs::read_to_string)
595            .collect::<std::io::Result<Vec<_>>>()?;
596        let has_source = |needle: &str| sources.iter().any(|source| source.contains(needle));
597        if domain_root_is_empty(&root.join("src/models"))
598            || domain_root_is_empty(&root.join("src/services"))
599        {
600            report.errors.push(
601                "empty domain roots must not be generated; create models/services on demand"
602                    .to_string(),
603            );
604        }
605        let database = config_value
606            .as_ref()
607            .and_then(|value| value.pointer("/database/driver"))
608            .and_then(serde_json::Value::as_str);
609        if database == Some("sqlite") {
610            let manual = config_value
611                .as_ref()
612                .and_then(|value| value.pointer("/database/integration"))
613                .and_then(serde_json::Value::as_str)
614                == Some("manual");
615            let required_database_files: &[&str] = if manual {
616                &["src/db.rs", "data/.gitkeep", "migrations/.gitkeep"]
617            } else {
618                &[
619                    "src/db.rs",
620                    "src/loader.rs",
621                    "data/.gitkeep",
622                    "migrations/.gitkeep",
623                ]
624            };
625            for rel in required_database_files {
626                if !root.join(rel).exists() {
627                    report
628                        .errors
629                        .push(format!("SQLite capability is missing {rel}"));
630                }
631            }
632            if manual {
633                report.warnings.push(
634                    "SQLite is installed with manual integration pending; add `mod db;`, connect the pool, and place it in application state"
635                        .to_string(),
636                );
637            } else {
638                if !has_source("DataResolver::request_scope") {
639                    report.errors.push(
640                        "SQLite application does not create a request-scoped DataResolver"
641                            .to_string(),
642                    );
643                }
644            }
645        }
646        let markdown = config_value
647            .as_ref()
648            .and_then(|value| value.pointer("/representations/markdown/enabled"))
649            .and_then(serde_json::Value::as_bool)
650            .unwrap_or(false);
651        if markdown {
652            if origin_template {
653                let library = fs::read_to_string(root.join("src/lib.rs")).unwrap_or_default();
654                for contract in [
655                    "MarkdownAlternate::new(\"/index.md\")",
656                    "explicit_markdown(",
657                ] {
658                    if !library.contains(contract) {
659                        report.errors.push(format!(
660                            "Markdown representation contract is missing `{contract}`"
661                        ));
662                    }
663                }
664                let page = fs::read_to_string(root.join("src/components/atlas_page.rs"))
665                    .unwrap_or_default();
666                if !page.contains("MdRenderSync") {
667                    report.errors.push(
668                        "Markdown representation contract is missing `MdRenderSync`".to_string(),
669                    );
670                }
671            } else {
672                for contract in ["MdRenderSync", "explicit_markdown("] {
673                    let has_contract = has_source(contract)
674                        || match contract {
675                            "MdRenderSync" => has_source("MdRender<"),
676                            "explicit_markdown(" => {
677                                has_source("explicit_markdown_async_with_loader(")
678                            }
679                            _ => false,
680                        };
681                    if !has_contract {
682                        report.errors.push(format!(
683                            "Markdown representation contract is missing `{contract}`"
684                        ));
685                    }
686                }
687            }
688            let layout = fs::read_to_string(root.join("src/layouts/root.rs")).unwrap_or_default();
689            if layout.contains("MdRender") {
690                report
691                    .errors
692                    .push("RootDocument must remain HTML-only".to_string());
693            }
694        }
695        if let Ok(validation) = crate::config::validate_project_config(&root) {
696            report.errors.extend(validation.errors);
697            report.warnings.extend(validation.warnings);
698        }
699        for rel in [
700            ".vscode/extensions.json",
701            ".vscode/settings.json",
702            ".vscode/tasks.json",
703        ] {
704            let path = root.join(rel);
705            if path.exists()
706                && fs::read_to_string(&path)
707                    .ok()
708                    .and_then(|source| serde_json::from_str::<serde_json::Value>(&source).ok())
709                    .is_none()
710            {
711                report.errors.push(format!("{rel} is not valid JSON"));
712            }
713        }
714        validate_component_hashes(&root, &mut report)?;
715        validate_migration_pairs(&root, &mut report)?;
716    }
717
718    let pages_dir = root.join("src/pages");
719    if pages_dir.exists() {
720        for file in rust_files(&pages_dir)? {
721            if file.file_name().and_then(|name| name.to_str()) == Some("mod.rs") {
722                continue;
723            }
724            let source =
725                fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?;
726            if !source.contains("fn handler") && !source.contains("fn render") {
727                // proa-perf-ok: CLI validation builds diagnostic messages outside SSR render paths
728                report.errors.push(format!(
729                    "{} does not expose a handler or render function",
730                    display_rel(&root, &file)
731                ));
732            }
733        }
734    }
735
736    Ok(report)
737}
738
739fn domain_root_is_empty(path: &Path) -> bool {
740    if !path.is_dir() {
741        return false;
742    }
743    fs::read_dir(path)
744        .ok()
745        .into_iter()
746        .flatten()
747        .filter_map(Result::ok)
748        .all(|entry| entry.file_name() == "mod.rs")
749}
750
751fn validate_component_hashes(root: &Path, report: &mut SiteCheckReport) -> Result<()> {
752    let lock_path = root.join(crate::config::LOCK_FILE);
753    if !lock_path.is_file() {
754        return Ok(());
755    }
756    let lock: serde_json::Value = serde_json::from_str(&fs::read_to_string(&lock_path)?)?;
757    let Some(components) = lock
758        .get("components")
759        .and_then(serde_json::Value::as_object)
760    else {
761        return Ok(());
762    };
763    for (component, value) in components {
764        let Some(files) = value.get("files").and_then(serde_json::Value::as_object) else {
765            continue;
766        };
767        for (relative, expected) in files {
768            let path = root.join(relative);
769            let actual = fs::read(&path)
770                .ok()
771                .map(|bytes| format!("sha256:{:x}", Sha256::digest(bytes)));
772            if actual.as_deref() != expected.as_str() {
773                report.errors.push(format!(
774                    "component {component} has local drift in {relative}"
775                ));
776            }
777        }
778    }
779    Ok(())
780}
781
782fn validate_migration_pairs(root: &Path, report: &mut SiteCheckReport) -> Result<()> {
783    let directory = root.join("migrations");
784    if !directory.is_dir() {
785        return Ok(());
786    }
787    let mut up = std::collections::BTreeSet::new();
788    let mut down = std::collections::BTreeSet::new();
789    for entry in fs::read_dir(directory)? {
790        let name = entry?.file_name().to_string_lossy().into_owned();
791        if let Some(base) = name.strip_suffix(".up.sql") {
792            up.insert(base.to_string());
793        } else if let Some(base) = name.strip_suffix(".down.sql") {
794            down.insert(base.to_string());
795        }
796    }
797    for missing in up.difference(&down) {
798        report
799            .errors
800            .push(format!("migration {missing} is missing its .down.sql pair"));
801    }
802    for missing in down.difference(&up) {
803        report
804            .errors
805            .push(format!("migration {missing} is missing its .up.sql pair"));
806    }
807    Ok(())
808}
809
810pub fn print_site_check(report: &SiteCheckReport, json: bool) -> Result<()> {
811    if json {
812        println!("{}", serde_json::to_string_pretty(report)?);
813        return Ok(());
814    }
815
816    if report.errors.is_empty() {
817        println!("Proa site check passed for {}", report.root.display());
818    } else {
819        for error in &report.errors {
820            eprintln!("error: {error}");
821        }
822    }
823    for warning in &report.warnings {
824        eprintln!("warning: {warning}");
825    }
826    Ok(())
827}
828
829pub fn site_routes(root: Option<PathBuf>) -> Result<Vec<RouteInfo>> {
830    let root = resolve_root(root)?;
831    let config = fs::read_to_string(root.join(crate::config::CONFIG_FILE))
832        .ok()
833        .and_then(|source| serde_json::from_str::<serde_json::Value>(&source).ok());
834    if config
835        .as_ref()
836        .and_then(|value| value.get("application"))
837        .is_some()
838    {
839        let markdown = config
840            .as_ref()
841            .and_then(|value| value.pointer("/representations/markdown/enabled"))
842            .and_then(serde_json::Value::as_bool)
843            .unwrap_or(false);
844        let mut routes = vec![RouteInfo {
845            method: "GET",
846            path: "/".to_string(),
847            kind: "page",
848            representations: if markdown {
849                "html · md:/index.md".to_string()
850            } else {
851                "html".to_string()
852            },
853            file: PathBuf::from("src/pages/home.rs"),
854        }];
855        if markdown {
856            routes.push(RouteInfo {
857                method: "GET",
858                path: "/index.md".to_string(),
859                kind: "representation",
860                representations: "markdown".to_string(),
861                file: PathBuf::from("src/pages/home.rs"),
862            });
863        }
864        for path in ["/healthz", "/readyz"] {
865            routes.push(RouteInfo {
866                method: "GET",
867                path: path.to_string(),
868                kind: "endpoint",
869                representations: "json".to_string(),
870                file: PathBuf::from("src/endpoints/health.rs"),
871            });
872        }
873        let generated_routes = fs::read_to_string(root.join("src/routes.rs")).unwrap_or_default();
874        for line in generated_routes.lines() {
875            let trimmed = line.trim();
876            if !trimmed.starts_with("Route::endpoint(\"") {
877                continue;
878            }
879            let Some(route_path) = trimmed
880                .strip_prefix("Route::endpoint(\"")
881                .and_then(|rest| rest.split('\"').next())
882            else {
883                continue;
884            };
885            if route_path == "/" || routes.iter().any(|route| route.path == route_path) {
886                continue;
887            }
888            let (kind, module, method) = if let Some(rest) = trimmed.split("pages::").nth(1) {
889                ("page", rest.split("::").next().unwrap_or("unknown"), "GET")
890            } else if let Some(rest) = trimmed.split("endpoints::").nth(1) {
891                let method = ["get", "post", "put", "patch", "delete"]
892                    .into_iter()
893                    .find(|method| trimmed.contains(&format!("routing::{method}(")))
894                    .unwrap_or("get");
895                (
896                    "endpoint",
897                    rest.split("::").next().unwrap_or("unknown"),
898                    match method {
899                        "post" => "POST",
900                        "put" => "PUT",
901                        "patch" => "PATCH",
902                        "delete" => "DELETE",
903                        _ => "GET",
904                    },
905                )
906            } else {
907                continue;
908            };
909            let markdown_alias = format!("{route_path}.md");
910            let has_markdown = kind == "page"
911                && generated_routes.contains(&format!(".route(\"{markdown_alias}\""));
912            routes.push(RouteInfo {
913                method,
914                path: route_path.to_string(),
915                kind,
916                representations: if has_markdown {
917                    format!("html · md:{markdown_alias}")
918                } else if kind == "page" {
919                    "html".to_string()
920                } else {
921                    "response".to_string()
922                },
923                file: PathBuf::from(format!("src/{}s/{module}.rs", kind)),
924            });
925            if has_markdown {
926                routes.push(RouteInfo {
927                    method: "GET",
928                    path: markdown_alias,
929                    kind: "representation",
930                    representations: "markdown".to_string(),
931                    file: PathBuf::from(format!("src/pages/{module}.rs")),
932                });
933            }
934        }
935        routes.sort_by(|left, right| left.path.cmp(&right.path));
936        return Ok(routes);
937    }
938    let pages_dir = root.join("src/pages");
939    let mut routes = Vec::new();
940    if !pages_dir.exists() {
941        return Ok(routes);
942    }
943
944    for file in rust_files(&pages_dir)? {
945        if file.file_name().and_then(|name| name.to_str()) == Some("mod.rs") {
946            continue;
947        }
948        let rel = file.strip_prefix(&pages_dir).unwrap_or(&file);
949        routes.push(RouteInfo {
950            method: "GET",
951            path: route_path_for_page(rel),
952            kind: "page",
953            representations: "html".to_string(),
954            file: display_rel_path(&root, &file),
955        });
956    }
957    routes.sort_by(|a, b| a.path.cmp(&b.path));
958    Ok(routes)
959}
960
961pub fn print_routes(routes: &[RouteInfo], json: bool) -> Result<()> {
962    if json {
963        println!("{}", serde_json::to_string_pretty(routes)?);
964        return Ok(());
965    }
966
967    println!("METHOD  PATH                             KIND            REPRESENTATIONS             SOURCE");
968    for route in routes {
969        println!(
970            "{:<7} {:<32} {:<15} {:<27} {}",
971            route.method,
972            route.path,
973            route.kind,
974            route.representations,
975            route.file.display()
976        );
977    }
978    Ok(())
979}
980
981impl ScaffoldPlan {
982    fn new(root: PathBuf) -> Self {
983        Self {
984            root,
985            operations: Vec::new(),
986            warnings: Vec::new(),
987            follow_up: Vec::new(),
988        }
989    }
990
991    fn write_file(&mut self, path: PathBuf, content: String) {
992        self.operations.push(PlanOperation::WriteFile {
993            description: "write file".to_string(),
994            path,
995            bytes: content.len(),
996            content,
997        });
998    }
999
1000    fn append_line(&mut self, path: PathBuf, line: String, description: impl Into<String>) {
1001        self.operations.push(PlanOperation::AppendLine {
1002            path,
1003            line,
1004            description: description.into(),
1005        });
1006    }
1007}
1008
1009fn finish_plan(plan: ScaffoldPlan, dry_run: Option<DryRunFormat>, force: bool) -> Result<()> {
1010    if let Some(format) = dry_run {
1011        match format {
1012            DryRunFormat::Text => print_plan(&plan),
1013            DryRunFormat::Json => println!("{}", serde_json::to_string_pretty(&plan)?),
1014        }
1015        return Ok(());
1016    }
1017
1018    preflight(&plan, force)?;
1019    apply_plan(&plan, force)?;
1020    print_plan(&plan);
1021    Ok(())
1022}
1023
1024fn print_plan(plan: &ScaffoldPlan) {
1025    for operation in &plan.operations {
1026        match operation {
1027            PlanOperation::WriteFile { path, .. } => println!("create {}", path.display()),
1028            PlanOperation::AppendLine { path, .. } => println!("update {}", path.display()),
1029        }
1030    }
1031    for warning in &plan.warnings {
1032        eprintln!("warning: {warning}");
1033    }
1034    if !plan.follow_up.is_empty() {
1035        println!("\nNext steps:");
1036        for step in &plan.follow_up {
1037            println!("- {step}");
1038        }
1039    }
1040}
1041
1042fn preflight(plan: &ScaffoldPlan, force: bool) -> Result<()> {
1043    if force {
1044        return Ok(());
1045    }
1046
1047    for operation in &plan.operations {
1048        if let PlanOperation::WriteFile { path, .. } = operation {
1049            if path.exists() {
1050                bail!(
1051                    "{} already exists (use --force to overwrite)",
1052                    path.display()
1053                );
1054            }
1055        }
1056    }
1057    Ok(())
1058}
1059
1060fn apply_plan(plan: &ScaffoldPlan, force: bool) -> Result<()> {
1061    // Journal each file's prior state so a mid-plan failure rolls everything
1062    // back instead of leaving a half-written project.
1063    let mut journal: Vec<(PathBuf, Option<String>)> = Vec::new();
1064    let outcome = apply_operations(plan, force, &mut journal);
1065    if outcome.is_err() {
1066        rollback(&journal);
1067    }
1068    outcome
1069}
1070
1071fn apply_operations(
1072    plan: &ScaffoldPlan,
1073    force: bool,
1074    journal: &mut Vec<(PathBuf, Option<String>)>,
1075) -> Result<()> {
1076    for operation in &plan.operations {
1077        match operation {
1078            PlanOperation::WriteFile { path, content, .. } => {
1079                if path.exists() && !force {
1080                    bail!(
1081                        "{} already exists (use --force to overwrite)",
1082                        path.display()
1083                    );
1084                }
1085                if let Some(parent) = path.parent() {
1086                    fs::create_dir_all(parent)
1087                        .with_context(|| format!("create {}", parent.display()))?;
1088                }
1089                journal.push((path.clone(), fs::read_to_string(path).ok()));
1090                fs::write(path, content).with_context(|| format!("write {}", path.display()))?;
1091            }
1092            PlanOperation::AppendLine { path, line, .. } => {
1093                if let Some(parent) = path.parent() {
1094                    fs::create_dir_all(parent)
1095                        .with_context(|| format!("create {}", parent.display()))?;
1096                }
1097                let mut current = fs::read_to_string(path).unwrap_or_default();
1098                if !current
1099                    .lines()
1100                    .any(|existing| existing.trim() == line.trim())
1101                {
1102                    journal.push((path.clone(), fs::read_to_string(path).ok()));
1103                    if !current.is_empty() && !current.ends_with('\n') {
1104                        current.push('\n');
1105                    }
1106                    current.push_str(line);
1107                    current.push('\n');
1108                    fs::write(path, current)
1109                        .with_context(|| format!("update {}", path.display()))?;
1110                }
1111            }
1112        }
1113    }
1114    Ok(())
1115}
1116
1117fn rollback(journal: &[(PathBuf, Option<String>)]) {
1118    for (path, prior) in journal.iter().rev() {
1119        let restored = match prior {
1120            Some(content) => fs::write(path, content),
1121            None => fs::remove_file(path),
1122        };
1123        if restored.is_err() {
1124            eprintln!(
1125                "warning: could not roll back {} after a failed scaffold",
1126                path.display()
1127            );
1128        }
1129    }
1130}
1131
1132struct ModuleTarget {
1133    leaf: String,
1134    file_path: PathBuf,
1135    mod_updates: Vec<(PathBuf, String)>,
1136}
1137
1138impl ModuleTarget {
1139    fn new(root: &Path, bucket: &str, raw_name: &str) -> Result<Self> {
1140        let parts: Vec<String> = raw_name
1141            .split('/')
1142            .filter(|part| !part.is_empty())
1143            .map(snake_case)
1144            .collect();
1145        if parts.is_empty() {
1146            bail!("name cannot be empty");
1147        }
1148        let leaf = parts.last().cloned().unwrap();
1149        let base = root.join("src").join(bucket);
1150        let mut dir = base.clone();
1151        let mut mod_updates = Vec::new();
1152
1153        for (index, part) in parts.iter().enumerate() {
1154            let mod_path = if index == 0 {
1155                base.join("mod.rs")
1156            } else {
1157                base.join(parts[..index].join("/")).join("mod.rs")
1158            };
1159            mod_updates.push((mod_path, format!("pub mod {part};")));
1160            if index + 1 < parts.len() {
1161                dir.push(part);
1162            }
1163        }
1164
1165        Ok(Self {
1166            leaf,
1167            file_path: dir.join(format!("{}.rs", parts.last().unwrap())),
1168            mod_updates,
1169        })
1170    }
1171
1172    fn plan_mod_updates(&self, plan: &mut ScaffoldPlan) {
1173        for (path, line) in &self.mod_updates {
1174            plan.append_line(path.clone(), line.clone(), "add module export");
1175        }
1176    }
1177}
1178
1179pub fn resolve_root(root: Option<PathBuf>) -> Result<PathBuf> {
1180    if let Some(root) = root {
1181        return Ok(root);
1182    }
1183
1184    let mut current = env::current_dir()?;
1185    loop {
1186        if current.join("Cargo.toml").exists() && current.join("src").exists() {
1187            return Ok(current);
1188        }
1189        if !current.pop() {
1190            bail!("could not find a Proa project root (pass --root)");
1191        }
1192    }
1193}
1194
1195fn rust_files(root: &Path) -> Result<Vec<PathBuf>> {
1196    let mut files = Vec::new();
1197    collect_rust_files(root, &mut files)?;
1198    Ok(files)
1199}
1200
1201fn collect_rust_files(root: &Path, files: &mut Vec<PathBuf>) -> Result<()> {
1202    for entry in fs::read_dir(root).with_context(|| format!("read {}", root.display()))? {
1203        let entry = entry?;
1204        let path = entry.path();
1205        if path.is_dir() {
1206            collect_rust_files(&path, files)?;
1207        } else if path.extension().and_then(|ext| ext.to_str()) == Some("rs") {
1208            files.push(path);
1209        }
1210    }
1211    Ok(())
1212}
1213
1214fn route_path_for_page(rel: &Path) -> String {
1215    let mut parts: Vec<String> = rel
1216        .with_extension("")
1217        .components()
1218        .filter_map(|component| component.as_os_str().to_str().map(str::to_string))
1219        .collect();
1220    if parts.last().is_some_and(|part| part == "index") {
1221        parts.pop();
1222    }
1223    if parts.len() == 1 && parts[0] == "home" {
1224        return "/".to_string();
1225    }
1226    if parts.is_empty() {
1227        "/".to_string()
1228    } else {
1229        format!("/{}", parts.join("/").replace('_', "-"))
1230    }
1231}
1232
1233fn display_rel(root: &Path, path: &Path) -> String {
1234    display_rel_path(root, path).display().to_string()
1235}
1236
1237fn display_rel_path(root: &Path, path: &Path) -> PathBuf {
1238    path.strip_prefix(root).unwrap_or(path).to_path_buf()
1239}
1240
1241fn package_name(value: &str) -> String {
1242    kebab_case(value)
1243}
1244
1245fn snake_case(value: &str) -> String {
1246    normalize_case(value, '_')
1247}
1248
1249fn kebab_case(value: &str) -> String {
1250    normalize_case(value, '-')
1251}
1252
1253fn normalize_case(value: &str, separator: char) -> String {
1254    let mut out = String::new();
1255    let mut last_was_sep = false;
1256    for ch in value.chars() {
1257        if ch.is_ascii_alphanumeric() {
1258            out.push(ch.to_ascii_lowercase());
1259            last_was_sep = false;
1260        } else if !last_was_sep && !out.is_empty() {
1261            out.push(separator);
1262            last_was_sep = true;
1263        }
1264    }
1265    while out.ends_with(separator) {
1266        out.pop();
1267    }
1268    if out.is_empty() {
1269        out.push_str("generated");
1270    }
1271    if out.starts_with(|ch: char| ch.is_ascii_digit()) {
1272        out.insert(0, separator);
1273    }
1274    out
1275}
1276
1277fn pascal_case(value: &str) -> String {
1278    let mut out = String::new();
1279    for part in value
1280        .split(|ch: char| !ch.is_ascii_alphanumeric())
1281        .filter(|part| !part.is_empty())
1282    {
1283        let mut chars = part.chars();
1284        if let Some(first) = chars.next() {
1285            out.push(first.to_ascii_uppercase());
1286            for ch in chars {
1287                out.push(ch.to_ascii_lowercase());
1288            }
1289        }
1290    }
1291    if out.is_empty() {
1292        out.push_str("Generated");
1293    }
1294    if out.starts_with(|ch: char| ch.is_ascii_digit()) {
1295        out.insert_str(0, "Generated");
1296    }
1297    out
1298}
1299
1300fn title_case(value: &str) -> String {
1301    value
1302        .split(['-', '_'])
1303        .filter(|part| !part.is_empty())
1304        .map(|part| {
1305            let mut chars = part.chars();
1306            match chars.next() {
1307                Some(first) => format!("{}{}", first.to_ascii_uppercase(), chars.as_str()),
1308                None => String::new(),
1309            }
1310        })
1311        .collect::<Vec<_>>()
1312        .join(" ")
1313}
1314
1315fn fill(mut template: String, replacements: &[(&str, &str)]) -> String {
1316    for (needle, value) in replacements {
1317        template = template.replace(needle, value);
1318    }
1319    template
1320}
1321
1322fn cargo_toml(project_name: &str, options: &NewSiteOptions) -> String {
1323    // Mirrors `new_site`: font wiring is tied to the generated Axum crate
1324    // root, since the include! boilerplate lives in src/main.rs.
1325    let has_fonts = !options.empty && options.server == ServerIntegration::Axum;
1326    let mut deps = vec![
1327        "proa_core = \"0.3.0\"".to_string(),
1328        "proa_macros = \"0.3.0\"".to_string(),
1329    ];
1330    if has_fonts {
1331        deps.extend([
1332            "proa_fonts = \"0.1.0\"".to_string(),
1333            "proa_fonts_macros = \"0.1.0\"".to_string(),
1334        ]);
1335    }
1336    if options.server == ServerIntegration::Axum {
1337        deps.extend([
1338            "proa_framework_axum = \"0.3.0\"".to_string(),
1339            "anyhow = \"1\"".to_string(),
1340            "axum = \"0.7\"".to_string(),
1341            "tokio = { version = \"1\", features = [\"macros\", \"rt-multi-thread\"] }".to_string(),
1342            "tower = \"0.5\"".to_string(),
1343            "tower-http = { version = \"0.6\", features = [\"fs\", \"set-header\", \"trace\"] }"
1344                .to_string(),
1345            "tracing = \"0.1\"".to_string(),
1346            "tracing-subscriber = \"0.3\"".to_string(),
1347        ]);
1348    }
1349    if options.docs == DocsIntegration::ProaDocs || options.blog {
1350        deps.push("proa_docs = { version = \"0.2.0\", features = [\"axum\"] }".to_string());
1351    }
1352
1353    let has_docs_build = options.docs == DocsIntegration::ProaDocs || options.blog;
1354    let mut build_deps = String::new();
1355    if has_fonts || has_docs_build {
1356        build_deps.push_str("\n[build-dependencies]\n");
1357        if has_fonts {
1358            build_deps.push_str("proa_fonts_build = \"0.1.0\"\n");
1359        }
1360        if has_docs_build {
1361            build_deps.push_str("proa_docs_build = \"0.2.0\"\n");
1362        }
1363    }
1364
1365    format!(
1366        "[package]\nname = \"{project_name}\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[dependencies]\n{}\n{build_deps}\n[profile.release]\nlto = \"thin\"\ncodegen-units = 1\nstrip = true\n",
1367        deps.join("\n")
1368    )
1369}
1370
1371fn cargo_config_toml() -> String {
1372    "# Fetch Git dependencies using your Git credential helpers and proxy settings.\n[net]\ngit-fetch-with-cli = true\n".to_string()
1373}
1374
1375fn dev_script() -> String {
1376    include_str!("../templates/dev.sh").to_string()
1377}
1378
1379fn build_script() -> String {
1380    include_str!("../templates/build.sh").to_string()
1381}
1382
1383fn watch_lock_script() -> String {
1384    include_str!("../templates/watch-lock.sh").to_string()
1385}
1386
1387fn readme(project_name: &str, deploy: DeployTarget) -> String {
1388    let deploy_section = if deploy == DeployTarget::Coolify {
1389        "\n## Deploy\n\nThis project includes a Coolify deployment preset. Read `COOLIFY.md`, then deploy with the generated `Dockerfile`.\n"
1390    } else {
1391        ""
1392    };
1393    format!(
1394        "# {}\n\nGenerated with `proa new site`.\n\nDevelop with a watching server:\n\n```bash\nbash scripts/dev.sh\n```\n\nBuild the release binary:\n\n```bash\nbash scripts/build.sh\n```\n{}",
1395        title_case(project_name),
1396        deploy_section
1397    )
1398}
1399
1400fn gitignore() -> String {
1401    "/target\n/public/styles.css\n.env\n".to_string()
1402}
1403
1404fn agents_md() -> String {
1405    "# Agent instructions\n\nFollow the Proa site structure: reusable render components in `src/components/`, route surfaces in `src/pages/`, shared shells in `src/layouts/`, and route/nav data in `src/data/`.\n\nAuthor ordinary synchronous components with explicit `impl<L: DataLoader> WebRenderSync<L>` blocks. Their `fn render(self, cx: &mut WebContext<L>) -> Result<(), WriteError>` implementations should end in `html_sync! { ... }.render(cx)`. Add `C: WebRenderSync<L>` for generic child renderables. `WebContext<L>` owns the default `RenderBuffer`; only lower-level custom-writer integrations need the second `B` parameter. When a component actually awaits, implement the canonical `WebRender<L>` signature directly and return `RenderOutcome::pending(async move { ... })`; bridge synchronous children only at that async composition boundary.\n\nOpaque SSR components use no RSJS attribute. Put `#[rsjs(component)]` on a real render-trait impl only when it must participate in analyzed composition, and use `#[rsjs(component, client)]` when that component originates signals, event handlers, queries, mutations, shared-state acquisition, node refs, or browser work. Do not use inherent render shorthand, `async fn render` sugar, or component `clients(...)` allowlists; annotate each portable browser helper once with `#[rsjs::client]`.\n\nInside an analyzed component, a direct inbound read such as `self.label` is eligible to remain live when a parent supplies a live value. A `signal(self.value)` initializer samples that inbound value once for the child-owned signal. Use `rsjs::server_only(...)` or `rsjs::server_attr(...)` only when the contract intentionally takes a per-render server snapshot.\n\nRun `proa site check` after structural changes.\n".to_string()
1406}
1407
1408fn components_mod() -> String {
1409    "// Reusable Proa render components live here.\n".to_string()
1410}
1411
1412fn pages_mod(has_docs: bool, has_blog: bool) -> String {
1413    let mut out = "pub mod home;\n".to_string();
1414    if has_docs {
1415        out.push_str("pub mod docs;\n");
1416    }
1417    if has_blog {
1418        out.push_str("pub mod blog;\n");
1419    }
1420    out
1421}
1422
1423fn routes_data(has_docs: bool, has_blog: bool) -> String {
1424    let mut routes = vec!["\"/\""];
1425    if has_docs {
1426        routes.push("\"/docs\"");
1427        routes.push("\"/docs/*path\"");
1428    }
1429    if has_blog {
1430        routes.push("\"/blog\"");
1431        routes.push("\"/blog/*path\"");
1432    }
1433    format!("pub const ROUTES: &[&str] = &[{}];\n", routes.join(", "))
1434}
1435
1436fn nav_data() -> String {
1437    "pub struct NavItem {\n    pub label: &'static str,\n    pub href: &'static str,\n}\n\npub const NAV_ITEMS: &[NavItem] = &[\n    NavItem { label: \"Home\", href: \"/\" },\n];\n".to_string()
1438}
1439
1440fn root_layout() -> String {
1441    r#"use crate::data::nav::NAV_ITEMS;
1442use proa_core::{raw_text_ok, DataLoader, WebContext, WebRenderSync, WriteError};
1443use proa_macros::html_sync;
1444
1445pub struct PageMeta {
1446    pub title: &'static str,
1447    pub description: &'static str,
1448    pub path: &'static str,
1449}
1450
1451pub struct RootDocument<C> {
1452    pub meta: PageMeta,
1453    pub content: C,
1454}
1455
1456struct SiteNav;
1457
1458impl<L: DataLoader> WebRenderSync<L> for SiteNav {
1459    fn render(self, cx: &mut WebContext<L>) -> Result<(), WriteError> {
1460        html_sync! {
1461            {for item in NAV_ITEMS {
1462                html_sync! {
1463                    <a class="text-sm text-zinc-600 hover:text-zinc-900" href={item.href}>
1464                        {item.label}
1465                    </a>
1466                }
1467            }}
1468        }
1469        .render(cx)
1470    }
1471}
1472
1473impl<L, C> WebRenderSync<L> for RootDocument<C>
1474where
1475    L: DataLoader,
1476    C: WebRenderSync<L>,
1477{
1478    fn render(self, cx: &mut WebContext<L>) -> Result<(), WriteError> {
1479        html_sync! {
1480            <!DOCTYPE html>
1481            <html lang="en">
1482                <head>
1483                    <meta charset="utf-8" />
1484                    <meta name="viewport" content="width=device-width, initial-scale=1" />
1485                    <title>{raw_text_ok(self.meta.title)}</title>
1486                    <meta name="description" content={self.meta.description} />
1487                    <meta name="proa-route" content={self.meta.path} />
1488                    <link rel="icon" href="/static/favicon.svg" type="image/svg+xml" />
1489                    <link rel="stylesheet" href="/static/styles.css" />
1490                </head>
1491                <body>
1492                    <header class="mx-auto max-w-4xl px-6 pt-8">
1493                        <nav class="flex items-center gap-6">{SiteNav}</nav>
1494                    </header>
1495                    {self.content}
1496                </body>
1497            </html>
1498        }
1499        .render(cx)
1500    }
1501}
1502"#
1503    .to_string()
1504}
1505
1506// proa-perf-ok(scope): trusted scaffold emitter assembles Rust source, not response HTML
1507fn home_page(title: &str, axum: bool) -> String {
1508    let response = if axum {
1509        "use axum::response::Html;\n\npub async fn handler() -> Html<String> {\n    // proa-perf-ok: top-level Axum response finalization owns the HTML String\n    Html(render())\n}\n\n"
1510    } else {
1511        ""
1512    };
1513
1514    fill(
1515        format!(
1516            r#"{}use proa_core::{{
1517    render_to_string, DataLoader, WebContext, WebRenderSync, WriteError,
1518}};
1519use proa_macros::html_sync;
1520
1521use crate::layouts::root::{{PageMeta, RootDocument}};
1522
1523pub fn render() -> String {{
1524    // proa-perf-ok: generated scaffold owns the top-level HTML String at the HTTP boundary
1525    render_to_string(RootDocument {{
1526        meta: PageMeta {{
1527            title: "__TITLE__",
1528            description: "A Proa site.",
1529            path: "/",
1530        }},
1531        content: HomePage,
1532    }})
1533}}
1534
1535struct HomePage;
1536
1537impl<L: DataLoader> WebRenderSync<L> for HomePage {{
1538    fn render(self, cx: &mut WebContext<L>) -> Result<(), WriteError> {{
1539        html_sync! {{
1540            <main class="mx-auto max-w-4xl px-6 py-16">
1541                <p class="font-mono text-sm uppercase tracking-[0.18em] text-zinc-500">"Proa"</p>
1542                <h1 class="mt-4 text-5xl font-semibold tracking-[-0.04em]">"__TITLE__"</h1>
1543                <p class="mt-4 text-lg leading-8 text-zinc-600">
1544                    "Edit src/pages/home.rs to start building."
1545                </p>
1546            </main>
1547        }}
1548        .render(cx)
1549    }}
1550}}
1551
1552#[cfg(test)]
1553mod tests {{
1554    #[test]
1555    fn home_page_renders() {{
1556        let html = super::render();
1557        assert!(html.starts_with("<!DOCTYPE html>"));
1558        assert!(html.contains("__TITLE__"));
1559        assert!(crate::data::routes::ROUTES.contains(&"/"));
1560    }}
1561}}
1562"#,
1563            response
1564        ),
1565        &[("__TITLE__", title)],
1566    )
1567}
1568
1569fn docs_page(axum: bool) -> String {
1570    docs_like_page("DOCS", "docs", "/docs", axum)
1571}
1572
1573fn blog_page(axum: bool) -> String {
1574    docs_like_page("BLOG", "blog", "/blog", axum)
1575}
1576
1577fn docs_like_page(const_name: &str, dir: &str, base_path: &str, axum: bool) -> String {
1578    let template = if axum {
1579        r#"use axum::{extract::Path, response::Response};
1580use proa_docs::Docs;
1581
1582static __CONST__: Docs = proa_docs::include_docs!("__DIR__");
1583
1584pub async fn handler() -> Response {
1585    proa_docs::adapter::axum::response(&__CONST__, "__BASE__")
1586}
1587
1588pub async fn path_handler(Path(path): Path<String>) -> Response {
1589    let path = if path.trim_matches('/').is_empty() {
1590        "__BASE__".to_string()
1591    } else {
1592        format!("__BASE__/{}", path.trim_matches('/'))
1593    };
1594    proa_docs::adapter::axum::response(&__CONST__, &path)
1595}
1596"#
1597    } else {
1598        r#"use proa_docs::{Docs, DocsResponse};
1599
1600static __CONST__: Docs = proa_docs::include_docs!("__DIR__");
1601
1602pub fn render(path: &str) -> DocsResponse {
1603    proa_docs::render(&__CONST__, path)
1604}
1605"#
1606    };
1607    fill(
1608        template.to_string(),
1609        &[
1610            ("__CONST__", const_name),
1611            ("__DIR__", dir),
1612            ("__BASE__", base_path),
1613        ],
1614    )
1615}
1616
1617fn main_rs(has_fonts: bool, has_docs: bool, has_blog: bool) -> String {
1618    let fonts_mod = if has_fonts {
1619        "\n// Generated font consts for google_font!/local_font! declarations.\nmod __proa_fonts_generated { include!(concat!(env!(\"OUT_DIR\"), \"/proa_fonts.rs\")); }\n"
1620    } else {
1621        ""
1622    };
1623    let fonts_route = if has_fonts {
1624        "        .nest_service(\"/fonts\", static_assets::fonts_service())\n"
1625    } else {
1626        ""
1627    };
1628    let mut routes = "        .route(\"/\", get(pages::home::handler))\n        .route(\"/healthz\", get(healthz))\n".to_string();
1629    if has_docs {
1630        routes.push_str("        .route(\"/docs\", get(pages::docs::handler))\n");
1631        routes.push_str("        .route(\"/docs/*path\", get(pages::docs::path_handler))\n");
1632    }
1633    if has_blog {
1634        routes.push_str("        .route(\"/blog\", get(pages::blog::handler))\n");
1635        routes.push_str("        .route(\"/blog/*path\", get(pages::blog::path_handler))\n");
1636    }
1637
1638    fill(
1639        r#"use axum::{
1640    http::header::{HeaderValue, REFERRER_POLICY, X_CONTENT_TYPE_OPTIONS, X_FRAME_OPTIONS},
1641    routing::get,
1642    Router,
1643};
1644use std::time::Duration;
1645use tower_http::{set_header::SetResponseHeaderLayer, trace::TraceLayer};
1646
1647mod components;
1648mod data;
1649mod layouts;
1650mod pages;
1651mod static_assets;
1652__FONTS_MOD__
1653const SHUTDOWN_DRAIN_TIMEOUT: Duration = Duration::from_secs(30);
1654
1655async fn healthz() -> &'static str {
1656    "ok"
1657}
1658
1659async fn robots_txt() -> &'static str {
1660    "User-agent: *\nAllow: /\n"
1661}
1662
1663#[tokio::main]
1664async fn main() -> anyhow::Result<()> {
1665    tracing_subscriber::fmt().init();
1666    let host = std::env::var("HOST").unwrap_or_else(|_| "127.0.0.1".to_string());
1667    let port = std::env::var("PORT")
1668        .ok()
1669        .and_then(|port| port.parse::<u16>().ok())
1670        .unwrap_or(3000);
1671
1672    let app = Router::new()
1673__ROUTES__        .route("/robots.txt", get(robots_txt))
1674__FONTS_ROUTE__        .nest_service("/static", static_assets::service())
1675        .layer(TraceLayer::new_for_http())
1676        .layer(SetResponseHeaderLayer::if_not_present(
1677            X_CONTENT_TYPE_OPTIONS,
1678            HeaderValue::from_static("nosniff"),
1679        ))
1680        .layer(SetResponseHeaderLayer::if_not_present(
1681            X_FRAME_OPTIONS,
1682            HeaderValue::from_static("DENY"),
1683        ))
1684        .layer(SetResponseHeaderLayer::if_not_present(
1685            REFERRER_POLICY,
1686            HeaderValue::from_static("strict-origin-when-cross-origin"),
1687        ));
1688
1689    let listener = tokio::net::TcpListener::bind((host.as_str(), port)).await?;
1690    tracing::info!("listening on http://{}", listener.local_addr()?);
1691    tracing::info!(routes = ?data::routes::ROUTES, "registered page routes");
1692    proa_framework_axum::serve(listener, app, SHUTDOWN_DRAIN_TIMEOUT).await?;
1693    Ok(())
1694}
1695"#
1696        .to_string(),
1697        &[
1698            ("__FONTS_MOD__", fonts_mod),
1699            ("__FONTS_ROUTE__", fonts_route),
1700            ("__ROUTES__", &routes),
1701        ],
1702    )
1703}
1704
1705fn static_assets_rs(has_fonts: bool) -> String {
1706    let fonts_service = if has_fonts {
1707        r#"
1708/// Vendored font files are content-hashed, so they can be cached forever.
1709pub fn fonts_service() -> Router {
1710    serve_dir(
1711        static_root().join("fonts"),
1712        "public, max-age=31536000, immutable",
1713    )
1714}
1715"#
1716    } else {
1717        ""
1718    };
1719    fill(
1720        r#"use std::{env, path::PathBuf};
1721
1722use axum::{
1723    http::header::{HeaderValue, CACHE_CONTROL, X_CONTENT_TYPE_OPTIONS},
1724    Router,
1725};
1726use tower::ServiceBuilder;
1727use tower_http::{services::ServeDir, set_header::SetResponseHeaderLayer};
1728
1729fn static_root() -> PathBuf {
1730    env::var_os("STATIC_DIR")
1731        .map(PathBuf::from)
1732        .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("public"))
1733}
1734
1735fn serve_dir(dir: PathBuf, cache_control: &'static str) -> Router {
1736    Router::new().nest_service(
1737        "/",
1738        ServiceBuilder::new()
1739            .layer(SetResponseHeaderLayer::if_not_present(
1740                CACHE_CONTROL,
1741                HeaderValue::from_static(cache_control),
1742            ))
1743            .layer(SetResponseHeaderLayer::if_not_present(
1744                X_CONTENT_TYPE_OPTIONS,
1745                HeaderValue::from_static("nosniff"),
1746            ))
1747            .service(ServeDir::new(dir)),
1748    )
1749}
1750
1751pub fn service() -> Router {
1752    // Debug builds revalidate on every load so `proa dev` asset rebuilds show
1753    // up on refresh; release builds keep the shared one-hour cache.
1754    let cache_control = if cfg!(debug_assertions) {
1755        "no-cache"
1756    } else {
1757        "public, max-age=3600"
1758    };
1759    serve_dir(static_root(), cache_control)
1760}
1761__FONTS_SERVICE__"#
1762            .to_string(),
1763        &[("__FONTS_SERVICE__", fonts_service)],
1764    )
1765}
1766
1767fn dockerfile(project_name: &str) -> String {
1768    format!(
1769        r#"# syntax=docker/dockerfile:1.7
1770
1771FROM rust:1.93-bookworm AS build
1772WORKDIR /app
1773
1774COPY . .
1775
1776# Public Proa dependencies resolve from crates.io without credentials.
1777RUN cargo build --release --bin {project_name}
1778
1779FROM debian:bookworm-slim AS runtime
1780WORKDIR /app
1781RUN apt-get update \
1782    && apt-get install -y --no-install-recommends ca-certificates \
1783    && rm -rf /var/lib/apt/lists/*
1784
1785COPY --from=build /app/target/release/{project_name} /usr/local/bin/{project_name}
1786COPY --from=build /app/public /app/public
1787
1788ENV HOST=0.0.0.0
1789ENV PORT=3000
1790ENV STATIC_DIR=/app/public
1791ENV RUST_LOG=info
1792
1793EXPOSE 3000
1794CMD ["{project_name}"]
1795"#
1796    )
1797}
1798
1799fn dockerignore() -> String {
1800    r#".git
1801target
1802.env
1803.env.*
1804!.env.example
1805node_modules
1806.DS_Store
1807"#
1808    .to_string()
1809}
1810
1811fn coolify_env_example() -> String {
1812    r#"# Runtime variables for Coolify.
1813HOST=0.0.0.0
1814PORT=3000
1815STATIC_DIR=/app/public
1816RUST_LOG=info
1817
1818"#
1819    .to_string()
1820}
1821
1822fn coolify_readme(project_name: &str) -> String {
1823    format!(
1824        r#"# Coolify deployment
1825
1826This Proa app is ready for Coolify's Dockerfile deployment path.
1827
1828## Local image check
1829
1830```bash
1831docker build -t {project_name} .
1832
1833docker run --rm -p 3000:3000 -e PORT=3000 {project_name}
1834curl -fsS http://127.0.0.1:3000/healthz
1835```
1836
1837## Coolify settings
1838
1839- Deployment type: Dockerfile
1840- Exposed port: `3000`
1841- Health check path: `/healthz`
1842- Runtime variables: copy from `coolify.env.example`
1843
1844Proa dependencies resolve from crates.io at build time. No registry or GitHub
1845credentials are required.
1846
1847## Pull request previews
1848
1849Coolify can create pull request preview deployments with unique URLs. Use the
1850GitHub App integration, add a wildcard DNS record such as
1851`*.preview.example.com`, then enable Preview Deployments with a URL template
1852such as `{{{{pr_id}}}}.preview.example.com`.
1853"#
1854    )
1855}
1856
1857fn build_rs(has_fonts: bool, has_docs: bool, has_blog: bool) -> String {
1858    let has_docs_build = has_docs || has_blog;
1859    let mut out = String::new();
1860    if has_docs_build {
1861        out.push_str("use std::{env, path::PathBuf};\n\n");
1862    }
1863    out.push_str("fn main() {\n");
1864    if has_fonts {
1865        out.push_str(
1866            r#"    println!("cargo:rerun-if-changed=src");
1867    println!("cargo:rerun-if-changed=proa-fonts.lock");
1868    let fonts = proa_fonts_build::collect::CollectOptions::from_build_env()
1869        .expect("cargo build env");
1870    if let Err(error) = proa_fonts_build::collect::run(&fonts) {
1871        panic!("proa fonts: {error}");
1872    }
1873"#,
1874        );
1875    }
1876    if has_docs_build {
1877        if has_fonts {
1878            out.push('\n');
1879        }
1880        out.push_str(
1881            r#"    let manifest_dir = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").expect("manifest dir"));
1882    println!("cargo:rerun-if-changed=build.rs");
1883    println!("cargo:rerun-if-changed={}", manifest_dir.join("src/docs").display());
1884    println!("cargo:rerun-if-changed={}", manifest_dir.join("src/blog").display());
1885
1886    let config = proa_docs_build::Config::new()
1887"#,
1888        );
1889        if has_docs {
1890            out.push_str(
1891                r#"        .source(
1892            proa_docs_build::DocsSource::new(manifest_dir.join("src/docs"))
1893                .out_dir_name("docs")
1894                .base_path("/docs")
1895                .site_name("Docs"),
1896        )
1897"#,
1898            );
1899        }
1900        if has_blog {
1901            out.push_str(
1902                r#"        .source(
1903            proa_docs_build::DocsSource::new(manifest_dir.join("src/blog"))
1904                .out_dir_name("blog")
1905                .base_path("/blog")
1906                .site_name("Blog"),
1907        )
1908"#,
1909            );
1910        }
1911        out.push_str(";\n\n    proa_docs_build::compile(config);\n");
1912    }
1913    out.push_str("}\n");
1914    out
1915}
1916
1917fn docs_index() -> String {
1918    "---\ntitle: Introduction\ndescription: Start here.\nnav_order: 1\n---\n\n# Introduction\n\nWelcome to your Proa docs.\n".to_string()
1919}
1920
1921fn docs_getting_started() -> String {
1922    "---\ntitle: Getting Started\ndescription: Your first Proa page.\nnav_order: 2\n---\n\n# Getting Started\n\nEdit `src/docs/getting-started.mdx`.\n".to_string()
1923}
1924
1925fn blog_first_post() -> String {
1926    "---\ntitle: First Post\ndescription: Your first Proa blog post.\n---\n\n# First Post\n\nEdit `src/blog/first-post.mdx`.\n".to_string()
1927}
1928
1929fn tailwind_input_css() -> String {
1930    // The layer declaration has to precede `@import "tailwindcss"`. Tailwind
1931    // otherwise declares `@layer theme, base, components, utilities` itself,
1932    // whichever declaration the browser sees first wins, and `proa-compat`
1933    // lands last — where a component stylesheet's hand-written colour
1934    // fallbacks outrank the real generated utilities and buttons come out
1935    // without their padding or radius.
1936    //
1937    // `proa-compat` is the layer Proa UI's runtime CSS wraps those fallbacks
1938    // in. Declaring it here is inert for a site that never installs a
1939    // component, and correct in advance for one that does.
1940    "@layer theme, base, proa-compat, components, utilities;\n\n\
1941     @import \"tailwindcss\";\n\n@source \"../src/**/*.rs\";\n\nbody {\n  margin: 0;\n}\n"
1942        .to_string()
1943}
1944
1945fn generated_styles_placeholder() -> String {
1946    "/* Generated CSS placeholder. Run the Tailwind build command from the CLI output. */\n"
1947        .to_string()
1948}
1949
1950fn plain_css() -> String {
1951    ":root {\n  color: #18181b;\n  background: #ffffff;\n}\n\n* {\n  box-sizing: border-box;\n}\n\nbody {\n  margin: 0;\n  font-family: system-ui, sans-serif;\n}\n".to_string()
1952}
1953
1954fn favicon_svg() -> String {
1955    r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><path d="M13 36.5C17.6 25.7 25.5 18 36.2 13L34.8 33.5L13 36.5Z" fill="#dd7627"/><path d="M10 39.5C16.2 39.8 23.4 39.2 31.3 37.9C41.2 36.3 49 33.7 54 30.2C50.9 39.8 42.3 46.5 30 47.8C18.7 49 11.5 46 10 39.5Z" fill="#18181b"/></svg>
1956"##
1957    .to_string()
1958}
1959
1960fn component_source(
1961    struct_name: &str,
1962    data_attr: &str,
1963    children: bool,
1964    asynchronous: bool,
1965    markdown: bool,
1966    recipe: bool,
1967    test: bool,
1968) -> String {
1969    let base = if recipe {
1970        "use super::recipe::BASE_CLASS;\n"
1971    } else {
1972        "const BASE_CLASS: &str = \"rounded-lg border p-4\";\n"
1973    };
1974    let template = match (children, asynchronous) {
1975        (true, false) => {
1976            r#"use proa_core::{ClassList, DataLoader, WebContext, WebRenderSync, WriteError};
1977use proa_macros::html_sync;
1978
1979__BASE__
1980pub struct __STRUCT__<C = ()> {
1981    pub class: Option<&'static str>,
1982    pub children: C,
1983}
1984
1985impl<C> __STRUCT__<C> {
1986    pub const fn new(children: C) -> Self {
1987        Self { class: None, children }
1988    }
1989
1990    pub const fn class(mut self, class: &'static str) -> Self {
1991        self.class = Some(class);
1992        self
1993    }
1994}
1995
1996impl<L, C> WebRenderSync<L> for __STRUCT__<C>
1997where
1998    L: DataLoader,
1999    C: WebRenderSync<L>,
2000{
2001    fn render(self, cx: &mut WebContext<L>) -> Result<(), WriteError> {
2002        let classes = ClassList::<2>::new().add(BASE_CLASS).add_opt(self.class);
2003        html_sync! {
2004            <div __DATA__ class={classes}>{self.children}</div>
2005        }
2006        .render(cx)
2007    }
2008}
2009"#
2010        }
2011        (false, false) => {
2012            r#"use proa_core::{ClassList, DataLoader, WebContext, WebRenderSync, WriteError};
2013use proa_macros::html_sync;
2014
2015__BASE__
2016#[derive(Debug, Clone, Copy, Default)]
2017pub struct __STRUCT__ {
2018    pub class: Option<&'static str>,
2019}
2020
2021impl __STRUCT__ {
2022    pub const fn new() -> Self {
2023        Self { class: None }
2024    }
2025
2026    pub const fn class(mut self, class: &'static str) -> Self {
2027        self.class = Some(class);
2028        self
2029    }
2030}
2031
2032impl<L: DataLoader> WebRenderSync<L> for __STRUCT__ {
2033    fn render(self, cx: &mut WebContext<L>) -> Result<(), WriteError> {
2034        let classes = ClassList::<2>::new().add(BASE_CLASS).add_opt(self.class);
2035        html_sync! {
2036            <div __DATA__ class={classes}>"__STRUCT__"</div>
2037        }
2038        .render(cx)
2039    }
2040}
2041"#
2042        }
2043        (true, true) => {
2044            r#"use std::future::Future;
2045
2046use proa_core::{ClassList, DataLoader, RenderOutcome, WebContext, WebRender, WriteError};
2047use proa_macros::html;
2048
2049__BASE__
2050pub struct __STRUCT__<C = ()> {
2051    pub class: Option<&'static str>,
2052    pub children: C,
2053}
2054
2055impl<C> __STRUCT__<C> {
2056    pub const fn new(children: C) -> Self {
2057        Self { class: None, children }
2058    }
2059
2060    pub const fn class(mut self, class: &'static str) -> Self {
2061        self.class = Some(class);
2062        self
2063    }
2064}
2065
2066impl<L, C> WebRender<L> for __STRUCT__<C>
2067where
2068    L: DataLoader,
2069    C: WebRender<L> + Send + 'static,
2070{
2071    fn render(self, cx: &mut WebContext<L>) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
2072        RenderOutcome::pending(async move {
2073            let classes = ClassList::<2>::new().add(BASE_CLASS).add_opt(self.class);
2074            html! {
2075                <div __DATA__ class={classes}>{self.children}</div>
2076            }
2077            .render(cx)
2078            .resolve()
2079            .await
2080        })
2081    }
2082}
2083"#
2084        }
2085        (false, true) => {
2086            r#"use std::future::Future;
2087
2088use proa_core::{ClassList, DataLoader, RenderOutcome, WebContext, WebRender, WriteError};
2089use proa_macros::html;
2090
2091__BASE__
2092#[derive(Debug, Clone, Copy, Default)]
2093pub struct __STRUCT__ {
2094    pub class: Option<&'static str>,
2095}
2096
2097impl __STRUCT__ {
2098    pub const fn new() -> Self {
2099        Self { class: None }
2100    }
2101
2102    pub const fn class(mut self, class: &'static str) -> Self {
2103        self.class = Some(class);
2104        self
2105    }
2106}
2107
2108impl<L: DataLoader> WebRender<L> for __STRUCT__ {
2109    fn render(self, cx: &mut WebContext<L>) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
2110        RenderOutcome::pending(async move {
2111            let classes = ClassList::<2>::new().add(BASE_CLASS).add_opt(self.class);
2112            let content = proa_core::await_component(async { proa_core::text::text("__STRUCT__") });
2113            html! {
2114                <div __DATA__ class={classes}>{content}</div>
2115            }
2116            .render(cx)
2117            .resolve()
2118            .await
2119        })
2120    }
2121}
2122"#
2123        }
2124    };
2125
2126    let markdown_source = if markdown {
2127        if children {
2128            r####"
2129use proa_core::{MdRenderSync, WriteBuf};
2130use proa_macros::md_sync;
2131
2132impl<L: proa_core::DataLoader, B, C> MdRenderSync<L, B> for __STRUCT__<C>
2133where
2134    B: WriteBuf,
2135    C: MdRenderSync<L, B>,
2136{
2137    fn render_md(self, cx: &mut WebContext<L, B>) -> Result<(), WriteError> {
2138        md_sync! { r###"
2139### __STRUCT__
2140
2141{self.children}
2142"###
2143        }
2144        .render_md(cx)
2145    }
2146}
2147"####
2148        } else {
2149            r####"
2150use proa_core::{MdRenderSync, WriteBuf};
2151use proa_macros::md_sync;
2152
2153impl<L: proa_core::DataLoader, B: WriteBuf> MdRenderSync<L, B> for __STRUCT__ {
2154    fn render_md(self, cx: &mut WebContext<L, B>) -> Result<(), WriteError> {
2155        md_sync! { r###"__STRUCT__"### }.render_md(cx)
2156    }
2157}
2158"####
2159        }
2160    } else {
2161        ""
2162    };
2163
2164    let test_source = if test {
2165        match (children, asynchronous) {
2166            (true, false) => {
2167                r#"
2168#[cfg(test)]
2169mod tests {
2170    use super::*;
2171    use proa_core::{text::text, WebContext, WebRenderSync};
2172
2173    #[test]
2174    fn renders_dynamic_children_and_the_component_contract() {
2175        let mut cx = WebContext::new();
2176        __STRUCT__::new(text("dynamic child")).render(&mut cx).unwrap();
2177        let html = cx.into_output().into_string();
2178        assert!(html.contains("__DATA__"));
2179        assert!(html.contains("dynamic child"));
2180    }
2181}
2182"#
2183            }
2184            (false, false) => {
2185                r#"
2186#[cfg(test)]
2187mod tests {
2188    use super::*;
2189    use proa_core::{WebContext, WebRenderSync};
2190
2191    #[test]
2192    fn renders_the_component_contract() {
2193        let mut cx = WebContext::new();
2194        __STRUCT__::new().render(&mut cx).unwrap();
2195        let html = cx.into_output().into_string();
2196        assert!(html.contains("__DATA__"));
2197    }
2198}
2199"#
2200            }
2201            (true, true) => {
2202                r#"
2203#[cfg(test)]
2204mod tests {
2205    use super::*;
2206    use proa_core::{text::text, WebContext, WebRender};
2207
2208    #[tokio::test]
2209    async fn renders_dynamic_children_and_the_component_contract() {
2210        let mut cx = WebContext::new();
2211        __STRUCT__::new(proa_core::to_async(text("dynamic child")))
2212            .render(&mut cx)
2213            .resolve()
2214            .await
2215            .unwrap();
2216        let html = cx.into_output().into_string();
2217        assert!(html.contains("__DATA__"));
2218        assert!(html.contains("dynamic child"));
2219    }
2220}
2221"#
2222            }
2223            (false, true) => {
2224                r#"
2225#[cfg(test)]
2226mod tests {
2227    use super::*;
2228    use proa_core::{WebContext, WebRender};
2229
2230    #[tokio::test]
2231    async fn renders_the_component_contract() {
2232        let mut cx = WebContext::new();
2233        __STRUCT__::new()
2234            .render(&mut cx)
2235            .resolve()
2236            .await
2237            .unwrap();
2238        let html = cx.into_output().into_string();
2239        assert!(html.contains("__DATA__"));
2240    }
2241}
2242"#
2243            }
2244        }
2245    } else {
2246        ""
2247    };
2248
2249    fill(
2250        format!("{template}{markdown_source}{test_source}"),
2251        &[
2252            ("__BASE__", base),
2253            ("__STRUCT__", struct_name),
2254            ("__DATA__", data_attr),
2255        ],
2256    )
2257}
2258
2259fn component_recipe_source(struct_name: &str) -> String {
2260    fill(
2261        r#"pub const BASE_CLASS: &str = "rounded-lg border p-4";
2262
2263pub struct __STRUCT__Recipe {
2264    pub class: &'static str,
2265}
2266
2267impl Default for __STRUCT__Recipe {
2268    fn default() -> Self {
2269        Self { class: BASE_CLASS }
2270    }
2271}
2272"#
2273        .to_string(),
2274        &[("__STRUCT__", struct_name)],
2275    )
2276}
2277
2278fn section_layout_source(struct_name: &str) -> String {
2279    fill(
2280        r#"use proa_core::{DataLoader, WebContext, WebRenderSync, WriteError};
2281use proa_macros::html_sync;
2282
2283pub struct __STRUCT__<C> {
2284    pub content: C,
2285}
2286
2287impl<C> __STRUCT__<C> {
2288    pub const fn new(content: C) -> Self {
2289        Self { content }
2290    }
2291}
2292
2293impl<L, C> WebRenderSync<L> for __STRUCT__<C>
2294where
2295    L: DataLoader,
2296    C: WebRenderSync<L>,
2297{
2298    fn render(self, cx: &mut WebContext<L>) -> Result<(), WriteError> {
2299        html_sync! {
2300            <section class="mx-auto max-w-5xl px-6 py-12">
2301                {self.content}
2302            </section>
2303        }
2304        .render(cx)
2305    }
2306}
2307"#
2308        .to_string(),
2309        &[("__STRUCT__", struct_name)],
2310    )
2311}
2312
2313fn document_layout_source(struct_name: &str) -> String {
2314    fill(
2315        r#"// proa:document-root
2316use proa_core::{raw_text_ok, DataLoader, WebContext, WebRenderSync, WriteError};
2317use proa_macros::html_sync;
2318
2319pub struct __STRUCT__<C> {
2320    pub title: &'static str,
2321    pub description: &'static str,
2322    pub content: C,
2323}
2324
2325impl<L, C> WebRenderSync<L> for __STRUCT__<C>
2326where
2327    L: DataLoader,
2328    C: WebRenderSync<L>,
2329{
2330    fn render(self, cx: &mut WebContext<L>) -> Result<(), WriteError> {
2331        html_sync! {
2332            <!DOCTYPE html>
2333            <html lang="en">
2334                <head>
2335                    <meta charset="utf-8" />
2336                    <meta name="viewport" content="width=device-width, initial-scale=1" />
2337                    <title>{raw_text_ok(self.title)}</title>
2338                    <meta name="description" content={self.description} />
2339                </head>
2340                <body>{self.content}</body>
2341            </html>
2342        }
2343        .render(cx)
2344    }
2345}
2346"#
2347        .to_string(),
2348        &[("__STRUCT__", struct_name)],
2349    )
2350}
2351
2352fn data_source(name: &str) -> String {
2353    if name == "routes" {
2354        "pub const ROUTES: &[&str] = &[\"/\"];\n".to_string()
2355    } else if name == "nav" {
2356        nav_data()
2357    } else {
2358        format!(
2359            "pub struct {}Item {{\n    pub label: &'static str,\n}}\n\npub const ITEMS: &[{}Item] = &[];\n",
2360            pascal_case(name),
2361            pascal_case(name)
2362        )
2363    }
2364}
2365
2366#[cfg(test)]
2367mod tests {
2368    use super::*;
2369
2370    #[test]
2371    fn new_site_dry_run_writes_nothing() {
2372        let temp = tempfile::tempdir().unwrap();
2373        let root = temp.path().join("demo");
2374        new_site(NewSiteOptions {
2375            name: "demo".to_string(),
2376            root: root.clone(),
2377            template: "basic".to_string(),
2378            empty: false,
2379            server: ServerIntegration::Axum,
2380            tailwind: true,
2381            docs: DocsIntegration::None,
2382            blog: false,
2383            deploy: DeployTarget::None,
2384            skip_install: true,
2385            no_git: true,
2386            agents_md: true,
2387            dry_run: Some(DryRunFormat::Text),
2388            force: false,
2389            yes: true,
2390        })
2391        .unwrap();
2392
2393        assert!(!root.exists());
2394    }
2395
2396    #[test]
2397    fn new_site_writes_tailwind_sources_under_styles() {
2398        let temp = tempfile::tempdir().unwrap();
2399        let root = temp.path().join("styles-demo");
2400        new_site(NewSiteOptions {
2401            name: "styles-demo".to_string(),
2402            root: root.clone(),
2403            template: "basic".to_string(),
2404            empty: false,
2405            server: ServerIntegration::Axum,
2406            tailwind: true,
2407            docs: DocsIntegration::None,
2408            blog: false,
2409            deploy: DeployTarget::None,
2410            skip_install: true,
2411            no_git: true,
2412            agents_md: true,
2413            dry_run: None,
2414            force: false,
2415            yes: true,
2416        })
2417        .unwrap();
2418
2419        assert!(root.join("styles/input.css").exists());
2420        assert!(!root.join("styles/tailwind.config.cjs").exists());
2421        assert!(root.join("public/styles.css").exists());
2422        assert!(!root.join("frontend").exists());
2423
2424        // Layer order is load-bearing and fails silently: get it wrong and the
2425        // site still builds, but installed components render without their
2426        // padding or radius. Assert the declaration exists and, critically,
2427        // that it comes before the Tailwind import.
2428        let input = fs::read_to_string(root.join("styles/input.css")).unwrap();
2429        let layers = input
2430            .find("@layer theme, base, proa-compat, components, utilities;")
2431            .expect("input.css must declare the cascade layer order");
2432        let tailwind = input
2433            .find("@import \"tailwindcss\";")
2434            .expect("input.css must import Tailwind");
2435        assert!(
2436            layers < tailwind,
2437            "the layer declaration must precede the Tailwind import, or Tailwind's own \
2438             declaration wins and `proa-compat` is appended last"
2439        );
2440    }
2441
2442    #[test]
2443    fn apply_plan_rolls_back_files_on_mid_plan_failure() {
2444        let temp = tempfile::tempdir().unwrap();
2445        let root = temp.path().to_path_buf();
2446        let mut plan = ScaffoldPlan::new(root.clone());
2447        plan.write_file(root.join("ok.txt"), "hello".to_string());
2448        // Writing over a directory fails, aborting the plan midway.
2449        let blocked = root.join("blocked");
2450        fs::create_dir_all(&blocked).unwrap();
2451        plan.write_file(blocked.clone(), "nope".to_string());
2452
2453        apply_plan(&plan, true).unwrap_err();
2454        assert!(
2455            !root.join("ok.txt").exists(),
2456            "files from the failed plan should be rolled back"
2457        );
2458    }
2459
2460    #[test]
2461    fn apply_plan_rollback_restores_overwritten_files() {
2462        let temp = tempfile::tempdir().unwrap();
2463        let root = temp.path().to_path_buf();
2464        fs::write(root.join("keep.txt"), "original").unwrap();
2465        let mut plan = ScaffoldPlan::new(root.clone());
2466        plan.write_file(root.join("keep.txt"), "replaced".to_string());
2467        let blocked = root.join("blocked");
2468        fs::create_dir_all(&blocked).unwrap();
2469        plan.write_file(blocked.clone(), "nope".to_string());
2470
2471        apply_plan(&plan, true).unwrap_err();
2472        assert_eq!(
2473            fs::read_to_string(root.join("keep.txt")).unwrap(),
2474            "original",
2475            "overwritten files should be restored on rollback"
2476        );
2477    }
2478
2479    #[test]
2480    fn generate_component_updates_mod_file() {
2481        let temp = tempfile::tempdir().unwrap();
2482        fs::create_dir_all(temp.path().join("src/components")).unwrap();
2483        fs::write(temp.path().join("Cargo.toml"), "[package]\nname=\"demo\"\n").unwrap();
2484        fs::write(temp.path().join("src/components/mod.rs"), "").unwrap();
2485
2486        generate_component(GenerateComponentOptions {
2487            name: "marketing-card".to_string(),
2488            root: Some(temp.path().to_path_buf()),
2489            folder: false,
2490            recipe: false,
2491            children: false,
2492            asynchronous: false,
2493            markdown: false,
2494            no_test: true,
2495            dry_run: None,
2496            force: false,
2497        })
2498        .unwrap();
2499
2500        let module = fs::read_to_string(temp.path().join("src/components/mod.rs")).unwrap();
2501        assert!(module.contains("pub mod marketing_card;"));
2502        assert!(temp
2503            .path()
2504            .join("src/components/marketing_card.rs")
2505            .exists());
2506
2507        let source =
2508            fs::read_to_string(temp.path().join("src/components/marketing_card.rs")).unwrap();
2509        assert!(source.contains(
2510            "use proa_core::{ClassList, DataLoader, WebContext, WebRenderSync, WriteError};"
2511        ));
2512        assert!(source.contains("impl<L: DataLoader> WebRenderSync<L> for MarketingCard"));
2513        assert!(source.contains("fn render(self, cx: &mut WebContext<L>)"));
2514        syn::parse_file(&source).expect("generated component must be valid Rust syntax");
2515    }
2516
2517    #[test]
2518    fn generated_component_with_children_uses_default_writer() {
2519        let source = component_source(
2520            "MarketingCard",
2521            "data-marketing-card",
2522            true,
2523            false,
2524            false,
2525            false,
2526            true,
2527        );
2528
2529        assert!(source.contains("impl<L, C> WebRenderSync<L> for MarketingCard<C>"));
2530        assert!(source.contains("C: WebRenderSync<L>"));
2531        assert!(source.contains("WebContext::new()"));
2532        assert!(source.contains("cx.into_output().into_string()"));
2533        syn::parse_file(&source).expect("generated child component must be valid Rust syntax");
2534    }
2535
2536    #[test]
2537    fn generated_layouts_use_default_writer() {
2538        for source in [
2539            section_layout_source("MarketingLayout"),
2540            document_layout_source("DocumentLayout"),
2541        ] {
2542            assert!(source.contains("impl<L, C> WebRenderSync<L>"));
2543            assert!(source.contains("C: WebRenderSync<L>"));
2544            assert!(source.contains("DataLoader"));
2545            assert!(!source.contains("WriteBuf"));
2546            syn::parse_file(&source).expect("generated layout must be valid Rust syntax");
2547        }
2548    }
2549
2550    #[test]
2551    fn new_site_writes_project_config_and_lock() {
2552        let temp = tempfile::tempdir().unwrap();
2553        let root = temp.path().join("config-demo");
2554        new_site(NewSiteOptions {
2555            name: "config-demo".to_string(),
2556            root: root.clone(),
2557            template: "basic".to_string(),
2558            empty: false,
2559            server: ServerIntegration::Axum,
2560            tailwind: false,
2561            docs: DocsIntegration::None,
2562            blog: false,
2563            deploy: DeployTarget::None,
2564            skip_install: true,
2565            no_git: true,
2566            agents_md: true,
2567            dry_run: None,
2568            force: false,
2569            yes: true,
2570        })
2571        .unwrap();
2572
2573        assert!(root.join(crate::config::CONFIG_FILE).exists());
2574        assert!(root.join(crate::config::LOCK_FILE).exists());
2575    }
2576
2577    #[test]
2578    fn new_site_writes_hardened_dev_scripts() {
2579        let temp = tempfile::tempdir().unwrap();
2580        let root = temp.path().join("watch-demo");
2581        new_site(NewSiteOptions {
2582            name: "watch-demo".to_string(),
2583            root: root.clone(),
2584            template: "basic".to_string(),
2585            empty: false,
2586            server: ServerIntegration::Axum,
2587            tailwind: false,
2588            docs: DocsIntegration::None,
2589            blog: false,
2590            deploy: DeployTarget::None,
2591            skip_install: true,
2592            no_git: true,
2593            agents_md: true,
2594            dry_run: None,
2595            force: false,
2596            yes: true,
2597        })
2598        .unwrap();
2599
2600        let dev = fs::read_to_string(root.join("scripts/dev.sh")).unwrap();
2601        assert_eq!(dev, dev_script());
2602        assert!(dev.contains("$ROOT/target/watch/dev"));
2603        assert!(dev.contains("proa_watch_lock_acquire \"dev\" \"$ROOT\""));
2604        assert!(dev.contains(
2605            "proa_watch_run proa dev --root \"$ROOT\" ${dev_args[@]+\"${dev_args[@]}\"} \"$@\""
2606        ));
2607
2608        // Live-reload settings are shell variables at the top of the script,
2609        // so they can be edited in place or exported, and each one maps to the
2610        // `proa dev` flag that implements it.
2611        for setting in [
2612            "PROA_DEV_RELOAD=\"${PROA_DEV_RELOAD:-on}\"",
2613            "PROA_DEV_RELOAD_PORT=\"${PROA_DEV_RELOAD_PORT:-}\"",
2614            "PROA_DEV_CSS_HOT_SWAP=\"${PROA_DEV_CSS_HOT_SWAP:-on}\"",
2615            "PROA_DEV_DEBOUNCE_MS=\"${PROA_DEV_DEBOUNCE_MS:-300}\"",
2616            "dev_args+=(--no-reload)",
2617            "dev_args+=(--no-css-hot-swap)",
2618            "dev_args+=(--reload-port \"$PROA_DEV_RELOAD_PORT\")",
2619            "dev_args+=(--debounce-ms \"$PROA_DEV_DEBOUNCE_MS\")",
2620            // Turning a setting off must work for the spellings people
2621            // actually type, not only the literal `0`.
2622            "0 | false | no | off) return 0 ;;",
2623        ] {
2624            assert!(dev.contains(setting), "dev.sh is missing `{setting}`");
2625        }
2626
2627        let watch_lock = fs::read_to_string(root.join("scripts/watch-lock.sh")).unwrap();
2628        assert_eq!(watch_lock, watch_lock_script());
2629        assert!(watch_lock.contains("if mkdir \"$lock_dir\""));
2630        assert!(watch_lock.contains("kill -KILL -- \"-$child_pgid\""));
2631
2632        let build = fs::read_to_string(root.join("scripts/build.sh")).unwrap();
2633        assert_eq!(build, build_script());
2634        assert!(build.contains("proa build --root \"$ROOT\" \"$@\""));
2635
2636        let readme = fs::read_to_string(root.join("README.md")).unwrap();
2637        assert!(readme.contains("bash scripts/dev.sh"));
2638        assert!(readme.contains("bash scripts/build.sh"));
2639    }
2640
2641    #[test]
2642    fn new_site_generates_production_server_defaults() {
2643        let temp = tempfile::tempdir().unwrap();
2644        let root = temp.path().join("prod-demo");
2645        new_site(NewSiteOptions {
2646            name: "prod-demo".to_string(),
2647            root: root.clone(),
2648            template: "basic".to_string(),
2649            empty: false,
2650            server: ServerIntegration::Axum,
2651            tailwind: false,
2652            docs: DocsIntegration::None,
2653            blog: false,
2654            deploy: DeployTarget::None,
2655            skip_install: true,
2656            no_git: true,
2657            agents_md: true,
2658            dry_run: None,
2659            force: false,
2660            yes: true,
2661        })
2662        .unwrap();
2663
2664        let main = fs::read_to_string(root.join("src/main.rs")).unwrap();
2665        assert!(main.contains("const SHUTDOWN_DRAIN_TIMEOUT"));
2666        assert!(main.contains("proa_framework_axum::serve(listener, app, SHUTDOWN_DRAIN_TIMEOUT)"));
2667        assert!(!main.contains("async fn shutdown_signal"));
2668        assert!(main.contains("/robots.txt"));
2669        assert!(main.contains("X_CONTENT_TYPE_OPTIONS"));
2670        assert!(main.contains("X_FRAME_OPTIONS"));
2671        assert!(main.contains("REFERRER_POLICY"));
2672        assert!(main.contains("TraceLayer::new_for_http()"));
2673
2674        let layout = fs::read_to_string(root.join("src/layouts/root.rs")).unwrap();
2675        // Written into the macro, not through StaticRaw: `html/staticraw-doctype`
2676        // rejects the wrapped form, so scaffolding it made every fresh project
2677        // fail the `proa lint --deny warnings` and `proa build` we tell people to run.
2678        assert!(layout.contains("<!DOCTYPE html>"));
2679        assert!(!layout.contains("StaticRaw"));
2680        assert!(!layout.contains("UnsafeRaw"));
2681        assert!(layout.contains("NAV_ITEMS"));
2682        assert!(layout.contains("rel=\"icon\""));
2683        assert!(layout.contains("impl<L, C> WebRenderSync<L> for RootDocument<C>"));
2684        assert!(layout.contains("C: WebRenderSync<L>"));
2685        assert!(layout.contains("impl<L: DataLoader> WebRenderSync<L> for SiteNav"));
2686        syn::parse_file(&layout).expect("generated root layout must be valid Rust syntax");
2687
2688        let home = fs::read_to_string(root.join("src/pages/home.rs")).unwrap();
2689        assert!(home.contains("fn home_page_renders"));
2690        assert!(home.contains("impl<L: DataLoader> WebRenderSync<L> for HomePage"));
2691        assert!(home.contains("render_to_string(RootDocument"));
2692        assert!(!home.contains("WebContext::with_buffer(&mut out)"));
2693        syn::parse_file(&home).expect("generated home page must be valid Rust syntax");
2694
2695        let agent_instructions = fs::read_to_string(root.join("AGENTS.md")).unwrap();
2696        assert!(agent_instructions.contains("WebRenderSync<L>"));
2697        assert!(agent_instructions.contains("C: WebRenderSync<L>"));
2698        assert!(agent_instructions.contains("owns the default `RenderBuffer`"));
2699        assert!(agent_instructions.contains("#[rsjs(component)]"));
2700        assert!(agent_instructions.contains("#[rsjs(component, client)]"));
2701        assert!(agent_instructions.contains("Do not use inherent render shorthand"));
2702        assert!(agent_instructions.contains("component `clients(...)` allowlists"));
2703        assert!(agent_instructions.contains("direct inbound read such as `self.label`"));
2704        assert!(agent_instructions.contains("`signal(self.value)` initializer samples"));
2705
2706        let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
2707        assert!(cargo.contains("proa_core = \"0.3.0\""));
2708        assert!(cargo.contains("proa_macros = \"0.3.0\""));
2709        assert!(cargo.contains("proa_framework_axum = \"0.3.0\""));
2710        assert!(!cargo.contains("registry = \"proa\""));
2711        assert!(!cargo.contains("proa_core = { path ="));
2712        let cargo_config = fs::read_to_string(root.join(".cargo/config.toml")).unwrap();
2713        assert!(cargo_config.contains("git-fetch-with-cli = true"));
2714        assert!(cargo_config
2715            .parse::<toml::Value>()
2716            .unwrap()
2717            .get("registries")
2718            .is_none());
2719        assert!(!cargo.contains("proa_macros = { path ="));
2720        assert!(!cargo.contains("proa_framework_axum = { path ="));
2721        assert!(!cargo.contains("\"signal\""));
2722        assert!(cargo.contains("\"trace\""));
2723        assert!(cargo.contains("[profile.release]"));
2724    }
2725
2726    #[test]
2727    fn new_site_docs_option_creates_docs_route() {
2728        let temp = tempfile::tempdir().unwrap();
2729        let root = temp.path().join("docs-demo");
2730        new_site(NewSiteOptions {
2731            name: "docs-demo".to_string(),
2732            root: root.clone(),
2733            template: "basic".to_string(),
2734            empty: false,
2735            server: ServerIntegration::Axum,
2736            tailwind: false,
2737            docs: DocsIntegration::ProaDocs,
2738            blog: false,
2739            deploy: DeployTarget::None,
2740            skip_install: true,
2741            no_git: true,
2742            agents_md: true,
2743            dry_run: None,
2744            force: false,
2745            yes: true,
2746        })
2747        .unwrap();
2748
2749        assert!(root.join("src/docs/index.mdx").exists());
2750        assert!(root.join("src/pages/docs.rs").exists());
2751        let main = fs::read_to_string(root.join("src/main.rs")).unwrap();
2752        assert!(main.contains("/docs/*path"));
2753
2754        // Docs and fonts share one build.rs: the font collector first, then
2755        // the docs compilation, with [build-dependencies] emitted only once.
2756        let build = fs::read_to_string(root.join("build.rs")).unwrap();
2757        let fonts = build
2758            .find("proa_fonts_build::collect::run")
2759            .expect("build.rs must run the font collector");
2760        let docs = build
2761            .find("proa_docs_build::compile")
2762            .expect("build.rs must compile docs");
2763        assert!(
2764            fonts < docs,
2765            "the fonts section must precede docs compilation"
2766        );
2767        syn::parse_file(&build).expect("generated build.rs must be valid Rust syntax");
2768
2769        let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
2770        assert_eq!(cargo.matches("[build-dependencies]").count(), 1);
2771        assert!(cargo.contains("proa_fonts_build = \"0.1.0\""));
2772        assert!(cargo.contains("proa_docs_build = \"0.2.0\""));
2773    }
2774
2775    #[test]
2776    fn new_site_wires_font_collector() {
2777        let temp = tempfile::tempdir().unwrap();
2778        let root = temp.path().join("fonts-demo");
2779        new_site(NewSiteOptions {
2780            name: "fonts-demo".to_string(),
2781            root: root.clone(),
2782            template: "basic".to_string(),
2783            empty: false,
2784            server: ServerIntegration::Axum,
2785            tailwind: false,
2786            docs: DocsIntegration::None,
2787            blog: false,
2788            deploy: DeployTarget::None,
2789            skip_install: true,
2790            no_git: true,
2791            agents_md: false,
2792            dry_run: None,
2793            force: false,
2794            yes: true,
2795        })
2796        .unwrap();
2797
2798        let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
2799        assert!(cargo.contains("proa_fonts = \"0.1.0\""));
2800        assert!(cargo.contains("proa_fonts_macros = \"0.1.0\""));
2801        assert!(cargo.contains("[build-dependencies]\nproa_fonts_build = \"0.1.0\""));
2802        assert!(!cargo.contains("proa_docs_build"));
2803
2804        let build = fs::read_to_string(root.join("build.rs")).unwrap();
2805        assert!(build.contains("proa_fonts_build::collect::run("));
2806        assert!(build.contains("CollectOptions::from_build_env()"));
2807        assert!(build.contains("panic!(\"proa fonts: {error}\")"));
2808        assert!(build.contains("cargo:rerun-if-changed=src"));
2809        assert!(build.contains("cargo:rerun-if-changed=proa-fonts.lock"));
2810        assert!(!build.contains("proa_docs_build"));
2811        syn::parse_file(&build).expect("generated build.rs must be valid Rust syntax");
2812
2813        let main = fs::read_to_string(root.join("src/main.rs")).unwrap();
2814        assert!(main.contains(
2815            "mod __proa_fonts_generated { include!(concat!(env!(\"OUT_DIR\"), \"/proa_fonts.rs\")); }"
2816        ));
2817        assert!(
2818            main.contains("// Generated font consts for google_font!/local_font! declarations.")
2819        );
2820        // The generated CSS references /fonts, so the router must serve the
2821        // vendored files there, not only under /static.
2822        let fonts_route = main
2823            .find(".nest_service(\"/fonts\", static_assets::fonts_service())")
2824            .expect("main.rs must mount the fonts service at /fonts");
2825        let static_route = main
2826            .find(".nest_service(\"/static\"")
2827            .expect("main.rs must mount the static service");
2828        assert!(fonts_route < static_route);
2829        syn::parse_file(&main).expect("generated main.rs must be valid Rust syntax");
2830
2831        let assets = fs::read_to_string(root.join("src/static_assets.rs")).unwrap();
2832        assert!(assets.contains("pub fn fonts_service() -> Router"));
2833        assert!(assets.contains("static_root().join(\"fonts\")"));
2834        assert!(assets.contains("public, max-age=31536000, immutable"));
2835        syn::parse_file(&assets).expect("generated static_assets.rs must be valid Rust syntax");
2836    }
2837
2838    #[test]
2839    fn new_site_empty_skips_font_wiring() {
2840        let temp = tempfile::tempdir().unwrap();
2841        let root = temp.path().join("empty-demo");
2842        new_site(NewSiteOptions {
2843            name: "empty-demo".to_string(),
2844            root: root.clone(),
2845            template: "basic".to_string(),
2846            empty: true,
2847            server: ServerIntegration::Axum,
2848            tailwind: false,
2849            docs: DocsIntegration::None,
2850            blog: false,
2851            deploy: DeployTarget::None,
2852            skip_install: true,
2853            no_git: true,
2854            agents_md: false,
2855            dry_run: None,
2856            force: false,
2857            yes: true,
2858        })
2859        .unwrap();
2860
2861        let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
2862        assert!(!cargo.contains("proa_fonts"));
2863        assert!(!cargo.contains("[build-dependencies]"));
2864        assert!(!root.join("build.rs").exists());
2865
2866        let main = fs::read_to_string(root.join("src/main.rs")).unwrap();
2867        assert!(!main.contains("__proa_fonts_generated"));
2868        assert!(!main.contains("fonts_service"));
2869
2870        let assets = fs::read_to_string(root.join("src/static_assets.rs")).unwrap();
2871        assert!(!assets.contains("fonts_service"));
2872        syn::parse_file(&assets).expect("generated static_assets.rs must be valid Rust syntax");
2873    }
2874
2875    #[test]
2876    fn new_site_server_none_skips_font_wiring() {
2877        let temp = tempfile::tempdir().unwrap();
2878        let root = temp.path().join("headless-demo");
2879        new_site(NewSiteOptions {
2880            name: "headless-demo".to_string(),
2881            root: root.clone(),
2882            template: "basic".to_string(),
2883            empty: false,
2884            server: ServerIntegration::None,
2885            tailwind: false,
2886            docs: DocsIntegration::ProaDocs,
2887            blog: false,
2888            deploy: DeployTarget::None,
2889            skip_install: true,
2890            no_git: true,
2891            agents_md: false,
2892            dry_run: None,
2893            force: false,
2894            yes: true,
2895        })
2896        .unwrap();
2897
2898        // Without a generated crate root there is nowhere to include the
2899        // build-generated module, so no font wiring is emitted.
2900        let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
2901        assert!(!cargo.contains("proa_fonts"));
2902        assert_eq!(cargo.matches("[build-dependencies]").count(), 1);
2903        assert!(cargo.contains("proa_docs_build = \"0.2.0\""));
2904
2905        let build = fs::read_to_string(root.join("build.rs")).unwrap();
2906        assert!(!build.contains("proa_fonts_build"));
2907        assert!(build.contains("proa_docs_build::compile(config);"));
2908        syn::parse_file(&build).expect("generated build.rs must be valid Rust syntax");
2909
2910        assert!(!root.join("src/main.rs").exists());
2911    }
2912
2913    #[test]
2914    fn new_site_coolify_deploy_preset_writes_deploy_files() {
2915        let temp = tempfile::tempdir().unwrap();
2916        let root = temp.path().join("deploy-demo");
2917        new_site(NewSiteOptions {
2918            name: "deploy-demo".to_string(),
2919            root: root.clone(),
2920            template: "basic".to_string(),
2921            empty: false,
2922            server: ServerIntegration::Axum,
2923            tailwind: false,
2924            docs: DocsIntegration::None,
2925            blog: false,
2926            deploy: DeployTarget::Coolify,
2927            skip_install: true,
2928            no_git: true,
2929            agents_md: true,
2930            dry_run: None,
2931            force: false,
2932            yes: true,
2933        })
2934        .unwrap();
2935
2936        assert!(root.join("Dockerfile").exists());
2937        assert!(root.join(".dockerignore").exists());
2938        assert!(root.join("coolify.env.example").exists());
2939        assert!(root.join("COOLIFY.md").exists());
2940        let dockerfile = fs::read_to_string(root.join("Dockerfile")).unwrap();
2941        assert!(!dockerfile.contains("CARGO_REGISTRIES_PROA_TOKEN"));
2942        assert!(!dockerfile.contains("GIT_CONFIG"));
2943        assert!(!dockerfile.contains("github_token"));
2944        assert!(dockerfile.contains("cargo build --release --bin deploy-demo"));
2945        assert!(dockerfile.contains("EXPOSE 3000"));
2946        let main = fs::read_to_string(root.join("src/main.rs")).unwrap();
2947        assert!(main.contains("/healthz"));
2948    }
2949}