puerto 0.22.0

Puerto — Rust full-stack DDD framework CLI. Scaffolds Clean Architecture projects with auto-wired DI, SQLx support, and zero manual wiring. Formerly puerto-framework.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use std::path::Path;

use crate::generators::types::{
    is_enum_vo, is_option_vo, is_value_object, is_vec_vo, resolve_type,
};
use crate::puerto_toml;

use crate::validation::SHARED_VO_ALLOWED_INNER_TYPES;

const VO_ALLOWED_INNER_TYPES: &[&str] = &[
    "String",
    "i64",
    "bool",
    "f64",
    "Uuid",
    "DateTime<Utc>",
    "Option<String>",
    "Option<i64>",
    "Option<bool>",
    "Option<f64>",
    "Option<DateTime<Utc>>",
    "Vec<String>",
    "Vec<i64>",
];

fn vo_inner_type_is_valid(field_type: &str) -> bool {
    if field_type.starts_with("Option<") {
        let inner = &field_type[7..field_type.len() - 1];
        return !inner.starts_with("Vec<")
            && !inner.starts_with("Option<")
            && !inner.starts_with("HashMap<");
    }
    if field_type.starts_with("Vec<") {
        let inner = &field_type[4..field_type.len() - 1];
        return !inner.starts_with("Option<")
            && !inner.starts_with("Vec<")
            && !inner.starts_with("HashMap<");
    }
    !field_type.starts_with("HashMap<")
}

