Skip to content

Commit 3f26009

Browse files
authored
Give each .rx module its own stylesheet; find a cold dependency's program (#66)
Under vite dev, a <style> edit in a non-entry module never reached the page, because the program's whole stylesheet came only on the entry and the plugin recompiles CSS per file. Under Vitest's fsModuleCache, a cached entry left builds empty, so the next changed dependency threw "no program built so far contains it".
1 parent 588582b commit 3f26009

4 files changed

Lines changed: 95 additions & 15 deletions

File tree

‎compiler/src/app.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ pub fn target(name: &str) -> Target {
2323
}
2424
}
2525

26-
/// `{entry, css, modules: {path: {code, map}}}`, or `{diagnostics: [...]}` / `{error}`. `entry` is an absolute path.
26+
/// `{entry, css, modules: {path: {code, map, css}}}` (the program's stylesheet, and each module's own), or `{diagnostics: [...]}` / `{error}`. `entry` is an absolute path.
2727
/// `spa`: a client-only build, checked under 08 CN-3d.
2828
pub fn app(entry: &str, target: Target, module_name: &str, spa: bool) -> Value {
2929
// module keys are POSIX paths (`modules::join_path`); Windows takes `D:/a/b.rx` as it takes `D:\a\b.rx`
@@ -49,7 +49,7 @@ pub fn app(entry: &str, target: Target, module_name: &str, spa: bool) -> Value {
4949
let path = &out.paths[name];
5050
let text = read_disk(path).unwrap_or_default();
5151
let l = lower_view(module, path, target, module_name, Some((path, &text))).map_err(|e| json!({ "error": e }))?;
52-
modules.insert(path.clone(), json!({ "code": l.code, "map": l.map }));
52+
modules.insert(path.clone(), json!({ "code": l.code, "map": l.map, "css": out.module_css[name] }));
5353
}
5454
Ok(json!({ "entry": set.entry, "css": out.css, "modules": modules }))
5555
})()

‎compiler/src/emit.rs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,8 @@ pub struct Compiled {
180180
pub entry: String,
181181
/// CSS-4: the modules' stylesheets, beside their JavaScript
182182
pub css: String,
183+
/// CSS-4: each module's own stylesheet, by its output name
184+
pub module_css: IndexMap<String, String>,
183185
}
184186

185187
/// 09 MO-1: one ES module per `.rx` module. A dependency's module is a factory over the app (`__rt.module` runs it once per
@@ -197,8 +199,10 @@ pub fn compile_linked(set: &ModuleSet, extra: &[Vec<Stmt>], by_source: bool) ->
197199
g.by_source = by_source;
198200
let mut files = IndexMap::new();
199201
let mut paths = IndexMap::new();
202+
let mut module_css = IndexMap::new();
200203
for path in &set.order {
201204
let p = &set.programs[path];
205+
let css0 = g.css.len();
202206
g.begin_module(path, &p.decls);
203207
let mut deps: Vec<&str> = vec![];
204208
for d in &p.decls {
@@ -232,10 +236,11 @@ pub fn compile_linked(set: &ModuleSet, extra: &[Vec<Stmt>], by_source: bool) ->
232236
fbody.append(&mut inner);
233237
body.push(S::ExportDefault(Func { name: Some("module".into()), params: vec![P::Id("__rt".into())], directives: vec![], body: fbody, is_async: false, generator: false }));
234238
}
239+
module_css.insert(g.out(path), g.css[css0..].join("\n"));
235240
files.insert(g.out(path), body);
236241
paths.insert(g.out(path), path.clone());
237242
}
238-
Ok(Compiled { files, paths, entry: g.out(&set.entry), css: g.css.join("\n") })
243+
Ok(Compiled { files, paths, entry: g.out(&set.entry), css: g.css.join("\n"), module_css })
239244
}
240245

241246
struct Gen<'p> {

