sailfork / t3code-github / apps/ desktop/ scripts/ build-preview-annotation-css.mjs

import * as NodeFSP from "node:fs/promises";
import * as NodeModule from "node:module";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";

import { compile } from "tailwindcss";

const directory = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
const appRoot = NodePath.join(directory, "..");
const sourcePath = NodePath.join(appRoot, "src", "preview", "Annotation.css");
const preloadPath = NodePath.join(appRoot, "src", "preview", "PickPreload.ts");
const outputPath = NodePath.join(appRoot, "src", "preview", "AnnotationStyles.generated.ts");
const require = NodeModule.createRequire(import.meta.url);
const tailwindRoot = NodePath.dirname(require.resolve("tailwindcss/package.json"));

const [annotationSource, preloadSource, themeSource, preflightSource] = await Promise.all([
  NodeFSP.readFile(sourcePath, "utf8"),
  NodeFSP.readFile(preloadPath, "utf8"),
  NodeFSP.readFile(NodePath.join(tailwindRoot, "theme.css"), "utf8"),
  NodeFSP.readFile(NodePath.join(tailwindRoot, "preflight.css"), "utf8"),
]);

const candidates = new Set(
  Array.from(preloadSource.matchAll(/!?-?[A-Za-z0-9_:@/.[\]()%,-]+/g), (match) => match[0]),
);
const compilerInput = [
  themeSource,
  preflightSource,
  annotationSource.replace('@import "tailwindcss";', "@tailwind utilities;"),
].join("\n");
const compiler = await compile(compilerInput, { base: appRoot });
// Shadow-root styles cannot register @property defaults. Make Tailwind's
// fallback unconditional so border, shadow, and ring utilities have defaults.
const compiledCss = compiler.build([...candidates]);
const css = compiledCss.replace(
  /(@layer properties \{\n)  @supports [^\n]*\{\n([\s\S]*?)\n  \}\n(\})/,
  "$1$2\n$3",
);
if (css === compiledCss || /@layer properties\s*\{\s*@supports\b/.test(css)) {
  throw new Error("Tailwind @property fallback was not unwrapped; update the pattern above.");
}
const encodedCss = `'${css
  .replaceAll("\\", "\\\\")
  .replaceAll("'", "\\'")
  .replaceAll("\r", "\\r")
  .replaceAll("\n", "\\n")}'`;
const moduleSource = `// Generated by scripts/build-preview-annotation-css.mjs. Do not edit.\nexport const previewAnnotationStyles =\n  ${encodedCss};\n`;

await NodeFSP.writeFile(outputPath, moduleSource);