Files
sure/bin/tokens.mjs
Guillem Arias Fauste e250d266e8 refactor(design-system): single-source design tokens via DTCG JSON (#1604)
* refactor(css): rename maybe-design-system → sure-design-system

Rename design system CSS file and directory to match the project name
post-rebrand. Update internal imports plus references in CLAUDE.md,
copilot instructions, and Junie guidelines. No CSS rules change; Tailwind
compiled output is byte-identical.

* build(tokens): introduce single-source tokens.json + build script

Make the design system a tool-agnostic single source of truth.

- tokens/sure.tokens.json: every primitive, semantic alias, and Tailwind
  utility token in one W3C DTCG-flavored file.
- tools/tokens/build.mjs: ~120 LOC plain Node script (zero deps) that
  resolves token references and emits Tailwind v4 source CSS.
- app/assets/tailwind/sure-design-system/_generated.css: build output —
  the @theme block, dark-mode overrides, and 50 @utility blocks.
- Hand-written CSS split into base.css (element resets), components.css
  (form-field/checkbox/tooltip/qrcode), and prose.css (prose dark
  overrides). The 5 maybe-design-system/*-utils.css files are removed —
  their contents now live inside _generated.css.
- application.css gains `@source not "../../../tokens"` so Tailwind's
  content scanner ignores the JSON file (it would otherwise treat token
  keys like `bg-surface` as "used" classes and skip tree-shaking).
- package.json: `npm run tokens:build` and `npm run tokens:check`.
- .gitattributes: _generated.css marked linguist-generated.

Functional parity verified: compiled `tailwind.css` has the same 378 CSS
variables and byte-identical non-:root rules as before. The only diff is
which of Tailwind's internal `:root,:host` blocks each variable lands in,
which is invisible to the browser.

* build(tokens): wire tokens build into bin/setup

Run `npm install && npm run tokens:build` after bundle so a fresh
checkout reaches a runnable state with one command.

* docs(css): explain @source not exclusion of tokens dir

Adds a comment so future readers know why tokens/ is excluded from
Tailwind's content scanner (utility keys in the JSON would otherwise
be treated as used classes and bypass tree-shaking).

* docs(tokens): add tokens/README

Schema overview, workflow, custom $extensions reference, and a list of
the edge cases the build script handles. Lands as a follow-up commit on
the same branch so reviewers landing on the diff have something to read
before opening sure.tokens.json.

* Update tokens/README.md

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: Guillem Arias Fauste <gariasf@proton.me>

* docs(tokens): swap em-dashes for colons in README

* refactor(tokens): move tokens to design/, build script to bin/

Per PR review feedback (jjmata):
- tokens/ → design/tokens/ — top-level design/ namespace leaves room for
  future design assets (Figma exports, design docs, etc.) without
  cluttering the repo root.
- tools/tokens/build.mjs → bin/tokens.mjs — keeps all developer-facing
  scripts in one place (bin/) regardless of language.

Path references updated in:
- bin/tokens.mjs (TOKENS / OUT / generated header)
- package.json (tokens:build, tokens:check)
- app/assets/tailwind/application.css (@source not directive)
- app/assets/tailwind/sure-design-system.css (comment)
- app/assets/tailwind/sure-design-system/_generated.css (regenerated)
- design/tokens/README.md (workflow examples)

bin/tokens.mjs gains a +x bit. Tailwind compile verified.

* docs(tokens): normalize README paths to repo-root style

Files section was mixing relative-to-README paths (`../../bin/...`)
with repo-root paths (`design/tokens/...`) used elsewhere in the same
README. Switching everything to repo-root style for consistency.

* fix(tokens): validate {ref} placeholders against the known token set

CodeRabbit caught: resolveTemplate() and refToClass() would happily emit
var(--foo-bar) or bg-foo-bar for any {foo.bar} input, so a typo in
design/tokens/sure.tokens.json would silently ship broken CSS.

Now build() pre-computes the set of valid token paths from the walker,
and resolveTemplate() / refToClass() throw a clean "[tokens] Unknown
token reference ..." error when a placeholder doesn't match. Top-level
catch surfaces just the message and exits 1, no Node stack trace noise.

Smoke-tested both directions:
- Valid JSON: builds.
- {color.gray.NONEXISTENT|5%}: fails with clear message, exit 1.

* docs(tokens): humanize README prose

* One more refenrece to `maybe-design-system`

---------

Signed-off-by: Guillem Arias Fauste <gariasf@proton.me>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Juan José Mata <jjmata@jjmata.com>
2026-05-01 14:46:33 +02:00

173 lines
5.4 KiB
JavaScript
Executable File

#!/usr/bin/env node
// Sure design tokens build.
// Reads design/tokens/sure.tokens.json (W3C DTCG-flavored), emits one Tailwind v4 CSS file.
import { readFileSync, writeFileSync } from "node:fs";
import { resolve, dirname } from "node:path";
import { fileURLToPath } from "node:url";
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const TOKENS = resolve(ROOT, "design/tokens/sure.tokens.json");
const OUT = resolve(ROOT, "app/assets/tailwind/sure-design-system/_generated.css");
const HEADER = `/*
* GENERATED — do not edit by hand.
* Source: design/tokens/sure.tokens.json
* Build: npm run tokens:build
*/
`;
// Single inline keyframe; not worth its own JSON token.
const KEYFRAMES = ` @keyframes stroke-fill {
0% { stroke-dashoffset: 43.9822971503; }
100% { stroke-dashoffset: 0; }
}`;
// Yield [path, node] for every token leaf (object with $value or $type === "utility").
function* walk(node, path = []) {
if (!node || typeof node !== "object") return;
if ("$value" in node || node.$type === "utility") {
yield [path, node];
if (!node.$value || typeof node.$value !== "object") return;
}
for (const [k, v] of Object.entries(node)) {
if (k.startsWith("$")) continue;
yield* walk(v, [...path, k]);
}
}
// Path → CSS variable name. Trailing `DEFAULT` segment is dropped (Tailwind convention).
function varName(path) {
const cleaned = path[path.length - 1] === "DEFAULT" ? path.slice(0, -1) : path;
return "--" + cleaned.join("-");
}
// Set of valid token paths (e.g. "color.gray.50", "utility.border-tertiary").
// Populated once at the start of build(); referenced by resolveTemplate() and
// refToClass() so a typo'd `{ref}` fails the build instead of emitting broken
// CSS or a dangling utility class.
let VALID_PATHS = null;
function assertKnownRef(ref, source) {
if (VALID_PATHS && !VALID_PATHS.has(ref)) {
throw new Error(
`[tokens] Unknown token reference \`${source}\` (resolved path: \`${ref}\`). ` +
`Add it to design/tokens/sure.tokens.json or fix the typo.`
);
}
}
// Resolve template strings:
// {a.b} → var(--a-b)
// {a.b|N%} → --alpha(var(--a-b) / N%)
function resolveTemplate(s) {
if (typeof s !== "string") return s;
return s.replace(/\{([^|}]+)(?:\|([^}]+))?\}/g, (whole, ref, alpha) => {
assertKnownRef(ref, whole);
const cssVar = "--" + ref.split(".").join("-");
return alpha ? `--alpha(var(${cssVar}) / ${alpha})` : `var(${cssVar})`;
});
}
// {color.gray.50} or {utility.border-tertiary} → Tailwind utility class name with the given prefix.
// Drops a leading `color.` segment (since Tailwind colors are referenced as `bg-gray-50`, not `bg-color-gray-50`).
function refToClass(refStr, prefix) {
const inner = refStr.replace(/^\{|\}$/g, "");
assertKnownRef(inner, refStr);
if (inner.startsWith("utility.")) return inner.slice("utility.".length);
const parts = inner.split(".");
if (parts[0] === "color") parts.shift();
return prefix + "-" + parts.join("-");
}
// Utility @apply argument. If value is a raw class string (no `{}`), pass through.
// If value is a `{ref}`, resolve to a Tailwind class via the given prefix.
function utilityClasses(value, prefix) {
if (typeof value !== "string") return "";
if (!value.includes("{")) return value;
return refToClass(value, prefix);
}
function build() {
const tokens = JSON.parse(readFileSync(TOKENS, "utf8"));
// Pre-compute the set of valid token paths so refs can be validated as we go.
VALID_PATHS = new Set();
for (const [path] of walk(tokens)) {
VALID_PATHS.add(path.join("."));
}
const themeLines = [];
const darkLines = [];
const utilityBlocks = [];
for (const [path, node] of walk(tokens)) {
if (path[0] === "utility") {
const name = path.slice(1).join("-");
const ext = node.$extensions || {};
if (ext["sure.compose"]) {
utilityBlocks.push(`@utility ${name} {\n @apply ${ext["sure.compose"].join(" ")};\n}`);
continue;
}
const prefix = ext["sure.utility"]?.prefix;
const raw = ext["sure.utility"]?.raw;
const dark = ext["sure.dark"];
const lightLine = raw
? `${raw}: ${resolveTemplate(node.$value)};`
: `@apply ${utilityClasses(node.$value, prefix)};`;
let block = `@utility ${name} {\n ${lightLine}`;
if (dark) {
const darkLine = raw
? `${raw}: ${resolveTemplate(dark)};`
: `@apply ${utilityClasses(dark, prefix)};`;
block += `\n\n @variant theme-dark {\n ${darkLine}\n }`;
}
block += `\n}`;
utilityBlocks.push(block);
continue;
}
const name = varName(path);
themeLines.push(` ${name}: ${resolveTemplate(node.$value)};`);
const dark = node.$extensions?.["sure.dark"];
if (dark !== undefined) {
darkLines.push(` ${name}: ${resolveTemplate(dark)};`);
}
}
const css = `${HEADER}
@theme {
${themeLines.join("\n")}
${KEYFRAMES}
}
@layer base {
[data-theme="dark"] {
${darkLines.join("\n")}
}
}
${utilityBlocks.join("\n\n")}
`;
writeFileSync(OUT, css);
console.log(`tokens → ${OUT.replace(ROOT + "/", "")} (${themeLines.length} primitives, ${darkLines.length} dark overrides, ${utilityBlocks.length} utilities)`);
}
try {
build();
} catch (err) {
// Token errors are user-facing; the stack trace is noise.
if (err.message?.startsWith("[tokens]")) {
console.error(err.message);
process.exit(1);
}
throw err;
}