rproj 0.20.1

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
742
743
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicUsize, Ordering};

use anyhow::{Context, Result, bail};
use serde_json::{Map, Value, json};

use crate::catalog::place_template;
use crate::config::PackageWorkflow;
use crate::steps::capture;
use crate::ui;

/// Writes `default.project.json` from scratch (rather than `rojo init` +
/// patching) with the conventional server/client/shared split, and creates
/// the matching `src/` folders. The packages folder mapped into
/// `ReplicatedStorage` depends on which package workflow this project uses:
/// Wally's `packages/` or git submodules' `modules/`.
/// Starter files, one per source folder.
///
/// These are named `hello.*`, never `init.*`: Rojo turns a directory
/// containing an `init.luau` into a *script* named after the directory, so
/// `src/shared/init.luau` would make `ReplicatedStorage.shared` a
/// ModuleScript-with-children and `src/server/init.server.luau` would make
/// it a Script, instead of the plain Folders these are meant to be.
/// (Verified from the sourcemap's `className` both ways.)
///
/// They also do the job a `.gitkeep` was previously doing - git doesn't
/// track empty directories, so without *some* file a fresh clone would be
/// missing the very paths `default.project.json` maps - while actually
/// being useful, unlike an empty placeholder.
const STARTER_FILES: &[(&str, &str)] = &[
    (
        "src/shared/hello.luau",
        "--!strict\n\nreturn {\n\tgreeting = \"hello from shared\",\n}\n",
    ),
    (
        "src/server/hello.server.luau",
        "--!strict\n\nlocal ReplicatedStorage = game:GetService(\"ReplicatedStorage\")\n\nlocal hello = require(ReplicatedStorage.shared.hello)\n\nprint(hello.greeting, \"- server\")\n",
    ),
    (
        "src/client/hello.client.luau",
        "--!strict\n\nlocal ReplicatedStorage = game:GetService(\"ReplicatedStorage\")\n\nlocal hello = require(ReplicatedStorage.shared.hello)\n\nprint(hello.greeting, \"- client\")\n",
    ),
];

pub const TEMPLATE_PROJECT_NAME: &str = "ProjectName";

const ALWAYS_CREATED_TEMPLATE_PATHS: &[&str] = &["src/shared", "src/server", "src/client"];

const RESERVED_DYNAMIC_PATHS: &[&[&str]] = &[
    &["tree", "ReplicatedStorage", "packages"],
    &["tree", "ReplicatedStorage", "modules"],
    &["tree", "ReplicatedStorage", "test"],
    &["tree", "ReplicatedStorage", "DevPackages"],
    &["tree", "ReplicatedStorage", "devPackages"],
    &["tree", "ServerScriptService", "serverPackages"],
    &["tree", "ServerScriptService", "test"],
    &["tree", "StarterPlayer", "StarterPlayerScripts", "test"],
];

pub fn scaffold_project_json(
    project_dir: &Path,
    project_name: &str,
    package_workflow: PackageWorkflow,
    testez_selected: bool,
    has_server_packages: bool,
    template: Option<&Value>,
) -> Result<()> {
    let path = project_dir.join("default.project.json");
    if path.exists() {
        ui::ok("default.project.json already exists");
        return Ok(());
    }

    for (rel_path, contents) in STARTER_FILES {
        let file = project_dir.join(rel_path);
        fs::create_dir_all(file.parent().expect("starter paths have a parent"))?;
        if !file.exists() {
            fs::write(&file, contents)?;
        }
    }

    let project = project_document(
        project_name,
        package_workflow,
        testez_selected,
        has_server_packages,
        template,
    )?;
    fs::write(&path, serde_json::to_string_pretty(&project)?)?;
    ui::ok("wrote default.project.json");
    Ok(())
}

