mortise-core 1.1.0

Reads Laravel apps that use nwidart/laravel-modules. No interface.
Documentation
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
//! The public surface of a module: the one a team accepted, and a scan that proposes one.
//!
//! The surface is everything of a module that something outside it may use: classes
//! for other modules, routes for HTTP clients, console commands for the command line
//! and the scheduler. The accepted surface is the `surface` key of the module's
//! `module.json`, which the package command `module:surface` writes (P6). The scan
//! reads the files of the module and proposes a list. Neither writes anything.

use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;

use serde::{Deserialize, Serialize};

use crate::app::AppSnapshot;
use crate::modules::kind::{Kinds, TESTS};
use crate::modules::layout::Layout;
use crate::modules::module::{artisan_command, command_of, files_of, is_php};
use crate::php::{DeclaredKind, analyze};

/// The folder kind of the package's event generator.
const EVENTS: &str = "Events";

/// The accepted public surface of a module: the `surface` key of its `module.json`.
///
/// The package stores each list deduplicated and sorted by byte order. A module whose
/// `module.json` has no `surface` key has no accepted surface; one with empty lists
/// offers nothing.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AcceptedSurface {
    /// Full class names, without a leading backslash.
    #[serde(default)]
    pub classes: Vec<String>,
    /// Route URIs or patterns, as the package stores them.
    #[serde(default)]
    pub routes: Vec<String>,
    /// Console command names.
    #[serde(default)]
    pub commands: Vec<String>,
}

impl AcceptedSurface {
    /// The surface of a `module.json` document. `None` when it has no `surface` key, or
    /// when the package would refuse it: the rule then uses the folder list. The package
    /// reads an object of the lists `classes`, `routes` and `commands`, each an array of
    /// strings, and refuses an entry that `--set` would not store as it is.
    pub(crate) fn of_manifest(manifest: &serde_json::Value) -> Option<Self> {
        // Serde also reads a struct from a positional array; the package does not.
        let surface = manifest
            .get("surface")
            .filter(|surface| surface.is_object())?;
        let surface: Self = serde_json::from_value(surface.clone()).ok()?;
        let stored =
            |list: &[String], valid: fn(&str) -> bool| list.iter().all(|entry| valid(entry));
        (stored(&surface.classes, is_class_name)
            && stored(&surface.routes, |route| {
                stored_route(route).as_deref() == Some(route)
            })
            && stored(&surface.commands, is_command_name))
        .then_some(surface)
    }

    /// The surface stored in the `module.json` file at `path`. `None` when the file
    /// cannot be read, or holds no surface the package would read.
    pub fn of_file(path: &std::path::Path) -> Option<Self> {
        let text = std::fs::read(path).ok()?;
        Self::of_manifest(&serde_json::from_slice(&text).ok()?)
    }

    /// The surface as the package stores it: each list deduplicated and sorted by byte
    /// order. Classes lose a leading backslash and are the same in any case: the first
    /// spelling is kept.
    pub fn normalized(mut self) -> Self {
        let mut seen = BTreeSet::new();
        self.classes = self
            .classes
            .into_iter()
            .map(|class| class.trim_start_matches('\\').to_owned())
            .filter(|class| seen.insert(class.to_lowercase()))
            .collect();
        self.routes = self
            .routes
            .into_iter()
            .map(|route| stored_route(&route).unwrap_or(route))
            .collect();
        for list in [&mut self.classes, &mut self.routes, &mut self.commands] {
            list.sort();
            list.dedup();
        }
        self
    }

    /// The list an entry of this kind belongs to.
    fn list_of(&mut self, kind: SurfaceKind) -> &mut Vec<String> {
        match kind {
            SurfaceKind::Contract | SurfaceKind::Event | SurfaceKind::OtherClass => {
                &mut self.classes
            }
            SurfaceKind::Route => &mut self.routes,
            SurfaceKind::Command => &mut self.commands,
        }
    }

    /// How many entries the surface has.
    pub fn entries(&self) -> usize {
        self.classes.len() + self.routes.len() + self.commands.len()
    }

