noxid-cli 0.2.1

The Noxid compiler command line: check, build, test, adapt, and the agent surface
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
//! `noxid new` — copy a compile-tested template project into a new directory.
//!
//! Template sources are ordinary projects under `examples/templates/<name>/`,
//! embedded by `build.rs`. Nothing here holds project source in a string
//! literal: a template can only change by editing a project the examples test
//! already compiles, so `noxid new` cannot emit syntax the compiler rejects.

use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Component, Path, PathBuf};

include!(concat!(env!("OUT_DIR"), "/templates.rs"));

/// Resolve `noxid new`'s target and refuse an unsafe one.
///
/// A scaffold writes a whole project tree, so the target has to be a place the
/// person running the command can see they named. Two spellings are refused:
/// a path with a `..` component, which reads as one directory and means
/// another; and any path — relative or absolute — that lands outside the
/// current directory's subtree. Containment is checked against the canonical
/// path, so a symlinked target is judged by where it actually points.
///
/// Returns the resolved absolute target, which is also what the command
/// reports, so the line the user reads names the directory that was written.
pub(crate) fn resolve_target(target: &Path) -> Result<PathBuf, String> {
    let escapes = |reason: &str| {
        format!(
            "error[SCAFFOLD_TARGET_ESCAPES]: `noxid new {}` {reason}; a scaffold writes a whole \
             project tree, so its target must be a directory inside the one you are in. Write a \
             plain name like `noxid new my-app`, or `cd` to the parent directory first.",
            target.display()
        )
    };
    if target
        .components()
        .any(|component| matches!(component, Component::ParentDir))
    {
        return Err(escapes("names a target through `..`"));
    }
    let working = std::env::current_dir()
        .map_err(|error| format!("cannot resolve the current directory: {error}"))?;
    let canonical_working = fs::canonicalize(&working)
        .map_err(|error| format!("cannot resolve {}: {error}", working.display()))?;
    let joined = if target.is_absolute() {
        target.to_path_buf()
    } else {
        working.join(target)
    };
    // `..` is already refused, so dropping `.` is the whole of normalization.
    let mut absolute = PathBuf::new();
    for component in joined.components() {
        if !matches!(component, Component::CurDir) {
            absolute.push(component);
        }
    }
    let resolved = canonical_with_missing_tail(&absolute)?;
    if !resolved.starts_with(&canonical_working) {
        return Err(escapes(&format!(
            "resolves to {}, which is outside {}",
            resolved.display(),
            canonical_working.display()
        )));
    }
    // Containment is decided on the canonical path; the absolute form is what
    // the scaffold writes into, so `noxid new .` names the project after the
    // directory it lands in rather than after a bare dot.
    Ok(absolute)
}

/// Canonicalize the part of `path` that exists and re-append the rest, so a
/// target that has not been created yet is still judged by the real location of
/// its nearest existing ancestor rather than by its spelling.
fn canonical_with_missing_tail(path: &Path) -> Result<PathBuf, String> {
    let mut tail = Vec::new();
    let mut existing = path.to_path_buf();
    loop {
        if existing.exists() {
            let mut resolved = fs::canonicalize(&existing)
                .map_err(|error| format!("cannot resolve {}: {error}", existing.display()))?;
            for component in tail.iter().rev() {
                resolved.push(component);
            }
            return Ok(resolved);
        }
        let Some(name) = existing.file_name().map(|name| name.to_os_string()) else {
            return Ok(path.to_path_buf());
        };
        tail.push(name);
        let Some(parent) = existing.parent().map(Path::to_path_buf) else {
            return Ok(path.to_path_buf());
        };
        existing = parent;
    }
}

/// The closed set of `--template` names. `counter` is today's default until
/// 1.0; `app` is the full-stack starting shape.
pub(crate) const TEMPLATE_NAMES: [&str; 2] = ["app", "counter"];

/// Directories a scaffold target may already contain and still count as empty:
/// `noxid new .` inside a freshly cloned or `npm install`ed directory is a
/// legitimate way to start.
const IGNORED_EXISTING_ENTRIES: [&str; 2] = [".git", "node_modules"];