pub fn builtin_project_template() -> Value {
    let mut tree = Map::new();
    tree.insert("$className".to_string(), json!("DataModel"));
    tree.insert(
        "ReplicatedStorage".to_string(),
        json!({ "shared": { "$path": "src/shared" } }),
    );
    tree.insert(
        "ServerScriptService".to_string(),
        json!({ "server": { "$path": "src/server" } }),
    );
    tree.insert(
        "StarterPlayer".to_string(),
        json!({
            "$className": "StarterPlayer",
            "StarterPlayerScripts": {
                "$className": "StarterPlayerScripts",
                "client": { "$path": "src/client" }
            }
        }),
    );
    for (name, node) in place_template::render() {
        tree.insert(name, node);
    }
    json!({ "name": TEMPLATE_PROJECT_NAME, "tree": tree })
}

pub fn project_document(
    project_name: &str,
    package_workflow: PackageWorkflow,
    testez_selected: bool,
    has_server_packages: bool,
    template: Option<&Value>,
) -> Result<Value> {
    let mut project = template.cloned().unwrap_or_else(builtin_project_template);
    validate_template_structure(&project)?;
    project["name"] = json!(project_name);

    apply_dynamic_mounts(
        &mut project,
        package_workflow,
        testez_selected,
        has_server_packages,
    )?;
    Ok(project)
}

pub fn ensure_project_mounts(
    project_dir: &Path,
    package_workflow: PackageWorkflow,
    testez_selected: bool,
    has_server_packages: bool,
) -> Result<()> {
    let path = project_dir.join("default.project.json");
    let mut project: Value = serde_json::from_str(&fs::read_to_string(&path)?)
        .with_context(|| format!("failed to parse {}", path.display()))?;
    let before = project.clone();
    apply_dynamic_mounts(
        &mut project,
        package_workflow,
        testez_selected,
        has_server_packages,
    )?;
    if project == before {
        ui::ok("default.project.json already has selected mounts");
    } else {
        fs::write(
            &path,
            format!("{}\n", serde_json::to_string_pretty(&project)?),
        )?;
        ui::ok("updated default.project.json mounts");
    }
    Ok(())
}

fn apply_dynamic_mounts(
    project: &mut Value,
    package_workflow: PackageWorkflow,
    testez_selected: bool,
    has_server_packages: bool,
) -> Result<()> {
    let tree = project["tree"]
        .as_object_mut()
        .context("project template `tree` must be an object")?;
    let replicated_storage = child_object_mut(tree, "ReplicatedStorage")?;
    match package_workflow {
        PackageWorkflow::Wally => {
            replicated_storage.insert("packages".into(), json!({ "$path": "Packages" }));
        }
        PackageWorkflow::GitSubmodules => {
            replicated_storage.insert("modules".into(), json!({ "$path": "modules" }));
        }
        PackageWorkflow::None => {}
    }
    if testez_selected {
        replicated_storage.insert("test".into(), json!({ "$path": "tests/shared" }));
    }

    let server_scripts = child_object_mut(tree, "ServerScriptService")?;
    if has_server_packages {
        server_scripts.insert(
            "serverPackages".into(),
            json!({ "$path": "ServerPackages" }),
        );
    }
    if testez_selected {
        server_scripts.insert("test".into(), json!({ "$path": "tests/server" }));
    }

    let starter_player = child_object_mut(tree, "StarterPlayer")?;
    starter_player.insert("$className".into(), json!("StarterPlayer"));
    let client_scripts = child_object_mut(starter_player, "StarterPlayerScripts")?;
    client_scripts.insert("$className".into(), json!("StarterPlayerScripts"));
    if testez_selected {
        client_scripts.insert("test".into(), json!({ "$path": "tests/client" }));
    }
    Ok(())
}

pub fn validate_template_structure(template: &Value) -> Result<()> {
    let object = template
        .as_object()
        .context("project template must be a JSON object")?;
    if object.get("name") != Some(&json!(TEMPLATE_PROJECT_NAME)) {
        bail!("`name` is managed by rproj and must remain `{TEMPLATE_PROJECT_NAME}`");
    }
    let tree = object
        .get("tree")
        .and_then(Value::as_object)
        .context("project template `tree` must be an object")?;
    if tree.get("$className") != Some(&json!("DataModel")) {
        bail!("`tree.$className` is managed by rproj and must remain `DataModel`");
    }

    for (path, expected) in [
        (
            &["tree", "ReplicatedStorage", "shared", "$path"][..],
            "src/shared",
        ),
        (
            &["tree", "ServerScriptService", "server", "$path"][..],
            "src/server",
        ),
        (
            &[
                "tree",
                "StarterPlayer",
                "StarterPlayerScripts",
                "client",
                "$path",
            ][..],
            "src/client",
        ),
    ] {
        if value_at(template, path) != Some(&json!(expected)) {
            bail!(
                "`{}` is managed by rproj and must remain `{expected}`",
                path.join(".")
            );
        }
    }

    for path in RESERVED_DYNAMIC_PATHS {
        if value_at(template, path).is_some() {
            bail!(
                "`{}` is reserved for dependency or testing mounts and must be removed",
                path.join(".")
            );
        }
    }
    validate_instance_names(tree, "tree")?;
    validate_paths(template, "")
}