    /// True when the class is in the surface. PHP class names are the same in any case.
    pub fn has_class(&self, class: &str) -> bool {
        self.classes.iter().any(|listed| same_class(listed, class))
    }

    /// True when a route of the module is under a route of the surface.
    fn covers(&self, uri: &str) -> bool {
        self.routes.iter().any(|route| pattern_matches(route, uri))
    }

    /// True when the entry of a proposal is in the surface: a class in any case, a
    /// route and a command exactly.
    pub fn has(&self, entry: &SurfaceEntry) -> bool {
        match entry.kind {
            SurfaceKind::Contract | SurfaceKind::Event | SurfaceKind::OtherClass => {
                self.has_class(&entry.name)
            }
            SurfaceKind::Route => self.routes.contains(&entry.name),
            SurfaceKind::Command => self.commands.contains(&entry.name),
        }
    }

    /// The surface with the differences that are taken: a new entry added, an entry
    /// that is gone removed.
    pub fn with_differences(&self, differences: &[Difference]) -> Self {
        let mut surface = self.clone();
        for difference in differences.iter().filter(|difference| difference.taken) {
            let entry = &difference.entry;
            let list = surface.list_of(entry.kind);
            if difference.new {
                list.push(entry.name.clone());
            } else {
                // A class is the same in any case; the other lists are exact.
                let class = !matches!(entry.kind, SurfaceKind::Route | SurfaceKind::Command);
                list.retain(|listed| {
                    if class {
                        !same_class(listed, &entry.name)
                    } else {
                        listed != &entry.name
                    }
                });
            }
        }
        surface.normalized()
    }

    /// The JSON object that `module:surface <module> --set --stdin` reads.
    pub fn to_stdin(&self) -> String {
        serde_json::to_string(self).expect("a surface is plain data")
    }
}

/// The package command that stores `surface` as the accepted surface of `module`.
/// Its standard input is [`AcceptedSurface::to_stdin`].
pub fn surface_args(module: &str) -> Vec<String> {
    ["module:surface", module, "--set", "--stdin", "--json"]
        .map(str::to_owned)
        .to_vec()
}

/// What `module:surface --json` prints: the surface it stored, or why it stored nothing.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct SurfaceAnswer {
    pub module: String,
    /// The surface as stored. `None` with errors.
    #[serde(default)]
    pub surface: Option<AcceptedSurface>,
    /// False when the stored surface was the same already.
    #[serde(default)]
    pub changed: bool,
    #[serde(default)]
    pub errors: Vec<SurfaceProblem>,
}

/// One reason `module:surface` stored nothing.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct SurfaceProblem {
    pub message: String,
}

/// One difference between a later scan and the accepted surface (S5.9).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Difference {
    /// The entry of the proposal, for a new one, or the accepted entry that is gone.
    pub entry: SurfaceEntry,
    /// True when the scan proposes it and the surface lacks it. False when the surface
    /// has it and the module no longer does.
    pub new: bool,
    /// True when accepting the differences takes this one. The developer can change it.
    pub taken: bool,
}

/// What an entry of a public surface is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum SurfaceKind {
    /// An interface the module declares.
    Contract,
    /// A class in the module's events folder.
    Event,
    /// A class that another module uses and that is neither a contract nor an event.
    OtherClass,
    /// The routes of the module under one prefix.
    Route,
    /// A console command of the module.
    Command,
}

/// One thing a module offers to the outside.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SurfaceEntry {
    pub kind: SurfaceKind,
    /// The full class name, the route pattern or the command name.
    pub name: String,
    /// For a class: the kind of the folder its file is in, such as `Contracts` or `Models`.
    pub folder: String,
    /// For a class: the modules that use it today, each with how many of its files do.
    pub used_by: Vec<(String, usize)>,
    /// For a route pattern: how many routes it stands for.
    pub routes: usize,
    /// For a command: the schedule of a scheduled task that runs it, as the app wrote it.
    pub schedule: Option<String>,
    /// True when the entry is in the proposal. The developer can change it.
    pub proposed: bool,
    /// True for an entry the developer added by hand.
    pub by_hand: bool,
}

