An open source design system that's fully customizable and agent ready
TypeScript
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
* @file no-raw-private-attribute.js
* @description Reports a private `data-astryx-*` attribute written by hand
* outside its owner module (`architecture:public-component-api` INV23).
*
* A `data-astryx-*` attribute is private unless INV23 names it public. Each
* private attribute has one owner module in the package that writes it,
* `packages/<package>/src/privateAttributes/<name>.stylex.ts` with the name in
* camelCase (`focusOwner.stylex.ts` for `data-astryx-focus-owner`), that writes its
* name and selectors once and exports ready-made styles, setter props and the
* runtime readers its package needs. Every other file spreads those exports,
* so the attribute can be renamed or reshaped in one place and never leaks
* into the public surface by accident.
*
* In Core, the owner can instead be a plain-TS module,
* `packages/core/src/privateAttributes/<name>.ts`, that the uncompiled theme
* engine can import. It may export its name and the selector text built on
* it, and only its `.stylex.ts` sibling and the theme engine
* (`packages/core/src/theme/`) may import it. When it exists, its
* `.stylex.ts` sibling is not an owner. The sibling may write the attribute's
* selectors only as literals that reach its own `stylex.create` calls,
* directly or through module constants read only there, because StyleX
* resolves a selector only where it is written. Any other use in the sibling
* is reported. A binding the sibling imports from its owner may be read, but
* not exported, re-exported, used as a setter-prop key outside
* `stylex.create`, or passed to `setAttribute`, `toggleAttribute` or
* `removeAttribute`.
*
* Reported, outside the owner modules:
* - a string literal that contains `data-astryx-<name>`, in any position
* (an object key, a `setAttribute` argument, a selector inside
* `stylex.create` or `stylex.when.*`);
* - a template literal that does, including one built from the namespace
* constant (`data-${dataAttrNamespace}-press`);
* - a JSX attribute named `data-astryx-<name>`;
* - a `dataAttr('<name>')` call that names a private attribute.
* A name the rule cannot read (`data-astryx-${part}`, `dataAttr(name)`) is
* reported as `data-astryx-*`: it cannot be shown to be public.
*
* Inside an owner module, only its own attribute may be written, and a
* `.stylex.ts` owner may not export the raw name or a selector as a string: not as an
* exported or default-exported value, not inside an exported object, array or
* function's return value, and not through a module constant that one of
* those uses, including a string built from that constant in a template or
* with `+`. The name stays allowed as an object key (setter props and
* `stylex.create` selectors) and as a call argument (a writer or a
* `closest`/`matches` reader). Anywhere, an
* import of another package's owner module is reported: a private attribute
* stays inside the package that writes it.
*
* Public, never reported: the names INV23 lists (`PUBLIC_ATTRIBUTES`).
* `naming.ts`, which builds every `data-astryx-*` name, is not checked.
*
* Known limitations: a name assembled from the namespace with `+`
* (`'data-' + NAMESPACE + '-press'`), a template that reaches the namespace
* through anything but `dataAttrNamespace` or `NAMESPACE` (a member access,
* an aliased import, `classPrefix`), a name read through `element.dataset`,
* and a sibling's imported name copied to another variable before it sets the
* attribute are not seen; no shipped source does any of these today, and public-API
* review covers them.
*
* Options: `{baseline: {[repoRelativeFile]: string[]}, root: string}`. The
* baseline lists, per file, each private attribute once per site that
* predates the rule; that many sites stay allowed until moved into the owner
* module, and one more is reported. The list only shrinks.
* `no-raw-private-attribute.baseline.mjs` writes it.
*/
import fs from 'node:fs';
import path from 'node:path';
import {baselineAllowance} from './rule-baseline.mjs';
/**
* Where the repository config enforces the rule with its baseline: shipped
* package source. Tests, stories and test helpers never ship, and they read
* attributes back from the DOM to check behavior, so they may name them.
* Shared with the baseline script so both lint the same files.
*/
export const scope = {
files: ['packages/*/src/**/*.{ts,tsx,mts,cts,js,jsx,mjs}'],
ignores: [
'**/*.test.*',
'**/*.spec.*',
'**/*.stories.*',
'**/*.testing.*',
'**/*.render-testing.*',
'**/__tests__/**',
'**/__fixtures__/**',
'**/dist/**',
],
};
const PREFIX = 'data-astryx-';
/**
* The data attributes INV23 names public, after the `data-astryx-` prefix:
* the theme and media-surface scopes, AspectRatio's override hook, the Chat
* composer token's attributes, the menu-root and press markers, and the
* edge-compensation marker. They change only under INV9.
*/
export const PUBLIC_ATTRIBUTES = new Set([
'theme',
'media',
'aspect-ratio-override',
'token',
'token-value',
'menu-press',
'pressable',
'edge-comp',
]);
/**
* Identifiers that hold the `astryx` namespace segment, exported by
* `naming.ts`; a template that interpolates one still spells the attribute.
*/
const NAMESPACE_IDENTIFIERS = new Set(['dataAttrNamespace', 'NAMESPACE']);
/** Stands in for an interpolated value whose text is unknown. */
const UNKNOWN = '\u0000';
const STYLEX_OWNER_MODULE =
/(?:^|\/)packages\/[^/]+\/src\/privateAttributes\/([^/]+)\.stylex\.ts$/;
const PLAIN_OWNER_MODULE =
/(?:^|\/)packages\/core\/src\/privateAttributes\/([^/.]+)\.ts$/;
const PACKAGE_SOURCE = /(?:^|\/)packages\/([^/]+)\/src\//;
const NAMING_MODULE = /(?:^|\/)packages\/core\/src\/naming\.ts$/;
const PLAIN_OWNER_TARGET =
/^(.*\/packages\/core\/src\/privateAttributes)\/([^/.]+)(?:\.(?:ts|js))?$/;
const THEME_ENGINE = /(?:^|\/)packages\/core\/src\/theme\//;
const ATTRIBUTE_WRITERS = new Set([
'setAttribute',
'toggleAttribute',
'removeAttribute',
]);
/** Is `node` an argument of a `stylex.create` call, at any depth? */
function insideStylexCreate(node) {
let current = node;
while (current.parent != null) {
const parent = current.parent;
if (
parent.type === 'CallExpression' &&
parent.arguments.includes(current) &&
parent.callee.type === 'MemberExpression' &&
!parent.callee.computed &&
parent.callee.object.type === 'Identifier' &&
parent.callee.object.name === 'stylex' &&
parent.callee.property.type === 'Identifier' &&
parent.callee.property.name === 'create'
) {
return true;
}
current = parent;
}
return false;
}
/**
* Every `data-astryx-*` attribute a piece of text names, as the attribute
* name after the prefix, or `null` where the name is interpolated and so
* cannot be read.
*
* @param {string} text
* @returns {Array<string | null>}
*/
export function attributeNames(text) {
const names = [];
const pattern = /data-astryx-([a-z0-9-]*)/gi;
let match;
while ((match = pattern.exec(text)) != null) {
const name = match[1].replace(/-+$/, '').toLowerCase();
const next = text[match.index + match[0].length];
names.push(name === '' || next === UNKNOWN ? null : name);
}
return names;
}
/** `focusOwner` → `focus-owner`; a kebab-case stem is returned unchanged. */
function kebabCase(stem) {
return stem.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
}
/** `focus-owner` → `focusOwner`, the owner module's file stem. */
function camelCase(name) {
return name.replace(/-([a-z0-9])/g, (_, letter) => letter.toUpperCase());
}
/** `data-astryx-press`, or `data-astryx-*` for a name that cannot be read. */
function attributeLabel(name) {
return name == null ? `${PREFIX}*` : `${PREFIX}${name}`;
}
/** The text of a template literal, interpolating the namespace constant. */
function templateText(node) {
let text = '';
node.quasis.forEach((quasi, index) => {
text += quasi.value.cooked ?? quasi.value.raw;
const expression = node.expressions[index];
if (expression != null) {
text +=
expression.type === 'Identifier' &&
NAMESPACE_IDENTIFIERS.has(expression.name)
? 'astryx'
: UNKNOWN;
}
});
return text;
}
/** The static text of a call argument, or `null` when it is computed. */
function staticText(node) {
if (node?.type === 'Literal' && typeof node.value === 'string') {
return node.value;
}
if (node?.type === 'TemplateLiteral' && node.expressions.length === 0) {
return node.quasis[0].value.cooked ?? node.quasis[0].value.raw;
}
return null;
}
function isDataAttrCall(node) {
const callee = node.callee;
return (
(callee.type === 'Identifier' && callee.name === 'dataAttr') ||
(callee.type === 'MemberExpression' &&
!callee.computed &&
callee.property.type === 'Identifier' &&
callee.property.name === 'dataAttr')
);
}
/** Wrappers that pass their operand's value through unchanged. */
const PASS_THROUGH = new Set([
'TSAsExpression',
'TSSatisfiesExpression',
'TSNonNullExpression',
'TSTypeAssertion',
'ChainExpression',
'AwaitExpression',
'LogicalExpression',
'ArrayExpression',
'ObjectExpression',
'SpreadElement',
]);
const FUNCTIONS = new Set([
'FunctionDeclaration',
'FunctionExpression',
'ArrowFunctionExpression',
]);
/**
* Where the value of `node` ends up, following it out through wrappers,
* strings built from it (a template slot, a `+` operand), object property
* values, array elements and function return values:
* `{exported: true}` when it reaches an export, `{binding}` when it is bound
* to a name (a variable declarator or a function declaration) whose uses
* decide, or `null` when it is consumed some other way (an object key, a call
* argument, a member access).
*/
function valueDestination(node) {
let current = node;
for (;;) {
const parent = current.parent;
if (parent == null) {
return null;
}
if (
PASS_THROUGH.has(parent.type) ||
(parent.type === 'ConditionalExpression' && parent.test !== current) ||
// A string built from the value carries it on: a template slot, or an
// operand of `+`.
parent.type === 'TemplateLiteral' ||
(parent.type === 'BinaryExpression' && parent.operator === '+') ||
(parent.type === 'SequenceExpression' &&
parent.expressions.at(-1) === current) ||
(parent.type === 'Property' && parent.value === current) ||
(parent.type === 'ArrowFunctionExpression' && parent.body === current)
) {
current = parent;
continue;
}
if (parent.type === 'ReturnStatement') {
let fn = parent.parent;
while (fn != null && !FUNCTIONS.has(fn.type)) {
fn = fn.parent;
}
if (fn == null) {
return null;
}
if (fn.type === 'FunctionDeclaration') {
const holder = fn.parent?.type;
if (
holder === 'ExportNamedDeclaration' ||
holder === 'ExportDefaultDeclaration'
) {
return {exported: true};
}
return fn.id == null ? null : {binding: fn};
}
current = fn;
continue;
}
if (parent.type === 'VariableDeclarator' && parent.init === current) {
if (parent.parent?.parent?.type === 'ExportNamedDeclaration') {
return {exported: true};
}
return parent.id.type === 'Identifier' ? {binding: parent} : null;
}
if (
parent.type === 'ExportDefaultDeclaration' ||
parent.type === 'ExportSpecifier'
) {
return {exported: true};
}
return null;
}
}
const rule = {
meta: {
type: 'problem',
docs: {
description:
'Disallow private data-astryx-* attributes written outside their owner module in packages/<package>/src/privateAttributes',
},
schema: [
{
type: 'object',
properties: {
baseline: {
type: 'object',
additionalProperties: {type: 'array', items: {type: 'string'}},
},
root: {type: 'string'},
},
additionalProperties: false,
},
],
messages: {
raw:
'`{{attribute}}` is a private data attribute. Write it only in its owner module, ' +
'{{owner}}, and spread the styles, setter props and readers it exports ' +
'(architecture:public-component-api INV23 lists the public attributes).',
unreadable:
'`{{attribute}}` names a data attribute this rule cannot read, so it cannot be ' +
'shown to be public. Write a private attribute only in its owner module under ' +
"{{ownerDirectory}}, and build a public one by name, as in dataAttr('theme').",
foreignOwner:
'`{{attribute}}` belongs in {{owner}}; each owner module writes only its own ' +
'attribute.',
foreignPackage:
"'{{source}}' imports another package's private-attribute owner module. A private " +
'attribute stays inside the package that writes it; reach it through that ' +
"package's public API.",
exportedName:
'An owner module exports styles, setter props and readers, never its attribute name ' +
'or a selector on it as a string ({{attribute}}).',
siblingSelector:
'`{{attribute}}` belongs to {{owner}}. Its `.stylex.ts` sibling writes the attribute ' +
'only as a selector literal for its own `stylex.create` calls; it never sets the ' +
'attribute or exports the selector.',
plainOwnerImport:
"'{{source}}' is a plain-TS owner module. Only its `.stylex.ts` sibling and the theme " +
'engine in packages/core/src/theme import it; other files spread the styles, setter ' +
'props and readers the owner modules export.',
},
},
create(context) {
const filename = (context.filename ?? context.getFilename())
.split(path.sep)
.join('/');
if (NAMING_MODULE.test(filename)) {
return {};
}
const packageSource = PACKAGE_SOURCE.exec(filename);
const packageName = packageSource?.[1] ?? null;
const ownerDirectory = `packages/${packageName ?? '<package>'}/src/privateAttributes`;
const ownerDirectoryOnDisk =
packageSource == null
? null
: `${filename.slice(0, packageSource.index + packageSource[0].length)}privateAttributes`;
const hasPlainOwner = stem =>
packageName === 'core' &&
ownerDirectoryOnDisk != null &&
fs.existsSync(`${ownerDirectoryOnDisk}/${stem}.ts`);
// Owner modules are named in camelCase (`focusOwner.stylex.ts` owns
// `data-astryx-focus-owner`); compare in the attribute's kebab case.
const plainOwnerStem = PLAIN_OWNER_MODULE.exec(filename)?.[1] ?? null;
const stylexOwnerStem = STYLEX_OWNER_MODULE.exec(filename)?.[1] ?? null;
const ownerStem =
plainOwnerStem ??
(stylexOwnerStem != null && !hasPlainOwner(stylexOwnerStem)
? stylexOwnerStem
: null);
const ownedName = ownerStem == null ? null : kebabCase(ownerStem);
const mayExportName = plainOwnerStem != null;
// The `.stylex.ts` sibling of a plain-TS owner: the attribute it may
// still write as a `stylex.create` selector.
const siblingName =
stylexOwnerStem != null && ownerStem == null
? kebabCase(stylexOwnerStem)
: null;
const siblingValues = [];
// In the sibling: import and re-export declarations from its own owner.
const siblingOwnerImports = [];
const isOwnSiblingOwner = specifier =>
siblingName != null &&
typeof specifier === 'string' &&
specifier.startsWith('.') &&
path
.resolve(
path.dirname(context.filename ?? context.getFilename()),
specifier,
)
.split(path.sep)
.join('/')
.replace(/\.(?:ts|js)$/, '') === filename.replace(/\.stylex\.ts$/, '');
const ownerOf = name => {
if (name == null) {
return ownerDirectory;
}
const stem = camelCase(name);
return hasPlainOwner(stem)
? `${ownerDirectory}/${stem}.ts`
: `${ownerDirectory}/${stem}.stylex.ts`;
};
const sourceCode = context.sourceCode ?? context.getSourceCode();
// Each listed attribute allows as many sites as it is listed; the next
// one is reported.
const isAllowed = baselineAllowance(context);
// Local names an owner module exports, by `export {name}`.
const exportedLocals = new Set();
function report(node, name) {
if (name != null && PUBLIC_ATTRIBUTES.has(name)) {
return;
}
const attribute = attributeLabel(name);
if (siblingName != null && name === siblingName) {
siblingValues.push(node);
return;
}
if (ownedName != null) {
if (name === ownedName) {
return;
}
if (isAllowed(attribute)) {
return;
}
context.report({
node,
messageId: name == null ? 'unreadable' : 'foreignOwner',
data: {attribute, owner: ownerOf(name), ownerDirectory},
});
return;
}
if (isAllowed(attribute)) {
return;
}
context.report({
node,
messageId: name == null ? 'unreadable' : 'raw',
data: {attribute, owner: ownerOf(name), ownerDirectory},
});
}
// In a `.stylex.ts` owner module: strings (and `dataAttr()` calls) that
// spell its own attribute, checked at the end for a path to an export.
const ownerValues = [];
function noteOwnerValue(node, names) {
if (!mayExportName && ownedName != null && names.includes(ownedName)) {
ownerValues.push(node);
}
}
/** Does the value of `node` reach an export, directly or through a name? */
function reachesExport(node, seen) {
const destination = valueDestination(node);
if (destination == null) {
return false;
}
if (destination.exported) {
return true;
}
const {binding} = destination;
if (seen.has(binding)) {
return false;
}
seen.add(binding);
const name = binding.id.name;
const scopeHolder =
binding.type === 'VariableDeclarator' ? binding.parent : binding;
if (exportedLocals.has(name) && scopeHolder.parent?.type === 'Program') {
return true;
}
return sourceCode
.getDeclaredVariables(binding)
.filter(variable => variable.name === name)
.some(variable =>
variable.references.some(
reference =>
reference.identifier !== binding.id &&
reference.isRead() &&
reachesExport(reference.identifier, seen),
),
);
}
/**
* Another package's owner module: a package specifier that reaches a
* `privateAttributes` folder, or a relative path into one under another
* package's `src`.
*/
function checkImport(source) {
const specifier = source?.value;
if (typeof specifier !== 'string') {
return;
}
// A neighbour in the same folder reaches a plain-TS owner as `./press`.
if (!/(?:^|\/)privateAttributes(?:\/|$)/.test(specifier)) {
checkPlainOwnerImport(source, specifier);
return;
}
let foreign = !specifier.startsWith('.');
if (!foreign) {
const target = path
.resolve(
path.dirname(context.filename ?? context.getFilename()),
specifier,
)
.split(path.sep)
.join('/');
const targetPackage = PACKAGE_SOURCE.exec(target)?.[1] ?? null;
foreign = targetPackage != null && targetPackage !== packageName;
}
if (foreign) {
context.report({
node: source,
messageId: 'foreignPackage',
data: {source: specifier},
});
return;
}
checkPlainOwnerImport(source, specifier);
}
/**
* Only a plain-TS owner's `.stylex.ts` sibling and the theme engine may
* import it, because it exports the raw name.
*/
function checkPlainOwnerImport(source, specifier) {
if (!specifier.startsWith('.')) {
return;
}
const target = path
.resolve(
path.dirname(context.filename ?? context.getFilename()),
specifier,
)
.split(path.sep)
.join('/');
const match = PLAIN_OWNER_TARGET.exec(target);
if (match == null) {
return;
}
const [, directory, stem] = match;
if (
!fs.existsSync(`${directory}/${stem}.ts`) ||
filename === `${directory}/${stem}.stylex.ts` ||
`${directory}/${stem}.ts` === filename ||
THEME_ENGINE.test(filename)
) {
return;
}
context.report({
node: source,
messageId: 'plainOwnerImport',
data: {source: specifier},
});
}
/**
* Does the value of `node` reach only `stylex.create` arguments, directly
* or through module constants that are read only there?
*/
function reachesOnlyStylexCreate(node, seen) {
if (insideStylexCreate(node)) {
return true;
}
const destination = valueDestination(node);
if (
destination == null ||
destination.exported ||
destination.binding.type !== 'VariableDeclarator'
) {
return false;
}
const {binding} = destination;
if (seen.has(binding)) {
return true;
}
seen.add(binding);
const name = binding.id.name;
if (exportedLocals.has(name)) {
return false;
}
return sourceCode
.getDeclaredVariables(binding)
.filter(variable => variable.name === name)
.every(variable =>
variable.references.every(
reference =>
reference.identifier === binding.id ||
!reference.isRead() ||
reachesOnlyStylexCreate(reference.identifier, seen),
),
);
}
function reportSiblingUse(node) {
context.report({
node,
messageId: 'siblingSelector',
data: {
attribute: attributeLabel(siblingName),
owner: ownerOf(siblingName),
},
});
}
/**
* Does a read of a binding imported from the sibling's owner set the
* attribute: a setter-prop key outside `stylex.create`, or a
* `setAttribute`, `toggleAttribute` or `removeAttribute` argument?
*/
function setsAttribute(identifier) {
const parent = identifier.parent;
if (
parent?.type === 'Property' &&
parent.computed &&
parent.key === identifier
) {
return !insideStylexCreate(parent);
}
return (
parent?.type === 'CallExpression' &&
parent.arguments[0] === identifier &&
parent.callee.type === 'MemberExpression' &&
!parent.callee.computed &&
parent.callee.property.type === 'Identifier' &&
ATTRIBUTE_WRITERS.has(parent.callee.property.name)
);
}
function checkText(node, text) {
const names = attributeNames(text);
for (const name of names) {
report(node, name);
}
noteOwnerValue(node, names);
}
return {
ImportDeclaration(node) {
checkImport(node.source);
if (isOwnSiblingOwner(node.source.value)) {
siblingOwnerImports.push(node);
}
},
ExportNamedDeclaration(node) {
checkImport(node.source);
if (isOwnSiblingOwner(node.source?.value)) {
reportSiblingUse(node);
}
},
ExportAllDeclaration(node) {
checkImport(node.source);
if (isOwnSiblingOwner(node.source.value)) {
reportSiblingUse(node);
}
},
ImportExpression(node) {
if (node.source.type === 'Literal') {
checkImport(node.source);
}
},
Literal(node) {
if (typeof node.value !== 'string') {
return;
}
checkText(node, node.value);
},
TemplateLiteral(node) {
checkText(node, templateText(node));
},
JSXAttribute(node) {
if (node.name.type !== 'JSXIdentifier') {
return;
}
if (node.name.name.toLowerCase().startsWith(PREFIX)) {
for (const name of attributeNames(node.name.name)) {
report(node.name, name);
}
}
},
CallExpression(node) {
if (!isDataAttrCall(node)) {
return;
}
const text = staticText(node.arguments[0]);
const name = text == null || text === '' ? null : text.toLowerCase();
// A literal argument that already spells the prefix is reported by
// the literal check.
if (text != null && text.toLowerCase().includes(PREFIX)) {
return;
}
report(node, name);
noteOwnerValue(node, [name]);
},
ExportSpecifier(node) {
if (node.local.type === 'Identifier') {
exportedLocals.add(node.local.name);
}
},
'Program:exit'() {
for (const declaration of siblingOwnerImports) {
for (const variable of sourceCode.getDeclaredVariables(declaration)) {
for (const reference of variable.references) {
if (
reference.isRead() &&
(setsAttribute(reference.identifier) ||
reachesExport(reference.identifier, new Set()))
) {
reportSiblingUse(reference.identifier);
}
}
}
}
for (const node of siblingValues) {
if (
!reachesOnlyStylexCreate(node, new Set()) &&
!isAllowed(attributeLabel(siblingName))
) {
context.report({
node,
messageId: 'siblingSelector',
data: {
attribute: attributeLabel(siblingName),
owner: ownerOf(siblingName),
},
});
}
}
for (const node of ownerValues) {
if (reachesExport(node, new Set())) {
context.report({
node,
messageId: 'exportedName',
data: {attribute: attributeLabel(ownedName)},
});
}
}
},
};
},
};
export default rule;