/// `--render` only selects the counter template's rendering; the `app`
/// template is a server project already.
fn template_directory(template: &str, render: Option<&str>) -> Result<&'static str, String> {
    match (template, render) {
        ("app", None) => Ok("app"),
        ("app", Some(_)) => Err(
            "error[SCAFFOLD_RENDER_NOT_APPLICABLE]: `--render` selects the counter template's \
             rendering and cannot be combined with `--template app`, which is already a \
             server-rendered full-stack project; drop `--render`, or use `--template counter \
             --render universal`"
                .into(),
        ),
        ("counter", None | Some("client")) => Ok("counter"),
        ("counter", Some("universal")) => Ok("counter-universal"),
        ("counter", Some(other)) => Err(format!(
            "error[SCAFFOLD_RENDER_UNKNOWN]: `--render {other}` is not a rendering mode; write \
             `--render client` for a browser-only project or `--render universal` for a \
             server-rendered one"
        )),
        (other, _) => Err(format!(
            "error[SCAFFOLD_TEMPLATE_UNKNOWN]: `--template {other}` is not a template; write \
             `--template app` for the full-stack starting shape (a typed form, one typed \
             endpoint, scoped tables, a migration, a sign-in door and session middleware that \
             refuses every unauthenticated request, three requirements with passing scenarios, \
             and a live resource) or `--template counter` for the minimal single-page project"
        )),
    }
}

/// What `noxid new` calls the project it just wrote. The counter template
/// predates `--template`, and its two rendering modes are how people have
/// always named it, so `counter` keeps reporting `client` and `universal`
/// exactly as the pre-WO-50 scaffolder did.
pub(crate) fn output_label<'a>(template: &'a str, render: Option<&'a str>) -> &'a str {
    match (template, render) {
        ("counter", None) => "client",
        ("counter", Some(render)) => render,
        (other, _) => other,
    }
}

fn source(directory: &str) -> Result<&'static TemplateSource, String> {
    TEMPLATE_SOURCES
        .iter()
        .find(|candidate| candidate.directory == directory)
        .ok_or_else(|| {
            format!(
                "error[SCAFFOLD_TEMPLATE_MISSING]: this build embeds no template \
                 `examples/templates/{directory}`; rebuild the compiler from a checkout that \
                 contains it"
            )
        })
}

/// Every scaffolded project is renamed after its directory, so two projects on
/// one machine never share an `[app] id` (which partitions live topics,
/// storage keys, and rate buckets) or a package name.
/// The `[app] id` grammar the project loader enforces: `[a-z][a-z0-9_]{0,31}`.
const APP_ID_MAX_CHARS: usize = 32;

fn project_name(root: &Path, separator: char) -> String {
    let raw = root
        .file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_default();
    let mut name = String::new();
    for character in raw.chars() {
        if character.is_ascii_alphanumeric() {
            name.push(character.to_ascii_lowercase());
        } else if !name.ends_with(separator) && !name.is_empty() {
            name.push(separator);
        }
    }
    let name = name.trim_matches(separator).to_string();
    let name = if name.is_empty() || name.starts_with(|character: char| character.is_ascii_digit())
    {
        format!("noxid{separator}{name}")
            .trim_matches(separator)
            .to_string()
    } else {
        name
    };
    // `[app] id` must match `[a-z][a-z0-9_]{0,31}`, so a long directory name
    // has to be cut here or `noxid new` writes a project the compiler refuses
    // with APP_ID_INVALID — a scaffold that does not build with zero edits.
    // The npm name is cut to the same length so both identities stay one word.
    let truncated = name
        .char_indices()
        .nth(APP_ID_MAX_CHARS)
        .map_or(name.as_str(), |(index, _)| &name[..index]);
    truncated.trim_end_matches(separator).to_string()
}

/// Rewrite the one identity field each manifest carries. Only the value
/// changes: the template's declarations are copied verbatim.
fn rename(relative: &str, contents: &str, root: &Path) -> String {
    match relative {
        "Noxid.toml" => replace_line_value(contents, "id = \"", &project_name(root, '_'), "\""),
        "package.json" => {
            replace_line_value(contents, "\"name\": \"", &project_name(root, '-'), "\"")
        }
        _ => contents.to_string(),
    }
}