impl SurfaceEntry {
    fn new(kind: SurfaceKind, name: String) -> Self {
        Self {
            kind,
            name,
            folder: String::new(),
            used_by: Vec::new(),
            routes: 0,
            schedule: None,
            proposed: true,
            by_hand: false,
        }
    }

    /// How many files outside the module use the entry.
    pub fn used_files(&self) -> usize {
        self.used_by.iter().map(|(_, files)| files).sum()
    }
}

/// What a name typed by hand turned out to be.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Typed {
    /// A class the module declares, in this folder.
    Class { folder: String },
    /// A console command of the module.
    Command,
    /// A route pattern that stands for this many routes of the module.
    Route { routes: usize },
    /// It is in the proposal already.
    Listed,
    /// Nothing in the module has this name.
    Unknown,
}

/// What a scan found, as a list the developer can change.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Proposal {
    pub module: String,
    /// Contracts, events, other classes, routes, then commands. In each kind what is
    /// used from outside comes first.
    pub entries: Vec<SurfaceEntry>,
    /// False when no routes were given to the scan: no environment is connected.
    pub routes_read: bool,
    /// Every class the module declares outside its tests, with the kind of its folder.
    declared: BTreeMap<String, String>,
    /// The names of the module's console commands.
    commands: BTreeSet<String>,
    /// The URIs of the module's routes.
    uris: Vec<String>,
}

impl Proposal {
    /// How many entries the scan found or the developer added.
    pub fn found(&self) -> usize {
        self.entries.len()
    }

    /// How many entries are in the proposal.
    pub fn proposed(&self) -> usize {
        self.entries.iter().filter(|entry| entry.proposed).count()
    }

    /// The entries of one kind.
    pub fn of(&self, kind: SurfaceKind) -> impl Iterator<Item = (usize, &SurfaceEntry)> {
        self.entries
            .iter()
            .enumerate()
            .filter(move |(_, entry)| entry.kind == kind)
    }

    /// Says what a name typed by hand is in this module.
    pub fn check(&self, typed: &str) -> Typed {
        let typed = typed.trim().trim_start_matches('\\');
        if typed.is_empty() {
            return Typed::Unknown;
        }
        if self.entries.iter().any(|entry| entry.name == typed) {
            return Typed::Listed;
        }
        if let Some(folder) = self.declared.get(typed) {
            return Typed::Class {
                folder: folder.clone(),
            };
        }
        if self.commands.contains(typed) {
            return Typed::Command;
        }
        let routes = self
            .uris
            .iter()
            .filter(|uri| pattern_matches(typed, uri))
            .count();
        if routes > 0 {
            Typed::Route { routes }
        } else {
            Typed::Unknown
        }
    }

    /// Adds an entry by hand, when the name is something of the module. Returns
    /// false when it is not, or when it is listed already.
    pub fn add(&mut self, typed: &str) -> bool {
        let name = typed.trim().trim_start_matches('\\').to_owned();
        let mut entry = match self.check(&name) {
            Typed::Class { folder } => {
                let mut entry = SurfaceEntry::new(SurfaceKind::OtherClass, name);
                entry.folder = folder;
                entry
            }
            Typed::Command => SurfaceEntry::new(SurfaceKind::Command, name),
            Typed::Route { routes } => {
                let mut entry = SurfaceEntry::new(SurfaceKind::Route, name);
                entry.routes = routes;
                entry
            }
            Typed::Listed | Typed::Unknown => return false,
        };
        entry.by_hand = true;
        self.insert(entry);
        true
    }

    /// Puts an entry after the last entry of its kind, so that the kinds stay together.
    fn insert(&mut self, entry: SurfaceEntry) {
        let at = self
            .entries
            .iter()
            .rposition(|other| other.kind <= entry.kind)
            .map_or(0, |last| last + 1);
        self.entries.insert(at, entry);
    }

