rproj 0.1.0

Guided bootstrap-to-game-dev CLI for Roblox: takes a fresh Windows PC to a working Roblox/Luau setup, then scaffolds projects on it
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
use std::collections::BTreeSet;

use super::Maintenance;

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Category {
    StateManagement,
    Ui,
    DataProfile,
    Testing,
    Utility,
}

impl Category {
    pub fn label(&self) -> &'static str {
        match self {
            Category::StateManagement => "State management",
            Category::Ui => "UI",
            Category::DataProfile => "Data & profiles",
            Category::Testing => "Testing",
            Category::Utility => "Utilities",
        }
    }

    pub const ALL: [Category; 5] = [
        Category::StateManagement,
        Category::Ui,
        Category::DataProfile,
        Category::Testing,
        Category::Utility,
    ];

    /// Whether more than one pick makes sense in this category. State
    /// management/UI/data-profile are architecturally exclusive choices (you
    /// don't run two UI frameworks at once), so those stay single-select;
    /// testing and utility libraries are additive toolboxes where wanting
    /// several at once (janitor + promise + greentea, say) is normal.
    pub fn allows_multiple(&self) -> bool {
        matches!(self, Category::Testing | Category::Utility)
    }
}

/// Where a package's source sits inside its cloned repo, for the
/// git-submodule workflow. Verified against each upstream repo's own
/// `default.project.json` rather than assumed - most are a plain `src` (or
/// `lib`), but monorepos like littensy/charm and littensy/ripple publish
/// several packages from one repo, so those point at a specific subpackage
/// folder instead of the repo root.
#[derive(Clone, Copy)]
pub struct Submodule {
    /// Folder name under `modules/submodules/` that this package's repo is
    /// cloned into. Packages sharing a repo share this value, so the repo
    /// is only cloned once. Chosen explicitly rather than derived from the
    /// clone URL's last segment, which would produce names like
    /// `roblox-lua-promise` and inconsistent casing (`Janitor`, `Fusion`).
    pub dir: &'static str,
    /// Path to the requirable source *within* `dir` - the folder holding
    /// the package's `init.luau` (or a single file, for one-file packages).
    pub path: &'static str,
}

/// Which wally realm a package is published under.
///
/// Not cosmetic and not rproj's choice: wally refuses to resolve a
/// server-realm package listed under `[dependencies]` at all, failing with
/// "No packages were found that matched (Shared) <pkg>. Are you sure this is
/// a Shared dependency?" - which is what every selection including
/// ProfileStore did, aborting the scaffold. Server-realm packages go in
/// `[server-dependencies]` and wally installs them into `ServerPackages/`
/// instead of `Packages/`.
///
/// Applies to the Wally workflow only. A git submodule is just a checkout;
/// nothing enforces a realm, and the whole `modules/` tree is mounted in one
/// place regardless.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Realm {
    Shared,
    Server,
}

/// Packages whose public API is a table holding both properties and
/// children, which selene's `mixed_table` lint objects to.
///
/// Vide is written `create("Frame")({ Name = "x", create("TextLabel")({}) })`:
/// properties as key/value pairs and children as array entries, in one
/// table. That is not a style choice a user can avoid, it is how every Vide
/// component is written, so with the lint at its default `warn` every UI
/// file a Vide project will ever contain fails the quality gate — and
/// selene exits 1 on warnings as well as errors (checked, not assumed).
///
/// Deliberately just Vide. Fusion's children go under a `[Children]` key,
/// which keeps the table a pure dictionary, and React takes props and
/// children as separate arguments - neither produces a mixed table.
const MIXED_TABLE_IDIOM: &[&str] = &["vide"];

/// Whether this selection's UI library forces mixed tables on the user.
pub fn allows_mixed_tables<'a>(selected: impl IntoIterator<Item = &'a String>) -> bool {
    selected.into_iter().any(|key| MIXED_TABLE_IDIOM.contains(&key.as_str()))
}