fn validate_instance_names(node: &Map<String, Value>, location: &str) -> Result<()> {
    if node
        .get("$properties")
        .and_then(Value::as_object)
        .is_some_and(|properties| properties.contains_key("Name"))
    {
        bail!(
            "`{location}.$properties.Name` cannot be set manually; rename the `{location}` tree key instead"
        );
    }
    for (name, child) in node.iter().filter(|(name, _)| !name.starts_with('$')) {
        if let Some(child) = child.as_object() {
            validate_instance_names(child, &format!("{location}.{name}"))?;
        }
    }
    Ok(())
}

fn validate_paths(value: &Value, location: &str) -> Result<()> {
    match value {
        Value::Object(object) => {
            if let Some(path) = object.get("$path") {
                let path = match path {
                    Value::String(path) => path.as_str(),
                    Value::Object(optional) if optional.len() == 1 => optional
                        .get("optional")
                        .and_then(Value::as_str)
                        .context("optional `$path` must contain a string")?,
                    _ => bail!("`{location}.$path` must be a string or an optional path"),
                };
                if !ALWAYS_CREATED_TEMPLATE_PATHS.contains(&path) {
                    bail!(
                        "`{location}.$path` points to `{path}`; custom paths may only use the always-created `src/shared`, `src/server`, or `src/client` directories"
                    );
                }
            }
            for (key, child) in object {
                let next = if location.is_empty() {
                    key.clone()
                } else {
                    format!("{location}.{key}")
                };
                validate_paths(child, &next)?;
            }
        }
        Value::Array(values) => {
            for (index, child) in values.iter().enumerate() {
                validate_paths(child, &format!("{location}[{index}]"))?;
            }
        }
        _ => {}
    }
    Ok(())
}

fn value_at<'a>(value: &'a Value, path: &[&str]) -> Option<&'a Value> {
    path.iter().try_fold(value, |current, key| current.get(key))
}

fn child_object_mut<'a>(
    parent: &'a mut Map<String, Value>,
    key: &str,
) -> Result<&'a mut Map<String, Value>> {
    parent
        .get_mut(key)
        .and_then(Value::as_object_mut)
        .with_context(|| format!("project template `{key}` must be an object"))
}

pub fn validate_template_with_rojo(template: &Value) -> Result<()> {
    validate_template_structure(template)?;
    ensure_rojo_available()?;
    let workspace = ValidationWorkspace::new()?;
    for (label, workflow, tests, server_packages) in [
        ("plain", PackageWorkflow::None, false, false),
        ("plain-tests", PackageWorkflow::None, true, false),
        ("wally", PackageWorkflow::Wally, false, false),
        ("wally-server", PackageWorkflow::Wally, false, true),
        ("wally-tests", PackageWorkflow::Wally, true, false),
        ("wally-tests-server", PackageWorkflow::Wally, true, true),
        ("submodules", PackageWorkflow::GitSubmodules, false, false),
        (
            "submodules-tests",
            PackageWorkflow::GitSubmodules,
            true,
            false,
        ),
    ] {
        let dir = workspace.path.join(label);
        materialize_validation_project(&dir, workflow, tests, server_packages)?;
        let document = project_document(
            "TemplateValidation",
            workflow,
            tests,
            server_packages,
            Some(template),
        )?;
        let project_file = dir.join("default.project.json");
        fs::write(&project_file, serde_json::to_string_pretty(&document)?)?;
        validate_rojo_project(label, &project_file, &dir)?;
    }
    for (label, server_packages) in [("jest", false), ("jest-server", true)] {
        let dir = workspace.path.join(label);
        materialize_validation_project(&dir, PackageWorkflow::Wally, true, server_packages)?;
        materialize_validation_path(&dir, "DevPackages")?;
        let production = project_document(
            "TemplateValidation",
            PackageWorkflow::Wally,
            false,
            server_packages,
            Some(template),
        )?;
        let document = crate::steps::jest::project_document(&production)?;
        let project_file = dir.join("jest.project.json");
        fs::write(&project_file, serde_json::to_string_pretty(&document)?)?;
        validate_rojo_project(label, &project_file, &dir)?;
    }
    Ok(())
}

