Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

Project registry (docs/projects.feature PJ8): one static reading of a project's compositions, components and controllers, and lint for what isn't connected

shinyobjectz9aaf3f21e60e
diff --git a/Cargo.lock b/Cargo.lock
index eea02b57..86a6ad3b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -13704,6 +13704,7 @@ dependencies = [
name = "raea-app-workspace"
version = "0.1.0"
dependencies = [
+ "oxc",
"raea-core-brief",
"serde_json",
]
diff --git a/apps/workspace/Cargo.toml b/apps/workspace/Cargo.toml
index fe1799cf..8ac0af88 100644
--- a/apps/workspace/Cargo.toml
+++ b/apps/workspace/Cargo.toml
@@ -10,3 +10,6 @@ description = "`raea workspace`, `raea project` and `raea controller`: a workspa
# the controller schema (core/brief controller.rs): a controller file is checked and normalized against it
raea-core-brief = { path = "../../core/brief" }
serde_json = "1"
+# a project's compositions, components and controllers read from their source (registry/, docs/projects.feature PJ8):
+# the version engine/bundle parses TSX with
+oxc = { version = "=0.152.0", features = ["ast_visit"] }
diff --git a/apps/workspace/src/controllers.rs b/apps/workspace/src/controllers.rs
index 33074001..83bceeb6 100644
--- a/apps/workspace/src/controllers.rs
+++ b/apps/workspace/src/controllers.rs
@@ -55,7 +55,7 @@ fn parse(f: &Field, s: &str) -> R<serde_json::Value> {
}
/// The overrides of the project `from` is in, by path.
-fn overrides(from: &Path) -> Vec<(String, String)> {
+pub(crate) fn overrides(from: &Path) -> Vec<(String, String)> {
let Some(p) = workspace::up(from, ".raea/project") else { return vec![] };
let text = workspace::config(Some(&p.join(".raea/project")), &["--get-regexp", "^controller\\."]).unwrap_or_default();
text.lines().filter_map(|l| l.split_once(' ')).map(|(k, v)| (k.trim_start_matches("controller.").to_string(), v.to_string())).collect()
diff --git a/apps/workspace/src/doctor.rs b/apps/workspace/src/doctor.rs
index a2e14113..bea7ed47 100644
--- a/apps/workspace/src/doctor.rs
+++ b/apps/workspace/src/doctor.rs
@@ -2,6 +2,8 @@
//! files raea no longer reads, a workspace or project file missing what this version writes (or not included from the
//! repo's git config), and an agent's copy of the raea skill from another version. `raea context` runs the same checks
//! and prints CONTEXT_STALE when any finds something, so they stay cheap: file reads and git config, no engine.
+//! It also lists what in the project isn't connected to raea's project system (docs/projects.feature PJ8, registry.rs):
+//! `--fix` registers a default export and moves a stray controller to controllers/, as a commit.
use super::*;
use crate::workspace::{get, git, include, new_id, set};
@@ -19,6 +21,8 @@ enum Fix {
Include(PathBuf, PathBuf),
/// an agent's skills reinstalled from this raea
Skills(String),
+ /// a project file connected to raea's project system (PJ8)
+ Registry(crate::registry::Fix),
}
impl Finding {
@@ -97,15 +101,59 @@ pub fn findings(from: &Path, skills: &[(&str, PathBuf)], version: &str) -> Vec<F
out
}
+/// The folder a registry scan reads from here: the project, else the folder itself unless it's the workspace's root
+/// (whose projects are each scanned in their own).
+pub fn registry_dir(from: &Path) -> Option<PathBuf> {
+ if let Some(p) = up(from, ".raea/project") {
+ return Some(p);
+ }
+ let from = from.canonicalize().unwrap_or_else(|_| from.to_path_buf());
+ (up(&from, ".raea/workspace").as_deref() != Some(from.as_path())).then_some(from)
+}
+
+/// What isn't connected to raea's project system (PJ8's warnings; its notes are `raea project scan`'s), as findings.
+pub fn registry_findings(from: &Path) -> Vec<Finding> {
+ let Some(dir) = registry_dir(from) else { return vec![] };
+ let reg = crate::registry::scan(&dir);
+ reg.lint
+ .into_iter()
+ .filter(|l| l.level == crate::registry::Level::Warn)
+ .map(|l| {
+ let at = if l.file.is_empty() { reg.dir.display().to_string() } else { reg.dir.join(&l.file).display().to_string() };
+ let at = if l.line > 0 { format!("{at}:{}", l.line) } else { at };
+ Finding { says: format!("{at}: {} ({})", l.says, l.fix), fix: l.action.map_or(Fix::No, Fix::Registry) }
+ })
+ .collect()
+}
+
+/// A commit of the files a registry fix touched, in the repo that holds them, naming only them.
+fn commit_touched(paths: &[PathBuf]) {
+ let Some(first) = paths.iter().find_map(|p| p.parent().filter(|d| d.is_dir())) else { return };
+ let Ok(top) = git(first, &["rev-parse", "--show-toplevel"]) else { return };
+ let top = PathBuf::from(top);
+ let rel: Vec<String> = paths.iter().map(|p| p.strip_prefix(&top).unwrap_or(p).display().to_string()).collect();
+ let mut add = vec!["add", "-A", "--"];
+ add.extend(rel.iter().map(String::as_str));
+ let mut changed = vec!["diff", "--cached", "--quiet", "--"];
+ changed.extend(rel.iter().map(String::as_str));
+ if git(&top, &add).is_ok() && git(&top, &changed).is_err() {
+ let mut c = vec!["commit", "-q", "-m", "raea: doctor --fix connected the project's files", "--"];
+ c.extend(rel.iter().map(String::as_str));
+ let _ = git(&top, &c);
+ }
+}
+
/// `raea doctor [--fix] [DIR]`: what it found and, with --fix, what it fixed. `reinstall` puts an agent's skills back
/// (the raea CLI's `skills install`).
pub fn doctor(args: &[String], skills: &[(&str, PathBuf)], version: &str, reinstall: &dyn Fn(&str) -> R<String>) -> R<String> {
let fix = args.iter().any(|a| a == "--fix");
let from = PathBuf::from(args.iter().find(|a| !a.starts_with("--")).map(String::as_str).unwrap_or("."));
- let found = findings(&from, skills, version);
+ let mut found = findings(&from, skills, version);
+ found.extend(registry_findings(&from));
if found.is_empty() {
- return Ok("CHECKED nothing to fix: this folder's files and the agents' raea skill match this raea".into());
+ return Ok("CHECKED nothing to fix: this folder's files and the agents' raea skill match this raea, and its compositions, components and controllers are connected".into());
}
+ let mut touched = Vec::new();
let mut lines = Vec::new();
let mut fixed = 0;
for f in &found {
@@ -113,6 +161,13 @@ pub fn doctor(args: &[String], skills: &[(&str, PathBuf)], version: &str, reinst
(Fix::Set(file, k, v), true) => set(file, k, v).map(|_| true),
(Fix::Include(repo, file), true) => include(repo, file).map(|_| true),
(Fix::Skills(agent), true) => reinstall(agent).map(|_| true),
+ (Fix::Registry(r), true) => {
+ touched.extend(match r {
+ crate::registry::Fix::Register { file, .. } => vec![file.clone()],
+ crate::registry::Fix::Move { from, to } => vec![from.clone(), to.clone()],
+ });
+ crate::registry::apply(r).map(|_| true)
+ }
_ => Ok(false),
};
match done {
@@ -131,6 +186,7 @@ pub fn doctor(args: &[String], skills: &[(&str, PathBuf)], version: &str, reinst
let _ = crate::workspace::commit(&repo, &[marker], "doctor --fix");
}
}
+ commit_touched(&touched);
}
let can = found.iter().filter(|f| f.fixable()).count();
let head = if fix { format!("APPLIED {fixed} of {} fixed", found.len()) } else { format!("CHECKED {} to fix ({can} by raea doctor --fix)", found.len()) };
diff --git a/apps/workspace/src/lib.rs b/apps/workspace/src/lib.rs
index b42a1f21..3e9dbaa3 100644
--- a/apps/workspace/src/lib.rs
+++ b/apps/workspace/src/lib.rs
@@ -9,6 +9,7 @@ mod controllers;
pub mod doctor;
mod literal;
pub mod next;
+pub mod registry;
mod storage;
mod workspace;
diff --git a/apps/workspace/src/next.rs b/apps/workspace/src/next.rs
index 88edd868..a4e2471c 100644
--- a/apps/workspace/src/next.rs
+++ b/apps/workspace/src/next.rs
@@ -53,7 +53,15 @@ pub fn steps(dir: &Path, brief: &Brief, stale: usize) -> Vec<String> {
if boarded && scripts.is_empty() {
out.push("plan it: write the storyboard as NAME.script.ts beside the brief (`raea spec NAME.script.ts` checks it) and wait for the person's approval".into());
}
- let comps: Vec<PathBuf> = files(dir, ".tsx").into_iter().filter(|p| std::fs::read_to_string(p).map(|t| t.contains("registerRoot")).unwrap_or(false)).collect();
+ // the compositions as raea's project system reads them (PJ8), newest first; what isn't connected is a step before
+ let reg = crate::registry::scan(dir);
+ let loose: Vec<&crate::registry::Lint> = reg.lint.iter().filter(|l| l.level == crate::registry::Level::Warn).collect();
+ if let Some(first) = loose.first() {
+ out.push(format!("connect the project's files: {} thing(s) aren't connected, first {} (`raea project scan` lists them, `raea doctor --fix` fixes what it can)", loose.len(), first.line()));
+ }
+ let mut comps: Vec<PathBuf> = reg.compositions.iter().map(|c| reg.dir.join(&c.file)).collect();
+ comps.dedup();
+ comps.sort_by_key(|p| std::cmp::Reverse(modified(p)));
let renders = files(&dir.join("out"), ".mp4");
match (comps.first(), renders.first()) {
(None, _) => out.push("make the first item: one .tsx whose root registers a Composition (`raea guide craft` first)".into()),
diff --git a/apps/workspace/src/registry/lint.rs b/apps/workspace/src/registry/lint.rs
new file mode 100644
index 00000000..9b3e947c
--- /dev/null
+++ b/apps/workspace/src/registry/lint.rs
@@ -0,0 +1,216 @@
+//! What in a project isn't connected to raea's project system (docs/projects.feature PJ8), each with its file and line,
+//! what's wrong and the fix; `raea doctor --fix` applies the ones it can (`apply`).
+use std::collections::{BTreeMap, BTreeSet};
+use std::path::{Path, PathBuf};
+
+use serde_json::{Value, json};
+
+use super::{File, How, Prop, Registry, is_path, resolve, stem};
+
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub enum Level {
+ /// not connected: something reads it wrong or not at all
+ Warn,
+ /// said so the person knows (a size only the render knows), not wrong
+ Info,
+}
+
+/// What `--fix` does.
+#[derive(Debug, Clone)]
+pub enum Fix {
+ /// registers a default export: an import line at the top (when one is missing) and a registerRoot at the end
+ Register { file: PathBuf, import: Option<String>, root: String },
+ /// a controller moved to the workspace's (or the project's) controllers/
+ Move { from: PathBuf, to: PathBuf },
+}
+
+#[derive(Debug, Clone)]
+pub struct Lint {
+ /// relative to the scanned folder ("" for the folder itself)
+ pub file: String,
+ pub line: usize,
+ pub rule: &'static str,
+ pub level: Level,
+ pub says: String,
+ pub fix: String,
+ pub action: Option<Fix>,
+}
+
+impl Lint {
+ pub fn json(&self) -> Value {
+ json!({
+ "file": self.file, "line": self.line, "rule": self.rule,
+ "level": if self.level == Level::Warn { "warn" } else { "info" },
+ "says": self.says, "fix": self.fix, "fixable": self.action.is_some(),
+ })
+ }
+
+ /// file:line: what (the fix)
+ pub fn line(&self) -> String {
+ let at = if self.file.is_empty() { ".".to_string() } else if self.line > 0 { format!("{}:{}", self.file, self.line) } else { self.file.clone() };
+ format!("{at}: {} ({})", self.says, self.fix)
+ }
+}
+
+fn warn(file: &str, line: usize, rule: &'static str, says: String, fix: impl Into<String>) -> Lint {
+ Lint { file: file.into(), line, rule, level: Level::Warn, says, fix: fix.into(), action: None }
+}
+
+pub(super) fn lint(reg: &Registry, files: &[File], used_by: &BTreeMap<String, BTreeSet<String>>) -> Vec<Lint> {
+ let mut out = Vec::new();
+ if !reg.project && !(reg.compositions.is_empty() && reg.controllers.is_empty()) {
+ out.push(warn("", 0, "not-a-project", "this folder isn't in a raea project (no .raea/project at or above it)".into(), "raea project new NAME and move the files in, or raea workspace adopt the folder"));
+ }
+ let comp_files: BTreeSet<&str> = reg.compositions.iter().map(|c| c.file.as_str()).collect();
+ let controller_files: BTreeSet<&str> = reg.controllers.iter().map(|c| c.file.as_str()).collect();
+
+ for f in files {
+ if let Some(why) = &f.facts.broken {
+ out.push(warn(&f.rel, 1, "broken", format!("doesn't parse: {why}"), "fix the syntax: nothing reads a file that doesn't parse"));
+ continue;
+ }
+ // a .tsx that is neither a composition nor reached from one
+ if f.rel.ends_with(".tsx") && !comp_files.contains(f.rel.as_str()) && !used_by.contains_key(&f.rel) && !controller_files.contains(f.rel.as_str()) {
+ out.push(warn(&f.rel, 1, "orphan", "isn't a composition, and no composition imports it".into(), "register it (a default export or a registerRoot <Composition>), import it from a composition, or delete it"));
+ }
+ for (spec, line) in f.facts.imports.iter().filter(|(s, _)| is_path(s)) {
+ match resolve(&f.path, spec) {
+ None => out.push(warn(&f.rel, *line, "unresolved", format!("imports {spec}, which isn't there"), "fix the path, or add the file")),
+ Some(to) if !to.starts_with(&reg.dir) => out.push(warn(
+ &f.rel,
+ *line,
+ "outside",
+ format!("imports {} from outside the project", to.display()),
+ "copy it into the project (raea part add, for raea's parts), so the project renders on its own",
+ )),
+ _ => {}
+ }
+ }
+ }
+
+ // one id, two compositions (a composition's versions share theirs)
+ let mut by_id: BTreeMap<&str, BTreeSet<String>> = BTreeMap::new();
+ for c in &reg.compositions {
+ by_id.entry(c.id.as_str()).or_default().insert(stem(&c.file));
+ }
+ for c in &reg.compositions {
+ let names = &by_id[c.id.as_str()];
+ if names.len() > 1 {
+ let others: Vec<&str> = names.iter().map(String::as_str).filter(|n| *n != stem(&c.file)).collect();
+ let who = match others.as_slice() {
+ [one] => format!("{one} does"),
+ [rest @ .., last] => format!("{} and {last} do", rest.join(", ")),
+ [] => continue,
+ };
+ out.push(warn(&c.file, c.line, "duplicate-id", format!("registers \"{}\", as {who}", c.id), "give one of them its own id: `raea render --composition ID` picks by it"));
+ }
+ }
+
+ for c in &reg.compositions {
+ let f = files.iter().find(|f| f.rel == c.file).expect("a composition's file was read");
+ match c.how {
+ How::Registered => {
+ let computed: Vec<String> = [("width", &c.width), ("height", &c.height), ("fps", &c.fps), ("durationInFrames", &c.frames)]
+ .into_iter()
+ .filter_map(|(k, v)| match v {
+ Some(Prop::Computed(e)) => Some(format!("{k} = {e}")),
+ None => Some(format!("{k} missing")),
+ _ => None,
+ })
+ .collect();
+ if !computed.is_empty() {
+ out.push(Lint { file: c.file.clone(), line: c.line, rule: "computed", level: Level::Info, says: format!("<Composition id=\"{}\">: {}", c.id, computed.join(", ")), fix: "known when it renders; write them out to have them listed before".into(), action: None });
+ }
+ }
+ How::Default => {
+ let known = [&c.width, &c.height, &c.fps, &c.frames].iter().all(|v| matches!(v, Some(Prop::Num(_))));
+ let action = match (&c.component, known) {
+ (Some(name), true) => {
+ let n = |v: &Option<Prop>| match v {
+ Some(Prop::Num(n)) => *n,
+ _ => 0.0,
+ };
+ let missing: Vec<&str> = ["Composition", "registerRoot"].into_iter().filter(|x| !f.facts.raea_names.iter().any(|h| h == x)).collect();
+ Some(Fix::Register {
+ file: f.path.clone(),
+ import: (!missing.is_empty()).then(|| format!("import {{ {} }} from \"raea\";\n", missing.join(", "))),
+ root: format!("\nregisterRoot(() => <Composition id=\"{}\" component={{{name}}} width={{{}}} height={{{}}} fps={{{}}} durationInFrames={{{}}} />);\n", c.id, n(&c.width), n(&c.height), n(&c.fps), n(&c.frames)),
+ })
+ }
+ _ => None,
+ };
+ let fix = match (&c.component, known) {
+ (Some(_), true) => "raea doctor --fix registers it with its last render's size, fps and length".to_string(),
+ (None, _) => "name the default export (export default function Name) and register it: registerRoot(() => <Composition id component width height fps durationInFrames />)".to_string(),
+ (Some(_), false) => "render it once (raea render), then raea doctor --fix registers it with that size, fps and length; or write its registerRoot".to_string(),
+ };
+ out.push(Lint { file: c.file.clone(), line: 1, rule: "unregistered", level: Level::Info, says: format!("registered from its default export as \"{}\": raea renders it at 1080x1920, 30 fps unless told", c.id), fix, action });
+ }
+ }
+ }
+
+ // controllers: where they're kept, one id each, and every override naming one that's there
+ let ws = crate::up(&reg.dir, ".raea/workspace");
+ let home = ws.clone().unwrap_or_else(|| reg.dir.clone()).join("controllers");
+ let mut ids: BTreeMap<String, Vec<&str>> = BTreeMap::new();
+ for c in &reg.controllers {
+ let f = files.iter().find(|f| f.rel == c.file).expect("a controller's file was read");
+ if let Some(id) = &c.id {
+ ids.entry(id.clone()).or_default().push(&c.file);
+ }
+ let in_home = f.path.parent().and_then(Path::file_name).is_some_and(|n| n == "controllers");
+ if !in_home {
+ let id = c.id.clone().unwrap_or_else(|| stem(&c.file));
+ let to = home.join(format!("{id}.ts"));
+ out.push(Lint {
+ file: c.file.clone(),
+ line: c.line,
+ rule: "controller-home",
+ level: Level::Warn,
+ says: "a controller outside controllers/: `raea controller` and the app don't read it".into(),
+ fix: format!("move it to {}", to.display()),
+ action: (!to.exists()).then(|| Fix::Move { from: f.path.clone(), to }),
+ });
+ }
+ }
+ for (id, at) in ids.iter().filter(|(_, at)| at.len() > 1) {
+ for f in at {
+ out.push(warn(f, 1, "controller-duplicate", format!("controller \"{id}\" is declared in {} files", at.len()), "keep one: the others' fields override nothing"));
+ }
+ }
+ // the workspace's controllers too, read the same way, for overrides naming them
+ let mut known: BTreeSet<String> = ids.keys().cloned().collect();
+ for e in std::fs::read_dir(&home).into_iter().flatten().flatten() {
+ let src = std::fs::read_to_string(e.path()).unwrap_or_default();
+ if let Some(id) = super::read::read(&src, false).controller.and_then(|c| c.id) {
+ known.insert(id);
+ }
+ }
+ let mut named = BTreeSet::new();
+ for (path, _) in crate::controllers::overrides(&reg.dir) {
+ let id = path.split('.').next().unwrap_or_default().to_string();
+ if !known.contains(&id) && named.insert(id.clone()) {
+ out.push(warn(".raea/project", 0, "override-missing", format!("overrides controller \"{id}\", which isn't there"), format!("raea controller ls lists the ones there; remove the override with git config --file .raea/project --remove-section controller.{id}")));
+ }
+ }
+ out
+}
+
+/// Applies a fix; what it did, for doctor's output.
+pub fn apply(fix: &Fix) -> Result<String, String> {
+ match fix {
+ Fix::Register { file, import, root } => {
+ let src = std::fs::read_to_string(file).map_err(|e| format!("{}: {e}", file.display()))?;
+ let text = format!("{}{}{root}", import.clone().unwrap_or_default(), src.trim_end_matches('\n'));
+ std::fs::write(file, text).map_err(|e| format!("{}: {e}", file.display()))?;
+ Ok(format!("registered {}", file.display()))
+ }
+ Fix::Move { from, to } => {
+ if let Some(d) = to.parent() {
+ std::fs::create_dir_all(d).map_err(|e| e.to_string())?;
+ }
+ std::fs::rename(from, to).map_err(|e| format!("{}: {e}", from.display()))?;
+ Ok(format!("moved {} to {}", from.display(), to.display()))
+ }
+ }
+}
diff --git a/apps/workspace/src/registry/mod.rs b/apps/workspace/src/registry/mod.rs
new file mode 100644
index 00000000..8d2af759
--- /dev/null
+++ b/apps/workspace/src/registry/mod.rs
@@ -0,0 +1,279 @@
+//! A project's compositions, components and controllers, registered by reading its files (docs/projects.feature PJ8),
+//! so the raea app, `raea project scan`, `raea doctor` and `raea next` agree on what each file is:
+//! - a composition is each <Composition> a registerRoot registers (its props read from the source, not rendered), or a
+//! .tsx's default export with none that no other file imports, registered for it under its file's name (versions
+//! NAME-vN.tsx are one composition), sized from its newest render's manifest when it has one;
+//! - a component is a .tsx a composition imports, directly or through another;
+//! - a controller is a module whose default export is `controller({...})` from "raea/brief".
+//! What isn't connected is linted (lint.rs), each with its file and line and the fix.
+use std::collections::{BTreeMap, BTreeSet};
+use std::path::{Path, PathBuf};
+
+use serde_json::{Value, json};
+
+mod lint;
+mod read;
+
+pub use lint::{Fix, Level, Lint, apply};
+pub use read::{Facts, Prop};
+
+#[cfg(test)]
+mod tests;
+
+/// Folders that hold no compositions: media, renders, packages, raea's own (host/compositions.ts skips the same).
+const SKIP: &[&str] = &["node_modules", ".git", ".raea", "media", "out", "renders", "raw-audio", "stills", "dist", "build"];
+const MAX_FILES: usize = 600;
+
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub enum How {
+ /// a <Composition> in a registerRoot
+ Registered,
+ /// a default export with no <Composition>, registered under its file's name
+ Default,
+}
+
+#[derive(Debug, Clone)]
+pub struct Composition {
+ pub id: String,
+ /// relative to the scanned folder, with `/`
+ pub file: String,
+ pub line: usize,
+ pub how: How,
+ pub component: Option<String>,
+ pub width: Option<Prop>,
+ pub height: Option<Prop>,
+ pub fps: Option<Prop>,
+ pub frames: Option<Prop>,
+}
+
+#[derive(Debug, Clone)]
+pub struct Component {
+ pub file: String,
+ /// the composition files that import it, directly or through another file
+ pub used_by: Vec<String>,
+}
+
+#[derive(Debug, Clone)]
+pub struct Controller {
+ pub id: Option<String>,
+ pub file: String,
+ pub line: usize,
+}
+
+#[derive(Debug)]
+pub struct Registry {
+ pub dir: PathBuf,
+ /// the folder is in a raea project (.raea/project at or above it)
+ pub project: bool,
+ pub compositions: Vec<Composition>,
+ pub components: Vec<Component>,
+ pub controllers: Vec<Controller>,
+ pub lint: Vec<Lint>,
+}
+
+/// One file read: its path and what it declares.
+pub(crate) struct File {
+ pub path: PathBuf,
+ pub rel: String,
+ pub facts: Facts,
+}
+
+/// Every .tsx and .ts under the folder, a few levels down, skipping media, packages, raea's own folders and generated
+/// files (NAME.gen.tsx: written by a tool, not a person).
+fn sources(dir: &Path, rel: &str, depth: usize, out: &mut Vec<(PathBuf, String)>) {
+ if depth > 4 || out.len() >= MAX_FILES {
+ return;
+ }
+ let Ok(rd) = std::fs::read_dir(dir) else { return };
+ let mut entries: Vec<_> = rd.flatten().collect();
+ entries.sort_by_key(|e| e.file_name());
+ for e in entries {
+ let name = e.file_name().to_string_lossy().into_owned();
+ let p = e.path();
+ let r = if rel.is_empty() { name.clone() } else { format!("{rel}/{name}") };
+ if p.is_dir() {
+ if !name.starts_with('.') && !SKIP.contains(&name.as_str()) {
+ sources(&p, &r, depth + 1, out);
+ }
+ } else if (name.ends_with(".tsx") || name.ends_with(".ts")) && !name.ends_with(".d.ts") && !name.ends_with(".gen.tsx") && !name.ends_with(".gen.ts") {
+ out.push((p, r));
+ }
+ }
+}
+
+/// NAME for NAME.tsx and NAME-vN.tsx: one composition's versions share it.
+pub fn stem(file: &str) -> String {
+ let base = file.rsplit('/').next().unwrap_or(file).trim_end_matches(".tsx").trim_end_matches(".ts");
+ match base.rsplit_once("-v") {
+ Some((name, n)) if !name.is_empty() && !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()) => name.to_string(),
+ _ => base.to_string(),
+ }
+}
+
+/// The file a relative or absolute import names: as written, or with .tsx, .ts, .jsx or .js, or its folder's index.
+pub(crate) fn resolve(from: &Path, spec: &str) -> Option<PathBuf> {
+ let base = if spec.starts_with('/') { PathBuf::from(spec) } else { from.parent()?.join(spec) };
+ let tries = [base.clone(), base.with_extension("tsx"), base.with_extension("ts"), base.with_extension("jsx"), base.with_extension("js")];
+ let named = |ext: &str| PathBuf::from(format!("{}.{ext}", base.display()));
+ tries
+ .into_iter()
+ .chain(["tsx", "ts", "jsx", "js"].map(named))
+ .chain(["index.tsx", "index.ts"].map(|i| base.join(i)))
+ .find(|p| p.is_file())
+ .map(|p| std::fs::canonicalize(&p).unwrap_or(p))
+}
+
+/// An import of a file (not a package): relative or absolute.
+pub(crate) fn is_path(spec: &str) -> bool {
+ spec.starts_with("./") || spec.starts_with("../") || spec.starts_with('/')
+}
+
+/// A version's newest render manifest: NAME[-vN][.play].render.json beside it, or the folder's render.json for edit.tsx.
+fn manifest(path: &Path) -> Option<Value> {
+ let dir = path.parent()?;
+ let base = path.file_name()?.to_string_lossy().trim_end_matches(".tsx").to_string();
+ let mut tries = vec![dir.join(format!("{base}.render.json")), dir.join(format!("{base}.play.render.json"))];
+ if base == "edit" {
+ tries.push(dir.join("render.json"));
+ }
+ let f = tries.into_iter().find(|p| p.is_file())?;
+ serde_json::from_str(&std::fs::read_to_string(f).ok()?).ok()
+}
+
+/// The folder's registry. `controllers_home`: the workspace's controllers/ folder, read too, so an override or a
+/// controller elsewhere can be checked against the whole set.
+pub fn scan(dir: &Path) -> Registry {
+ let dir = std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
+ let project = crate::up(&dir, ".raea/project").is_some();
+ let mut found = Vec::new();
+ sources(&dir, "", 0, &mut found);
+ let files: Vec<File> = found
+ .into_iter()
+ .map(|(path, rel)| {
+ let src = std::fs::read_to_string(&path).unwrap_or_default();
+ let facts = read::read(&src, rel.ends_with(".tsx"));
+ File { path: std::fs::canonicalize(&path).unwrap_or(path), rel, facts }
+ })
+ .collect();
+
+ // a default-exported part another file imports (kit/statcard.tsx) is a component, not a piece of its own
+ let imported: BTreeSet<PathBuf> = files.iter().flat_map(|f| f.facts.imports.iter().filter(|(s, _)| is_path(s)).filter_map(|(s, _)| resolve(&f.path, s))).collect();
+ let mut compositions = Vec::new();
+ for f in &files {
+ if !f.facts.registered.is_empty() {
+ for r in &f.facts.registered {
+ let id = match &r.id {
+ Some(Prop::Text(t)) => t.clone(),
+ Some(Prop::Num(n)) => n.to_string(),
+ _ => stem(&f.rel),
+ };
+ compositions.push(Composition { id, file: f.rel.clone(), line: r.line, how: How::Registered, component: r.component.clone(), width: r.width.clone(), height: r.height.clone(), fps: r.fps.clone(), frames: r.frames.clone() });
+ }
+ } else if f.rel.ends_with(".tsx") && f.facts.default.is_some() && !imported.contains(&f.path) {
+ let m = manifest(&f.path);
+ let num = |k: &str| m.as_ref().and_then(|m| m[k].as_f64()).map(Prop::Num);
+ let frames = m.as_ref().and_then(|m| m["frames"].as_array()).map(|a| Prop::Num(a.len() as f64));
+ compositions.push(Composition { id: stem(&f.rel), file: f.rel.clone(), line: 1, how: How::Default, component: f.facts.default.clone().flatten(), width: num("width"), height: num("height"), fps: num("fps"), frames });
+ }
+ }
+
+ // the files each composition reaches through its imports, inside the scanned folder
+ let by_path: BTreeMap<&Path, &File> = files.iter().map(|f| (f.path.as_path(), f)).collect();
+ let comp_files: BTreeSet<&str> = compositions.iter().map(|c| c.file.as_str()).collect();
+ let mut used_by: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
+ for f in files.iter().filter(|f| comp_files.contains(f.rel.as_str())) {
+ let mut seen = BTreeSet::new();
+ let mut stack = vec![f];
+ while let Some(at) = stack.pop() {
+ for (spec, _) in at.facts.imports.iter().filter(|(s, _)| is_path(s)) {
+ let Some(to) = resolve(&at.path, spec) else { continue };
+ if let Some(g) = by_path.get(to.as_path())
+ && seen.insert(g.rel.clone())
+ {
+ stack.push(g);
+ }
+ }
+ }
+ for r in seen {
+ used_by.entry(r).or_default().insert(f.rel.clone());
+ }
+ }
+ let components = files
+ .iter()
+ .filter(|f| f.rel.ends_with(".tsx") && !comp_files.contains(f.rel.as_str()) && used_by.contains_key(&f.rel))
+ .map(|f| Component { file: f.rel.clone(), used_by: used_by[&f.rel].iter().cloned().collect() })
+ .collect();
+ let controllers = files.iter().filter_map(|f| f.facts.controller.as_ref().map(|c| Controller { id: c.id.clone(), file: f.rel.clone(), line: c.line })).collect();
+
+ let mut reg = Registry { dir, project, compositions, components, controllers, lint: Vec::new() };
+ reg.lint = lint::lint(&reg, &files, &used_by);
+ reg
+}
+
+impl Registry {
+ pub fn json(&self) -> Value {
+ let p = |v: &Option<Prop>| v.as_ref().map_or(Value::Null, Prop::json);
+ json!({
+ "dir": self.dir,
+ "project": self.project,
+ "compositions": self.compositions.iter().map(|c| json!({
+ "id": c.id, "file": c.file, "line": c.line,
+ "how": if c.how == How::Registered { "registered" } else { "default" },
+ "component": c.component, "width": p(&c.width), "height": p(&c.height), "fps": p(&c.fps), "frames": p(&c.frames),
+ })).collect::<Vec<_>>(),
+ "components": self.components.iter().map(|c| json!({ "file": c.file, "usedBy": c.used_by })).collect::<Vec<_>>(),
+ "controllers": self.controllers.iter().map(|c| json!({ "id": c.id, "file": c.file, "line": c.line })).collect::<Vec<_>>(),
+ "lint": self.lint.iter().map(Lint::json).collect::<Vec<_>>(),
+ })
+ }
+
+ /// For an agent (`raea context`): each composition with its id, file, size, fps and length, the components and
+ /// controllers, and what isn't connected (its warnings, at most ten; the notes are `raea project scan`'s).
+ pub fn summary(&self) -> String {
+ let p = |v: &Option<Prop>| match v {
+ Some(Prop::Num(n)) => format!("{n}"),
+ Some(Prop::Text(t)) => t.clone(),
+ Some(Prop::Computed(_)) => "(computed)".into(),
+ None => "?".into(),
+ };
+ let mut out = String::new();
+ for c in &self.compositions {
+ out.push_str(&format!("composition {}: {}:{}, {}x{}, {} fps, {} frames{}\n", c.id, c.file, c.line, p(&c.width), p(&c.height), p(&c.fps), p(&c.frames), if c.how == How::Default { " (its default export, not registered)" } else { "" }));
+ }
+ if self.compositions.is_empty() {
+ out.push_str("no compositions yet: a .tsx whose registerRoot registers a <Composition id width height fps durationInFrames />\n");
+ }
+ if !self.components.is_empty() {
+ out.push_str(&format!("components: {}\n", self.components.iter().map(|c| c.file.as_str()).collect::<Vec<_>>().join(", ")));
+ }
+ if !self.controllers.is_empty() {
+ out.push_str(&format!("controllers: {}\n", self.controllers.iter().map(|c| format!("{} ({})", c.id.as_deref().unwrap_or("?"), c.file)).collect::<Vec<_>>().join(", ")));
+ }
+ let warn: Vec<&Lint> = self.lint.iter().filter(|l| l.level == Level::Warn).collect();
+ if !warn.is_empty() {
+ out.push_str(&format!("\nnot connected ({}; raea doctor --fix fixes what it can):\n", warn.len()));
+ for l in warn.iter().take(10) {
+ out.push_str(&format!("- {}\n", l.line()));
+ }
+ }
+ out.trim_end().to_string()
+ }
+
+ /// What it found, for a person: a line each for the counts, then each lint as file:line, what, and the fix.
+ pub fn text(&self) -> String {
+ let mut out = format!(
+ "{}: {} compositions, {} components, {} controllers",
+ self.dir.display(),
+ self.compositions.len(),
+ self.components.len(),
+ self.controllers.len()
+ );
+ for c in &self.compositions {
+ out.push_str(&format!("\n composition {} ({}:{}{})", c.id, c.file, c.line, if c.how == How::Default { ", its default export" } else { "" }));
+ }
+ for l in &self.lint {
+ out.push_str(&format!("\n{}", l.line()));
+ }
+ out
+ }
+}
diff --git a/apps/workspace/src/registry/read.rs b/apps/workspace/src/registry/read.rs
new file mode 100644
index 00000000..0cc110b7
--- /dev/null
+++ b/apps/workspace/src/registry/read.rs
@@ -0,0 +1,295 @@
+//! What one .tsx or .ts file declares, read from its source without running it (docs/projects.feature PJ8): the
+//! compositions its registerRoot registers, each <Composition>'s id, component, size, fps and length (a value written
+//! out, or the expression that computes it); its default export; what it imports; and whether its default export is a
+//! controller (`export default controller({...})` from "raea/brief"). A prop written as a top-level constant, or simple
+//! arithmetic on them (`const FPS = 30; … durationInFrames={15 * FPS}`), is read as its value.
+use oxc::allocator::Allocator;
+use oxc::ast::ast::*;
+use oxc::ast_visit::{Visit, walk};
+use oxc::parser::Parser;
+use oxc::span::{GetSpan, SourceType};
+use oxc::syntax::operator::{BinaryOperator, UnaryOperator};
+use serde_json::{Value, json};
+use std::collections::HashMap;
+
+/// A <Composition> prop as written.
+#[derive(Debug, Clone, PartialEq)]
+pub enum Prop {
+ Num(f64),
+ Text(String),
+ /// an expression only the render knows the value of
+ Computed(String),
+}
+
+impl Prop {
+ pub fn json(&self) -> Value {
+ match self {
+ Prop::Num(n) => json!(n),
+ Prop::Text(t) => json!(t),
+ Prop::Computed(e) => json!({ "computed": e }),
+ }
+ }
+}
+
+/// One registered <Composition>.
+#[derive(Debug, Clone, Default)]
+pub struct Registered {
+ pub line: usize,
+ pub id: Option<Prop>,
+ pub component: Option<String>,
+ pub width: Option<Prop>,
+ pub height: Option<Prop>,
+ pub fps: Option<Prop>,
+ pub frames: Option<Prop>,
+}
+
+/// A controller the file's default export declares: its id (written, else from its title), at a line.
+#[derive(Debug, Clone)]
+pub struct Declared {
+ pub line: usize,
+ pub id: Option<String>,
+}
+
+#[derive(Debug, Default)]
+pub struct Facts {
+ pub registered: Vec<Registered>,
+ /// the default export, with its name when it has one (`export default function Promo`)
+ pub default: Option<Option<String>>,
+ /// each import or re-export's module, at its line
+ pub imports: Vec<(String, usize)>,
+ pub controller: Option<Declared>,
+ /// the names it imports from "raea" (a fix that registers its default export adds only what's missing)
+ pub raea_names: Vec<String>,
+ /// why it didn't parse (the first diagnostic), when it didn't
+ pub broken: Option<String>,
+}
+
+/// The file's facts; `tsx` for .tsx (JSX on), else plain TypeScript.
+pub fn read(source: &str, tsx: bool) -> Facts {
+ let alloc = Allocator::default();
+ let st = if tsx { SourceType::tsx() } else { SourceType::ts() };
+ let parsed = Parser::new(&alloc, source, st).parse();
+ let lines = line_starts(source);
+ let line = |at: u32| lines.partition_point(|&s| s <= at as usize);
+ let mut f = Facts::default();
+ if let Some(d) = parsed.diagnostics.first() {
+ f.broken = Some(d.to_string());
+ return f;
+ }
+ let mut controller_fn = None;
+ for s in &parsed.program.body {
+ match s {
+ Statement::ImportDeclaration(d) => {
+ f.imports.push((d.source.value.to_string(), line(d.span.start)));
+ if d.source.value == "raea" {
+ f.raea_names.extend(d.specifiers.iter().flatten().map(|sp| sp.local().name.to_string()));
+ }
+ if d.source.value == "raea/brief" {
+ for sp in d.specifiers.iter().flatten() {
+ if let ImportDeclarationSpecifier::ImportSpecifier(x) = sp
+ && x.imported.name() == "controller"
+ {
+ controller_fn = Some(sp.local().name.to_string());
+ }
+ }
+ }
+ }
+ Statement::ExportFromDeclaration(d) => f.imports.push((d.source.value.to_string(), line(d.span.start))),
+ Statement::ExportAllDeclaration(d) => f.imports.push((d.source.value.to_string(), line(d.span.start))),
+ Statement::ExportNamedDeclaration(d) => {
+ if let Some(sp) = d.specifiers.iter().find(|sp| sp.exported.name() == "default") {
+ f.default = Some(Some(sp.local.name().to_string()));
+ }
+ }
+ Statement::ExportDefaultDeclaration(d) => {
+ f.default = Some(match &d.declaration {
+ ExportDefaultDeclarationKind::FunctionDeclaration(x) => x.id.as_ref().map(|i| i.name.to_string()),
+ ExportDefaultDeclarationKind::ClassDeclaration(x) => x.id.as_ref().map(|i| i.name.to_string()),
+ ExportDefaultDeclarationKind::Identifier(x) => Some(x.name.to_string()),
+ _ => None,
+ });
+ if let ExportDefaultDeclarationKind::CallExpression(c) = &d.declaration
+ && let Expression::Identifier(callee) = &c.callee
+ && controller_fn.as_deref() == Some(callee.name.as_str())
+ {
+ f.controller = Some(Declared { line: line(d.span.start), id: controller_id(c) });
+ }
+ }
+ _ => {}
+ }
+ }
+ let mut v = Compositions { src: source, depth: 0, found: Vec::new(), consts: consts(&parsed.program) };
+ v.visit_program(&parsed.program);
+ f.registered = v.found.into_iter().map(|(at, mut r)| {
+ r.line = line(at);
+ r
+ }).collect();
+ f
+}
+
+/// A controller's id as written, else from its title (core/brief fills an id in from the title the same way).
+fn controller_id(c: &CallExpression) -> Option<String> {
+ let Some(Argument::ObjectExpression(o)) = c.arguments.first() else { return None };
+ let text = |key: &str| {
+ o.properties.iter().find_map(|p| match p {
+ ObjectPropertyKind::ObjectProperty(p) if p.key.static_name().as_deref() == Some(key) => match &p.value {
+ Expression::StringLiteral(s) => Some(s.value.to_string()),
+ _ => None,
+ },
+ _ => None,
+ })
+ };
+ text("id").or_else(|| text("title").map(|t| crate::slug(&t)))
+}
+
+/// The file's top-level numeric constants, in order: `const FPS = 30`, `const DUR = 15 * FPS`, and an object constant's
+/// numeric properties as `NAME.prop` (`const edit = { fps: 30 }`).
+fn consts(p: &Program) -> HashMap<String, f64> {
+ let mut k = HashMap::new();
+ for s in &p.body {
+ let v = match s {
+ Statement::VariableDeclaration(v) => v,
+ Statement::ExportDeclaration(d) => match &d.declaration {
+ Declaration::VariableDeclaration(v) => v,
+ _ => continue,
+ },
+ _ => continue,
+ };
+ if v.kind != VariableDeclarationKind::Const {
+ continue;
+ }
+ for d in &v.declarations {
+ let (BindingPattern::BindingIdentifier(id), Some(init)) = (&d.id, &d.init) else { continue };
+ match unwrap(init) {
+ Expression::ObjectExpression(o) => {
+ for p in &o.properties {
+ if let ObjectPropertyKind::ObjectProperty(p) = p
+ && let (Some(key), Some(n)) = (p.key.static_name(), number(&p.value, &k))
+ {
+ k.insert(format!("{}.{key}", id.name), n);
+ }
+ }
+ }
+ e => {
+ if let Some(n) = number(e, &k) {
+ k.insert(id.name.to_string(), n);
+ }
+ }
+ }
+ }
+ }
+ k
+}
+
+/// Through `x as T`, `x satisfies T` and parentheses.
+fn unwrap<'a, 'b>(e: &'b Expression<'a>) -> &'b Expression<'a> {
+ match e {
+ Expression::ParenthesizedExpression(p) => unwrap(&p.expression),
+ Expression::TSAsExpression(x) => unwrap(&x.expression),
+ Expression::TSSatisfiesExpression(x) => unwrap(&x.expression),
+ e => e,
+ }
+}
+
+/// An expression's value when it's numbers and known constants: + - * /, unary minus, Math.round, floor and ceil.
+fn number(e: &Expression, k: &HashMap<String, f64>) -> Option<f64> {
+ match unwrap(e) {
+ Expression::NumericLiteral(n) => Some(n.value),
+ Expression::Identifier(id) => k.get(id.name.as_str()).copied(),
+ Expression::StaticMemberExpression(m) => match &m.object {
+ Expression::Identifier(o) => k.get(&format!("{}.{}", o.name, m.property.name)).copied(),
+ _ => None,
+ },
+ Expression::UnaryExpression(u) if u.operator == UnaryOperator::UnaryNegation => number(&u.argument, k).map(|n| -n),
+ Expression::BinaryExpression(b) => {
+ let (l, r) = (number(&b.left, k)?, number(&b.right, k)?);
+ match b.operator {
+ BinaryOperator::Addition => Some(l + r),
+ BinaryOperator::Subtraction => Some(l - r),
+ BinaryOperator::Multiplication => Some(l * r),
+ BinaryOperator::Division if r != 0.0 => Some(l / r),
+ _ => None,
+ }
+ }
+ Expression::CallExpression(c) => {
+ let Expression::StaticMemberExpression(m) = &c.callee else { return None };
+ let Expression::Identifier(o) = &m.object else { return None };
+ let x = number(c.arguments.first()?.as_expression()?, k)?;
+ match (o.name.as_str(), m.property.name.as_str()) {
+ ("Math", "round") => Some(x.round()),
+ ("Math", "floor") => Some(x.floor()),
+ ("Math", "ceil") => Some(x.ceil()),
+ _ => None,
+ }
+ }
+ _ => None,
+ }
+}
+
+/// Every <Composition> inside a registerRoot(...) call's argument.
+struct Compositions<'s> {
+ src: &'s str,
+ depth: usize,
+ found: Vec<(u32, Registered)>,
+ consts: HashMap<String, f64>,
+}
+
+impl<'a> Visit<'a> for Compositions<'_> {
+ fn visit_call_expression(&mut self, it: &CallExpression<'a>) {
+ let root = matches!(&it.callee, Expression::Identifier(id) if id.name == "registerRoot");
+ self.depth += root as usize;
+ walk::walk_call_expression(self, it);
+ self.depth -= root as usize;
+ }
+
+ fn visit_jsx_element(&mut self, it: &JSXElement<'a>) {
+ let open = &it.opening_element;
+ if self.depth > 0 && matches!(&open.name, JSXElementName::IdentifierReference(r) if r.name == "Composition") {
+ let mut r = Registered::default();
+ for a in &open.attributes {
+ let JSXAttributeItem::Attribute(x) = a else { continue };
+ let JSXAttributeName::Identifier(n) = &x.name else { continue };
+ let value = x.value.as_ref().map(|v| self.prop(v));
+ match n.name.as_str() {
+ "id" => r.id = value,
+ "width" => r.width = value,
+ "height" => r.height = value,
+ "fps" => r.fps = value,
+ "durationInFrames" => r.frames = value,
+ "component" => {
+ r.component = match value {
+ Some(Prop::Computed(e)) => Some(e),
+ Some(Prop::Text(t)) => Some(t),
+ _ => None,
+ }
+ }
+ _ => {}
+ }
+ }
+ self.found.push((it.span.start, r));
+ }
+ walk::walk_jsx_element(self, it);
+ }
+}
+
+impl Compositions<'_> {
+ fn prop(&self, v: &JSXAttributeValue) -> Prop {
+ match v {
+ JSXAttributeValue::StringLiteral(l) => Prop::Text(l.value.to_string()),
+ JSXAttributeValue::ExpressionContainer(c) => match c.expression.as_expression() {
+ Some(Expression::NumericLiteral(n)) => Prop::Num(n.value),
+ Some(Expression::StringLiteral(s)) => Prop::Text(s.value.to_string()),
+ Some(Expression::TemplateLiteral(t)) if t.expressions.is_empty() && t.quasis.len() == 1 => Prop::Text(t.quasis[0].value.cooked.map(|c| c.to_string()).unwrap_or_default()),
+ Some(e) if number(e, &self.consts).is_some() => Prop::Num(number(e, &self.consts).unwrap_or_default()),
+ Some(e) => Prop::Computed(self.src[e.span().start as usize..e.span().end as usize].to_string()),
+ None => Prop::Computed(String::new()),
+ },
+ other => Prop::Computed(self.src[other.span().start as usize..other.span().end as usize].to_string()),
+ }
+ }
+}
+
+/// Where each line starts, for 1-based line numbers.
+fn line_starts(src: &str) -> Vec<usize> {
+ std::iter::once(0).chain(src.match_indices('\n').map(|(i, _)| i + 1)).collect()
+}
diff --git a/apps/workspace/src/registry/tests.rs b/apps/workspace/src/registry/tests.rs
new file mode 100644
index 00000000..6236c252
--- /dev/null
+++ b/apps/workspace/src/registry/tests.rs
@@ -0,0 +1,134 @@
+//! PJ8: a project's files read as compositions, components and controllers, and what isn't connected linted.
+use super::*;
+
+fn project() -> (tempdir::Dir, PathBuf) {
+ let t = tempdir::Dir::new();
+ let p = t.0.join("film");
+ let w = |rel: &str, text: &str| {
+ let f = p.join(rel);
+ std::fs::create_dir_all(f.parent().unwrap()).unwrap();
+ std::fs::write(f, text).unwrap();
+ };
+ w(".raea/project", "[project]\n\tid = pj-test\n");
+ w("promo.tsx", "import { Composition, registerRoot } from \"raea\";\nimport { Card } from \"./card\";\nconst FPS = 30, edit = { w: 1080 };\nfunction Promo() { return <Card />; }\nregisterRoot(() => <Composition id=\"promo\" component={Promo} width={edit.w} height={1920} fps={FPS} durationInFrames={Math.round(2.5 * FPS) + total()} />);\n");
+ w("promo-v2.tsx", "import { Composition, registerRoot } from \"raea\";\nfunction Promo() { return null; }\nregisterRoot(() => <Composition id=\"promo\" component={Promo} width={1080} height={1920} fps={30} durationInFrames={90} />);\n");
+ w("teaser.tsx", "import { Composition, registerRoot } from \"raea\";\nfunction T() { return null; }\nregisterRoot(() => (\n <Composition id=\"promo\" component={T} width={1080} height={1080} fps={30} durationInFrames={60} />\n));\n");
+ w("card.tsx", "import Glyph from \"./lib/glyph\";\nimport { gone } from \"./nope\";\nimport { far } from \"../outside\";\nexport function Card() { return <Glyph />; }\n");
+ w("lib/glyph.tsx", "export default function Glyph() { return <span />; }\n");
+ w("stray.tsx", "export function Stray() { return null; }\n");
+ w("bare.tsx", "import { AbsoluteFill } from \"raea\";\nexport default function Bare() { return <AbsoluteFill />; }\n");
+ w("bare.render.json", "{\"width\": 1080, \"height\": 1080, \"fps\": 30, \"frames\": [{}, {}, {}]}");
+ w("anon.tsx", "export default () => <div />;\n");
+ w("broken.tsx", "export default function (\n");
+ w("controllers/delivery.ts", "import { controller } from \"raea/brief\";\nexport default controller({ id: \"delivery\", title: \"Delivery\", groups: [] });\n");
+ w("settings/look.ts", "import { controller } from \"raea/brief\";\n\nexport default controller({ title: \"Look and feel\", groups: [] });\n");
+ std::fs::write(t.0.join("outside.tsx"), "export const far = 1;\n").unwrap();
+ (t, p)
+}
+
+/// A folder removed when the test ends.
+mod tempdir {
+ pub struct Dir(pub std::path::PathBuf);
+ impl Dir {
+ pub fn new() -> Dir {
+ static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
+ let d = std::env::temp_dir().join(format!("raea-registry-{}-{}", std::process::id(), N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
+ std::fs::create_dir_all(&d).unwrap();
+ Dir(std::fs::canonicalize(&d).unwrap())
+ }
+ }
+ impl Drop for Dir {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_dir_all(&self.0);
+ }
+ }
+}
+
+#[test]
+fn compositions_components_and_controllers_are_read_from_the_files() {
+ let (_t, p) = project();
+ let r = scan(&p);
+ assert!(r.project);
+ let comps: Vec<(&str, &str, How)> = r.compositions.iter().map(|c| (c.id.as_str(), c.file.as_str(), c.how)).collect();
+ assert!(comps.contains(&("promo", "promo.tsx", How::Registered)));
+ assert!(comps.contains(&("promo", "promo-v2.tsx", How::Registered)));
+ assert!(comps.contains(&("bare", "bare.tsx", How::Default)));
+ assert!(comps.contains(&("anon", "anon.tsx", How::Default)));
+ let promo = r.compositions.iter().find(|c| c.file == "promo.tsx").unwrap();
+ assert_eq!((promo.line, promo.component.as_deref(), promo.width.clone(), promo.fps.clone()), (5, Some("Promo"), Some(Prop::Num(1080.0)), Some(Prop::Num(30.0))), "constants read as their values");
+ assert_eq!(promo.frames, Some(Prop::Computed("Math.round(2.5 * FPS) + total()".into())), "a call only the render knows");
+ let teaser = r.compositions.iter().find(|c| c.file == "teaser.tsx").unwrap();
+ assert_eq!(teaser.line, 4, "the <Composition>'s own line, inside a multi-line registerRoot");
+ let bare = r.compositions.iter().find(|c| c.file == "bare.tsx").unwrap();
+ assert_eq!((bare.width.clone(), bare.frames.clone()), (Some(Prop::Num(1080.0)), Some(Prop::Num(3.0))), "sized from its render's manifest");
+ // card is imported by promo, glyph through card (a default export, but imported): both components, used by promo
+ let comps: Vec<(&str, Vec<&str>)> = r.components.iter().map(|c| (c.file.as_str(), c.used_by.iter().map(String::as_str).collect())).collect();
+ assert_eq!(comps, [("card.tsx", vec!["promo.tsx"]), ("lib/glyph.tsx", vec!["promo.tsx"])]);
+ let ctl: Vec<(Option<&str>, &str)> = r.controllers.iter().map(|c| (c.id.as_deref(), c.file.as_str())).collect();
+ assert_eq!(ctl, [(Some("delivery"), "controllers/delivery.ts"), (Some("look-and-feel"), "settings/look.ts")]);
+}
+
+#[test]
+fn what_isnt_connected_is_linted_with_its_place_and_fix() {
+ let (_t, p) = project();
+ let r = scan(&p);
+ let has = |rule: &str, file: &str, line: usize| r.lint.iter().any(|l| l.rule == rule && l.file == file && l.line == line);
+ assert!(has("orphan", "stray.tsx", 1));
+ assert!(!r.lint.iter().any(|l| l.rule == "orphan" && ["card.tsx", "lib/glyph.tsx", "promo.tsx"].contains(&l.file.as_str())));
+ assert!(has("unresolved", "card.tsx", 2));
+ assert!(has("outside", "card.tsx", 3));
+ assert!(has("broken", "broken.tsx", 1));
+ // promo's versions share an id; teaser takes it too
+ assert!(has("duplicate-id", "teaser.tsx", 4));
+ assert!(r.lint.iter().filter(|l| l.rule == "duplicate-id").all(|l| l.says.contains("teaser") || l.file == "teaser.tsx"));
+ assert!(has("computed", "promo.tsx", 5));
+ assert!(has("controller-home", "settings/look.ts", 3));
+ assert!(!r.lint.iter().any(|l| l.file == "controllers/delivery.ts"));
+ // a default export with a render is registered by --fix; a nameless one says how
+ let bare = r.lint.iter().find(|l| l.rule == "unregistered" && l.file == "bare.tsx").unwrap();
+ assert!(bare.action.is_some());
+ let anon = r.lint.iter().find(|l| l.rule == "unregistered" && l.file == "anon.tsx").unwrap();
+ assert!(anon.action.is_none() && anon.fix.contains("name the default export"));
+}
+
+#[test]
+fn fixes_register_a_default_export_and_move_a_controller_home() {
+ let (_t, p) = project();
+ let r = scan(&p);
+ for l in r.lint.iter().filter(|l| l.action.is_some()) {
+ lint::apply(l.action.as_ref().unwrap()).unwrap();
+ }
+ let bare = std::fs::read_to_string(p.join("bare.tsx")).unwrap();
+ assert!(bare.starts_with("import { Composition, registerRoot } from \"raea\";\nimport { AbsoluteFill }"), "{bare}");
+ assert!(bare.ends_with("registerRoot(() => <Composition id=\"bare\" component={Bare} width={1080} height={1080} fps={30} durationInFrames={3} />);\n"), "{bare}");
+ assert!(p.join("controllers/look-and-feel.ts").is_file() && !p.join("settings/look.ts").exists());
+ let again = scan(&p);
+ assert_eq!(again.compositions.iter().find(|c| c.file == "bare.tsx").unwrap().how, How::Registered);
+ assert!(!again.lint.iter().any(|l| l.rule == "controller-home" || (l.rule == "unregistered" && l.file == "bare.tsx")));
+}
+
+#[test]
+fn a_folder_outside_any_project_says_so() {
+ let t = tempdir::Dir::new();
+ std::fs::write(t.0.join("a.tsx"), "export default function A() { return null; }\n").unwrap();
+ let r = scan(&t.0);
+ assert!(!r.project);
+ assert!(r.lint.iter().any(|l| l.rule == "not-a-project"));
+}
+
+#[test]
+fn versions_share_a_stem() {
+ assert_eq!(stem("promo-v12.tsx"), "promo");
+ assert_eq!(stem("dir/my-video.tsx"), "my-video");
+ assert_eq!(stem("x-v.tsx"), "x-v");
+}
+
+/// A real folder's registry, printed: `RAEA_SCAN_DIR=~/Studio/x cargo test -p raea-app-workspace real_folder -- --ignored --nocapture`.
+#[test]
+#[ignore]
+fn real_folder() {
+ let Some(dir) = std::env::var_os("RAEA_SCAN_DIR") else { return };
+ let t = std::time::Instant::now();
+ let r = scan(Path::new(&dir));
+ println!("{}\n({} ms)", r.text(), t.elapsed().as_millis());
+}
diff --git a/apps/workspace/src/tests.rs b/apps/workspace/src/tests.rs
index 6dbc449f..f0f6c4f0 100644
--- a/apps/workspace/src/tests.rs
+++ b/apps/workspace/src/tests.rs
@@ -35,13 +35,18 @@ fn scratch(name: &str) -> PathBuf {
#[test]
fn next_walks_a_project_from_brief_to_show() {
let d = scratch("next");
+ std::fs::create_dir_all(d.join(".raea")).unwrap();
+ std::fs::write(d.join(".raea/project"), "").unwrap();
let shaped = next::Brief { needs: vec![], modes: vec!["tool".into()] };
let unshaped = next::Brief { needs: vec!["who it's for (audience)".into()], modes: vec!["pitch".into()] };
let s = next::steps(&d, &unshaped, 0);
assert!(s[0].starts_with("shape the brief: who it's for") && s[1].starts_with("plan it") && s[2].starts_with("make the first item"), "{s:?}");
assert!(next::steps(&d, &shaped, 2)[0].starts_with("raea doctor: 2"));
- std::fs::write(d.join("piece.tsx"), "registerRoot(() => null)").unwrap();
- assert!(next::steps(&d, &shaped, 0)[0].starts_with("render piece.tsx"));
+ std::fs::write(d.join("card.tsx"), "export const Card = () => null;\n").unwrap();
+ let s = next::steps(&d, &shaped, 0);
+ assert!(s[0].starts_with("connect the project's files: 1 thing(s) aren't connected, first card.tsx:1: isn't a composition"), "{s:?}");
+ std::fs::write(d.join("piece.tsx"), "import { Composition, registerRoot } from \"raea\";\nimport { Card } from \"./card\";\nregisterRoot(() => <Composition id=\"piece\" component={Card} width={1080} height={1920} fps={30} durationInFrames={90} />);\n").unwrap();
+ assert!(next::steps(&d, &shaped, 0)[0].starts_with("render piece.tsx"), "{:?}", next::steps(&d, &shaped, 0));
std::fs::create_dir_all(d.join("out")).unwrap();
std::thread::sleep(std::time::Duration::from_millis(20));
std::fs::write(d.join("out/piece.mp4"), "").unwrap();
@@ -54,6 +59,24 @@ fn next_walks_a_project_from_brief_to_show() {
let _ = std::fs::remove_dir_all(&d);
}
+#[test]
+fn doctor_connects_a_projects_files() {
+ let d = scratch("doctor-pj8");
+ std::fs::create_dir_all(d.join(".raea")).unwrap();
+ std::fs::write(d.join(".raea/project"), "").unwrap();
+ std::fs::write(d.join("loose.tsx"), "export const Loose = () => null;\n").unwrap();
+ std::fs::write(d.join("pace.ts"), "import { controller } from \"raea/brief\";\nexport default controller({ title: \"Pace\", fields: {} });\n").unwrap();
+ let found = doctor::registry_findings(&d);
+ let says: Vec<&String> = found.iter().map(|f| &f.says).collect();
+ assert_eq!(found.len(), 2, "{says:?}");
+ assert!(says[0].contains("loose.tsx:1: isn't a composition") && !found[0].fixable(), "{says:?}");
+ assert!(says[1].contains("pace.ts:2: a controller outside controllers/") && found[1].fixable(), "{says:?}");
+ let out = doctor::doctor(&["--fix".into(), d.display().to_string()], &[], "0.0.1", &|_| Ok(String::new())).unwrap();
+ assert!(out.starts_with("APPLIED 3 of 4 fixed") && out.contains("fixed ") && d.join("controllers/pace.ts").is_file() && !d.join("pace.ts").exists(), "{out}");
+ assert_eq!(doctor::registry_findings(&d).len(), 1, "only the loose file is left");
+ let _ = std::fs::remove_dir_all(&d);
+}
+
#[test]
fn doctor_finds_old_briefs_and_old_skills() {
let d = scratch("doctor");
diff --git a/apps/workspace/src/workspace.rs b/apps/workspace/src/workspace.rs
index c7bf6cd2..a1332e12 100644
--- a/apps/workspace/src/workspace.rs
+++ b/apps/workspace/src/workspace.rs
@@ -5,7 +5,7 @@
use super::*;
use std::process::Command;
-const USAGE: &str = "usage: raea workspace [--json] | raea workspace init [NAME] [--layout monorepo|submodules] | raea workspace adopt DIR [--name NAME] [--layout monorepo|submodules]\n raea project [--json] | raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME";
+const USAGE: &str = "usage: raea workspace [--json] | raea workspace init [NAME] [--layout monorepo|submodules] | raea workspace adopt DIR [--name NAME] [--layout monorepo|submodules]\n raea project [--json] | raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME | raea project scan [DIR] [--json]";
/// git for raea's own commits. A new Mac has no user.email and a hostname git can't make one from, so every commit
/// failed with "Author identity unknown" and the person's first project was never made. git reads $EMAIL only when
@@ -305,6 +305,12 @@ pub fn project(args: &[String]) -> R<String> {
Some("new") => new_project(w.get(1).ok_or(USAGE)?, flag(args, "--storage")),
Some("split") => storage::split(w.get(1).ok_or(USAGE)?, flag(args, "--remote")),
Some("join") => storage::join(w.get(1).ok_or(USAGE)?),
+ // PJ8: the folder's compositions, components and controllers, and what isn't connected
+ Some("scan") => {
+ let dir = w.get(1).map(PathBuf::from).map_or_else(|| std::env::current_dir().map_err(|e| e.to_string()), Ok)?;
+ let r = crate::registry::scan(&dir);
+ Ok(if args.iter().any(|a| a == "--json") { r.json().to_string() } else { r.text() })
+ }
Some(v) => Err(format!("raea project has no {v:?}\n{USAGE}")),
}
}
diff --git a/engine/cli/src/guide.rs b/engine/cli/src/guide.rs
index 68ea5668..5bbda74c 100644
--- a/engine/cli/src/guide.rs
+++ b/engine/cli/src/guide.rs
@@ -134,6 +134,10 @@ fn context_body(out: &mut String, dir: &Path, taste_dir: Option<PathBuf>, modes:
if let Some(text) = raea_app_workspace::summary(&dir, spec::spec_json) {
section("CONTROLLERS (raea controller ls; a project's own values marked)".into(), text);
}
+ // the project's compositions, components and controllers as raea's project system reads them (PJ8)
+ if let Some(d) = raea_app_workspace::doctor::registry_dir(dir) {
+ section("PROJECT FILES (raea project scan)".into(), raea_app_workspace::registry::scan(&d).summary());
+ }
section(format!("BRIEF {}", brief_path.display()), brief.clone());
for (p, t) in &subs {
section(format!("{} {}", if p.to_string_lossy().contains("script") { "SCRIPT" } else { "BRIEF" }, p.display()), t.clone());