pub struct PackageSpec {
    /// Short identifier used in rproj.toml and on the CLI (e.g. `rproj info reflex`).
    pub key: &'static str,
    /// Wally dependency line value, e.g. "littensy/reflex@4.3.1".
    pub source: &'static str,
    /// The realm this package is published under. Every catalog entry is
    /// `Shared` except ProfileStore - verified by installing all 22 packages
    /// together, which succeeds only with ProfileStore under
    /// `[server-dependencies]`.
    pub realm: Realm,
    /// Git clone URL, used by the git-submodule package workflow instead of
    /// Wally. Some entries share the same repo (e.g. charm/charmSync/
    /// reactCharm/videCharm all live in littensy/charm's `packages/`
    /// directory as a monorepo) - the submodule workflow dedupes by this
    /// URL and clones it once, since Wally's per-subpackage publishing has
    /// no equivalent for a raw git checkout.
    pub git_repo: &'static str,
    /// The instance name this package is mounted under, both in
    /// `modules/submodules/` and as the generated `modules/<name>.luau`
    /// link file. Canonical upstream casing (`Charm`, `CharmSync`, `gt`),
    /// not the catalog key - this is the name written in user code, and
    /// for the monorepo packages it is load-bearing, see `submodule`.
    pub module_name: &'static str,
    /// Where this package's real Luau source lives inside its cloned repo,
    /// for the git-submodule workflow only (Wally resolves its own package
    /// layout and never looks at this). `None` means upstream only ships a
    /// working module through an npm/pnpm install step (react-lua's
    /// `require("@pkg/...")` aliases resolve through `node_modules`, which
    /// a bare git clone never populates), so it can't be vendored as a raw
    /// submodule at all - `pick_package_workflow` falls back to Wally when
    /// one of these is selected.
    pub submodule: Option<Submodule>,
    /// Catalog keys of other packages this one requires at runtime.
    ///
    /// Wally resolves transitive dependencies itself, so this exists for the
    /// git-submodule workflow, which has *no* dependency resolution at all -
    /// it clones exactly what was selected. A package whose dependency
    /// wasn't also selected is mounted but broken, and the two ways it
    /// breaks are both invisible at build time: `charm-sync` does
    /// `require("../Charm")` and gets a runtime nil, while `reflex` and
    /// `remo` look their Promise up through `script.Parent.Parent` and
    /// `error()` outright when it isn't there.
    ///
    /// Derived by cloning all 15 repos and resolving every require against
    /// the mounted layout, not from the packages' wally.toml files - three
    /// distinct require styles are in play (relative strings, instance
    /// paths, and roblox-ts's `FindFirstAncestor("rbxts_include")` fallback
    /// chain), and only the last of these is visible from a manifest.
    pub requires: &'static [&'static str],
    pub description: &'static str,
    pub maintenance: Maintenance,
    pub category: Category,
    pub docs_url: &'static str,
    /// Shown as a guided-mode choice. Companions (bridge/renderer packages
    /// that only make sense alongside a primary pick) are not offered on
    /// their own in guided mode - they ride along automatically, see
    /// `companions_for`. The expert flat checklist always shows every
    /// entry regardless of this flag.
    pub primary_choice: bool,
}

/// Packages that get pulled in automatically alongside a primary pick
/// (e.g. picking `react` also needs `react-roblox` to actually render).
/// Guided mode applies this; expert mode lists everything
/// individually so an experienced dev can opt out of a companion.
///
/// `has` reports whether a given package key is already in the selection -
/// used to pick the right UI-specific binding (e.g. `charm` pulls in
/// `reactCharm` alongside React but `videCharm` alongside Vide) instead of
/// always assuming React, which would staple a React binding onto a
/// Vide/Fusion project.
pub fn companions_for(key: &str, has: impl Fn(&str) -> bool) -> Vec<&'static str> {
    match key {
        "react" => vec!["reactRoblox"],
        "reflex" if has("react") => vec!["reactReflex"],
        "charm" => {
            let mut companions = vec!["charmSync"];
            if has("react") {
                companions.push("reactCharm");
            } else if has("vide") {
                companions.push("videCharm");
            }
            companions
        }
        "ripple" if has("react") => vec!["reactRipple"],
        "ripple" if has("vide") => vec!["videRipple"],
        _ => vec![],
    }
}