    /// Takes over what the developer chose in an earlier proposal, where the entry
    /// still exists: what was left out stays out, what was added by hand stays in.
    pub fn keep_choices_of(&mut self, earlier: &Proposal) {
        for entry in &earlier.entries {
            let same = self
                .entries
                .iter_mut()
                .find(|other| other.kind == entry.kind && other.name == entry.name);
            match same {
                Some(same) => same.proposed = entry.proposed,
                None if entry.by_hand => {
                    if self.add(&entry.name)
                        && let Some(added) = self
                            .entries
                            .iter_mut()
                            .find(|other| other.name == entry.name)
                    {
                        added.proposed = entry.proposed;
                    }
                }
                None => {}
            }
        }
    }

    /// The entries that are in the proposal, as a surface to store.
    pub fn surface(&self) -> AcceptedSurface {
        let mut surface = AcceptedSurface::default();
        for entry in self.entries.iter().filter(|entry| entry.proposed) {
            let list = surface.list_of(entry.kind);
            list.push(entry.name.clone());
        }
        surface.normalized()
    }

    /// Checks what the accepted surface has and nothing else, for a change of it (S5.8).
    /// An accepted entry that the scan did not list is added, when the module has it.
    /// An accepted route stays when the routes were not read: the scan cannot say
    /// whether the module still has it.
    pub fn take_choices_of(&mut self, accepted: &AcceptedSurface) {
        for entry in &mut self.entries {
            entry.proposed = accepted.has(entry);
        }
        let names = accepted
            .classes
            .iter()
            .chain(&accepted.routes)
            .chain(&accepted.commands);
        for name in names {
            if self.add(name)
                && let Some(added) = self.entries.iter_mut().find(|entry| &entry.name == name)
            {
                added.by_hand = false;
            }
        }
        if !self.routes_read {
            for route in &accepted.routes {
                if !self
                    .entries
                    .iter()
                    .any(|entry| entry.kind == SurfaceKind::Route && &entry.name == route)
                {
                    self.insert(SurfaceEntry::new(SurfaceKind::Route, route.clone()));
                }
            }
        }
    }

    /// What differs between this scan and the accepted surface (S5.9): what the scan
    /// proposes that the surface lacks, then what the surface has that the module no
    /// longer has. A route pattern is new only when the surface does not cover one of
    /// its routes. A route is gone only when the routes were read.
    pub fn differences(&self, accepted: &AcceptedSurface) -> Vec<Difference> {
        let lacks = |entry: &SurfaceEntry| match entry.kind {
            SurfaceKind::Route => self
                .uris
                .iter()
                .any(|uri| pattern_matches(&entry.name, uri) && !accepted.covers(uri)),
            _ => !accepted.has(entry),
        };
        let mut differences: Vec<Difference> = self
            .entries
            .iter()
            .filter(|entry| entry.proposed && lacks(entry))
            .map(|entry| Difference {
                entry: entry.clone(),
                new: true,
                taken: true,
            })
            .collect();
        let gone = |kind: SurfaceKind, name: &String| Difference {
            entry: SurfaceEntry::new(kind, name.clone()),
            new: false,
            taken: true,
        };
        for class in &accepted.classes {
            if !self
                .declared
                .keys()
                .any(|declared| same_class(declared, class))
            {
                differences.push(gone(SurfaceKind::OtherClass, class));
            }
        }
        if self.routes_read {
            for route in &accepted.routes {
                if !self.uris.iter().any(|uri| pattern_matches(route, uri)) {
                    differences.push(gone(SurfaceKind::Route, route));
                }
            }
        }
        for command in &accepted.commands {
            if !self.commands.contains(command) {
                differences.push(gone(SurfaceKind::Command, command));
            }
        }
        differences
    }

    /// The proposal as text, for a place the package does not give yet: the entries
    /// that are in it, by kind.
    pub fn as_text(&self) -> String {
        let mut text = format!("Public surface of {}, proposed by Mortise\n", self.module);
        let groups = [
            (SurfaceKind::Contract, "Contracts"),
            (SurfaceKind::Event, "Events"),
            (SurfaceKind::OtherClass, "Other classes"),
            (SurfaceKind::Route, "Routes"),
            (SurfaceKind::Command, "Console commands"),
        ];
        for (kind, title) in groups {
            let names: Vec<&str> = self
                .of(kind)
                .filter(|(_, entry)| entry.proposed)
                .map(|(_, entry)| entry.name.as_str())
                .collect();
            if names.is_empty() {
                continue;
            }
            text.push_str(&format!("\n{title}\n"));
            for name in names {
                text.push_str(&format!("  {name}\n"));
            }
        }
        text
    }
}

