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.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
Layout LY1-LY4: a project's compositions/, components/, controllers/, assets/ and artifacts/, and the workspace's shared/ (docs/layout.feature)
shinyobjectzcb87e0cd596c
diff --git a/apps/direction/src/check.rs b/apps/direction/src/check.rsindex 7d15b822..20068cac 100644--- a/apps/direction/src/check.rs+++ b/apps/direction/src/check.rs@@ -113,7 +113,7 @@ fn held(project: &Path, given: Vec<PathBuf>, host: &Host) -> (Vec<Rule>, Vec<Fin}}let ws = record::up(project, ".raea/workspace");- for (dir, scope) in ws.iter().map(|w| (w.join("controllers"), "workspace")).chain([(project.join("controllers"), "project")]) {+ for (dir, scope) in ws.iter().map(|w| (raea_app_registry::shared_dir(w, "controllers"), "workspace")).chain([(project.join("controllers"), "project")]) {// a workspace's own folder is its project's too: read onceif scope == "project" && ws.as_deref() == Some(project) {continue;diff --git a/apps/workspace/registry/src/lib.rs b/apps/workspace/registry/src/lib.rsindex 64471887..f4c6e7ca 100644--- a/apps/workspace/registry/src/lib.rs+++ b/apps/workspace/registry/src/lib.rs@@ -22,6 +22,17 @@ pub use read::{Facts, Prop};/// The nearest folder at or above a path that holds a marker (.raea/workspace, .raea/project), as the record finds it.pub use raea_core_facts::record::up;+/// The workspace's shared folder of one kind (docs/layout.feature: shared/compositions, components, controllers, assets,+/// artifacts), which every project can call on as @shared/<kind>/. A workspace from before shared/ keeps that kind at+/// its root (controllers/, artifacts/) until `raea workspace tidy` moves it, and it's read there meanwhile.+pub fn shared_dir(ws: &Path, kind: &str) -> PathBuf {+ let old = ws.join(kind);+ if !ws.join("shared").is_dir() && old.is_dir() {+ return old;+ }+ ws.join("shared").join(kind)+}+/// A name as a folder: lowercase, dashes. A controller's id from its title is this (core/brief fills it the same way).pub fn slug(s: &str) -> String {let mut out = String::new();@@ -131,7 +142,14 @@ pub fn stem(file: &str) -> String {/// The file a relative or absolute import names: as written, or with .tsx, .ts, .jsx or .js (in place of an extension/// or after the name), 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) };+ // @shared/<kind>/<name>: the workspace's shared/ (docs/layout.feature LY2), as the engine's loader resolves it+ let base = if let Some(rest) = spec.strip_prefix(SHARED) {+ up(from.parent()?, ".raea/workspace")?.join("shared").join(rest)+ } else if spec.starts_with('/') {+ PathBuf::from(spec)+ } else {+ from.parent()?.join(spec)+ };let mut tries = vec![base.clone()];for ext in ["tsx", "ts", "jsx", "js"] {tries.push(base.with_extension(ext));@@ -142,11 +160,14 @@ pub(crate) fn resolve(from: &Path, spec: &str) -> Option<PathBuf> {Some(std::fs::canonicalize(&found).unwrap_or(found))}-/// An import of a file (not a package): relative or absolute.+/// An import of a file (not a package): relative, absolute, or the workspace's shared/ (@shared/...).pub(crate) fn is_path(spec: &str) -> bool {- spec.starts_with("./") || spec.starts_with("../") || spec.starts_with('/')+ spec.starts_with("./") || spec.starts_with("../") || spec.starts_with('/') || spec.starts_with(SHARED)}+/// The prefix a project imports its workspace's shared files by: @shared/components/desk (docs/layout.feature LY2).+pub const SHARED: &str = "@shared/";+/// 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()?;diff --git a/apps/workspace/registry/src/lint.rs b/apps/workspace/registry/src/lint.rsindex e4deafb3..1f977d1f 100644--- a/apps/workspace/registry/src/lint.rs+++ b/apps/workspace/registry/src/lint.rs@@ -73,6 +73,8 @@ pub(super) fn lint(reg: &Registry, files: &[File], used_by: &BTreeMap<String, BT}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();+ // the workspace's shared/, which a project reaches as @shared/+ let shared = super::up(®.dir, ".raea/workspace").map(|w| w.join("shared")).map(|s| s.canonicalize().unwrap_or(s));for f in files {if let Some(why) = &f.facts.broken {@@ -90,18 +92,47 @@ pub(super) fn lint(reg: &Registry, files: &[File], used_by: &BTreeMap<String, BTfor (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(®.dir) => out.push(warn(- &f.rel,- *line,- "outside",- format!("imports {} from outside the project", tilde(&to)),- "copy it into the project (raea part add, for raea's parts), so the project renders on its own",- )),+ // the workspace's shared/ by its name is how a project reaches it (docs/layout.feature LY2)+ Some(_) if spec.starts_with(super::SHARED) => {}+ Some(to) if !to.starts_with(®.dir) => {+ let in_shared = shared.as_ref().and_then(|s| to.strip_prefix(s).ok()).map(|r| r.with_extension("").display().to_string());+ out.push(warn(+ &f.rel,+ *line,+ "outside",+ format!("imports {} from outside the project", tilde(&to)),+ &match in_shared {+ Some(r) => format!("import it by the workspace's name for it: \"@shared/{r}\""),+ None => "move it to the workspace's shared/ and import it as @shared/<kind>/<name>, or copy it into the project (raea component add, for raea's sets)".into(),+ },+ ))+ }_ => {}}}}+ // where each kind is kept (docs/layout.feature LY3): a project in the layout has a folder per kind, and a file+ // elsewhere is said once with the folder it belongs in; a project from before the layout is said once, as a whole+ if reg.project && reg.dir.join(".raea/project").is_file() {+ let laid = reg.dir.join("compositions").is_dir() || reg.dir.join("components").is_dir();+ let home = |rel: &str, kind: &str| rel.starts_with(&format!("{kind}/"));+ let components: BTreeSet<&str> = used_by.keys().map(String::as_str).filter(|f| f.ends_with(".tsx") && !comp_files.contains(f)).collect();+ let stray: Vec<(&str, &str)> = comp_files+ .iter()+ .filter(|f| !home(f, "compositions"))+ .map(|f| (*f, "compositions"))+ .chain(components.iter().filter(|f| !home(f, "components")).map(|f| (*f, "components")))+ .collect();+ if !laid && !stray.is_empty() {+ out.push(Lint { file: String::new(), line: 0, rule: "old-layout", level: Level::Info, says: format!("keeps {} files loose, from before compositions/ and components/", stray.len()), fix: "`raea project tidy --dry-run` shows where each goes, then `raea project tidy` moves them".into(), action: None });+ } else {+ for (f, kind) in stray {+ out.push(Lint { file: f.to_string(), line: 1, rule: "misplaced", level: Level::Info, says: format!("a {} outside {kind}/", &kind[..kind.len() - 1]), fix: format!("move it into {kind}/ (`raea project tidy` moves it and its imports)"), action: None });+ }+ }+ }+// one id, two compositions (a composition's versions share theirs)let mut by_id: BTreeMap<&str, BTreeSet<String>> = BTreeMap::new();for c in ®.compositions {@@ -165,7 +196,12 @@ pub(super) fn lint(reg: &Registry, files: &[File], used_by: &BTreeMap<String, BT// controllers: where they're kept, one id each, and every override naming one that's therelet ws = super::up(®.dir, ".raea/workspace");- let home = ws.clone().unwrap_or_else(|| reg.dir.clone()).join("controllers");+ // a project keeps its own (its controllers/); the workspace's own folder keeps the shared ones (docs/layout.feature LY3)+ let home = match &ws {+ Some(w) if w != ®.dir => reg.dir.join("controllers"),+ Some(w) => super::shared_dir(w, "controllers"),+ None => reg.dir.join("controllers"),+ };let mut ids: BTreeMap<String, Vec<&str>> = BTreeMap::new();for c in ®.controllers {let f = files.iter().find(|f| f.rel == c.file).expect("a controller's file was read");diff --git a/apps/workspace/registry/src/tests.rs b/apps/workspace/registry/src/tests.rsindex a33661a6..c2341719 100644--- a/apps/workspace/registry/src/tests.rs+++ b/apps/workspace/registry/src/tests.rs@@ -148,3 +148,37 @@ fn real_folder() {let r = scan(Path::new(&dir), &[]);println!("{}\n({} ms)", r.text(), t.elapsed().as_millis());}++#[test]+fn a_project_in_the_layout_reaches_shared_and_says_whats_out_of_place() {+ // docs/layout.feature LY2, LY3: @shared/ resolves and isn't "outside"; a relative climb into shared/ is told its+ // @shared/ name; a composition outside compositions/ is misplaced; a project from before the layout is said once+ let t = tempdir::Dir::new();+ let w = |rel: &str, text: &str| {+ let f = t.0.join(rel);+ std::fs::create_dir_all(f.parent().unwrap()).unwrap();+ std::fs::write(f, text).unwrap();+ };+ w(".raea/workspace", "[workspace]\n\tname = W\n");+ w("shared/components/desk.tsx", "export function Desk() { return <div />; }\n");+ w("projects/a/.raea/project", "[project]\n\tid = pj-a\n");+ w("projects/a/compositions/main.tsx", "import { Desk } from \"@shared/components/desk\";\nimport { Leg } from \"../components/leg\";\nimport { Desk as D2 } from \"../../../shared/components/desk\";\nexport default () => <><Desk /><Leg /><D2 /></>;\n");+ w("projects/a/components/leg.tsx", "export function Leg() { return <i />; }\n");+ w("projects/a/loose.tsx", "export default () => <b />;\n");+ let r = scan(&t.0.join("projects/a"), &[]);+ let says = |rule: &str| r.lint.iter().filter(|l| l.rule == rule).map(|l| format!("{} {}: {}", l.file, l.says, l.fix)).collect::<Vec<_>>();+ assert!(says("unresolved").is_empty(), "{:?}", says("unresolved"));+ let outside = says("outside");+ assert_eq!(outside.len(), 1, "{outside:?}");+ assert!(outside[0].contains("\"@shared/components/desk\""), "{outside:?}");+ assert_eq!(says("misplaced"), ["loose.tsx a composition outside compositions/: move it into compositions/ (`raea project tidy` moves it and its imports)"]);+ assert!(!r.lint.iter().any(|l| l.rule == "orphan" && l.file == "components/leg.tsx"));++ w("projects/old/.raea/project", "[project]\n\tid = pj-old\n");+ w("projects/old/promo.tsx", "import { Card } from \"./card\";\nexport default () => <Card />;\n");+ w("projects/old/card.tsx", "export function Card() { return <i />; }\n");+ let r = scan(&t.0.join("projects/old"), &[]);+ let old: Vec<_> = r.lint.iter().filter(|l| l.rule == "old-layout").collect();+ assert!(old.len() == 1 && old[0].says.contains("2 files loose") && old[0].fix.contains("raea project tidy"), "{:?}", r.lint);+ assert!(!r.lint.iter().any(|l| l.rule == "misplaced"));+}diff --git a/apps/workspace/src/controllers.rs b/apps/workspace/src/controllers.rsindex 308f134a..f57f299e 100644--- a/apps/workspace/src/controllers.rs+++ b/apps/workspace/src/controllers.rs@@ -1,4 +1,5 @@-//! A workspace's controllers on disk (docs/projects.feature PJ2): controllers/<id>.ts, each `export default+//! A workspace's controllers on disk (docs/projects.feature PJ2): shared/controllers/<id>.ts (docs/layout.feature; a+//! workspace from before shared/ keeps controllers/ at its root), each `export default//! controller({...})` from "raea/brief", checked by core/brief's normalize. A project overrides a field's value in its//! .raea/project (`[controller "delivery.format"] aspect-ratio = 16:9`), so the project's value wins, as git config's//! own scopes do. Every change is a commit by who made it ("you", or the agent's name with --by).@@ -16,7 +17,7 @@ fn workspace_dir() -> R<PathBuf> {/// Every controller in the workspace, checked, in file order.pub fn load(ws: &Path, eval: Eval) -> R<Vec<(PathBuf, Controller)>> {- let mut files: Vec<PathBuf> = std::fs::read_dir(ws.join("controllers")).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "ts")).collect();+ let mut files: Vec<PathBuf> = std::fs::read_dir(raea_app_registry::shared_dir(ws, "controllers")).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "ts")).collect();files.sort();files.into_iter().map(|f| read(&f, eval).map(|c| (f, c))).collect()}@@ -188,9 +189,9 @@ fn set(ws: &Path, path: &str, value: &str, project: bool, by: &str, eval: Eval)fn write(ws: &Path, file: &Path, by: &str, eval: Eval) -> R<String> {let c = read(file, eval)?;- let to = ws.join("controllers").join(format!("{}.ts", c.id));+ let to = raea_app_registry::shared_dir(ws, "controllers").join(format!("{}.ts", c.id));let new = !to.exists();- std::fs::create_dir_all(ws.join("controllers")).map_err(|e| e.to_string())?;+ std::fs::create_dir_all(raea_app_registry::shared_dir(ws, "controllers")).map_err(|e| e.to_string())?;std::fs::write(&to, module(&c)).map_err(|e| format!("{}: {e}", to.display()))?;commit(ws, &[&to], &format!("{} controller {}", if new { "add" } else { "rewrite" }, c.id), by)?;let n = |k: usize, what: &str| format!("{k} {what}{}", if k == 1 { "" } else { "s" });@@ -198,7 +199,7 @@ fn write(ws: &Path, file: &Path, by: &str, eval: Eval) -> R<String> {}fn rm(ws: &Path, id: &str, by: &str) -> R<String> {- let file = ws.join("controllers").join(format!("{id}.ts"));+ let file = raea_app_registry::shared_dir(ws, "controllers").join(format!("{id}.ts"));if !file.is_file() {return Err(format!("no controller {id}: raea controller ls lists them"));}diff --git a/apps/workspace/src/tests.rs b/apps/workspace/src/tests.rsindex 8dbdab1f..2b3389c5 100644--- a/apps/workspace/src/tests.rs+++ b/apps/workspace/src/tests.rs@@ -140,3 +140,31 @@ fn the_root_with_none_set() {std::fs::create_dir_all(synced.join("Library/Mobile Documents/com~apple~CloudDocs/Documents")).unwrap();assert_eq!(default_root(&synced), synced.join("raea"));}++#[test]+fn a_new_workspace_and_project_have_the_layout() {+ // docs/layout.feature LY1: a folder per kind in the project and in the workspace's shared/, no media/ brand/ parts/+ let ws = scratch("layout");+ crate::workspace::make_workspace(&ws, "Layout", "monorepo").unwrap();+ for k in crate::workspace::KINDS {+ assert!(ws.join("shared").join(k).join(".gitkeep").is_file(), "shared/{k}");+ }+ assert!(!ws.join("controllers").exists() && !ws.join("artifacts").exists());+ let attrs = std::fs::read_to_string(ws.join(".gitattributes")).unwrap();+ assert!(attrs.contains("**/assets/** filter=lfs"), "{attrs}");+ crate::workspace::new_project_in(&ws, "Desk Test", None).unwrap();+ let p = ws.join("projects/desk-test");+ for k in crate::workspace::KINDS.iter().chain(["out"].iter()) {+ assert!(p.join(k).join(".gitkeep").is_file(), "{k}");+ }+ for gone in ["media", "brand", "parts"] {+ assert!(!p.join(gone).exists(), "{gone}");+ }+ assert!(std::fs::read_to_string(p.join("tsconfig.json")).unwrap().contains("\"@shared/*\": [\"../../shared/*\"]"));+ assert!(std::fs::read_to_string(p.join("AGENTS.md")).unwrap().contains("@shared/components/desk"));+ // committed: the workspace's repo has every kept folder+ let tracked = std::process::Command::new("git").args(["ls-files"]).current_dir(&ws).output().unwrap();+ let tracked = String::from_utf8_lossy(&tracked.stdout);+ assert!(tracked.contains("projects/desk-test/components/.gitkeep") && tracked.contains("shared/assets/.gitkeep"), "{tracked}");+ let _ = std::fs::remove_dir_all(&ws);+}diff --git a/apps/workspace/src/workspace.rs b/apps/workspace/src/workspace.rsindex b4fa8dae..3ac5b07c 100644--- a/apps/workspace/src/workspace.rs+++ b/apps/workspace/src/workspace.rs@@ -156,7 +156,17 @@ pub(crate) fn commit(repo: &Path, paths: &[&str], what: &str) -> R<()> {git(repo, &["commit", "-q", "-m", &format!("raea: {what}"), "--"]).map(|_| ())}-const AGENTS_PROJECT: &str = "# Agents\n\nRun `raea context .` here before any work: the taste, this project's brief.ts and script.ts, its look and the guides\nits modes need, in the order to read them. Specs are TypeScript (`export default brief({...})` from \"raea/brief\").\n";+const AGENTS_PROJECT: &str = "# Agents\n\nRun `raea context .` here before any work: the taste, this project's brief.ts and script.ts, its look and the guides\nits modes need, in the order to read them. Specs are TypeScript (`export default brief({...})` from \"raea/brief\").\n\nWhere files go (docs/layout.feature):\n\n- compositions/: what renders, a registerRoot <Composition> or a default export; versions are NAME-v2.tsx\n- components/: what compositions import; every prop is a component whose props animate it\n- controllers/: this project's controllers, over the workspace's shared ones by id\n- assets/: media in (footage, stills, audio, models, fonts) and the brand kit in assets/brand/\n- artifacts/: the small React apps posted to the feed\n- out/: renders\n\nThe workspace's shared/ holds the same five folders for every project: import them as\n`@shared/components/desk`, never by a relative path out of this folder.\n";++/// The kinds of file a project, and the workspace's shared/, keep a folder each for (docs/layout.feature).+pub const KINDS: [&str; 5] = ["compositions", "components", "controllers", "assets", "artifacts"];++/// LFS for media in and renders out, at any depth: in each project and in shared/ (a pattern with a slash is anchored to+/// the workspace root, so the old media/** never matched a project's media/)+const GITATTRIBUTES: &str = "**/assets/** filter=lfs diff=lfs merge=lfs -text\n**/out/** filter=lfs diff=lfs merge=lfs -text\n**/media/** filter=lfs diff=lfs merge=lfs -text\n";++/// A project's tsconfig: @shared/ resolves to the workspace's shared/ for an editor and tsc, as the engine resolves it.+const TSCONFIG_PROJECT: &str = "{\n \"compilerOptions\": {\n \"jsx\": \"react-jsx\",\n \"module\": \"esnext\",\n \"moduleResolution\": \"bundler\",\n \"target\": \"es2022\",\n \"strict\": true,\n \"noEmit\": true,\n \"baseUrl\": \".\",\n \"paths\": { \"@shared/*\": [\"../../shared/*\"] }\n }\n}\n";/// `raea workspace …`pub fn workspace(args: &[String]) -> R<String> {@@ -229,7 +239,7 @@ fn count(n: usize) -> String {if n == 1 { "1 project".into() } else { format!("{n} projects") }}-fn make_workspace(dir: &Path, name: &str, layout: &str) -> R<()> {+pub(crate) fn make_workspace(dir: &Path, name: &str, layout: &str) -> R<()> {// never a workspace in another repo's own folder (on a case-insensitive disk ~/Raea is ~/raea, raea's checkout); a// repo further up, as a home folder kept in git, is fine: the workspace is a repo of its own inside itlet parent = dir.parent().unwrap_or(Path::new("/"));@@ -250,11 +260,17 @@ fn make_workspace(dir: &Path, name: &str, layout: &str) -> R<()> {set(&file, "workspace.name", name)?;set(&file, "workspace.layout", layout)?;include(dir, &file)?;- write_new(&dir.join("controllers/.gitkeep"), "")?;+ // what every project here can call on (docs/layout.feature LY1, LY2): imported as @shared/<kind>/...+ for k in KINDS {+ write_new(&dir.join("shared").join(k).join(".gitkeep"), "")?;+ }write_new(&dir.join("projects/.gitkeep"), "")?;write_new(&dir.join("taste.ts"), &format!("import {{ taste }} from \"raea/brief\";\n\n// {name}'s house rules: every project here follows them, after the person's own taste.\nexport default taste({{\n title: {:?},\n sections: [],\n}});\n", format!("{name}: house rules")))?;- write_new(&dir.join(".gitattributes"), "media/** filter=lfs diff=lfs merge=lfs -text\nout/** filter=lfs diff=lfs merge=lfs -text\n")?;- commit(dir, &[".raea/workspace", "controllers/.gitkeep", "projects/.gitkeep", "taste.ts", ".gitattributes"], &format!("workspace {name}"))+ write_new(&dir.join(".gitattributes"), GITATTRIBUTES)?;+ let kept: Vec<String> = KINDS.iter().map(|k| format!("shared/{k}/.gitkeep")).collect();+ let mut files: Vec<&str> = vec![".raea/workspace", "projects/.gitkeep", "taste.ts", ".gitattributes"];+ files.extend(kept.iter().map(String::as_str));+ commit(dir, &files, &format!("workspace {name}"))}/// The workspace's projects: (name, path, storage), from .raea/workspace.@@ -327,6 +343,12 @@ pub fn project(args: &[String]) -> R<String> {fn new_project(name: &str, storage: Option<&str>) -> R<String> {let here = std::env::current_dir().map_err(|e| e.to_string())?;let ws = up(&here, ".raea/workspace").ok_or("not in a workspace: raea workspace init NAME makes one")?;+ new_project_in(&ws, name, storage)+}++/// A new project in the workspace at `ws` (the folder holding .raea/workspace).+pub(crate) fn new_project_in(ws: &Path, name: &str, storage: Option<&str>) -> R<String> {+ let ws = ws.to_path_buf();let slugged = slug(name);if slugged.is_empty() {return Err(format!("{name:?} has no letters or digits to name a folder by"));@@ -344,11 +366,15 @@ fn new_project(name: &str, storage: Option<&str>) -> R<String> {std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;write_new(&dir.join("brief.ts"), &format!("import {{ brief }} from \"raea/brief\";\n\nexport default brief({{\n title: {name:?},\n}});\n"))?;write_new(&dir.join("AGENTS.md"), AGENTS_PROJECT)?;- for d in ["media", "brand", "out"] {+ write_new(&dir.join("tsconfig.json"), TSCONFIG_PROJECT)?;+ // the project's layout (docs/layout.feature LY1): a folder for each kind of file, and its renders+ for d in KINDS.iter().chain(["out"].iter()) {write_new(&dir.join(d).join(".gitkeep"), "")?;}let id = register(&ws, &dir, &rel, storage)?;- let files = [".raea/project", "brief.ts", "AGENTS.md", "media/.gitkeep", "brand/.gitkeep", "out/.gitkeep"];+ let kept: Vec<String> = KINDS.iter().chain(["out"].iter()).map(|d| format!("{d}/.gitkeep")).collect();+ let mut files: Vec<&str> = vec![".raea/project", "brief.ts", "AGENTS.md", "tsconfig.json"];+ files.extend(kept.iter().map(String::as_str));if storage == "submodule" {git(&dir, &["init", "-q"])?;commit(&dir, &files, &format!("project {name}"))?;diff --git a/docs/layout.feature b/docs/layout.featurenew file mode 100644index 00000000..da94ac68--- /dev/null+++ b/docs/layout.feature@@ -0,0 +1,97 @@+Feature: One project layout: compositions, components, controllers, assets, artifacts; and the workspace's shared/+ Shane, 11-12: "reorganize the default project organization to remove "parts" and really align around the folders of+ compositions, components, controllers, assets, artifacts. this should be the default, and at the workspace level+ having a library that any project can call upon from those global folders." On naming: "just make sure it doesn't+ get confused with our other concept of libraries" (docs/libraries.feature: indexed media, `raea library`), so the+ workspace's folder is shared/ and its import prefix @shared/. Existing projects move with a command, reviewed+ before they land; `raea part` becomes `raea component`.++ Read 11-12, before any change:+ - `raea project new` (apps/workspace/src/workspace.rs new_project) makes brief.ts, AGENTS.md, media/, brand/, out/.+ Compositions and components are loose .tsx at the project's root, told apart by `raea project scan` (PJ8).+ - Agents made parts/ by hand in stay and orientation (scene pieces); nothing scaffolds it. "Parts" is otherwise+ raea's own sets: `raea part add reel` copies examples/parts/reel into components/reel/ (engine/cli index.ts,+ registry.gen.ts from tools/pack.ts).+ - The workspace root has controllers/ (PJ2) and artifacts/; 11-07 (docs/organize.md) made controllers per project.+ - The engine's loader (engine/modules resolve) takes relative imports inside the space and prebuilt libraries by+ name; anything else is refused (UnknownLibrary, OutsideSpace). PJ8's lint flags a component imported from+ outside the project's folder.++ Built 11-12 (lane layout): LY1 (raea project new and workspace init make the folders, .gitattributes, AGENTS.md+ and the @shared/ tsconfig), LY2 (the loader resolves @shared/, PJ8's lint takes it), LY3's scan and lint and+ controllers over shared/controllers/, and LY4's `raea component` (`raea part` still answers). Still to do: LY3's+ app pages (Compositions, Controllers, Source), LY4's examples/components rename and the guides and skill wording,+ LY5 (`raea project tidy`), LY6.++ The layout:++ <workspace>/+ .raea/workspace, taste.ts, projects/, attachments/ as now+ shared/ what every project in the workspace can call on+ compositions/ components/ controllers/ assets/ artifacts/+ <workspace>/projects/<name>/+ .raea/project, brief.ts, <name>.script.ts, AGENTS.md what the project is (as now, at its root)+ compositions/ what renders: a registerRoot <Composition>, or a default export; versions NAME-v2.tsx+ components/ what compositions import: props as rigs (component-library-first), raea's sets+ controllers/ the project's controllers (PJ2), over shared/controllers/ by id+ assets/ media in: footage, stills, audio, models, fonts, the brand kit (assets/brand/)+ artifacts/ the small React apps agents post to the feed+ out/ renders (LFS, as now)++ Scenario: LY1. A new project and a new workspace have the layout+ When `raea project new NAME` makes a project+ Then its folder has compositions/, components/, controllers/, assets/ and artifacts/ (each kept with a .gitkeep),+ out/, brief.ts and AGENTS.md, and no media/, brand/ or parts/+ And `raea workspace init` makes shared/ with the same five folders, and no root controllers/ or artifacts/+ And .gitattributes keeps assets/** and out/** in LFS (shared/assets/** too)+ And AGENTS.md says where each kind of file goes, in a line each, and that @shared/ is the workspace's+ And `raea init` in a loose folder makes compositions/edit.tsx and components/, not edit.tsx at the root++ Scenario: LY2. A project imports from the workspace's shared/ by @shared/+ Given shared/components/desk.tsx in the workspace+ When a project's composition imports "@shared/components/desk"+ Then the engine's loader resolves it to the workspace's shared/components/desk.tsx (walking up to .raea/workspace),+ as it resolves a relative import, with the same extensions and index files+ And a render, `raea check`, `raea context` and the app's Compositions page all read it the same way+ And TypeScript resolves it too: the project's tsconfig (made by `raea project new`, kept by `raea doctor --fix`)+ maps @shared/* to ../../shared/*, so an editor and tsc follow the import+ And @shared/ outside a workspace is refused with what to do (UnknownLibrary's message names shared/)+ And PJ8's lint no longer flags an @shared/ import; a relative import that climbs out of the project still is,+ with @shared/ as the fix when the file is in shared/++ Scenario: LY3. One reading of the layout, everywhere+ When `raea project scan`, the app's Compositions, Controllers and Source pages, and `raea context` read a project+ Then compositions come from compositions/ and components from components/, each also from shared/ (marked shared)+ And a .tsx elsewhere in the project is still read by what it is (PJ8), and linted as out of place with the folder+ it belongs in as the fix+ And controllers are the project's controllers/ over shared/controllers/ by id (a project's own wins), so the 11-07+ per-project copy is no longer needed: `raea controller ls` says which are shared+ And Source's Assets tab lists assets/ (and shared/assets/), and its Artifacts tab artifacts/ (and shared/artifacts/)+ And an agent's feed_post of an artifact writes it to the project's artifacts/++ Scenario: LY4. `raea component` replaces `raea part`+ When `raea component list` or `raea component add reel [--shared]` runs+ Then it lists and copies raea's sets as `raea part` did, into components/<set>/ (or shared/components/<set>/)+ And examples/parts is examples/components, and registry.gen.ts is packed from it+ And `raea part ...` still works for this release, saying once that it's `raea component` now+ And the guides, the raea skill and AGENTS.md say components, never parts++ Scenario: LY5. An existing project moves into the layout with one command+ When `raea project tidy [NAME] [--dry-run]` runs on a project in the old layout+ Then each file goes where its kind belongs, as the scan reads it: compositions (and their versions) to+ compositions/, the .tsx they import to components/ (parts/ and its subfolders as components/<same path>),+ controllers to controllers/, media/ and brand/ to assets/ (assets/brand/), artifacts to artifacts/+ And brief.ts, scripts, notes (.md) and out/ stay where they are; anything it can't place is listed, not moved+ And every import that names a moved file is rewritten (relative paths, media imports), and so are the paths the+ project's feed items, render manifests and checks name+ And --dry-run prints the moves and rewrites and changes nothing+ And it proves the move before it commits: the scan has no new lint, tsc passes if it passed before, and each+ composition's first frame renders as it did (raea check --quick); a failure undoes the move+ And it is one commit per project, moves as renames (git mv), so history follows each file+ And the workspace's root controllers/ and artifacts/ move to shared/ the same way (`raea workspace tidy`)++ Scenario: LY6. The Raea workspace is tidied+ Given the Raea workspace (~/Documents/raea/raea): stay, orientation, v0-1-launch and two untitled projects+ When each is tidied, its --dry-run read by Shane first+ Then each project's feed still opens with its items playing, its compositions render, and nothing is lost+ And `raea doctor` in an old-layout project says to run `raea project tidy`diff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rsindex 73aff44d..17175b04 100644--- a/engine/cli/src/cli.rs+++ b/engine/cli/src/cli.rs@@ -138,7 +138,7 @@ pub fn run(args: &[String]) -> R<String> {let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|plan|controller] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, plan.ts, controllers/ID.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects and controllers under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; split and join keep its history)\n raea controller ls [--json] | raea controller get PATH [--json] | raea controller set PATH VALUE [--project] [--by NAME] | raea controller write FILE.ts [--by NAME] | raea controller rm ID [--by NAME] (the workspace's controllers, controllers/ID.ts; PATH is controller.group.field; every change a commit)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);let (export_game, capcut, scene, physics, splat) = (raea_app_game::USAGE, raea_app_capcut::USAGE, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE);let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE);- return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea part list | raea part add NAME ... [--force] (a ready part copied into components/, yours to change)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {capcut}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)"));+ return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea component list | raea component add NAME ... [--shared] [--force] | raea part list | raea part add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; raea part is its old name)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {capcut}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)"));}// `--version`: the release's version, which a skill's front matter names (docs/skills.feature SK6)if args.len() == 1 && matches!(args[0].as_str(), "--version" | "-V") {diff --git a/engine/cli/src/index.ts b/engine/cli/src/index.tsindex 33b853e9..c8e1b914 100644--- a/engine/cli/src/index.ts+++ b/engine/cli/src/index.ts@@ -72,7 +72,7 @@ A video edit as a React + TypeScript project, rendered by raea.- edit.tsx: the composition. Change anything: layout, timing, which component plays when.- cuts.ts: the clips (\`raea cut\` writes it, with cuts.json and words.json beside it; re-run it rather than editing- by hand, or captions and checks lose their timing). components/: parts you added (\`raea part add\`), yours to change.+ by hand, or captions and checks lose their timing). components/: components you added (\`raea component add\`), yours to change.- brand/brand.css: the brand's tokens (\`raea brand DOMAIN\` reads them from the brand's site). edit.tsx loads them with the project'sTailwind: \`<style>{css}</style>\`, css from "./styles.gen" (raea render writes it). Style only with the brandclasses: colour text-brand-accent, bg-brand-accent, bg-brand-surface (bg-brand-bg), text-brand-on-surface,@@ -105,6 +105,14 @@ Composition: registerRoot(() => <Composition id component width height fps duratNot there: React hooks come from "react" (useMemo, useState), not from raea.`;+/** The workspace a folder is in: the nearest folder at or above it holding .raea/workspace, through the shell's fs. */+async function workspaceAbove(c: Ctx, from: string): Promise<string | undefined> {+ for (let d = from.replace(/\/$/, ""); d; d = d.slice(0, d.lastIndexOf("/"))) {+ if (await c.fs.exists(`${d}/.raea/workspace`)) return d;+ }+ return undefined;+}+/** The `raea` command's handler (the shell wraps it with just-bash's defineCommand, so this package needs no dependency). */export function raeaHandler(host?: Host, engine?: Engine) {return async (args: string[], ctx: unknown) => {@@ -119,10 +127,10 @@ export function raeaHandler(host?: Host, engine?: Engine) {if (!engine) throw new Error(`raea ${a[0]} is the engine's (the native raea), and this shell has none`);return engine(a, ctx);};- // a set is a folder of examples/parts (`raea part add reel` copies it whole); a part is one file of a set that says- // `// raea part add NAME: ...` at its top, and copies alone- const said = (src: string) => (/^\/\/ raea part add [\w-]+: (.*)$/m.exec(src)?.[1] ?? "").split(". ")[0];- const single = (n: string) => Object.values(REGISTRY).map((set) => set[`${n}.tsx`]).find((src) => src && new RegExp(`^// raea part add ${n}:`, "m").test(src));+ // a set is a folder of examples/components (`raea component add reel` copies it whole); a component is one file of a+ // set that says `// raea component add NAME: ...` at its top (`raea part add`, before 11-12), and copies alone+ const said = (src: string) => (/^\/\/ raea (?:component|part) add [\w-]+: (.*)$/m.exec(src)?.[1] ?? "").split(". ")[0];+ const single = (n: string) => Object.values(REGISTRY).map((set) => set[`${n}.tsx`]).find((src) => src && new RegExp(`^// raea (?:component|part) add ${n}:`, "m").test(src));const parts = () =>Object.entries(REGISTRY).flatMap(([set, files]) => [@@ -169,42 +177,57 @@ export function raeaHandler(host?: Host, engine?: Engine) {} else await put("AGENTS.md", NOTES);return out(made.length ? `made ${made.join(", ")}\n` : "nothing to make: the project's files are here\n");}- case "part": {- if (args[1] === "list" || args[1] === undefined) return out(parts());- if (args[1] !== "add") return out("", 2, "raea part list | raea part add NAME ... [--force]\n");+ // `raea component` copies raea's sets and components into the project's components/ (docs/layout.feature LY4),+ // or with --shared into the workspace's shared/components/, which every project imports as @shared/components/+ // `raea part` was its name until 11-12, and still works, saying so+ case "part":+ case "component": {+ const was = args[0] === "part" ? "(raea part is raea component now)\n" : "";+ if (args[1] === "list" || args[1] === undefined) return out(parts(), 0, was);+ if (args[1] !== "add") return out("", 2, `${was}raea component list | raea component add NAME ... [--shared] [--force]\n`);const names = clean(args.slice(2));- if (!names.length) return out("", 2, "raea part add NAME ... (raea part list shows them)\n");+ if (!names.length) return out("", 2, `${was}raea component add NAME ... (raea component list shows them)\n`);const force = args.includes("--force");- await c.fs.mkdir(p("components"), { recursive: true });+ let home = "components";+ // what imports it: a composition in compositions/ reaches ../components/, one at the root ./components/+ let from = (await c.fs.exists(p("compositions"))) ? "../components" : "./components";+ if (args.includes("--shared")) {+ const ws = await workspaceAbove(c, c.cwd);+ if (!ws) return out("", 1, `${was}raea component add --shared: no workspace above ${c.cwd} (no .raea/workspace): add it to the project instead\n`);+ home = `${ws}/shared/components`;+ from = "@shared/components";+ }+ await c.fs.mkdir(p(home), { recursive: true });const done: string[] = [];+ const shown = (rel: string) => (home.startsWith("/") ? `shared/components/${rel.slice(home.length + 1)}` : rel);for (const n of names) {const set = REGISTRY[n];if (set) {// a set is the project's own once copied: never overwritten unasked, and said so loudly- const dir = `components/${n}`;- if (!force && (await c.fs.exists(p(dir)))) return out(done.join(""), 1, `raea part add: ${dir}/ is already here (yours now; --force replaces its files)\n`);+ const dir = `${home}/${n}`;+ if (!force && (await c.fs.exists(p(dir)))) return out(done.join(""), 1, `raea component add: ${shown(dir)}/ is already here (yours now; --force replaces its files)\n`);await c.fs.mkdir(p(dir), { recursive: true });for (const [f, src] of Object.entries(set)) await c.fs.writeFile(p(`${dir}/${f}`), src);- done.push(`${dir}/ ${Object.keys(set).length} files; import from "./${dir}"\n`);+ done.push(`${shown(dir)}/ ${Object.keys(set).length} files; import from "${from}/${n}"\n`);continue;}const src = single(n);- if (!src) return out(done.join(""), 1, `raea part add: no part or set "${n}" (raea part list shows them)\n`);- const dest = p(`components/${n}.tsx`);+ if (!src) return out(done.join(""), 1, `raea component add: no component or set "${n}" (raea component list shows them)\n`);+ const dest = p(`${home}/${n}.tsx`);if (!force && (await c.fs.exists(dest))) {- done.push(`components/${n}.tsx is already here (yours now; --force replaces it)\n`);+ done.push(`${shown(`${home}/${n}.tsx`)} is already here (yours now; --force replaces it)\n`);continue;}await c.fs.writeFile(dest, src);- done.push(`components/${n}.tsx import it: import ${n.replace(/(^|-)(\w)/g, (_, __, ch) => ch.toUpperCase())} from "./components/${n}";\n`);+ done.push(`${shown(`${home}/${n}.tsx`)} import it: import ${n.replace(/(^|-)(\w)/g, (_, __, ch) => ch.toUpperCase())} from "${from}/${n}";\n`);}- return out(done.join(""));+ return out(done.join(""), 0, was);}- // `add` is npm packages (the engine's package manager); a registry part's name is pointed at `raea part add`+ // `add` is npm packages (the engine's package manager); a registry component's name is pointed at `raea component add`case "add": {const r = await native();const part = clean(args.slice(1)).find((n) => REGISTRY[n] || single(n));- return r.exitCode && part ? { ...r, stderr: r.stderr + `(a raea part? raea part add ${part})\n` } : r;+ return r.exitCode && part ? { ...r, stderr: r.stderr + `(a raea component? raea component add ${part})\n` } : r;}case "cut": {const spans: number[][] = [];diff --git a/engine/cli/src/tests.rs b/engine/cli/src/tests.rsindex d03f0df3..c86f031a 100644--- a/engine/cli/src/tests.rs+++ b/engine/cli/src/tests.rs@@ -8,6 +8,9 @@ fn shell_runs() {// `raea help` lists SHELL's verbs (help_lists_every_verb)let parts = shell(&["part".to_string(), "list".to_string()]).unwrap();assert!(parts.contains("captions"), "{parts}");+ // raea component is its name now (docs/layout.feature LY4); raea part still answers+ let components = shell(&["component".to_string(), "list".to_string()]).unwrap();+ assert!(components.contains("captions") && components.contains("into components/reel/"), "{components}");}#[test]@@ -68,6 +71,7 @@ fn a_verb_refuses_what_it_doesnt_take() {&["song", "s.wav", "--plot", "p.png", "--backend", "x"],&["cut", "take.mp4", "one line", "another", "--append"],&["part", "add", "captions", "face-frame", "--force"],+ &["component", "add", "reel", "--shared", "--force"],&["mezz", "--check", "a.mov", "b.mov"],&["traces", "show", "last"],&["media", "ffmpeg", "-i", "x", "--anything"],diff --git a/engine/cli/src/verbs.rs b/engine/cli/src/verbs.rsindex a0941fb0..d073a123 100644--- a/engine/cli/src/verbs.rs+++ b/engine/cli/src/verbs.rs@@ -96,7 +96,7 @@ pub fn mezz(args: &[String]) -> R<String> {/// The agent shell's own verbs (engine/cli/src/index.ts) this binary runs; the rest come one by one (docs/agent-surfaces.md)-pub const SHELL: &[&str] = &["init", "cut", "frame", "part", "brand", "library", "show"];+pub const SHELL: &[&str] = &["init", "cut", "frame", "component", "part", "brand", "library", "show"];/// One of SHELL's verbs: @raea/cli's handler, run by engine/cli/src/native.ts on raea's JavaScriptCore with Node's core, so the/// verb's one source is its TypeScript. native.ts answers the host's ops it needs, and runs this binary for the engine's verbs.diff --git a/engine/modules/src/lib.rs b/engine/modules/src/lib.rsindex 93832511..97221bd6 100644--- a/engine/modules/src/lib.rs+++ b/engine/modules/src/lib.rs@@ -92,6 +92,13 @@ impl std::fmt::Display for Refusal {}const EXTS: [&str; 5] = ["tsx", "ts", "jsx", "js", "mjs"];+/// The prefix a project imports its workspace's shared files by (docs/layout.feature LY2): @shared/components/desk.+pub const SHARED: &str = "@shared/";++/// The workspace a folder is in: the nearest folder at or above it holding .raea/workspace.+fn workspace_of(dir: &Path) -> Option<PathBuf> {+ dir.ancestors().find(|d| d.join(".raea/workspace").is_file()).map(Path::to_path_buf)+}const MEDIA: [&str; 12] = ["mp4", "mov", "m4v", "webm", "m4a", "mp3", "wav", "aac", "png", "jpg", "jpeg", "svg"];pub struct Loader {@@ -125,6 +132,9 @@ impl Loader {/// An import (`specifier`) from a module (`referrer`: a ModuleId's url, or a path for the entry) to the module it names.pub fn resolve(&self, specifier: &str, referrer: &str) -> Result<ModuleId, Refusal> {+ if let Some(rest) = specifier.strip_prefix(SHARED) {+ return self.shared(rest, specifier, referrer);+ }if !(specifier.starts_with("./") || specifier.starts_with("../") || specifier.starts_with('/') || specifier.starts_with("file://")) {if self.prebuilt.contains_key(specifier) {return Ok(ModuleId::Prebuilt(specifier.to_string()));@@ -140,10 +150,30 @@ impl Loader {let base = base.canonicalize().unwrap_or(base);let raw = specifier.strip_prefix("file://").unwrap_or(specifier);let want = lexical(&if raw.starts_with('/') { PathBuf::from(raw) } else { base.join(raw) });- if !want.starts_with(&self.root) {- return Err(Refusal::new(RefusalKind::OutsideSpace, format!("`{specifier}` (imported by {referrer}) is outside the space: import files inside {}", self.root.display()), Some(specifier), Some(referrer)));+ // inside the space, or inside its workspace's shared/ (a file there imports its neighbours relatively)+ let shared = workspace_of(&self.root).map(|w| w.join("shared"));+ if !want.starts_with(&self.root) && !shared.as_ref().is_some_and(|s| want.starts_with(s)) {+ return Err(Refusal::new(RefusalKind::OutsideSpace, format!("`{specifier}` (imported by {referrer}) is outside the space: import files inside {}, and the workspace's shared files as @shared/<kind>/<name>", self.root.display()), Some(specifier), Some(referrer)));+ }+ self.file(want, specifier, referrer)+ }++ /// `@shared/<kind>/<name>`: the workspace's shared/ (docs/layout.feature LY2), found by walking up from the space to+ /// the folder holding .raea/workspace, resolved as a relative import is.+ fn shared(&self, rest: &str, specifier: &str, referrer: &str) -> Result<ModuleId, Refusal> {+ let Some(ws) = workspace_of(&self.root) else {+ return Err(Refusal::new(RefusalKind::UnknownLibrary, format!("`{specifier}` (imported by {referrer}) names the workspace's shared/, and {} is in no workspace (no .raea/workspace above it): copy the file into the project, or `raea workspace adopt` the folder", self.root.display()), Some(specifier), Some(referrer)));+ };+ let dir = ws.join("shared");+ let want = lexical(&dir.join(rest));+ if !want.starts_with(&dir) {+ return Err(Refusal::new(RefusalKind::OutsideSpace, format!("`{specifier}` (imported by {referrer}) climbs out of the workspace's shared/"), Some(specifier), Some(referrer)));}- // as written, then with each extension, then as a folder's index+ self.file(want, specifier, referrer)+ }++ /// A file by its path: as written, then with each extension, then as a folder's index.+ fn file(&self, want: PathBuf, specifier: &str, referrer: &str) -> Result<ModuleId, Refusal> {let mut tries = vec![want.clone()];tries.extend(EXTS.iter().map(|e| want.with_extension(e)));tries.extend(EXTS.iter().map(|e| want.join(format!("index.{e}"))));diff --git a/engine/modules/tests/loader.rs b/engine/modules/tests/loader.rsindex d4826509..4c7cb2b0 100644--- a/engine/modules/tests/loader.rs+++ b/engine/modules/tests/loader.rs@@ -92,3 +92,33 @@ fn a_parse_error_says_where() {assert!(e.contains("bad.tsx") && e.contains("can't be parsed"), "{e}");}++#[test]+fn shared_imports_resolve_to_the_workspaces_shared_folder() {+ // docs/layout.feature LY2: a project imports its workspace's shared/ by @shared/, and a shared file its neighbours+ let w = space("shared", &[+ (".raea/workspace", "[workspace]\n\tname = W\n"),+ ("shared/components/desk.tsx", "import { leg } from \"./leg\";\nexport default () => leg;"),+ ("shared/components/leg.ts", "export const leg = 1;"),+ ("shared/components/props/index.ts", "export const p = 1;"),+ ("projects/a/compositions/main.tsx", ""),+ ]);+ let root = w.canonicalize().unwrap();+ let l = Loader::new(&w.join("projects/a"), libs()).unwrap();+ let entry = root.join("projects/a/compositions/main.tsx").display().to_string();+ assert_eq!(l.resolve("@shared/components/desk", &entry).unwrap(), ModuleId::File(root.join("shared/components/desk.tsx")));+ assert_eq!(l.resolve("@shared/components/props", &entry).unwrap(), ModuleId::File(root.join("shared/components/props/index.ts")));+ let desk = root.join("shared/components/desk.tsx").display().to_string();+ assert_eq!(l.resolve("./leg", &desk).unwrap(), ModuleId::File(root.join("shared/components/leg.ts")));+ // a relative climb to another project is still outside, and says @shared/+ let other = l.resolve("../../b/x", &entry).unwrap_err().message;+ assert!(other.contains("outside the space") && other.contains("@shared/"), "{other}");+ assert!(l.resolve("@shared/../projects/b/x", &entry).unwrap_err().message.contains("climbs out"));+ assert!(l.resolve("@shared/components/nope", &entry).unwrap_err().message.contains("isn't there"));+ // with no workspace above, @shared/ says so+ let loose = space("shared-loose", &[("edit.tsx", "")]);+ let l = Loader::new(&loose, libs()).unwrap();+ let e = loose.join("edit.tsx").display().to_string();+ let r = l.resolve("@shared/components/desk", &e).unwrap_err();+ assert!(r.kind == RefusalKind::UnknownLibrary && r.message.contains("in no workspace"), "{}", r.message);+}