pub fn run_validate(cwd: &Path) -> Result<(), Box<dyn std::error::Error>> {
    crate::commands::list::require_puerto_project(cwd)?;
    let config = puerto_toml::read(cwd)?;

    let mut errors: Vec<String> = vec![];
    let mut warnings: Vec<String> = vec![];

    if config.project.name.is_empty() {
        errors.push("proyecto.nombre is empty".into());
    }
    if let Some(transport) = &config.project.events {
        if let Err(e) = crate::validation::validate_events_transport(transport) {
            errors.push(format!("proyecto.eventos: {e}"));
        }
        // The outbox is written in the same transaction as the entity (ADR-0018 § 1).
        if !config.project.db {
            errors.push("proyecto.eventos needs proyecto.db = true: events are written to an outbox table in the entity's transaction".into());
        }
    }

    if let Some(mode) = &config.project.auth {
        if let Err(e) = crate::validation::validate_auth_mode(mode) {
            errors.push(format!("proyecto.auth: {e}"));
        }
        // Local sessions and credentials are rows (ADR-0021 § 2).
        if mode == "local" && !config.project.db {
            errors.push("proyecto.auth = \"local\" needs proyecto.db = true: sessions and credentials are database rows".into());
        }
    }

    let mut seen_entities: Vec<String> = vec![];
    for entity in &config.entity {
        if let Err(e) = crate::validation::validate_entity_name(&entity.name) {
            errors.push(format!("entity '{}': {}", entity.name, e));
        }

        if config.project.has_auth() {
            if let Err(e) = crate::validation::validate_auth_entity_name(&entity.name) {
                errors.push(format!("entity '{}': {}", entity.name, e));
            }
        } else if !entity.public.is_empty() || !entity.roles.is_empty() {
            errors.push(format!(
                "entity '{}': declares publicos or roles, but proyecto.auth is not set",
                entity.name
            ));
        }
        for e in crate::validation::validate_entity_access(entity) {
            errors.push(format!("entity '{}': {e}", entity.name));
        }
        for e in crate::validation::validate_entity_shape(entity) {
            errors.push(format!("entity '{}': {e}", entity.name));
        }
        if !config.project.has_auth() {
            for f in entity.fields.iter().filter(|f| f.private) {
                errors.push(format!(
                    "entity '{}': field '{}' is privado, but proyecto.auth is not set — with no \
                     session, nobody would ever see it",
                    entity.name, f.name
                ));
            }
        }

        if seen_entities.contains(&entity.name) {
            errors.push(format!("duplicate entity name '{}'", entity.name));
        }
        seen_entities.push(entity.name.clone());

        if entity.use_cases.is_empty() {
            warnings.push(format!(
                "entity '{}': has no use cases defined",
                entity.name
            ));
        }

        for uc in &entity.use_cases {
            if crate::validation::validate_use_case_name(uc).is_err() {
                errors.push(format!(
                    "entity '{}': use case '{}' is not valid snake_case",
                    entity.name, uc
                ));
            }
        }

        let snake = crate::generators::naming::pascal_to_snake(&entity.name);
        if !entity.events.is_empty() && !config.project.has_events() {
            errors.push(format!(
                "entity '{}': declares eventos, but proyecto.eventos is not set",
                entity.name
            ));
        }
        for (i, event) in entity.events.iter().enumerate() {
            if let Err(e) =
                crate::validation::validate_event_name(&snake, event, &entity.events[..i])
            {
                errors.push(format!("entity '{}': {e}", entity.name));
            }
        }

        let mut seen_fields: Vec<String> = vec![];
        for field in &entity.fields {
            if field.name.is_empty() {
                errors.push(format!("entity '{}': field has empty name", entity.name));
                continue;
            }

            if let Err(e) = crate::validation::validate_field_name(&field.name) {
                errors.push(format!("entity '{}': {}", entity.name, e));
            }
            if config.project.db {
                if let Err(e) = crate::validation::validate_sql_field_name(&field.name) {
                    errors.push(format!("entity '{}': {}", entity.name, e));
                }
            }

            if seen_fields.contains(&field.name) {
                errors.push(format!(
                    "entity '{}': duplicate field name '{}'",
                    entity.name, field.name
                ));
            }
            seen_fields.push(field.name.clone());

            if let Err(e) = resolve_type(&field.field_type) {
                errors.push(format!(
                    "entity '{}': field '{}' has {}",
                    entity.name, field.name, e
                ));
            }

            if field.field_type.starts_with("Option<") && field.unique {
                warnings.push(format!(
                    "entity '{}': field '{}' is Option<> and marked unique — nullable unique fields may not be intended",
                    entity.name, field.name
                ));
            }

            if is_value_object(field) {
                if let Err(e) =
                    crate::validation::validate_vo_name(field.value_object.as_deref().unwrap())
                {
                    errors.push(format!(
                        "entity '{}': field '{}': {}",
                        entity.name, field.name, e
                    ));
                }
                if is_enum_vo(field) {
                    if field.field_type != "String" {
                        errors.push(format!(
                            "entity '{}': field '{}' has enum objeto_valor but type '{}' is not String",
                            entity.name, field.name, field.field_type
                        ));
                    }
                    if field.enum_variants.is_none() {
                        errors.push(format!(
                            "entity '{}': field '{}' has enum clase_objeto_valor but no variantes",
                            entity.name, field.name
                        ));
                    }
                    if let Some(variants) = &field.enum_variants {
                        if let Err(e) = crate::validation::validate_enum_variants(variants) {
                            errors.push(format!(
                                "entity '{}': field '{}': {}",
                                entity.name, field.name, e
                            ));
                        }
                    }
                } else {
                    if !VO_ALLOWED_INNER_TYPES.contains(&field.field_type.as_str()) {
                        errors.push(format!(
                            "entity '{}': field '{}' has objeto_valor but inner type '{}' is not a allowed (allowed: {})",
                            entity.name, field.name, field.field_type, VO_ALLOWED_INNER_TYPES.join(", ")
                        ));
                    }
                    if !vo_inner_type_is_valid(&field.field_type) {
                        errors.push(format!(
                            "entity '{}': field '{}' has objeto_valor with invalid composed inner type '{}'",
                            entity.name, field.name, field.field_type
                        ));
                    }
                    if field.enum_variants.is_some() {
                        errors.push(format!(
                            "entity '{}': field '{}' has variantes but clase_objeto_valor is not 'enum'",
                            entity.name, field.name
                        ));
                    }
                }
                if field.unique && (is_option_vo(field) || is_vec_vo(field)) {
                    errors.push(format!(
                        "entity '{}': field '{}' is an Option/Vec value object and cannot be marked unique",
                        entity.name, field.name
                    ));
                }
            }
        }

        for field in entity.fields.iter().filter(|f| f.references.is_some()) {
            if let Err(e) = crate::validation::validate_field(field) {
                errors.push(format!("entity '{}': {e}", entity.name));
            }
        }
        for e in crate::validation::validate_references(&entity.name, &entity.fields, &config) {
            errors.push(format!("entity '{}': {e}", entity.name));
        }

        // One `value_objects.rs` is written per entity — two fields cannot define the same VO
        // with different inner types.
        for e in crate::validation::validate_vo_coherence(&entity.fields, &config.value_object) {
            errors.push(format!("entity '{}': {}", entity.name, e));
        }
    }

    let mut seen_shared_vo_names: Vec<String> = vec![];
    for vo_def in &config.value_object {
        if let Err(e) = crate::validation::validate_vo_name(&vo_def.name) {
            errors.push(format!("shared objeto_valor '{}': {}", vo_def.name, e));
        }
        if seen_shared_vo_names.contains(&vo_def.name) {
            errors.push(format!(
                "duplicate shared objeto_valor name '{}'",
                vo_def.name
            ));
        }
        seen_shared_vo_names.push(vo_def.name.clone());
        if !SHARED_VO_ALLOWED_INNER_TYPES.contains(&vo_def.inner_type.as_str()) {
            errors.push(format!(
                "shared objeto_valor '{}': inner type '{}' is not allowed (allowed: {})",
                vo_def.name,
                vo_def.inner_type,
                SHARED_VO_ALLOWED_INNER_TYPES.join(", ")
            ));
        }
    }

    // Consumers (ADR-0018 § 5): the worker's registry names each one and the events it handles.
    let declared = crate::generators::worker::declared_events(&config);
    let mut seen_consumers: Vec<&str> = vec![];
    for consumer in &config.consumer {
        if !config.project.has_events() {
            errors.push(format!(
                "consumer '{}': declared, but proyecto.eventos is not set",
                consumer.name
            ));
        }
        if let Err(e) = crate::validation::validate_consumer_name(&consumer.name) {
            errors.push(format!("consumer '{}': {e}", consumer.name));
        }
        if seen_consumers.contains(&consumer.name.as_str()) {
            errors.push(format!("duplicate consumer name '{}'", consumer.name));
        }
        seen_consumers.push(&consumer.name);
        if consumer.events.is_empty() {
            errors.push(format!(
                "consumer '{}': subscribes to no event",
                consumer.name
            ));
        }
        for event in &consumer.events {
            if !declared.iter().any(|d| d.event_type == *event) {
                errors.push(format!(
                    "consumer '{}': event '{event}' is not declared by any entity",
                    consumer.name
                ));
            }
        }
    }
    errors.extend(crate::generators::consistency::missing_consumer_files(
        cwd, &config,
    ));

    // Mails (ADR-0020): two modules and a template folder each; `on` is worker wiring.
    let mut seen_mails: Vec<&str> = vec![];
    for mail in &config.mail {
        if let Err(e) = crate::validation::validate_mail_name(&mail.name) {
            errors.push(format!("mail '{}': {e}", mail.name));
        }
        if seen_mails.contains(&mail.name.as_str()) {
            errors.push(format!("duplicate mail name '{}'", mail.name));
        }
        seen_mails.push(&mail.name);
        if mail.on.is_empty() {
            continue;
        }
        if !config.project.has_events() {
            errors.push(format!(
                "mail '{}': sent on events, but proyecto.eventos is not set",
                mail.name
            ));
        }
        for event in &mail.on {
            if !declared.iter().any(|d| d.event_type == *event) {
                errors.push(format!(
                    "mail '{}': event '{event}' is not declared by any entity",
                    mail.name
                ));
            }
        }
        if config
            .consumer
            .iter()
            .any(|c| c.name == format!("correo_{}", mail.name))
        {
            errors.push(format!(
                "mail '{0}': the worker runs it as the consumer 'correo_{0}', which a [[consumidor]] \
                 already uses",
                mail.name
            ));
        }
    }
    errors.extend(crate::generators::consistency::missing_mail_files(
        cwd, &config,
    ));

    // The manifest can be internally consistent and still describe code that is not there —
    // `generate bootstrap` would then emit imports for modules that do not exist.
    for line in crate::generators::consistency::drift_lines(
        &crate::generators::consistency::missing_entity_files(cwd, &config),
    ) {
        errors.push(line);
    }
    errors.extend(crate::generators::consistency::auth_drift(cwd, &config));
    for orphan in crate::generators::consistency::orphan_entity_dirs(cwd, &config) {
        warnings.push(format!(
            "'contextos/{orphan}' exists but has no [[entidad]] block — Puerto commands cannot \
             see it"
        ));
    }

    // Generated code expects the runtime of the CLI that generates it; another minor may not have
    // what it imports. A warning: the project still builds against the runtime it pins.
    if let Ok(manifest) = std::fs::read_to_string(cwd.join("Cargo.toml")) {
        warnings.extend(crate::runtime::version_warnings(
            &manifest,
            env!("CARGO_PKG_VERSION"),
        ));
    }

    if !errors.is_empty() {
        eprintln!("Validation failed:");
        for e in &errors {
            eprintln!("  ✗ {e}");
        }
        if !warnings.is_empty() {
            for w in &warnings {
                eprintln!("  ⚠ {w}");
            }
        }
        let msg = errors.join("\n  ");
        return Err(format!("{}\n  {} error(s) found", msg, errors.len()).into());
    }

    if !warnings.is_empty() {
        eprintln!("Warnings:");
        for w in &warnings {
            eprintln!("  ⚠ {w}");
        }
    }

    println!(
        "✓ puerto.toml is valid — {} entit{} validated",
        config.entity.len(),
        if config.entity.len() == 1 { "y" } else { "ies" }
    );
    Ok(())
}