diff --git a/CHANGELOG.md b/CHANGELOG.md index ccafe60d..c8ce0494 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- An editor's source-tagging plugin runs natively in `oj dev` (the `lovable-tagger` package's `lovable-plugin`, 1.3.x, is the one oj knows). Config extraction asks the instance what it does, and oj does it: `react/jsx-dev-runtime` is answered with the plugin's own module, served at Vite's URL for its virtual id and compiled like any module so its import of the real runtime reaches the pre-bundle; and the app's resolved Tailwind theme is written to `src/tailwind.config.lov.json` at boot and when `tailwind.config.ts` or a v4 CSS entry changes, with the app's own `@tailwindcss/node` (v4) or esbuild and `tailwindcss/resolveConfig` (v3), off the boot's path. The plugin host leaves the plugin out, so an app whose other plugins are native (React's) boots no host at all. An instance with a hook oj does not know, and every build, keep the host as before. + ### Changed - The goldens and the TanStack Start fixture (`e2e/fixtures/start-app`) are recorded from Vite 8.4.0, the release, in place of 8.4.0-beta.1; rolldown stays 1.3.2, the crate oj builds with (8.4.0 declares `~1.3.2`; 8.4.1 declares `~1.3.4`, whose Rust crates are not published, and its build import analysis hands rolldown a field 1.3.2 rejects). Recorded from `/tmp`, so a recording carries no path depth of the machine it was made on. diff --git a/crates/oj_config/src/schema.rs b/crates/oj_config/src/schema.rs index 7eb5e8ef..67dd025c 100644 --- a/crates/oj_config/src/schema.rs +++ b/crates/oj_config/src/schema.rs @@ -91,6 +91,36 @@ pub struct OjConfig { /// `recordStartImportProtection` writes. #[serde(skip)] pub vite_start_import_protection: Option, + /// The config's source-tagging plugin (an editor's), from extraction + /// (not a config key): what oj does in its place in a serve. + #[serde(skip)] + pub vite_source_tagging: Option, +} + +/// What a config's source-tagging plugin does in a serve, as config +/// extraction asked the instance (native-plugins.mjs `isSourceTaggingPlugin`): +/// oj serves the module and writes the theme itself and hosts no plugin for +/// it. +#[derive(Debug, Default, Clone, PartialEq, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct SourceTagging { + /// The package the plugin ships in, whose own dependencies its theme + /// tools resolve from. + pub package: Option, + /// The module it answers `react/jsx-dev-runtime` with, from every + /// importer but that module: its id (a `\0`-prefixed virtual id) and + /// its code. None: the feature is off (its `resolveId` passed). + pub jsx_dev_runtime: Option, + /// It writes the app's resolved Tailwind theme to + /// `src/tailwind.config.lov.json` at boot and on a Tailwind config change. + pub tailwind_theme: bool, +} + +/// A virtual module a plugin answers a specifier with: its id and its code. +#[derive(Debug, Default, Clone, PartialEq, Deserialize)] +pub struct JsxDevRuntime { + pub id: String, + pub code: String, } /// Vite's `worker` block, the part a build's worker bundles take. diff --git a/crates/oj_server/src/assets/native-plugins.mjs b/crates/oj_server/src/assets/native-plugins.mjs index c32238d2..357d6267 100644 --- a/crates/oj_server/src/assets/native-plugins.mjs +++ b/crates/oj_server/src/assets/native-plugins.mjs @@ -45,6 +45,46 @@ export const OJ_NATIVE_PLUGIN_NAMES = new Set([ // worker they spawn throws asynchronously; skip them outright. export const OJ_UNSUPPORTED_PLUGIN_NAMES = new Set(["vite-plugin-checker"]); +// An editor's source-tagging plugin: a `pre` plugin whose work in a serve is +// two things oj does itself. It answers `react/jsx-dev-runtime` with a +// virtual module wrapping React's jsxDEV, which records each element's source +// on its DOM node for the editor (resolveId + load), and it writes the app's +// resolved Tailwind theme to `src/tailwind.config.lov.json` at boot and when +// the Tailwind config changes, for the editor's color picker (buildStart + +// configureServer). Known by plugin name, with the package the plugin ships +// in (where its own tools, esbuild and tailwindcss, resolve from). Config +// extraction asks the instance what it does (`sourceTagging` in +// vite-extract.mjs); the dev server serves the module and writes the file +// (oj_server's source_tagging). Only an instance with exactly these hooks is +// taken over: one with more (a later version's transform) stays hosted, and a +// build hosts it as before. +export const SOURCE_TAGGING_PLUGINS = new Map([["lovable-plugin", "lovable-tagger"]]); +const SOURCE_TAGGING_PLUGIN_HOOKS = new Set([ + "name", + "enforce", + "configResolved", + "buildStart", + "configureServer", + "resolveId", + "load", +]); + +export function isSourceTaggingPlugin(plugin) { + if (!plugin || typeof plugin !== "object" || !SOURCE_TAGGING_PLUGINS.has(plugin.name)) return false; + return Object.keys(plugin).every((key) => SOURCE_TAGGING_PLUGIN_HOOKS.has(key)); +} + +// The package a source-tagging plugin ships in. +export function sourceTaggingPackage(plugin) { + return SOURCE_TAGGING_PLUGINS.get(plugin && plugin.name) ?? null; +} + +// Whether oj does `plugin`'s work itself under `command`, by its name: the +// host leaves such a plugin out, and config extraction does not count it. +export function nativeByName(plugin, command) { + return OJ_NATIVE_PLUGIN_NAMES.has(plugin && plugin.name) || (command === "serve" && isSourceTaggingPlugin(plugin)); +} + // Start's router plugin: the code splitter pair it adds per environment // (client and server, sharing one route list) and the router generator, whose // run fills that list (`routesByFile`, the files the route tree imports). diff --git a/crates/oj_server/src/assets/plugin-host.mjs b/crates/oj_server/src/assets/plugin-host.mjs index 84c34f0c..ee5b8d95 100644 --- a/crates/oj_server/src/assets/plugin-host.mjs +++ b/crates/oj_server/src/assets/plugin-host.mjs @@ -28,6 +28,7 @@ import { isReimplemented, isRouteSplitting, isStartManifest, + nativeByName, isStartPostBuild, } from "./native-plugins.mjs"; import { idFilterGlob, idFilterRegExp, loadViteGlobs, viteGlobs } from "./start/vite-globs.mjs"; @@ -2365,7 +2366,7 @@ function esbuildMinifyPlugin() { // top-level list and what applyToEnvironment returns alike. function ojRunsNatively(p, c = main) { const name = p && p.name; - return OJ_NATIVE_PLUGIN_NAMES.has(name) || nativeImportProtection(name) || (c.leaveOut && startLeavesOut(name)); + return nativeByName(p, command) || nativeImportProtection(name) || (c.leaveOut && startLeavesOut(name)); } // Start's import protection (its resolve and transform-cache plugins), where // oj checks imports itself (`ojNativeImportProtection`: a dev server whose @@ -2406,7 +2407,7 @@ try { // loads it; the hooks below run under the resolved one. applyUserNodeEnv(userConfig); allPlugins = (await flattenPlugins(list)).map(nativeStylexStandIn); - nativePlugins = allPlugins.filter((p) => OJ_NATIVE_PLUGIN_NAMES.has(p && p.name)); + nativePlugins = allPlugins.filter((p) => nativeByName(p, command)); main.rawPlugins = allPlugins; noteStartCompilerPosition(allPlugins); main.plugins = hostedPlugins(allPlugins, userConfig); @@ -6530,7 +6531,7 @@ async function openWorkerContainer(parent, bundleChain) { bundleChain, }; // As the app's: the natively run plugins stay listed (hooks unrun). - const native = raw.filter((p) => OJ_NATIVE_PLUGIN_NAMES.has(p && p.name)); + const native = raw.filter((p) => nativeByName(p, command)); resolved.plugins = withCssPostShim(workerPlugins.concat(native), cssPostShimInto(c.pluginCss)); await runConfigResolved(workerPlugins, resolved, c); c.resolvedConfig = resolved; diff --git a/crates/oj_server/src/assets/source-tagging-theme.mjs b/crates/oj_server/src/assets/source-tagging-theme.mjs new file mode 100644 index 00000000..ef976762 --- /dev/null +++ b/crates/oj_server/src/assets/source-tagging-theme.mjs @@ -0,0 +1,176 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Raphael Amorim +// +// The source-tagging plugin's Tailwind theme (oj_server's source_tagging): +// the resolved theme of the app at `root`, written to +// src/tailwind.config.lov.json as the plugin writes it. Tailwind v4 first: a +// CSS entry that imports tailwindcss, read by the app's @tailwindcss/node, +// the theme namespaces with their `var()`s resolved from `:root`. Else v3: +// tailwind.config.ts bundled by esbuild, resolved by tailwindcss/resolveConfig, +// both from the plugin's `package` (its dependencies) or the app. `run` +// returns { wrote } (null when the app has neither) or { error }. +import { existsSync } from "node:fs"; +import fs from "node:fs/promises"; +import { createRequire } from "node:module"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; + +const V4_CSS_CANDIDATES = ["src/styles.css", "src/index.css", "src/globals.css", "src/app.css"]; + +const V4_NAMESPACES = { + colors: "--color", + screens: "--breakpoint", + spacing: "--spacing", + borderRadius: "--radius", + fontFamily: "--font", + opacity: "--opacity", +}; + +// The plugin resolves its tools from its own package (esbuild and tailwindcss +// are its dependencies; @tailwindcss/node an optional peer), so that comes +// first, then the app itself. +let anchors = []; +function setAnchors(root, pkg) { + const candidates = [pkg && path.join(root, "node_modules", pkg, "package.json"), path.join(root, "package.json")]; + anchors = candidates.filter((anchor) => anchor && existsSync(anchor)).map((anchor) => createRequire(anchor)); +} + +function requirers() { + return anchors; +} + +function resolveFrom(root, spec) { + for (const req of requirers(root)) { + try { + return req.resolve(spec); + } catch { + // Not from here; the next anchor may have it. + } + } + return null; +} + +async function importFrom(root, spec) { + const resolved = resolveFrom(root, spec); + return resolved ? import(pathToFileURL(resolved).href) : null; +} + +function requireFrom(root, spec) { + for (const req of requirers(root)) { + try { + return req(spec); + } catch (e) { + if (e && e.code !== "MODULE_NOT_FOUND") throw e; + } + } + return null; +} + +async function findV4CssEntry(root) { + for (const candidate of V4_CSS_CANDIDATES) { + const abs = path.resolve(root, candidate); + try { + const contents = await fs.readFile(abs, "utf8"); + if (/@import\s+["']tailwindcss/.test(contents)) return abs; + } catch { + // Not there; the next candidate may be. + } + } + return null; +} + +// v4's `@theme inline { --color-primary: var(--primary) }` with +// `:root { --primary: oklch(...) }` leaves the namespace values as var() +// references; an editor's color picker wants the values, so `:root` is read +// and substituted. Scoped to the common shape, as the plugin's is. +export function parseRootVars(css) { + const vars = {}; + const rootMatch = css.match(/:root\s*\{([^}]*)\}/s); + if (!rootMatch) return vars; + for (const decl of rootMatch[1].split(";")) { + const trimmed = decl.trim(); + if (!trimmed.startsWith("--")) continue; + const colon = trimmed.indexOf(":"); + if (colon === -1) continue; + const key = trimmed.slice(0, colon).trim(); + const value = trimmed.slice(colon + 1).trim(); + if (key && value) vars[key] = value; + } + return vars; +} + +export function resolveVars(value, rootVars, depth = 0) { + if (depth > 8) return value; + return value.replace(/var\(\s*(--[\w-]+)(?:\s*,\s*([^)]+))?\s*\)/g, (match, name, fallback) => { + const resolved = rootVars[name]; + if (resolved !== undefined) return resolveVars(resolved, rootVars, depth + 1); + return fallback ?? match; + }); +} + +async function generateV4Config(cssEntry, outfile, load) { + const css = await fs.readFile(cssEntry, "utf8"); + const ds = await load(css, { base: path.dirname(cssEntry) }); + const rootVars = parseRootVars(css); + const theme = {}; + for (const [configKey, namespace] of Object.entries(V4_NAMESPACES)) { + const entries = {}; + for (const [key, rawValue] of ds.theme.namespace(namespace)) { + if (key === null) continue; + entries[key] = resolveVars(rawValue, rootVars); + } + theme[configKey] = entries; + } + await fs.mkdir(path.dirname(outfile), { recursive: true }); + await fs.writeFile(outfile, JSON.stringify({ theme }, null, 2)); +} + +async function generateV3Config(root, configFile, outfile) { + const esbuild = await importFrom(root, "esbuild"); + if (!esbuild) throw new Error("esbuild is not installed (the plugin's dependency)"); + // Bundled beside the config, so its relative imports resolve as they do for + // the plugin; removed once imported. + const intermediate = path.resolve(root, "./.lov.tailwind.config.js"); + await esbuild.build({ + entryPoints: [configFile], + outfile: intermediate, + bundle: true, + format: "esm", + banner: { + js: 'import { createRequire } from "module"; const require = createRequire(import.meta.url);', + }, + }); + try { + const userConfig = await import(pathToFileURL(intermediate).href + "?update=" + Date.now()); + if (!userConfig || !userConfig.default) throw new Error("Invalid Tailwind config structure"); + const resolveConfigModule = requireFrom(root, "tailwindcss/resolveConfig.js"); + if (!resolveConfigModule) throw new Error("tailwindcss/resolveConfig.js is not installed"); + const resolveConfig = resolveConfigModule.default ?? resolveConfigModule; + await fs.mkdir(path.dirname(outfile), { recursive: true }); + await fs.writeFile(outfile, JSON.stringify(resolveConfig(userConfig.default), null, 2)); + } finally { + await fs.unlink(intermediate).catch(() => {}); + } +} + +export async function run({ root, package: pkg }) { + const outfile = path.resolve(root, "./src/tailwind.config.lov.json"); + setAnchors(root, pkg); + try { + const cssEntry = await findV4CssEntry(root); + if (cssEntry) { + const tailwindNode = await importFrom(root, "@tailwindcss/node"); + const load = tailwindNode && tailwindNode.__unstable__loadDesignSystem; + if (typeof load === "function") { + await generateV4Config(cssEntry, outfile, load); + return { wrote: outfile }; + } + } + const v3ConfigFile = path.resolve(root, "./tailwind.config.ts"); + if (!existsSync(v3ConfigFile)) return { wrote: null }; + await generateV3Config(root, v3ConfigFile, outfile); + return { wrote: outfile }; + } catch (e) { + return { error: String((e && e.stack) || e) }; + } +} diff --git a/crates/oj_server/src/assets/vite-extract.mjs b/crates/oj_server/src/assets/vite-extract.mjs index 709cbcb6..e5a2138f 100644 --- a/crates/oj_server/src/assets/vite-extract.mjs +++ b/crates/oj_server/src/assets/vite-extract.mjs @@ -17,7 +17,10 @@ import { OJ_NATIVE_PLUGIN_NAMES, OJ_UNSUPPORTED_PLUGIN_NAMES, flattenPlugins, + isSourceTaggingPlugin, + sourceTaggingPackage, isReimplemented, + nativeByName, } from "./native-plugins.mjs"; // The slice of Vite's mergeConfigRecursively these assets need (twin copies: @@ -2106,13 +2109,62 @@ async function activePluginCount(raw) { if (!raw) return null; try { return (await flattenPlugins(raw.plugins)).filter( - (p) => !OJ_NATIVE_PLUGIN_NAMES.has(p.name) && !OJ_UNSUPPORTED_PLUGIN_NAMES.has(p.name), + (p) => !nativeByName(p, command) && !OJ_UNSUPPORTED_PLUGIN_NAMES.has(p.name), ).length; } catch { return null; } } +// What the config's source-tagging plugin (native-plugins.mjs) does in this +// serve, asked of the instance itself so no version of it is assumed: the +// module it answers `react/jsx-dev-runtime` with (its resolveId, then its +// load, from an importer of the app's), and whether it watches the Tailwind +// config (its configureServer registers a change listener only with that +// feature on, and the watcher calls are the hook's only effect, so a stand-in +// server sees them). null: no such plugin, or not a serve. +async function sourceTagging(raw) { + if (command !== "serve" || !raw) return null; + let plugin; + try { + plugin = (await flattenPlugins(raw.plugins)).find(isSourceTaggingPlugin); + } catch { + return null; + } + if (!plugin) return null; + const hook = (h) => (typeof h === "function" ? h : h && typeof h.handler === "function" ? h.handler : null); + let jsxDevRuntime = null; + try { + const resolveId = hook(plugin.resolveId); + const load = hook(plugin.load); + const answer = + resolveId && + (await resolveId.call({}, "react/jsx-dev-runtime", appRoot + "/index.html", { ssr: false, isEntry: false })); + const id = typeof answer === "string" ? answer : answer && typeof answer.id === "string" ? answer.id : null; + const loaded = id && load ? await load.call({}, id) : null; + const code = typeof loaded === "string" ? loaded : loaded && typeof loaded.code === "string" ? loaded.code : null; + if (id && code != null) jsxDevRuntime = { id, code }; + } catch (e) { + emitStderr(`oj: the source-tagging plugin's jsx-dev-runtime could not be read: ${(e && e.stack) || e}\n`); + } + let tailwindTheme = false; + try { + const configureServer = hook(plugin.configureServer); + if (configureServer) { + const watcher = { + add() {}, + on(event) { + if (event === "change") tailwindTheme = true; + }, + }; + await configureServer.call({}, { watcher }); + } + } catch { + // The plugin's own try/catch swallows a watcher error; so does this. + } + return { package: sourceTaggingPackage(plugin), jsxDevRuntime, tailwindTheme }; +} + // Whether the config carries an editor's HMR gate plugin, which oj replaces // with its native gate (native-plugins.mjs). async function hasEditorHmrGate(raw) { @@ -2409,6 +2461,7 @@ async function extractValues(input) { resolveError: resolveFailure ? String((resolveFailure && resolveFailure.message) || resolveFailure) : null, stylex: await stylexPlugin(raw), editorHmrGate: await hasEditorHmrGate(raw), + sourceTagging: await sourceTagging(raw), }; }; const out = await valuesOf(c); diff --git a/crates/oj_server/src/lib.rs b/crates/oj_server/src/lib.rs index 0690f5b0..cec6ca05 100644 --- a/crates/oj_server/src/lib.rs +++ b/crates/oj_server/src/lib.rs @@ -39,6 +39,7 @@ use plugin_routes::*; mod ui; pub use ui::*; mod client_js; +mod source_tagging; use client_js::*; mod assets_serve; mod css_urls; @@ -454,6 +455,9 @@ struct ServerState { /// The keys of `virtual_modules`, shared with per-request rewrite closures /// (the map is fixed at boot; cloning the keyset per compile was waste). virtual_ids: Arc>, + /// The config's source-tagging plugin, done natively (see + /// [`source_tagging`]). + source_tagging: Option>, /// Memo of is_cjs_dep_file's per-file verdict (a read + syntax probe): /// dep files do not change within a session, like `dir_cache`. cjs_dep_memo: Mutex>, @@ -2526,6 +2530,7 @@ impl DevServer { ), canon_memo: Mutex::new(std::collections::HashMap::new()), virtual_modules: config.virtual_modules.clone().unwrap_or_default(), + source_tagging: config.vite_source_tagging.clone().map(Arc::new), jsx_overrides, jsx, stylex, @@ -2673,6 +2678,7 @@ impl DevServer { typecheck.follow(&state.watch_feed); } spawn_warmup(&state, &config); + source_tagging::spawn_tailwind_theme(&state); if self.lazy { // Lazy mode (Vite's default): compile on demand. Mark the crawl "done" so // preload injection and chunk assembly never block on a crawl that will not run. diff --git a/crates/oj_server/src/module_pipeline.rs b/crates/oj_server/src/module_pipeline.rs index 23a09c5e..ed0f2f7f 100644 --- a/crates/oj_server/src/module_pipeline.rs +++ b/crates/oj_server/src/module_pipeline.rs @@ -1477,6 +1477,13 @@ impl ImportRewrite<'_> { let stamp = state.graph.lock().unwrap().hmr_timestamp(path); return Some(stamp_module_import(state, spec, stamp)); } + // The source-tagging plugin's `pre` resolveId, ahead of the + // pre-bundle as a pre plugin's is of vite:resolve. + if let Some(url) = + crate::source_tagging::jsx_dev_runtime_url(state, spec, &job.importer_abs) + { + return Some(url); + } // Vite's URL for an optimized dep (`/node_modules/.vite/deps/react.js`), // written by hand or by tooling that knows Vite's cache: the import // of the dep itself, so the page keeps the one copy its bare imports diff --git a/crates/oj_server/src/plugins/engine_extraction_tests.rs b/crates/oj_server/src/plugins/engine_extraction_tests.rs index 72200d90..b6822bee 100644 --- a/crates/oj_server/src/plugins/engine_extraction_tests.rs +++ b/crates/oj_server/src/plugins/engine_extraction_tests.rs @@ -600,3 +600,84 @@ export default { define: { __API__: JSON.stringify(all.OJ_EXTRACT_TEST_API_URL ? )); assert!(serves(root, config, &env_with(&[("OLDPWD", "/elsewhere")]))); } + +// A source-tagging plugin's shape (native-plugins.mjs): the hooks of the +// known plugin, answering the JSX dev runtime and watching the Tailwind +// config; `extra` adds or replaces hooks. +const TAGGING_PLUGIN: &str = r#"const tagging = (extra = {}) => ({ + name: "lovable-plugin", + enforce: "pre", + configResolved() {}, + async buildStart() {}, + configureServer(server) { + try { + server.watcher.add("/app/tailwind.config.ts"); + server.watcher.on("change", () => {}); + } catch {} + }, + resolveId(id, importer) { + if (id === "react/jsx-dev-runtime" && !importer?.includes("\0jsx-source")) return "\0jsx-source/jsx-dev-runtime"; + return null; + }, + load(id) { + return id === "\0jsx-source/jsx-dev-runtime" ? "export const tagged = true;" : null; + }, + ...extra, +}); +"#; + +#[test] +fn a_source_tagging_plugin_is_asked_what_it_does_and_counts_as_native_in_a_serve() { + let _g = lock(); + let dir = app(&format!( + "{TAGGING_PLUGIN}export default {{ plugins: [tagging()] }};" + )); + let root = dir.path(); + let v = extract_vite_values_with(root, None, "serve", "development", true).expect("extracts"); + let tagging = v.source_tagging.expect("the plugin was asked"); + assert_eq!(tagging.package.as_deref(), Some("lovable-tagger")); + assert_eq!( + tagging.jsx_dev_runtime.map(|m| (m.id, m.code)), + Some(( + "\0jsx-source/jsx-dev-runtime".to_string(), + "export const tagged = true;".to_string() + )) + ); + assert!(tagging.tailwind_theme); + assert_eq!( + v.active_plugins, + Some(0), + "nothing is left for a plugin host" + ); + + // A build hosts it as before. + let v = extract_vite_values_with(root, None, "build", "production", true).expect("extracts"); + assert!(v.source_tagging.is_none()); + assert_eq!(v.active_plugins, Some(1)); +} + +#[test] +fn a_source_tagging_plugin_with_its_features_off_is_native_with_nothing_to_do() { + let _g = lock(); + let dir = app(&format!( + "{TAGGING_PLUGIN}export default {{ plugins: [tagging({{ resolveId: () => null, configureServer() {{}} }})] }};" + )); + let v = + extract_vite_values_with(dir.path(), None, "serve", "development", true).expect("extracts"); + let tagging = v.source_tagging.expect("the plugin was asked"); + assert!(tagging.jsx_dev_runtime.is_none()); + assert!(!tagging.tailwind_theme); + assert_eq!(v.active_plugins, Some(0)); +} + +#[test] +fn a_source_tagging_plugin_with_a_hook_oj_does_not_know_stays_hosted() { + let _g = lock(); + let dir = app(&format!( + "{TAGGING_PLUGIN}export default {{ plugins: [tagging({{ transform() {{ return null; }} }})] }};" + )); + let v = + extract_vite_values_with(dir.path(), None, "serve", "development", true).expect("extracts"); + assert!(v.source_tagging.is_none()); + assert_eq!(v.active_plugins, Some(1)); +} diff --git a/crates/oj_server/src/plugins/extract.rs b/crates/oj_server/src/plugins/extract.rs index 2c07b41f..2fce6349 100644 --- a/crates/oj_server/src/plugins/extract.rs +++ b/crates/oj_server/src/plugins/extract.rs @@ -93,6 +93,9 @@ pub struct ViteValues { /// The config has an editor's HMR gate plugin: oj's native gate stands /// in for it. pub editor_hmr_gate: bool, + /// The config's source-tagging plugin and what it does in this serve + /// (`sourceTagging`): oj does it in its place. + pub source_tagging: Option, /// The routes directory, route tree and options TanStack Start's router /// generator ran with (`startRouter`). pub start_router: Option, @@ -1352,6 +1355,10 @@ pub(crate) fn parse_vite_values(json: &serde_json::Value) -> ViteValues { .get("editorHmrGate") .and_then(|v| v.as_bool()) .unwrap_or(false), + source_tagging: json + .get("sourceTagging") + .filter(|v| v.is_object()) + .and_then(|v| serde_json::from_value(v.clone()).ok()), start_router: json.get("startRouter").and_then(|v| { Some(oj_config::StartRouterPaths { routes_directory: v.get("routesDirectory")?.as_str()?.into(), @@ -1483,6 +1490,7 @@ pub(crate) fn merge_vite_values(config: &mut oj_config::OjConfig, v: ViteValues) server.hmr_gate.get_or_insert(true); } config.vite_stylex = v.stylex; + config.vite_source_tagging = v.source_tagging; config.vite_start_router = v.start_router; config.vite_start_import_protection = v.start_import_protection; if config.base.is_none() { diff --git a/crates/oj_server/src/plugins/host_filter_tests.rs b/crates/oj_server/src/plugins/host_filter_tests.rs index 1aff356e..2f8758d1 100644 --- a/crates/oj_server/src/plugins/host_filter_tests.rs +++ b/crates/oj_server/src/plugins/host_filter_tests.rs @@ -267,3 +267,36 @@ async fn in_start_mode_a_rejection_inside_an_apply_to_environment_result_keeps_t let names = hosted_names("nested-reject", "vite.config.mjs", src, extra).await; assert_eq!(names, ["user", "rejects"]); } + +// A source-tagging plugin (native-plugins.mjs), a lookalike with a hook oj +// does not know, and a plugin of the user's. +const TAGGING_AND_LOOKALIKE: &str = r#"const hooks = { + enforce: "pre", + configResolved() {}, + async buildStart() {}, + configureServer() {}, + resolveId() { return null; }, + load() { return null; }, +}; +export default { + plugins: [ + { name: "lovable-plugin", ...hooks }, + { name: "lovable-plugin", ...hooks, transform() { return null; } }, + { name: "user-plugin" }, + ], +}; +"#; + +#[tokio::test] +async fn a_build_host_keeps_the_source_tagging_plugin() { + // The native path is a serve's (the dev tests cover it); a build hosts + // the plugin, its lookalike and the user's plugin as before. + let names = hosted_names( + "tagging-build", + "vite.config.mjs", + TAGGING_AND_LOOKALIKE, + serde_json::json!({ "pluginsFormat": "vite" }), + ) + .await; + assert_eq!(names, ["lovable-plugin", "lovable-plugin", "user-plugin"]); +} diff --git a/crates/oj_server/src/plugins/vite_values_tests.rs b/crates/oj_server/src/plugins/vite_values_tests.rs index b8eb89a5..a4d9ac32 100644 --- a/crates/oj_server/src/plugins/vite_values_tests.rs +++ b/crates/oj_server/src/plugins/vite_values_tests.rs @@ -1715,6 +1715,7 @@ fn merge_adopts_only_unset_fields() { active_plugins: None, stylex: None, editor_hmr_gate: false, + source_tagging: None, start_router: None, start_import_protection: None, resolve_error: None, @@ -1783,6 +1784,7 @@ fn merge_never_overrides_config() { active_plugins: None, stylex: None, editor_hmr_gate: false, + source_tagging: None, start_router: None, start_import_protection: None, resolve_error: None, @@ -4161,3 +4163,34 @@ async fn closing_a_worker_container_never_respawns_a_dead_host() { assert_eq!(worker.close_container().await, Ok(())); assert!(worker.load("/app/a.js").await.is_err(), "a stale handle"); } + +#[test] +fn a_source_tagging_plugins_answers_reach_the_config() { + let json = serde_json::json!({ + "sourceTagging": { + "package": "tagger-pkg", + "jsxDevRuntime": { "id": "\u{0}jsx-source/jsx-dev-runtime", "code": "export {};" }, + "tailwindTheme": true, + } + }); + let mut config = oj_config::OjConfig::default(); + merge_vite_values(&mut config, parse_vite_values(&json)); + let tagging = config.vite_source_tagging.expect("the plugin's answers"); + assert_eq!(tagging.package.as_deref(), Some("tagger-pkg")); + assert_eq!( + tagging + .jsx_dev_runtime + .as_ref() + .map(|m| (m.id.as_str(), m.code.as_str())), + Some(("\0jsx-source/jsx-dev-runtime", "export {};")) + ); + assert!(tagging.tailwind_theme); + + // No such plugin, or one left to the host: nothing to do natively. + let mut config = oj_config::OjConfig::default(); + merge_vite_values( + &mut config, + parse_vite_values(&serde_json::json!({ "sourceTagging": null })), + ); + assert!(config.vite_source_tagging.is_none()); +} diff --git a/crates/oj_server/src/serve.rs b/crates/oj_server/src/serve.rs index 6fe208c8..5882a096 100644 --- a/crates/oj_server/src/serve.rs +++ b/crates/oj_server/src/serve.rs @@ -168,6 +168,14 @@ async fn serve_internal_route( .await, ); } + if let Some(source) = crate::source_tagging::jsx_dev_runtime_source(state, &spec) { + // Compiled like any module, so its own import of the runtime + // reaches the pre-bundle as an app module's would. + let file = crate::source_tagging::synthetic_file(state); + return Some( + serve_compiled_from(state, &file, &id_path, None, headers, Some(source)).await, + ); + } // An id nothing resolves or loads (oj's 404) goes on to the app, as // Vite's transform hands its `ERR_LOAD_URL` on; a module request keeps it. let resp = serve_plugin_id(state, &spec, &importer).await; diff --git a/crates/oj_server/src/source_tagging.rs b/crates/oj_server/src/source_tagging.rs new file mode 100644 index 00000000..bd782d2a --- /dev/null +++ b/crates/oj_server/src/source_tagging.rs @@ -0,0 +1,158 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Raphael Amorim + +//! An editor's source-tagging plugin, done natively in a serve. Config +//! extraction asked the instance what it does (native-plugins.mjs +//! `isSourceTaggingPlugin`, vite-extract.mjs `sourceTagging`), the plugin +//! host leaves it out, and this module does its two things. (1) Its `pre` +//! resolveId answers `react/jsx-dev-runtime` from every importer but its own +//! module with a virtual module its `load` returns (a wrapper of React's +//! jsxDEV that records each element's source on the DOM node): the import +//! rewrite sends the specifier to that module's URL, Vite's for a `\0` id, +//! and the server compiles the module like any other, so its own import of +//! the runtime reaches the pre-bundle. (2) Its buildStart writes the app's +//! resolved Tailwind theme to `src/tailwind.config.lov.json` and its +//! configureServer rewrites it when `tailwind.config.ts` or a v4 CSS entry +//! changes: an engine job (`source-tagging-theme.mjs`) does the same with +//! the app's own packages. Off the boot's path: the plugin's buildStart ran +//! before Vite listened, but the file is read by an editor on demand, not +//! by the page. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use crate::ServerState; + +/// The file the virtual module compiles under: a compile needs a path for +/// its graph node and `import.meta.hot`; nothing is read from it. +const SYNTHETIC_FILE: &str = "__oj_source_tagging_jsx_dev_runtime.js"; + +/// Vite's spelling of a `\0` in a `/@id/` URL (dev_html's placeholder). +const NULL_BYTE_PLACEHOLDER: &str = "__x00__"; + +const THEME_SCRIPT: &str = "source-tagging-theme.mjs"; +const THEME_JS: &str = include_str!("assets/source-tagging-theme.mjs"); + +pub(crate) fn synthetic_file(state: &ServerState) -> PathBuf { + state.root.join(SYNTHETIC_FILE) +} + +/// The URL `spec` imported by `importer` is rewritten to: the virtual +/// module's, for `react/jsx-dev-runtime` from every module but that one (the +/// plugin's `!importer.includes("\0jsx-source")`). +pub(crate) fn jsx_dev_runtime_url( + state: &ServerState, + spec: &str, + importer: &str, +) -> Option { + let runtime = state.source_tagging.as_ref()?.jsx_dev_runtime.as_ref()?; + if spec != "react/jsx-dev-runtime" || Path::new(importer) == synthetic_file(state) { + return None; + } + Some(format!( + "/@id/{}", + runtime.id.replacen('\0', NULL_BYTE_PLACEHOLDER, 1) + )) +} + +/// The module's code when `id` (a decoded `/@id/` request, query and all) +/// names the plugin's module. +pub(crate) fn jsx_dev_runtime_source(state: &ServerState, id: &str) -> Option { + let runtime = state.source_tagging.as_ref()?.jsx_dev_runtime.as_ref()?; + (id.split('?').next() == Some(runtime.id.as_str())).then(|| runtime.code.clone()) +} + +/// The files whose change rewrites the theme, the plugin's watch list: +/// `tailwind.config.ts` and the v4 CSS entry candidates. +fn watched_files(root: &Path) -> [PathBuf; 5] { + [ + "tailwind.config.ts", + "src/styles.css", + "src/index.css", + "src/globals.css", + "src/app.css", + ] + .map(|rel| root.join(rel)) +} + +fn same_file(a: &Path, b: &Path) -> bool { + a == b + || match (a.canonicalize(), b.canonicalize()) { + (Ok(a), Ok(b)) => a == b, + _ => false, + } +} + +/// Writes the theme now and after every change to a watched file, when the +/// config's tagger does; on a thread of its own. +pub(crate) fn spawn_tailwind_theme(state: &Arc) { + if !state + .source_tagging + .as_ref() + .is_some_and(|tagger| tagger.tailwind_theme) + { + return; + } + let package = state + .source_tagging + .as_ref() + .and_then(|tagger| tagger.package.clone()); + let events = state.watch_feed.subscribe(); + let root = state.root.clone(); + let _ = std::thread::Builder::new() + .name("oj-source-tagging-theme".into()) + .spawn(move || { + write_theme(&root, package.as_deref()); + let watched = watched_files(&root); + let hit = |event: ¬ify::Event| { + event + .paths + .iter() + .any(|p| watched.iter().any(|w| same_file(w, p))) + }; + while let Ok(event) = events.recv() { + if !hit(&event) { + continue; + } + // An editor's save is a burst of events: one write for it. + std::thread::sleep(Duration::from_millis(50)); + while events.try_recv().is_ok() {} + write_theme(&root, package.as_deref()); + } + }); +} + +/// One run of the theme job: the plugin's `run()`, in oj's engine, with the +/// app's own `@tailwindcss/node` (v4) or esbuild and `tailwindcss` (v3), +/// resolved from `package` (the plugin's) first. +fn write_theme(root: &Path, package: Option<&str>) { + let cache = oj_cache::cache_root(root); + let _ = std::fs::create_dir_all(&cache); + if crate::plugins::ensure_asset(&cache, THEME_SCRIPT, THEME_JS).is_err() { + return; + } + let script = cache.join(THEME_SCRIPT); + let payload = serde_json::json!({ "root": root.to_string_lossy(), "package": package }); + match crate::plugins::run_engine_job_in_process( + root, + &script, + "run", + payload, + Some(Duration::from_secs(120)), + ) { + Ok(out) => { + if let Some(error) = out.get("error").and_then(|e| e.as_str()) { + eprintln!("oj: source tagging: the tailwind theme was not written: {error}"); + } else if let Some(wrote) = out.get("wrote").and_then(|w| w.as_str()) { + let shown = Path::new(wrote) + .strip_prefix(root) + .unwrap_or(Path::new(wrote)); + println!(" source tagging: wrote {}", shown.display()); + } + } + Err(error) => { + eprintln!("oj: source tagging: the tailwind theme job failed: {error}"); + } + } +} diff --git a/crates/oj_server/tests/dev/main.rs b/crates/oj_server/tests/dev/main.rs index 96643b2a..f0bdca77 100644 --- a/crates/oj_server/tests/dev/main.rs +++ b/crates/oj_server/tests/dev/main.rs @@ -109,6 +109,7 @@ mod resolve_created_files; mod restart_check; mod runtime_env; mod silent_proxy; +mod source_tagging; mod spa_socket_keepalive; mod ssr_externalize; mod stylex; diff --git a/crates/oj_server/tests/dev/source_tagging.rs b/crates/oj_server/tests/dev/source_tagging.rs new file mode 100644 index 00000000..a01dde55 --- /dev/null +++ b/crates/oj_server/tests/dev/source_tagging.rs @@ -0,0 +1,280 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Raphael Amorim + +//! An editor's source-tagging plugin (native-plugins.mjs) is done natively: +//! the import of `react/jsx-dev-runtime` every JSX module takes goes to the +//! plugin's own module, served at Vite's URL for its `\0` id and compiled +//! like any module (its import of the real runtime reaches the pre-bundle), +//! with no plugin host; and the resolved Tailwind theme the plugin writes for +//! the editor is written at boot and again when the Tailwind config changes, +//! by Tailwind v4's design system or v3's resolveConfig. + +use std::path::Path; +use std::time::{Duration, Instant}; + +use crate::{App, INDEX_HTML}; + +/// The plugin's shape (the hooks of the known one), answering the JSX dev +/// runtime with `runtime` and watching the Tailwind config. +fn config(runtime: &str) -> String { + format!( + r#"export default {{ + plugins: [{{ + name: "lovable-plugin", + enforce: "pre", + configResolved() {{}}, + async buildStart() {{}}, + configureServer(server) {{ + server.watcher.on("change", () => {{}}); + }}, + resolveId(id, importer) {{ + if (id === "react/jsx-dev-runtime" && !importer?.includes("\0jsx-source")) return "\0jsx-source/jsx-dev-runtime"; + return null; + }}, + load(id) {{ + return id === "\0jsx-source/jsx-dev-runtime" ? {runtime:?} : null; + }}, + }}], +}}; +"# + ) +} + +/// A wrapper of the real runtime, as the known plugin's is. +const RUNTIME: &str = "import * as R from \"react/jsx-dev-runtime\";\nexport const Fragment = R.Fragment;\nexport function jsxDEV(type, props, key, isStatic, source, self) {\n globalThis.__tagged = (globalThis.__tagged ?? 0) + 1;\n return R.jsxDEV(type, props, key, isStatic, source, self);\n}\n"; + +async fn wait_until(mut ready: impl FnMut() -> bool, what: &str) { + let deadline = Instant::now() + Duration::from_secs(90); + while !ready() { + assert!(Instant::now() < deadline, "timed out waiting: {what}"); + tokio::time::sleep(Duration::from_millis(100)).await; + } +} + +fn theme_json(out: &Path) -> Option { + serde_json::from_str(&std::fs::read_to_string(out).ok()?).ok() +} + +#[tokio::test(flavor = "multi_thread")] +async fn the_jsx_dev_runtime_import_goes_to_the_plugins_module_with_no_host() { + crate::require_fixture!("react"); + let app = App::new(&[ + ( + "package.json", + r#"{"name":"tagging","private":true,"dependencies":{"react":"*"}}"#, + ), + ("index.html", INDEX_HTML), + ("src/App.jsx", "export const App = () =>
hi
;\n"), + ( + "src/main.js", + "import { App } from \"./App.jsx\";\nwindow.__APP = App;\n", + ), + ("vite.config.mjs", &config(RUNTIME)), + ]); + app.link_fixture("react"); + let server = app.serve().await; + assert!( + server.built.plugin_host.is_none(), + "the plugin's work is oj's: no host" + ); + + let module = server.text("/src/App.jsx").await; + assert!( + module.contains("\"/@id/__x00__jsx-source/jsx-dev-runtime\""), + "the JSX runtime import goes to the plugin's module:\n{module}" + ); + + let runtime = server.get("/@id/__x00__jsx-source/jsx-dev-runtime").await; + assert_eq!(runtime.status, 200, "{}", runtime.body); + assert!( + runtime.body.contains("__tagged"), + "the plugin's code is served:\n{}", + runtime.body + ); + assert!( + !runtime.body.contains("__x00__jsx-source"), + "its own runtime import is not sent back to itself:\n{}", + runtime.body + ); + assert!( + runtime.body.contains("jsx-dev-runtime"), + "its runtime import reaches the pre-bundle:\n{}", + runtime.body + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn the_tailwind_theme_is_written_at_boot_and_again_when_the_css_changes() { + crate::require_fixture!("tailwindcss", "@tailwindcss/node"); + let css = |color: &str| { + format!("@import \"tailwindcss\";\n@theme {{\n --color-brand: {color};\n}}\n") + }; + let app = App::new(&[ + ("package.json", r#"{"name":"tagging-theme","private":true}"#), + ("index.html", INDEX_HTML), + ("src/main.js", "document.body.dataset.ok = \"1\";\n"), + ("src/index.css", &css("#123456")), + ("vite.config.mjs", &config("export {};")), + ]); + // The whole fixture install: @tailwindcss/node needs its own deps beside it. + let node_modules = crate::fixture("tailwindcss") + .unwrap() + .parent() + .unwrap() + .to_path_buf(); + std::os::unix::fs::symlink(node_modules, app.root.join("node_modules")).unwrap(); + let server = app.serve().await; + + let out = app.root.join("src/tailwind.config.lov.json"); + let brand = || { + theme_json(&out).and_then(|json| { + json["theme"]["colors"]["brand"] + .as_str() + .map(str::to_string) + }) + }; + wait_until( + || brand().as_deref() == Some("#123456"), + "the theme written at boot", + ) + .await; + + app.write(&[("src/index.css", &css("#654321"))]); + wait_until( + || brand().as_deref() == Some("#654321"), + "the theme rewritten after the CSS change", + ) + .await; + drop(server); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_v3_tailwind_config_is_bundled_and_resolved_by_the_apps_tailwind() { + crate::require_fixture!("esbuild", "@esbuild"); + let app = App::new(&[ + ("package.json", r#"{"name":"tagging-v3","private":true}"#), + ("index.html", INDEX_HTML), + ("src/main.js", "document.body.dataset.ok = \"1\";\n"), + ("src/brand.ts", "export const brand: string = \"#abcdef\";\n"), + ( + "tailwind.config.ts", + "import type { Config } from \"tailwindcss\";\nimport { brand } from \"./src/brand\";\nexport default { content: [\"./src/**/*.tsx\"], theme: { extend: { colors: { brand } } }, plugins: [require(\"./plugin.cjs\")] } satisfies Config;\n", + ), + ("plugin.cjs", "module.exports = { name: \"stub\" };\n"), + // A v3 `tailwindcss` stand-in: the fixture installs v4, which has no + // resolveConfig. + ( + "node_modules/tailwindcss/package.json", + r#"{"name":"tailwindcss","version":"3.4.17","main":"index.js"}"#, + ), + ("node_modules/tailwindcss/index.js", "module.exports = {};\n"), + ( + "node_modules/tailwindcss/resolveConfig.js", + "module.exports = (config) => ({ resolved: true, ...config });\n", + ), + ("vite.config.mjs", &config("export {};")), + ]); + app.link_fixture("esbuild"); + // esbuild's binary package, whatever this platform's is. + for entry in std::fs::read_dir(crate::fixture("@esbuild").unwrap()).unwrap() { + let name = entry.unwrap().file_name(); + app.link_fixture(&format!("@esbuild/{}", name.to_string_lossy())); + } + let server = app.serve().await; + + let out = app.root.join("src/tailwind.config.lov.json"); + wait_until(|| out.exists(), "the theme written at boot").await; + let json = theme_json(&out).expect("a JSON theme"); + assert_eq!(json["resolved"], true, "{json}"); + assert_eq!( + json["theme"]["extend"]["colors"]["brand"], "#abcdef", + "{json}" + ); + assert_eq!(json["plugins"][0]["name"], "stub", "{json}"); + assert!( + !app.root.join(".lov.tailwind.config.js").exists(), + "the bundled config is removed once read" + ); + drop(server); +} + +/// `config` with `extra` plugins after the source-tagging one. +fn config_with(runtime: &str, extra: &str) -> String { + config(runtime).replace(" }],\n};", &format!(" }}, {extra}],\n}};")) +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_hosted_plugin_beside_it_keeps_a_host_that_leaves_the_tagging_plugin_out() { + crate::require_fixture!("react"); + let app = App::new(&[ + ( + "package.json", + r#"{"name":"tagging-hosted","private":true,"dependencies":{"react":"*"}}"#, + ), + ("index.html", INDEX_HTML), + ("src/App.jsx", "export const App = () =>
hi
;\n"), + ( + "src/main.js", + "import { App } from \"./App.jsx\";\nwindow.__APP = App;\n", + ), + ( + "vite.config.mjs", + &config_with( + RUNTIME, + "{ name: \"user-plugin\", transform(code, id) { return null; } }", + ), + ), + ]); + app.link_fixture("react"); + let server = app.serve().await; + let host = server + .built + .plugin_host + .as_ref() + .expect("the user's plugin keeps a host"); + assert_eq!( + host.plugin_names().await, + ["user-plugin"], + "the host leaves the source-tagging plugin out" + ); + let module = server.text("/src/App.jsx").await; + assert!( + module.contains("\"/@id/__x00__jsx-source/jsx-dev-runtime\""), + "the JSX runtime import still goes to the plugin's module:\n{module}" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_lookalike_with_a_hook_oj_does_not_know_stays_hosted_and_oj_leaves_the_runtime_alone() { + crate::require_fixture!("react"); + let plugin = config(RUNTIME).replace( + " load(id) {", + " transform(code, id) { return null; },\n load(id) {", + ); + let app = App::new(&[ + ( + "package.json", + r#"{"name":"tagging-lookalike","private":true,"dependencies":{"react":"*"}}"#, + ), + ("index.html", INDEX_HTML), + ("src/App.jsx", "export const App = () =>
hi
;\n"), + ( + "src/main.js", + "import { App } from \"./App.jsx\";\nwindow.__APP = App;\n", + ), + ("vite.config.mjs", &plugin), + ]); + app.link_fixture("react"); + let server = app.serve().await; + let host = server + .built + .plugin_host + .as_ref() + .expect("a plugin with a hook oj does not know keeps a host"); + assert_eq!(host.plugin_names().await, ["lovable-plugin"]); + let module = server.text("/src/App.jsx").await; + assert!( + !module.contains("__x00__jsx-source"), + "oj does not answer the runtime for a hosted plugin:\n{module}" + ); +}