/// How far a scan is, for the lines of the scanning view.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ScanCounts {
    /// Classes of the module that other modules use, and in how many files.
    pub used_classes: usize,
    pub used_files: usize,
    pub contracts: usize,
    pub events: usize,
    pub commands: usize,
}

/// A class the module declares, as the scan needs it.
struct Found {
    class: String,
    interface: bool,
    /// The kind of the folder its file is in.
    folder: String,
    command: Option<String>,
}

/// A scan in progress. It reads the files of one module, a few at each step, so
/// that the interface can show how far it is and stop it.
pub struct SurfaceScan {
    module: String,
    kinds: Kinds,
    /// The module's PHP files outside its tests: the path, and the path inside the module.
    files: Vec<(PathBuf, String)>,
    next: usize,
    found: Vec<Found>,
    /// Each class of the module that another module uses, with the files that use
    /// it by the module they are in.
    used: BTreeMap<String, BTreeMap<String, BTreeSet<String>>>,
}

impl SurfaceScan {
    /// Starts a scan of one module of the app. `None` when the app has no such module.
    pub fn start(app: &AppSnapshot, module: &str) -> Option<Self> {
        let found = app.module(module)?;
        let (layout, config) = Layout::read(&app.root);
        let kinds = Kinds::new(config.as_ref(), &layout.app_folder);
        let files = files_of(&found.dir)
            .into_iter()
            .filter(|(_, relative)| is_php(relative) && kinds.of(relative) != TESTS)
            .collect();

        // Classes that other modules use: the links Mortise already has.
        let mut used: BTreeMap<String, BTreeMap<String, BTreeSet<String>>> = BTreeMap::new();
        for link in app.links.iter().filter(|link| link.to == module) {
            for reference in &link.refs {
                used.entry(reference.class.clone())
                    .or_default()
                    .entry(link.from.clone())
                    .or_default()
                    .insert(reference.file.clone());
            }
        }
        Some(Self {
            module: module.to_owned(),
            kinds,
            files,
            next: 0,
            found: Vec::new(),
            used,
        })
    }

    /// How many files the scan reads in all.
    pub fn total(&self) -> usize {
        self.files.len()
    }

    /// How many files are read.
    pub fn read(&self) -> usize {
        self.next
    }

    pub fn module(&self) -> &str {
        &self.module
    }

    /// Reads up to `files` more files. Returns true when every file is read.
    pub fn step(&mut self, files: usize) -> bool {
        let end = (self.next + files).min(self.files.len());
        for (path, relative) in &self.files[self.next..end] {
            let folder = self.kinds.of(relative);
            let analysis = analyze(&std::fs::read(path).unwrap_or_default());
            for declared in analysis.declares {
                self.found.push(Found {
                    command: command_of(&declared, &folder),
                    class: declared.class,
                    interface: declared.kind == DeclaredKind::Interface,
                    folder: folder.clone(),
                });
            }
        }
        self.next = end;
        self.next == self.files.len()
    }

    /// What was found so far.
    pub fn counts(&self) -> ScanCounts {
        let files: BTreeSet<&String> = self
            .used
            .values()
            .flat_map(|users| users.values().flatten())
            .collect();
        ScanCounts {
            used_classes: self.used.len(),
            used_files: files.len(),
            contracts: self.found.iter().filter(|found| found.interface).count(),
            events: self.found.iter().filter(|found| is_event(found)).count(),
            commands: self
                .found
                .iter()
                .filter(|found| found.command.is_some())
                .count(),
        }
    }

