An open source design system that's fully customizable and agent ready
TypeScript
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
* @file App-theme state stored in the generated theme module.
*
* The module is both the app import surface and the only record of added themes.
* Its generated header records owners and the default without adding another public
* export. Commands parse that header without running project code, regenerate the
* whole marked file instead of editing it, and never replace an authored file.
*
* @input A project directory and resolved built-theme imports
* @output Parsed state plus deterministic generated-module write plans
* @position packages/cli/foundation/config — shared app-theme state
*/
import * as fs from 'node:fs';
import * as path from 'node:path';
import {assertWithin, PathSafetyError} from '../fs/path-safety.mjs';
import {formatCliCommand} from '../env/package-manager.mjs';
export const LOCAL_THEME_ROOT = './src/themes';
export const THEME_MODULE_BASENAME = 'astryx-themes';
export const THEME_MODULE_MARKER =
'@generated by `astryx theme` — do not edit manually.';
export const THEME_RECORD_MARKER = '@astryx-theme-record';
const THEME_SLUG_RE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;
export class ThemeStateError extends Error {}
/** @param {unknown} value @returns {value is Record<string, unknown>} */
function isRecord(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
/** @param {string} value */
export function projectPath(value) {
return value.split(path.sep).join('/');
}
/**
* Find the nearest package.json from a working directory.
* @param {string} cwd
*/
export function findThemeProject(cwd) {
let projectDir = path.resolve(cwd);
for (let depth = 0; depth < 50; depth++) {
const packageFile = path.join(projectDir, 'package.json');
if (fs.existsSync(packageFile)) return {projectDir, packageFile};
const parent = path.dirname(projectDir);
if (parent === projectDir) break;
projectDir = parent;
}
throw new ThemeStateError(
'No package.json found. Run this command inside an app project.',
);
}
/**
* Whether an owner value names a project-relative local theme root instead of
* an installed package.
* @param {string} owner
*/
export function isLocalThemeOwner(owner) {
return owner.startsWith('./') || owner.startsWith('../') || path.isAbsolute(owner);
}
/** @param {string} projectDir */
export function projectUsesTypeScript(projectDir) {
try {
return fs
.readdirSync(projectDir, {withFileTypes: true})
.some(
entry =>
entry.isFile() &&
/^tsconfig(?:\.[^.]+)*\.json$/u.test(entry.name),
);
} catch {
return false;
}
}
/**
* All conventional module locations. The preferred new location is first.
* @param {string} projectDir
*/
export function themeModuleCandidates(projectDir) {
const src = path.join(projectDir, 'src');
const hasSrc = fs.existsSync(src) && fs.statSync(src).isDirectory();
const typescript = projectUsesTypeScript(projectDir);
const preferredDir = hasSrc ? src : projectDir;
const otherDir = hasSrc ? projectDir : src;
const preferredExtension = typescript ? '.ts' : '.js';
const otherExtension = typescript ? '.js' : '.ts';
return [
path.join(preferredDir, `${THEME_MODULE_BASENAME}${preferredExtension}`),
path.join(preferredDir, `${THEME_MODULE_BASENAME}${otherExtension}`),
path.join(otherDir, `${THEME_MODULE_BASENAME}${preferredExtension}`),
path.join(otherDir, `${THEME_MODULE_BASENAME}${otherExtension}`),
];
}
/**
* @param {unknown} value
* @param {string} label
*/
function validThemeRecord(value, label) {
if (!isRecord(value) || !isRecord(value.themes)) {
throw new ThemeStateError(
`${label} must carry a static ${THEME_RECORD_MARKER} header. Regenerate it with \`${formatCliCommand('theme add <slug>')}\`.`,
);
}
const keys = Object.keys(value);
if (
keys.length !== 2 ||
!keys.includes('themes') ||
!keys.includes('defaultThemeSlug')
) {
throw new ThemeStateError(
`${label} ${THEME_RECORD_MARKER} header must contain only themes and defaultThemeSlug.`,
);
}
/** @type {Record<string, string>} */
const themes = {};
for (const [slug, owner] of Object.entries(value.themes)) {
if (
!THEME_SLUG_RE.test(slug) ||
typeof owner !== 'string' ||
owner.trim() === ''
) {
throw new ThemeStateError(
`${label} theme record must map lowercase kebab-case slugs to package names or local theme roots.`,
);
}
themes[slug] = owner;
}
if (
typeof value.defaultThemeSlug !== 'string' ||
!THEME_SLUG_RE.test(value.defaultThemeSlug)
) {
throw new ThemeStateError(
`${label} defaultThemeSlug must be a lowercase kebab-case slug. Regenerate it with \`${formatCliCommand('theme use <slug>')}\`.`,
);
}
return {themes, defaultSlug: value.defaultThemeSlug};
}
/**
* Parse the generated module's record without executing the module.
* @param {string} source
* @param {string} label
*/
export function parseThemeModuleRecord(source, label = 'theme module') {
if (!source.includes(THEME_MODULE_MARKER)) {
throw new ThemeStateError(`${label} does not carry the Astryx generated marker.`);
}
const recordLines = source
.split(/\r?\n/u)
.filter(line => /^\s*\*\s*@astryx-theme-record\s+/u.test(line));
if (recordLines.length !== 1) {
throw new ThemeStateError(
`${label} must carry exactly one static ${THEME_RECORD_MARKER} header. Regenerate it with \`${formatCliCommand('theme add <slug>')}\`.`,
);
}
const payload = recordLines[0].replace(
/^\s*\*\s*@astryx-theme-record\s+/u,
'',
);
let record;
try {
record = JSON.parse(payload);
} catch (error) {
throw new ThemeStateError(
`${label} has an invalid ${THEME_RECORD_MARKER} header: ${error instanceof Error ? error.message : String(error)}`,
{cause: error},
);
}
return validThemeRecord(record, label);
}
/**
* Preserve the one existing generated module. With none, choose the first
* conventional location. Two generated copies are ambiguous and fail closed.
* @param {string} projectDir
* @param {{forWrite?: boolean}} [options]
*/
export function resolveThemeModule(projectDir, {forWrite = false} = {}) {
const candidates = themeModuleCandidates(projectDir);
const generated = candidates.filter(file => {
try {
return fs.readFileSync(file, 'utf-8').includes(THEME_MODULE_MARKER);
} catch {
return false;
}
});
if (generated.length > 1) {
throw new ThemeStateError(
`More than one generated theme module exists: ${generated
.map(file => projectPath(path.relative(projectDir, file)))
.join(', ')}. Keep one and remove the others before running the command again.`,
);
}
const file = generated[0] ?? candidates[0];
if (forWrite) {
try {
assertWithin(path.relative(projectDir, file), projectDir, {
label: 'generated theme module',
});
} catch (error) {
if (error instanceof PathSafetyError) {
throw new ThemeStateError(error.message, {cause: error});
}
throw error;
}
}
let expectedOriginal;
if (fs.existsSync(file)) {
expectedOriginal = fs.readFileSync(file);
if (!expectedOriginal.toString('utf-8').includes(THEME_MODULE_MARKER)) {
if (forWrite) {
throw new ThemeStateError(
`Refusing to replace ${projectPath(path.relative(projectDir, file))}: it is not an Astryx-generated theme module. Move that file before adding themes.`,
);
}
expectedOriginal = undefined;
}
}
return {
file,
path: projectPath(path.relative(projectDir, file)),
typescript: file.endsWith('.ts'),
expectedOriginal,
exists: generated.length === 1,
};
}
/**
* @typedef {object} ThemeState
* @property {string} projectDir
* @property {string} packageFile
* @property {Record<string, string>} themes
* @property {string|null} defaultSlug
* @property {string|null} legacyTheme
* @property {boolean} configured
* @property {ReturnType<typeof resolveThemeModule>} module
*/
/**
* Read app-theme state from the generated module. Only when no module exists is
* the released `package.json#astryx.theme` meaning returned as legacy input.
* @param {string} [cwd]
* @returns {ThemeState}
*/
export function readThemeState(cwd = process.cwd()) {
const {projectDir, packageFile} = findThemeProject(cwd);
const module = resolveThemeModule(projectDir);
if (module.exists && module.expectedOriginal) {
const record = parseThemeModuleRecord(
module.expectedOriginal.toString('utf-8'),
module.path,
);
return {
projectDir,
packageFile,
themes: record.themes,
defaultSlug: record.defaultSlug,
legacyTheme: null,
configured: true,
module,
};
}
let legacyTheme = null;
try {
const pkg = JSON.parse(fs.readFileSync(packageFile, 'utf-8'));
if (
isRecord(pkg) &&
isRecord(pkg.astryx) &&
typeof pkg.astryx.theme === 'string'
) {
legacyTheme = pkg.astryx.theme;
}
} catch {
// Theme commands surface package problems at their own write boundary. A
// legacy lookup with no readable package field simply has no configured theme.
}
return {
projectDir,
packageFile,
themes: {},
defaultSlug: null,
legacyTheme,
configured: false,
module,
};
}
/**
* @typedef {object} ResolvedAppTheme
* @property {string} slug
* @property {string} owner
* @property {string} exportName
* @property {string} module
* @property {string} stylesheet
* @property {string} [fontStylesheet]
* @property {string} moduleFile
* @property {string} stylesheetFile
* @property {string} [fontStylesheetFile]
* @property {'bundled'|'package'|'local'} source
*/
/**
* Render one generated module from final resolved state.
* @param {ResolvedAppTheme[]} themes
* @param {string} defaultSlug
* @param {boolean} typescript
*/
export function renderThemeModule(themes, defaultSlug, typescript) {
if (!themes.some(theme => theme.slug === defaultSlug)) {
throw new ThemeStateError(
`Default theme "${defaultSlug}" is not added. Run \`${formatCliCommand(`theme add ${defaultSlug}`)}\` first.`,
);
}
/** @type {string[]} */
const imports = [];
/** @type {string[]} */
const entries = [];
/** @type {Record<string, string>} */
const owners = {};
themes.forEach((theme, index) => {
const local = `_astryxTheme${index}`;
imports.push(
`import {${theme.exportName} as ${local}} from ${JSON.stringify(theme.module)};`,
`import ${JSON.stringify(theme.stylesheet)};`,
);
if (theme.fontStylesheet) {
imports.push(`import ${JSON.stringify(theme.fontStylesheet)};`);
}
entries.push(` ${JSON.stringify(theme.slug)}: ${local},`);
owners[theme.slug] = theme.owner;
});
const record = JSON.stringify({themes: owners, defaultThemeSlug: defaultSlug});
return `/**\n * ${THEME_MODULE_MARKER}\n * ${THEME_RECORD_MARKER} ${record}\n */\n\n${imports.join(
'\n',
)}\n\nexport const themes = {\n${entries.join('\n')}\n}${
typescript ? ' as const' : ''
};\n${
typescript ? 'export type ThemeSlug = keyof typeof themes;\n' : ''
}\nexport const defaultThemeSlug${
typescript ? ': keyof typeof themes' : ''
} = ${JSON.stringify(defaultSlug)};\n`;
}
/**
* Resolve a project-relative import from the generated module to a local file.
* @param {string} moduleFile
* @param {string} target
*/
export function localImportSpecifier(moduleFile, target) {
let relative = projectPath(path.relative(path.dirname(moduleFile), target));
if (!relative.startsWith('.')) relative = `./${relative}`;
return relative;
}
/**
* Plan the generated-module write. The caller applies it through the shared
* atomic transaction.
* @param {ThemeState} state
* @param {Record<string, string>} themes
* @param {string} defaultSlug
* @param {ResolvedAppTheme[]} resolvedThemes
*/
export function planThemeAppWrite(state, themes, defaultSlug, resolvedThemes) {
const module = resolveThemeModule(state.projectDir, {forWrite: true});
const entries = resolvedThemes.map(theme =>
theme.source === 'local'
? {
...theme,
module: localImportSpecifier(module.file, theme.moduleFile),
stylesheet: localImportSpecifier(module.file, theme.stylesheetFile),
...(theme.fontStylesheetFile
? {
fontStylesheet: localImportSpecifier(
module.file,
theme.fontStylesheetFile,
),
}
: {}),
}
: theme,
);
for (const theme of entries) {
if (themes[theme.slug] !== theme.owner) {
throw new ThemeStateError(
`Theme record for "${theme.slug}" does not match its resolved owner.`,
);
}
}
const moduleContents = renderThemeModule(
entries,
defaultSlug,
module.typescript,
);
return {
module,
entries,
plan: {
path: module.file,
contents: moduleContents,
createOnly: module.expectedOriginal == null,
...(module.expectedOriginal != null
? {expectedOriginal: module.expectedOriginal}
: {}),
},
moduleContents,
};
}