fn replace_line_value(contents: &str, prefix: &str, value: &str, suffix: &str) -> String {
    let mut lines = Vec::new();
    let mut replaced = false;
    for line in contents.lines() {
        let trimmed = line.trim_start();
        if !replaced
            && trimmed.starts_with(prefix)
            && let Some(rest) = trimmed[prefix.len()..].find(suffix)
        {
            let indent = &line[..line.len() - trimmed.len()];
            let tail = &trimmed[prefix.len() + rest + suffix.len()..];
            lines.push(format!("{indent}{prefix}{value}{suffix}{tail}"));
            replaced = true;
            continue;
        }
        lines.push(line.to_string());
    }
    let mut out = lines.join("\n");
    if contents.ends_with('\n') {
        out.push('\n');
    }
    out
}

fn refuse_non_empty(root: &Path) -> Result<(), String> {
    if !root.exists() {
        return Ok(());
    }
    let entries = root
        .read_dir()
        .map_err(|error| format!("cannot read {}: {error}", root.display()))?;
    let mut existing = entries
        .filter_map(Result::ok)
        .map(|entry| entry.file_name().to_string_lossy().into_owned())
        .filter(|name| !IGNORED_EXISTING_ENTRIES.contains(&name.as_str()))
        .collect::<Vec<_>>();
    if existing.is_empty() {
        return Ok(());
    }
    existing.sort();
    existing.truncate(5);
    Err(format!(
        "error[SCAFFOLD_TARGET_NOT_EMPTY]: {} already contains {}; `noxid new` only writes into \
         an empty directory and never overwrites a file. Scaffold into a new directory instead, \
         or empty this one first.",
        root.display(),
        existing.join(", ")
    ))
}

/// The specifier a template writes when it wants the compiler-owned adapter.
/// A template that names it gets the vetted plugin files copied in beside it;
/// one that does not stays dependency-free.
const DRIZZLE_ADAPTER_SPECIFIER: &str = "plugins/drizzle-orm/adapter.js";

/// The ledger a scaffolded project carries so it can prove which vetted files
/// it holds and which package versions those files were reviewed against.
pub(crate) const PLUGIN_LEDGER: &str = ".noxid-plugins.json";

fn declares_drizzle_adapter(source: &TemplateSource) -> bool {
    source
        .files
        .iter()
        .any(|file| file.contents.contains(DRIZZLE_ADAPTER_SPECIFIER))
}

/// Parse the `version:`/`integrity:` header of a vetting record. The record is
/// the single source of truth for a pin: `noxid new` never invents a version.
fn vetted_pin(contents: &str) -> Option<(String, String)> {
    let mut version = None;
    let mut integrity = None;
    for line in contents.lines() {
        let line = line.trim();
        if version.is_none()
            && let Some(value) = line.strip_prefix("version:")
        {
            version = Some(value.trim().to_string());
        } else if integrity.is_none()
            && let Some(value) = line.strip_prefix("integrity:")
        {
            integrity = Some(value.trim().to_string());
        }
    }
    Some((version?, integrity?))
}