    /// Makes the proposal from what was read.
    ///
    /// `routes` are the URIs of the module's routes, when a running app gave them.
    /// `scheduled` are the scheduled tasks of the app: a target and its schedule.
    pub fn finish(self, routes: Option<&[String]>, scheduled: &[(String, String)]) -> Proposal {
        let users = |class: &str| -> Vec<(String, usize)> {
            let mut users: Vec<(String, usize)> = self
                .used
                .get(class)
                .map(|users| {
                    users
                        .iter()
                        .map(|(module, files)| (module.clone(), files.len()))
                        .collect()
                })
                .unwrap_or_default();
            users.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
            users
        };
        let class_entry = |kind: SurfaceKind, found: &Found| {
            let mut entry = SurfaceEntry::new(kind, found.class.clone());
            entry.folder = found.folder.clone();
            entry.used_by = users(&found.class);
            entry
        };
        // What is used from outside first, then by name.
        let sorted = |mut entries: Vec<SurfaceEntry>| {
            entries.sort_by(|a, b| {
                b.used_files()
                    .cmp(&a.used_files())
                    .then_with(|| a.name.cmp(&b.name))
            });
            entries
        };

        let contracts: Vec<SurfaceEntry> = self
            .found
            .iter()
            .filter(|found| found.interface)
            .map(|found| class_entry(SurfaceKind::Contract, found))
            .collect();
        let events: Vec<SurfaceEntry> = self
            .found
            .iter()
            .filter(|found| is_event(found))
            .map(|found| class_entry(SurfaceKind::Event, found))
            .collect();
        // A class another module uses that is neither: shown, and not proposed.
        let listed: BTreeSet<&str> = contracts
            .iter()
            .chain(&events)
            .map(|entry| entry.name.as_str())
            .collect();
        let others: Vec<SurfaceEntry> = self
            .used
            .keys()
            .filter(|class| !listed.contains(class.as_str()))
            .map(|class| {
                let mut entry = SurfaceEntry::new(SurfaceKind::OtherClass, class.clone());
                entry.folder = self
                    .found
                    .iter()
                    .find(|found| &found.class == class)
                    .map(|found| found.folder.clone())
                    .unwrap_or_default();
                entry.used_by = users(class);
                entry.proposed = false;
                entry
            })
            .collect();

        // The routes of the module, by their prefix.
        let mut patterns: BTreeMap<String, usize> = BTreeMap::new();
        for uri in routes.unwrap_or_default() {
            *patterns.entry(pattern_of(uri)).or_default() += 1;
        }
        let mut route_entries: Vec<SurfaceEntry> = patterns
            .into_iter()
            .map(|(pattern, count)| {
                let mut entry = SurfaceEntry::new(SurfaceKind::Route, pattern);
                entry.routes = count;
                entry
            })
            .collect();
        route_entries.sort_by(|a, b| b.routes.cmp(&a.routes).then_with(|| a.name.cmp(&b.name)));

        let mut commands: Vec<SurfaceEntry> = self
            .found
            .iter()
            .filter_map(|found| found.command.as_ref())
            .map(|name| {
                let mut entry = SurfaceEntry::new(SurfaceKind::Command, name.clone());
                // A scheduled task runs the command when its target is `php artisan <name>`.
                entry.schedule = scheduled
                    .iter()
                    .find(|(target, _)| artisan_command(target) == Some(name.as_str()))
                    .map(|(_, schedule)| schedule.clone());
                entry
            })
            .collect();
        commands.sort_by(|a, b| {
            b.schedule
                .is_some()
                .cmp(&a.schedule.is_some())
                .then_with(|| a.name.cmp(&b.name))
        });

        let mut entries = sorted(contracts);
        entries.extend(sorted(events));
        entries.extend(sorted(others));
        entries.extend(route_entries);
        entries.extend(commands);
        Proposal {
            module: self.module,
            entries,
            routes_read: routes.is_some(),
            declared: self
                .found
                .iter()
                .map(|found| (found.class.clone(), found.folder.clone()))
                .collect(),
            commands: self
                .found
                .iter()
                .filter_map(|found| found.command.clone())
                .collect(),
            uris: routes.unwrap_or_default().to_vec(),
        }
    }
}