pub const PACKAGES: &[PackageSpec] = &[
    // --- UI ---
    PackageSpec {
        key: "react",
        source: "jsdotlua/react@17.2.1",
        realm: Realm::Shared,
        git_repo: "https://github.com/jsdotlua/react-lua",
        module_name: "React",
        submodule: None,
        requires: &[],
        description: "Roact-style declarative UI library, a Luau port of React",
        maintenance: Maintenance::Active,
        category: Category::Ui,
        docs_url: "https://jsdotlua.github.io/react-lua/",
        primary_choice: true,
    },
    PackageSpec {
        key: "reactRoblox",
        source: "jsdotlua/react-roblox@17.2.1",
        realm: Realm::Shared,
        git_repo: "https://github.com/jsdotlua/react-lua",
        module_name: "ReactRoblox",
        submodule: None,
        requires: &[],
        description: "React's Roblox renderer - required alongside react to mount anything",
        maintenance: Maintenance::Active,
        category: Category::Ui,
        docs_url: "https://jsdotlua.github.io/react-lua/",
        primary_choice: false,
    },
    PackageSpec {
        key: "vide",
        source: "centau/vide@0.4.1",
        realm: Realm::Shared,
        git_repo: "https://github.com/centau/vide",
        module_name: "Vide",
        submodule: Some(Submodule { dir: "vide", path: "src" }),
        requires: &[],
        description: "Lightweight reactive UI + state library built for Luau",
        maintenance: Maintenance::Active,
        category: Category::Ui,
        docs_url: "https://centau.github.io/vide/",
        primary_choice: true,
    },
    PackageSpec {
        key: "fusion",
        source: "elttob/fusion@0.3.0",
        realm: Realm::Shared,
        git_repo: "https://github.com/dphfox/Fusion",
        module_name: "Fusion",
        submodule: Some(Submodule { dir: "fusion", path: "src" }),
        requires: &[],
        description: "Reactive UI library with state management built in",
        maintenance: Maintenance::Active,
        category: Category::Ui,
        docs_url: "https://elttob.uk/Fusion/",
        primary_choice: true,
    },
    // --- State management ---
    // (ripple/remo used to be listed here too - verified against their own
    // repos and they are not state management: ripple is an animation
    // library and remo is a networking wrapper. Moved to Utilities below.)
    PackageSpec {
        key: "reflex",
        source: "littensy/reflex@4.3.1",
        realm: Realm::Shared,
        git_repo: "https://github.com/littensy/reflex",
        module_name: "Reflex",
        submodule: Some(Submodule { dir: "reflex", path: "src" }),
        requires: &["promise"],
        description: "Redux-inspired predictable state container",
        maintenance: Maintenance::Active,
        category: Category::StateManagement,
        docs_url: "https://littensy.github.io/reflex/",
        primary_choice: true,
    },
    PackageSpec {
        key: "reactReflex",
        source: "littensy/react-reflex@0.3.6",
        realm: Realm::Shared,
        git_repo: "https://github.com/littensy/react-reflex",
        module_name: "ReactReflex",
        submodule: Some(Submodule { dir: "react-reflex", path: "src" }),
        requires: &["react", "reflex"],
        description: "React bindings for Reflex",
        maintenance: Maintenance::Active,
        category: Category::StateManagement,
        docs_url: "https://littensy.github.io/reflex/",
        primary_choice: false,
    },
    PackageSpec {
        key: "charm",
        source: "littensy/charm@0.11.0",
        realm: Realm::Shared,
        git_repo: "https://github.com/littensy/charm",
        module_name: "Charm",
        submodule: Some(Submodule { dir: "charm", path: "packages/charm/src" }),
        requires: &[],
        description: "Atom-based state management, inspired by Jotai/Nanostores",
        maintenance: Maintenance::Active,
        category: Category::StateManagement,
        docs_url: "https://github.com/littensy/charm",
        primary_choice: true,
    },
    PackageSpec {
        key: "charmSync",
        source: "littensy/charm-sync@0.4.0",
        realm: Realm::Shared,
        git_repo: "https://github.com/littensy/charm",
        module_name: "CharmSync",
        submodule: Some(Submodule { dir: "charm", path: "packages/charm-sync/src" }),
        requires: &["charm"],
        description: "Client/server atom synchronization for Charm",
        maintenance: Maintenance::Active,
        category: Category::StateManagement,
        docs_url: "https://github.com/littensy/charm",
        primary_choice: false,
    },
    PackageSpec {
        key: "reactCharm",
        source: "littensy/react-charm@0.4.0",
        realm: Realm::Shared,
        git_repo: "https://github.com/littensy/charm",
        module_name: "ReactCharm",
        submodule: None,
        requires: &[],
        description: "React bindings for Charm",
        maintenance: Maintenance::Active,
        category: Category::StateManagement,
        docs_url: "https://github.com/littensy/charm",
        primary_choice: false,
    },
    PackageSpec {
        key: "videCharm",
        source: "littensy/vide-charm@0.4.0",
        realm: Realm::Shared,
        git_repo: "https://github.com/littensy/charm",
        module_name: "VideCharm",
        submodule: Some(Submodule { dir: "charm", path: "packages/vide-charm/src" }),
        requires: &["charm", "vide"],
        description: "Bridge between Vide and Charm, for using Charm atoms in Vide UI",
        maintenance: Maintenance::Active,
        category: Category::StateManagement,
        docs_url: "https://github.com/littensy/charm",
        primary_choice: false,
    },
    // --- Data & profiles ---
    PackageSpec {
        key: "lyra",
        source: "paradoxum-games/lyra@0.6.0",
        realm: Realm::Shared,
        git_repo: "https://github.com/paradoxum-games/lyra",
        module_name: "Lyra",
        submodule: Some(Submodule { dir: "lyra", path: "src" }),
        requires: &["promise", "t"],
        description: "Full game framework with a built-in player-data/profile layer",
        maintenance: Maintenance::Active,
        category: Category::DataProfile,
        docs_url: "https://paradoxum-games.github.io/lyra/",
        primary_choice: true,
    },
    PackageSpec {
        key: "profilestore",
        source: "lm-loleris/profilestore@1.0.3",
        realm: Realm::Server,
        git_repo: "https://github.com/MadStudioRoblox/ProfileStore",
        module_name: "ProfileStore",
        submodule: Some(Submodule { dir: "profilestore", path: "ProfileStore.luau" }),
        requires: &[],
        description: "DataStore session-locking wrapper - the successor to ProfileService, recommended for new projects",
        maintenance: Maintenance::Active,
        category: Category::DataProfile,
        docs_url: "https://madstudioroblox.github.io/ProfileStore/",
        primary_choice: true,
    },
    // --- Testing ---
    PackageSpec {
        key: "testez",
        source: "roblox/testez@0.4.1",
        realm: Realm::Shared,
        git_repo: "https://github.com/Roblox/testez",
        module_name: "TestEZ",
        submodule: Some(Submodule { dir: "testez", path: "src" }),
        requires: &[],
        description: "Roblox's own BDD-style unit testing framework - archived by Roblox in Sept 2024, no longer receiving updates upstream, but still the most common Wally-installable test framework in existing projects",
        maintenance: Maintenance::Legacy,
        category: Category::Testing,
        docs_url: "https://roblox.github.io/testez/",
        primary_choice: true,
    },
    // --- Utilities ---
    PackageSpec {
        key: "janitor",
        source: "howmanysmall/janitor@1.18.3",
        realm: Realm::Shared,
        git_repo: "https://github.com/howmanysmall/Janitor",
        module_name: "Janitor",
        submodule: Some(Submodule { dir: "janitor", path: "src" }),
        requires: &[],
        description: "Cleanup/connection-management utility (a faster, typed Maid)",
        maintenance: Maintenance::Active,
        category: Category::Utility,
        docs_url: "https://howmanysmall.github.io/Janitor/",
        primary_choice: true,
    },
    PackageSpec {
        key: "ripple",
        source: "littensy/ripple@0.10.2",
        realm: Realm::Shared,
        git_repo: "https://github.com/littensy/ripple",
        module_name: "Ripple",
        submodule: Some(Submodule { dir: "ripple", path: "packages/ripple/src" }),
        requires: &[],
        description: "Spring/tween-based animation library for Roblox UI, inspired by react-spring",
        maintenance: Maintenance::Active,
        category: Category::Utility,
        docs_url: "https://github.com/littensy/ripple",
        primary_choice: true,
    },
    PackageSpec {
        key: "reactRipple",
        source: "littensy/react-ripple@3.0.1",
        realm: Realm::Shared,
        git_repo: "https://github.com/littensy/ripple",
        module_name: "ReactRipple",
        submodule: None,
        requires: &[],
        description: "React bindings for Ripple's animation primitives",
        maintenance: Maintenance::Active,
        category: Category::Utility,
        docs_url: "https://github.com/littensy/ripple",
        primary_choice: false,
    },
    PackageSpec {
        key: "videRipple",
        source: "littensy/vide-ripple@0.10.2",
        realm: Realm::Shared,
        git_repo: "https://github.com/littensy/ripple",
        module_name: "VideRipple",
        submodule: Some(Submodule { dir: "ripple", path: "packages/vide-ripple/src" }),
        requires: &["ripple", "vide"],
        description: "Vide bindings for Ripple's animation primitives",
        maintenance: Maintenance::Active,
        category: Category::Utility,
        docs_url: "https://github.com/littensy/ripple",
        primary_choice: false,
    },
    PackageSpec {
        key: "remo",
        source: "littensy/remo@1.5.3",
        realm: Realm::Shared,
        git_repo: "https://github.com/littensy/remo",
        module_name: "Remo",
        submodule: Some(Submodule { dir: "remo", path: "src" }),
        requires: &["promise"],
        description: "Type-safe remote event/networking wrapper",
        maintenance: Maintenance::Active,
        category: Category::Utility,
        docs_url: "https://github.com/littensy/remo",
        primary_choice: true,
    },
    PackageSpec {
        key: "promise",
        source: "evaera/promise@4.0.0",
        realm: Realm::Shared,
        git_repo: "https://github.com/evaera/roblox-lua-promise",
        module_name: "Promise",
        submodule: Some(Submodule { dir: "promise", path: "lib" }),
        requires: &[],
        description: "Promise/A+-style async utility for Luau",
        maintenance: Maintenance::CommunityStable,
        category: Category::Utility,
        docs_url: "https://eryn.io/roblox-lua-promise/",
        primary_choice: true,
    },
    PackageSpec {
        key: "greentea",
        source: "corecii/greentea@0.4.11",
        realm: Realm::Shared,
        git_repo: "https://github.com/corecii/greentea",
        module_name: "gt",
        submodule: Some(Submodule { dir: "greentea", path: "src" }),
        requires: &[],
        description: "Runtime type-checking utility",
        maintenance: Maintenance::CommunityStable,
        category: Category::Utility,
        docs_url: "https://github.com/corecii/greentea",
        primary_choice: true,
    },
    PackageSpec {
        key: "t",
        source: "osyrisrblx/t@3.1.1",
        realm: Realm::Shared,
        git_repo: "https://github.com/osyrisrblx/t",
        module_name: "t",
        submodule: Some(Submodule { dir: "t", path: "lib" }),
        requires: &[],
        description: "Runtime type checker - validates values (e.g. RemoteEvent payloads) against type definitions",
        maintenance: Maintenance::CommunityStable,
        category: Category::Utility,
        docs_url: "https://github.com/osyrisrblx/t",
        primary_choice: true,
    },
    PackageSpec {
        key: "sift",
        source: "csqrl/sift@0.0.11",
        realm: Realm::Shared,
        git_repo: "https://github.com/csqrl/sift",
        module_name: "Sift",
        submodule: Some(Submodule { dir: "sift", path: "src" }),
        requires: &[],
        description: "Immutable data utility library for tables/arrays (Llama-style helpers) - no longer actively maintained upstream, but stable and widely used",
        maintenance: Maintenance::CommunityStable,
        category: Category::Utility,
        docs_url: "https://cxmeel.github.io/sift",
        primary_choice: true,
    },
];

