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