/// The vetted plugin files a CLI holds, with the commit they were taken from.
/// `noxid new` writes this set into a scaffold; `noxid vet --sync` restores a
/// scaffold to it. Contents are owned rather than borrowed only so the
/// debug-build staleness hook below can hand back a modified copy.
pub(crate) struct VendoredPlugins {
    pub(crate) commit: String,
    pub(crate) files: Vec<(&'static str, String)>,
}

/// What *this* compiler embeds. This is the source of truth for `--sync`: it
/// is compiled into the binary, so it resolves the same way inside a
/// scaffolded project on another machine as it does in this checkout.
pub(crate) fn embedded_plugins() -> VendoredPlugins {
    VendoredPlugins {
        commit: VENDORED_PLUGIN_COMMIT.to_string(),
        files: VENDORED_PLUGIN_FILES
            .iter()
            .map(|file| (file.path, file.contents.to_string()))
            .collect(),
    }
}

/// What `noxid new` writes. Identical to `embedded_plugins` in every shipped
/// build; see `older_cli_plugins` for the one debug-only exception.
fn scaffolded_plugins() -> VendoredPlugins {
    #[cfg(debug_assertions)]
    if let Some(older) = older_cli_plugins() {
        return older;
    }
    embedded_plugins()
}

/// Test-only: write the scaffold an *older* CLI would have written, so
/// `noxid vet --sync`'s reason for existing can be exercised end to end.
///
/// `NOXID_TEST_OLDER_VENDORED_PLUGIN=<vendored path>` appends one comment line
/// to that file and stamps an unknown source commit. The result is
/// self-consistent — the ledger hashes the modified bytes, so `noxid build`
/// accepts it — which is exactly what a project created by a previous release
/// looks like, and exactly what a byte-tamper cannot simulate.
///
/// This is compiled out of release builds. A shipped `noxid` has no way to
/// vendor bytes it does not embed.
#[cfg(debug_assertions)]
fn older_cli_plugins() -> Option<VendoredPlugins> {
    let target = std::env::var("NOXID_TEST_OLDER_VENDORED_PLUGIN").ok()?;
    let mut plugins = embedded_plugins();
    let entry = plugins
        .files
        .iter_mut()
        .find(|(path, _)| *path == target)
        .unwrap_or_else(|| {
            panic!("NOXID_TEST_OLDER_VENDORED_PLUGIN names no vendored file: {target}")
        });
    entry.1.push_str("// vendored by an older noxid\n");
    plugins.commit = "0000000000000000000000000000000000000000".to_string();
    Some(plugins)
}

/// Render `.noxid-plugins.json`: the source commit, one content hash per
/// vendored file, and the package pins those files were vetted against. Hand
/// rolled, like every other JSON this compiler writes.
pub(crate) fn plugin_ledger(plugins: &VendoredPlugins) -> Result<String, String> {
    let mut files = Vec::new();
    let mut pins = Vec::new();
    for (path, contents) in &plugins.files {
        files.push(format!(
            "    {{ \"path\": \"{path}\", \"sha256\": \"{}\" }}",
            crate::sha256::hex_digest(contents.as_bytes())
        ));
        let Some(package) = path
            .strip_prefix("plugins/")
            .and_then(|rest| rest.strip_suffix("/VETTING.md"))
        else {
            continue;
        };
        let (version, integrity) = vetted_pin(contents).ok_or_else(|| {
            format!(
                "error[PLUGIN_VETTING_RECORD_INCOMPLETE]: {path} has no version/integrity header; \
                 a scaffold cannot pin a package the record does not identify"
            )
        })?;
        pins.push(format!(
            "    {{ \"package\": \"{package}\", \"version\": \"{version}\", \"integrity\": \
             \"{integrity}\", \"record\": \"{path}\" }}"
        ));
    }
    Ok(format!(
        "{{\n  \"schemaVersion\": 1,\n  \"sourceCommit\": \"{}\",\n  \
         \"files\": [\n{}\n  ],\n  \"pins\": [\n{}\n  ]\n}}\n",
        plugins.commit,
        files.join(",\n"),
        pins.join(",\n")
    ))
}

/// Write one scaffolded file. `create_new` is the real never-overwrite
/// guarantee: the emptiness check is a courteous refusal, this is the one that
/// holds under a race or a symlinked path.
fn write_new(path: &Path, contents: &str) -> Result<(), String> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .map_err(|error| format!("cannot create {}: {error}", parent.display()))?;
    }
    let mut handle = OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(path)
        .map_err(|error| {
            format!(
                "error[SCAFFOLD_TARGET_NOT_EMPTY]: cannot create {} without overwriting it \
                 ({error}); `noxid new` never overwrites a file. Scaffold into a new directory \
                 instead.",
                path.display()
            )
        })?;
    handle
        .write_all(contents.as_bytes())
        .map_err(|error| format!("cannot write {}: {error}", path.display()))
}