/// True when two class names are the same class: PHP ignores case and a leading backslash.
fn same_class(a: &str, b: &str) -> bool {
    a.trim_start_matches('\\')
        .eq_ignore_ascii_case(b.trim_start_matches('\\'))
}

/// True for a full class name as the package stores it: parts of letters, digits and
/// `_` joined by a backslash, no part starting with a digit, no leading backslash.
fn is_class_name(class: &str) -> bool {
    class.split('\\').all(|part| {
        let mut bytes = part.bytes();
        let word = |byte: u8| byte == b'_' || byte >= 0x80 || byte.is_ascii_alphanumeric();
        bytes
            .next()
            .is_some_and(|first| word(first) && !first.is_ascii_digit())
            && bytes.all(word)
    })
}

/// True for a command name as the package stores it: parts without white space joined by `:`.
fn is_command_name(command: &str) -> bool {
    command
        .split(':')
        .all(|part| !part.is_empty() && !part.chars().any(char::is_whitespace))
}

/// A route as the package stores it: without `/` at its ends, and `/` for the root.
/// `None` for a route the package refuses: empty, or with white space.
fn stored_route(route: &str) -> Option<String> {
    if route.is_empty() || route.chars().any(char::is_whitespace) {
        return None;
    }
    let route = route.trim_matches('/');
    Some(if route.is_empty() { "/" } else { route }.to_owned())
}

fn is_event(found: &Found) -> bool {
    !found.interface && found.folder == EVENTS
}

/// The pattern a route is proposed under: its first part and everything below it,
/// or its first two parts for an API route. `api/billing/invoices/{invoice}` is
/// under `api/billing/*`.
fn pattern_of(uri: &str) -> String {
    if uri.trim_matches('/').is_empty() {
        return "/".to_owned();
    }
    let parts: Vec<&str> = uri.trim_matches('/').split('/').collect();
    let take = if parts.first() == Some(&"api") { 2 } else { 1 };
    let prefix: Vec<&str> = parts
        .iter()
        .copied()
        .take(take)
        .take_while(|part| !part.is_empty() && !part.starts_with('{'))
        .collect();
    if prefix.len() < take || prefix.is_empty() {
        // Nothing fixed to group by: the route stands for itself.
        return uri.trim_matches('/').to_owned();
    }
    format!("{}/*", prefix.join("/"))
}

/// True when a route is under a pattern: the pattern itself, or with `/*` at its
/// end, the prefix and everything below it.
fn pattern_matches(pattern: &str, uri: &str) -> bool {
    let (pattern, uri) = (pattern.trim_matches('/'), uri.trim_matches('/'));
    match pattern.strip_suffix("/*") {
        Some(prefix) => {
            uri == prefix
                || uri
                    .strip_prefix(prefix)
                    .is_some_and(|rest| rest.starts_with('/'))
        }
        None => pattern == uri,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_route_is_proposed_under_its_prefix() {
        assert_eq!(
            pattern_of("api/billing/invoices/{invoice}"),
            "api/billing/*"
        );
        assert_eq!(pattern_of("billing/invoices"), "billing/*");
        assert_eq!(pattern_of("checkout"), "checkout/*");
        assert_eq!(pattern_of("/api/billing"), "api/billing/*");
        // Nothing fixed to group by.
        assert_eq!(pattern_of("{tenant}/invoices"), "{tenant}/invoices");
        assert_eq!(
            pattern_of("api/{version}/invoices"),
            "api/{version}/invoices"
        );
        assert_eq!(pattern_of("api"), "api");
        // The root route stays the root, which the package stores as `/`.
        assert_eq!(pattern_of("/"), "/");
        assert_eq!(pattern_of(""), "/");
        assert!(pattern_matches("/", "/"));

        assert!(pattern_matches("billing/*", "billing"));
        assert!(pattern_matches("billing/*", "billing/invoices/{invoice}"));
        assert!(!pattern_matches("billing/*", "billings/list"));
        assert!(pattern_matches("checkout/confirm", "checkout/confirm"));
        assert!(!pattern_matches("checkout/confirm", "checkout/confirm/now"));
    }
}