impl PackageSpec {
    /// The wally author/org, parsed from `source` (e.g. "littensy" out of
    /// "littensy/reflex@4.3.1"). Used for the compact `rproj info` listing.
    pub fn author(&self) -> &'static str {
        self.source.split('/').next().unwrap_or(self.source)
    }

    /// The pinned version, parsed from `source` (e.g. "4.3.1" out of
    /// "littensy/reflex@4.3.1"). Used for the compact `rproj info` listing.
    pub fn version(&self) -> &'static str {
        self.source.rsplit('@').next().unwrap_or("")
    }

}

pub fn find(key: &str) -> Option<&'static PackageSpec> {
    PACKAGES.iter().find(|p| p.key == key)
}

pub fn in_category(category: Category) -> impl Iterator<Item = &'static PackageSpec> {
    PACKAGES.iter().filter(move |p| p.category == category)
}

/// Whether any selected package is server-realm, i.e. whether wally will
/// create a `ServerPackages/` folder.
///
/// Several unrelated things key off this - the project file's mount, the
/// retyping arguments, CI - and every one of them breaks differently if it
/// disagrees with the manifest: rojo fails on a `$path` that doesn't exist,
/// and wally-package-types fails on a directory argument that doesn't
/// exist. Deriving them all from one predicate keeps them from drifting.
pub fn has_server_realm<'a>(keys: impl IntoIterator<Item = &'a String>) -> bool {
    keys.into_iter().filter_map(|k| find(k)).any(|p| p.realm == Realm::Server)
}

