Skip to main content

phoenix_cli/
scaffold.rs

1use std::{
2    collections::{BTreeMap, BTreeSet},
3    env, fs,
4    io::ErrorKind,
5    path::{Component, Path, PathBuf},
6    process::Command,
7    str::FromStr,
8    time::{SystemTime, UNIX_EPOCH},
9};
10
11use thiserror::Error;
12
13const MODULES_START: &str = "// <phoenix:modules>";
14const MODULES_END: &str = "// </phoenix:modules>";
15const MODELS_START: &str = "// <phoenix:model-registry>";
16const MODELS_END: &str = "// </phoenix:model-registry>";
17const MIGRATIONS_START: &str = "// <phoenix:migration-registry>";
18const MIGRATIONS_END: &str = "// </phoenix:migration-registry>";
19const COMMANDS_START: &str = "// <phoenix:commands>";
20const COMMANDS_END: &str = "// </phoenix:commands>";
21const PROJECT_OPTIONS_FILE: &str = ".phoenix";
22const PHOENIXRS_VERSION: &str = "0.1.3";
23const APIZERO_REACT_VERSION: &str = "0.1.2";
24const APIZERO_REACT_SSR_VERSION: &str = "0.1.2";
25const APIZERO_VITE_VERSION: &str = "0.1.3";
26
27#[derive(Clone, Debug, Eq, PartialEq)]
28pub enum DependencySource {
29    Registry,
30    Local(PathBuf),
31}
32
33/// Options for [`ProjectGenerator::update_core`] / `px update`.
34#[derive(Clone, Debug)]
35pub struct UpdateProjectOptions {
36    pub dependencies: DependencySource,
37    pub install_dependencies: bool,
38    pub dry_run: bool,
39}
40
41impl UpdateProjectOptions {
42    #[must_use]
43    pub fn new() -> Self {
44        Self {
45            dependencies: DependencySource::discover(),
46            install_dependencies: true,
47            dry_run: false,
48        }
49    }
50
51    #[must_use]
52    pub fn dependencies(mut self, dependencies: DependencySource) -> Self {
53        self.dependencies = dependencies;
54        self
55    }
56
57    #[must_use]
58    pub const fn install_dependencies(mut self, install: bool) -> Self {
59        self.install_dependencies = install;
60        self
61    }
62
63    #[must_use]
64    pub const fn dry_run(mut self, dry_run: bool) -> Self {
65        self.dry_run = dry_run;
66        self
67    }
68}
69
70impl Default for UpdateProjectOptions {
71    fn default() -> Self {
72        Self::new()
73    }
74}
75
76#[derive(Clone, Debug, Eq, PartialEq)]
77struct StoredProjectOptions {
78    frontend: ProjectFrontend,
79    database: Option<ProjectDatabase>,
80    render_mode: ProjectRenderMode,
81    tailwind: bool,
82    features: Vec<ProjectFeature>,
83}
84
85/// One optional official Feature selected during `px new --feature ...`.
86#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
87pub enum ProjectFeature {
88    Captcha,
89    Pay,
90    Notify,
91}
92
93impl ProjectFeature {
94    pub const ALL: [Self; 3] = [Self::Captcha, Self::Pay, Self::Notify];
95
96    /// Cargo feature name on the `phoenixrs` facade and `config/<key>.toml` stem.
97    #[must_use]
98    pub const fn key(self) -> &'static str {
99        match self {
100            Self::Captcha => "captcha",
101            Self::Pay => "pay",
102            Self::Notify => "notify",
103        }
104    }
105
106    /// One-line Chinese description used by the interactive wizard.
107    #[must_use]
108    pub const fn summary(self) -> &'static str {
109        match self {
110            Self::Captcha => "图形验证码(SVG、一次一用,GET /captcha)",
111            Self::Pay => "聚合支付(微信 Native / 支付宝当面付 / Mock)",
112            Self::Notify => "通知(邮件 + 数据库双通道)",
113        }
114    }
115
116    /// Whether this Feature registers database migrations through its plugin.
117    #[must_use]
118    pub const fn has_migrations(self) -> bool {
119        matches!(self, Self::Pay | Self::Notify)
120    }
121}
122
123impl FromStr for ProjectFeature {
124    type Err = String;
125
126    fn from_str(value: &str) -> Result<Self, Self::Err> {
127        match value.trim().to_ascii_lowercase().as_str() {
128            "captcha" => Ok(Self::Captcha),
129            "pay" | "payment" | "payments" => Ok(Self::Pay),
130            "notify" | "notification" | "notifications" => Ok(Self::Notify),
131            _ => Err(format!(
132                "unknown feature `{value}`; expected captcha, pay, or notify"
133            )),
134        }
135    }
136}
137
138/// Parse a comma-separated `--feature` list; deduplicates and keeps a stable order.
139///
140/// # Errors
141///
142/// Returns an error naming the first unknown feature.
143pub fn parse_feature_list(value: &str) -> Result<Vec<ProjectFeature>, String> {
144    let mut features = Vec::new();
145    for part in value.split(',') {
146        let part = part.trim();
147        if part.is_empty() {
148            continue;
149        }
150        let feature = part.parse::<ProjectFeature>()?;
151        if !features.contains(&feature) {
152            features.push(feature);
153        }
154    }
155    features.sort_unstable();
156    Ok(features)
157}
158
159/// Initial React rendering mode selected by `px new`.
160#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
161pub enum ProjectRenderMode {
162    Spa,
163    Ssr,
164    #[default]
165    Islands,
166}
167
168impl ProjectRenderMode {
169    #[must_use]
170    pub const fn page_builder(self) -> &'static str {
171        match self {
172            Self::Spa => ".spa()",
173            Self::Ssr => ".ssr()",
174            Self::Islands => ".islands()",
175        }
176    }
177}
178
179impl FromStr for ProjectRenderMode {
180    type Err = String;
181
182    fn from_str(value: &str) -> Result<Self, Self::Err> {
183        match value.trim().to_ascii_lowercase().as_str() {
184            "spa" => Ok(Self::Spa),
185            "ssr" => Ok(Self::Ssr),
186            "islands" | "island" => Ok(Self::Islands),
187            _ => Err("render mode must be spa, ssr, or islands".to_owned()),
188        }
189    }
190}
191
192/// One optional database driver selected when a project is created.
193#[derive(Clone, Copy, Debug, Eq, PartialEq)]
194pub enum ProjectDatabase {
195    Sqlite,
196    Pgsql,
197    Mysql,
198    All,
199}
200
201/// Source format used for generated React components.
202#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
203pub enum ProjectFrontend {
204    Jsx,
205    #[default]
206    Tsx,
207}
208
209impl ProjectFrontend {
210    #[must_use]
211    pub const fn extension(self) -> &'static str {
212        match self {
213            Self::Jsx => "jsx",
214            Self::Tsx => "tsx",
215        }
216    }
217}
218
219impl FromStr for ProjectFrontend {
220    type Err = String;
221
222    fn from_str(value: &str) -> Result<Self, Self::Err> {
223        match value.trim().to_ascii_lowercase().as_str() {
224            "jsx" | "js" => Ok(Self::Jsx),
225            "tsx" | "ts" => Ok(Self::Tsx),
226            _ => Err("frontend must be jsx or tsx".to_owned()),
227        }
228    }
229}
230
231impl ProjectDatabase {
232    #[must_use]
233    pub const fn cargo_feature(self) -> &'static str {
234        match self {
235            Self::Sqlite => "sqlite",
236            Self::Pgsql => "pgsql",
237            Self::Mysql => "mysql",
238            Self::All => "all-databases",
239        }
240    }
241
242    #[must_use]
243    pub const fn toasty_features(self) -> &'static str {
244        match self {
245            Self::Sqlite => "serde\", \"sqlite",
246            Self::Pgsql => "postgresql\", \"serde",
247            Self::Mysql => "mysql\", \"serde",
248            Self::All => "mysql\", \"postgresql\", \"serde\", \"sqlite",
249        }
250    }
251}
252
253impl FromStr for ProjectDatabase {
254    type Err = String;
255
256    fn from_str(value: &str) -> Result<Self, Self::Err> {
257        match value.trim().to_ascii_lowercase().as_str() {
258            "sqlite" => Ok(Self::Sqlite),
259            "pgsql" | "postgres" | "postgresql" => Ok(Self::Pgsql),
260            "mysql" | "mariadb" => Ok(Self::Mysql),
261            "all" => Ok(Self::All),
262            _ => Err("database must be sqlite, pgsql, mysql, or all".to_owned()),
263        }
264    }
265}
266
267impl DependencySource {
268    #[must_use]
269    pub fn discover() -> Self {
270        if let Some(path) = env::var_os("PHOENIX_FRAMEWORK_PATH") {
271            let path = PathBuf::from(path);
272            if is_framework_root(&path) {
273                return Self::Local(path);
274            }
275        }
276        let Ok(executable) = env::current_exe() else {
277            return Self::Registry;
278        };
279        for ancestor in executable.ancestors() {
280            if is_framework_root(ancestor) {
281                return Self::Local(ancestor.to_path_buf());
282            }
283        }
284        let build_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
285            .join("../..")
286            .canonicalize()
287            .unwrap_or_else(|_| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../.."));
288        if is_framework_root(&build_root) {
289            return Self::Local(build_root);
290        }
291        Self::Registry
292    }
293}
294
295fn is_framework_root(path: &Path) -> bool {
296    path.join("crates/phoenix/Cargo.toml").is_file()
297        && path.join("packages/phoenix-react/package.json").is_file()
298        && path.join("packages/phoenix-vite/package.json").is_file()
299}
300
301#[derive(Clone, Debug)]
302pub struct NewProjectOptions {
303    pub target: PathBuf,
304    pub dependencies: DependencySource,
305    pub initialize_git: bool,
306    pub install_dependencies: bool,
307    pub render_mode: ProjectRenderMode,
308    pub database: Option<ProjectDatabase>,
309    pub frontend: ProjectFrontend,
310    pub tailwind: bool,
311    pub features: Vec<ProjectFeature>,
312}
313
314impl NewProjectOptions {
315    #[must_use]
316    pub fn new(target: impl Into<PathBuf>) -> Self {
317        Self {
318            target: target.into(),
319            dependencies: DependencySource::discover(),
320            initialize_git: false,
321            install_dependencies: true,
322            render_mode: ProjectRenderMode::default(),
323            database: None,
324            frontend: ProjectFrontend::default(),
325            tailwind: false,
326            features: Vec::new(),
327        }
328    }
329
330    #[must_use]
331    pub fn dependencies(mut self, dependencies: DependencySource) -> Self {
332        self.dependencies = dependencies;
333        self
334    }
335
336    #[must_use]
337    pub const fn initialize_git(mut self, initialize: bool) -> Self {
338        self.initialize_git = initialize;
339        self
340    }
341
342    #[must_use]
343    pub const fn install_dependencies(mut self, install: bool) -> Self {
344        self.install_dependencies = install;
345        self
346    }
347
348    #[must_use]
349    pub const fn render_mode(mut self, render_mode: ProjectRenderMode) -> Self {
350        self.render_mode = render_mode;
351        self
352    }
353
354    #[must_use]
355    pub const fn database(mut self, database: Option<ProjectDatabase>) -> Self {
356        self.database = database;
357        self
358    }
359
360    #[must_use]
361    pub const fn frontend(mut self, frontend: ProjectFrontend) -> Self {
362        self.frontend = frontend;
363        self
364    }
365
366    #[must_use]
367    pub const fn tailwind(mut self, tailwind: bool) -> Self {
368        self.tailwind = tailwind;
369        self
370    }
371
372    #[must_use]
373    pub fn features(mut self, features: Vec<ProjectFeature>) -> Self {
374        self.features = features;
375        self
376    }
377}
378
379#[derive(Clone, Copy, Debug, Default)]
380pub struct GenerateOptions {
381    pub force: bool,
382}
383
384#[derive(Clone, Copy, Debug, Default)]
385pub struct ControllerOptions {
386    pub force: bool,
387    pub resource: bool,
388    pub route: bool,
389}
390
391#[derive(Clone, Debug, Default)]
392#[allow(clippy::struct_excessive_bools)]
393pub struct ModelOptions {
394    pub all: bool,
395    pub api_resource: bool,
396    pub controller: bool,
397    pub factory: bool,
398    pub force: bool,
399    pub migration: bool,
400    pub page: bool,
401    pub relations: Vec<Relation>,
402    pub request: bool,
403    pub resource_controller: bool,
404}
405
406/// How a generated model relates to another one.
407///
408/// The whole point of naming these is that picking the *kind* and the *target*
409/// is all the information a relation needs — the foreign key, the column it
410/// maps to, and the pairing are conventions `#[phoenix::model]` fills in.
411#[derive(Clone, Copy, Debug, Eq, PartialEq)]
412pub enum RelationKind {
413    /// This model holds the foreign key (`Post` → `User`).
414    BelongsTo,
415    /// The other model holds the foreign key, and there are many (`User` → `Post`).
416    HasMany,
417    /// The other model holds the foreign key, and there is at most one.
418    HasOne,
419}
420
421impl RelationKind {
422    /// The attribute this kind writes.
423    const fn attribute(self) -> &'static str {
424        match self {
425            Self::BelongsTo => "belongs_to",
426            Self::HasMany => "has_many",
427            Self::HasOne => "has_one",
428        }
429    }
430
431    /// The CLI flag that selects it.
432    #[must_use]
433    pub const fn flag(self) -> &'static str {
434        match self {
435            Self::BelongsTo => "--belongs-to",
436            Self::HasMany => "--has-many",
437            Self::HasOne => "--has-one",
438        }
439    }
440}
441
442/// One relation declared on the command line.
443#[derive(Clone, Debug, Eq, PartialEq)]
444pub struct Relation {
445    /// Which side of the foreign key this model is on.
446    pub kind: RelationKind,
447    /// The model being related to, exactly as typed (`User`, `blog::Post`).
448    pub target: String,
449}
450
451#[derive(Debug, Error)]
452pub enum ScaffoldError {
453    #[error("invalid Phoenix name `{0}`; use letters, numbers, dashes, underscores, / or ::")]
454    InvalidName(String),
455    #[error("project target {0} already exists and is not empty")]
456    ProjectNotEmpty(PathBuf),
457    #[error("{0} is not a Phoenix project root")]
458    NotProject(PathBuf),
459    #[error("refusing to overwrite existing file {0}; pass --force to replace it")]
460    AlreadyExists(PathBuf),
461    #[error("Phoenix managed markers are missing or malformed in {0}")]
462    InvalidManagedFile(PathBuf),
463    #[error("local Phoenix framework root is invalid: {0}")]
464    InvalidFrameworkRoot(PathBuf),
465    #[error("failed to read or write {path}: {source}")]
466    Io {
467        path: PathBuf,
468        source: std::io::Error,
469    },
470    #[error("{program} exited unsuccessfully while preparing the project")]
471    CommandFailed { program: &'static str },
472    #[error("the current time is before the Unix epoch")]
473    InvalidClock,
474    #[error(
475        "make:auth needs a database for the persistent User model; recreate with \
476         `px new <app> --database sqlite` (or pgsql/mysql) and try again"
477    )]
478    AuthRequiresDatabase,
479}
480
481/// Files changed by `px feature:add` and an optional manual integration note.
482#[derive(Clone, Debug, Default)]
483pub struct FeatureAddResult {
484    pub written: Vec<PathBuf>,
485    pub integration_note: Option<String>,
486}
487
488/// Write the project skeleton only (no `git init`, no `npm install`).
489///
490/// Returns the number of files written so callers can report progress.
491///
492/// # Errors
493///
494/// Returns an error for invalid names, non-empty targets, invalid local
495/// framework paths, or file-system failures.
496pub fn scaffold_project(options: &NewProjectOptions) -> Result<usize, ScaffoldError> {
497    let target = absolute_path(&options.target)?;
498    ensure_empty_target(&target)?;
499    let directory_name = target
500        .file_name()
501        .and_then(|value| value.to_str())
502        .ok_or_else(|| ScaffoldError::InvalidName(target.display().to_string()))?;
503    let package = package_name(directory_name)?;
504    if let DependencySource::Local(root) = &options.dependencies
505        && !is_framework_root(root)
506    {
507        return Err(ScaffoldError::InvalidFrameworkRoot(root.clone()));
508    }
509
510    let mut editor = ProjectEditor::new(&target, false);
511    for (path, content) in project_files(&package, options)? {
512        editor.create(path, content)?;
513    }
514    Ok(editor.commit()?.len())
515}
516
517/// Create a complete Phoenix application that can immediately run `px dev`.
518///
519/// # Errors
520///
521/// Returns an error for invalid names, non-empty targets, invalid local framework
522/// paths, file-system failures, or dependency/bootstrap command failures.
523pub fn create_project(options: &NewProjectOptions) -> Result<(), ScaffoldError> {
524    scaffold_project(options)?;
525    let target = absolute_path(&options.target)?;
526    if options.initialize_git {
527        run_optional("git", &["init", "--quiet"], &target)?;
528    }
529    if options.install_dependencies {
530        run_required("npm", &["install"], &target)?;
531        run_required("npm", &["run", "types", "--silent"], &target)?;
532    }
533    Ok(())
534}
535
536#[derive(Clone, Debug)]
537pub struct ProjectGenerator {
538    root: PathBuf,
539}
540
541impl ProjectGenerator {
542    /// Locate the Phoenix project containing `start`.
543    ///
544    /// # Errors
545    ///
546    /// Returns an error when no parent contains the expected Phoenix layout.
547    pub fn discover(start: impl AsRef<Path>) -> Result<Self, ScaffoldError> {
548        let start = absolute_path(start.as_ref())?;
549        for candidate in start.ancestors() {
550            if is_project_root(candidate) {
551                return Ok(Self {
552                    root: candidate.to_path_buf(),
553                });
554            }
555        }
556        Err(ScaffoldError::NotProject(start))
557    }
558
559    #[must_use]
560    pub fn root(&self) -> &Path {
561        &self.root
562    }
563
564    /// Refresh generated TypeScript contracts after a Rust generator runs.
565    ///
566    /// Returns `Ok(false)` before JavaScript dependencies are installed; Vite
567    /// will still generate the files when development starts.
568    ///
569    /// # Errors
570    ///
571    /// Returns an error when the installed Phoenix Vite generator fails.
572    pub fn refresh_types(&self) -> Result<bool, ScaffoldError> {
573        if !self.root.join("node_modules/@apizero/vite").is_dir() {
574            return Ok(false);
575        }
576        run_required("npm", &["run", "types", "--silent"], &self.root)?;
577        Ok(true)
578    }
579
580    /// Generate a controller and optionally its conventional resource route.
581    ///
582    /// # Errors
583    ///
584    /// Returns an error for invalid names, conflicts, or malformed managed files.
585    pub fn controller(
586        &self,
587        name: &str,
588        options: ControllerOptions,
589    ) -> Result<Vec<PathBuf>, ScaffoldError> {
590        let name = QualifiedName::parse_with_suffix(name, "Controller")?;
591        let mut editor = ProjectEditor::new(&self.root, options.force);
592        add_rust_item(
593            &mut editor,
594            "app/controllers",
595            &name,
596            &controller_template(&name.class, options.resource),
597        )?;
598        if options.route || options.resource {
599            add_controller_route(&mut editor, &name, options.resource, None)?;
600        }
601        editor.commit()
602    }
603
604    /// Generate a Toasty model and any requested companion artifacts.
605    ///
606    /// `--all` creates the currently supported cohesive business slice: model,
607    /// migration, request, API resource, resource controller/route, and index page.
608    ///
609    /// # Errors
610    ///
611    /// Returns an error for invalid names, conflicts, or malformed managed files.
612    pub fn model(
613        &self,
614        name: &str,
615        mut options: ModelOptions,
616    ) -> Result<Vec<PathBuf>, ScaffoldError> {
617        if options.all {
618            options.factory = true;
619            options.migration = true;
620            options.request = true;
621            options.api_resource = true;
622            options.controller = true;
623            options.resource_controller = true;
624            options.page = true;
625        }
626        let model = QualifiedName::parse(name)?;
627        let request = model.with_leaf(format!("Store{}Request", model.class));
628        let resource = model.with_leaf(format!("{}Resource", model.class));
629        let controller = model.with_leaf(format!("{}Controller", model.class));
630        let page = model.index_page_name();
631        let props = page_props_name(&page);
632        let cohesive = options.request
633            && options.api_resource
634            && options.controller
635            && options.resource_controller
636            && options.page;
637        let mut editor = ProjectEditor::new(&self.root, options.force);
638        add_model(&mut editor, &model, &options.relations)?;
639        if options.factory {
640            add_factory(&mut editor, &model, &options.relations)?;
641        }
642        if options.migration {
643            add_model_migration(&mut editor, &model)?;
644        }
645        if options.request {
646            add_rust_item(
647                &mut editor,
648                "app/requests",
649                &request,
650                &request_template(&request.class),
651            )?;
652        }
653        if options.api_resource {
654            add_rust_item(
655                &mut editor,
656                "app/resources",
657                &resource,
658                &resource_template(&resource.class),
659            )?;
660        }
661        if options.controller || options.resource_controller {
662            let content = if cohesive {
663                model_controller_template(&controller, &request, &resource, &props, &page.route)
664            } else {
665                controller_template(&controller.class, options.resource_controller)
666            };
667            add_rust_item(&mut editor, "app/controllers", &controller, &content)?;
668            let action = cohesive.then_some((&request, &resource));
669            add_controller_route(
670                &mut editor,
671                &controller,
672                options.resource_controller,
673                action,
674            )?;
675        }
676        if options.page {
677            add_page(&mut editor, &page, self.frontend())?;
678        }
679        editor.commit()
680    }
681
682    /// Generate one migration and register it in `database/migrations/mod.rs`.
683    ///
684    /// # Errors
685    ///
686    /// Returns an error for invalid names, conflicts, time, or managed files.
687    pub fn migration(
688        &self,
689        name: &str,
690        options: GenerateOptions,
691    ) -> Result<Vec<PathBuf>, ScaffoldError> {
692        let migration_name = snake_identifier(name)?;
693        let mut editor = ProjectEditor::new(&self.root, options.force);
694        add_migration(
695            &mut editor,
696            &migration_name,
697            inferred_table(&migration_name),
698        )?;
699        editor.commit()
700    }
701
702    /// Generate a validated request DTO and update its Rust module.
703    ///
704    /// # Errors
705    ///
706    /// Returns an error for invalid names, conflicts, or malformed managed files.
707    pub fn request(
708        &self,
709        name: &str,
710        options: GenerateOptions,
711    ) -> Result<Vec<PathBuf>, ScaffoldError> {
712        self.rust_contract(name, "Request", "app/requests", request_template, options)
713    }
714
715    /// Generate a browser-safe API resource and update its Rust module.
716    ///
717    /// # Errors
718    ///
719    /// Returns an error for invalid names, conflicts, or malformed managed files.
720    pub fn resource(
721        &self,
722        name: &str,
723        options: GenerateOptions,
724    ) -> Result<Vec<PathBuf>, ScaffoldError> {
725        self.rust_contract(
726            name,
727            "Resource",
728            "app/resources",
729            resource_template,
730            options,
731        )
732    }
733
734    /// Generate a pass-through middleware ready for application logic.
735    ///
736    /// # Errors
737    ///
738    /// Returns an error for invalid names, conflicts, or malformed managed files.
739    pub fn middleware(
740        &self,
741        name: &str,
742        options: GenerateOptions,
743    ) -> Result<Vec<PathBuf>, ScaffoldError> {
744        let name = QualifiedName::parse_with_suffix(name, "Middleware")?;
745        let mut editor = ProjectEditor::new(&self.root, options.force);
746        add_rust_item(
747            &mut editor,
748            "app/middleware",
749            &name,
750            &middleware_template(&name.class),
751        )?;
752        editor.commit()
753    }
754
755    /// Generate a React page plus its Rust Page Props contract.
756    ///
757    /// # Errors
758    ///
759    /// Returns an error for invalid names, conflicts, or malformed managed files.
760    pub fn page(
761        &self,
762        name: &str,
763        options: GenerateOptions,
764    ) -> Result<Vec<PathBuf>, ScaffoldError> {
765        let page = PageName::parse(name)?;
766        let mut editor = ProjectEditor::new(&self.root, options.force);
767        add_page(&mut editor, &page, self.frontend())?;
768        editor.commit()
769    }
770
771    /// Generate a React Island component.
772    ///
773    /// # Errors
774    ///
775    /// Returns an error for invalid names, conflicts, or file-system failures.
776    pub fn island(
777        &self,
778        name: &str,
779        options: GenerateOptions,
780    ) -> Result<Vec<PathBuf>, ScaffoldError> {
781        let name = QualifiedName::parse(name)?;
782        let mut editor = ProjectEditor::new(&self.root, options.force);
783        let mut path = PathBuf::from("views/islands");
784        path.extend(name.modules.iter().map(|module| kebab_case(module)));
785        let frontend = self.frontend();
786        path.push(format!(
787            "{}.{}",
788            kebab_case(&name.class),
789            frontend.extension()
790        ));
791        editor.create(path, island_template(&name.class, frontend))?;
792        editor.commit()
793    }
794
795    /// Generate a console command and register it in `app/commands/mod.rs`.
796    ///
797    /// # Errors
798    ///
799    /// Returns an error for invalid names, conflicts, or malformed managed files.
800    pub fn command(
801        &self,
802        name: &str,
803        options: GenerateOptions,
804    ) -> Result<Vec<PathBuf>, ScaffoldError> {
805        let name = QualifiedName::parse(name)?;
806        let mut editor = ProjectEditor::new(&self.root, options.force);
807        add_command(&mut editor, &name)?;
808        editor.commit()
809    }
810
811    /// Enable one official Feature in an existing Phoenix project.
812    ///
813    /// The command writes only the requested Feature's TOML starter, preserves
814    /// existing environment examples, and refreshes the generated `FeatureSet`
815    /// assembly only when the project already opted into that scaffold pattern.
816    ///
817    /// # Errors
818    ///
819    /// Returns an error when project metadata or Cargo.toml cannot be read or
820    /// written.
821    pub fn add_feature(&self, feature: ProjectFeature) -> Result<FeatureAddResult, ScaffoldError> {
822        let mut stored = self.stored_options();
823        if !stored.features.contains(&feature) {
824            stored.features.push(feature);
825            stored.features.sort_unstable();
826        }
827
828        let mut editor = ProjectEditor::new(&self.root, false);
829        editor.set(PROJECT_OPTIONS_FILE, format_stored_options(&stored))?;
830
831        let config_path = PathBuf::from(format!("config/{}.toml", feature.key()));
832        if !self.root.join(&config_path).is_file() {
833            editor.create(&config_path, feature_config_template(feature))?;
834        }
835
836        let cargo_path = PathBuf::from("Cargo.toml");
837        let cargo = editor.read(&cargo_path)?;
838        if cargo.is_empty() {
839            return Err(ScaffoldError::InvalidManagedFile(
840                self.root.join(&cargo_path),
841            ));
842        }
843        editor.set(
844            &cargo_path,
845            enable_app_feature_in_manifest(&cargo, feature.key()),
846        )?;
847
848        let env_path = PathBuf::from(".env.example");
849        let env = editor.read(&env_path)?;
850        if env.is_empty() {
851            editor.set(
852                &env_path,
853                append_feature_env_example(&env_example_template(stored.database, &[]), feature),
854            )?;
855        } else if !env_example_has_feature_comment(&env, feature) {
856            editor.set(&env_path, append_feature_env_example(&env, feature))?;
857        }
858
859        let lib_path = PathBuf::from("src/lib.rs");
860        let lib = editor.read(&lib_path)?;
861        let integration_note = if lib.contains("use phoenix::plugin::FeatureSet;")
862            && lib.contains("pub fn features() -> Result<FeatureSet")
863        {
864            editor.set(
865                &lib_path,
866                lib_template_with_features(stored.database.is_some(), &stored.features),
867            )?;
868            None
869        } else {
870            Some(format!(
871                "未更新 src/lib.rs:未检测到 FeatureSet 装配。请手动注册 `{}` 插件;可参考 docs/FEATURES.md。",
872                feature.key()
873            ))
874        };
875
876        Ok(FeatureAddResult {
877            written: editor.commit()?,
878            integration_note,
879        })
880    }
881
882    /// Generate the authentication starter kit (`px make:auth`).
883    ///
884    /// Creates named login / logout / register / password-reset routes with a
885    /// stricter rate limit, an `AuthController`, validated request contracts,
886    /// browser-safe resources, page props, and React form pages.
887    ///
888    /// # Errors
889    ///
890    /// Returns an error for conflicts or malformed managed files.
891    pub fn auth(&self, options: GenerateOptions) -> Result<Vec<PathBuf>, ScaffoldError> {
892        // The generated slice authenticates against a persistent `users` table,
893        // so a database driver must have been selected at `px new`.
894        if self.stored_options().database.is_none() {
895            return Err(ScaffoldError::AuthRequiresDatabase);
896        }
897        let frontend = self.frontend();
898        let mut editor = ProjectEditor::new(&self.root, options.force);
899        // Persistent User model + migration; registered like `px make:model`.
900        add_rust_item(
901            &mut editor,
902            "app/models",
903            &QualifiedName {
904                modules: Vec::new(),
905                class: "User".to_owned(),
906            },
907            &auth_user_model_template(),
908        )?;
909        editor.update_registry(
910            "app/models/mod.rs",
911            MODELS_START,
912            MODELS_END,
913            "model",
914            "User",
915            render_model_registry,
916        )?;
917        add_auth_user_migration(&mut editor)?;
918        // Credentials use Argon2id (`password`) and the guard lives in the
919        // `phoenix-auth` crate (`auth`); enable both facade features.
920        enable_project_features(&mut editor, &["password", "auth"])?;
921        for (class, content) in [
922            ("LoginInput", login_input_template()),
923            ("RegisterInput", register_input_template()),
924            ("PasswordResetInput", password_reset_input_template()),
925        ] {
926            add_rust_item(
927                &mut editor,
928                "app/requests",
929                &QualifiedName {
930                    modules: Vec::new(),
931                    class: class.to_owned(),
932                },
933                &content,
934            )?;
935        }
936        for (class, content) in [
937            ("AuthSessionResource", auth_session_resource_template()),
938            ("AuthMessageResource", auth_message_resource_template()),
939        ] {
940            add_rust_item(
941                &mut editor,
942                "app/resources",
943                &QualifiedName {
944                    modules: Vec::new(),
945                    class: class.to_owned(),
946                },
947                &content,
948            )?;
949        }
950        add_rust_item(
951            &mut editor,
952            "app/controllers",
953            &QualifiedName {
954                modules: Vec::new(),
955                class: "AuthController".to_owned(),
956            },
957            &auth_controller_template(),
958        )?;
959        for (page, content) in [
960            ("auth/login", auth_login_page_template(frontend)),
961            ("auth/register", auth_register_page_template(frontend)),
962            (
963                "auth/forgot-password",
964                auth_forgot_password_page_template(frontend),
965            ),
966        ] {
967            add_auth_page(&mut editor, page, content, frontend)?;
968        }
969        editor.create("routes/auth.rs", auth_routes_template())?;
970        editor.commit()
971    }
972
973    fn rust_contract(
974        &self,
975        name: &str,
976        suffix: &str,
977        directory: &str,
978        template: fn(&str) -> String,
979        options: GenerateOptions,
980    ) -> Result<Vec<PathBuf>, ScaffoldError> {
981        let name = QualifiedName::parse_with_suffix(name, suffix)?;
982        let mut editor = ProjectEditor::new(&self.root, options.force);
983        add_rust_item(&mut editor, directory, &name, &template(&name.class))?;
984        editor.commit()
985    }
986
987    fn frontend(&self) -> ProjectFrontend {
988        self.stored_options().frontend
989    }
990
991    fn stored_options(&self) -> StoredProjectOptions {
992        read_stored_options(&self.root)
993    }
994
995    /// Refresh framework-owned core files without touching business code.
996    ///
997    /// Updates `src/lib.rs` / `src/main.rs`, Vite/TS config, config schemas, dependency
998    /// pins for `phoenixrs` / `@apizero/*`, and (when the project uses a database)
999    /// `src/bin/phoenix-manage.rs`. Leaves controllers, routes, pages, and user TOML alone.
1000    ///
1001    /// # Errors
1002    ///
1003    /// Returns an error for invalid local framework roots, I/O failures, or npm failures.
1004    pub fn update_core(
1005        &self,
1006        options: &UpdateProjectOptions,
1007    ) -> Result<Vec<PathBuf>, ScaffoldError> {
1008        if let DependencySource::Local(root) = &options.dependencies
1009            && !is_framework_root(root)
1010        {
1011            return Err(ScaffoldError::InvalidFrameworkRoot(root.clone()));
1012        }
1013
1014        let package = read_package_name(&self.root)?;
1015        let crate_name = package.replace('-', "_");
1016        let stored = self.stored_options();
1017        let has_database = stored.database.is_some();
1018        let (rust_dependency, react, react_ssr, vite) =
1019            framework_dependency_pins(&options.dependencies, &stored.features)?;
1020
1021        let mut planned: BTreeMap<PathBuf, String> = BTreeMap::new();
1022        planned.insert("src/main.rs".into(), main_template(&crate_name));
1023        planned.insert(
1024            "src/lib.rs".into(),
1025            lib_template(has_database, &stored.features),
1026        );
1027        planned.insert("config/mod.rs".into(), config_template(has_database));
1028        planned.insert(
1029            "vite.config.ts".into(),
1030            vite_template(false, stored.tailwind),
1031        );
1032        planned.insert(
1033            "vite.ssr.config.ts".into(),
1034            vite_template(true, stored.tailwind),
1035        );
1036        planned.insert("tsconfig.json".into(), tsconfig_template());
1037        planned.insert(
1038            ".gitignore".into(),
1039            "/target\n/node_modules\n/public/assets\n/public/ssr\n/views/generated/*.ts\n/dist\n/storage/*.sqlite\n/storage/*.sqlite-*\n.env\n.DS_Store\n".to_owned(),
1040        );
1041        planned.insert(PROJECT_OPTIONS_FILE.into(), format_stored_options(&stored));
1042
1043        if stored.database.is_some() {
1044            planned.insert(
1045                "src/bin/phoenix-manage.rs".into(),
1046                management_template(
1047                    &crate_name,
1048                    stored
1049                        .features
1050                        .iter()
1051                        .any(|feature| feature.has_migrations()),
1052                ),
1053            );
1054            // Ensure empty registries exist when upgrading a no-db project that later
1055            // recorded a database in `.phoenix` — do not overwrite populated registries.
1056            for (path, content) in [
1057                ("app/models/mod.rs", empty_model_registry()),
1058                ("database/migrations/mod.rs", empty_migration_registry()),
1059                ("database/seeders/mod.rs", seeder_template()),
1060            ] {
1061                if !self.root.join(path).is_file() {
1062                    planned.insert(path.into(), content);
1063                }
1064            }
1065        }
1066
1067        // Feature config files carry user values: create only when missing.
1068        for feature in &stored.features {
1069            let path = format!("config/{}.toml", feature.key());
1070            if !self.root.join(&path).is_file() {
1071                planned.insert(path.into(), feature_config_template(*feature));
1072            }
1073        }
1074
1075        let cargo_path = PathBuf::from("Cargo.toml");
1076        let cargo = fs::read_to_string(self.root.join(&cargo_path)).map_err(|source| {
1077            ScaffoldError::Io {
1078                path: self.root.join(&cargo_path),
1079                source,
1080            }
1081        })?;
1082        let cargo = patch_cargo_toml_core(&cargo, &rust_dependency);
1083        planned.insert(cargo_path, cargo);
1084
1085        let package_json_path = PathBuf::from("package.json");
1086        let package_json =
1087            fs::read_to_string(self.root.join(&package_json_path)).map_err(|source| {
1088                ScaffoldError::Io {
1089                    path: self.root.join(&package_json_path),
1090                    source,
1091                }
1092            })?;
1093        let package_json =
1094            patch_package_json_core(&package_json, &react, &react_ssr, &vite, stored.tailwind)?;
1095        planned.insert(package_json_path, package_json);
1096
1097        let mut changed = Vec::new();
1098        for (relative, content) in &planned {
1099            let absolute = self.root.join(relative);
1100            let existing = match fs::read_to_string(&absolute) {
1101                Ok(text) => text,
1102                Err(error) if error.kind() == ErrorKind::NotFound => String::new(),
1103                Err(source) => {
1104                    return Err(ScaffoldError::Io {
1105                        path: absolute,
1106                        source,
1107                    });
1108                }
1109            };
1110            if existing == *content {
1111                continue;
1112            }
1113            changed.push(absolute.clone());
1114            if options.dry_run {
1115                continue;
1116            }
1117            if let Some(parent) = absolute.parent() {
1118                fs::create_dir_all(parent).map_err(|source| ScaffoldError::Io {
1119                    path: parent.to_path_buf(),
1120                    source,
1121                })?;
1122            }
1123            fs::write(&absolute, content).map_err(|source| ScaffoldError::Io {
1124                path: absolute,
1125                source,
1126            })?;
1127        }
1128
1129        if !options.dry_run
1130            && options.install_dependencies
1131            && self.root.join("package.json").is_file()
1132        {
1133            run_required("npm", &["install"], &self.root)?;
1134            let _ = self.refresh_types()?;
1135        }
1136
1137        Ok(changed)
1138    }
1139}
1140
1141fn is_project_root(path: &Path) -> bool {
1142    path.join("Cargo.toml").is_file()
1143        && path.join("package.json").is_file()
1144        && path.join("app").is_dir()
1145        && path.join("routes").is_dir()
1146        && path.join("views").is_dir()
1147}
1148
1149fn framework_dependency_pins(
1150    source: &DependencySource,
1151    features: &[ProjectFeature],
1152) -> Result<(String, String, String, String), ScaffoldError> {
1153    // Comma-separated `"captcha", "pay"` fragment for the phoenix dependency line.
1154    let feature_list = features
1155        .iter()
1156        .map(|feature| format!("\"{}\"", feature.key()))
1157        .collect::<Vec<_>>()
1158        .join(", ");
1159    let feature_suffix = if feature_list.is_empty() {
1160        String::new()
1161    } else {
1162        format!(", features = [{feature_list}]")
1163    };
1164    match source {
1165        // Plain semver ranges: the user's own npm registry (npmmirror and
1166        // friends included) resolves them. Never emit registry.npmjs.org
1167        // tarball URLs — they bypass configured mirrors.
1168        DependencySource::Registry => Ok((
1169            format!(
1170                "phoenix = {{ package = \"phoenixrs\", version = \"{PHOENIXRS_VERSION}\", default-features = false{feature_suffix} }}"
1171            ),
1172            format!("^{APIZERO_REACT_VERSION}"),
1173            format!("^{APIZERO_REACT_SSR_VERSION}"),
1174            format!("^{APIZERO_VITE_VERSION}"),
1175        )),
1176        DependencySource::Local(root) => {
1177            let root = absolute_path(root)?;
1178            Ok((
1179                format!(
1180                    "phoenix = {{ package = \"phoenixrs\", path = {}, default-features = false{feature_suffix} }}",
1181                    json_string(&root.join("crates/phoenix").to_string_lossy())
1182                ),
1183                format!("file:{}", root.join("packages/phoenix-react").display()),
1184                format!("file:{}", root.join("packages/phoenix-react-ssr").display()),
1185                format!("file:{}", root.join("packages/phoenix-vite").display()),
1186            ))
1187        }
1188    }
1189}
1190
1191fn format_stored_options(options: &StoredProjectOptions) -> String {
1192    let database = options.database.map_or("none", database_option_key);
1193    let render_mode = match options.render_mode {
1194        ProjectRenderMode::Spa => "spa",
1195        ProjectRenderMode::Ssr => "ssr",
1196        ProjectRenderMode::Islands => "islands",
1197    };
1198    let features = options
1199        .features
1200        .iter()
1201        .map(|feature| feature.key())
1202        .collect::<Vec<_>>()
1203        .join(",");
1204    format!(
1205        "frontend={}\nrender_mode={render_mode}\ndatabase={database}\ntailwind={}\nfeatures={features}\n",
1206        options.frontend.extension(),
1207        if options.tailwind { "true" } else { "false" },
1208    )
1209}
1210
1211fn database_option_key(database: ProjectDatabase) -> &'static str {
1212    match database {
1213        ProjectDatabase::Sqlite => "sqlite",
1214        ProjectDatabase::Pgsql => "pgsql",
1215        ProjectDatabase::Mysql => "mysql",
1216        ProjectDatabase::All => "all",
1217    }
1218}
1219
1220fn read_stored_options(root: &Path) -> StoredProjectOptions {
1221    let mut options = StoredProjectOptions {
1222        frontend: ProjectFrontend::default(),
1223        database: None,
1224        render_mode: ProjectRenderMode::default(),
1225        tailwind: false,
1226        features: Vec::new(),
1227    };
1228    let mut render_mode_recorded = false;
1229
1230    if let Ok(source) = fs::read_to_string(root.join(PROJECT_OPTIONS_FILE)) {
1231        for line in source.lines() {
1232            if let Some(value) = line.strip_prefix("frontend=") {
1233                if let Ok(frontend) = value.parse() {
1234                    options.frontend = frontend;
1235                }
1236            } else if let Some(value) = line.strip_prefix("render_mode=") {
1237                if let Ok(render_mode) = value.parse() {
1238                    options.render_mode = render_mode;
1239                    render_mode_recorded = true;
1240                }
1241            } else if let Some(value) = line.strip_prefix("database=") {
1242                options.database = match value.trim() {
1243                    "" | "none" | "no" => None,
1244                    other => other.parse().ok(),
1245                };
1246            } else if let Some(value) = line.strip_prefix("tailwind=") {
1247                options.tailwind = matches!(value.trim(), "1" | "true" | "yes");
1248            } else if let Some(value) = line.strip_prefix("features=")
1249                && let Ok(features) = parse_feature_list(value)
1250            {
1251                options.features = features;
1252            }
1253        }
1254    }
1255
1256    if options.database.is_none() && root.join("src/bin/phoenix-manage.rs").is_file() {
1257        options.database = Some(infer_database(root));
1258    }
1259    if !options.tailwind
1260        && fs::read_to_string(root.join("package.json"))
1261            .ok()
1262            .is_some_and(|text| text.contains("tailwindcss"))
1263    {
1264        options.tailwind = true;
1265    }
1266    if !render_mode_recorded
1267        && let Ok(controller) = fs::read_to_string(root.join("app/controllers/home_controller.rs"))
1268        && let Some(render_mode) = sniff_home_render_mode(&controller)
1269    {
1270        options.render_mode = render_mode;
1271    }
1272    if options.frontend == ProjectFrontend::default()
1273        && root.join("views/pages/home.jsx").is_file()
1274        && !root.join("views/pages/home.tsx").is_file()
1275    {
1276        options.frontend = ProjectFrontend::Jsx;
1277    }
1278    options
1279}
1280
1281/// Legacy fallback for projects without `render_mode=` in `.phoenix`: the mode
1282/// marker closest after `Page::new("home"` wins, so the demo-page methods in
1283/// the same controller do not confuse the detection.
1284fn sniff_home_render_mode(controller: &str) -> Option<ProjectRenderMode> {
1285    let start = controller.find("\"home\"").unwrap_or(0);
1286    let tail = &controller[start..];
1287    [
1288        (".spa()", ProjectRenderMode::Spa),
1289        (".ssr()", ProjectRenderMode::Ssr),
1290        (".islands()", ProjectRenderMode::Islands),
1291    ]
1292    .into_iter()
1293    .filter_map(|(marker, mode)| tail.find(marker).map(|index| (index, mode)))
1294    .min_by_key(|(index, _)| *index)
1295    .map(|(_, mode)| mode)
1296}
1297
1298/// Infer the driver for legacy projects (no `database=` line in `.phoenix`)
1299/// from the Cargo feature default, falling back to the `.env` `DATABASE_URL`.
1300fn infer_database(root: &Path) -> ProjectDatabase {
1301    if let Ok(cargo) = fs::read_to_string(root.join("Cargo.toml")) {
1302        if cargo.contains("default = [\"all-databases\"]") || cargo.contains("all-databases =") {
1303            return ProjectDatabase::All;
1304        }
1305        if cargo.contains("default = [\"mysql\"]") {
1306            return ProjectDatabase::Mysql;
1307        }
1308        if cargo.contains("default = [\"pgsql\"]") {
1309            return ProjectDatabase::Pgsql;
1310        }
1311        if cargo.contains("default = [\"sqlite\"]") {
1312            return ProjectDatabase::Sqlite;
1313        }
1314    }
1315    for env_file in [".env", ".env.example"] {
1316        if let Ok(env) = fs::read_to_string(root.join(env_file)) {
1317            for line in env.lines() {
1318                let Some(url) = line.trim().strip_prefix("DATABASE_URL=") else {
1319                    continue;
1320                };
1321                let url = url.trim();
1322                if url.starts_with("sqlite:") {
1323                    return ProjectDatabase::Sqlite;
1324                }
1325                if url.starts_with("postgres") {
1326                    return ProjectDatabase::Pgsql;
1327                }
1328                if url.starts_with("mysql:") {
1329                    return ProjectDatabase::Mysql;
1330                }
1331            }
1332        }
1333    }
1334    ProjectDatabase::Sqlite
1335}
1336
1337fn read_package_name(root: &Path) -> Result<String, ScaffoldError> {
1338    let path = root.join("Cargo.toml");
1339    let text = fs::read_to_string(&path).map_err(|source| ScaffoldError::Io {
1340        path: path.clone(),
1341        source,
1342    })?;
1343    let mut in_package = false;
1344    for line in text.lines() {
1345        let trimmed = line.trim();
1346        if trimmed.starts_with('[') && trimmed.ends_with(']') {
1347            in_package = trimmed == "[package]";
1348            continue;
1349        }
1350        if in_package && let Some(value) = trimmed.strip_prefix("name = ") {
1351            let value = value.trim();
1352            if value.starts_with('"') && value.ends_with('"') && value.len() >= 2 {
1353                return Ok(value[1..value.len() - 1].to_owned());
1354            }
1355        }
1356    }
1357    Err(ScaffoldError::InvalidManagedFile(path))
1358}
1359
1360fn patch_cargo_toml_core(cargo: &str, phoenix_dependency: &str) -> String {
1361    let mut lines = cargo.lines().map(str::to_owned).collect::<Vec<_>>();
1362    let mut replaced = false;
1363    for line in &mut lines {
1364        let trimmed = line.trim_start();
1365        if trimmed.starts_with("phoenix =") || trimmed.starts_with("phoenixrs =") {
1366            phoenix_dependency.clone_into(line);
1367            replaced = true;
1368        }
1369    }
1370    if !replaced {
1371        if let Some(index) = lines
1372            .iter()
1373            .position(|line| line.trim() == "[dependencies]")
1374        {
1375            lines.insert(index + 1, phoenix_dependency.to_owned());
1376        } else {
1377            lines.push(String::new());
1378            lines.push("[dependencies]".to_owned());
1379            lines.push(phoenix_dependency.to_owned());
1380        }
1381    }
1382
1383    let required_features = [
1384        ("tls =", "tls = [\"phoenix/tls\"]"),
1385        ("websocket =", "websocket = [\"phoenix/websocket\"]"),
1386        ("sse =", "sse = [\"phoenix/sse\"]"),
1387        ("auth =", "auth = [\"phoenix/auth\"]"),
1388        ("jwt =", "jwt = [\"phoenix/jwt\"]"),
1389        ("password =", "password = [\"phoenix/password\"]"),
1390        ("metrics =", "metrics = [\"phoenix/metrics\"]"),
1391        ("redis =", "redis = [\"phoenix/redis\"]"),
1392        ("storage =", "storage = [\"phoenix/storage\"]"),
1393        ("queue =", "queue = [\"phoenix/queue\"]"),
1394        ("mail =", "mail = [\"phoenix/mail\"]"),
1395        ("testing =", "testing = [\"phoenix/testing\"]"),
1396        ("factory =", "factory = [\"phoenix/factory\"]"),
1397    ];
1398    let mut missing = Vec::new();
1399    for (prefix, line) in required_features {
1400        if !lines
1401            .iter()
1402            .any(|existing| existing.trim_start().starts_with(prefix))
1403        {
1404            missing.push(line.to_owned());
1405        }
1406    }
1407    if !missing.is_empty() {
1408        let insert_at = lines
1409            .iter()
1410            .position(|line| line.trim() == "[dependencies]")
1411            .unwrap_or(lines.len());
1412        for (offset, line) in missing.into_iter().enumerate() {
1413            lines.insert(insert_at + offset, line);
1414        }
1415    }
1416
1417    let mut body = lines.join("\n");
1418    if !body.ends_with('\n') {
1419        body.push('\n');
1420    }
1421    body
1422}
1423
1424/// Make an app-level Feature forward to the Phoenix facade and enable it by
1425/// default, retaining every existing feature declaration and default entry.
1426fn enable_app_feature_in_manifest(manifest: &str, feature: &str) -> String {
1427    let feature_line = format!("{feature} = [\"phoenix/{feature}\"]");
1428    let mut lines = manifest.lines().map(str::to_owned).collect::<Vec<_>>();
1429    let has_newline = manifest.ends_with('\n');
1430    let section_start = lines.iter().position(|line| line.trim() == "[features]");
1431
1432    if let Some(start) = section_start {
1433        let section_end = lines[start + 1..]
1434            .iter()
1435            .position(|line| {
1436                let trimmed = line.trim();
1437                trimmed.starts_with('[') && trimmed.ends_with(']')
1438            })
1439            .map_or(lines.len(), |offset| start + 1 + offset);
1440        let has_feature = lines[start + 1..section_end].iter().any(|line| {
1441            line.trim_start()
1442                .strip_prefix(feature)
1443                .is_some_and(|rest| rest.trim_start().starts_with('='))
1444        });
1445        if !has_feature {
1446            lines.insert(section_end, feature_line);
1447        }
1448        let has_default = lines[start + 1..]
1449            .iter()
1450            .take_while(|line| {
1451                let trimmed = line.trim();
1452                !(trimmed.starts_with('[') && trimmed.ends_with(']'))
1453            })
1454            .any(|line| {
1455                line.trim_start()
1456                    .strip_prefix("default")
1457                    .is_some_and(|rest| rest.trim_start().starts_with('='))
1458            });
1459        if !has_default {
1460            lines.insert(start + 1, format!("default = [\"{feature}\"]"));
1461        }
1462    } else {
1463        let insert_at = lines
1464            .iter()
1465            .position(|line| line.trim() == "[dependencies]")
1466            .unwrap_or(lines.len());
1467        lines.insert(insert_at, String::new());
1468        lines.insert(insert_at + 1, "[features]".to_owned());
1469        lines.insert(insert_at + 2, format!("default = [\"{feature}\"]"));
1470        lines.insert(insert_at + 3, feature_line);
1471    }
1472
1473    let mut rendered = lines.join("\n");
1474    if has_newline {
1475        rendered.push('\n');
1476    }
1477    ensure_default_features(&rendered, &[feature])
1478}
1479
1480fn patch_package_json_core(
1481    raw: &str,
1482    react: &str,
1483    react_ssr: &str,
1484    vite: &str,
1485    tailwind: bool,
1486) -> Result<String, ScaffoldError> {
1487    let mut value: serde_json::Value =
1488        serde_json::from_str(raw).map_err(|source| ScaffoldError::Io {
1489            path: PathBuf::from("package.json"),
1490            source: std::io::Error::new(ErrorKind::InvalidData, source.to_string()),
1491        })?;
1492    let object = value.as_object_mut().ok_or_else(|| ScaffoldError::Io {
1493        path: PathBuf::from("package.json"),
1494        source: std::io::Error::new(
1495            ErrorKind::InvalidData,
1496            "package.json root must be an object",
1497        ),
1498    })?;
1499
1500    let dependencies = object
1501        .entry("dependencies")
1502        .or_insert_with(|| serde_json::json!({}));
1503    if let Some(deps) = dependencies.as_object_mut() {
1504        deps.insert(
1505            "@apizero/react".to_owned(),
1506            serde_json::Value::String(react.to_owned()),
1507        );
1508        deps.insert(
1509            "@apizero/react-ssr".to_owned(),
1510            serde_json::Value::String(react_ssr.to_owned()),
1511        );
1512        deps.insert(
1513            "@apizero/vite".to_owned(),
1514            serde_json::Value::String(vite.to_owned()),
1515        );
1516    }
1517
1518    let scripts = object
1519        .entry("scripts")
1520        .or_insert_with(|| serde_json::json!({}));
1521    if let Some(scripts) = scripts.as_object_mut() {
1522        scripts.insert(
1523            "dev".to_owned(),
1524            serde_json::Value::String("vite --host 127.0.0.1".to_owned()),
1525        );
1526        scripts.insert(
1527            "build".to_owned(),
1528            serde_json::Value::String("npm run build:client && npm run build:ssr".to_owned()),
1529        );
1530        scripts.insert(
1531            "build:client".to_owned(),
1532            serde_json::Value::String("vite build".to_owned()),
1533        );
1534        scripts.insert(
1535            "build:ssr".to_owned(),
1536            serde_json::Value::String("vite build --config vite.ssr.config.ts".to_owned()),
1537        );
1538        scripts.insert(
1539            "types".to_owned(),
1540            serde_json::Value::String(
1541                "node -e \"import('@apizero/vite').then(({ generateRouteTypes }) => generateRouteTypes('routes', 'views/generated/routes.ts', '.', 'views/generated/contracts.ts'))\""
1542                    .to_owned(),
1543            ),
1544        );
1545        scripts.insert(
1546            "typecheck".to_owned(),
1547            serde_json::Value::String("npm run types && tsc --noEmit".to_owned()),
1548        );
1549    }
1550
1551    let dev_dependencies = object
1552        .entry("devDependencies")
1553        .or_insert_with(|| serde_json::json!({}));
1554    if let Some(deps) = dev_dependencies.as_object_mut() {
1555        // Required by `@apizero/vite` production minify (`build.minify = "terser"`).
1556        deps.entry("terser".to_owned())
1557            .or_insert_with(|| serde_json::Value::String("^5.43.0".to_owned()));
1558        if tailwind {
1559            deps.entry("@tailwindcss/vite".to_owned())
1560                .or_insert_with(|| serde_json::Value::String("^4.3.0".to_owned()));
1561            deps.entry("tailwindcss".to_owned())
1562                .or_insert_with(|| serde_json::Value::String("^4.3.0".to_owned()));
1563        }
1564    }
1565
1566    let mut rendered =
1567        serde_json::to_string_pretty(&value).map_err(|source| ScaffoldError::Io {
1568            path: PathBuf::from("package.json"),
1569            source: std::io::Error::new(ErrorKind::InvalidData, source.to_string()),
1570        })?;
1571    rendered.push('\n');
1572    Ok(rendered)
1573}
1574
1575// The body is the flat scaffold file list; the length is data, not logic.
1576#[allow(clippy::too_many_lines)]
1577fn project_files(
1578    package: &str,
1579    options: &NewProjectOptions,
1580) -> Result<Vec<(PathBuf, String)>, ScaffoldError> {
1581    let (rust_dependency, react, react_ssr, vite) =
1582        framework_dependency_pins(&options.dependencies, &options.features)?;
1583    let crate_name = package.replace('-', "_");
1584    let tailwind = if options.tailwind {
1585        ",\n    \"@tailwindcss/vite\": \"^4.3.0\",\n    \"tailwindcss\": \"^4.3.0\""
1586    } else {
1587        ""
1588    };
1589    let package_json = format!(
1590        r#"{{
1591  "name": {package},
1592  "version": "0.1.0",
1593  "private": true,
1594  "type": "module",
1595  "scripts": {{
1596    "dev": "vite --host 127.0.0.1",
1597    "build": "npm run build:client && npm run build:ssr",
1598    "build:client": "vite build",
1599    "build:ssr": "vite build --config vite.ssr.config.ts",
1600    "types": "node -e \"import('@apizero/vite').then(({{ generateRouteTypes }}) => generateRouteTypes('routes', 'views/generated/routes.ts', '.', 'views/generated/contracts.ts'))\"",
1601    "typecheck": "npm run types && tsc --noEmit"
1602  }},
1603  "dependencies": {{
1604    "@apizero/react": {react},
1605    "@apizero/react-ssr": {react_ssr},
1606    "@apizero/vite": {vite},
1607    "react": "^19.1.0",
1608    "react-dom": "^19.1.0"
1609  }},
1610  "devDependencies": {{
1611    "@types/react": "^19.0.0",
1612    "@types/react-dom": "^19.0.0",
1613    "terser": "^5.43.0",
1614    "typescript": "^5.8.0",
1615    "vite": "^7.3.6"{tailwind}
1616  }}
1617}}
1618"#,
1619        package = json_string(package),
1620        react = json_string(&react),
1621        react_ssr = json_string(&react_ssr),
1622        vite = json_string(&vite),
1623        tailwind = tailwind,
1624    );
1625    let (database_features, toasty_dependency) = options.database.map_or_else(
1626        || ("default = []\ndatabase = []\n".to_owned(), String::new()),
1627        |database| {
1628            let app_feature = database.cargo_feature();
1629            let phoenix_features = match database {
1630                ProjectDatabase::All => "\"database\", \"phoenix/sqlite\", \"phoenix/pgsql\", \"phoenix/mysql\"".to_owned(),
1631                _ => format!("\"database\", \"phoenix/{app_feature}\""),
1632            };
1633            let toasty_features = database.toasty_features();
1634            (
1635                format!(
1636                    "default = [\"{app_feature}\"]\ndatabase = [\"phoenix/database\"]\n{app_feature} = [{phoenix_features}]\n"
1637                ),
1638                format!(
1639                    "toasty = {{ version = \"0.8\", default-features = false, features = [\"migration\", \"{toasty_features}\"] }}\n"
1640                ),
1641            )
1642        },
1643    );
1644    let cargo_toml = format!(
1645        "[package]\nname = {package}\nversion = \"0.1.0\"\nedition = \"2024\"\nrust-version = \"1.95\"\npublish = false\ndefault-run = {package}\n\n[features]\n# Database support is omitted unless selected during `px new`.\n{database_features}tls = [\"phoenix/tls\"]\nwebsocket = [\"phoenix/websocket\"]\nsse = [\"phoenix/sse\"]\nauth = [\"phoenix/auth\"]\njwt = [\"phoenix/jwt\"]\npassword = [\"phoenix/password\"]\nmetrics = [\"phoenix/metrics\"]\nredis = [\"phoenix/redis\"]\nstorage = [\"phoenix/storage\"]\nqueue = [\"phoenix/queue\"]\nmail = [\"phoenix/mail\"]\ntesting = [\"phoenix/testing\"]\n# Batch test data. Development and test only; never enable in a release build.\nfactory = [\"phoenix/factory\"]\n\n[dependencies]\n{rust_dependency}\nserde = {{ version = \"1\", features = [\"derive\"] }}\nserde_json = \"1\"\n{toasty_dependency}tokio = {{ version = \"1\", features = [\"macros\", \"rt-multi-thread\", \"signal\"] }}\n\n[profile.release]\ncodegen-units = 1\nlto = true\nopt-level = \"z\"\npanic = \"unwind\"\nstrip = \"symbols\"\n\n[workspace]\n",
1646        package = json_string(package),
1647        database_features = database_features,
1648        rust_dependency = rust_dependency,
1649        toasty_dependency = toasty_dependency,
1650    );
1651
1652    let stored = StoredProjectOptions {
1653        frontend: options.frontend,
1654        database: options.database,
1655        render_mode: options.render_mode,
1656        tailwind: options.tailwind,
1657        features: options.features.clone(),
1658    };
1659    let extension = options.frontend.extension();
1660
1661    let mut files = vec![
1662        ("Cargo.toml".into(), cargo_toml),
1663        (
1664            PROJECT_OPTIONS_FILE.into(),
1665            format_stored_options(&stored),
1666        ),
1667        ("package.json".into(), package_json),
1668        (".gitignore".into(), "/target\n/node_modules\n/public/assets\n/public/ssr\n/views/generated/*.ts\n/dist\n/storage/*.sqlite\n/storage/*.sqlite-*\n.env\n.DS_Store\n".to_owned()),
1669        (".env.example".into(), env_example_template(options.database, &options.features)),
1670        ("README.md".into(), project_readme(package, options)),
1671        ("src/main.rs".into(), main_template(&crate_name)),
1672        ("src/lib.rs".into(), lib_template(options.database.is_some(), &options.features)),
1673        ("config/mod.rs".into(), config_template(options.database.is_some())),
1674        ("app/controllers/mod.rs".into(), managed_modules(&["pub mod home_controller;", "pub use home_controller::HomeController;"])),
1675        ("app/controllers/home_controller.rs".into(), home_controller_template(options.render_mode)),
1676        ("app/props/mod.rs".into(), managed_modules(&[
1677            "pub mod demo_ssr_props;",
1678            "pub mod home_props;",
1679            "pub use demo_ssr_props::DemoSsrProps;",
1680            "pub use home_props::HomeProps;",
1681        ])),
1682        ("app/props/home_props.rs".into(), home_props_template()),
1683        ("app/props/demo_ssr_props.rs".into(), demo_ssr_props_template()),
1684        ("app/requests/mod.rs".into(), managed_modules(&[])),
1685        ("app/resources/mod.rs".into(), managed_modules(&[])),
1686        ("app/middleware/mod.rs".into(), managed_modules(&[])),
1687        ("app/commands/mod.rs".into(), commands_mod_template()),
1688        ("routes/web.rs".into(), home_route_template()),
1689        (
1690            format!("views/pages/home.{extension}").into(),
1691            home_page_template(options.frontend),
1692        ),
1693        (
1694            format!("views/pages/demo/spa.{extension}").into(),
1695            demo_spa_page_template(),
1696        ),
1697        (
1698            format!("views/pages/demo/ssr.{extension}").into(),
1699            demo_ssr_page_template(options.frontend),
1700        ),
1701        (
1702            format!("views/pages/demo/islands.{extension}").into(),
1703            demo_islands_page_template(),
1704        ),
1705        (
1706            format!("views/islands/counter.{extension}").into(),
1707            island_template("Counter", options.frontend),
1708        ),
1709        ("views/styles.css".into(), styles_template(options.tailwind)),
1710        ("views/generated/contracts.ts".into(), generated_contracts_template()),
1711        ("views/generated/routes.ts".into(), generated_routes_template()),
1712        ("vite.config.ts".into(), vite_template(false, options.tailwind)),
1713        ("vite.ssr.config.ts".into(), vite_template(true, options.tailwind)),
1714        ("tsconfig.json".into(), tsconfig_template()),
1715        ("public/.gitkeep".into(), String::new()),
1716        ("storage/cache/.gitkeep".into(), String::new()),
1717        ("storage/logs/.gitkeep".into(), String::new()),
1718    ];
1719    if options.database.is_some() {
1720        files.extend([
1721            ("app/models/mod.rs".into(), empty_model_registry()),
1722            (
1723                "database/migrations/mod.rs".into(),
1724                empty_migration_registry(),
1725            ),
1726            ("database/seeders/mod.rs".into(), seeder_template()),
1727            (
1728                "src/bin/phoenix-manage.rs".into(),
1729                management_template(
1730                    &crate_name,
1731                    options
1732                        .features
1733                        .iter()
1734                        .any(|feature| feature.has_migrations()),
1735                ),
1736            ),
1737        ]);
1738    }
1739    for feature in &options.features {
1740        files.push((
1741            format!("config/{}.toml", feature.key()).into(),
1742            feature_config_template(*feature),
1743        ));
1744    }
1745    Ok(files)
1746}
1747
1748// One grouped template literal per section; the length is the generated file.
1749#[allow(clippy::too_many_lines)]
1750fn env_example_template(database: Option<ProjectDatabase>, features: &[ProjectFeature]) -> String {
1751    let database_block = match database {
1752        None => {
1753            "# ── 数据库(创建时未启用)────────────────────────────\n# 需要时用 `px new --database sqlite|pgsql|mysql` 重新创建,\n# 或按 docs/CONFIG.md 手动启用驱动 feature 后设置:\n# DATABASE_URL=sqlite:storage/app.sqlite\n".to_owned()
1754        }
1755        Some(driver) => {
1756            let (active, hints) = match driver {
1757                ProjectDatabase::Sqlite => (
1758                    "DATABASE_URL=sqlite:storage/app.sqlite",
1759                    "# DATABASE_URL=postgresql://phoenix:secret@127.0.0.1:5432/phoenix\n# DATABASE_URL=mysql://phoenix:secret@127.0.0.1:3306/phoenix\n",
1760                ),
1761                ProjectDatabase::Pgsql => (
1762                    "DATABASE_URL=postgresql://phoenix:secret@127.0.0.1:5432/phoenix",
1763                    "# DATABASE_URL=sqlite:storage/app.sqlite\n",
1764                ),
1765                ProjectDatabase::Mysql => (
1766                    "DATABASE_URL=mysql://phoenix:secret@127.0.0.1:3306/phoenix",
1767                    "# DATABASE_URL=sqlite:storage/app.sqlite\n",
1768                ),
1769                ProjectDatabase::All => (
1770                    "DATABASE_URL=sqlite:storage/app.sqlite",
1771                    "# 已编译全部驱动,改 URL 即可换库:\n# DATABASE_URL=postgresql://phoenix:secret@127.0.0.1:5432/phoenix\n# DATABASE_URL=mysql://phoenix:secret@127.0.0.1:3306/phoenix\n",
1772                ),
1773            };
1774            format!("# ── 数据库 ──────────────────────────────────────────\n{active}\n{hints}")
1775        }
1776    };
1777    let feature_block = if features.is_empty() {
1778        String::new()
1779    } else {
1780        let mut block =
1781            String::from("\n# ── Feature 密钥(config/*.toml 里以 ${VAR} 引用)─────\n");
1782        for feature in [
1783            ProjectFeature::Pay,
1784            ProjectFeature::Captcha,
1785            ProjectFeature::Notify,
1786        ] {
1787            if features.contains(&feature) {
1788                block.push_str(feature_env_comments(feature));
1789            }
1790        }
1791        block
1792    };
1793    format!(
1794        "# 复制为 `.env`:前后端启动 + 数据库的运行时配置都在这里。\n# 优先级:.env < 进程环境变量。config/ 目录只放 Feature 配置(TOML)。\n\n# ── 应用 ────────────────────────────────────────────\nAPP_ENV=development\nAPP_ADDR=127.0.0.1:3000\nAPP_URL=http://127.0.0.1:3000\n\n# ── 前端(Vite 开发服务器,`px dev` 使用)───────────\nVITE_DEV_URL=http://127.0.0.1:5173\n\n{database_block}\n# ── 日志 ────────────────────────────────────────────\nPHOENIX_LOG=info,hyper=warn\n\n# ── 限流与信任代理 ──────────────────────────────────\nRATE_LIMIT_REQUESTS=60\nRATE_LIMIT_WINDOW_SECONDS=60\nTRUSTED_PROXIES=none\nALLOWED_HOSTS=127.0.0.1,localhost,[::1]\n{feature_block}"
1795    )
1796}
1797
1798const fn feature_env_comments(feature: ProjectFeature) -> &'static str {
1799    match feature {
1800        ProjectFeature::Captcha => "# 验证码无密钥;参数见 config/captcha.toml。\n",
1801        ProjectFeature::Pay => {
1802            "# PAY_WECHAT_API_V3_KEY=\n# PAY_ALIPAY_APP_PRIVATE_KEY=\n# PAY_ALIPAY_PUBLIC_KEY=\n"
1803        }
1804        ProjectFeature::Notify => "# 通知本地用内存邮件传输;接真实 SMTP 时在此加对应密钥。\n",
1805    }
1806}
1807
1808fn env_example_has_feature_comment(env: &str, feature: ProjectFeature) -> bool {
1809    match feature {
1810        ProjectFeature::Captcha => env.contains("# 验证码无密钥;参数见 config/captcha.toml。"),
1811        ProjectFeature::Pay => env.contains("# PAY_WECHAT_API_V3_KEY="),
1812        ProjectFeature::Notify => {
1813            env.contains("# 通知本地用内存邮件传输;接真实 SMTP 时在此加对应密钥。")
1814        }
1815    }
1816}
1817
1818fn append_feature_env_example(env: &str, feature: ProjectFeature) -> String {
1819    let mut updated = env.trim_end().to_owned();
1820    if !updated.contains("# ── Feature 密钥(config/*.toml 里以 ${VAR} 引用)─────")
1821    {
1822        updated.push_str("\n\n# ── Feature 密钥(config/*.toml 里以 ${VAR} 引用)─────");
1823    }
1824    updated.push('\n');
1825    updated.push_str(feature_env_comments(feature));
1826    updated
1827}
1828
1829/// `config/<feature>.toml` starter: non-secret parameters live here, secrets
1830/// are injected from `.env` through `${VAR}` (see `load_feature_config`).
1831// One template literal per Feature; the length is the generated files.
1832#[allow(clippy::too_many_lines)]
1833fn feature_config_template(feature: ProjectFeature) -> String {
1834    match feature {
1835        ProjectFeature::Captcha => {
1836            r"# 图形验证码 Feature(phoenix-captcha)。详见 docs/CAPTCHA.md。
1837#
1838# CaptchaConfig 目前在代码中构造(src/lib.rs 的 features()),本文件记录默认
1839# 可调项;修改后把对应值同步到 `CaptchaFeature::with_config(...)`。
1840#
1841# length = 5        # 每次挑战的字符数(1–16)
1842# width = 160       # SVG 画布宽度
1843# height = 60       # SVG 画布高度
1844# noise_curves = 3  # 干扰曲线条数
1845# noise_dots = 28   # 噪点数量
1846"
1847            .to_owned()
1848        }
1849        ProjectFeature::Pay => r#"# 聚合支付 Feature(phoenix-pay)。详见 docs/PAYMENTS.md。
1850#
1851# 结构留在本文件,密钥放 `.env`:字符串值支持 `${VAR}` 占位符,加载时从
1852# 环境注入(src/lib.rs 的 pay_manager() 通过 load_feature_config("pay") 读取)。
1853# 两个渠道段都注释时仅启用 MockProvider——本地/测试即可完整跑通下单与回调。
1854
1855# [wechat_native]                                       # 微信支付 Native(APIv3)
1856# app_id = "wx1234567890"
1857# mch_id = "1900000001"
1858# mch_serial_no = ""                                    # 商户 API 证书序列号
1859# api_v3_key = "${PAY_WECHAT_API_V3_KEY}"               # 密钥进 .env
1860# private_key_path = "storage/certs/apiclient_key.pem"  # 商户私钥(不进仓库)
1861# notify_url = "https://example.com/pay/notify/wechat"
1862
1863# [alipay_f2f]                                          # 支付宝当面付(RSA2)
1864# app_id = "2021000000000000"
1865# app_private_key = "${PAY_ALIPAY_APP_PRIVATE_KEY}"     # 密钥进 .env
1866# alipay_public_key = "${PAY_ALIPAY_PUBLIC_KEY}"        # 支付宝公钥(非应用公钥)
1867# notify_url = "https://example.com/pay/notify/alipay"
1868"#
1869        .to_owned(),
1870        ProjectFeature::Notify => {
1871            r#"# 通知 Feature(phoenix-notify):邮件 + 数据库双通道。详见 docs/NOTIFICATIONS.md。
1872#
1873# 本地默认内存邮件传输 + 内存存储(src/lib.rs 的 notifier());
1874# 生产环境在代码中替换真实 MailTransport 与数据库 store。
1875#
1876# from = "noreply@example.com"   # 通知邮件的默认发件地址(应用代码中使用)
1877"#
1878            .to_owned()
1879        }
1880    }
1881}
1882
1883fn config_template(database: bool) -> String {
1884    let database = if database {
1885        " (`DATABASE_URL` selects the database)"
1886    } else {
1887        ""
1888    };
1889    format!(
1890        "pub use phoenix::config::{{\n    AppConfig, AppConfigBuilder, ConfigError, Environment, SecretValue, load_feature_config,\n}};\n\n/// Load this application's configuration.\n///\n/// Runtime settings come from `.env`, then the process environment{database}.\n/// Feature settings live in `config/<feature>.toml` via `load_feature_config`.\n///\n/// # Errors\n///\n/// Returns a source, validation, or production-requirement error.\npub fn load() -> Result<AppConfig, ConfigError> {{\n    AppConfig::load()\n}}\n"
1891    )
1892}
1893
1894// The body is one template literal; the line count is the generated file.
1895#[allow(clippy::too_many_lines)]
1896fn management_template(crate_name: &str, feature_migrations: bool) -> String {
1897    let migrations_expr = if feature_migrations {
1898        // Official Features (pay / notify) contribute migrations through their plugins.
1899        "{\n        let mut migrations = __PHOENIX_APP_CRATE__::migrations::all();\n        let features = __PHOENIX_APP_CRATE__::features()\n            .map_err(|error| error as Box<dyn Error>)?;\n        migrations.extend(features.into_parts().migrations);\n        migrations\n    }"
1900    } else {
1901        "__PHOENIX_APP_CRATE__::migrations::all()"
1902    };
1903    r#"#[cfg(feature = "database")]
1904use std::{env, error::Error, io};
1905
1906#[cfg(feature = "database")]
1907use phoenix::database::MigrationRunner;
1908
1909#[cfg(feature = "database")]
1910type CommandResult<T = ()> = Result<T, Box<dyn Error>>;
1911
1912#[cfg(not(feature = "database"))]
1913fn main() {
1914    println!("Database support is disabled; enable the sqlite, pgsql, or mysql feature.");
1915}
1916
1917#[cfg(feature = "database")]
1918#[tokio::main]
1919async fn main() -> CommandResult {
1920    let arguments = env::args().skip(1).collect::<Vec<_>>();
1921    let command = arguments
1922        .first()
1923        .map(String::as_str)
1924        .ok_or_else(|| input_error("expected migrate, status, rollback, fresh, or seed"))?;
1925    let options = &arguments[1..];
1926    if !matches!(command, "migrate" | "status" | "rollback" | "fresh" | "seed") {
1927        return Err(input_error(format!("unknown management command `{command}`")).into());
1928    }
1929
1930    let config = __PHOENIX_APP_CRATE__::config::load()?;
1931    let mut database = __PHOENIX_APP_CRATE__::database(&config).await?;
1932    if command == "seed" {
1933        require_no_options(options)?;
1934        __PHOENIX_APP_CRATE__::seeders::run(&mut database).await?;
1935        println!("Seeders completed.");
1936        return Ok(());
1937    }
1938
1939    let mut runner = MigrationRunner::new(
1940        &mut database,
1941        __PHOENIX_MIGRATIONS__,
1942    )?;
1943    match command {
1944        "migrate" => {
1945            require_no_options(options)?;
1946            let applied = runner.up().await?;
1947            println!("Applied {applied} migration(s).");
1948        }
1949        "status" => {
1950            require_no_options(options)?;
1951            let plan = runner.plan().await?;
1952            if plan.applied.is_empty() && plan.pending.is_empty() {
1953                println!("No migrations registered or applied.");
1954            }
1955            for migration in plan.applied {
1956                println!(
1957                    "APPLIED  {}  batch={}  {}  {}",
1958                    migration.id, migration.batch, migration.applied_at, migration.name
1959                );
1960            }
1961            for id in plan.pending {
1962                println!("PENDING  {id}");
1963            }
1964        }
1965        "rollback" => {
1966            let steps = parse_rollback_steps(options)?;
1967            let rolled_back = runner.down(steps).await?;
1968            println!("Rolled back {rolled_back} migration(s).");
1969        }
1970        "fresh" => {
1971            let run_seeders = parse_fresh_options(options)?;
1972            let applied = runner.plan().await?.applied.len();
1973            let rolled_back = runner.down(applied).await?;
1974            let migrated = runner.up().await?;
1975            println!(
1976                "Rebuilt the database: rolled back {rolled_back}, applied {migrated} migration(s)."
1977            );
1978            drop(runner);
1979            if run_seeders {
1980                __PHOENIX_APP_CRATE__::seeders::run(&mut database).await?;
1981                println!("Seeders completed.");
1982            }
1983        }
1984        "seed" => unreachable!("seed is handled before creating the migration runner"),
1985        _ => unreachable!("management commands are validated before connecting"),
1986    }
1987    Ok(())
1988}
1989
1990#[cfg(feature = "database")]
1991fn require_no_options(options: &[String]) -> CommandResult {
1992    if options.is_empty() {
1993        Ok(())
1994    } else {
1995        Err(input_error(format!("unexpected arguments: {}", options.join(" "))).into())
1996    }
1997}
1998
1999#[cfg(feature = "database")]
2000fn parse_rollback_steps(options: &[String]) -> CommandResult<usize> {
2001    let [steps] = options else {
2002        return Err(input_error("rollback expects one positive step count").into());
2003    };
2004    steps
2005        .parse::<usize>()
2006        .ok()
2007        .filter(|steps| *steps > 0)
2008        .ok_or_else(|| input_error("rollback step count must be a positive integer").into())
2009}
2010
2011#[cfg(feature = "database")]
2012fn parse_fresh_options(options: &[String]) -> CommandResult<bool> {
2013    match options {
2014        [] => Ok(false),
2015        [option] if option == "--seed" => Ok(true),
2016        _ => Err(input_error("fresh only accepts --seed").into()),
2017    }
2018}
2019
2020#[cfg(feature = "database")]
2021fn input_error(message: impl Into<String>) -> io::Error {
2022    io::Error::new(io::ErrorKind::InvalidInput, message.into())
2023}
2024"#
2025    .replace("__PHOENIX_MIGRATIONS__", migrations_expr)
2026    .replace("__PHOENIX_APP_CRATE__", crate_name)
2027}
2028
2029fn seeder_template() -> String {
2030    format!(
2031        r"use std::error::Error;
2032
2033use phoenix::database::Database;
2034
2035{MODULES_START}
2036{MODULES_END}
2037
2038/// Insert repeatable development or test data.
2039///
2040/// Factories generated by `px make:model --factory` land in this directory and
2041/// are registered above. They compile only with the `factory` feature, so none
2042/// of this reaches a release build.
2043///
2044/// # Errors
2045///
2046/// Returns the first application or database error raised by a seeder.
2047pub async fn run(_database: &mut Database) -> Result<(), Box<dyn Error>> {{
2048    Ok(())
2049}}
2050"
2051    )
2052}
2053
2054fn empty_model_registry() -> String {
2055    format!(
2056        "{MODULES_START}\n{MODULES_END}\n\n{MODELS_START}\n{}\n{MODELS_END}\n",
2057        render_model_registry(&BTreeSet::new()).join("\n")
2058    )
2059}
2060
2061fn empty_migration_registry() -> String {
2062    format!(
2063        "{MIGRATIONS_START}\n{}\n{MIGRATIONS_END}\n",
2064        render_migration_registry(&BTreeSet::new()).join("\n")
2065    )
2066}
2067
2068fn project_readme(package: &str, options: &NewProjectOptions) -> String {
2069    let mode = match options.render_mode {
2070        ProjectRenderMode::Spa => "SPA",
2071        ProjectRenderMode::Ssr => "SSR",
2072        ProjectRenderMode::Islands => "Islands",
2073    };
2074    let database = options.database.map_or_else(
2075        || "This project has no database dependency. Create one with `px new --database sqlite|pgsql|mysql`.".to_owned(),
2076        |database| format!("Selected driver: `{}` (`DATABASE_URL` in `.env`). Use `px migrate` and `px status` for migrations.", database.cargo_feature()),
2077    );
2078    let tailwind = if options.tailwind {
2079        "Tailwind CSS v4 is enabled through `@tailwindcss/vite`."
2080    } else {
2081        "Tailwind CSS is not enabled; add it at creation time with `px new --tailwind`."
2082    };
2083    let features = if options.features.is_empty() {
2084        String::new()
2085    } else {
2086        use std::fmt::Write as _;
2087
2088        let mut list = String::new();
2089        for feature in &options.features {
2090            let _ = writeln!(
2091                list,
2092                "- `{key}` — {summary}(配置:`config/{key}.toml`)",
2093                key = feature.key(),
2094                summary = feature.summary(),
2095            );
2096        }
2097        format!(
2098            "\n## 已启用 Feature\n\n{list}\n装配代码在 `src/lib.rs` 的 `features()`;密钥放 `.env`,非敏感参数放 `config/*.toml`。\n\n> 注意:crates.io 上已发布的 `phoenixrs` 尚未包含 `captcha` / `pay` / `notify`\n> feature(需要 > {PHOENIXRS_VERSION} 的后续版本)。在其发布前请使用\n> `px new --framework-path <Phoenix-rs 检出>` 的本地依赖模式。\n"
2099        )
2100    };
2101    format!(
2102        "# {package}\n\nPhoenix Rust + React application.\n\n## Start\n\n```bash\ncp .env.example .env\npx dev\n```\n\n`px dev` builds the browser and renderer bundles before it starts the app, then rebuilds them whenever Rust or React source changes. The development document therefore uses the same Vite assets and renderer contract as `npm run build`.\n\n运行时配置(地址 / 数据库 / 日志 / 限流)都在 `.env`;`config/` 目录只存放 Feature 的 TOML 配置。\n\n## Rendering mode\n\nThis application starts in **{mode}** mode. Change only the page chain in `app/controllers/home_controller.rs`:\n\n```rust\n.spa()       // SPA\n.ssr()       // SSR\n.islands()   // Islands\n```\n\nThe controller, routes, renderer and build pipeline stay unchanged.\n\n首页链接了三种渲染模式的最小演示页:`/demo/spa`、`/demo/ssr`、`/demo/islands`\n(`views/pages/demo/` 与 `HomeController`,确认理解后即可删除)。\n\n## Optional integrations\n\n- {database}\n- {tailwind}\n{features}\n## Release\n\n```bash\npx release --version 0.1.0 --tarball\n```\n\n`px release:install` / `px release:rollback` 可在切换版本后执行 `deploy/restart.sh`\n(或 `--restart-cmd`);需要自动重启时创建该脚本并 `chmod +x`。\n"
2103    )
2104}
2105
2106fn main_template(crate_name: &str) -> String {
2107    format!(
2108        r#"use phoenix::prelude::{{CommandResult, Console, LogFormat, Logging}};
2109
2110use {crate_name}::commands;
2111
2112#[tokio::main]
2113async fn main() -> CommandResult {{
2114    Console::new(env!("CARGO_PKG_NAME"))
2115        .about("Phoenix application")
2116        .serve(|_ctx| async move {{
2117            let config = {crate_name}::config::load()?;
2118            let address = config.address().to_owned();
2119            let public_url = config.public_url().to_owned();
2120            let production = config.environment().is_production();
2121            let _logging = Logging::new()
2122                .format(if production {{ LogFormat::Json }} else {{ LogFormat::Compact }})
2123                .ansi(!production)
2124                .init()?;
2125            let server = {crate_name}::application(config).await?.bind(&address).await?;
2126            println!(
2127                "Phoenix application ready at {{public_url}} (listening on {{}})",
2128                server.local_addr()
2129            );
2130            server
2131                .run_with_shutdown(async {{
2132                    let _ = tokio::signal::ctrl_c().await;
2133                }})
2134                .await?;
2135            Ok(())
2136        }})
2137        .commands(commands::registry())
2138        .run()
2139        .await
2140}}
2141"#
2142    )
2143}
2144
2145// The body is one template literal; the line count is the generated file.
2146#[allow(clippy::too_many_lines)]
2147fn lib_template(database: bool, features: &[ProjectFeature]) -> String {
2148    if !features.is_empty() {
2149        return lib_template_with_features(database, features);
2150    }
2151    r#"#[path = "../config/mod.rs"]
2152pub mod config;
2153#[path = "../app/commands/mod.rs"]
2154pub mod commands;
2155#[path = "../app/controllers/mod.rs"]
2156pub mod controllers;
2157#[path = "../app/middleware/mod.rs"]
2158pub mod middleware;
2159#[cfg(feature = "database")]
2160#[path = "../app/models/mod.rs"]
2161pub mod models;
2162#[path = "../app/props/mod.rs"]
2163pub mod props;
2164#[path = "../app/requests/mod.rs"]
2165pub mod requests;
2166#[path = "../app/resources/mod.rs"]
2167pub mod resources;
2168#[cfg(feature = "database")]
2169#[path = "../database/migrations/mod.rs"]
2170pub mod migrations;
2171#[cfg(feature = "database")]
2172#[path = "../database/seeders/mod.rs"]
2173pub mod seeders;
2174
2175use phoenix::prelude::{
2176    AccessLog, Application, AssetManifest, Csrf, HostAllowlist, NodeRenderer,
2177    NonceSecurityPolicy, RateLimit, RateLimitConfig, RendererConfig, RendererManifest, RequestId, Routes, ServeProductionAssets, SessionConfig, SessionMiddleware,
2178    SessionStore, StateMiddleware, TrustedProxies,
2179};
2180#[cfg(feature = "database")]
2181use phoenix::prelude::{Database, DatabaseError};
2182
2183use config::AppConfig;
2184
2185#[must_use]
2186#[allow(clippy::duplicate_mod)]
2187pub fn routes(
2188    config: &AppConfig,
2189    assets: Option<&AssetManifest>,
2190    renderer: &NodeRenderer,
2191) -> Routes {
2192    let session_config = SessionConfig {
2193        secure: config.public_url().starts_with("https://"),
2194        ..SessionConfig::default()
2195    };
2196    let session_store = SessionStore::memory(session_config.max_age);
2197
2198    let mut routes = phoenix::mount_routes!()
2199        .with_middleware(TrustedProxies::new(config.trusted_proxies().iter().copied()))
2200        .with_middleware(RequestId)
2201        .with_middleware(AccessLog);
2202    if let Some(assets) = assets.cloned() {
2203        // Serve hashed Vite assets before session/CSRF so static GETs stay cheap.
2204        routes = routes.with_middleware(ServeProductionAssets::new(assets, "public/assets"));
2205    }
2206    routes
2207        .with_middleware(HostAllowlist::new(config.allowed_hosts().iter().cloned()))
2208        .with_middleware(RateLimit::new(RateLimitConfig {
2209            requests: config.rate_limit_requests(),
2210            window: config.rate_limit_window(),
2211        }))
2212        .with_middleware(content_security_policy(config))
2213        .with_middleware(SessionMiddleware::new(session_store, session_config))
2214        .with_middleware(Csrf)
2215        .with_middleware(StateMiddleware::new(config.clone()))
2216        .with_middleware(StateMiddleware::new(assets.cloned()))
2217        .with_middleware(StateMiddleware::new(renderer.clone()))
2218}
2219
2220fn content_security_policy(config: &AppConfig) -> NonceSecurityPolicy {
2221    if !config.environment().is_production() {
2222        return NonceSecurityPolicy::development(
2223            config
2224                .vite_dev_url()
2225                .expect("development configuration always has a Vite origin"),
2226        )
2227        .expect("AppConfig validates VITE_DEV_URL as one trusted HTTP(S) origin");
2228    }
2229    NonceSecurityPolicy::default()
2230}
2231
2232/// Build the Phoenix application.
2233///
2234/// # Errors
2235///
2236/// Returns a route error when route names or patterns conflict.
2237pub async fn application(
2238    config: AppConfig,
2239) -> Result<Application, Box<dyn std::error::Error + Send + Sync>> {
2240    let vite_dev_server = std::env::var_os("PHOENIX_VITE_DEV").is_some();
2241    let (assets, renderer) = if !vite_dev_server {
2242        let assets = AssetManifest::load("public/assets/phoenix-manifest.json")?;
2243        let renderer_manifest = RendererManifest::load("public/ssr/phoenix-renderer.json")?;
2244        let renderer = NodeRenderer::new(
2245            RendererConfig::production(&assets, &renderer_manifest, "public/ssr")?,
2246        );
2247        (Some(assets), renderer)
2248    } else {
2249        // `px dev` sets PHOENIX_VITE_DEV so JS comes from Vite HMR.
2250        // Still load the hashed CSS manifest so Islands SSR can link stylesheets
2251        // in <head> before the Vite client runs — otherwise hard refresh FOUCs.
2252        let assets = AssetManifest::load("public/assets/phoenix-manifest.json").ok();
2253        (
2254            assets,
2255            NodeRenderer::new(RendererConfig::node("public/ssr/renderer.js")),
2256        )
2257    };
2258    renderer.warm_up().await?;
2259    let built = routes(&config, assets.as_ref(), &renderer);
2260    // Connect the database once at startup and share it with every handler via
2261    // request state (`State<Database>` / `extensions().get::<Database>()`).
2262    #[cfg(feature = "database")]
2263    let built = built.with_middleware(StateMiddleware::new(database(&config).await?));
2264    Ok(Application::new(built)?)
2265}
2266
2267/// Connect the configured database with every registered Toasty model.
2268///
2269/// # Errors
2270///
2271/// Returns a database error when the URL or connection is invalid.
2272#[cfg(feature = "database")]
2273pub async fn database(config: &AppConfig) -> Result<Database, DatabaseError> {
2274    Database::builder(models::all())
2275        .connect(config.database_url())
2276        .await
2277}
2278"#
2279    .to_owned()
2280}
2281
2282/// `src/lib.rs` variant that assembles the official Features selected by
2283/// `px new --feature ...` (docs/FEATURES.md).
2284// The body is one template literal; the line count is the generated file.
2285#[allow(clippy::too_many_lines)]
2286fn lib_template_with_features(_database: bool, features: &[ProjectFeature]) -> String {
2287    let captcha = features.contains(&ProjectFeature::Captcha);
2288    let pay = features.contains(&ProjectFeature::Pay);
2289    let notify = features.contains(&ProjectFeature::Notify);
2290
2291    let arc_import = if pay || notify {
2292        "\nuse std::sync::Arc;\n"
2293    } else {
2294        ""
2295    };
2296
2297    let mut plugin_lines = String::new();
2298    if captcha {
2299        plugin_lines.push_str(
2300            "    // 图形验证码:注册 GET /captcha(路由名 captcha.image),依赖 Session。\n    // 自定义样式用 CaptchaFeature::with_config(...)(参数见 config/captcha.toml),\n    // 登录表单接入见 docs/CAPTCHA.md(CaptchaProtected 提取器)。\n    let features = features.plugin(phoenix::captcha::CaptchaFeature::new())?;\n",
2301        );
2302    }
2303    if pay {
2304        plugin_lines.push_str(
2305            "    // 聚合支付:注册回调路由(pay.notify.*)与 payments 迁移。docs/PAYMENTS.md。\n    let features = features.plugin(phoenix::pay::PayFeature::new(pay_manager()?))?;\n",
2306        );
2307    }
2308    if notify {
2309        plugin_lines.push_str(
2310            "    // 通知:注册 notifications 迁移;发送入口见下方 notifier()。docs/NOTIFICATIONS.md。\n    let features = features.plugin(phoenix::notify::NotifyFeature::new())?;\n",
2311        );
2312    }
2313
2314    let mut helper_fns = String::new();
2315    if pay {
2316        helper_fns.push_str(
2317            r#"
2318/// 从 `config/pay.toml` 装配支付渠道;文件缺省时仅启用 Mock(本地即可闭环)。
2319///
2320/// 密钥经 `.env` 注入(`${VAR}` 占位符),非敏感参数留在 TOML。
2321fn pay_manager() -> Result<
2322    Arc<phoenix::pay::PayManager>,
2323    Box<dyn std::error::Error + Send + Sync>,
2324> {
2325    use phoenix::pay::{AlipayF2FProvider, MockProvider, PayManager, WechatNativeProvider};
2326
2327    #[derive(Default, serde::Deserialize)]
2328    struct PayFileConfig {
2329        wechat_native: Option<phoenix::pay::WechatNativeConfig>,
2330        alipay_f2f: Option<phoenix::pay::AlipayF2FConfig>,
2331    }
2332
2333    let file: PayFileConfig = phoenix::config::load_feature_config("pay")?;
2334    let mut builder = PayManager::builder().provider(Arc::new(MockProvider::new()));
2335    if let Some(wechat) = file.wechat_native {
2336        builder = builder.provider(Arc::new(WechatNativeProvider::new(wechat)));
2337    }
2338    if let Some(alipay) = file.alipay_f2f {
2339        builder = builder.provider(Arc::new(AlipayF2FProvider::new(alipay)));
2340    }
2341    Ok(Arc::new(builder.build()))
2342}
2343"#,
2344        );
2345    }
2346    if notify {
2347        helper_fns.push_str(
2348            r"
2349/// 通知发送器:本地为内存邮件传输 + 内存存储,重启即清空。
2350/// 上线前替换为真实 MailTransport 与数据库 store(docs/NOTIFICATIONS.md)。
2351#[must_use]
2352pub fn notifier() -> phoenix::notify::Notifier {
2353    let (mailer, _outbox) = phoenix::mail::Mailer::memory();
2354    phoenix::notify::Notifier::new()
2355        .with_mailer(mailer)
2356        .with_store(Arc::new(phoenix::notify::MemoryNotificationStore::new()))
2357}
2358",
2359        );
2360    }
2361
2362    format!(
2363        r#"#[path = "../config/mod.rs"]
2364pub mod config;
2365#[path = "../app/commands/mod.rs"]
2366pub mod commands;
2367#[path = "../app/controllers/mod.rs"]
2368pub mod controllers;
2369#[path = "../app/middleware/mod.rs"]
2370pub mod middleware;
2371#[cfg(feature = "database")]
2372#[path = "../app/models/mod.rs"]
2373pub mod models;
2374#[path = "../app/props/mod.rs"]
2375pub mod props;
2376#[path = "../app/requests/mod.rs"]
2377pub mod requests;
2378#[path = "../app/resources/mod.rs"]
2379pub mod resources;
2380#[cfg(feature = "database")]
2381#[path = "../database/migrations/mod.rs"]
2382pub mod migrations;
2383#[cfg(feature = "database")]
2384#[path = "../database/seeders/mod.rs"]
2385pub mod seeders;
2386{arc_import}
2387use phoenix::plugin::FeatureSet;
2388use phoenix::prelude::{{
2389    AccessLog, Application, AssetManifest, Csrf, HostAllowlist, NodeRenderer,
2390    NonceSecurityPolicy, RateLimit, RateLimitConfig, RendererConfig, RendererManifest, RequestId, RouteGroup, Routes, ServeProductionAssets, SessionConfig, SessionMiddleware,
2391    SessionStore, StateMiddleware, TrustedProxies,
2392}};
2393#[cfg(feature = "database")]
2394use phoenix::prelude::{{Database, DatabaseError}};
2395
2396use config::AppConfig;
2397
2398/// `px new --feature` 选中的官方 Feature 装配(docs/FEATURES.md)。
2399///
2400/// # Errors
2401///
2402/// 返回 Feature 安装冲突(名称 / 能力 / 迁移 ID 重复)或 Feature 配置错误。
2403pub fn features() -> Result<FeatureSet, Box<dyn std::error::Error + Send + Sync>> {{
2404    let features = FeatureSet::new();
2405{plugin_lines}    Ok(features)
2406}}
2407{helper_fns}
2408/// # Errors
2409///
2410/// 返回路由冲突或 Feature 装配错误。
2411#[allow(clippy::duplicate_mod)]
2412pub fn routes(
2413    config: &AppConfig,
2414    assets: Option<&AssetManifest>,
2415    renderer: &NodeRenderer,
2416) -> Result<Routes, Box<dyn std::error::Error + Send + Sync>> {{
2417    let session_config = SessionConfig {{
2418        secure: config.public_url().starts_with("https://"),
2419        ..SessionConfig::default()
2420    }};
2421    let session_store = SessionStore::memory(session_config.max_age);
2422
2423    let mut routes = phoenix::mount_routes!()
2424        // 业务路由启用 CSRF;Feature 路由不在此列——支付回调等由平台服务器
2425        // 调用,真实性靠验签(docs/PAYMENTS.md),挂 CSRF 会拒掉合法通知。
2426        .scoped(RouteGroup::new().middleware(Csrf))
2427        .merge(features()?.into_routes())
2428        .with_middleware(TrustedProxies::new(config.trusted_proxies().iter().copied()))
2429        .with_middleware(RequestId)
2430        .with_middleware(AccessLog);
2431    if let Some(assets) = assets.cloned() {{
2432        // Serve hashed Vite assets before session/CSRF so static GETs stay cheap.
2433        routes = routes.with_middleware(ServeProductionAssets::new(assets, "public/assets"));
2434    }}
2435    Ok(routes
2436        .with_middleware(HostAllowlist::new(config.allowed_hosts().iter().cloned()))
2437        .with_middleware(RateLimit::new(RateLimitConfig {{
2438            requests: config.rate_limit_requests(),
2439            window: config.rate_limit_window(),
2440        }}))
2441        .with_middleware(content_security_policy(config))
2442        // 会话全局挂载:验证码等 Feature 路由依赖 Session。
2443        .with_middleware(SessionMiddleware::new(session_store, session_config))
2444        .with_middleware(StateMiddleware::new(config.clone()))
2445        .with_middleware(StateMiddleware::new(assets.cloned()))
2446        .with_middleware(StateMiddleware::new(renderer.clone())))
2447}}
2448
2449fn content_security_policy(config: &AppConfig) -> NonceSecurityPolicy {{
2450    if !config.environment().is_production() {{
2451        return NonceSecurityPolicy::development(
2452            config
2453                .vite_dev_url()
2454                .expect("development configuration always has a Vite origin"),
2455        )
2456        .expect("AppConfig validates VITE_DEV_URL as one trusted HTTP(S) origin");
2457    }}
2458    NonceSecurityPolicy::default()
2459}}
2460
2461/// Build the Phoenix application.
2462///
2463/// # Errors
2464///
2465/// Returns a route error when route names or patterns conflict.
2466pub async fn application(
2467    config: AppConfig,
2468) -> Result<Application, Box<dyn std::error::Error + Send + Sync>> {{
2469    let vite_dev_server = std::env::var_os("PHOENIX_VITE_DEV").is_some();
2470    let (assets, renderer) = if !vite_dev_server {{
2471        let assets = AssetManifest::load("public/assets/phoenix-manifest.json")?;
2472        let renderer_manifest = RendererManifest::load("public/ssr/phoenix-renderer.json")?;
2473        let renderer = NodeRenderer::new(
2474            RendererConfig::production(&assets, &renderer_manifest, "public/ssr")?,
2475        );
2476        (Some(assets), renderer)
2477    }} else {{
2478        // `px dev` sets PHOENIX_VITE_DEV so JS comes from Vite HMR.
2479        // Still load the hashed CSS manifest so Islands SSR can link stylesheets
2480        // in <head> before the Vite client runs — otherwise hard refresh FOUCs.
2481        let assets = AssetManifest::load("public/assets/phoenix-manifest.json").ok();
2482        (
2483            assets,
2484            NodeRenderer::new(RendererConfig::node("public/ssr/renderer.js")),
2485        )
2486    }};
2487    renderer.warm_up().await?;
2488    let built = routes(&config, assets.as_ref(), &renderer)?;
2489    // Connect the database once at startup and share it with every handler via
2490    // request state (`State<Database>` / `extensions().get::<Database>()`).
2491    #[cfg(feature = "database")]
2492    let built = built.with_middleware(StateMiddleware::new(database(&config).await?));
2493    Ok(Application::new(built)?)
2494}}
2495
2496/// Connect the configured database with every registered Toasty model.
2497///
2498/// # Errors
2499///
2500/// Returns a database error when the URL or connection is invalid.
2501#[cfg(feature = "database")]
2502pub async fn database(config: &AppConfig) -> Result<Database, DatabaseError> {{
2503    Database::builder(models::all())
2504        .connect(config.database_url())
2505        .await
2506}}
2507"#
2508    )
2509}
2510
2511fn commands_mod_template() -> String {
2512    format!(
2513        "use phoenix::prelude::commands;\n\n{MODULES_START}\n{MODULES_END}\n\ncommands! {{\n{COMMANDS_START}\n{COMMANDS_END}\n}}\n"
2514    )
2515}
2516
2517fn command_template(function_name: &str) -> String {
2518    format!(
2519        r#"use phoenix::prelude::{{CommandContext, CommandResult}};
2520
2521/// Application console command.
2522#[allow(clippy::unused_async)]
2523pub async fn {function_name}(_ctx: CommandContext<'_>) -> CommandResult {{
2524    println!("{function_name} ran.");
2525    Ok(())
2526}}
2527"#
2528    )
2529}
2530
2531// The body is one template literal; the line count is the generated file.
2532#[allow(clippy::too_many_lines)]
2533fn home_controller_template(render_mode: ProjectRenderMode) -> String {
2534    format!(
2535        r#"use std::time::{{SystemTime, UNIX_EPOCH}};
2536
2537use phoenix::prelude::{{AssetManifest, NodeRenderer, Page, Request, Response, StatusCode}};
2538
2539use crate::config::AppConfig;
2540use crate::props::{{DemoSsrProps, HomeProps}};
2541
2542pub struct HomeController;
2543
2544impl HomeController {{
2545    /// 首页;渲染模式由 `px new` 的选择决定(当前 `{render_mode}`)。
2546    pub async fn index(request: Request) -> Response {{
2547        let page = Page::new(
2548            "home",
2549            HomeProps {{
2550                title: "Phoenix is ready".to_owned(),
2551                description: "Rust owns the application contract; React renders the page.".to_owned(),
2552            }},
2553        )
2554        {render_mode};
2555        render(&request, page).await
2556    }}
2557
2558    /// SPA 演示:整页交给浏览器 React 渲染,任意组件可直接交互。
2559    pub async fn demo_spa(request: Request) -> Response {{
2560        render(&request, Page::new("demo/spa", serde_json::json!({{}})).spa()).await
2561    }}
2562
2563    /// SSR 演示:服务端先渲染完整 HTML,首屏即含数据(查看网页源代码可见)。
2564    pub async fn demo_ssr(request: Request) -> Response {{
2565        let rendered_at = SystemTime::now()
2566            .duration_since(UNIX_EPOCH)
2567            .map_or_else(|_| "epoch".to_owned(), |at| at.as_secs().to_string());
2568        render(&request, Page::new("demo/ssr", DemoSsrProps {{ rendered_at }}).ssr()).await
2569    }}
2570
2571    /// Islands 演示:静态 HTML 中只有标记 `client:load` 的岛屿被水合。
2572    pub async fn demo_islands(request: Request) -> Response {{
2573        render(&request, Page::new("demo/islands", serde_json::json!({{}})).islands()).await
2574    }}
2575}}
2576
2577/// 注入 Vite 资源并交给 Node renderer 输出(三种渲染模式共用)。
2578async fn render(request: &Request, mut page: Page) -> Response {{
2579    let renderer = request.extensions().get::<NodeRenderer>().cloned();
2580    let assets = request
2581        .extensions()
2582        .get::<Option<AssetManifest>>()
2583        .and_then(Option::as_ref);
2584    let vite_dev_url = request
2585        .extensions()
2586        .get::<AppConfig>()
2587        .and_then(AppConfig::vite_dev_url);
2588    if let Some(assets) = assets {{
2589        page = match page.production_assets(assets, "client") {{
2590            Ok(page) => page,
2591            Err(error) => {{
2592                return Response::text(format!("asset manifest error: {{error}}"))
2593                    .with_status(StatusCode::INTERNAL_SERVER_ERROR);
2594            }}
2595        }};
2596    }}
2597    // Only `px dev` (PHOENIX_VITE_DEV) may override the browser entry with Vite.
2598    // Packaged binaries must keep hashed assets even when APP_ENV=development /
2599    // VITE_DEV_URL is set — otherwise HTML leaks the Vite origin.
2600    if std::env::var_os("PHOENIX_VITE_DEV").is_some()
2601        && let Some(vite_dev_url) = vite_dev_url
2602    {{
2603        page = page.script_src(format!(
2604            "{{}}/@id/__x00__virtual:phoenix/client",
2605            vite_dev_url.trim_end_matches('/'),
2606        ));
2607    }}
2608    match renderer {{
2609        Some(renderer) => page.respond_with_renderer(request, &renderer).await,
2610        None => Response::text("Phoenix renderer is unavailable")
2611            .with_status(StatusCode::INTERNAL_SERVER_ERROR),
2612    }}
2613}}
2614"#,
2615        render_mode = render_mode.page_builder(),
2616    )
2617}
2618
2619fn home_props_template() -> String {
2620    r#"use serde::Serialize;
2621
2622#[phoenix::contract(page, page = "home")]
2623#[derive(Serialize)]
2624pub struct HomeProps {
2625    pub title: String,
2626    pub description: String,
2627}
2628"#
2629    .to_owned()
2630}
2631
2632fn demo_ssr_props_template() -> String {
2633    r#"use serde::Serialize;
2634
2635/// SSR 演示页数据:由服务端注入,首屏 HTML 即包含(`views/pages/demo/ssr`)。
2636#[phoenix::contract(page, page = "demo/ssr")]
2637#[derive(Serialize)]
2638#[serde(rename_all = "camelCase")]
2639pub struct DemoSsrProps {
2640    pub rendered_at: String,
2641}
2642"#
2643    .to_owned()
2644}
2645
2646fn home_route_template() -> String {
2647    r#"use phoenix::prelude::Routes;
2648
2649use crate::controllers::HomeController;
2650
2651#[must_use]
2652pub fn routes() -> Routes {
2653    Routes::new()
2654        .get("/", HomeController::index)
2655        .name("home")
2656        // 三种渲染模式的最小演示页(确认理解后可整组删除)。
2657        .get("/demo/spa", HomeController::demo_spa)
2658        .name("demo.spa")
2659        .get("/demo/ssr", HomeController::demo_ssr)
2660        .name("demo.ssr")
2661        .get("/demo/islands", HomeController::demo_islands)
2662        .name("demo.islands")
2663}
2664"#
2665    .to_owned()
2666}
2667
2668const HOME_PAGE_BODY: &str = r#"  return (
2669    <main className="welcome">
2670      <p className="eyebrow">PHOENIX / RUST + REACT</p>
2671      <h1>{title}</h1>
2672      <p>{description}</p>
2673      {/* 同一套控制器 / 路由下的三种渲染模式,每页一个最小演示。 */}
2674      <ul className="demo-links">
2675        <li>
2676          <Link href={demo.spa()}>SPA</Link> — 整页浏览器渲染,交互最自由
2677        </li>
2678        <li>
2679          <Link href={demo.ssr()}>SSR</Link> — 服务端渲染完整 HTML,首屏即含数据
2680        </li>
2681        <li>
2682          <Link href={demo.islands()}>Islands</Link> — 静态页里只水合少量交互岛
2683        </li>
2684      </ul>
2685      <code>px make:model Post --all</code>
2686    </main>
2687  );
2688}
2689"#;
2690
2691fn home_page_template(frontend: ProjectFrontend) -> String {
2692    let (imports, signature) = match frontend {
2693        ProjectFrontend::Tsx => (
2694            concat!(
2695                "import { Link } from \"@apizero/react\";\n",
2696                "import type { HomeProps } from \"../generated/contracts.js\";\n",
2697                "import { demo } from \"../generated/routes.js\";",
2698            ),
2699            "export default function Home({ title, description }: HomeProps) {",
2700        ),
2701        ProjectFrontend::Jsx => (
2702            concat!(
2703                "import { Link } from \"@apizero/react\";\n",
2704                "import { demo } from \"../generated/routes.js\";",
2705            ),
2706            "export default function Home({ title, description }) {",
2707        ),
2708    };
2709    format!("{imports}\n\n{signature}\n{HOME_PAGE_BODY}")
2710}
2711
2712/// SPA 演示页:整页 hydrate,`useState` 计数器即时生效(TSX/JSX 同文)。
2713fn demo_spa_page_template() -> String {
2714    r#"import { useState } from "react";
2715import { Link } from "@apizero/react";
2716import { home } from "../../generated/routes.js";
2717
2718// SPA:整页都在浏览器渲染——查看网页源代码只有挂载点,没有正文。
2719export default function DemoSpa() {
2720  const [count, setCount] = useState(0);
2721  return (
2722    <main className="welcome">
2723      <p className="eyebrow">DEMO / SPA</p>
2724      <h1>SPA 模式</h1>
2725      <p>本页任何组件都可以直接使用浏览器状态与事件。</p>
2726      <button type="button" onClick={() => setCount((value) => value + 1)}>
2727        点击了 {count} 次
2728      </button>
2729      <p>
2730        <Link href={home()}>← 返回首页</Link>
2731      </p>
2732    </main>
2733  );
2734}
2735"#
2736    .to_owned()
2737}
2738
2739fn demo_ssr_page_template(frontend: ProjectFrontend) -> String {
2740    let (imports, signature) = match frontend {
2741        ProjectFrontend::Tsx => (
2742            concat!(
2743                "import { Link } from \"@apizero/react\";\n",
2744                "import type { DemoSsrProps } from \"../../generated/contracts.js\";\n",
2745                "import { home } from \"../../generated/routes.js\";",
2746            ),
2747            "export default function DemoSsr({ renderedAt }: DemoSsrProps) {",
2748        ),
2749        ProjectFrontend::Jsx => (
2750            concat!(
2751                "import { Link } from \"@apizero/react\";\n",
2752                "import { home } from \"../../generated/routes.js\";",
2753            ),
2754            "export default function DemoSsr({ renderedAt }) {",
2755        ),
2756    };
2757    // SSR:完整 HTML 在服务端生成后再 hydrate。
2758    format!(
2759        r#"{imports}
2760
2761// SSR:服务端渲染完整 HTML——查看网页源代码能直接看到下面的数据。
2762{signature}
2763  return (
2764    <main className="welcome">
2765      <p className="eyebrow">DEMO / SSR</p>
2766      <h1>SSR 模式</h1>
2767      <p>本页由服务端渲染,Rust 注入的时间戳:{{renderedAt}}。</p>
2768      <p>刷新后时间戳变化;右键「查看网页源代码」可在 HTML 里找到它。</p>
2769      <p>
2770        <Link href={{home()}}>← 返回首页</Link>
2771      </p>
2772    </main>
2773  );
2774}}
2775"#
2776    )
2777}
2778
2779/// Islands 演示页:静态正文 + 一个 `client:load` 岛(TSX/JSX 同文)。
2780fn demo_islands_page_template() -> String {
2781    r#"import { Link } from "@apizero/react";
2782import Counter from "../../islands/counter";
2783import { home } from "../../generated/routes.js";
2784
2785// Islands:页面主体是静态 HTML,只有标记 client:load 的组件会加载浏览器代码。
2786export default function DemoIslands() {
2787  return (
2788    <main className="welcome">
2789      <p className="eyebrow">DEMO / ISLANDS</p>
2790      <h1>Islands 模式</h1>
2791      <p>下面的计数器是本页唯一被水合的交互岛,其余内容零 JS。</p>
2792      <Counter client:load />
2793      <p>
2794        <Link href={home()}>← 返回首页</Link>
2795      </p>
2796    </main>
2797  );
2798}
2799"#
2800    .to_owned()
2801}
2802
2803fn styles_template(tailwind: bool) -> String {
2804    let tailwind = if tailwind {
2805        "@import \"tailwindcss\";\n\n"
2806    } else {
2807        ""
2808    };
2809    format!(
2810        r"{tailwind}:root {{
2811  font-family: Inter, ui-sans-serif, system-ui, sans-serif;
2812  color: #172033;
2813  background: #f5f7fb;
2814}}
2815* {{ box-sizing: border-box; }}
2816body {{ margin: 0; min-width: 320px; min-height: 100vh; }}
2817.welcome {{ width: min(760px, calc(100% - 40px)); margin: 16vh auto 0; }}
2818.eyebrow {{ color: #315bd6; font-size: 12px; font-weight: 800; letter-spacing: 0.14em; }}
2819h1 {{ margin: 12px 0; font-size: clamp(42px, 8vw, 76px); line-height: 0.98; }}
2820.welcome > p:not(.eyebrow) {{ max-width: 640px; color: #5d6879; font-size: 18px; line-height: 1.7; }}
2821code {{ display: inline-block; margin-top: 18px; padding: 12px 14px; border: 1px solid #d7dce5; background: white; }}
2822a {{ color: #315bd6; }}
2823button {{ margin-top: 8px; padding: 10px 16px; border: 1px solid #d7dce5; background: white; font-size: 16px; cursor: pointer; }}
2824.demo-links {{ margin: 18px 0 0; padding-left: 20px; }}
2825.demo-links li {{ margin: 6px 0; color: #5d6879; }}
2826"
2827    )
2828}
2829
2830fn generated_contracts_template() -> String {
2831    r#"// Generated by Phoenix. Vite will refresh this file from Rust contracts.
2832export interface HomeProps {
2833  title: string;
2834  description: string;
2835}
2836export interface DemoSsrProps {
2837  renderedAt: string;
2838}
2839export interface PhoenixPageProps {
2840  home: HomeProps;
2841  "demo/ssr": DemoSsrProps;
2842}
2843export type PhoenixSharedProps = Record<string, never>;
2844export const contractHash = "scaffold" as const;
2845"#
2846    .to_owned()
2847}
2848
2849fn generated_routes_template() -> String {
2850    r#"// Generated by Phoenix. Vite will refresh this file from Rust routes.
2851export const routes = {
2852  home: "home",
2853  demo: { spa: "demo.spa", ssr: "demo.ssr", islands: "demo.islands" },
2854} as const;
2855export type PhoenixRouteName = "home" | "demo.spa" | "demo.ssr" | "demo.islands";
2856export const home = routes.home;
2857export const demo = routes.demo;
2858"#
2859    .to_owned()
2860}
2861
2862fn vite_template(renderer: bool, tailwind: bool) -> String {
2863    let tailwind_import = if tailwind {
2864        "import tailwindcss from \"@tailwindcss/vite\";\n"
2865    } else {
2866        ""
2867    };
2868    let tailwind_plugin = if tailwind { ", tailwindcss()" } else { "" };
2869    format!(
2870        "import {{ defineConfig }} from \"vite\";\nimport {{ phoenix }} from \"@apizero/vite\";\n{tailwind_import}\nexport default defineConfig({{\n  plugins: [phoenix({renderer}){tailwind_plugin}],\n}});\n",
2871        renderer = if renderer { "{ renderer: true }" } else { "" },
2872    )
2873}
2874
2875fn tsconfig_template() -> String {
2876    r#"{
2877  "compilerOptions": {
2878    "target": "ES2022",
2879    "lib": ["ES2022", "DOM", "DOM.Iterable"],
2880    "module": "ESNext",
2881    "moduleResolution": "Bundler",
2882    "jsx": "react-jsx",
2883    "strict": true,
2884    "noEmit": true,
2885    "preserveSymlinks": true,
2886    "skipLibCheck": true,
2887    "types": ["vite/client"]
2888  },
2889  "include": ["views/**/*.js", "views/**/*.jsx", "views/**/*.ts", "views/**/*.tsx", "vite.config.ts", "vite.ssr.config.ts"]
2890}
2891"#
2892    .to_owned()
2893}
2894
2895fn managed_modules(entries: &[&str]) -> String {
2896    let body = entries.join("\n");
2897    if body.is_empty() {
2898        format!("{MODULES_START}\n{MODULES_END}\n")
2899    } else {
2900        format!("{MODULES_START}\n{body}\n{MODULES_END}\n")
2901    }
2902}
2903
2904fn add_rust_item(
2905    editor: &mut ProjectEditor,
2906    base: &str,
2907    name: &QualifiedName,
2908    content: &str,
2909) -> Result<(), ScaffoldError> {
2910    let mut directory = PathBuf::from(base);
2911    let mut parent_module = directory.join("mod.rs");
2912    for namespace in &name.modules {
2913        let module = snake_case(namespace);
2914        editor.update_managed_lines(
2915            &parent_module,
2916            MODULES_START,
2917            MODULES_END,
2918            &[format!("pub mod {module};")],
2919        )?;
2920        directory.push(&module);
2921        parent_module = directory.join("mod.rs");
2922    }
2923    let module = snake_case(&name.class);
2924    editor.create(directory.join(format!("{module}.rs")), content.to_owned())?;
2925    editor.update_managed_lines(
2926        &parent_module,
2927        MODULES_START,
2928        MODULES_END,
2929        &[
2930            format!("pub mod {module};"),
2931            format!("pub use {module}::{};", name.class),
2932        ],
2933    )?;
2934    Ok(())
2935}
2936
2937fn add_command(editor: &mut ProjectEditor, name: &QualifiedName) -> Result<(), ScaffoldError> {
2938    let function_name = snake_case(&name.class);
2939    if matches!(function_name.as_str(), "serve" | "help") {
2940        return Err(ScaffoldError::InvalidName(function_name));
2941    }
2942
2943    let mut directory = PathBuf::from("app/commands");
2944    let mut parent_module = directory.join("mod.rs");
2945    let mut export_path = Vec::new();
2946    for namespace in &name.modules {
2947        let module = snake_case(namespace);
2948        editor.update_managed_lines(
2949            &parent_module,
2950            MODULES_START,
2951            MODULES_END,
2952            &[format!("pub mod {module};")],
2953        )?;
2954        directory.push(&module);
2955        parent_module = directory.join("mod.rs");
2956        export_path.push(module);
2957    }
2958
2959    editor.create(
2960        directory.join(format!("{function_name}.rs")),
2961        command_template(&function_name),
2962    )?;
2963    editor.update_managed_lines(
2964        &parent_module,
2965        MODULES_START,
2966        MODULES_END,
2967        &[
2968            format!("pub mod {function_name};"),
2969            format!("pub use {function_name}::{function_name};"),
2970        ],
2971    )?;
2972
2973    if !export_path.is_empty() {
2974        let path = format!("{}::{function_name}", export_path.join("::"));
2975        editor.update_managed_lines(
2976            "app/commands/mod.rs",
2977            MODULES_START,
2978            MODULES_END,
2979            &[format!("pub use {path};")],
2980        )?;
2981    }
2982
2983    editor.update_managed_lines(
2984        "app/commands/mod.rs",
2985        COMMANDS_START,
2986        COMMANDS_END,
2987        &[format!("{function_name},")],
2988    )?;
2989    Ok(())
2990}
2991
2992/// A factory for `model`, wired to whichever parent it belongs to.
2993///
2994/// Development and test only: the file is compiled behind the `factory`
2995/// feature, so it never reaches a release build.
2996fn factory_template(model: &QualifiedName, relations: &[Relation]) -> String {
2997    let class = &model.class;
2998    let parent = relations
2999        .iter()
3000        .find(|relation| relation.kind == RelationKind::BelongsTo);
3001
3002    let (signature, extra) = parent.map_or_else(
3003        || (String::from("|f|"), String::new()),
3004        |relation| {
3005            let leaf = relation
3006                .target
3007                .rsplit("::")
3008                .next()
3009                .unwrap_or(&relation.target);
3010            let key = format!("{}_id", snake_case(leaf));
3011            (
3012                format!("|f, {key}: i64|"),
3013                format!("\n        .{key}({key})"),
3014            )
3015        },
3016    );
3017    let usage = parent.map_or_else(
3018        || format!("seeder.create::<{class}>(10).await?"),
3019        |relation| {
3020            let leaf = relation
3021                .target
3022                .rsplit("::")
3023                .next()
3024                .unwrap_or(&relation.target);
3025            format!(
3026                "seeder.create_with::<{class}, _>(5, {}.id).await?",
3027                snake_case(leaf)
3028            )
3029        },
3030    );
3031
3032    format!(
3033        r#"//! Generated rows for `{class}`. **Development and test only** — the
3034//! whole file disappears without the `factory` feature.
3035//!
3036//! Seed with: `{usage}`
3037#![cfg(feature = "factory")]
3038
3039use crate::models::{class};
3040
3041phoenix::factory! {{
3042    {class}, {signature} {class}::create()
3043        .name(f.name()){extra},
3044}}
3045"#
3046    )
3047}
3048
3049/// Write a factory and register its module.
3050///
3051/// Not `add_rust_item`: that also re-exports a type named after the file, and a
3052/// factory file declares no type — it only implements a trait for the model.
3053fn add_factory(
3054    editor: &mut ProjectEditor,
3055    model: &QualifiedName,
3056    relations: &[Relation],
3057) -> Result<(), ScaffoldError> {
3058    let module = format!("{}_factory", snake_case(&model.class));
3059    editor.create(
3060        PathBuf::from("database/seeders").join(format!("{module}.rs")),
3061        factory_template(model, relations),
3062    )?;
3063    editor.update_managed_lines(
3064        Path::new("database/seeders/mod.rs"),
3065        MODULES_START,
3066        MODULES_END,
3067        &[format!("pub mod {module};")],
3068    )
3069}
3070
3071fn add_model(
3072    editor: &mut ProjectEditor,
3073    model: &QualifiedName,
3074    relations: &[Relation],
3075) -> Result<(), ScaffoldError> {
3076    add_rust_item(
3077        editor,
3078        "app/models",
3079        model,
3080        &model_template(&model.class, relations),
3081    )?;
3082    let path = if model.modules.is_empty() {
3083        model.class.clone()
3084    } else {
3085        format!(
3086            "{}::{}",
3087            model
3088                .modules
3089                .iter()
3090                .map(|part| snake_case(part))
3091                .collect::<Vec<_>>()
3092                .join("::"),
3093            model.class
3094        )
3095    };
3096    editor.update_registry(
3097        "app/models/mod.rs",
3098        MODELS_START,
3099        MODELS_END,
3100        "model",
3101        &path,
3102        render_model_registry,
3103    )
3104}
3105
3106fn add_model_migration(
3107    editor: &mut ProjectEditor,
3108    model: &QualifiedName,
3109) -> Result<(), ScaffoldError> {
3110    let table = pluralize(&snake_case(&model.class));
3111    add_migration(editor, &format!("create_{table}_table"), &table)
3112}
3113
3114/// Register the `users` table migration generated by `px make:auth`.
3115///
3116/// Idempotent: a `--force` rebuild reuses the existing migration rather than
3117/// stacking a second, duplicate `create_users_table` file.
3118fn add_auth_user_migration(editor: &mut ProjectEditor) -> Result<(), ScaffoldError> {
3119    if editor
3120        .read(Path::new("database/migrations/mod.rs"))?
3121        .contains("create_users_table")
3122    {
3123        return Ok(());
3124    }
3125    let milliseconds = SystemTime::now()
3126        .duration_since(UNIX_EPOCH)
3127        .map_err(|_| ScaffoldError::InvalidClock)?
3128        .as_millis();
3129    let id = milliseconds.to_string();
3130    let module = format!("m_{id}_create_users_table");
3131    editor.create(
3132        format!("database/migrations/{module}.rs"),
3133        auth_user_migration_template(&id),
3134    )?;
3135    editor.update_registry(
3136        "database/migrations/mod.rs",
3137        MIGRATIONS_START,
3138        MIGRATIONS_END,
3139        "migration",
3140        &module,
3141        render_migration_registry,
3142    )
3143}
3144
3145/// Ensure every named feature is present in the project's `[features] default`
3146/// array so a bare `cargo check` compiles the generated slice.
3147fn enable_project_features(
3148    editor: &mut ProjectEditor,
3149    features: &[&str],
3150) -> Result<(), ScaffoldError> {
3151    let relative = PathBuf::from("Cargo.toml");
3152    let manifest = editor.read(&relative)?;
3153    if manifest.is_empty() {
3154        return Err(ScaffoldError::InvalidManagedFile(
3155            editor.root.join(&relative),
3156        ));
3157    }
3158    editor.set(relative, ensure_default_features(&manifest, features))
3159}
3160
3161/// Add `features` to the `default = [...]` array in a Cargo manifest, keeping
3162/// existing entries and order, and leaving the rest of the file untouched.
3163fn ensure_default_features(manifest: &str, features: &[&str]) -> String {
3164    let mut updated = manifest
3165        .lines()
3166        .map(|line| {
3167            let trimmed = line.trim_start();
3168            let is_default = trimmed
3169                .strip_prefix("default")
3170                .is_some_and(|rest| rest.trim_start().starts_with('='));
3171            if is_default
3172                && let Some(open) = line.find('[')
3173                && let Some(close_offset) = line[open..].find(']')
3174            {
3175                let close = open + close_offset;
3176                let mut entries = line[open + 1..close]
3177                    .split(',')
3178                    .map(|entry| entry.trim().trim_matches('"').to_owned())
3179                    .filter(|entry| !entry.is_empty())
3180                    .collect::<Vec<_>>();
3181                for feature in features {
3182                    if !entries.iter().any(|entry| entry == feature) {
3183                        entries.push((*feature).to_owned());
3184                    }
3185                }
3186                let indent = &line[..line.len() - trimmed.len()];
3187                let rendered = entries
3188                    .iter()
3189                    .map(|entry| format!("\"{entry}\""))
3190                    .collect::<Vec<_>>()
3191                    .join(", ");
3192                return format!("{indent}default = [{rendered}]");
3193            }
3194            line.to_owned()
3195        })
3196        .collect::<Vec<_>>()
3197        .join("\n");
3198    if manifest.ends_with('\n') {
3199        updated.push('\n');
3200    }
3201    updated
3202}
3203
3204fn add_migration(editor: &mut ProjectEditor, name: &str, table: &str) -> Result<(), ScaffoldError> {
3205    let milliseconds = SystemTime::now()
3206        .duration_since(UNIX_EPOCH)
3207        .map_err(|_| ScaffoldError::InvalidClock)?
3208        .as_millis();
3209    let id = milliseconds.to_string();
3210    let module = format!("m_{id}_{name}");
3211    editor.create(
3212        format!("database/migrations/{module}.rs"),
3213        migration_template(&id, name, table),
3214    )?;
3215    editor.update_registry(
3216        "database/migrations/mod.rs",
3217        MIGRATIONS_START,
3218        MIGRATIONS_END,
3219        "migration",
3220        &module,
3221        render_migration_registry,
3222    )
3223}
3224
3225fn add_controller_route(
3226    editor: &mut ProjectEditor,
3227    controller: &QualifiedName,
3228    resource: bool,
3229    action: Option<(&QualifiedName, &QualifiedName)>,
3230) -> Result<(), ScaffoldError> {
3231    let base = controller
3232        .class
3233        .strip_suffix("Controller")
3234        .unwrap_or(&controller.class);
3235    let plural = pluralize(&snake_case(base));
3236    let namespace_modules = controller
3237        .modules
3238        .iter()
3239        .map(|part| snake_case(part))
3240        .collect::<Vec<_>>();
3241    let route_file = if namespace_modules.is_empty() {
3242        plural.clone()
3243    } else {
3244        format!("{}_{}", namespace_modules.join("_"), plural)
3245    };
3246    let import = if namespace_modules.is_empty() {
3247        format!("crate::controllers::{}", controller.class)
3248    } else {
3249        format!(
3250            "crate::controllers::{}::{}",
3251            namespace_modules.join("::"),
3252            controller.class
3253        )
3254    };
3255    let route_name = if namespace_modules.is_empty() {
3256        plural.clone()
3257    } else {
3258        format!("{}.{}", namespace_modules.join("."), plural)
3259    };
3260    let path = if namespace_modules.is_empty() {
3261        format!("/{}", plural.replace('_', "-"))
3262    } else {
3263        format!(
3264            "/{}/{}",
3265            namespace_modules
3266                .iter()
3267                .map(|part| kebab_case(part))
3268                .collect::<Vec<_>>()
3269                .join("/"),
3270            plural.replace('_', "-")
3271        )
3272    };
3273    editor.create(
3274        format!("routes/{route_file}.rs"),
3275        controller_route_template(
3276            &import,
3277            &route_name,
3278            &path,
3279            &controller.class,
3280            resource,
3281            action,
3282        ),
3283    )
3284}
3285
3286fn add_page(
3287    editor: &mut ProjectEditor,
3288    page: &PageName,
3289    frontend: ProjectFrontend,
3290) -> Result<(), ScaffoldError> {
3291    let props = page_props_name(page);
3292    add_rust_item(
3293        editor,
3294        "app/props",
3295        &props,
3296        &page_props_template(&props.class, &page.route),
3297    )?;
3298    let mut path = PathBuf::from("views/pages");
3299    for part in &page.parts[..page.parts.len() - 1] {
3300        path.push(kebab_case(part));
3301    }
3302    path.push(format!(
3303        "{}.{}",
3304        kebab_case(page.parts.last().expect("page has one part")),
3305        frontend.extension()
3306    ));
3307    editor.create(
3308        path,
3309        page_template(&page.class, &props.class, page.parts.len(), frontend),
3310    )
3311}
3312
3313fn page_props_name(page: &PageName) -> QualifiedName {
3314    QualifiedName {
3315        modules: page.parts[..page.parts.len() - 1].to_vec(),
3316        class: format!("{}Props", page.class),
3317    }
3318}
3319
3320/// Register the Rust page-props contract and write one auth page component.
3321fn add_auth_page(
3322    editor: &mut ProjectEditor,
3323    name: &str,
3324    content: String,
3325    frontend: ProjectFrontend,
3326) -> Result<(), ScaffoldError> {
3327    let page = PageName::parse(name)?;
3328    let props = page_props_name(&page);
3329    add_rust_item(
3330        editor,
3331        "app/props",
3332        &props,
3333        &page_props_template(&props.class, &page.route),
3334    )?;
3335    let mut path = PathBuf::from("views/pages");
3336    for part in &page.parts[..page.parts.len() - 1] {
3337        path.push(kebab_case(part));
3338    }
3339    path.push(format!(
3340        "{}.{}",
3341        kebab_case(page.parts.last().expect("page has one part")),
3342        frontend.extension()
3343    ));
3344    editor.create(path, content)
3345}
3346
3347/// A model written the short way: conventions filled in by `#[phoenix::model]`,
3348/// relations expressed as one line each.
3349fn model_template(name: &str, relations: &[Relation]) -> String {
3350    use std::fmt::Write as _;
3351
3352    let mut imports = String::from("use phoenix::model;\n");
3353    if !relations.is_empty() {
3354        imports.push_str("use phoenix::database::Deferred;\n\n");
3355        // Related models are reachable through the registry's re-exports, so a
3356        // relation never needs the target's module path spelled out.
3357        let mut targets: Vec<&str> = relations
3358            .iter()
3359            .map(|relation| {
3360                let target = relation.target.as_str();
3361                target.rsplit("::").next().unwrap_or(target)
3362            })
3363            .collect();
3364        targets.sort_unstable();
3365        targets.dedup();
3366        let _ = writeln!(imports, "use crate::models::{{{}}};", targets.join(", "));
3367    }
3368
3369    let mut fields = String::from("    pub name: String,\n");
3370    for relation in relations {
3371        let attribute = relation.kind.attribute();
3372        let target = &relation.target;
3373        let leaf = target.rsplit("::").next().unwrap_or(target);
3374        let field = snake_case(leaf);
3375        let (field, ty) = match relation.kind {
3376            // `#[belongs_to] user: Deferred<User>` — the foreign key and the
3377            // column it maps to are conventions, so neither is written here.
3378            RelationKind::BelongsTo | RelationKind::HasOne => {
3379                (field, format!("Deferred<{target}>"))
3380            }
3381            RelationKind::HasMany => (pluralize(&field), format!("Deferred<Vec<{target}>>")),
3382        };
3383        let _ = write!(fields, "    #[{attribute}]\n    pub {field}: {ty},\n");
3384    }
3385
3386    format!(
3387        "{imports}
3388/// `#[phoenix::model]` fills in the table name, an auto-increment `id`, the
3389/// derives, and every relation's foreign key. Write any of them yourself to
3390/// take that part back.
3391#[model]
3392pub struct {name} {{
3393{fields}}}
3394"
3395    )
3396}
3397
3398/// The persistent `User` model backing `px make:auth`.
3399fn auth_user_model_template() -> String {
3400    r"use phoenix::database::Model;
3401
3402/// Registered account. Passwords are stored only as Argon2id PHC hashes
3403/// (`password_hash`); the plaintext never touches the database.
3404#[derive(Clone, Debug, Model)]
3405pub struct User {
3406    #[key]
3407    #[auto]
3408    pub id: u64,
3409    #[unique]
3410    pub email: String,
3411    pub name: String,
3412    pub password_hash: String,
3413    pub created_at: String,
3414}
3415"
3416    .to_owned()
3417}
3418
3419/// The `users` table migration (portable across sqlite / pgsql / mysql).
3420fn auth_user_migration_template(id: &str) -> String {
3421    format!(
3422        r#"use phoenix::database::Migration;
3423
3424#[must_use]
3425pub fn migration() -> Migration {{
3426    Migration::new("{id}", "create users table")
3427        .up(
3428            "CREATE TABLE users (\
3429             id BIGINT PRIMARY KEY, \
3430             email VARCHAR(255) NOT NULL UNIQUE, \
3431             name VARCHAR(255) NOT NULL, \
3432             password_hash VARCHAR(255) NOT NULL, \
3433             created_at VARCHAR(64) NOT NULL)",
3434        )
3435        .down("DROP TABLE users")
3436}}
3437"#
3438    )
3439}
3440
3441fn request_template(name: &str) -> String {
3442    format!(
3443        r#"use phoenix::prelude::{{Validate, ValidationErrors, Validator, max_length, required, rules, string}};
3444use serde::Deserialize;
3445
3446#[phoenix::contract(input)]
3447#[derive(Debug, Deserialize)]
3448pub struct {name} {{
3449    pub name: String,
3450}}
3451
3452impl Validate for {name} {{
3453    fn validate(&self) -> Result<(), ValidationErrors> {{
3454        let data = serde_json::json!({{ "name": self.name }});
3455        Validator::new(&data)
3456            .field("name", rules![required(), string(), max_length(255)])
3457            .validate()
3458    }}
3459}}
3460"#
3461    )
3462}
3463
3464fn resource_template(name: &str) -> String {
3465    format!(
3466        r#"use serde::Serialize;
3467
3468#[phoenix::contract(resource)]
3469#[derive(Clone, Debug, Serialize)]
3470#[serde(rename_all = "camelCase")]
3471pub struct {name} {{
3472    pub id: String,
3473    pub name: String,
3474}}
3475"#
3476    )
3477}
3478
3479fn controller_template(name: &str, resource: bool) -> String {
3480    if !resource {
3481        return format!(
3482            r#"use phoenix::prelude::{{Request, Response}};
3483
3484pub struct {name};
3485
3486impl {name} {{
3487    #[allow(clippy::unused_async)]
3488    pub async fn index(_request: Request) -> Response {{
3489        Response::text("{name}@index")
3490    }}
3491}}
3492"#
3493        );
3494    }
3495    format!(
3496        r#"use phoenix::prelude::{{Request, Response, StatusCode}};
3497
3498pub struct {name};
3499
3500impl {name} {{
3501    #[allow(clippy::unused_async)]
3502    pub async fn index(_request: Request) -> Response {{ Response::text("{name}@index") }}
3503
3504    #[allow(clippy::unused_async)]
3505    pub async fn create(_request: Request) -> Response {{ Response::text("{name}@create") }}
3506
3507    #[allow(clippy::unused_async)]
3508    pub async fn store(_request: Request) -> Response {{
3509        Response::text("{name}@store").with_status(StatusCode::CREATED)
3510    }}
3511
3512    #[allow(clippy::unused_async)]
3513    pub async fn show(_request: Request) -> Response {{ Response::text("{name}@show") }}
3514
3515    #[allow(clippy::unused_async)]
3516    pub async fn edit(_request: Request) -> Response {{ Response::text("{name}@edit") }}
3517
3518    #[allow(clippy::unused_async)]
3519    pub async fn update(_request: Request) -> Response {{ Response::text("{name}@update") }}
3520
3521    #[allow(clippy::unused_async)]
3522    pub async fn destroy(_request: Request) -> Response {{
3523        Response::new(StatusCode::NO_CONTENT, phoenix::http::Bytes::new())
3524    }}
3525}}
3526"#
3527    )
3528}
3529
3530fn model_controller_template(
3531    controller: &QualifiedName,
3532    request: &QualifiedName,
3533    resource: &QualifiedName,
3534    props: &QualifiedName,
3535    page: &str,
3536) -> String {
3537    let request_path = rust_item_path("requests", request);
3538    let resource_path = rust_item_path("resources", resource);
3539    let props_path = rust_item_path("props", props);
3540    let name = &controller.class;
3541    let title = page
3542        .split('/')
3543        .next()
3544        .map_or_else(|| "Items".to_owned(), pascal_case);
3545    format!(
3546        r#"use phoenix::prelude::{{Json, Page, PageResponseError, Request, Response, StatusCode, Validated}};
3547
3548use {props_path};
3549use {request_path};
3550use {resource_path};
3551
3552pub struct {name};
3553
3554impl {name} {{
3555    pub async fn index(request: Request) -> Result<Response, PageResponseError> {{
3556        Page::new("{page}", {props_class} {{ title: "{title}".to_owned() }})
3557            .spa()
3558            .respond_to(&request, None)
3559    }}
3560
3561    #[allow(clippy::unused_async)]
3562    pub async fn create(_request: Request) -> Response {{ Response::text("{name}@create") }}
3563
3564    #[allow(clippy::unused_async)]
3565    pub async fn store(
3566        Validated(Json(input)): Validated<Json<{request_class}>>,
3567    ) -> (StatusCode, Json<{resource_class}>) {{
3568        (
3569            StatusCode::CREATED,
3570            Json({resource_class} {{ id: "generated".to_owned(), name: input.name }}),
3571        )
3572    }}
3573
3574    #[allow(clippy::unused_async)]
3575    pub async fn show(_request: Request) -> Response {{ Response::text("{name}@show") }}
3576
3577    #[allow(clippy::unused_async)]
3578    pub async fn edit(_request: Request) -> Response {{ Response::text("{name}@edit") }}
3579
3580    #[allow(clippy::unused_async)]
3581    pub async fn update(_request: Request) -> Response {{ Response::text("{name}@update") }}
3582
3583    #[allow(clippy::unused_async)]
3584    pub async fn destroy(_request: Request) -> Response {{
3585        Response::new(StatusCode::NO_CONTENT, phoenix::http::Bytes::new())
3586    }}
3587}}
3588"#,
3589        props_class = props.class,
3590        request_class = request.class,
3591        resource_class = resource.class,
3592    )
3593}
3594
3595fn middleware_template(name: &str) -> String {
3596    format!(
3597        r"use phoenix::prelude::{{BoxFuture, Middleware, Next, Request, Response}};
3598
3599pub struct {name};
3600
3601impl Middleware for {name} {{
3602    fn handle(&self, request: Request, next: Next) -> BoxFuture<Response> {{
3603        Box::pin(async move {{
3604            // Add authorization, request context, or response policy here.
3605            next.run(request).await
3606        }})
3607    }}
3608}}
3609"
3610    )
3611}
3612
3613fn migration_template(id: &str, name: &str, table: &str) -> String {
3614    format!(
3615        r#"use phoenix::database::Migration;
3616
3617#[must_use]
3618pub fn migration() -> Migration {{
3619    Migration::new("{id}", "{description}")
3620        .up("CREATE TABLE {table} (id BIGINT PRIMARY KEY, name TEXT NOT NULL)")
3621        .down("DROP TABLE {table}")
3622}}
3623"#,
3624        description = name.replace('_', " "),
3625    )
3626}
3627
3628fn controller_route_template(
3629    import: &str,
3630    route_name: &str,
3631    path: &str,
3632    controller: &str,
3633    resource: bool,
3634    action: Option<(&QualifiedName, &QualifiedName)>,
3635) -> String {
3636    if !resource {
3637        return format!(
3638            "use phoenix::prelude::Routes;\n\nuse {import};\n\n#[must_use]\npub fn routes() -> Routes {{\n    Routes::new()\n        .get(\"{path}\", {controller}::index)\n        .name(\"{route_name}.index\")\n}}\n"
3639        );
3640    }
3641    let parameter = snake_case(controller.strip_suffix("Controller").unwrap_or(controller));
3642    let (prelude, action_imports, store, action_binding) = action.map_or_else(
3643        || {
3644            (
3645                "Routes".to_owned(),
3646                String::new(),
3647                format!("{controller}::store"),
3648                String::new(),
3649            )
3650        },
3651        |(input, output)| {
3652            (
3653                "Routes, typed".to_owned(),
3654                format!(
3655                    "use {};\nuse {};\n",
3656                    rust_item_path("requests", input),
3657                    rust_item_path("resources", output),
3658                ),
3659                format!("typed({controller}::store)"),
3660                format!("\n        .action::<{}, {}>()", input.class, output.class),
3661            )
3662        },
3663    );
3664    format!(
3665        r#"use phoenix::prelude::{{{prelude}}};
3666
3667use {import};
3668{action_imports}
3669
3670#[must_use]
3671pub fn routes() -> Routes {{
3672    let member = "{path}/{{{parameter}}}";
3673    Routes::new()
3674        .get("{path}", {controller}::index)
3675        .name("{route_name}.index")
3676        .get("{path}/create", {controller}::create)
3677        .name("{route_name}.create")
3678        .post("{path}", {store})
3679        .name("{route_name}.store"){action_binding}
3680        .get(member, {controller}::show)
3681        .name("{route_name}.show")
3682        .get(format!("{{member}}/edit"), {controller}::edit)
3683        .name("{route_name}.edit")
3684        .put(member, {controller}::update)
3685        .name("{route_name}.update")
3686        .patch(member, {controller}::update)
3687        .delete(member, {controller}::destroy)
3688        .name("{route_name}.destroy")
3689}}
3690"#
3691    )
3692}
3693
3694fn auth_routes_template() -> String {
3695    r#"//! 认证路由:由 `px make:auth` 生成,`mount_routes!()` 自动收集本文件。
3696//!
3697//! 图形验证码(可选,默认以注释交付):`CaptchaFeature` 位于独立 crate
3698//! `phoenix-captcha`,未随 `phoenix` 门面导出,因此**不是零配置能力**,
3699//! 脚手架不默认开启。启用步骤(详见 docs/CAPTCHA.md):
3700//! 1. 应用 `Cargo.toml` 添加依赖 `phoenix-captcha`;
3701//! 2. `FeatureSet::new().plugin(CaptchaFeature::new())?` 注册 `GET /captcha`
3702//!    (命名路由 `captcha.image`),并把 Feature 路由合并进应用路由;
3703//! 3. `LoginInput` 增加 `captcha` 字段并实现 `CaptchaInput`,登录 handler
3704//!    换用 `CaptchaProtected` 提取器;
3705//! 4. 解开 `views/pages/auth/login` 页面里的 `CaptchaImage` 注释块。
3706
3707use std::time::Duration;
3708
3709use phoenix::prelude::{RateLimit, RateLimitConfig, RouteGroup, Routes, typed};
3710
3711use crate::controllers::AuthController;
3712use crate::requests::{LoginInput, PasswordResetInput, RegisterInput};
3713use crate::resources::{AuthMessageResource, AuthSessionResource};
3714
3715#[must_use]
3716pub fn routes() -> Routes {
3717    // 认证提交接口在全局限流之上叠加更严格的默认(每客户端 IP 每秒 2 次),
3718    // 抑制凭据爆破与重置邮件轰炸;次数与窗口按业务调整。
3719    let auth_rate_limit = RateLimit::new(RateLimitConfig {
3720        requests: 2,
3721        window: Duration::from_secs(1),
3722    });
3723
3724    Routes::new()
3725        .get("/login", AuthController::show_login)
3726        .name("login.show")
3727        .get("/register", AuthController::show_register)
3728        .name("register.show")
3729        .get("/forgot-password", AuthController::show_forgot_password)
3730        .name("password-reset.show")
3731        .group(RouteGroup::new().middleware(auth_rate_limit), |routes| {
3732            routes
3733                .post("/login", AuthController::login)
3734                .name("login.store")
3735                .action::<LoginInput, AuthSessionResource>()
3736                .post("/logout", AuthController::logout)
3737                .name("logout.store")
3738                .post("/register", AuthController::register)
3739                .name("register.store")
3740                .action::<RegisterInput, AuthSessionResource>()
3741                .post(
3742                    "/password-reset",
3743                    typed(AuthController::request_password_reset),
3744                )
3745                .name("password-reset.store")
3746                .action::<PasswordResetInput, AuthMessageResource>()
3747        })
3748}
3749"#
3750    .to_owned()
3751}
3752
3753// The body is one template literal; the line count is the generated file, not logic.
3754#[allow(clippy::too_many_lines)]
3755fn auth_controller_template() -> String {
3756    r#"use phoenix::auth::{AuthError, AuthGuard, AuthUser, UserProvider};
3757use phoenix::database::create;
3758use phoenix::prelude::{
3759    AssetManifest, BoxFuture, Database, FromRequest, IntoResponse, Json, Page, PageResponseError,
3760    Password, Request, Response, Session, StatusCode, Validated,
3761};
3762use serde_json::json;
3763
3764use crate::config::AppConfig;
3765use crate::models::User;
3766use crate::props::auth::{AuthForgotPasswordProps, AuthLoginProps, AuthRegisterProps};
3767use crate::requests::{LoginInput, PasswordResetInput, RegisterInput};
3768use crate::resources::{AuthMessageResource, AuthSessionResource};
3769
3770/// `UserProvider` backed by the persistent `users` table.
3771///
3772/// Holds a cloned `Database` handle (a shared connection pool), so each lookup
3773/// runs on its own executor without borrowing the request.
3774struct DatabaseUserProvider {
3775    database: Database,
3776}
3777
3778impl DatabaseUserProvider {
3779    fn new(database: Database) -> Self {
3780        Self { database }
3781    }
3782}
3783
3784impl UserProvider for DatabaseUserProvider {
3785    fn find_by_identifier(
3786        &self,
3787        identifier: &str,
3788    ) -> BoxFuture<Result<Option<AuthUser>, AuthError>> {
3789        let mut executor = self.database.toasty().clone();
3790        let email = identifier.trim().to_ascii_lowercase();
3791        Box::pin(async move {
3792            match User::filter_by_email(email).get(&mut executor).await {
3793                Ok(user) => Ok(Some(auth_user(&user))),
3794                Err(error) if error.is_record_not_found() => Ok(None),
3795                Err(error) => Err(AuthError::provider(error.to_string())),
3796            }
3797        })
3798    }
3799
3800    fn find_by_id(&self, id: &str) -> BoxFuture<Result<Option<AuthUser>, AuthError>> {
3801        let mut executor = self.database.toasty().clone();
3802        let parsed = id.parse::<u64>();
3803        Box::pin(async move {
3804            let Ok(id) = parsed else { return Ok(None) };
3805            match User::filter_by_id(id).get(&mut executor).await {
3806                Ok(user) => Ok(Some(auth_user(&user))),
3807                Err(error) if error.is_record_not_found() => Ok(None),
3808                Err(error) => Err(AuthError::provider(error.to_string())),
3809            }
3810        })
3811    }
3812}
3813
3814/// Map a persisted row onto the framework's minimal `AuthUser` (password hash
3815/// included so the guard can verify it with Argon2id).
3816fn auth_user(user: &User) -> AuthUser {
3817    AuthUser::new(
3818        user.id.to_string(),
3819        user.email.clone(),
3820        user.password_hash.clone(),
3821    )
3822    .with_name(user.name.clone())
3823    .with_role("member")
3824}
3825
3826pub struct AuthController;
3827
3828impl AuthController {
3829    #[allow(clippy::unused_async)]
3830    pub async fn show_login(request: Request) -> Response {
3831        render_auth_page(
3832            &request,
3833            Page::new(
3834                "auth/login",
3835                AuthLoginProps {
3836                    title: "登录".to_owned(),
3837                },
3838            ),
3839        )
3840    }
3841
3842    #[allow(clippy::unused_async)]
3843    pub async fn show_register(request: Request) -> Response {
3844        render_auth_page(
3845            &request,
3846            Page::new(
3847                "auth/register",
3848                AuthRegisterProps {
3849                    title: "注册".to_owned(),
3850                },
3851            ),
3852        )
3853    }
3854
3855    #[allow(clippy::unused_async)]
3856    pub async fn show_forgot_password(request: Request) -> Response {
3857        render_auth_page(
3858            &request,
3859            Page::new(
3860                "auth/forgot-password",
3861                AuthForgotPasswordProps {
3862                    title: "找回密码".to_owned(),
3863                },
3864            ),
3865        )
3866    }
3867
3868    /// 邮箱 + 密码登录,成功后开启会话。
3869    ///
3870    /// 校验交给 `phoenix::auth::AuthGuard`:内部用 Argon2id 比对 `password_hash`,
3871    /// 成功后轮换会话 id(OWASP 会话固定防护)并写入 subject。
3872    /// 可选图形验证码:启用 `phoenix-captcha` 后改用
3873    /// `CaptchaProtected<Validated<Json<LoginInput>>>` 提取器(docs/CAPTCHA.md)。
3874    pub async fn login(request: Request) -> Response {
3875        let Validated(Json(input)) = match Validated::<Json<LoginInput>>::from_request(&request) {
3876            Ok(input) => input,
3877            Err(rejection) => return rejection.into_response(),
3878        };
3879        let Some(session) = request.extensions().get::<Session>().cloned() else {
3880            return session_unavailable();
3881        };
3882        let Some(database) = request.extensions().get::<Database>().cloned() else {
3883            return database_unavailable();
3884        };
3885        let provider = DatabaseUserProvider::new(database);
3886        let guard = AuthGuard::new(&provider, &session);
3887        match guard.attempt(&input.email, &input.password).await {
3888            Ok(Some(user)) => Json(AuthSessionResource {
3889                subject: user.identifier().to_owned(),
3890                name: user.name().to_owned(),
3891                role: "member".to_owned(),
3892            })
3893            .into_response(),
3894            Ok(None) => (
3895                StatusCode::UNAUTHORIZED,
3896                Json(AuthMessageResource {
3897                    message: "邮箱或密码不正确。".to_owned(),
3898                }),
3899            )
3900                .into_response(),
3901            Err(error) => provider_error(&error),
3902        }
3903    }
3904
3905    /// 注册新用户:唯一邮箱查重、Argon2id 哈希入库,随后自动登录。
3906    pub async fn register(request: Request) -> Response {
3907        let Validated(Json(input)) = match Validated::<Json<RegisterInput>>::from_request(&request)
3908        {
3909            Ok(input) => input,
3910            Err(rejection) => return rejection.into_response(),
3911        };
3912        let Some(session) = request.extensions().get::<Session>().cloned() else {
3913            return session_unavailable();
3914        };
3915        let Some(mut database) = request.extensions().get::<Database>().cloned() else {
3916            return database_unavailable();
3917        };
3918        let email = input.email.trim().to_ascii_lowercase();
3919        let provider = DatabaseUserProvider::new(database.clone());
3920        match provider.find_by_identifier(&email).await {
3921            Ok(Some(_)) => return email_taken(),
3922            Ok(None) => {}
3923            Err(error) => return provider_error(&error),
3924        }
3925        let password_hash = match Password::hash(&input.password) {
3926            Ok(hash) => hash,
3927            Err(error) => {
3928                return Response::text(format!("password hashing failed: {error}"))
3929                    .with_status(StatusCode::INTERNAL_SERVER_ERROR);
3930            }
3931        };
3932        let created_at = std::time::SystemTime::now()
3933            .duration_since(std::time::UNIX_EPOCH)
3934            .map(|value| value.as_secs().to_string())
3935            .unwrap_or_default();
3936        let created = create!(User {
3937            email: email.clone(),
3938            name: input.name.clone(),
3939            password_hash: password_hash,
3940            created_at: created_at,
3941        })
3942        .exec(database.toasty_mut())
3943        .await;
3944        match created {
3945            Ok(user) => {
3946                // AuthGuard::login rotates the session id and stores the subject.
3947                AuthGuard::new(&provider, &session).login(&auth_user(&user));
3948                (
3949                    StatusCode::CREATED,
3950                    Json(AuthSessionResource {
3951                        subject: user.email,
3952                        name: user.name,
3953                        role: "member".to_owned(),
3954                    }),
3955                )
3956                    .into_response()
3957            }
3958            Err(error) => Response::text(format!("failed to create user: {error}"))
3959                .with_status(StatusCode::INTERNAL_SERVER_ERROR),
3960        }
3961    }
3962
3963    /// 退出登录并销毁会话。
3964    #[allow(clippy::unused_async)]
3965    pub async fn logout(request: Request) -> Json<AuthMessageResource> {
3966        if let Some(session) = request.extensions().get::<Session>() {
3967            session.destroy();
3968        }
3969        Json(AuthMessageResource {
3970            message: "已退出登录。".to_owned(),
3971        })
3972    }
3973
3974    /// 密码重置请求:为防账号枚举,无论邮箱是否存在都返回同一响应。
3975    #[allow(clippy::unused_async)]
3976    pub async fn request_password_reset(
3977        Validated(Json(_input)): Validated<Json<PasswordResetInput>>,
3978    ) -> (StatusCode, Json<AuthMessageResource>) {
3979        // TODO: 生成重置 token 并通过 phoenix-mail 发送(脚手架不落地邮件)。
3980        (
3981            StatusCode::ACCEPTED,
3982            Json(AuthMessageResource {
3983                message: "如果该邮箱已注册,稍后会收到重置说明。".to_owned(),
3984            }),
3985        )
3986    }
3987}
3988
3989/// 邮箱已注册:返回 422 校验错误信封,字段错误对齐 `Validated` 的响应形状。
3990fn email_taken() -> Response {
3991    (
3992        StatusCode::UNPROCESSABLE_ENTITY,
3993        Json(json!({
3994            "message": "The submitted data is invalid.",
3995            "errors": {
3996                "email": [{ "rule": "unique", "message": "该邮箱已注册。" }]
3997            }
3998        })),
3999    )
4000        .into_response()
4001}
4002
4003fn session_unavailable() -> Response {
4004    Response::text("SessionMiddleware is not mounted")
4005        .with_status(StatusCode::INTERNAL_SERVER_ERROR)
4006}
4007
4008fn database_unavailable() -> Response {
4009    // application() connects the database and mounts it via StateMiddleware.
4010    Response::text("database is unavailable")
4011        .with_status(StatusCode::INTERNAL_SERVER_ERROR)
4012}
4013
4014fn provider_error(error: &AuthError) -> Response {
4015    Response::text(format!("auth store error: {error}"))
4016        .with_status(StatusCode::INTERNAL_SERVER_ERROR)
4017}
4018
4019/// 认证页以 SPA 协议渲染(表单需要可交互),并把 CSRF token 注入页面信封,
4020/// 生成的 typed action 会自动携带 `X-CSRF-Token`。
4021fn render_auth_page(request: &Request, page: Page) -> Response {
4022    let mut page = page.spa();
4023    if let Some(token) = request
4024        .extensions()
4025        .get::<Session>()
4026        .and_then(Session::csrf_token)
4027    {
4028        page = page.csrf_token(token);
4029    }
4030    let assets = request
4031        .extensions()
4032        .get::<Option<AssetManifest>>()
4033        .and_then(Option::as_ref);
4034    if let Some(assets) = assets {
4035        page = match page.production_assets(assets, "client") {
4036            Ok(page) => page,
4037            Err(error) => {
4038                return Response::text(format!("asset manifest error: {error}"))
4039                    .with_status(StatusCode::INTERNAL_SERVER_ERROR);
4040            }
4041        };
4042    }
4043    // Only `px dev` (PHOENIX_VITE_DEV) may override the browser entry with Vite.
4044    if std::env::var_os("PHOENIX_VITE_DEV").is_some()
4045        && let Some(vite_dev_url) = request
4046            .extensions()
4047            .get::<AppConfig>()
4048            .and_then(AppConfig::vite_dev_url)
4049    {
4050        page = page.script_src(format!(
4051            "{}/@id/__x00__virtual:phoenix/client",
4052            vite_dev_url.trim_end_matches('/'),
4053        ));
4054    }
4055    page.respond_to(request, None)
4056        .unwrap_or_else(PageResponseError::into_response)
4057}
4058"#
4059    .to_owned()
4060}
4061
4062fn login_input_template() -> String {
4063    r#"use phoenix::prelude::{
4064    Validate, ValidationErrors, Validator, max_length, min_length, required, rules, string,
4065};
4066use serde::Deserialize;
4067
4068/// 登录表单入参。
4069///
4070/// 启用图形验证码后:增加 `pub captcha: String` 字段并实现
4071/// `phoenix_captcha::CaptchaInput`(见 routes/auth.rs 顶部说明)。
4072#[phoenix::contract(input)]
4073#[derive(Debug, Deserialize)]
4074pub struct LoginInput {
4075    pub email: String,
4076    pub password: String,
4077}
4078
4079impl Validate for LoginInput {
4080    fn validate(&self) -> Result<(), ValidationErrors> {
4081        let data = serde_json::json!({ "email": self.email, "password": self.password });
4082        Validator::new(&data)
4083            .field(
4084                "email",
4085                rules![required(), string(), min_length(3), max_length(120)],
4086            )
4087            .field(
4088                "password",
4089                rules![required(), string(), min_length(8), max_length(1024)],
4090            )
4091            .validate()
4092    }
4093}
4094"#
4095    .to_owned()
4096}
4097
4098fn register_input_template() -> String {
4099    r#"use phoenix::prelude::{
4100    Validate, ValidationErrors, Validator, max_length, min_length, required, rules, string,
4101};
4102use serde::Deserialize;
4103
4104/// 注册表单入参。
4105#[phoenix::contract(input)]
4106#[derive(Debug, Deserialize)]
4107pub struct RegisterInput {
4108    pub name: String,
4109    pub email: String,
4110    pub password: String,
4111}
4112
4113impl Validate for RegisterInput {
4114    fn validate(&self) -> Result<(), ValidationErrors> {
4115        let data = serde_json::json!({
4116            "name": self.name,
4117            "email": self.email,
4118            "password": self.password,
4119        });
4120        Validator::new(&data)
4121            .field(
4122                "name",
4123                rules![required(), string(), min_length(1), max_length(40)],
4124            )
4125            .field(
4126                "email",
4127                rules![required(), string(), min_length(3), max_length(120)],
4128            )
4129            .field(
4130                "password",
4131                rules![required(), string(), min_length(8), max_length(1024)],
4132            )
4133            .validate()
4134    }
4135}
4136"#
4137    .to_owned()
4138}
4139
4140fn password_reset_input_template() -> String {
4141    r#"use phoenix::prelude::{
4142    Validate, ValidationErrors, Validator, max_length, min_length, required, rules, string,
4143};
4144use serde::Deserialize;
4145
4146/// 密码重置请求入参。
4147#[phoenix::contract(input)]
4148#[derive(Debug, Deserialize)]
4149pub struct PasswordResetInput {
4150    pub email: String,
4151}
4152
4153impl Validate for PasswordResetInput {
4154    fn validate(&self) -> Result<(), ValidationErrors> {
4155        let data = serde_json::json!({ "email": self.email });
4156        Validator::new(&data)
4157            .field(
4158                "email",
4159                rules![required(), string(), min_length(3), max_length(120)],
4160            )
4161            .validate()
4162    }
4163}
4164"#
4165    .to_owned()
4166}
4167
4168fn auth_session_resource_template() -> String {
4169    r#"use serde::Serialize;
4170
4171/// 登录 / 注册成功后返回给浏览器的会话信息。
4172#[phoenix::contract(resource)]
4173#[derive(Clone, Debug, Serialize)]
4174#[serde(rename_all = "camelCase")]
4175pub struct AuthSessionResource {
4176    pub subject: String,
4177    pub name: String,
4178    pub role: String,
4179}
4180"#
4181    .to_owned()
4182}
4183
4184fn auth_message_resource_template() -> String {
4185    r#"use serde::Serialize;
4186
4187/// 认证流程的通用提示消息。
4188#[phoenix::contract(resource)]
4189#[derive(Clone, Debug, Serialize)]
4190#[serde(rename_all = "camelCase")]
4191pub struct AuthMessageResource {
4192    pub message: String,
4193}
4194"#
4195    .to_owned()
4196}
4197
4198const AUTH_LOGIN_PAGE_BODY: &str = r#"  return (
4199    <main className="auth-page">
4200      <h1>{title}</h1>
4201      <Form
4202        action={login.store}
4203        initialValues={{ email: "", password: "" }}
4204        fields={LoginInputFields}
4205        onSuccess={() => redirect(home())}
4206      >
4207        {(form) => (
4208          <>
4209            <label htmlFor="login-email">邮箱</label>
4210            <input id="login-email" type="email" autoComplete="email" {...form.field("email")} />
4211            <FieldError errors={form.errors} name="email" />
4212
4213            <label htmlFor="login-password">密码</label>
4214            <input
4215              id="login-password"
4216              type="password"
4217              autoComplete="current-password"
4218              {...form.field("password")}
4219            />
4220            <FieldError errors={form.errors} name="password" />
4221
4222            {/* 启用图形验证码后解开(Rust 侧装配见 routes/auth.rs 顶部注释与 docs/CAPTCHA.md):
4223            <CaptchaImage />
4224            <input autoComplete="off" {...form.field("captcha")} />
4225            <FieldError errors={form.errors} name="captcha" />
4226            */}
4227
4228            <button type="submit" disabled={form.processing}>
4229              {form.processing ? "登录中…" : "登录"}
4230            </button>
4231          </>
4232        )}
4233      </Form>
4234      <p>
4235        还没有账号?<Link href={register.show()}>注册</Link>
4236        <span> · </span>
4237        <Link href={routes["password-reset"].show()}>忘记密码?</Link>
4238      </p>
4239    </main>
4240  );
4241}
4242"#;
4243
4244fn auth_login_page_template(frontend: ProjectFrontend) -> String {
4245    let (imports, signature) = match frontend {
4246        ProjectFrontend::Tsx => (
4247            concat!(
4248                "import { FieldError, Form, Link, redirect } from \"@apizero/react\";\n",
4249                "// 启用图形验证码后解开:\n",
4250                "// import { CaptchaImage } from \"@apizero/react\";\n",
4251                "import type { AuthLoginProps } from \"../../generated/contracts.js\";\n",
4252                "import { LoginInputFields } from \"../../generated/contracts.js\";\n",
4253                "import { home, login, register, routes } from \"../../generated/routes.js\";",
4254            ),
4255            "export default function AuthLogin({ title }: AuthLoginProps) {",
4256        ),
4257        ProjectFrontend::Jsx => (
4258            concat!(
4259                "import { FieldError, Form, Link, redirect } from \"@apizero/react\";\n",
4260                "// 启用图形验证码后解开:\n",
4261                "// import { CaptchaImage } from \"@apizero/react\";\n",
4262                "import { LoginInputFields } from \"../../generated/contracts.js\";\n",
4263                "import { home, login, register, routes } from \"../../generated/routes.js\";",
4264            ),
4265            "export default function AuthLogin({ title }) {",
4266        ),
4267    };
4268    format!("{imports}\n\n{signature}\n{AUTH_LOGIN_PAGE_BODY}")
4269}
4270
4271const AUTH_REGISTER_PAGE_BODY: &str = r#"  return (
4272    <main className="auth-page">
4273      <h1>{title}</h1>
4274      <Form
4275        action={register.store}
4276        initialValues={{ name: "", email: "", password: "" }}
4277        fields={RegisterInputFields}
4278        onSuccess={() => redirect(home())}
4279      >
4280        {(form) => (
4281          <>
4282            <label htmlFor="register-name">昵称</label>
4283            <input id="register-name" autoComplete="nickname" {...form.field("name")} />
4284            <FieldError errors={form.errors} name="name" />
4285
4286            <label htmlFor="register-email">邮箱</label>
4287            <input
4288              id="register-email"
4289              type="email"
4290              autoComplete="email"
4291              {...form.field("email")}
4292            />
4293            <FieldError errors={form.errors} name="email" />
4294
4295            <label htmlFor="register-password">密码</label>
4296            <input
4297              id="register-password"
4298              type="password"
4299              autoComplete="new-password"
4300              {...form.field("password")}
4301            />
4302            <FieldError errors={form.errors} name="password" />
4303
4304            <button type="submit" disabled={form.processing}>
4305              {form.processing ? "注册中…" : "注册"}
4306            </button>
4307          </>
4308        )}
4309      </Form>
4310      <p>
4311        已有账号?<Link href={login.show()}>登录</Link>
4312      </p>
4313    </main>
4314  );
4315}
4316"#;
4317
4318fn auth_register_page_template(frontend: ProjectFrontend) -> String {
4319    let (imports, signature) = match frontend {
4320        ProjectFrontend::Tsx => (
4321            concat!(
4322                "import { FieldError, Form, Link, redirect } from \"@apizero/react\";\n",
4323                "import type { AuthRegisterProps } from \"../../generated/contracts.js\";\n",
4324                "import { RegisterInputFields } from \"../../generated/contracts.js\";\n",
4325                "import { home, login, register } from \"../../generated/routes.js\";",
4326            ),
4327            "export default function AuthRegister({ title }: AuthRegisterProps) {",
4328        ),
4329        ProjectFrontend::Jsx => (
4330            concat!(
4331                "import { FieldError, Form, Link, redirect } from \"@apizero/react\";\n",
4332                "import { RegisterInputFields } from \"../../generated/contracts.js\";\n",
4333                "import { home, login, register } from \"../../generated/routes.js\";",
4334            ),
4335            "export default function AuthRegister({ title }) {",
4336        ),
4337    };
4338    format!("{imports}\n\n{signature}\n{AUTH_REGISTER_PAGE_BODY}")
4339}
4340
4341const AUTH_FORGOT_PASSWORD_PAGE_BODY: &str = r#"  const [notice, setNotice] = useState("");
4342  return (
4343    <main className="auth-page">
4344      <h1>{title}</h1>
4345      {notice ? <p role="status">{notice}</p> : null}
4346      <Form
4347        action={passwordReset.store}
4348        initialValues={{ email: "" }}
4349        fields={PasswordResetInputFields}
4350        onSuccess={(result) => setNotice(result.message)}
4351      >
4352        {(form) => (
4353          <>
4354            <label htmlFor="reset-email">邮箱</label>
4355            <input id="reset-email" type="email" autoComplete="email" {...form.field("email")} />
4356            <FieldError errors={form.errors} name="email" />
4357
4358            <button type="submit" disabled={form.processing}>
4359              {form.processing ? "发送中…" : "发送重置说明"}
4360            </button>
4361          </>
4362        )}
4363      </Form>
4364      <p>
4365        想起密码了?<Link href={login.show()}>返回登录</Link>
4366      </p>
4367    </main>
4368  );
4369}
4370"#;
4371
4372fn auth_forgot_password_page_template(frontend: ProjectFrontend) -> String {
4373    let (imports, signature) = match frontend {
4374        ProjectFrontend::Tsx => (
4375            concat!(
4376                "import { useState } from \"react\";\n",
4377                "import { FieldError, Form, Link } from \"@apizero/react\";\n",
4378                "import type { AuthForgotPasswordProps } from \"../../generated/contracts.js\";\n",
4379                "import { PasswordResetInputFields } from \"../../generated/contracts.js\";\n",
4380                "import { login, routes } from \"../../generated/routes.js\";\n",
4381                "\n",
4382                "const passwordReset = routes[\"password-reset\"];",
4383            ),
4384            "export default function AuthForgotPassword({ title }: AuthForgotPasswordProps) {",
4385        ),
4386        ProjectFrontend::Jsx => (
4387            concat!(
4388                "import { useState } from \"react\";\n",
4389                "import { FieldError, Form, Link } from \"@apizero/react\";\n",
4390                "import { PasswordResetInputFields } from \"../../generated/contracts.js\";\n",
4391                "import { login, routes } from \"../../generated/routes.js\";\n",
4392                "\n",
4393                "const passwordReset = routes[\"password-reset\"];",
4394            ),
4395            "export default function AuthForgotPassword({ title }) {",
4396        ),
4397    };
4398    format!("{imports}\n\n{signature}\n{AUTH_FORGOT_PASSWORD_PAGE_BODY}")
4399}
4400
4401fn rust_item_path(category: &str, name: &QualifiedName) -> String {
4402    if name.modules.is_empty() {
4403        format!("crate::{category}::{}", name.class)
4404    } else {
4405        format!(
4406            "crate::{category}::{}::{}",
4407            name.modules
4408                .iter()
4409                .map(|part| snake_case(part))
4410                .collect::<Vec<_>>()
4411                .join("::"),
4412            name.class,
4413        )
4414    }
4415}
4416
4417fn page_props_template(name: &str, route: &str) -> String {
4418    format!(
4419        r#"use serde::Serialize;
4420
4421#[phoenix::contract(page, page = "{route}")]
4422#[derive(Serialize)]
4423#[serde(rename_all = "camelCase")]
4424pub struct {name} {{
4425    pub title: String,
4426}}
4427"#
4428    )
4429}
4430
4431fn page_template(component: &str, props: &str, depth: usize, frontend: ProjectFrontend) -> String {
4432    let contracts = format!("{}generated/contracts.js", "../".repeat(depth));
4433    if frontend == ProjectFrontend::Jsx {
4434        return format!(
4435            r"export default function {component}({{ title }}) {{
4436  return (
4437    <main>
4438      <h1>{{title}}</h1>
4439    </main>
4440  );
4441}}
4442"
4443        );
4444    }
4445    format!(
4446        r#"import type {{ {props} }} from "{contracts}";
4447
4448export default function {component}({{ title }}: {props}) {{
4449  return (
4450    <main>
4451      <h1>{{title}}</h1>
4452    </main>
4453  );
4454}}
4455"#
4456    )
4457}
4458
4459fn island_template(component: &str, frontend: ProjectFrontend) -> String {
4460    if frontend == ProjectFrontend::Jsx {
4461        return format!(
4462            r#"import {{ useState }} from "react";
4463
4464export default function {component}({{ initialCount = 0 }}) {{
4465  const [count, setCount] = useState(initialCount);
4466  return <button type="button" onClick={{() => setCount((value) => value + 1)}}>{{count}}</button>;
4467}}
4468"#
4469        );
4470    }
4471    format!(
4472        r#"import {{ useState }} from "react";
4473
4474export interface {component}Props {{
4475  initialCount?: number;
4476}}
4477
4478export default function {component}({{ initialCount = 0 }}: {component}Props) {{
4479  const [count, setCount] = useState(initialCount);
4480  return <button type="button" onClick={{() => setCount((value) => value + 1)}}>{{count}}</button>;
4481}}
4482"#
4483    )
4484}
4485
4486fn render_model_registry(values: &BTreeSet<String>) -> Vec<String> {
4487    let mut lines = values
4488        .iter()
4489        .map(|value| format!("// phoenix:model: {value}"))
4490        .collect::<Vec<_>>();
4491    if !lines.is_empty() {
4492        lines.push(String::new());
4493    }
4494    lines.extend([
4495        "#[must_use]".to_owned(),
4496        "pub fn all() -> phoenix::database::ModelSet {".to_owned(),
4497        "    phoenix::database::models!(".to_owned(),
4498    ]);
4499    lines.extend(values.iter().map(|value| format!("        {value},")));
4500    lines.extend(["    )".to_owned(), "}".to_owned()]);
4501    lines
4502}
4503
4504fn render_migration_registry(values: &BTreeSet<String>) -> Vec<String> {
4505    let mut lines = Vec::new();
4506    for value in values {
4507        lines.push(format!("// phoenix:migration: {value}"));
4508        lines.push(format!("pub mod {value};"));
4509    }
4510    if !lines.is_empty() {
4511        lines.push(String::new());
4512    }
4513    lines.extend([
4514        "#[must_use]".to_owned(),
4515        "pub fn all() -> Vec<phoenix::database::Migration> {".to_owned(),
4516        "    vec![".to_owned(),
4517    ]);
4518    lines.extend(
4519        values
4520            .iter()
4521            .map(|value| format!("        {value}::migration(),")),
4522    );
4523    lines.extend(["    ]".to_owned(), "}".to_owned()]);
4524    lines
4525}
4526
4527struct ProjectEditor {
4528    root: PathBuf,
4529    force: bool,
4530    changes: BTreeMap<PathBuf, String>,
4531}
4532
4533impl ProjectEditor {
4534    fn new(root: &Path, force: bool) -> Self {
4535        Self {
4536            root: root.to_path_buf(),
4537            force,
4538            changes: BTreeMap::new(),
4539        }
4540    }
4541
4542    fn create(
4543        &mut self,
4544        relative: impl Into<PathBuf>,
4545        content: String,
4546    ) -> Result<(), ScaffoldError> {
4547        let relative = safe_relative(relative.into())?;
4548        let absolute = self.root.join(&relative);
4549        if !self.force && (absolute.exists() || self.changes.contains_key(&relative)) {
4550            return Err(ScaffoldError::AlreadyExists(absolute));
4551        }
4552        self.changes.insert(relative, content);
4553        Ok(())
4554    }
4555
4556    /// Overwrite a file unconditionally (used to patch existing managed files
4557    /// such as `Cargo.toml` that have no marker regions).
4558    fn set(&mut self, relative: impl Into<PathBuf>, content: String) -> Result<(), ScaffoldError> {
4559        let relative = safe_relative(relative.into())?;
4560        self.changes.insert(relative, content);
4561        Ok(())
4562    }
4563
4564    fn read(&self, relative: &Path) -> Result<String, ScaffoldError> {
4565        if let Some(content) = self.changes.get(relative) {
4566            return Ok(content.clone());
4567        }
4568        let absolute = self.root.join(relative);
4569        match fs::read_to_string(&absolute) {
4570            Ok(content) => Ok(content),
4571            Err(error) if error.kind() == ErrorKind::NotFound => Ok(String::new()),
4572            Err(source) => Err(ScaffoldError::Io {
4573                path: absolute,
4574                source,
4575            }),
4576        }
4577    }
4578
4579    fn update_managed_lines(
4580        &mut self,
4581        relative: impl AsRef<Path>,
4582        start: &str,
4583        end: &str,
4584        added: &[String],
4585    ) -> Result<(), ScaffoldError> {
4586        let relative = safe_relative(relative.as_ref().to_path_buf())?;
4587        let existing = self.read(&relative)?;
4588        let initialized = if existing.is_empty() {
4589            format!("{start}\n{end}\n")
4590        } else {
4591            existing
4592        };
4593        let (before, managed, after) = managed_parts(&initialized, start, end)
4594            .ok_or_else(|| ScaffoldError::InvalidManagedFile(self.root.join(&relative)))?;
4595        let mut lines = managed
4596            .lines()
4597            .map(str::trim)
4598            .filter(|line| !line.is_empty())
4599            .map(str::to_owned)
4600            .collect::<BTreeSet<_>>();
4601        lines.extend(added.iter().cloned());
4602        let body = lines.into_iter().collect::<Vec<_>>().join("\n");
4603        let body = if body.is_empty() {
4604            body
4605        } else {
4606            format!("{body}\n")
4607        };
4608        self.changes
4609            .insert(relative, format!("{before}{start}\n{body}{end}{after}"));
4610        Ok(())
4611    }
4612
4613    fn update_registry(
4614        &mut self,
4615        relative: impl AsRef<Path>,
4616        start: &str,
4617        end: &str,
4618        key: &str,
4619        value: &str,
4620        render: fn(&BTreeSet<String>) -> Vec<String>,
4621    ) -> Result<(), ScaffoldError> {
4622        let relative = safe_relative(relative.as_ref().to_path_buf())?;
4623        let existing = self.read(&relative)?;
4624        let initialized = if existing.is_empty() {
4625            format!("{start}\n{end}\n")
4626        } else {
4627            existing
4628        };
4629        let (before, managed, after) = managed_parts(&initialized, start, end)
4630            .ok_or_else(|| ScaffoldError::InvalidManagedFile(self.root.join(&relative)))?;
4631        let prefix = format!("// phoenix:{key}: ");
4632        let mut values = managed
4633            .lines()
4634            .filter_map(|line| line.trim().strip_prefix(&prefix).map(str::to_owned))
4635            .collect::<BTreeSet<_>>();
4636        values.insert(value.to_owned());
4637        let rendered = render(&values).join("\n");
4638        let body = if rendered.is_empty() {
4639            rendered
4640        } else {
4641            format!("{rendered}\n")
4642        };
4643        self.changes
4644            .insert(relative, format!("{before}{start}\n{body}{end}{after}"));
4645        Ok(())
4646    }
4647
4648    fn commit(self) -> Result<Vec<PathBuf>, ScaffoldError> {
4649        let mut written = Vec::with_capacity(self.changes.len());
4650        for (relative, content) in self.changes {
4651            let path = self.root.join(relative);
4652            if let Some(parent) = path.parent() {
4653                fs::create_dir_all(parent).map_err(|source| ScaffoldError::Io {
4654                    path: parent.to_path_buf(),
4655                    source,
4656                })?;
4657            }
4658            fs::write(&path, content).map_err(|source| ScaffoldError::Io {
4659                path: path.clone(),
4660                source,
4661            })?;
4662            written.push(path);
4663        }
4664        Ok(written)
4665    }
4666}
4667
4668fn managed_parts<'a>(
4669    content: &'a str,
4670    start: &str,
4671    end: &str,
4672) -> Option<(&'a str, &'a str, &'a str)> {
4673    let start_index = content.find(start)?;
4674    let managed_start = start_index + start.len();
4675    let end_relative = content[managed_start..].find(end)?;
4676    let end_index = managed_start + end_relative;
4677    if content[end_index + end.len()..].contains(end) || content[..start_index].contains(start) {
4678        return None;
4679    }
4680    Some((
4681        &content[..start_index],
4682        content[managed_start..end_index].trim_matches('\n'),
4683        &content[end_index + end.len()..],
4684    ))
4685}
4686
4687#[derive(Clone, Debug)]
4688struct QualifiedName {
4689    modules: Vec<String>,
4690    class: String,
4691}
4692
4693impl QualifiedName {
4694    fn parse(value: &str) -> Result<Self, ScaffoldError> {
4695        let parts = name_parts(value)?;
4696        let class = pascal_case(parts.last().expect("validated names have a leaf"));
4697        let modules = parts[..parts.len() - 1]
4698            .iter()
4699            .map(|part| pascal_case(part))
4700            .collect();
4701        Ok(Self { modules, class })
4702    }
4703
4704    fn parse_with_suffix(value: &str, suffix: &str) -> Result<Self, ScaffoldError> {
4705        let mut name = Self::parse(value)?;
4706        if !name.class.ends_with(suffix) {
4707            name.class.push_str(suffix);
4708        }
4709        Ok(name)
4710    }
4711
4712    fn with_leaf(&self, class: String) -> Self {
4713        Self {
4714            modules: self.modules.clone(),
4715            class,
4716        }
4717    }
4718
4719    fn index_page_name(&self) -> PageName {
4720        let mut parts = self.modules.clone();
4721        parts.push(pluralize(&self.class));
4722        parts.push("Index".to_owned());
4723        PageName::from_parts(parts)
4724    }
4725}
4726
4727#[derive(Clone, Debug)]
4728struct PageName {
4729    parts: Vec<String>,
4730    route: String,
4731    class: String,
4732}
4733
4734impl PageName {
4735    fn parse(value: &str) -> Result<Self, ScaffoldError> {
4736        let parts = name_parts(value)?
4737            .into_iter()
4738            .map(|part| pascal_case(&part))
4739            .collect();
4740        Ok(Self::from_parts(parts))
4741    }
4742
4743    fn from_parts(parts: Vec<String>) -> Self {
4744        let route = parts
4745            .iter()
4746            .map(|part| kebab_case(part))
4747            .collect::<Vec<_>>()
4748            .join("/");
4749        let class = parts.iter().map(String::as_str).collect::<String>();
4750        Self {
4751            parts,
4752            route,
4753            class,
4754        }
4755    }
4756}
4757
4758fn name_parts(value: &str) -> Result<Vec<String>, ScaffoldError> {
4759    let normalized = value.replace("::", "/").replace('\\', "/");
4760    let parts = normalized
4761        .split('/')
4762        .filter(|part| !part.is_empty())
4763        .map(str::to_owned)
4764        .collect::<Vec<_>>();
4765    if parts.is_empty()
4766        || parts.iter().any(|part| {
4767            !part.chars().all(|character| {
4768                character.is_ascii_alphanumeric() || character == '_' || character == '-'
4769            }) || !part
4770                .chars()
4771                .any(|character| character.is_ascii_alphabetic())
4772        })
4773    {
4774        return Err(ScaffoldError::InvalidName(value.to_owned()));
4775    }
4776    Ok(parts)
4777}
4778
4779fn package_name(value: &str) -> Result<String, ScaffoldError> {
4780    let value = kebab_case(value).trim_matches('-').to_owned();
4781    if value.is_empty()
4782        || value.starts_with(|character: char| character.is_ascii_digit())
4783        || !value.chars().all(|character| {
4784            character.is_ascii_lowercase() || character.is_ascii_digit() || character == '-'
4785        })
4786    {
4787        return Err(ScaffoldError::InvalidName(value));
4788    }
4789    Ok(value)
4790}
4791
4792fn snake_identifier(value: &str) -> Result<String, ScaffoldError> {
4793    let parts = name_parts(value)?;
4794    Ok(parts
4795        .iter()
4796        .map(|part| snake_case(part))
4797        .collect::<Vec<_>>()
4798        .join("_"))
4799}
4800
4801fn pascal_case(value: &str) -> String {
4802    words(value)
4803        .into_iter()
4804        .map(|word| {
4805            let mut characters = word.chars();
4806            characters.next().map_or_else(String::new, |first| {
4807                format!(
4808                    "{}{}",
4809                    first.to_ascii_uppercase(),
4810                    characters.as_str().to_ascii_lowercase()
4811                )
4812            })
4813        })
4814        .collect()
4815}
4816
4817fn snake_case(value: &str) -> String {
4818    words(value).join("_").to_ascii_lowercase()
4819}
4820
4821fn kebab_case(value: &str) -> String {
4822    words(value).join("-").to_ascii_lowercase()
4823}
4824
4825fn words(value: &str) -> Vec<String> {
4826    let mut output = String::new();
4827    let mut previous_lower_or_digit = false;
4828    for character in value.chars() {
4829        if character == '-' || character == '_' || character.is_ascii_whitespace() {
4830            if !output.ends_with('_') && !output.is_empty() {
4831                output.push('_');
4832            }
4833            previous_lower_or_digit = false;
4834        } else {
4835            if character.is_ascii_uppercase() && previous_lower_or_digit {
4836                output.push('_');
4837            }
4838            output.push(character);
4839            previous_lower_or_digit = character.is_ascii_lowercase() || character.is_ascii_digit();
4840        }
4841    }
4842    output
4843        .split('_')
4844        .filter(|part| !part.is_empty())
4845        .map(str::to_owned)
4846        .collect()
4847}
4848
4849fn pluralize(value: &str) -> String {
4850    if let Some(stem) = value.strip_suffix('y')
4851        && !stem.ends_with(['a', 'e', 'i', 'o', 'u'])
4852    {
4853        return format!("{stem}ies");
4854    }
4855    if value.ends_with(['s', 'x', 'z']) || value.ends_with("ch") || value.ends_with("sh") {
4856        format!("{value}es")
4857    } else {
4858        format!("{value}s")
4859    }
4860}
4861
4862fn inferred_table(migration: &str) -> &str {
4863    migration
4864        .strip_prefix("create_")
4865        .and_then(|name| name.strip_suffix("_table"))
4866        .unwrap_or(migration)
4867}
4868
4869fn safe_relative(path: PathBuf) -> Result<PathBuf, ScaffoldError> {
4870    if path.is_absolute()
4871        || path
4872            .components()
4873            .any(|component| !matches!(component, Component::Normal(_)))
4874    {
4875        return Err(ScaffoldError::InvalidName(path.display().to_string()));
4876    }
4877    Ok(path)
4878}
4879
4880fn absolute_path(path: impl AsRef<Path>) -> Result<PathBuf, ScaffoldError> {
4881    let path = path.as_ref();
4882    if path.is_absolute() {
4883        return Ok(path.to_path_buf());
4884    }
4885    env::current_dir()
4886        .map(|current| current.join(path))
4887        .map_err(|source| ScaffoldError::Io {
4888            path: path.to_path_buf(),
4889            source,
4890        })
4891}
4892
4893fn ensure_empty_target(path: &Path) -> Result<(), ScaffoldError> {
4894    match fs::read_dir(path) {
4895        Ok(mut entries) => {
4896            if entries.next().is_some() {
4897                Err(ScaffoldError::ProjectNotEmpty(path.to_path_buf()))
4898            } else {
4899                Ok(())
4900            }
4901        }
4902        Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),
4903        Err(source) => Err(ScaffoldError::Io {
4904            path: path.to_path_buf(),
4905            source,
4906        }),
4907    }
4908}
4909
4910fn json_string(value: &str) -> String {
4911    serde_json::to_string(value).expect("strings always serialize")
4912}
4913
4914fn run_optional(program: &'static str, args: &[&str], cwd: &Path) -> Result<(), ScaffoldError> {
4915    match Command::new(program).args(args).current_dir(cwd).status() {
4916        Ok(status) if status.success() => Ok(()),
4917        Ok(_) => Err(ScaffoldError::CommandFailed { program }),
4918        Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),
4919        Err(source) => Err(ScaffoldError::Io {
4920            path: cwd.to_path_buf(),
4921            source,
4922        }),
4923    }
4924}
4925
4926fn run_required(program: &'static str, args: &[&str], cwd: &Path) -> Result<(), ScaffoldError> {
4927    match Command::new(program).args(args).current_dir(cwd).status() {
4928        Ok(status) if status.success() => Ok(()),
4929        Ok(_) => Err(ScaffoldError::CommandFailed { program }),
4930        Err(source) => Err(ScaffoldError::Io {
4931            path: cwd.to_path_buf(),
4932            source,
4933        }),
4934    }
4935}
4936
4937#[cfg(test)]
4938mod tests {
4939    use super::*;
4940
4941    fn temporary_directory(label: &str) -> PathBuf {
4942        let id = SystemTime::now()
4943            .duration_since(UNIX_EPOCH)
4944            .unwrap()
4945            .as_nanos();
4946        env::temp_dir().join(format!("phoenix-cli-{label}-{}-{id}", std::process::id()))
4947    }
4948
4949    fn framework_root() -> PathBuf {
4950        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
4951            .join("../..")
4952            .canonicalize()
4953            .unwrap()
4954    }
4955
4956    // Flat scaffold assertions; length is coverage, not logic.
4957    #[allow(clippy::too_many_lines)]
4958    #[test]
4959    fn creates_a_complete_local_project_without_installing() {
4960        let root = temporary_directory("new");
4961        create_project(
4962            &NewProjectOptions::new(&root)
4963                .dependencies(DependencySource::Local(framework_root()))
4964                .database(Some(ProjectDatabase::Sqlite))
4965                .initialize_git(false)
4966                .install_dependencies(false),
4967        )
4968        .unwrap();
4969
4970        assert!(root.join("src/main.rs").is_file());
4971        assert!(root.join("src/bin/phoenix-manage.rs").is_file());
4972        // Runtime settings converged into `.env`; config/ holds Feature TOML only.
4973        assert!(!root.join("config/app.toml").exists());
4974        assert!(!root.join("config/database.toml").exists());
4975        assert!(!root.join("config/schemas").exists());
4976        assert!(!root.join("taplo.toml").exists());
4977        assert!(!root.join("deploy").exists());
4978        let env_example = fs::read_to_string(root.join(".env.example")).unwrap();
4979        assert!(env_example.contains("DATABASE_URL=sqlite:storage/app.sqlite"));
4980        assert!(env_example.contains("APP_ADDR=127.0.0.1:3000"));
4981        assert!(env_example.contains("VITE_DEV_URL="));
4982        assert!(env_example.contains("PHOENIX_LOG="));
4983        assert!(root.join("app/commands/mod.rs").is_file());
4984        assert!(root.join("config/mod.rs").is_file());
4985        assert!(root.join("database/seeders/mod.rs").is_file());
4986        assert!(root.join("routes/web.rs").is_file());
4987        assert!(root.join("views/pages/home.tsx").is_file());
4988        let manifest = fs::read_to_string(root.join("Cargo.toml")).unwrap();
4989        assert!(manifest.contains("crates/phoenix"));
4990        assert!(manifest.contains("default-run = \"phoenix-cli-new-"));
4991        assert!(manifest.contains("default = [\"sqlite\"]"));
4992        assert!(manifest.contains("sqlite = [\"database\", \"phoenix/sqlite\"]"));
4993        assert!(manifest.contains("features = [\"migration\", \"serde\", \"sqlite\"]"));
4994        assert!(manifest.contains("tls = [\"phoenix/tls\"]"));
4995        assert!(manifest.contains("websocket = [\"phoenix/websocket\"]"));
4996        assert!(manifest.contains("sse = [\"phoenix/sse\"]"));
4997        assert!(manifest.contains("default-features = false"));
4998        assert!(manifest.contains("opt-level = \"z\""));
4999        assert!(manifest.contains("strip = \"symbols\""));
5000        assert!(
5001            fs::read_to_string(root.join("package.json"))
5002                .unwrap()
5003                .contains("file:")
5004        );
5005        let main = fs::read_to_string(root.join("src/main.rs")).unwrap();
5006        assert!(main.contains("Console::new"));
5007        assert!(main.contains("commands::registry()"));
5008        assert!(main.contains(".serve("));
5009        let commands = fs::read_to_string(root.join("app/commands/mod.rs")).unwrap();
5010        assert!(commands.contains("commands!"));
5011        assert!(commands.contains("<phoenix:commands>"));
5012        let application = fs::read_to_string(root.join("src/lib.rs")).unwrap();
5013        assert!(application.contains("pub mod commands"));
5014        assert!(application.contains("NonceSecurityPolicy::development"));
5015        assert!(application.contains("with_middleware(content_security_policy(config))"));
5016        assert!(application.contains("with_middleware(RequestId)"));
5017        assert!(application.contains("with_middleware(AccessLog)"));
5018        assert!(application.contains("SessionMiddleware::new"));
5019        assert!(application.contains("with_middleware(Csrf)"));
5020        assert!(application.contains("TrustedProxies::new"));
5021        assert!(application.contains("HostAllowlist::new"));
5022        assert!(application.contains("RateLimit::new"));
5023        assert!(application.contains("StateMiddleware::new(config.clone())"));
5024        assert!(application.contains("StateMiddleware::new(renderer.clone())"));
5025        assert!(application.contains("RendererConfig::production"));
5026        assert!(application.contains("renderer.warm_up().await"));
5027        assert!(
5028            application
5029                .contains("let vite_dev_server = std::env::var_os(\"PHOENIX_VITE_DEV\").is_some()")
5030        );
5031        assert!(application.contains("RendererConfig::node(\"public/ssr/renderer.js\")"));
5032        let home_controller =
5033            fs::read_to_string(root.join("app/controllers/home_controller.rs")).unwrap();
5034        assert!(home_controller.contains("get::<NodeRenderer>().cloned()"));
5035        assert!(home_controller.contains("respond_with_renderer(request, &renderer).await"));
5036        assert!(
5037            home_controller.contains("PHOENIX_VITE_DEV"),
5038            "scaffold must gate Vite client injection on PHOENIX_VITE_DEV"
5039        );
5040        let home_route = fs::read_to_string(root.join("routes/web.rs")).unwrap();
5041        assert!(home_route.contains(".get(\"/\", HomeController::index)"));
5042        assert!(home_route.contains(".name(\"demo.spa\")"));
5043        assert!(home_route.contains(".name(\"demo.ssr\")"));
5044        assert!(home_route.contains(".name(\"demo.islands\")"));
5045        let cargo = env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
5046        let status = Command::new(cargo)
5047            .args(["check", "--quiet"])
5048            .current_dir(&root)
5049            .status()
5050            .unwrap();
5051        assert!(status.success());
5052        let config = fs::read_to_string(root.join("config/mod.rs")).unwrap();
5053        assert!(config.contains("AppConfig::load()"));
5054        assert!(config.lines().count() < 20);
5055        let manager = fs::read_to_string(root.join("src/bin/phoenix-manage.rs")).unwrap();
5056        assert!(manager.contains("MigrationRunner::new"));
5057        assert!(manager.contains("migrations::all()"));
5058        assert!(manager.contains("seeders::run"));
5059        let models = fs::read_to_string(root.join("app/models/mod.rs")).unwrap();
5060        let migrations = fs::read_to_string(root.join("database/migrations/mod.rs")).unwrap();
5061        assert!(models.contains("pub fn all()"));
5062        assert!(migrations.contains("pub fn all()"));
5063        fs::remove_dir_all(root).unwrap();
5064    }
5065
5066    #[test]
5067    fn default_project_is_islands_without_database_or_git() {
5068        let root = temporary_directory("default-options");
5069        let options = NewProjectOptions::new(&root)
5070            .dependencies(DependencySource::Local(framework_root()))
5071            .install_dependencies(false);
5072        assert!(!options.initialize_git);
5073        assert_eq!(options.render_mode, ProjectRenderMode::Islands);
5074        assert_eq!(options.database, None);
5075        assert_eq!(options.frontend, ProjectFrontend::Tsx);
5076        create_project(&options).unwrap();
5077
5078        let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
5079        assert!(cargo.contains("default = []"));
5080        assert!(!cargo.contains("toasty ="));
5081        assert!(!root.join("config/database.toml").exists());
5082        assert!(!root.join("src/bin/phoenix-manage.rs").exists());
5083        let home_controller =
5084            fs::read_to_string(root.join("app/controllers/home_controller.rs")).unwrap();
5085        // The chosen mode drives the home page; every mode has a demo action.
5086        assert!(home_controller.contains("Page::new(\n            \"home\""));
5087        assert!(home_controller.contains(".islands();"));
5088        assert!(home_controller.contains("Page::new(\"demo/spa\", serde_json::json!({})).spa()"));
5089        assert!(home_controller.contains("DemoSsrProps { rendered_at }).ssr()"));
5090        assert!(
5091            home_controller
5092                .contains("Page::new(\"demo/islands\", serde_json::json!({})).islands()")
5093        );
5094        // One demo page per render mode, plus the hydrated counter island.
5095        let spa = fs::read_to_string(root.join("views/pages/demo/spa.tsx")).unwrap();
5096        assert!(spa.contains("useState"));
5097        let ssr = fs::read_to_string(root.join("views/pages/demo/ssr.tsx")).unwrap();
5098        assert!(ssr.contains("renderedAt"));
5099        let islands = fs::read_to_string(root.join("views/pages/demo/islands.tsx")).unwrap();
5100        assert!(islands.contains("client:load"));
5101        assert!(root.join("views/islands/counter.tsx").is_file());
5102        let home = fs::read_to_string(root.join("views/pages/home.tsx")).unwrap();
5103        assert!(home.contains("<Link href={demo.spa()}"));
5104        assert!(home.contains("<Link href={demo.ssr()}"));
5105        assert!(home.contains("<Link href={demo.islands()}"));
5106        assert!(!root.join(".git").exists());
5107
5108        let cargo = env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
5109        let status = Command::new(cargo)
5110            .args(["check", "--quiet"])
5111            .current_dir(&root)
5112            .status()
5113            .unwrap();
5114        assert!(status.success());
5115        fs::remove_dir_all(root).unwrap();
5116    }
5117
5118    #[test]
5119    fn project_options_select_jsx_tailwind_and_database() {
5120        let root = temporary_directory("options");
5121        create_project(
5122            &NewProjectOptions::new(&root)
5123                .dependencies(DependencySource::Local(framework_root()))
5124                .database(Some(ProjectDatabase::Pgsql))
5125                .render_mode(ProjectRenderMode::Ssr)
5126                .frontend(ProjectFrontend::Jsx)
5127                .tailwind(true)
5128                .install_dependencies(false),
5129        )
5130        .unwrap();
5131
5132        let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
5133        assert!(cargo.contains("default = [\"pgsql\"]"));
5134        assert!(cargo.contains("\"postgresql\""));
5135        assert!(root.join("views/pages/home.jsx").is_file());
5136        assert!(!root.join("views/pages/home.tsx").exists());
5137        assert!(
5138            fs::read_to_string(root.join("app/controllers/home_controller.rs"))
5139                .unwrap()
5140                .contains(".ssr()")
5141        );
5142        assert!(
5143            fs::read_to_string(root.join("package.json"))
5144                .unwrap()
5145                .contains("@tailwindcss/vite")
5146        );
5147        assert!(
5148            fs::read_to_string(root.join("views/styles.css"))
5149                .unwrap()
5150                .starts_with("@import \"tailwindcss\";")
5151        );
5152        assert!(
5153            fs::read_to_string(root.join("vite.config.ts"))
5154                .unwrap()
5155                .contains("tailwindcss()")
5156        );
5157        let generator = ProjectGenerator::discover(&root).unwrap();
5158        generator
5159            .page("reports/index", GenerateOptions::default())
5160            .unwrap();
5161        generator
5162            .island("LikeButton", GenerateOptions::default())
5163            .unwrap();
5164        assert!(root.join("views/pages/reports/index.jsx").is_file());
5165        assert!(root.join("views/islands/like-button.jsx").is_file());
5166        // The scaffolded demo island is already there in the selected frontend.
5167        assert!(root.join("views/islands/counter.jsx").is_file());
5168        assert!(
5169            !fs::read_to_string(root.join("views/pages/reports/index.jsx"))
5170                .unwrap()
5171                .contains("import type")
5172        );
5173        generator.auth(GenerateOptions::default()).unwrap();
5174        assert!(root.join("views/pages/auth/login.jsx").is_file());
5175        assert!(
5176            !fs::read_to_string(root.join("views/pages/auth/login.jsx"))
5177                .unwrap()
5178                .contains("import type")
5179        );
5180        fs::remove_dir_all(root).unwrap();
5181    }
5182
5183    #[test]
5184    fn all_database_option_writes_all_toasty_drivers() {
5185        let root = temporary_directory("all-databases");
5186        create_project(
5187            &NewProjectOptions::new(&root)
5188                .dependencies(DependencySource::Local(framework_root()))
5189                .database(Some(ProjectDatabase::All))
5190                .install_dependencies(false),
5191        )
5192        .unwrap();
5193        let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
5194        assert!(cargo.contains(
5195            "toasty = { version = \"0.8\", default-features = false, features = [\"migration\", \"mysql\", \"postgresql\", \"serde\", \"sqlite\"] }"
5196        ));
5197        assert!(cargo.contains("all-databases = [\"database\", \"phoenix/sqlite\", \"phoenix/pgsql\", \"phoenix/mysql\"]"));
5198        let cargo = env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
5199        let status = Command::new(cargo)
5200            .args(["check", "--quiet"])
5201            .current_dir(&root)
5202            .status()
5203            .unwrap();
5204        assert!(status.success());
5205        fs::remove_dir_all(root).unwrap();
5206    }
5207
5208    #[test]
5209    fn registry_dependencies_use_plain_versions_not_npmjs_tarballs() {
5210        let (phoenix, react, react_ssr, vite) =
5211            framework_dependency_pins(&DependencySource::Registry, &[]).unwrap();
5212        for pin in [&phoenix, &react, &react_ssr, &vite] {
5213            assert!(
5214                !pin.contains("registry.npmjs.org"),
5215                "registry pins must not bypass the user's npm mirror: {pin}"
5216            );
5217        }
5218        assert_eq!(react, format!("^{APIZERO_REACT_VERSION}"));
5219        assert_eq!(react_ssr, format!("^{APIZERO_REACT_SSR_VERSION}"));
5220        assert_eq!(vite, format!("^{APIZERO_VITE_VERSION}"));
5221        assert!(phoenix.contains(&format!("version = \"{PHOENIXRS_VERSION}\"")));
5222        assert!(!phoenix.contains("features = ["));
5223
5224        let (phoenix, ..) = framework_dependency_pins(
5225            &DependencySource::Registry,
5226            &[ProjectFeature::Captcha, ProjectFeature::Pay],
5227        )
5228        .unwrap();
5229        assert!(phoenix.contains("features = [\"captcha\", \"pay\"]"));
5230    }
5231
5232    #[test]
5233    fn feature_selection_generates_config_and_assembly() {
5234        let root = temporary_directory("features");
5235        create_project(
5236            &NewProjectOptions::new(&root)
5237                .dependencies(DependencySource::Local(framework_root()))
5238                .database(Some(ProjectDatabase::Sqlite))
5239                .features(vec![
5240                    ProjectFeature::Captcha,
5241                    ProjectFeature::Pay,
5242                    ProjectFeature::Notify,
5243                ])
5244                .install_dependencies(false),
5245        )
5246        .unwrap();
5247
5248        let cargo_manifest = fs::read_to_string(root.join("Cargo.toml")).unwrap();
5249        assert!(cargo_manifest.contains("features = [\"captcha\", \"pay\", \"notify\"]"));
5250
5251        let pay_config = fs::read_to_string(root.join("config/pay.toml")).unwrap();
5252        assert!(pay_config.contains("${PAY_WECHAT_API_V3_KEY}"));
5253        assert!(root.join("config/captcha.toml").is_file());
5254        assert!(root.join("config/notify.toml").is_file());
5255
5256        let lib = fs::read_to_string(root.join("src/lib.rs")).unwrap();
5257        assert!(lib.contains("pub fn features()"));
5258        assert!(lib.contains("CaptchaFeature::new()"));
5259        assert!(lib.contains("PayFeature::new(pay_manager()?)"));
5260        assert!(lib.contains("NotifyFeature::new()"));
5261        assert!(lib.contains("load_feature_config(\"pay\")"));
5262        assert!(lib.contains("pub fn notifier()"));
5263        // Webhooks stay outside CSRF; business routes keep it via the scope.
5264        assert!(lib.contains(".scoped(RouteGroup::new().middleware(Csrf))"));
5265        assert!(lib.contains(".merge(features()?.into_routes())"));
5266
5267        let manage = fs::read_to_string(root.join("src/bin/phoenix-manage.rs")).unwrap();
5268        assert!(manage.contains("features.into_parts().migrations"));
5269
5270        let env_example = fs::read_to_string(root.join(".env.example")).unwrap();
5271        assert!(env_example.contains("PAY_WECHAT_API_V3_KEY"));
5272        let stored = fs::read_to_string(root.join(".phoenix")).unwrap();
5273        assert!(stored.contains("features=captcha,pay,notify"));
5274        let readme = fs::read_to_string(root.join("README.md")).unwrap();
5275        assert!(readme.contains("已启用 Feature"));
5276
5277        let cargo = env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
5278        let status = Command::new(cargo)
5279            .args(["check", "--quiet"])
5280            .current_dir(&root)
5281            .status()
5282            .unwrap();
5283        assert!(status.success());
5284        fs::remove_dir_all(root).unwrap();
5285    }
5286
5287    #[test]
5288    fn feature_add_writes_only_requested_config_and_records_option() {
5289        let root = temporary_directory("feature-add");
5290        create_project(
5291            &NewProjectOptions::new(&root)
5292                .dependencies(DependencySource::Local(framework_root()))
5293                .database(Some(ProjectDatabase::Sqlite))
5294                .install_dependencies(false),
5295        )
5296        .unwrap();
5297
5298        let generator = ProjectGenerator::discover(&root).unwrap();
5299        let result = generator.add_feature(ProjectFeature::Captcha).unwrap();
5300
5301        assert!(result.integration_note.is_some());
5302        let captcha = fs::read_to_string(root.join("config/captcha.toml")).unwrap();
5303        assert!(captcha.contains("# 图形验证码 Feature(phoenix-captcha)。"));
5304        assert!(captcha.contains("# length = 5"));
5305        assert!(!root.join("config/pay.toml").exists());
5306        assert!(!root.join("config/notify.toml").exists());
5307        assert!(
5308            fs::read_to_string(root.join(".phoenix"))
5309                .unwrap()
5310                .contains("features=captcha")
5311        );
5312        let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
5313        assert!(cargo.contains("default = [\"sqlite\", \"captcha\"]"));
5314        assert!(cargo.contains("captcha = [\"phoenix/captcha\"]"));
5315        assert!(
5316            fs::read_to_string(root.join(".env.example"))
5317                .unwrap()
5318                .contains("# 验证码无密钥;参数见 config/captcha.toml。")
5319        );
5320        fs::remove_dir_all(root).unwrap();
5321    }
5322
5323    #[test]
5324    fn stored_feature_options_survive_update_core() {
5325        let root = temporary_directory("features-update");
5326        create_project(
5327            &NewProjectOptions::new(&root)
5328                .dependencies(DependencySource::Local(framework_root()))
5329                .features(vec![ProjectFeature::Captcha])
5330                .install_dependencies(false),
5331        )
5332        .unwrap();
5333        // User values in feature config files must survive `px update`.
5334        fs::write(root.join("config/captcha.toml"), "length = 6\n").unwrap();
5335
5336        let generator = ProjectGenerator::discover(&root).unwrap();
5337        let _ = generator
5338            .update_core(
5339                &UpdateProjectOptions::new()
5340                    .dependencies(DependencySource::Local(framework_root()))
5341                    .install_dependencies(false),
5342            )
5343            .unwrap();
5344
5345        let lib = fs::read_to_string(root.join("src/lib.rs")).unwrap();
5346        assert!(lib.contains("CaptchaFeature::new()"));
5347        let cargo_manifest = fs::read_to_string(root.join("Cargo.toml")).unwrap();
5348        assert!(cargo_manifest.contains("features = [\"captcha\"]"));
5349        assert_eq!(
5350            fs::read_to_string(root.join("config/captcha.toml")).unwrap(),
5351            "length = 6\n"
5352        );
5353        fs::remove_dir_all(root).unwrap();
5354    }
5355
5356    #[test]
5357    fn make_command_registers_async_handler() {
5358        let root = temporary_directory("command");
5359        create_project(
5360            &NewProjectOptions::new(&root)
5361                .dependencies(DependencySource::Local(framework_root()))
5362                .database(Some(ProjectDatabase::Sqlite))
5363                .initialize_git(false)
5364                .install_dependencies(false),
5365        )
5366        .unwrap();
5367        let generator = ProjectGenerator::discover(&root).unwrap();
5368        generator
5369            .command("Update", GenerateOptions::default())
5370            .unwrap();
5371
5372        assert!(root.join("app/commands/update.rs").is_file());
5373        let module = fs::read_to_string(root.join("app/commands/mod.rs")).unwrap();
5374        assert!(module.contains("pub mod update;"));
5375        assert!(module.contains("pub use update::update;"));
5376        assert!(module.contains("update,"));
5377        let command = fs::read_to_string(root.join("app/commands/update.rs")).unwrap();
5378        assert!(command.contains("pub async fn update"));
5379        assert!(command.contains("CommandContext<'_>"));
5380        fs::remove_dir_all(root).unwrap();
5381    }
5382
5383    #[test]
5384    fn model_all_registers_every_supported_business_artifact() {
5385        let root = temporary_directory("model-all");
5386        create_project(
5387            &NewProjectOptions::new(&root)
5388                .dependencies(DependencySource::Local(framework_root()))
5389                .database(Some(ProjectDatabase::Sqlite))
5390                .initialize_git(false)
5391                .install_dependencies(false),
5392        )
5393        .unwrap();
5394        let generator = ProjectGenerator::discover(&root).unwrap();
5395        generator
5396            .model(
5397                "Admin/Post",
5398                ModelOptions {
5399                    all: true,
5400                    ..ModelOptions::default()
5401                },
5402            )
5403            .unwrap();
5404        generator.model("Comment", ModelOptions::default()).unwrap();
5405
5406        assert!(root.join("app/models/admin/post.rs").is_file());
5407        assert!(
5408            root.join("app/controllers/admin/post_controller.rs")
5409                .is_file()
5410        );
5411        assert!(
5412            root.join("app/requests/admin/store_post_request.rs")
5413                .is_file()
5414        );
5415        assert!(root.join("app/resources/admin/post_resource.rs").is_file());
5416        assert!(root.join("routes/admin_posts.rs").is_file());
5417        assert!(root.join("views/pages/admin/posts/index.tsx").is_file());
5418        let routes = fs::read_to_string(root.join("routes/admin_posts.rs")).unwrap();
5419        assert!(routes.contains(".name(\"admin.posts.index\")"));
5420        assert!(routes.contains(".name(\"admin.posts.destroy\")"));
5421        assert!(routes.contains("typed(PostController::store)"));
5422        assert!(routes.contains(".action::<StorePostRequest, PostResource>()"));
5423        let controller =
5424            fs::read_to_string(root.join("app/controllers/admin/post_controller.rs")).unwrap();
5425        assert!(controller.contains("Validated(Json(input))"));
5426        assert!(controller.contains("Page::new(\"admin/posts/index\""));
5427        let page = fs::read_to_string(root.join("views/pages/admin/posts/index.tsx")).unwrap();
5428        assert!(page.contains("../../../generated/contracts.js"));
5429        let models = fs::read_to_string(root.join("app/models/mod.rs")).unwrap();
5430        assert!(models.contains("admin::Post"));
5431        assert!(models.contains("Comment"));
5432        let migrations = fs::read_to_string(root.join("database/migrations/mod.rs")).unwrap();
5433        assert!(migrations.contains("pub fn all()"));
5434        fs::remove_dir_all(root).unwrap();
5435    }
5436
5437    #[test]
5438    fn relations_and_factories_generate_a_compiling_slice() {
5439        let root = temporary_directory("relations");
5440        create_project(
5441            &NewProjectOptions::new(&root)
5442                .dependencies(DependencySource::Local(framework_root()))
5443                .database(Some(ProjectDatabase::Sqlite))
5444                .initialize_git(false)
5445                .install_dependencies(false),
5446        )
5447        .unwrap();
5448        let generator = ProjectGenerator::discover(&root).unwrap();
5449
5450        // The parent side: one line to say "a user has many posts".
5451        generator
5452            .model(
5453                "User",
5454                ModelOptions {
5455                    migration: true,
5456                    factory: true,
5457                    relations: vec![Relation {
5458                        kind: RelationKind::HasMany,
5459                        target: "Post".to_owned(),
5460                    }],
5461                    ..ModelOptions::default()
5462                },
5463            )
5464            .unwrap();
5465        // The child side: one line to say "a post belongs to a user". No
5466        // foreign key, no key mapping, no table name.
5467        generator
5468            .model(
5469                "Post",
5470                ModelOptions {
5471                    migration: true,
5472                    factory: true,
5473                    relations: vec![Relation {
5474                        kind: RelationKind::BelongsTo,
5475                        target: "User".to_owned(),
5476                    }],
5477                    ..ModelOptions::default()
5478                },
5479            )
5480            .unwrap();
5481
5482        let post = fs::read_to_string(root.join("app/models/post.rs")).unwrap();
5483        assert!(post.contains("#[model]"), "{post}");
5484        assert!(post.contains("#[belongs_to]"), "{post}");
5485        assert!(post.contains("pub user: Deferred<User>"), "{post}");
5486        assert!(
5487            !post.contains("user_id"),
5488            "the foreign key is a convention, not something to write: {post}"
5489        );
5490        assert!(
5491            !post.contains("#[key]") && !post.contains("#[table"),
5492            "neither is the key or the table name: {post}"
5493        );
5494
5495        let user = fs::read_to_string(root.join("app/models/user.rs")).unwrap();
5496        assert!(user.contains("#[has_many]"), "{user}");
5497        assert!(user.contains("pub posts: Deferred<Vec<Post>>"), "{user}");
5498
5499        // The child factory takes its parent's key; the parent factory does not.
5500        let factory = fs::read_to_string(root.join("database/seeders/post_factory.rs")).unwrap();
5501        assert!(factory.contains("|f, user_id: i64|"), "{factory}");
5502        assert!(factory.contains(".user_id(user_id)"), "{factory}");
5503        assert!(
5504            factory.contains(r#"#![cfg(feature = "factory")]"#),
5505            "a factory never reaches a release build: {factory}"
5506        );
5507        let factory = fs::read_to_string(root.join("database/seeders/user_factory.rs")).unwrap();
5508        assert!(factory.contains("|f|"), "{factory}");
5509
5510        let seeders = fs::read_to_string(root.join("database/seeders/mod.rs")).unwrap();
5511        assert!(seeders.contains("pub mod post_factory;"), "{seeders}");
5512        assert!(seeders.contains("pub mod user_factory;"), "{seeders}");
5513
5514        // The real assertion: all of it compiles, with factories on and off.
5515        let cargo = env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
5516        for features in [None, Some("factory")] {
5517            let mut command = Command::new(&cargo);
5518            command.args(["check", "--quiet"]).current_dir(&root);
5519            if let Some(features) = features {
5520                command.args(["--features", features]);
5521            }
5522            assert!(
5523                command.status().unwrap().success(),
5524                "generated project must compile with features {features:?}"
5525            );
5526        }
5527        fs::remove_dir_all(root).unwrap();
5528    }
5529
5530    #[test]
5531    fn make_auth_requires_a_database() {
5532        let root = temporary_directory("auth-no-db");
5533        create_project(
5534            &NewProjectOptions::new(&root)
5535                .dependencies(DependencySource::Local(framework_root()))
5536                .initialize_git(false)
5537                .install_dependencies(false),
5538        )
5539        .unwrap();
5540        let generator = ProjectGenerator::discover(&root).unwrap();
5541        // No driver was selected at `px new`, so the persistent User model has
5542        // nowhere to live: refuse with a clear, actionable error and write nothing.
5543        assert!(matches!(
5544            generator.auth(GenerateOptions::default()),
5545            Err(ScaffoldError::AuthRequiresDatabase)
5546        ));
5547        assert!(!root.join("routes/auth.rs").exists());
5548        assert!(!root.join("app/models/user.rs").exists());
5549        fs::remove_dir_all(root).unwrap();
5550    }
5551
5552    #[test]
5553    #[allow(clippy::too_many_lines, reason = "one assertion per generated file")]
5554    fn make_auth_generates_a_working_authentication_slice() {
5555        let root = temporary_directory("auth");
5556        create_project(
5557            &NewProjectOptions::new(&root)
5558                .dependencies(DependencySource::Local(framework_root()))
5559                .database(Some(ProjectDatabase::Sqlite))
5560                .initialize_git(false)
5561                .install_dependencies(false),
5562        )
5563        .unwrap();
5564        let generator = ProjectGenerator::discover(&root).unwrap();
5565        generator.auth(GenerateOptions::default()).unwrap();
5566
5567        for path in [
5568            "routes/auth.rs",
5569            "app/controllers/auth_controller.rs",
5570            "app/models/user.rs",
5571            "app/requests/login_input.rs",
5572            "app/requests/register_input.rs",
5573            "app/requests/password_reset_input.rs",
5574            "app/resources/auth_session_resource.rs",
5575            "app/resources/auth_message_resource.rs",
5576            "app/props/auth/auth_login_props.rs",
5577            "app/props/auth/auth_register_props.rs",
5578            "app/props/auth/auth_forgot_password_props.rs",
5579            "views/pages/auth/login.tsx",
5580            "views/pages/auth/register.tsx",
5581            "views/pages/auth/forgot-password.tsx",
5582        ] {
5583            assert!(root.join(path).is_file(), "missing {path}");
5584        }
5585
5586        // Persistent User model + migration registered like `px make:model`.
5587        let user_model = fs::read_to_string(root.join("app/models/user.rs")).unwrap();
5588        assert!(user_model.contains("#[derive(Clone, Debug, Model)]"));
5589        assert!(user_model.contains("#[unique]"));
5590        assert!(user_model.contains("pub email: String"));
5591        assert!(user_model.contains("pub password_hash: String"));
5592        assert!(user_model.contains("pub created_at: String"));
5593        let models = fs::read_to_string(root.join("app/models/mod.rs")).unwrap();
5594        assert!(models.contains("// phoenix:model: User"));
5595        assert!(models.contains("pub use user::User;"));
5596        let migrations = fs::read_to_string(root.join("database/migrations/mod.rs")).unwrap();
5597        assert!(migrations.contains("create_users_table"));
5598        // The Argon2id (`password`) and guard (`auth`) facade features are on by default.
5599        let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
5600        let default_line = cargo
5601            .lines()
5602            .find(|line| line.trim_start().starts_with("default ="))
5603            .expect("default features line");
5604        assert!(default_line.contains("\"sqlite\""));
5605        assert!(default_line.contains("\"password\""));
5606        assert!(default_line.contains("\"auth\""));
5607
5608        let routes = fs::read_to_string(root.join("routes/auth.rs")).unwrap();
5609        assert!(routes.contains(".name(\"login.show\")"));
5610        assert!(routes.contains(".name(\"login.store\")"));
5611        assert!(routes.contains(".name(\"logout.store\")"));
5612        assert!(routes.contains(".name(\"register.store\")"));
5613        assert!(routes.contains(".name(\"password-reset.store\")"));
5614        assert!(routes.contains(".action::<LoginInput, AuthSessionResource>()"));
5615        assert!(routes.contains(".action::<RegisterInput, AuthSessionResource>()"));
5616        assert!(routes.contains(".action::<PasswordResetInput, AuthMessageResource>()"));
5617        assert!(routes.contains("RateLimit::new(RateLimitConfig {"));
5618        assert!(routes.contains("phoenix-captcha"), "captcha assembly notes");
5619
5620        let controller =
5621            fs::read_to_string(root.join("app/controllers/auth_controller.rs")).unwrap();
5622        // Credentials go through Argon2id + the phoenix-auth guard, never plaintext.
5623        assert!(
5624            controller
5625                .contains("use phoenix::auth::{AuthError, AuthGuard, AuthUser, UserProvider}")
5626        );
5627        assert!(controller.contains("impl UserProvider for DatabaseUserProvider"));
5628        assert!(controller.contains("guard.attempt(&input.email, &input.password)"));
5629        assert!(controller.contains("Password::hash(&input.password)"));
5630        assert!(controller.contains("StatusCode::UNPROCESSABLE_ENTITY"));
5631        assert!(controller.contains("Validated::<Json<LoginInput>>::from_request"));
5632        assert!(controller.contains("CaptchaProtected"));
5633        assert!(!controller.contains("DemoUser"), "no in-memory demo store");
5634        assert!(
5635            !controller.contains("user.password == input.password"),
5636            "no plaintext password comparison"
5637        );
5638        let controllers = fs::read_to_string(root.join("app/controllers/mod.rs")).unwrap();
5639        assert!(controllers.contains("pub use auth_controller::AuthController;"));
5640        let requests = fs::read_to_string(root.join("app/requests/login_input.rs")).unwrap();
5641        assert!(requests.contains("#[phoenix::contract(input)]"));
5642        assert!(requests.contains("impl Validate for LoginInput"));
5643        let props = fs::read_to_string(root.join("app/props/auth/auth_login_props.rs")).unwrap();
5644        assert!(props.contains("#[phoenix::contract(page, page = \"auth/login\")]"));
5645
5646        let login_page = fs::read_to_string(root.join("views/pages/auth/login.tsx")).unwrap();
5647        assert!(login_page.contains("<Form"));
5648        assert!(login_page.contains("form.field(\"email\")"));
5649        assert!(login_page.contains("form.field(\"password\")"));
5650        assert!(login_page.contains("<FieldError errors={form.errors} name=\"password\" />"));
5651        assert!(login_page.contains("fields={LoginInputFields}"));
5652        assert!(login_page.contains("CaptchaImage"));
5653        let reset_page =
5654            fs::read_to_string(root.join("views/pages/auth/forgot-password.tsx")).unwrap();
5655        assert!(reset_page.contains("fields={PasswordResetInputFields}"));
5656        assert!(reset_page.contains("routes[\"password-reset\"]"));
5657
5658        assert!(matches!(
5659            generator.auth(GenerateOptions::default()),
5660            Err(ScaffoldError::AlreadyExists(_))
5661        ));
5662        generator.auth(GenerateOptions { force: true }).unwrap();
5663        // The forced rebuild must not stack a second users migration. Assert on
5664        // the registration itself rather than counting substrings: one
5665        // migration is named three times in the registry (marker comment,
5666        // `pub mod`, and the `all()` entry).
5667        let migrations = fs::read_to_string(root.join("database/migrations/mod.rs")).unwrap();
5668        assert_eq!(
5669            migrations.matches("pub mod m_").count(),
5670            1,
5671            "exactly one migration is registered:\n{migrations}"
5672        );
5673        let migration_files = fs::read_dir(root.join("database/migrations"))
5674            .unwrap()
5675            .filter_map(Result::ok)
5676            .filter(|entry| entry.file_name() != "mod.rs")
5677            .count();
5678        assert_eq!(migration_files, 1, "and exactly one migration file exists");
5679
5680        let cargo = env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
5681        let status = Command::new(cargo)
5682            .args(["check", "--quiet"])
5683            .current_dir(&root)
5684            .status()
5685            .unwrap();
5686        assert!(status.success());
5687        fs::remove_dir_all(root).unwrap();
5688    }
5689
5690    #[test]
5691    fn update_core_refreshes_framework_files_only() {
5692        let root = temporary_directory("update-core");
5693        create_project(
5694            &NewProjectOptions::new(&root)
5695                .dependencies(DependencySource::Local(framework_root()))
5696                .initialize_git(false)
5697                .install_dependencies(false),
5698        )
5699        .unwrap();
5700
5701        let route_before = fs::read_to_string(root.join("routes/web.rs")).unwrap();
5702        let page_before = fs::read_to_string(root.join("views/pages/home.tsx")).unwrap();
5703        fs::write(root.join("src/lib.rs"), "// stale core\n").unwrap();
5704        fs::write(
5705            root.join("routes/web.rs"),
5706            format!("{route_before}\n// business marker\n"),
5707        )
5708        .unwrap();
5709
5710        let generator = ProjectGenerator::discover(&root).unwrap();
5711        let changed = generator
5712            .update_core(
5713                &UpdateProjectOptions::new()
5714                    .dependencies(DependencySource::Local(framework_root()))
5715                    .install_dependencies(false),
5716            )
5717            .unwrap();
5718        assert!(
5719            changed.iter().any(|path| path.ends_with("src/lib.rs")),
5720            "expected src/lib.rs to be refreshed"
5721        );
5722
5723        let lib = fs::read_to_string(root.join("src/lib.rs")).unwrap();
5724        assert!(
5725            lib.contains("let vite_dev_server = std::env::var_os(\"PHOENIX_VITE_DEV\").is_some()")
5726        );
5727        assert!(!lib.contains("// stale core"));
5728        let route_after = fs::read_to_string(root.join("routes/web.rs")).unwrap();
5729        assert!(route_after.contains("// business marker"));
5730        assert_eq!(
5731            fs::read_to_string(root.join("views/pages/home.tsx")).unwrap(),
5732            page_before
5733        );
5734        let options = fs::read_to_string(root.join(".phoenix")).unwrap();
5735        assert!(options.contains("render_mode=islands"));
5736        assert!(options.contains("database=none"));
5737        fs::remove_dir_all(root).unwrap();
5738    }
5739
5740    #[test]
5741    fn generators_refuse_overwrites_and_path_traversal() {
5742        let root = temporary_directory("safety");
5743        create_project(
5744            &NewProjectOptions::new(&root)
5745                .dependencies(DependencySource::Local(framework_root()))
5746                .database(Some(ProjectDatabase::Sqlite))
5747                .initialize_git(false)
5748                .install_dependencies(false),
5749        )
5750        .unwrap();
5751        let generator = ProjectGenerator::discover(&root).unwrap();
5752        generator
5753            .controller("Report", ControllerOptions::default())
5754            .unwrap();
5755        assert!(matches!(
5756            generator.controller("Report", ControllerOptions::default()),
5757            Err(ScaffoldError::AlreadyExists(_))
5758        ));
5759        assert!(matches!(
5760            generator.page("../outside", GenerateOptions::default()),
5761            Err(ScaffoldError::InvalidName(_))
5762        ));
5763        fs::remove_dir_all(root).unwrap();
5764    }
5765}