pub(crate) fn scaffold_project(
    root: &Path,
    template: &str,
    render: Option<&str>,
) -> Result<(), String> {
    let directory = template_directory(template, render)?;
    let source = source(directory)?;
    refuse_non_empty(root)?;
    fs::create_dir_all(root)
        .map_err(|error| format!("cannot create {}: {error}", root.display()))?;
    // A template that imports the compiler-owned adapter carries the vetted
    // files with it, byte-identical, plus the ledger that lets `noxid build`
    // notice a drifted copy. No package manager runs: the pinned dependencies
    // in package.json and the committed lockfile are the developer's first
    // `pnpm install`.
    if declares_drizzle_adapter(source) {
        let plugins = scaffolded_plugins();
        for (path, contents) in &plugins.files {
            write_new(&root.join(path), contents)?;
        }
        write_new(&root.join(PLUGIN_LEDGER), &plugin_ledger(&plugins)?)?;
    }
    for file in source.files {
        write_new(
            &root.join(file.path),
            &rename(file.path, file.contents, root),
        )?;
    }
    // Directories the template means to be empty. They exist in the scaffold
    // because the project layout declares them (`[app] components`,
    // `middleware`), and they stay empty: the placeholder file that keeps one
    // in git is a marker for this repository, never scaffold output.
    for relative in source.directories {
        let path = root.join(relative);
        fs::create_dir_all(&path)
            .map_err(|error| format!("cannot create {}: {error}", path.display()))?;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{TEMPLATE_SOURCES, project_name, rename, template_directory};
    use std::path::Path;

    #[test]
    fn every_template_name_resolves_to_an_embedded_project() {
        for directory in ["app", "counter", "counter-universal"] {
            assert!(
                TEMPLATE_SOURCES
                    .iter()
                    .any(|source| source.directory == directory),
                "examples/templates/{directory} is not embedded"
            );
        }
    }

    #[test]
    fn render_selects_only_the_counter_template() {
        assert_eq!(template_directory("app", None).unwrap(), "app");
        assert_eq!(template_directory("counter", None).unwrap(), "counter");
        assert_eq!(
            template_directory("counter", Some("universal")).unwrap(),
            "counter-universal"
        );
        assert!(
            template_directory("app", Some("universal"))
                .unwrap_err()
                .contains("SCAFFOLD_RENDER_NOT_APPLICABLE")
        );
        assert!(
            template_directory("agent", None)
                .unwrap_err()
                .contains("SCAFFOLD_TEMPLATE_UNKNOWN")
        );
    }

    #[test]
    fn project_names_are_sanitized_from_the_directory() {
        assert_eq!(project_name(Path::new("/tmp/My App!"), '_'), "my_app");
        assert_eq!(project_name(Path::new("/tmp/My App!"), '-'), "my-app");
        assert_eq!(project_name(Path::new("/tmp/2048"), '_'), "noxid_2048");
        // `[app] id` is `[a-z][a-z0-9_]{0,31}`: a longer directory name is cut
        // to 32 characters, and a cut that lands on the separator drops it, so
        // the identity never ends in `_` or `-`.
        assert_eq!(
            project_name(Path::new("/tmp/noxid-bench-fullstack-endpoint-9rUWQN"), '_'),
            "noxid_bench_fullstack_endpoint_9"
        );
        assert_eq!(
            project_name(Path::new("/tmp/noxid-bench-fullstack-endpoint-9rUWQN"), '-'),
            "noxid-bench-fullstack-endpoint-9"
        );
        assert_eq!(
            project_name(Path::new("/tmp/abcdefghij-abcdefghij-abcdefghij"), '_'),
            "abcdefghij_abcdefghij_abcdefghij"
        );
        assert_eq!(
            project_name(Path::new("/tmp/abcdefghij-abcdefghij-abcdefghi-x"), '_'),
            "abcdefghij_abcdefghij_abcdefghi"
        );
    }

    #[test]
    fn renaming_touches_only_the_identity_field() {
        let manifest = "[app]\nid = \"noxid_app_template\"\ntitle = \"Noxid App\"\n";
        let renamed = rename("Noxid.toml", manifest, Path::new("/tmp/demo"));
        assert_eq!(renamed, "[app]\nid = \"demo\"\ntitle = \"Noxid App\"\n");
        let package = "{\n  \"name\": \"noxid-app\",\n  \"private\": true\n}\n";
        assert_eq!(
            rename("package.json", package, Path::new("/tmp/demo")),
            "{\n  \"name\": \"demo\",\n  \"private\": true\n}\n"
        );
        let untouched = "component Home {}\n";
        assert_eq!(
            rename("src/routes/+page.nox", untouched, Path::new("/tmp/demo")),
            untouched
        );
    }
}