/// `selected` plus everything it transitively requires.
///
/// Only meaningful for the git-submodule workflow: wally resolves
/// dependencies itself, so expanding a Wally selection would just list
/// packages in `wally.toml` that the user didn't ask for. Under submodules
/// nothing resolves anything - the scaffold clones exactly what it's given -
/// so a selection that isn't closed over `requires` produces a tree where
/// some package is mounted next to a sibling that isn't there.
///
/// Unknown keys are preserved rather than dropped; validating them is
/// `load_setup`'s job and silently discarding one here would turn a typo
/// into a quietly smaller project.
pub fn with_dependencies(selected: &BTreeSet<String>) -> BTreeSet<String> {
    let mut resolved = selected.clone();
    let mut queue: Vec<String> = selected.iter().cloned().collect();
    while let Some(key) = queue.pop() {
        let Some(spec) = find(&key) else { continue };
        for dep in spec.requires {
            if resolved.insert((*dep).to_string()) {
                queue.push((*dep).to_string());
            }
        }
    }
    resolved
}

/// Packages in the transitive closure of `selected` that can't be vendored
/// as a git submodule, paired with why: `None` when the package itself was
/// selected, `Some(dependent)` when it was pulled in by something else.
///
/// The second case is the one worth reporting separately - `reactReflex`
/// looks perfectly vendorable on its own and is only unusable because it
/// reaches for React, which upstream ships solely through an npm install.
/// Told just "react can't be vendored", someone who never picked react has
/// no way to connect that to what they did pick.
pub fn unvendorable_in_closure(selected: &BTreeSet<String>) -> Vec<(&'static str, Option<&'static str>)> {
    let mut blocked = Vec::new();
    for key in with_dependencies(selected) {
        let Some(spec) = find(&key) else { continue };
        if spec.submodule.is_some() {
            continue;
        }
        let pulled_in_by = (!selected.contains(&key))
            .then(|| {
                PACKAGES
                    .iter()
                    .find(|p| selected.contains(p.key) && p.requires.contains(&spec.key))
                    .map(|p| p.key)
            })
            .flatten();
        blocked.push((spec.key, pulled_in_by));
    }
    blocked
}

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

    /// Every Vide component is a properties-and-children table, so with
    /// the lint left on, every UI file a Vide project will ever have fails
    /// the quality gate.
    #[test]
    fn only_the_create_style_ui_library_waives_the_mixed_table_lint() {
        let vide: BTreeSet<String> = ["vide".to_string()].into_iter().collect();
        assert!(allows_mixed_tables(&vide));

        // Fusion puts children under a `[Children]` key and React takes
        // them as a separate argument; neither builds a mixed table.
        for key in ["fusion", "react", "charm", "reflex"] {
            let other: BTreeSet<String> = [key.to_string()].into_iter().collect();
            assert!(!allows_mixed_tables(&other), "{key} should keep the lint");
        }
        assert!(!allows_mixed_tables(&BTreeSet::new()));
    }

    /// A server-realm package listed under `[dependencies]` doesn't land in
    /// the wrong folder - wally refuses to resolve it and the install fails,
    /// aborting the whole scaffold. This is what happened to every selection
    /// containing ProfileStore.
    #[test]
    fn profilestore_is_the_server_realm_package() {
        let profilestore = find("profilestore").expect("profilestore is in the catalog");
        assert!(profilestore.realm == Realm::Server, "ProfileStore is published server-realm");

        // Verified by installing all 22 catalog packages together: the
        // install succeeds only with ProfileStore under
        // `[server-dependencies]` and everything else under `[dependencies]`.
        for spec in PACKAGES.iter().filter(|p| p.key != "profilestore") {
            assert!(
                spec.realm == Realm::Shared,
                "{} is marked server-realm; confirm with a real `wally install` before trusting it",
                spec.key
            );
        }
    }

    fn owned(keys: &[&str]) -> BTreeSet<String> {
        keys.iter().map(|k| (*k).to_string()).collect()
    }

    /// A `requires` entry naming a package that doesn't exist would be
    /// silently skipped by the resolver, putting the dependency back in the
    /// state this field exists to prevent.
    #[test]
    fn every_required_key_names_a_real_package() {
        for spec in PACKAGES {
            for dep in spec.requires {
                assert!(find(dep).is_some(), "{}'s requires names unknown `{dep}`", spec.key);
                assert_ne!(*dep, spec.key, "{} requires itself", spec.key);
            }
        }
    }

    /// Git submodules resolve nothing - the scaffold clones exactly what
    /// it's given - so a selection that isn't closed over `requires` mounts
    /// a package next to a sibling that isn't there. Verified against the
    /// real repos: lyra's Promise wrapper and t usage, charm-sync's
    /// `require("../Charm")`.
    #[test]
    fn dependencies_are_pulled_in_transitively() {
        assert_eq!(with_dependencies(&owned(&["lyra"])), owned(&["lyra", "promise", "t"]));
        assert_eq!(with_dependencies(&owned(&["charmSync"])), owned(&["charm", "charmSync"]));
        // ripple itself needs nothing, so the closure stops at one level.
        assert_eq!(
            with_dependencies(&owned(&["videRipple"])),
            owned(&["ripple", "vide", "videRipple"])
        );
        // Already-complete selections are left exactly as they are.
        assert_eq!(with_dependencies(&owned(&["charm"])), owned(&["charm"]));
        assert_eq!(with_dependencies(&owned(&[])), owned(&[]));
        // An unknown key is preserved, not dropped - validating it belongs
        // to load_setup, and discarding it here would silently shrink the
        // project instead of reporting the typo.
        assert_eq!(with_dependencies(&owned(&["nope"])), owned(&["nope"]));
    }

    /// `reactReflex` is vendorable itself and still unusable as a submodule,
    /// because it reaches for React, which upstream ships only through npm.
    /// Before the closure check it scaffolded happily and failed at runtime
    /// in Studio with no build error anywhere.
    #[test]
    fn unvendorable_dependencies_are_reported_with_the_package_that_needs_them() {
        let blocked = unvendorable_in_closure(&owned(&["reactReflex"]));
        assert_eq!(blocked, vec![("react", Some("reactReflex"))], "{blocked:?}");

        // Directly selected: no "required by", because nothing pulled it in.
        assert_eq!(unvendorable_in_closure(&owned(&["react"])), vec![("react", None)]);

        // A fully vendorable selection blocks nothing.
        assert!(unvendorable_in_closure(&owned(&["lyra", "charm"])).is_empty());
    }

    /// Every vendorable package must have a vendorable dependency tree, or
    /// the workflow guard has to catch it - there is no third option that
    /// produces a working submodule project.
    #[test]
    fn vendorable_packages_either_resolve_or_are_caught_by_the_guard() {
        for spec in PACKAGES.iter().filter(|p| p.submodule.is_some()) {
            let selection = owned(&[spec.key]);
            let blocked = unvendorable_in_closure(&selection);
            if blocked.is_empty() {
                // Everything it needs can be vendored; the closure must
                // actually contain those dependencies.
                for dep in spec.requires {
                    assert!(
                        with_dependencies(&selection).contains(*dep),
                        "{} requires {dep}, which the closure dropped",
                        spec.key
                    );
                }
            } else {
                // Otherwise the guard names this package as the reason.
                assert!(
                    blocked.iter().any(|(_, via)| *via == Some(spec.key)),
                    "{} is blocked but nothing explains why: {blocked:?}",
                    spec.key
                );
            }
        }
    }

    /// Several unrelated things key off this predicate (the project file's
    /// ServerPackages mount, the retyping arguments, CI), and each fails
    /// differently when it disagrees with the manifest.
    #[test]
    fn has_server_realm_tracks_the_selection() {
        let owned = |keys: &[&str]| keys.iter().map(|k| (*k).to_string()).collect::<Vec<_>>();

        assert!(has_server_realm(&owned(&["charm", "profilestore"])));
        assert!(has_server_realm(&owned(&["profilestore"])));
        assert!(!has_server_realm(&owned(&["charm", "lyra", "remo"])));
        assert!(!has_server_realm(&owned(&[])));
        // An unknown key must not panic or count as server-realm.
        assert!(!has_server_realm(&owned(&["not-a-package"])));
    }
}