Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(cli): warn when a theme names fonts it does not load (#5045)

AK3afdd73d4b89
diff --git a/.changeset/theme-build-font-warning.md b/.changeset/theme-build-font-warning.md
new file mode 100644
index 0000000000..2e6aea2f6d
--- /dev/null
+++ b/.changeset/theme-build-font-warning.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] `astryx theme build` warns when a theme names fonts it does not load. The resolved `--font-family-*` tokens and component-override `fontFamily` values are checked against CSS generics and known system families; anything else gets one warning per family in the receipt and, after the install instructions, the `<link>`/`@font-face` snippet to add. `astryx docs typography` gains a Loading Custom Fonts section (Google Fonts and self-hosted recipes, `font-display: swap`, real fallback stacks), and the theme docs' production-build section points at it (#5015).
+
+@AKnassa
diff --git a/packages/cli/api/theme/build/build.font-warning.test.mjs b/packages/cli/api/theme/build/build.font-warning.test.mjs
new file mode 100644
index 0000000000..ae925b4562
--- /dev/null
+++ b/packages/cli/api/theme/build/build.font-warning.test.mjs
@@ -0,0 +1,161 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * API-contract tests for the font-loading warning in `themeBuild()` (#5015):
+ * a theme that names font families it does not load gets one entry per family
+ * in the `theme.build` receipt's `warnings` array, on BOTH load paths — a raw
+ * typography config (resolved through core's defineTheme) and an
+ * already-resolved theme that sets `--font-family-*` tokens directly. Themes
+ * that only name generics or known system families warn about nothing, and
+ * the warning never breaks the API's silence contract (default noopLogger).
+ *
+ * Needs a built core — the `node` project's globalSetup
+ * (vitest.global-setup.node.mjs) builds it once before workers fork.
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {themeBuild} from './build.mjs';
+
+vi.setConfig({testTimeout: 30000});
+
+let tmpDir;
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-theme-fonts-api-'));
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('themeBuild() — font-loading warnings in the receipt', () => {
+ it('warns once per unloaded family for a typography config (heading inherits body without duplicating)', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'fonty.mjs'),
+ `export default {
+ name: 'fonty',
+ typography: {
+ body: {family: 'Space Grotesk', fallbacks: 'Arial, sans-serif'},
+ code: {family: 'JetBrains Mono'},
+ },
+};\n`,
+ );
+
+ const result = await themeBuild('fonty.mjs', {}, {cwd: tmpDir});
+
+ expect(result?.type).toBe('theme.build');
+ const warnings = result?.data.warnings ?? [];
+ expect(warnings).toEqual(
+ expect.arrayContaining([
+ expect.stringContaining('Font "Space Grotesk"'),
+ expect.stringContaining('Font "JetBrains Mono"'),
+ ]),
+ );
+ // Heading inherits body's family; the shared family warns exactly once.
+ expect(warnings.filter(w => w.includes('Space Grotesk'))).toHaveLength(1);
+ });
+
+ it('warns for an already-resolved theme: font-family tokens and component overrides, nothing else', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'raw.mjs'),
+ `export default {
+ name: 'raw',
+ tokens: {
+ '--font-family-body': '"Bungee", cursive',
+ '--font-size-base': '1rem',
+ },
+ components: {button: {base: {fontFamily: 'Orbitron'}}},
+};\n`,
+ );
+
+ const result = await themeBuild('raw.mjs', {}, {cwd: tmpDir});
+
+ // Exactly the two named families — a non-family --font-* token must not
+ // produce a bogus "Font \\"1rem\\"" entry, and the components half of the
+ // feature must survive the real themeBuild path, not just the unit helper.
+ const fontWarnings = (result?.data.warnings ?? []).filter(w =>
+ w.startsWith('Font "'),
+ );
+ expect(fontWarnings).toEqual([
+ expect.stringContaining('Font "Bungee"'),
+ expect.stringContaining('Font "Orbitron"'),
+ ]);
+ });
+
+ it('warns for a family named only inside a pseudo-class component override (defineTheme path)', async () => {
+ // ':hover' blocks are legal override values (generateThemeRules), and the
+ // typography path deep-merges author components with generated ones — a
+ // webfont hiding at that depth must survive the merge and still warn.
+ fs.writeFileSync(
+ path.join(tmpDir, 'pseudo.mjs'),
+ `export default {
+ name: 'pseudo',
+ typography: {
+ body: {family: 'Helvetica', fallbacks: 'Arial, sans-serif'},
+ },
+ components: {
+ button: {base: {':hover': {fontFamily: '"Rubik Doodle", cursive'}}},
+ },
+};\n`,
+ );
+
+ const result = await themeBuild('pseudo.mjs', {}, {cwd: tmpDir});
+
+ const fontWarnings = (result?.data.warnings ?? []).filter(w =>
+ w.startsWith('Font "'),
+ );
+ // Exactly the hidden family — Helvetica/Arial are system fonts.
+ expect(fontWarnings).toEqual([
+ expect.stringContaining('Font "Rubik Doodle"'),
+ ]);
+ });
+
+ it('warns about nothing when every named family is a generic or known system font', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'sys.mjs'),
+ `export default {
+ name: 'sys',
+ tokens: {
+ '--color-bg': '#fff',
+ '--font-family-body': 'Helvetica, Arial, sans-serif',
+ },
+};\n`,
+ );
+
+ const result = await themeBuild('sys.mjs', {}, {cwd: tmpDir});
+
+ expect(result?.type).toBe('theme.build');
+ expect(result?.data.warnings).toEqual([]);
+ });
+
+ it('stays silent under the default noopLogger even when font warnings fire', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'loud.mjs'),
+ `export default { name: 'loud', tokens: { '--font-family-body': '"Orbitron", sans-serif' } };\n`,
+ );
+
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const outSpy = vi
+ .spyOn(process.stdout, 'write')
+ .mockImplementation(() => true);
+
+ try {
+ const result = await themeBuild('loud.mjs', {}, {cwd: tmpDir});
+ expect(result?.data.warnings).toEqual(
+ expect.arrayContaining([expect.stringContaining('Font "Orbitron"')]),
+ );
+ expect(logSpy).not.toHaveBeenCalled();
+ expect(warnSpy).not.toHaveBeenCalled();
+ expect(errSpy).not.toHaveBeenCalled();
+ expect(outSpy).not.toHaveBeenCalled();
+ } finally {
+ logSpy.mockRestore();
+ warnSpy.mockRestore();
+ errSpy.mockRestore();
+ outSpy.mockRestore();
+ }
+ });
+});
diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjs
index 39200d77ca..4f9cc85da7 100644
--- a/packages/cli/api/theme/build/build.mjs
+++ b/packages/cli/api/theme/build/build.mjs
@@ -11,8 +11,10 @@
* - A JS module that re-exports the built theme (+ icon registry)
* - A .d.ts (plus an optional .variants.d.ts for custom prop values)
*
- * It performs the writes and returns a `theme.build` receipt, or `null` when
- * the theme produced no CSS (nothing to build). Errors throw AstryxError (with
+ * It performs the writes and returns a `theme.build` receipt — its `warnings`
+ * carry override problems and any fonts the theme names but does not load
+ * (font-warning.mjs) — or `null` when the theme produced no CSS (nothing to
+ * build). Errors throw AstryxError (with
* a stable code). Human progress is emitted through the shared `logger`
* (silent by default), so the CLI keeps its exact output while a programmatic
* caller stays quiet.
@@ -41,6 +43,10 @@ import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
import {AstryxError} from '../../error.mjs';
import {logger} from '../../logger.mjs';
import {loadComponentDoc} from '../../../foundation/discovery/component-loader.mjs';
+import {
+ collectUnloadedFonts,
+ formatFontLoadingHelp,
+} from './font-warning.mjs';
// Import shared theme processing from core. `astryx theme build` MUST produce the
// exact same CSS as the `<Theme>` runtime, so it has exactly one generation
@@ -1341,16 +1347,17 @@ Or with a <link> tag:
</Theme>
`);
- // Print font declaration warnings (derived from typography roles)
- if (resolvedTheme && resolvedTheme.fonts && resolvedTheme.fonts.length > 0) {
- logger.log(
- `\n⚠ Theme "${themeDef.name}" requires fonts not included in the build:`,
- );
- for (const font of resolvedTheme.fonts) {
- logger.log(` ${font.family} — add to your document <head>:`);
- logger.log(` <link rel="stylesheet" href="${font.url}" />`);
- }
- logger.log('');
+ // Fonts the theme names but nothing loads (#5015). Resolved tokens and
+ // component overrides carry the final font-family values on both load
+ // paths, so this sees jiti-resolved and legacy themes alike.
+ const unloadedFonts = collectUnloadedFonts(resolvedTheme);
+ for (const family of unloadedFonts) {
+ const msg = `Font "${family}" is named by this theme but not loaded — add a <link> or @font-face in your app (recipe: astryx docs typography)`;
+ warningMessages.push(msg);
+ logger.warn(` ⚠ ${msg}`);
+ }
+ if (unloadedFonts.length > 0) {
+ logger.log(formatFontLoadingHelp(themeDef.name, unloadedFonts));
}
return {
diff --git a/packages/cli/api/theme/build/font-warning.mjs b/packages/cli/api/theme/build/font-warning.mjs
new file mode 100644
index 0000000000..afbf0894b4
--- /dev/null
+++ b/packages/cli/api/theme/build/font-warning.mjs
@@ -0,0 +1,214 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Font-loading warning helpers for `astryx theme build` (#5015).
+ *
+ * Nothing in the pipeline loads font files — defineTheme and the built CSS
+ * only set `font-family` — so a theme that names a webfont renders in the
+ * fallback typeface on every machine whose app never loads it, and no step
+ * says so. These helpers close that gap at build time.
+ *
+ * `collectUnloadedFonts` inspects a RESOLVED theme (raw typography configs
+ * are already collapsed into `--font-family-*` tokens by the time the build
+ * sees the theme, so tokens + component-override `fontFamily` values are the
+ * complete font surface on both load paths) and returns the families that
+ * are neither CSS generics nor known preinstalled system fonts. Unrecognized
+ * names are assumed to be webfonts on purpose: a missed warning hides the
+ * bug, a spurious one costs a glance.
+ *
+ * @input A resolved theme object ({tokens, components}) from build.mjs.
+ * @output Ordered, case-insensitively deduped family names, and the human
+ * help snippet (<link> pair + @font-face) printed after the install
+ * instructions.
+ * @position Sits beside build.mjs (api/theme/build/). Pure functions, no IO,
+ * so the `--json` receipt and the human output share one source of truth.
+ */
+
+// font-family values that never need loading: CSS generic families, the ui-*
+// system keywords, and CSS-wide keywords that can appear in a token value.
+const GENERIC_KEYWORDS = new Set([
+ 'serif',
+ 'sans-serif',
+ 'monospace',
+ 'cursive',
+ 'fantasy',
+ 'system-ui',
+ 'math',
+ 'emoji',
+ 'fangsong',
+ 'ui-serif',
+ 'ui-sans-serif',
+ 'ui-monospace',
+ 'ui-rounded',
+ 'inherit',
+ 'initial',
+ 'unset',
+ 'revert',
+ 'revert-layer',
+]);
+
+// Families a clean machine already has: the members of core's own default
+// stacks (tokens.stylex.ts typographyDefaults) plus the classic web-safe
+// macOS/Windows set. Deliberately short — an unknown family warns, and for a
+// preinstalled rarity that is a one-line false alarm, not a broken theme.
+const SYSTEM_FAMILIES = new Set([
+ '-apple-system',
+ 'blinkmacsystemfont',
+ 'segoe ui',
+ 'segoe ui emoji',
+ 'segoe ui symbol',
+ 'roboto',
+ 'helvetica',
+ 'helvetica neue',
+ 'arial',
+ 'arial black',
+ 'sf mono',
+ 'sf pro',
+ 'sf pro text',
+ 'sf pro display',
+ 'monaco',
+ 'consolas',
+ 'menlo',
+ 'courier',
+ 'courier new',
+ 'georgia',
+ 'times',
+ 'times new roman',
+ 'verdana',
+ 'tahoma',
+ 'trebuchet ms',
+ 'impact',
+ 'palatino',
+ 'cambria',
+ 'calibri',
+ 'lucida grande',
+ 'lucida console',
+ 'gill sans',
+ 'brush script mt',
+ 'snell roundhand',
+ 'old english text mt',
+ // Linux staples — the shipped themes' fallback stacks name these on
+ // purpose (e.g. neutral's code stack ends in Liberation Mono).
+ 'liberation mono',
+ 'liberation sans',
+ 'liberation serif',
+ 'dejavu sans',
+ 'dejavu sans mono',
+]);
+
+/**
+ * Split a CSS font-family value into clean family names. Complete `var()`
+ * calls are stripped first — neither the reference nor its fallback
+ * arguments are this theme's own family declarations (the referenced token
+ * is checked in its own right) — then names are unquoted and
+ * whitespace-collapsed, and any remaining function-shaped fragment is
+ * dropped. The unquoted branch of the tokenizer cannot start at whitespace
+ * or a quote, so a quoted name is always taken whole even mid-list (commas
+ * inside quotes stay inside the name).
+ *
+ * @param {string} value
+ * @returns {string[]}
+ */
+function splitFamilies(value) {
+ const families = [];
+ const withoutVars = value.replace(/var\([^()]*(?:\([^()]*\)[^()]*)*\)/g, '');
+ for (const segment of withoutVars.match(/"[^"]*"|'[^']*'|[^,"'\s][^,]*/g) ??
+ []) {
+ let name = segment.trim();
+ if (!name) continue;
+ // /s: a quoted name may span lines (template-literal theme sources).
+ const quoted = /^(["']).*\1$/s.test(name);
+ if (quoted) name = name.slice(1, -1);
+ name = name.trim().replace(/\s+/g, ' ');
+ if (!name || (!quoted && /[()]/.test(name))) continue;
+ families.push(name);
+ }
+ return families;
+}
+
+/**
+ * Collect the font families a resolved theme names but does not load —
+ * every `--font-family-*` token plus every component-override `fontFamily`,
+ * minus generics, CSS-wide keywords, `var()` references, and known system
+ * families. Source order, first-seen casing, deduped case-insensitively.
+ *
+ * @param {{tokens?: Record<string, string>, components?: object}} resolvedTheme
+ * @returns {string[]}
+ */
+export function collectUnloadedFonts(resolvedTheme) {
+ const seen = new Set();
+ /** @type {string[]} */
+ const unloaded = [];
+
+ /** @param {unknown} value */
+ const consider = value => {
+ if (typeof value !== 'string') return;
+ for (const family of splitFamilies(value)) {
+ const key = family.toLowerCase();
+ if (GENERIC_KEYWORDS.has(key) || SYSTEM_FAMILIES.has(key)) continue;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ unloaded.push(family);
+ }
+ };
+
+ for (const [token, value] of Object.entries(resolvedTheme?.tokens ?? {})) {
+ if (token.startsWith('--font-family-')) consider(value);
+ }
+
+ // Component overrides are plain CSS maps of unknown depth (style keys,
+ // nested at-rule blocks) — walk them and pick up every fontFamily.
+ /** @param {unknown} node */
+ const walk = node => {
+ if (!node || typeof node !== 'object') return;
+ for (const [key, value] of Object.entries(node)) {
+ if (key === 'fontFamily') consider(value);
+ else walk(value);
+ }
+ };
+ walk(resolvedTheme?.components);
+
+ return unloaded;
+}
+
+/**
+ * Render the human fix printed after the install instructions: which fonts
+ * the theme names but does not load, the Google Fonts `<link>` recipe, and
+ * the self-hosted `@font-face` alternative.
+ *
+ * @param {string} themeName
+ * @param {string[]} families
+ * @returns {string}
+ */
+export function formatFontLoadingHelp(themeName, families) {
+ const named = families.map(f => `"${f}"`).join(', ');
+ const cssHref =
+ 'https://fonts.googleapis.com/css2?' +
+ families
+ .map(f => `family=${encodeURIComponent(f).replace(/%20/g, '+')}`)
+ .join('&') +
+ '&display=swap';
+ const first = families[0];
+ const slug = first.toLowerCase().replace(/ /g, '-');
+ return `
+⚠ Theme "${themeName}" names fonts it does not load: ${named}
+ The built CSS only sets font-family — load these in your app, or every
+ browser quietly falls back.
+
+ Google Fonts (add :wght@… axes as your theme's weights require):
+
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
+ <link rel="stylesheet" href="${cssHref}" />
+
+ Self-hosted (repeat per family and weight):
+
+ @font-face {
+ font-family: ${JSON.stringify(first)};
+ src: url('/fonts/${slug}.woff2') format('woff2');
+ font-display: swap;
+ }
+
+ Recipe and fallback-stack guidance: astryx docs typography
+`;
+}
diff --git a/packages/cli/api/theme/build/font-warning.test.mjs b/packages/cli/api/theme/build/font-warning.test.mjs
new file mode 100644
index 0000000000..280fcef9b6
--- /dev/null
+++ b/packages/cli/api/theme/build/font-warning.test.mjs
@@ -0,0 +1,242 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Unit tests for the font-loading warning helpers behind `astryx theme build`
+ * (#5015). `collectUnloadedFonts()` reads a RESOLVED theme — `--font-family-*`
+ * tokens plus component-override `fontFamily` values (typography configs are
+ * already collapsed into tokens by the time the build sees the theme) — and
+ * returns the families the theme names but nothing loads. CSS generics,
+ * CSS-wide keywords, `var()` references, and known preinstalled system
+ * families are treated as loaded; anything unrecognized is assumed to be a
+ * webfont, because a missed warning is worse than a spurious one.
+ * `formatFontLoadingHelp()` renders the human snippet (<link> pair +
+ * @font-face) printed after the install instructions.
+ */
+
+import {describe, it, expect} from 'vitest';
+import {collectUnloadedFonts, formatFontLoadingHelp} from './font-warning.mjs';
+
+describe('collectUnloadedFonts', () => {
+ it('returns webfont families from font-family tokens, skipping known fallbacks', () => {
+ expect(
+ collectUnloadedFonts({
+ tokens: {'--font-family-body': '"Fraunces", Georgia, serif'},
+ }),
+ ).toEqual(['Fraunces']);
+ });
+
+ it('returns nothing for the default system stacks', () => {
+ expect(
+ collectUnloadedFonts({
+ tokens: {
+ '--font-family-body':
+ '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',
+ '--font-family-code': '"SF Mono", Monaco, Consolas, monospace',
+ },
+ }),
+ ).toEqual([]);
+ });
+
+ it('treats bare system keywords like ui-monospace as loaded', () => {
+ expect(
+ collectUnloadedFonts({tokens: {'--font-family-code': 'ui-monospace'}}),
+ ).toEqual([]);
+ });
+
+ it('handles single-quoted and unquoted multi-word family names', () => {
+ expect(
+ collectUnloadedFonts({
+ tokens: {
+ '--font-family-body': "'JetBrains Mono', monospace",
+ '--font-family-heading': 'Space Grotesk, sans-serif',
+ },
+ }),
+ ).toEqual(['JetBrains Mono', 'Space Grotesk']);
+ });
+
+ it('dedupes case-insensitively across roles, keeping the first casing', () => {
+ expect(
+ collectUnloadedFonts({
+ tokens: {
+ '--font-family-body': '"Space Grotesk", sans-serif',
+ '--font-family-heading': '"space grotesk", serif',
+ },
+ }),
+ ).toEqual(['Space Grotesk']);
+ });
+
+ it('skips var() references and CSS-wide keywords', () => {
+ expect(
+ collectUnloadedFonts({
+ tokens: {
+ '--font-family-heading': 'var(--font-family-body)',
+ '--font-family-code': 'inherit',
+ },
+ }),
+ ).toEqual([]);
+ });
+
+ it("strips whole var() calls — fallback arguments are not this theme's declarations", () => {
+ expect(
+ collectUnloadedFonts({
+ tokens: {
+ '--font-family-body': 'var(--x, "Web Font")',
+ '--font-family-heading': 'var(--x, "Web Font", serif)',
+ },
+ }),
+ ).toEqual([]);
+ // Families outside the var() call still count.
+ expect(
+ collectUnloadedFonts({
+ tokens: {'--font-family-code': 'var(--x), Bungee'},
+ }),
+ ).toEqual(['Bungee']);
+ });
+
+ it('keeps a comma inside a quoted name whole, even mid-list', () => {
+ expect(
+ collectUnloadedFonts({
+ tokens: {'--font-family-body': 'Georgia, "Foo, Bar", serif'},
+ }),
+ ).toEqual(['Foo, Bar']);
+ });
+
+ it('ignores an empty font-family token', () => {
+ expect(collectUnloadedFonts({tokens: {'--font-family-body': ''}})).toEqual(
+ [],
+ );
+ });
+
+ it('collects component-override fontFamily values, any style key', () => {
+ expect(
+ collectUnloadedFonts({
+ components: {
+ Button: {base: {fontFamily: '"Orbitron", sans-serif'}},
+ Card: {'variant:hero': {fontFamily: 'Bungee'}},
+ },
+ }),
+ ).toEqual(['Orbitron', 'Bungee']);
+ });
+
+ it('matches known system families case-insensitively', () => {
+ expect(
+ collectUnloadedFonts({
+ tokens: {'--font-family-body': 'arial, sans-serif'},
+ }),
+ ).toEqual([]);
+ });
+
+ it('returns nothing for a theme with no tokens or components', () => {
+ expect(collectUnloadedFonts({})).toEqual([]);
+ });
+
+ it('returns nothing for a null or undefined resolved theme', () => {
+ // Older build.mjs consumers guard with `resolvedTheme || themeDef` — if
+ // a path ever hands the collector nothing, it must shrug, not throw.
+ expect(collectUnloadedFonts(null)).toEqual([]);
+ expect(collectUnloadedFonts(undefined)).toEqual([]);
+ });
+
+ it('ignores non-string values without throwing: numeric or object-valued', () => {
+ // The generator only allows object values under ':pseudo' keys, so an
+ // object-valued fontFamily is not a family declaration — skip, not crash.
+ expect(
+ collectUnloadedFonts({
+ tokens: {'--font-family-body': 42},
+ components: {
+ button: {base: {fontFamily: 700}},
+ card: {base: {fontFamily: {default: '"Sneaky"'}}},
+ },
+ }),
+ ).toEqual([]);
+ });
+
+ it('collects fontFamily nested under a pseudo-class block', () => {
+ // generateThemeRules accepts {':hover': {fontFamily}} inside a style
+ // key — a family named only there must still warn.
+ expect(
+ collectUnloadedFonts({
+ components: {
+ button: {base: {':hover': {fontFamily: '"Rubik Doodle", cursive'}}},
+ },
+ }),
+ ).toEqual(['Rubik Doodle']);
+ });
+
+ it('strips a var() whose fallback list contains another var()', () => {
+ expect(
+ collectUnloadedFonts({
+ tokens: {
+ '--font-family-body': 'var(--brand, var(--fallback), "Web Font")',
+ },
+ }),
+ ).toEqual([]);
+ // …and still keeps a family declared outside the nested call.
+ expect(
+ collectUnloadedFonts({
+ tokens: {'--font-family-code': 'var(--a, var(--b, serif)), Bungee'},
+ }),
+ ).toEqual(['Bungee']);
+ });
+
+ it('matches generic keywords case-insensitively', () => {
+ expect(
+ collectUnloadedFonts({
+ tokens: {
+ '--font-family-body': 'Sans-Serif',
+ '--font-family-heading': 'SERIF',
+ '--font-family-code': 'Ui-Monospace',
+ },
+ }),
+ ).toEqual([]);
+ });
+
+ it('collapses newlines and whitespace runs inside a family name', () => {
+ // Template-literal theme sources wrap long stacks across lines.
+ expect(
+ collectUnloadedFonts({
+ tokens: {'--font-family-body': '"Space\n Grotesk",\n serif'},
+ }),
+ ).toEqual(['Space Grotesk']);
+ });
+});
+
+describe('formatFontLoadingHelp', () => {
+ const help = formatFontLoadingHelp('ocean', ['Fraunces', 'JetBrains Mono']);
+
+ it('names the theme and every family in the headline', () => {
+ expect(help).toContain('⚠');
+ expect(help).toContain('ocean');
+ expect(help).toContain('"Fraunces"');
+ expect(help).toContain('"JetBrains Mono"');
+ });
+
+ it('includes the Google Fonts recipe: preconnect pair + the exact css2 URL', () => {
+ expect(help).toContain(
+ '<link rel="preconnect" href="https://fonts.googleapis.com"',
+ );
+ expect(help).toContain('https://fonts.gstatic.com');
+ // The whole href, so a malformed URL cannot hide behind fragment checks.
+ expect(help).toContain(
+ 'href="https://fonts.googleapis.com/css2?family=Fraunces&family=JetBrains+Mono&display=swap"',
+ );
+ });
+
+ it('includes a self-hosted @font-face alternative with font-display: swap', () => {
+ expect(help).toContain('@font-face');
+ expect(help).toContain('font-family: "Fraunces"');
+ expect(help).toContain('woff2');
+ expect(help).toContain('font-display: swap');
+ });
+
+ it('points at the docs recipe', () => {
+ expect(help).toContain('astryx docs typography');
+ });
+
+ it('percent-encodes family names in the css2 URL', () => {
+ const spiced = formatFontLoadingHelp('spice', ['P&Co Sans', 'Sömething']);
+ expect(spiced).toContain(
+ 'href="https://fonts.googleapis.com/css2?family=P%26Co+Sans&family=S%C3%B6mething&display=swap"',
+ );
+ });
+});
diff --git a/packages/cli/assets/docs/theme.doc.mjs b/packages/cli/assets/docs/theme.doc.mjs
index 899f05b59d..7a11c647d2 100644
--- a/packages/cli/assets/docs/theme.doc.mjs
+++ b/packages/cli/assets/docs/theme.doc.mjs
@@ -417,6 +417,10 @@ import './themes/ocean.css';
<App />
</Theme>`,
},
+ {
+ type: 'prose',
+ text: 'The build also warns when the theme names font families it does not load (webfonts like Fraunces) and prints the `<link>`/`@font-face` to add — the built CSS only sets font-family, so loading the font files stays the app\'s job. See `astryx docs typography` for the full recipe.',
+ },
],
},
{
diff --git a/packages/cli/assets/docs/typography.doc.mjs b/packages/cli/assets/docs/typography.doc.mjs
index 9b8516566b..9e0de880e7 100644
--- a/packages/cli/assets/docs/typography.doc.mjs
+++ b/packages/cli/assets/docs/typography.doc.mjs
@@ -44,6 +44,44 @@ export const docs = {
],
},
+ // ── Loading Custom Fonts ────────────────────────────────────────────────
+ {
+ title: 'Loading Custom Fonts',
+ category: 'foundations',
+ content: [
+ {
+ type: 'prose',
+ text: 'Astryx never loads font files. defineTheme and the built CSS only set font-family — naming a webfont (Fraunces, JetBrains Mono, …) makes every browser look for it, and quietly fall back when the app has not loaded it. `astryx theme build` warns when a theme names families that are neither CSS generics nor common system fonts and prints the snippet to add; loading the font is always the app\'s job.',
+ },
+ {
+ type: 'code',
+ lang: 'html',
+ label: 'Google Fonts — add to your document <head>',
+ code: `<link rel="preconnect" href="https://fonts.googleapis.com" />
+<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
+<link
+ rel="stylesheet"
+ href="https://fonts.googleapis.com/css2?family=Fraunces:wght@400;600;700&family=JetBrains+Mono&display=swap"
+/>`,
+ },
+ {
+ type: 'code',
+ lang: 'css',
+ label: 'Self-hosted — one @font-face per family and weight',
+ code: `@font-face {
+ font-family: 'Fraunces';
+ src: url('/fonts/fraunces.woff2') format('woff2');
+ font-weight: 400 700; /* variable-font range, or one weight per file */
+ font-display: swap; /* fallback text stays visible while the font loads */
+}`,
+ },
+ {
+ type: 'prose',
+ text: "Always pair a webfont with a real fallback stack — metric-similar system fonts plus a generic — so text stays readable before the font loads and wherever it never does: defineTheme({typography: {heading: {family: 'Fraunces', fallbacks: 'Georgia, serif'}}}).",
+ },
+ ],
+ },
+
// ── Font Sizes ──────────────────────────────────────────────────────────
{
title: 'Font Sizes',
diff --git a/packages/cli/clients/cli/commands/build-theme.font-warning.test.mjs b/packages/cli/clients/cli/commands/build-theme.font-warning.test.mjs
new file mode 100644
index 0000000000..0b60c29799
--- /dev/null
+++ b/packages/cli/clients/cli/commands/build-theme.font-warning.test.mjs
@@ -0,0 +1,138 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file End-to-end test for the `astryx theme build` font-loading warning
+ * (#5015). A theme that names webfont families gets, AFTER the install
+ * instructions, a stdout notice naming the fonts plus the copy-pasteable
+ * fix — the Google Fonts <link> pair and a self-hosted @font-face with
+ * font-display: swap — and still exits 0 (it is a warning, not an error).
+ * Themes that only name generics or known system stacks get none of it.
+ */
+
+import {describe, it, expect, beforeAll, beforeEach, afterEach} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {ensureCoreBuilt} from './ensure-core-built.mjs';
+import {runCli} from '../../../test-utils/run-cli.mjs';
+
+function writeTheme(dir, name, source) {
+ fs.mkdirSync(dir, {recursive: true});
+ const file = path.join(dir, `${name}.mjs`);
+ fs.writeFileSync(file, source);
+ return file;
+}
+
+// `astryx theme build` imports the compiled @astryxdesign/core/theme entry.
+// Build core once if it isn't already present so the suite works in any CI
+// job, regardless of job ordering.
+beforeAll(() => {
+ ensureCoreBuilt();
+}, 200_000);
+
+let tmpDir;
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-build-theme-fonts-'));
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('theme build font-loading warning', () => {
+ it('prints the unloaded fonts and the <link>/@font-face fix after the install instructions', async () => {
+ const project = path.join(tmpDir, 'project');
+ const themeFile = writeTheme(
+ project,
+ 'fonty',
+ `export default {
+ name: 'fonty',
+ typography: {
+ body: {family: 'Space Grotesk', fallbacks: 'Arial, sans-serif'},
+ code: {family: 'JetBrains Mono'},
+ },
+};\n`,
+ );
+
+ const result = await runCli(
+ ['theme', 'build', path.relative(project, themeFile)],
+ project,
+ );
+
+ expect(result.code).toBe(0);
+ // The install instructions still come out intact…
+ expect(result.stdout).toContain("from './fonty'");
+ // …followed by the warning naming the theme and every unloaded family…
+ expect(result.stdout).toContain('names fonts it does not load');
+ expect(result.stdout).toContain('"Space Grotesk"');
+ expect(result.stdout).toContain('"JetBrains Mono"');
+ // …and the copy-pasteable fix, both flavors.
+ expect(result.stdout).toContain(
+ '<link rel="preconnect" href="https://fonts.googleapis.com"',
+ );
+ expect(result.stdout).toContain('family=Space+Grotesk');
+ expect(result.stdout).toContain('family=JetBrains+Mono');
+ expect(result.stdout).toContain('display=swap');
+ expect(result.stdout).toContain('@font-face');
+ expect(result.stdout).toContain('font-display: swap');
+ expect(result.stdout).toContain('astryx docs typography');
+ // The one-line summaries follow the CLI's stream contract: warnings on
+ // stderr, like the override-validation warnings in the same build.
+ expect(result.stderr).toContain('Font "Space Grotesk"');
+ expect(result.stderr).toContain('Font "JetBrains Mono"');
+ });
+
+ it('keeps --json stdout one valid envelope: warnings inside, snippet suppressed', async () => {
+ const project = path.join(tmpDir, 'project');
+ const themeFile = writeTheme(
+ project,
+ 'fonty',
+ `export default { name: 'fonty', tokens: { '--font-family-body': '"Space Grotesk", sans-serif' } };\n`,
+ );
+
+ const result = await runCli(
+ ['--json', 'theme', 'build', path.relative(project, themeFile)],
+ project,
+ );
+
+ expect(result.code).toBe(0);
+ // The whole stdout must parse — any human snippet leaking into --json
+ // mode corrupts the envelope, so this asserts the "JSON is always JSON"
+ // contract, not just substring presence.
+ const envelope = JSON.parse(result.stdout);
+ expect(envelope.type).toBe('theme.build');
+ expect(envelope.data.warnings).toEqual(
+ expect.arrayContaining([expect.stringContaining('Font "Space Grotesk"')]),
+ );
+ expect(result.stdout).not.toContain('fonts.googleapis.com');
+ // Human one-liners are silenced too — machine mode stays quiet.
+ expect(result.stderr).not.toContain('Font "');
+ });
+
+ it('prints nothing font-related for a theme of generics and system stacks', async () => {
+ const project = path.join(tmpDir, 'project');
+ const themeFile = writeTheme(
+ project,
+ 'sys',
+ `export default {
+ name: 'sys',
+ tokens: {
+ '--color-bg': '#fff',
+ '--font-family-body': 'Helvetica, Arial, sans-serif',
+ '--font-family-code': 'ui-monospace',
+ },
+};\n`,
+ );
+
+ const result = await runCli(
+ ['theme', 'build', path.relative(project, themeFile)],
+ project,
+ );
+
+ expect(result.code).toBe(0);
+ expect(result.stdout).toContain("from './sys'");
+ expect(result.stdout).not.toContain('names fonts it does not load');
+ expect(result.stdout).not.toContain('fonts.googleapis.com');
+ expect(result.stdout).not.toContain('@font-face');
+ expect(result.stderr).not.toContain('Font "');
+ });
+});