fn validate_rojo_project(label: &str, project_file: &Path, dir: &Path) -> Result<()> {
    let project_file = project_file.to_string_lossy().into_owned();
    for (check, command, output_file) in [
        ("sourcemap", "sourcemap", dir.join("sourcemap.json")),
        ("build", "build", dir.join("validation.rbxl")),
    ] {
        let output_file = output_file.to_string_lossy().into_owned();
        let output = capture(
            "rojo",
            &[command, project_file.as_str(), "-o", output_file.as_str()],
            None,
        )
        .context(
            "Rojo is required to validate templates; run `rokit add --global rojo` and try again",
        )?;
        if !output.success {
            bail!(
                "Rojo rejected the {label} template during {check} validation:\n{}",
                output.combined().trim()
            );
        }
    }
    Ok(())
}

fn ensure_rojo_available() -> Result<()> {
    let output = capture("rojo", &["--version"], None).context(
        "Rojo is required to validate templates; run `rokit add --global rojo` and try again",
    )?;
    if output.success {
        return Ok(());
    }
    bail!("{}", rojo_preflight_error(output.combined().trim()))
}

fn rojo_preflight_error(details: &str) -> String {
    if details.contains("Failed to find tool 'rojo'") {
        return "Rojo is not configured in this project or Rokit's global manifest. Run `rokit add --global rojo`, then save the template again.".into();
    }
    format!("Rojo could not start, so the template was not checked:\n{details}")
}

fn materialize_validation_project(
    dir: &Path,
    workflow: PackageWorkflow,
    tests: bool,
    server_packages: bool,
) -> Result<()> {
    for path in ALWAYS_CREATED_TEMPLATE_PATHS {
        materialize_validation_path(dir, path)?;
    }
    match workflow {
        PackageWorkflow::Wally => materialize_validation_path(dir, "Packages")?,
        PackageWorkflow::GitSubmodules => materialize_validation_path(dir, "modules")?,
        PackageWorkflow::None => {}
    }
    if tests {
        for path in ["tests/shared", "tests/server", "tests/client"] {
            materialize_validation_path(dir, path)?;
        }
    }
    if server_packages {
        materialize_validation_path(dir, "ServerPackages")?;
    }
    Ok(())
}

fn materialize_validation_path(dir: &Path, path: &str) -> Result<()> {
    let path = dir.join(path);
    fs::create_dir_all(&path)?;
    fs::write(path.join("template.luau"), "return nil\n")?;
    Ok(())
}

struct ValidationWorkspace {
    path: PathBuf,
}

impl ValidationWorkspace {
    fn new() -> Result<Self> {
        static COUNTER: AtomicUsize = AtomicUsize::new(0);
        let path = std::env::temp_dir().join(format!(
            "rproj-template-validation-{}-{}",
            std::process::id(),
            COUNTER.fetch_add(1, Ordering::Relaxed)
        ));
        let _ = fs::remove_dir_all(&path);
        fs::create_dir_all(&path)?;
        Ok(Self { path })
    }
}

impl Drop for ValidationWorkspace {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.path);
    }
}