‎compiler/test/vite.mjs‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,9 +118,51 @@ if (!filter || "shared".includes(filter)) { // two programs on one page, shari
118118
if (!filter || "todo".includes(filter)) { // the dev server: modules transformed on request
119119
const dir = project("todo-dev", "todo.rx");
120120
const server = await vite.createServer(config(dir, "todo.rx")); await server.listen(0);
121-
await drive("todo (dev)", `http://127.0.0.1:${server.httpServer.address().port}/`, todo);
121+
await drive("todo (dev)", server.resolvedUrls.local[0], todo);
122122
await server.close();
123123
}
124+
if (!filter || "styles".includes(filter)) { // CSS-4 under the dev server: a dependency's <style> edit reaches the page
125+
const dir = project("styles-dev", "styled/main.rx");
126+
mkdirSync(path.join(dir, "src/styled"));
127+
writeFileSync(path.join(dir, "src/styled/main.rx"), `import { Badge } from "./badge.rx"\n\nexport default component Main() {\n <main><Badge /></main>\n}\n`);
128+
const badge = path.join(dir, "src/styled/badge.rx");
129+
const style = color => `export component Badge() {\n <style>\n .badge { color: ${color} }\n </style>\n <p class="badge">badge</p>\n}\n`;
130+
writeFileSync(badge, style("rgb(0, 0, 255)"));
131+
const server = await vite.createServer(config(dir, "styled/main.rx")); await server.listen(0);
132+
const url = server.resolvedUrls.local[0];
133+
const color = page => page.$eval(".badge", e => getComputedStyle(e).color);
134+
const until = async (page, want, what) => {
135+
for (let i = 0; i < 40 && await color(page).catch(() => "") !== want; i++) await page.waitForTimeout(100);
136+
const got = await color(page).catch(e => e.message.split("\n")[0]); if (got !== want) throw new Error(`${what}: color ${got}, not ${want}`);
137+
};
138+
await drive("styles (dev)", url, async page => {
139+
await until(page, "rgb(0, 0, 255)", "first load");
140+
writeFileSync(badge, style("rgb(255, 0, 0)"));
141+
await until(page, "rgb(255, 0, 0)", "after the edit");
142+
await page.reload(); await until(page, "rgb(255, 0, 0)", "after a reload");
143+
const fresh = await browser.newPage();
144+
try { await fresh.goto(url); await until(fresh, "rgb(255, 0, 0)", "in a new page"); } finally { await fresh.close(); }
145+
});
146+
await server.close();
147+
}
148+
if (!filter || "cold".includes(filter)) { // a dependency asked for before its entry, as Vitest's `fsModuleCache` leaves it
149+
const { default: rx } = await import(pathToFileURL(path.join(pkg, "vite.mjs")).href);
150+
const root = project("cold", "shop/main.rx"), catalog = path.join(root, "src/shop/catalog.rx");
151+
const ctx = (id, moduleId) => ({ id, moduleId, root, ssr: false, solid: { generate: "dom", hydratable: false }, addWatchFile() {} });
152+
try {
153+
// a commented-out import is not an edge: read as one, it would make main.rx look imported and leave no entry
154+
writeFileSync(catalog, readFileSync(catalog, "utf8") + `\n// import { x } from "./main.rx"\n`);
155+
const warm = rx(); warm.compile("", ctx(path.join(root, "src/shop/main.rx"), path.join(root, "src/shop/main.rx")));
156+
const want = warm.compile("", ctx(catalog, `${catalog}?rx-dep`)).code;
157+
const got = rx().compile("", ctx(catalog, `${catalog}?rx-dep`)).code;
158+
if (got !== want) throw new Error("the dependency compiled cold differs from the one compiled after its entry");
159+
writeFileSync(catalog, readFileSync(catalog, "utf8") + "\nexport bad = missingName\n");
160+
let report = "";
161+
try { rx().compile("", ctx(catalog, `${catalog}?rx-dep`)); } catch (e) { report = e.message; }
162+
if (!/catalog\.rx:\d+(:\d+)?: error /.test(report)) throw new Error(`a cold dependency that does not compile reports ${JSON.stringify(report.slice(0, 200))}`);
163+
pass++; console.log("✓ cold dependency: compiled from the program that holds it, or that program's diagnostics");
164+
} catch (e) { fail++; console.log(`✗ cold dependency: ${e.message.split("\n")[0]}`); }
165+
}
124166
await browser.close();
125167
console.log(`\n${pass} pass, ${fail} fail (vite ${vite.version}, @solidjs/vite-plugin ${JSON.parse(readFileSync(path.join(pluginDir, "package.json"), "utf8")).version})`);
126168
process.exit(fail ? 1 : 0);

‎compiler/vite.mjs‎

Lines changed: 44 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
// names it explicitly.
44
//
55
// The crate (its Node-API build, `src/node.rs`: what `rxc app` does) already hands each module to Solid's compiler
6-
// (spec/11 CP-1), so a `.rx` module comes back as Solid's output for the environment's `generate`, with its source map onto the `.rx` and, on a
7-
// program's entry, the program's stylesheet. Solid's plugin then takes it the way it takes lowered `.tsrx`: primitive
6+
// (spec/11 CP-1), so a `.rx` module comes back as Solid's output for the environment's `generate`, with its source map onto the `.rx` and
7+
// its own stylesheet. Solid's plugin then takes it the way it takes lowered `.tsrx`: primitive
88
// names, `lazy()`, the HMR refresh pass, server functions (12 SF-7a), the stylesheet as a CSS module.
99
//
1010
// Entries find themselves. JavaScript imports only a program's entry (its default export mounts the app); an `.rx`
@@ -13,7 +13,7 @@
1313
// changes. The crate's output imports its dependencies as `./x.rx?rx-dep`, and a dependency is served from the build
1414
// of a program that contains it. A module several programs share is one module: its instance is keyed by its factory
1515
// (11 CP-4b `module`), not by its place in a program.
16-
import { existsSync, statSync } from "node:fs";
16+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
1717
import { createRequire } from "node:module";
1818
import path from "node:path";
1919
import { fileURLToPath } from "node:url";
@@ -35,6 +35,29 @@ const isDep = moduleId => new URLSearchParams(moduleId.split("?")[1] ?? "").has(
3535
// `import __m0 from "./catalog.rx";` → `"./catalog.rx?rx-dep"` (one line each: the module's map is by line, CP-1c)
3636
const tagDeps = code => code.replace(/^(import \w+ from ")(\.{1,2}\/[^"?]*\.rx)(";?)$/gm, `$1$2?${DEP}$3`);
3737

38+
const RX_IMPORT = /^import\b[^"']*?\bfrom\s+(["'])(\.{1,2}\/[^"'?]*\.rx)\1/gm;
39+
/** The `.rx` files under `root` from which `file` is reached by imports: first those no other `.rx` file imports. */
40+
function entriesOf(file, root) {
41+
const importers = new Map();
42+
const walk = dir => {
43+
for (const e of readdirSync(dir, { withFileTypes: true })) {
44+
if (e.name === "node_modules" || e.name.startsWith(".")) continue;
45+
const p = path.join(dir, e.name);
46+
if (e.isDirectory()) walk(p);
47+
else if (e.name.endsWith(".rx")) for (const [, , spec] of readFileSync(p, "utf8").matchAll(RX_IMPORT)) {
48+
const dep = path.resolve(path.dirname(p), spec);
49+
importers.set(dep, [...(importers.get(dep) ?? []), p]);
50+
}
51+
}
52+
};
53+
walk(root);
54+
const seen = new Set([file]);
55+
for (const f of seen) for (const i of importers.get(f) ?? []) seen.add(i);
56+
seen.delete(file);
57+
const top = f => !importers.has(f);
58+
return [...seen].sort().sort((a, b) => top(b) - top(a));
59+
}
60+
3861
/** @returns {import("@solidjs/vite-plugin").Frontend} */
3962
export default function rx() {
4063
const builds = new Map(); // entry\0target\0moduleName\0spa → { entry, target, moduleName, spa, out, stamps }
@@ -50,28 +73,38 @@ export default function rx() {
5073
builds.set(key, b);
5174
return b;
5275
}
76+
const built = (file, target, moduleName, spa) =>
77+
[...builds.values()].filter(b => b.target === target && b.moduleName === moduleName && b.spa === spa && b.out.modules?.[file]);
5378
/** A dependency: from a build of a program that has it, rebuilt if that program changed. */
54-
function containing(file, target, moduleName, spa) {
55-
const has = [...builds.values()].filter(b => b.target === target && b.moduleName === moduleName && b.spa === spa && b.out.modules?.[file]);
79+
function containing(file, target, moduleName, spa, root) {
80+
const has = built(file, target, moduleName, spa);
5681
const b = has.find(fresh) ?? has[0];
57-
if (!b) throw new Error(`${file} is imported as an .rx dependency, but no program built so far contains it`);
58-
return build(b.entry, target, moduleName, spa);
82+
if (b) return build(b.entry, target, moduleName, spa);
83+
// the entry's compile was skipped (Vitest's `fsModuleCache` served it), so find the program from the files
84+
let failed;
85+
for (const entry of entriesOf(file, root)) {
86+
const found = build(entry, target, moduleName, spa);
87+
if (found.out.modules?.[file]) return found;
88+
if (!failed && found.out.diagnostics) failed = found; // the program holds it but does not compile: report why
89+
}
90+
if (failed) return failed;
91+
throw new Error(`${file} is imported as an .rx dependency, but no program under ${root} contains it`);
5992
}
6093
return {
61-
compile(_source, { id, moduleId, solid, addWatchFile }) {
94+
compile(_source, { id, moduleId, root, solid, addWatchFile }) {
6295
const file = path.resolve(id);
6396
const target = solid.generate === "ssr" ? "ssr" : solid.generate === "universal" ? "universal" : "dom";
6497
const moduleName = solid.moduleName ?? "@solidjs/web";
6598
// 08 CN-3d: a client-only build (no SSR, nothing hydrates) has nothing to show on a first load nothing holds
6699
const spa = target === "dom" && solid.hydratable === false;
67100
const dep = isDep(moduleId);
68-
const { entry, out } = dep ? containing(file, target, moduleName, spa) : build(file, target, moduleName, spa);
101+
const { out } = dep ? containing(file, target, moduleName, spa, path.resolve(root ?? process.cwd())) : build(file, target, moduleName, spa);
69102
if (out.diagnostics) throw new Error(report(out.diagnostics));
70103
if (out.error) throw new Error(out.error);
71104
const m = out.modules[file];
72105
for (const p of Object.keys(out.modules)) if (p !== file) addWatchFile(p);
73-
// CSS-4: the program's stylesheet, linked once, from its entry
74-
return { code: tagDeps(m.code), map: m.map, css: !dep && file === entry ? out.css : "" };
106+
// CSS-4: each module links its own stylesheet, so a module several programs share links it once
107+
return { code: tagDeps(m.code), map: m.map, css: m.css ?? "" };
75108
},
76109
};
77110
}

0 commit comments

Comments
 (0)