mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-17 00:20:51 +00:00
feat: compile tailwind css v4 in raw app bundles (#12346)
* feat: compile tailwind css v4 in raw app bundles Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PjsYvugRUoJY5W81Mmwshi * fix: rebase relative urls in stylesheets tailwind inlines Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PjsYvugRUoJY5W81Mmwshi * fix: keep quoted arbitrary values intact when scanning tailwind classes Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PjsYvugRUoJY5W81Mmwshi * chore: bump ui builder to f9c1211 for tailwind v4 compilation Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PjsYvugRUoJY5W81Mmwshi * fix: tailwind object-key classes, config reload in app dev, dist of explicit sources Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PjsYvugRUoJY5W81Mmwshi * fix: reload commonjs tailwind configs on app dev rebuilds under node Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PjsYvugRUoJY5W81Mmwshi * chore: bump ui builder to 5ae35e6 for tailwind object-key classes Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PjsYvugRUoJY5W81Mmwshi * fix: reload the whole import graph of tailwind configs and plugins on app dev rebuilds Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PjsYvugRUoJY5W81Mmwshi * fix: load tailwind configs and plugins as is, ask for an app dev restart on edits Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PjsYvugRUoJY5W81Mmwshi --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
9d9875cf0e
commit
18556fd9b8
File diff suppressed because one or more lines are too long
@@ -44,6 +44,7 @@
|
||||
"@types/tar-stream": "^3.1.4",
|
||||
"@types/ws": "^8.5.0",
|
||||
"ajv": "^8.17.1",
|
||||
"tailwindcss": "4.1.14",
|
||||
"typescript": "^5.7.0",
|
||||
},
|
||||
},
|
||||
@@ -279,6 +280,8 @@
|
||||
|
||||
"svelte": ["svelte@5.56.8", "", { "dependencies": { "@jridgewell/remapping": "^2.3.4", "@jridgewell/sourcemap-codec": "^1.5.0", "@sveltejs/acorn-typescript": "^1.0.10", "@types/estree": "^1.0.5", "@types/trusted-types": "^2.0.7", "acorn": "^8.12.1", "aria-query": "5.3.1", "axobject-query": "^4.1.0", "clsx": "^2.1.1", "devalue": "^5.8.1", "esm-env": "^1.2.1", "esrap": "^2.2.12", "is-reference": "^3.0.3", "locate-character": "^3.0.0", "magic-string": "^0.30.11", "zimmerframe": "^1.1.2" } }, "sha512-PY8LOw7xP6c8IOiVqdo0sbbZVYhXRSfklOQLAUyGBKqjTX0wx/z4l/9J+PmBpmlLnxzEb1NqltxQ5/wZme/Cmg=="],
|
||||
|
||||
"tailwindcss": ["tailwindcss@4.1.14", "", {}, "sha512-b7pCxjGO98LnxVkKjaZSDeNuljC4ueKUddjENJOADtubtdo8llTaJy7HwBMeLNSSo2N5QIAgklslK1+Ir8r6CA=="],
|
||||
|
||||
"tar-stream": ["tar-stream@3.1.7", "", { "dependencies": { "b4a": "^1.6.4", "fast-fifo": "^1.2.0", "streamx": "^2.15.0" } }, "sha512-qJj60CXt7IU1Ffyc3NJMjh6EkuCFej46zUqJ4J7pqYlThyd9bO0XBTmcOIhSzZJVWfsLks0+nle/j538YAW9RQ=="],
|
||||
|
||||
"text-decoder": ["text-decoder@1.2.7", "", { "dependencies": { "b4a": "^1.6.4" } }, "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ=="],
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"@types/tar-stream": "^3.1.4",
|
||||
"@types/ws": "^8.5.0",
|
||||
"ajv": "^8.17.1",
|
||||
"tailwindcss": "4.1.14",
|
||||
"typescript": "^5.7.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { colors } from "@cliffy/ansi/colors";
|
||||
import * as windmillUtils from "@windmill-labs/shared-utils";
|
||||
import { readTextFile, readTextFileSync } from "../../utils/utils.ts";
|
||||
import { withEsbuild } from "../../utils/esbuild_loader.ts";
|
||||
import { createTailwindPlugin } from "./tailwind.ts";
|
||||
export interface BundleOptions {
|
||||
entryPoint?: string;
|
||||
outDir?: string;
|
||||
@@ -244,9 +245,13 @@ function createSveltePlugin(appDir: string): any {
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates framework-specific esbuild plugins based on detected dependencies
|
||||
* Creates framework-specific esbuild plugins based on detected dependencies.
|
||||
* `sharedUiDir` is scanned for Tailwind class names alongside the app.
|
||||
*/
|
||||
export async function createFrameworkPlugins(appDir: string): Promise<any[]> {
|
||||
export async function createFrameworkPlugins(
|
||||
appDir: string,
|
||||
sharedUiDir?: string
|
||||
): Promise<any[]> {
|
||||
const frameworks = detectFrameworks(appDir);
|
||||
const plugins: any[] = [];
|
||||
|
||||
@@ -255,6 +260,9 @@ export async function createFrameworkPlugins(appDir: string): Promise<any[]> {
|
||||
plugins.push(createSveltePlugin(appDir));
|
||||
}
|
||||
|
||||
const tailwind = createTailwindPlugin(appDir, sharedUiDir);
|
||||
if (tailwind) plugins.push(tailwind);
|
||||
|
||||
return plugins;
|
||||
}
|
||||
|
||||
@@ -393,8 +401,13 @@ export async function createBundle(
|
||||
// Ensure node_modules exists in the app directory
|
||||
await ensureNodeModules(appDir);
|
||||
|
||||
// Load framework-specific plugins (svelte) based on package.json
|
||||
const frameworkPlugins = await createFrameworkPlugins(appDir);
|
||||
const sharedUiDir =
|
||||
options.sharedUiDir && fs.existsSync(options.sharedUiDir)
|
||||
? options.sharedUiDir
|
||||
: undefined;
|
||||
|
||||
// Load framework-specific plugins (svelte, tailwind) based on package.json
|
||||
const frameworkPlugins = await createFrameworkPlugins(appDir, sharedUiDir);
|
||||
|
||||
// Ensure output directory exists
|
||||
const distDir = path.join(process.cwd(), outDir);
|
||||
@@ -439,10 +452,9 @@ export async function createBundle(
|
||||
},
|
||||
};
|
||||
|
||||
const sharedUiPlugins: any[] =
|
||||
options.sharedUiDir && fs.existsSync(options.sharedUiDir)
|
||||
? [createSharedUiPlugin(options.sharedUiDir, appDir)]
|
||||
: [];
|
||||
const sharedUiPlugins: any[] = sharedUiDir
|
||||
? [createSharedUiPlugin(sharedUiDir, appDir)]
|
||||
: [];
|
||||
|
||||
const buildOptions = {
|
||||
...DEFAULT_BUILD_OPTIONS,
|
||||
|
||||
@@ -592,14 +592,16 @@ async function dev(opts: DevOptions, appFolder?: string) {
|
||||
|
||||
const buildOptions = getDevBuildOptions(entryPoint, frameworks.svelte);
|
||||
|
||||
// Load framework-specific plugins (svelte) based on package.json
|
||||
const frameworkPlugins = await createFrameworkPlugins(appDir);
|
||||
const foundUiDir = findSharedUiDir(appDir);
|
||||
const sharedUiDir =
|
||||
foundUiDir && fs.existsSync(foundUiDir) ? foundUiDir : undefined;
|
||||
|
||||
const sharedUiDir = findSharedUiDir(appDir);
|
||||
const sharedUiPlugins =
|
||||
sharedUiDir && fs.existsSync(sharedUiDir)
|
||||
? [createSharedUiPlugin(sharedUiDir, appDir)]
|
||||
: [];
|
||||
// Load framework-specific plugins (svelte, tailwind) based on package.json
|
||||
const frameworkPlugins = await createFrameworkPlugins(appDir, sharedUiDir);
|
||||
|
||||
const sharedUiPlugins = sharedUiDir
|
||||
? [createSharedUiPlugin(sharedUiDir, appDir)]
|
||||
: [];
|
||||
|
||||
const wmillPlugin = {
|
||||
name: "wmill-virtual",
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
import { createRequire } from "node:module";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import * as log from "../../core/log.ts";
|
||||
import { colors } from "@cliffy/ansi/colors";
|
||||
import { readTextFileSync } from "../../utils/utils.ts";
|
||||
import { APP_BACKEND_FOLDER } from "./app_metadata.ts";
|
||||
import {
|
||||
compileTailwind,
|
||||
declaresTailwindV4,
|
||||
installedTailwindMajor,
|
||||
staticPrefix,
|
||||
TAILWIND_SOURCE_EXTENSIONS,
|
||||
type TailwindCompile,
|
||||
type TailwindHost,
|
||||
type TailwindSource,
|
||||
} from "./tailwind_core.ts";
|
||||
|
||||
const MAX_SOURCE_BYTES = 1024 * 1024;
|
||||
|
||||
/** `src/**\/*.vue` scans `.vue` files; a pattern naming no extension scans the default set. */
|
||||
function sourceExtensions(pattern: string): string[] {
|
||||
const ext = pattern.match(/\*(\.[\w-]+)$/);
|
||||
return ext ? [ext[1]] : TAILWIND_SOURCE_EXTENSIONS;
|
||||
}
|
||||
|
||||
function mtimeOf(file: string): number | undefined {
|
||||
try {
|
||||
return fs.statSync(file).mtimeMs;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function readJson(file: string): string | undefined {
|
||||
try {
|
||||
return readTextFileSync(file);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Walks `dir` for scannable files. The default walk skips build output
|
||||
* (`dist`); an explicit `@source` keeps it, since a component library
|
||||
* (`@source "../node_modules/some-ui-lib"`) ships its classes only there.
|
||||
* Neither descends into a nested `node_modules`.
|
||||
*/
|
||||
function walk(
|
||||
dir: string,
|
||||
extensions: string[],
|
||||
skipTop: Set<string>,
|
||||
out: { files: Map<string, string>; dirs: Set<string> },
|
||||
explicit: boolean,
|
||||
) {
|
||||
let entries: fs.Dirent[];
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
out.dirs.add(dir);
|
||||
for (const entry of entries) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
if (entry.name.startsWith(".") || skipTop.has(entry.name)) continue;
|
||||
if (entry.name === "node_modules" || (!explicit && entry.name === "dist")) continue;
|
||||
walk(full, extensions, new Set(), out, explicit);
|
||||
} else if (entry.isFile()) {
|
||||
if (!extensions.includes(path.extname(entry.name))) continue;
|
||||
addFile(full, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addFile(file: string, out: { files: Map<string, string> }) {
|
||||
let real: string;
|
||||
try {
|
||||
real = fs.realpathSync(file);
|
||||
if (out.files.has(real) || fs.statSync(real).size > MAX_SOURCE_BYTES) return;
|
||||
out.files.set(real, fs.readFileSync(real, "utf-8"));
|
||||
} catch {
|
||||
// A file that vanished mid-walk has no classes to contribute.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The esbuild plugin compiling Tailwind CSS v4 stylesheets, or undefined when
|
||||
* the app does not declare `tailwindcss` v4+: then nothing is registered and
|
||||
* the build is exactly what it is without Tailwind. The compiler is the app's
|
||||
* own, loaded on the first stylesheet that uses a Tailwind directive.
|
||||
*/
|
||||
export function createTailwindPlugin(appDir: string, sharedUiDir?: string): any | undefined {
|
||||
const resolvedApp = path.resolve(appDir);
|
||||
if (!declaresTailwindV4(readJson(path.join(resolvedApp, "package.json")))) {
|
||||
return undefined;
|
||||
}
|
||||
const requireFromApp = createRequire(path.join(resolvedApp, "package.json"));
|
||||
let pkgDir: string;
|
||||
try {
|
||||
pkgDir = path.dirname(requireFromApp.resolve("tailwindcss/package.json"));
|
||||
} catch {
|
||||
log.warn(
|
||||
colors.yellow(
|
||||
"⚠️ package.json declares tailwindcss but it is not installed; Tailwind stylesheets will not be compiled",
|
||||
),
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
const pkgJson = readJson(path.join(pkgDir, "package.json"));
|
||||
const major = installedTailwindMajor(pkgJson);
|
||||
if (major === undefined || major < 4) {
|
||||
log.warn(
|
||||
colors.yellow(
|
||||
`⚠️ installed tailwindcss is v${major ?? "?"}; only v4+ is compiled by the bundler`,
|
||||
),
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
log.info(colors.blue("🎨 Tailwind CSS v4 detected, adding tailwind plugin..."));
|
||||
|
||||
const uiDir = sharedUiDir && fs.existsSync(sharedUiDir) ? fs.realpathSync(sharedUiDir) : undefined;
|
||||
let compilePromise: Promise<TailwindCompile> | undefined;
|
||||
const moduleMtimes = new Map<string, number | undefined>();
|
||||
const loadCompile = () => {
|
||||
compilePromise ??= (async () => {
|
||||
const exportsMap = JSON.parse(pkgJson!)?.exports?.["."];
|
||||
const entry = typeof exportsMap === "object" && typeof exportsMap.import === "string"
|
||||
? path.resolve(pkgDir, exportsMap.import)
|
||||
: requireFromApp.resolve("tailwindcss");
|
||||
const mod = await import(pathToFileURL(entry).href);
|
||||
const compile = mod.compile ?? mod.default?.compile;
|
||||
if (typeof compile !== "function") {
|
||||
throw new Error(`tailwindcss at ${pkgDir} has no compile() export`);
|
||||
}
|
||||
return compile as TailwindCompile;
|
||||
})();
|
||||
return compilePromise;
|
||||
};
|
||||
|
||||
return {
|
||||
name: "wmill-tailwind",
|
||||
setup(build: any) {
|
||||
const host: TailwindHost = {
|
||||
loadCompile,
|
||||
// Through esbuild's own resolver, so `/ui/...`, the "style" export
|
||||
// condition and bare imports from `ui/` resolve as a plain `@import` would.
|
||||
async loadStylesheet(id, base) {
|
||||
const resolved = await build.resolve(id, {
|
||||
kind: "import-rule",
|
||||
resolveDir: base,
|
||||
importer: path.join(base, "__tailwind__.css"),
|
||||
});
|
||||
if (resolved.errors.length > 0) {
|
||||
throw new Error(resolved.errors[0].text);
|
||||
}
|
||||
return {
|
||||
path: resolved.path,
|
||||
base: path.dirname(resolved.path),
|
||||
content: fs.readFileSync(resolved.path, "utf-8"),
|
||||
};
|
||||
},
|
||||
rebaseUrl(url, from, to) {
|
||||
const cut = url.search(/[?#]/);
|
||||
const file = cut === -1 ? url : url.slice(0, cut);
|
||||
const suffix = cut === -1 ? "" : url.slice(cut);
|
||||
const rel = path.relative(to, path.resolve(from, file)).split(path.sep).join("/");
|
||||
return (rel.startsWith("../") ? rel : "./" + rel) + suffix;
|
||||
},
|
||||
// `@plugin` / `@config` run in this process, as they would under the
|
||||
// Tailwind CLI: resolved from the stylesheet, then from the app, and
|
||||
// imported as is so the module keeps its own location and globals.
|
||||
// The module cache keeps them for the life of the process, which
|
||||
// neither Node nor Bun can reset for a whole import graph: in `app dev`
|
||||
// an edit to one is reported rather than silently built from the old copy.
|
||||
async loadModule(id, base) {
|
||||
let resolved: string;
|
||||
try {
|
||||
resolved = createRequire(path.join(base, "__tailwind__.js")).resolve(id);
|
||||
} catch {
|
||||
resolved = requireFromApp.resolve(id);
|
||||
}
|
||||
const mtime = mtimeOf(resolved);
|
||||
const loadedAt = moduleMtimes.get(resolved);
|
||||
if (loadedAt === undefined) {
|
||||
moduleMtimes.set(resolved, mtime);
|
||||
} else if (loadedAt !== mtime) {
|
||||
moduleMtimes.set(resolved, mtime);
|
||||
log.warn(
|
||||
colors.yellow(
|
||||
`⚠️ ${path.relative(resolvedApp, resolved)} changed: restart to apply Tailwind \`@config\` / \`@plugin\` changes`,
|
||||
),
|
||||
);
|
||||
}
|
||||
const mod = await import(pathToFileURL(resolved).href);
|
||||
return { path: resolved, base: path.dirname(resolved), module: mod.default ?? mod };
|
||||
},
|
||||
async scan(sources: TailwindSource[], includeDefault: boolean) {
|
||||
const out = { files: new Map<string, string>(), dirs: new Set<string>() };
|
||||
if (includeDefault) {
|
||||
walk(resolvedApp, TAILWIND_SOURCE_EXTENSIONS, new Set([APP_BACKEND_FOLDER]), out, false);
|
||||
if (uiDir) walk(uiDir, TAILWIND_SOURCE_EXTENSIONS, new Set(), out, false);
|
||||
}
|
||||
for (const source of sources) {
|
||||
const target = path.resolve(source.base, staticPrefix(source.pattern));
|
||||
let stat: fs.Stats;
|
||||
try {
|
||||
stat = fs.statSync(target);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
if (stat.isFile()) addFile(target, out);
|
||||
else walk(target, sourceExtensions(source.pattern), new Set(), out, true);
|
||||
}
|
||||
return {
|
||||
files: [...out.files].map(([p, content]) => ({ path: p, content })),
|
||||
dirs: [...out.dirs],
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
build.onLoad({ filter: /\.css$/, namespace: "file" }, async (args: any) => {
|
||||
const css = fs.readFileSync(args.path, "utf-8");
|
||||
try {
|
||||
const result = await compileTailwind(css, args.path, path.dirname(args.path), host);
|
||||
if (!result) return undefined;
|
||||
return {
|
||||
contents: result.css,
|
||||
loader: "css",
|
||||
resolveDir: path.dirname(args.path),
|
||||
watchFiles: result.files,
|
||||
watchDirs: result.dirs,
|
||||
};
|
||||
} catch (e: any) {
|
||||
return {
|
||||
errors: [{ text: `Tailwind CSS: ${e?.message ?? e}` }],
|
||||
watchFiles: [args.path],
|
||||
};
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
/**
|
||||
* Tailwind CSS v4 for raw-app builds, independent of the bundler and of where
|
||||
* files live. The CLI's esbuild and the UI Builder's esbuild-wasm/rolldown
|
||||
* workers each supply a `TailwindHost`; this file is copied byte for byte into
|
||||
* windmill-code-ui-builder (`src/lib/tailwind_core.ts`), so keep it free of
|
||||
* Node and browser APIs and change both copies together.
|
||||
*/
|
||||
|
||||
/** The `compile` export of the app's own `tailwindcss` (v4). */
|
||||
export type TailwindCompile = (
|
||||
css: string,
|
||||
opts: {
|
||||
base: string;
|
||||
from?: string;
|
||||
loadStylesheet: (
|
||||
id: string,
|
||||
base: string,
|
||||
) => Promise<{ path: string; base: string; content: string }>;
|
||||
loadModule: (
|
||||
id: string,
|
||||
base: string,
|
||||
resourceHint: "plugin" | "config",
|
||||
) => Promise<{ path: string; base: string; module: unknown }>;
|
||||
},
|
||||
) => Promise<{
|
||||
sources: { base: string; pattern: string; negated: boolean }[];
|
||||
root: null | "none" | { base: string; pattern: string };
|
||||
features: number;
|
||||
build(candidates: string[]): string;
|
||||
}>;
|
||||
|
||||
/** Where `@source` (or `source(...)` on the import) points, before globbing. */
|
||||
export interface TailwindSource {
|
||||
base: string;
|
||||
pattern: string;
|
||||
}
|
||||
|
||||
export interface TailwindHost {
|
||||
/** Loaded on first use, so an app whose stylesheets never need it pays nothing. */
|
||||
loadCompile(): Promise<TailwindCompile>;
|
||||
loadStylesheet(
|
||||
id: string,
|
||||
base: string,
|
||||
): Promise<{ path: string; base: string; content: string }>;
|
||||
loadModule(
|
||||
id: string,
|
||||
base: string,
|
||||
resourceHint: "plugin" | "config",
|
||||
): Promise<{ path: string; base: string; module: unknown }>;
|
||||
/**
|
||||
* `url` as written in a stylesheet in directory `from`, made relative to
|
||||
* directory `to`, with forward slashes and a leading `./` or `../`.
|
||||
*/
|
||||
rebaseUrl(url: string, from: string, to: string): string;
|
||||
/**
|
||||
* The files whose class names the stylesheet must cover: the app's sources
|
||||
* (and the shared `/ui` folder) when `includeDefault`, plus whatever each
|
||||
* `@source` names. `dirs` are the directories walked, for watch mode.
|
||||
*/
|
||||
scan(
|
||||
sources: TailwindSource[],
|
||||
includeDefault: boolean,
|
||||
): Promise<{ files: { path: string; content: string }[]; dirs: string[] }>;
|
||||
}
|
||||
|
||||
export interface TailwindResult {
|
||||
css: string;
|
||||
/** Every file the output depends on: stylesheets read and sources scanned. */
|
||||
files: string[];
|
||||
dirs: string[];
|
||||
}
|
||||
|
||||
// A stylesheet without any of these is plain CSS and is left to the bundler,
|
||||
// which is what keeps a Tailwind app's other stylesheets (and every app without
|
||||
// Tailwind) on the bundler's normal path.
|
||||
const TAILWIND_DIRECTIVE =
|
||||
/@(?:import\s+(?:url\(\s*)?["']tailwindcss(?:["'/])|tailwind\b|theme\b|utility\b|apply\b|variant\b|custom-variant\b|source\b|plugin\b|config\b|reference\b)/;
|
||||
|
||||
export function usesTailwind(css: string): boolean {
|
||||
return TAILWIND_DIRECTIVE.test(css);
|
||||
}
|
||||
|
||||
/** `"tailwindcss"` at major version 4 or later in a package.json's dependencies. */
|
||||
export function declaresTailwindV4(packageJson: string | undefined): boolean {
|
||||
if (!packageJson) return false;
|
||||
let pkg: any;
|
||||
try {
|
||||
pkg = JSON.parse(packageJson);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
const spec = pkg?.dependencies?.tailwindcss ?? pkg?.devDependencies?.tailwindcss;
|
||||
if (typeof spec !== "string") return false;
|
||||
const major = spec.match(/\d+/);
|
||||
// A tag or URL ("latest", "next", a git link) has no major to read: latest is v4+.
|
||||
return major ? Number(major[0]) >= 4 : true;
|
||||
}
|
||||
|
||||
export function installedTailwindMajor(packageJson: string | undefined): number | undefined {
|
||||
if (!packageJson) return undefined;
|
||||
try {
|
||||
const major = String(JSON.parse(packageJson)?.version ?? "").match(/^\d+/);
|
||||
return major ? Number(major[0]) : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
const TRIM_START = /^[\s"'`{}()<>;,=]+/;
|
||||
const TRIM_END = /[\s"'`{}()<>;,=]+$/;
|
||||
|
||||
function addCandidate(token: string, out: Set<string>) {
|
||||
let t = token.replace(TRIM_START, "").replace(TRIM_END, "");
|
||||
if (t.startsWith("class:")) t = t.slice("class:".length);
|
||||
if (t.length === 0 || t.length > 300) return;
|
||||
out.add(t);
|
||||
// An object key (`clsx({ hidden: open })`, `{hidden:open}`) carries the
|
||||
// colon, or the value, of the key/value pair it belongs to.
|
||||
const key = t.match(/^([\w-]+):(?:[A-Za-z_$!][\w$.!]*)?$/);
|
||||
if (key) out.add(key[1]);
|
||||
}
|
||||
|
||||
/** `className="after:content-['x']"` -> `className=`, `after:content-['x']`. */
|
||||
function splitQuotesOutsideBrackets(token: string): string[] {
|
||||
const parts: string[] = [];
|
||||
let depth = 0;
|
||||
let start = 0;
|
||||
for (let i = 0; i < token.length; i++) {
|
||||
const c = token[i];
|
||||
if (c === "[") depth++;
|
||||
else if (c === "]") depth = Math.max(0, depth - 1);
|
||||
else if (depth === 0 && (c === '"' || c === "'" || c === "`")) {
|
||||
parts.push(token.slice(start, i));
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
parts.push(token.slice(start));
|
||||
return parts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every token that might be a class name. Tailwind ignores the ones that are
|
||||
* not, so this over-collects rather than parse: each whitespace-separated token
|
||||
* is taken whole, split at quotes outside `[...]`, and split at every quote
|
||||
* and markup punctuation, which keeps arbitrary values (`data-[state=open]:x`,
|
||||
* `[&>svg]:size-4`, `className="after:content-['x']"`) intact in at least one cut.
|
||||
*/
|
||||
export function extractCandidates(content: string, out: Set<string>): void {
|
||||
for (const raw of content.split(/\s+/)) {
|
||||
if (!raw) continue;
|
||||
addCandidate(raw, out);
|
||||
for (const part of splitQuotesOutsideBrackets(raw)) addCandidate(part, out);
|
||||
for (const part of raw.split(/["'`]/)) {
|
||||
addCandidate(part, out);
|
||||
for (const sub of part.split(/[{}()<>;,]/)) addCandidate(sub, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compiles one stylesheet, or returns undefined when it is not a Tailwind
|
||||
* stylesheet. `path` is the stylesheet's own path and `base` its directory.
|
||||
*/
|
||||
export async function compileTailwind(
|
||||
css: string,
|
||||
path: string,
|
||||
base: string,
|
||||
host: TailwindHost,
|
||||
): Promise<TailwindResult | undefined> {
|
||||
if (!usesTailwind(css)) return undefined;
|
||||
const compile = await host.loadCompile();
|
||||
const files = new Set<string>([path]);
|
||||
const compiler = await compile(css, {
|
||||
base,
|
||||
from: path,
|
||||
// Tailwind inlines every import into this stylesheet, which the bundler
|
||||
// then resolves from `base`: a relative url() has to be rebased to keep
|
||||
// pointing next to the sheet it was written in.
|
||||
loadStylesheet: async (id, from) => {
|
||||
const sheet = await host.loadStylesheet(id, from);
|
||||
files.add(sheet.path);
|
||||
if (sheet.base === base) return sheet;
|
||||
return {
|
||||
...sheet,
|
||||
content: rewriteUrls(sheet.content, (url) => host.rebaseUrl(url, sheet.base, base)),
|
||||
};
|
||||
},
|
||||
loadModule: async (id, from, hint) => {
|
||||
const mod = await host.loadModule(id, from, hint);
|
||||
files.add(mod.path);
|
||||
return mod;
|
||||
},
|
||||
});
|
||||
// Features.None: a directive matched in a comment, say. The bundler's output
|
||||
// is what the author would get without Tailwind, so hand it back.
|
||||
if (compiler.features === 0) return undefined;
|
||||
|
||||
const sources: TailwindSource[] = compiler.sources
|
||||
.filter((s) => !s.negated)
|
||||
.map((s) => ({ base: s.base, pattern: s.pattern }));
|
||||
let includeDefault = true;
|
||||
if (compiler.root === "none") {
|
||||
includeDefault = false;
|
||||
} else if (compiler.root) {
|
||||
includeDefault = false;
|
||||
sources.push(compiler.root);
|
||||
}
|
||||
const scanned = await host.scan(sources, includeDefault);
|
||||
const candidates = new Set<string>();
|
||||
for (const file of scanned.files) {
|
||||
files.add(file.path);
|
||||
extractCandidates(file.content, candidates);
|
||||
}
|
||||
return {
|
||||
css: compiler.build([...candidates]),
|
||||
files: [...files],
|
||||
dirs: scanned.dirs,
|
||||
};
|
||||
}
|
||||
|
||||
const CSS_URL = /url\(\s*(["']?)([^"')]+?)\1\s*\)/g;
|
||||
// Absolute, scheme-qualified (data:, https:, …), fragment or variable: not a file path.
|
||||
const NOT_RELATIVE = /^(?:\/|#|[a-z][a-z0-9+.-]*:|var\()/i;
|
||||
|
||||
/** Applies `rebase` to every relative `url()` in `css`. */
|
||||
export function rewriteUrls(css: string, rebase: (url: string) => string): string {
|
||||
return css.replace(CSS_URL, (match, quote, url) =>
|
||||
NOT_RELATIVE.test(url) ? match : `url(${quote}${rebase(url)}${quote})`,
|
||||
);
|
||||
}
|
||||
|
||||
/** The part of a glob before its first wildcard segment: `src/**\/*.tsx` -> `src`. */
|
||||
export function staticPrefix(pattern: string): string {
|
||||
const segments = pattern.split("/");
|
||||
const fixed: string[] = [];
|
||||
for (const segment of segments) {
|
||||
if (/[*?{}[\]!]/.test(segment)) break;
|
||||
fixed.push(segment);
|
||||
}
|
||||
return fixed.join("/");
|
||||
}
|
||||
|
||||
/** Source file extensions scanned for class names by default. */
|
||||
export const TAILWIND_SOURCE_EXTENSIONS = [
|
||||
".tsx",
|
||||
".ts",
|
||||
".jsx",
|
||||
".js",
|
||||
".mjs",
|
||||
".cjs",
|
||||
".mts",
|
||||
".cts",
|
||||
".svelte",
|
||||
".html",
|
||||
".md",
|
||||
".mdx",
|
||||
];
|
||||
Generated
+4
@@ -6787,6 +6787,10 @@ Svelte (\`index.ts\`): \`mount(App, { target: document.getElementById('root')! }
|
||||
|
||||
**Always begin every React file (\`.tsx\`/\`.jsx\`) that uses JSX with \`import React from 'react'\`.** esbuild uses the classic JSX transform, so \`React\` must be in scope wherever JSX appears — a missing import compiles fine but throws \`React is not defined\` at runtime, leaving a blank screen.
|
||||
|
||||
### Styling
|
||||
|
||||
Plain CSS imported from the entrypoint (\`import './index.css'\`) is bundled as is. For **Tailwind CSS v4**, add \`tailwindcss\` (\`^4\`) to \`package.json\` and start \`index.css\` with \`@import "tailwindcss";\`: the bundler then compiles it, generating the utilities used in the app's files and in the workspace's shared \`/ui\` folder, along with \`@theme\`, \`@utility\`, \`@apply\` and \`@custom-variant\`. A design system's stylesheet can live in \`/ui\` and be imported with \`@import "/ui/theme.css";\`. There is no \`tailwind.config.js\`: configure Tailwind in CSS. \`@plugin\` and \`@config\` are compiled only by the CLI (\`wmill app bundle\` / \`wmill app push\`), not by the web editor, and \`wmill app dev\` must be restarted to pick up an edit to one of them or to a file they import. Without the \`tailwindcss\` dependency, Tailwind directives are left uncompiled.
|
||||
|
||||
### Generated bindings (\`wmill.d.ts\` / \`wmill.ts\`)
|
||||
|
||||
The frontend imports a generated module that mirrors the backend runnables. **Never write to it directly** — it gets regenerated whenever backend runnables change. Modifying it by hand will be overwritten.
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Tailwind CSS v4 in `createBundle`: compiled only when the app declares
|
||||
* `tailwindcss`, from the app's own install, scanning the shared `ui/` folder.
|
||||
*/
|
||||
|
||||
import { afterAll, beforeAll, expect, test } from "bun:test";
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
import * as os from "node:os";
|
||||
import { createBundle } from "../src/commands/app/bundle.ts";
|
||||
|
||||
let root: string;
|
||||
const originalCwd = process.cwd();
|
||||
const cliNodeModules = path.resolve(import.meta.dir, "../node_modules");
|
||||
|
||||
function app(name: string, dependencies: Record<string, string>) {
|
||||
const dir = path.join(root, name);
|
||||
const write = (rel: string, content: string) => {
|
||||
fs.mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, rel), content);
|
||||
};
|
||||
write("package.json", JSON.stringify({ dependencies }));
|
||||
write("index.css", `@import "tailwindcss";\n@import "/ui/theme.css";\n@source "../lib";\n`);
|
||||
write(
|
||||
"index.ts",
|
||||
`import "./index.css";\nimport { card } from "/ui/card";\nconsole.log(card, "flex data-[state=open]:p-3");\n` +
|
||||
"console.log(`<div className=\"after:content-['hello']\"></div><div class=\"bg-[url('https://x.test/hero.png')]\"></div>`);\n" +
|
||||
"const open = true;\nconsole.log({ hidden: open, grid: !open }, {italic:open});\n",
|
||||
);
|
||||
// The app's own install, as `bun install` would leave it.
|
||||
fs.symlinkSync(cliNodeModules, path.join(dir, "node_modules"));
|
||||
return dir;
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
root = fs.mkdtempSync(path.join(os.tmpdir(), "raw-app-tailwind-"));
|
||||
fs.mkdirSync(path.join(root, "ui"));
|
||||
fs.writeFileSync(
|
||||
path.join(root, "ui/theme.css"),
|
||||
`@theme { --color-brand: #123456; }\n@utility glow { box-shadow: 0 0 2px red; }\n`,
|
||||
);
|
||||
fs.writeFileSync(path.join(root, "ui/card.ts"), `export const card = "bg-brand glow";\n`);
|
||||
// A component library built to dist/, scanned through an explicit @source.
|
||||
fs.mkdirSync(path.join(root, "lib/dist"), { recursive: true });
|
||||
fs.writeFileSync(path.join(root, "lib/dist/button.js"), `export const button = "tracking-widest";\n`);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
process.chdir(originalCwd);
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function bundle(dir: string) {
|
||||
process.chdir(dir);
|
||||
return createBundle({
|
||||
entryPoint: path.join(dir, "index.ts"),
|
||||
minify: false,
|
||||
sharedUiDir: path.join(root, "ui"),
|
||||
});
|
||||
}
|
||||
|
||||
test("an app declaring tailwindcss gets the utilities it and ui/ use", async () => {
|
||||
const { css } = await bundle(app("with", { tailwindcss: "^4.1.0" }));
|
||||
expect(css).not.toContain("@tailwind");
|
||||
for (const selector of [
|
||||
".hidden",
|
||||
".grid",
|
||||
".italic",
|
||||
".tracking-widest",
|
||||
".bg-brand",
|
||||
"#123456",
|
||||
".glow",
|
||||
".flex",
|
||||
"data-\\[state\\=open\\]\\:p-3",
|
||||
"after\\:content-\\[\\'hello\\'\\]",
|
||||
"https://x.test/hero.png",
|
||||
]) {
|
||||
expect(css).toContain(selector);
|
||||
}
|
||||
});
|
||||
|
||||
test("an app without the dependency builds as before", async () => {
|
||||
const { css } = await bundle(app("without", {}));
|
||||
expect(css).toContain("@tailwind utilities");
|
||||
expect(css).not.toContain(".bg-brand");
|
||||
});
|
||||
|
||||
// A config is the app's own Node module: it must run from where it lives.
|
||||
test("an @config runs with its own __dirname and imports", async () => {
|
||||
const dir = path.join(root, "config");
|
||||
fs.mkdirSync(dir);
|
||||
fs.symlinkSync(cliNodeModules, path.join(dir, "node_modules"));
|
||||
fs.writeFileSync(path.join(dir, "package.json"), JSON.stringify({ dependencies: { tailwindcss: "^4.1.0" } }));
|
||||
fs.writeFileSync(path.join(dir, "index.css"), `@import "tailwindcss";\n@config "./tw.config.cjs";\n`);
|
||||
fs.writeFileSync(path.join(dir, "index.ts"), `import "./index.css";\nconsole.log("text-brand");\n`);
|
||||
fs.writeFileSync(path.join(dir, "tokens.json"), JSON.stringify({ brand: "#123456" }));
|
||||
fs.writeFileSync(
|
||||
path.join(dir, "tw.config.cjs"),
|
||||
`const path = require("node:path");\n` +
|
||||
`const { brand } = require(path.join(__dirname, "tokens.json"));\n` +
|
||||
`module.exports = { theme: { extend: { colors: { brand } } } };\n`,
|
||||
);
|
||||
process.chdir(dir);
|
||||
const { css } = await createBundle({ entryPoint: path.join(dir, "index.ts"), minify: false });
|
||||
expect(css).toContain("#123456");
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"baseUrl": "https://pub-06154ed168a24e73a86ab84db6bf15d8.r2.dev",
|
||||
"version": "693aa1f",
|
||||
"sha256": "13ab69ab94e496e8254f01337eaa5ef9e2197fb0bf64f78100eaab66cb3c1eff"
|
||||
"version": "5ae35e6",
|
||||
"sha256": "cdc948ce65b3ed0befbbfab7c816f2db63ae9207bbd85653d3484516c7ac3238"
|
||||
}
|
||||
|
||||
@@ -1112,6 +1112,10 @@ Svelte (\`index.ts\`): \`mount(App, { target: document.getElementById('root')! }
|
||||
|
||||
**Always begin every React file (\`.tsx\`/\`.jsx\`) that uses JSX with \`import React from 'react'\`.** esbuild uses the classic JSX transform, so \`React\` must be in scope wherever JSX appears — a missing import compiles fine but throws \`React is not defined\` at runtime, leaving a blank screen.
|
||||
|
||||
### Styling
|
||||
|
||||
Plain CSS imported from the entrypoint (\`import './index.css'\`) is bundled as is. For **Tailwind CSS v4**, add \`tailwindcss\` (\`^4\`) to \`package.json\` and start \`index.css\` with \`@import "tailwindcss";\`: the bundler then compiles it, generating the utilities used in the app's files and in the workspace's shared \`/ui\` folder, along with \`@theme\`, \`@utility\`, \`@apply\` and \`@custom-variant\`. A design system's stylesheet can live in \`/ui\` and be imported with \`@import "/ui/theme.css";\`. There is no \`tailwind.config.js\`: configure Tailwind in CSS. \`@plugin\` and \`@config\` are compiled only by the CLI (\`wmill app bundle\` / \`wmill app push\`), not by the web editor, and \`wmill app dev\` must be restarted to pick up an edit to one of them or to a file they import. Without the \`tailwindcss\` dependency, Tailwind directives are left uncompiled.
|
||||
|
||||
### Generated bindings (\`wmill.d.ts\` / \`wmill.ts\`)
|
||||
|
||||
The frontend imports a generated module that mirrors the backend runnables. **Never write to it directly** — it gets regenerated whenever backend runnables change. Modifying it by hand will be overwritten.
|
||||
|
||||
@@ -317,6 +317,10 @@ Svelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`.
|
||||
|
||||
**Always begin every React file (`.tsx`/`.jsx`) that uses JSX with `import React from 'react'`.** esbuild uses the classic JSX transform, so `React` must be in scope wherever JSX appears — a missing import compiles fine but throws `React is not defined` at runtime, leaving a blank screen.
|
||||
|
||||
### Styling
|
||||
|
||||
Plain CSS imported from the entrypoint (`import './index.css'`) is bundled as is. For **Tailwind CSS v4**, add `tailwindcss` (`^4`) to `package.json` and start `index.css` with `@import "tailwindcss";`: the bundler then compiles it, generating the utilities used in the app's files and in the workspace's shared `/ui` folder, along with `@theme`, `@utility`, `@apply` and `@custom-variant`. A design system's stylesheet can live in `/ui` and be imported with `@import "/ui/theme.css";`. There is no `tailwind.config.js`: configure Tailwind in CSS. `@plugin` and `@config` are compiled only by the CLI (`wmill app bundle` / `wmill app push`), not by the web editor, and `wmill app dev` must be restarted to pick up an edit to one of them or to a file they import. Without the `tailwindcss` dependency, Tailwind directives are left uncompiled.
|
||||
|
||||
### Generated bindings (`wmill.d.ts` / `wmill.ts`)
|
||||
|
||||
The frontend imports a generated module that mirrors the backend runnables. **Never write to it directly** — it gets regenerated whenever backend runnables change. Modifying it by hand will be overwritten.
|
||||
|
||||
@@ -76,6 +76,10 @@ Svelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`.
|
||||
|
||||
**Always begin every React file (`.tsx`/`.jsx`) that uses JSX with `import React from 'react'`.** esbuild uses the classic JSX transform, so `React` must be in scope wherever JSX appears — a missing import compiles fine but throws `React is not defined` at runtime, leaving a blank screen.
|
||||
|
||||
### Styling
|
||||
|
||||
Plain CSS imported from the entrypoint (`import './index.css'`) is bundled as is. For **Tailwind CSS v4**, add `tailwindcss` (`^4`) to `package.json` and start `index.css` with `@import "tailwindcss";`: the bundler then compiles it, generating the utilities used in the app's files and in the workspace's shared `/ui` folder, along with `@theme`, `@utility`, `@apply` and `@custom-variant`. A design system's stylesheet can live in `/ui` and be imported with `@import "/ui/theme.css";`. There is no `tailwind.config.js`: configure Tailwind in CSS. `@plugin` and `@config` are compiled only by the CLI (`wmill app bundle` / `wmill app push`), not by the web editor, and `wmill app dev` must be restarted to pick up an edit to one of them or to a file they import. Without the `tailwindcss` dependency, Tailwind directives are left uncompiled.
|
||||
|
||||
### Generated bindings (`wmill.d.ts` / `wmill.ts`)
|
||||
|
||||
The frontend imports a generated module that mirrors the backend runnables. **Never write to it directly** — it gets regenerated whenever backend runnables change. Modifying it by hand will be overwritten.
|
||||
|
||||
Reference in New Issue
Block a user