/// Generates `sourcemap.json` once.
///
/// Deliberately *not* `--watch`: the scaffold only needs one sourcemap,
/// and the watch-then-kill approach it replaced was the source of two
/// bugs. It polled for the file with a 10s timeout, so any rojo failure
/// surfaced as "timed out waiting for sourcemap.json" with rojo's actual
/// explanation captured and thrown away - and on that timeout path it
/// bailed without killing the child, leaving a `rojo sourcemap --watch`
/// running forever. Running it once and reading the exit status reports
/// whatever rojo actually said, and leaves nothing behind.
pub fn generate_sourcemap(project_dir: &Path) -> Result<()> {
    generate_sourcemap_from(project_dir, "default.project.json")
}

pub fn generate_sourcemap_from(project_dir: &Path, project_file: &str) -> Result<()> {
    let output = capture(
        "rojo",
        &["sourcemap", project_file, "-o", "sourcemap.json"],
        Some(project_dir),
    )?;
    if !output.success || ui::is_verbose() {
        ui::passthrough(&output.stdout, &output.stderr);
    }
    if !output.success {
        bail!("rojo could not generate a sourcemap (see above)");
    }
    ui::ok("generated sourcemap.json");
    Ok(())
}

/// Runs `rojo sourcemap --watch` in the foreground until interrupted, for
/// `rproj watch`. Unlike the one-shot `generate_sourcemap`, this genuinely
/// wants a long-lived process, so stdio is inherited: the user is watching
/// this run and rojo's own "Created sourcemap at ..." on each rebuild is
/// the feedback that it's working.
pub fn watch_sourcemap(project_dir: &Path) -> Result<()> {
    watch_sourcemap_from(project_dir, "default.project.json")
}

pub fn watch_sourcemap_from(project_dir: &Path, project_file: &str) -> Result<()> {
    crate::interrupt::check()?;
    let args = ["sourcemap", "--watch", project_file, "-o", "sourcemap.json"];
    ui::command("rojo", &args);
    let status = Command::new("rojo")
        .args(args)
        .current_dir(project_dir)
        .status()
        .context("failed to start `rojo sourcemap --watch`")?;
    // Windows reports console interruption as STATUS_CONTROL_C_EXIT.
    crate::diagnostics::tool_exit("rojo", status);
    if !status.success()
        && !crate::interrupt::requested()
        && status.code() != Some(0xC000013Au32 as i32)
    {
        bail!("Rojo watcher failed: {status}");
    }
    Ok(())
}

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

    #[test]
    fn built_in_template_matches_the_existing_project_shape() {
        let project = project_document("MyGame", PackageWorkflow::None, false, false, None)
            .expect("render project");

        assert_eq!(project["name"], "MyGame");
        assert_eq!(project["tree"]["$className"], "DataModel");
        assert_eq!(
            project["tree"]["StarterPlayer"]["$className"],
            "StarterPlayer"
        );
        assert_eq!(
            project["tree"]["StarterPlayer"]["StarterPlayerScripts"]["$className"],
            "StarterPlayerScripts"
        );
        assert_eq!(
            project["tree"]["ReplicatedStorage"]["shared"]["$path"],
            "src/shared"
        );
        assert_eq!(
            project["tree"]["Lighting"]["$properties"]["Brightness"],
            2.5
        );
    }

    #[test]
    fn custom_nodes_and_top_level_settings_survive_generation() {
        let mut template = builtin_project_template();
        template["servePort"] = json!(40000);
        template["tree"]["Workspace"] = json!({
            "$className": "Workspace",
            "$properties": { "Gravity": 100 }
        });

        let project = project_document(
            "CustomGame",
            PackageWorkflow::Wally,
            true,
            true,
            Some(&template),
        )
        .expect("render custom project");

        assert_eq!(project["name"], "CustomGame");
        assert_eq!(project["servePort"], 40000);
        assert_eq!(project["tree"]["Workspace"]["$properties"]["Gravity"], 100);
        assert_eq!(
            project["tree"]["ReplicatedStorage"]["packages"]["$path"],
            "Packages"
        );
        assert_eq!(
            project["tree"]["ServerScriptService"]["serverPackages"]["$path"],
            "ServerPackages"
        );
        assert_eq!(
            project["tree"]["StarterPlayer"]["StarterPlayerScripts"]["test"]["$path"],
            "tests/client"
        );
    }

    #[test]
    fn changing_a_core_mount_is_rejected() {
        let mut template = builtin_project_template();
        template["tree"]["ReplicatedStorage"]["shared"]["$path"] = json!("src/other");

        let error = validate_template_structure(&template)
            .unwrap_err()
            .to_string();
        assert!(error.contains("ReplicatedStorage.shared.$path"), "{error}");
        assert!(error.contains("src/shared"), "{error}");
    }

    #[test]
    fn dependency_and_test_mount_names_are_reserved() {
        for path in RESERVED_DYNAMIC_PATHS {
            let mut template = builtin_project_template();
            let mut current = &mut template;
            for key in &path[..path.len() - 1] {
                current = current.get_mut(*key).expect("reserved parent exists");
            }
            current[path[path.len() - 1]] = json!({ "$className": "Folder" });

            let error = validate_template_structure(&template)
                .unwrap_err()
                .to_string();
            assert!(error.contains("reserved"), "{}: {error}", path.join("."));
        }
    }

    #[test]
    fn paths_outside_the_generated_tree_are_rejected() {
        let mut template = builtin_project_template();
        template["tree"]["Workspace"] = json!({ "$path": "assets/map.rbxm" });

        let error = validate_template_structure(&template)
            .unwrap_err()
            .to_string();
        assert!(error.contains("always-created"), "{error}");
    }

    #[test]
    fn conditional_paths_are_reserved_for_generated_mounts() {
        for path in [
            "Packages",
            "ServerPackages",
            "modules",
            "tests/shared",
            "tests/server",
            "tests/client",
            "DevPackages",
        ] {
            let mut template = builtin_project_template();
            template["tree"]["Workspace"] = json!({ "$path": path });

            let error = validate_template_structure(&template)
                .unwrap_err()
                .to_string();
            assert!(error.contains("always-created"), "{path}: {error}");
        }
    }

    #[test]
    fn each_dependency_workflow_gets_only_its_own_mount() {
        let wally = project_document("WallyGame", PackageWorkflow::Wally, false, false, None)
            .expect("wally project");
        let modules = project_document(
            "ModuleGame",
            PackageWorkflow::GitSubmodules,
            false,
            false,
            None,
        )
        .expect("submodule project");

        assert!(wally["tree"]["ReplicatedStorage"].get("packages").is_some());
        assert!(wally["tree"]["ReplicatedStorage"].get("modules").is_none());
        assert!(
            modules["tree"]["ReplicatedStorage"]
                .get("modules")
                .is_some()
        );
        assert!(
            modules["tree"]["ReplicatedStorage"]
                .get("packages")
                .is_none()
        );
    }

    #[test]
    #[ignore = "requires a real Rojo binary on PATH"]
    fn built_in_template_passes_every_real_rojo_validation_variant() {
        validate_template_with_rojo(&builtin_project_template())
            .expect("built-in template should pass Rojo validation");
    }

    #[test]
    #[ignore = "requires a real Rojo binary on PATH"]
    fn real_rojo_rejects_an_invalid_property_value() {
        let mut template = builtin_project_template();
        template["tree"]["Broken"] = json!({
            "$className": "Part",
            "$properties": { "Anchored": "not-a-boolean" }
        });

        let error = validate_template_with_rojo(&template)
            .unwrap_err()
            .to_string();
        assert!(error.contains("Rojo rejected"), "{error}");
    }

    #[test]
    fn missing_rokit_tool_is_not_reported_as_template_rejection() {
        let error =
            rojo_preflight_error("ERROR Failed to find tool 'rojo' in any project manifest file.");
        assert!(error.contains("rokit add --global rojo"), "{error}");
        assert!(!error.contains("Rojo rejected"), "{error}");
    }

    #[test]
    fn instance_name_property_is_rejected_before_rojo_ignores_it() {
        let mut template = builtin_project_template();
        template["tree"]["Part"] = json!({
            "$className": "Part",
            "$properties": { "Name": "IgnoredName" }
        });

        let error = validate_template_structure(&template)
            .unwrap_err()
            .to_string();
        assert!(error.contains("tree.Part.$properties.Name"), "{error}");
        assert!(error.contains("rename the `tree.Part` tree key"), "{error}");
    }
}