stylelint: Fix `*-no-unknown` false positives for latest specs by integrating `@csstools/css-syntax-patches-for-csstree`
I’ve finished the npm package containing the syntax definition patches as scraped from all CSS specifications.
- we can integrate this directly into
declaration-property-value-no-unknown - or we can leave it up to end users to use this package and maybe link to it from the rule docs
I think direct integration gives a better user experience for most users as they can set a simpler plugin option.
There is some parallel between this rule and the list of syntax definitions and the lib option in TypeScript.
The default lib is always a bit behind the latest platform developments but better reflects stable and widely available CSS features.
While this new next lib expands the default lib with everything that is more recent but possibly also less stable.
For example:
{
"rules": {
"declaration-property-value-no-unknown": [true, {lib: "next"}]
}
}
(Demo implementation)
import { createRequire } from 'node:module';
import { find, fork, parse, string } from 'css-tree';
import { isAtRule, isDeclaration } from '../../utils/typeGuards.mjs';
import { isRegExp, isString } from '../../utils/validateTypes.mjs';
import declarationValueIndex from '../../utils/declarationValueIndex.mjs';
import getDeclarationValue from '../../utils/getDeclarationValue.mjs';
import isCustomProperty from '../../utils/isCustomProperty.mjs';
import isStandardSyntaxDeclaration from '../../utils/isStandardSyntaxDeclaration.mjs';
import isStandardSyntaxProperty from '../../utils/isStandardSyntaxProperty.mjs';
import isStandardSyntaxValue from '../../utils/isStandardSyntaxValue.mjs';
import matchesStringOrRegExp from '../../utils/matchesStringOrRegExp.mjs';
import { nestingSupportedAtKeywords } from '../../reference/atKeywords.mjs';
import report from '../../utils/report.mjs';
import ruleMessages from '../../utils/ruleMessages.mjs';
import validateObjectWithArrayProps from '../../utils/validateObjectWithArrayProps.mjs';
import validateObjectWithProps from '../../utils/validateObjectWithProps.mjs';
import validateOptions from '../../utils/validateOptions.mjs';
const require = createRequire(import.meta.url);
// TODO: Replace this with Import attributes when dropping the support for older Node.js versions.
// See https://nodejs.org/api/esm.html#import-attributes
const syntaxPatches = require('@csstools/css-syntax-patches-for-csstree');
const ruleName = 'declaration-property-value-no-unknown';
const messages = ruleMessages(ruleName, {
rejected: (property, value) => `Unexpected unknown value "${value}" for property "${property}"`,
rejectedParseError: (property, value) =>
`Cannot parse property value "${value}" for property "${property}"`,
});
const meta = {
url: 'https://stylelint.io/user-guide/rules/declaration-property-value-no-unknown',
};
const SYNTAX_DESCRIPTOR = /^syntax$/i;
/** @typedef {import('stylelint').CoreRules[ruleName]} Rule */
/** @typedef {Parameters<Rule>[1]} SecondaryOptions */
/** @type {Rule} */
const rule = (primary, secondaryOptions) => {
return (root, result) => {
const validOptions = validateOptions(
result,
ruleName,
{ actual: primary },
{
actual: secondaryOptions,
possible: {
lib: ['next'],
ignoreProperties: [validateObjectWithArrayProps(isString, isRegExp)],
propertiesSyntax: [validateObjectWithProps(isString)],
typesSyntax: [validateObjectWithProps(isString)],
},
optional: true,
},
);
if (!validOptions) {
return;
}
const ignoreProperties = Array.from(Object.entries(secondaryOptions?.ignoreProperties ?? {}));
/** @type {(name: string, propValue: string) => boolean} */
const isPropIgnored = (name, value) => {
const [, valuePattern] =
ignoreProperties.find(([namePattern]) => matchesStringOrRegExp(name, namePattern)) || [];
return Boolean(valuePattern && matchesStringOrRegExp(value, valuePattern));
};
/** @type {SecondaryOptions['propertiesSyntax']} */
let propertiesSyntax;
if (secondaryOptions?.lib === 'next') {
propertiesSyntax = mergeOptions(
{ ...secondaryOptions?.propertiesSyntax },
syntaxPatches.next.properties
);
} else {
propertiesSyntax = {
'text-box-edge':
'auto | [ text | cap | ex | ideographic | ideographic-ink ] [ text | alphabetic | ideographic | ideographic-ink ]?',
'text-box-trim': 'none | trim-start | trim-end | trim-both',
'view-timeline':
"[ <'view-timeline-name'> [ <'view-timeline-axis'> || <'view-timeline-inset'> ]? ]#",
...secondaryOptions?.propertiesSyntax,
};
}
/** @type {SecondaryOptions['propertiesSyntax']} */
let typesSyntax = { ...secondaryOptions?.typesSyntax };
if (secondaryOptions?.lib === 'next') {
typesSyntax = mergeOptions(
{ ...secondaryOptions?.typesSyntax },
syntaxPatches.next.types
);
} else {
typesSyntax = { ...secondaryOptions?.typesSyntax };
}
/** @type {Map<string, string>} */
const typedCustomPropertyNames = new Map();
root.walkAtRules(/^property$/i, (atRule) => {
const propName = atRule.params.trim();
if (!propName || !atRule.nodes || !isCustomProperty(propName)) return;
for (const node of atRule.nodes) {
if (isDeclaration(node) && SYNTAX_DESCRIPTOR.test(node.prop)) {
const value = node.value.trim();
const unquoted = string.decode(value);
// Only string values are valid.
// We can not check the syntax of this property.
if (unquoted === value) continue;
// Any value is allowed in this custom property.
// We don't need to check this property.
if (unquoted === '*') continue;
// https://github.com/csstree/csstree/pull/256
// We can circumvent this issue by prefixing the property name,
// making it a vendor-prefixed property instead of a custom property.
// No one should be using `-stylelint--` as a property prefix.
//
// When this is resolved `typedCustomPropertyNames` can become a `Set<string>`
// and the prefix can be removed.
const prefixedPropName = `-stylelint${propName}`;
typedCustomPropertyNames.set(propName, prefixedPropName);
propertiesSyntax[prefixedPropName] = unquoted;
}
}
});
const forkedLexer = fork({
properties: propertiesSyntax,
types: typesSyntax,
}).lexer;
root.walkDecls((decl) => {
const { prop, parent } = decl;
const value = getDeclarationValue(decl);
// csstree/csstree#243
// NOTE: CSSTree's `fork()` doesn't support `-moz-initial`, but it may be possible in the future.
if (/^-moz-initial$/i.test(value)) return;
if (!isStandardSyntaxDeclaration(decl)) return;
if (!isStandardSyntaxProperty(prop)) return;
if (!isStandardSyntaxValue(value)) return;
if (isCustomProperty(prop) && !typedCustomPropertyNames.has(prop)) return;
if (isPropIgnored(prop, value)) return;
/** @type {import('css-tree').CssNode} */
let cssTreeValueNode;
try {
cssTreeValueNode = parse(value, { context: 'value', positions: true });
if (containsUnsupportedFunction(cssTreeValueNode)) return;
} catch {
const index = declarationValueIndex(decl);
const endIndex = index + value.length;
report({
message: messages.rejectedParseError(prop, value),
node: decl,
index,
endIndex,
result,
ruleName,
});
return;
}
const { error } =
parent && isAtRule(parent) && !nestingSupportedAtKeywords.has(parent.name.toLowerCase())
? forkedLexer.matchAtruleDescriptor(parent.name, prop, cssTreeValueNode)
: forkedLexer.matchProperty(typedCustomPropertyNames.get(prop) ?? prop, cssTreeValueNode);
if (!error) return;
if (!('mismatchLength' in error)) return;
const { name, rawMessage, loc } = error;
if (name !== 'SyntaxMatchError') return;
if (rawMessage !== 'Mismatch') return;
const valueIndex = declarationValueIndex(decl);
const mismatchValue = value.slice(loc.start.offset, loc.end.offset);
report({
message: messages.rejected(prop, mismatchValue),
node: decl,
index: valueIndex + loc.start.offset,
endIndex: valueIndex + loc.end.offset,
result,
ruleName,
});
});
};
};
/**
*
* @see csstree/csstree#164 min, max, clamp
* @see csstree/csstree#245 env
* @param {import('css-tree').CssNode} cssTreeNode
* @returns {boolean}
*/
function containsUnsupportedFunction(cssTreeNode) {
return Boolean(
find(
cssTreeNode,
(node) => node.type === 'Function' && ['clamp', 'min', 'max', 'env'].includes(node.name),
),
);
}
/**
* @param {Record<string, string>} userProvided
* @param {Record<string, string>} existing
* @returns Record<string, string>
*/
function mergeOptions(userProvided, existing) {
const merged = {
...existing
};
for (const [key, value] of Object.entries(userProvided)) {
if (existing[key] && value.trimStart()[0] === '|') {
merged[key] = existing[key] + value;
continue;
}
merged[key] = value
}
return merged;
}
rule.ruleName = ruleName;
rule.messages = messages;
rule.meta = meta;
export default rule;
Either is fine with me.
About this issue
- Original URL
- State: open
- Created 2 years ago
- Comments: 30 (29 by maintainers)
Hum, in my opinion, I’m negative that the
{lib: 'next'}format would depend on third-party packages. 🤔For example, in a JS config file, we might be able to achieve the same by directly importing packages, instead of the magic word
"next":In the case of a JSON config, we might be able to support the following:
Like I said, your stance is widely shared among the other maintainers, I am a completist. I wish it would be restricted to our recommended/standard configs though.
The only thing that I would like to tweak would be how the json file(s) are being imported. e.g. caching for the second call, delayed import, etc. Apart from those considerations, I would support the integration—without
lib. If we could have individual library components, I would have picked theliboption but as @romainmenke explained it would be nonsensical—i.e. all specifications must be evaluated as a whole. Constructing an isolated dependency tree for each draft would have been a headache for sure.I have compared our overrides with what’s currently included in https://github.com/csstools/postcss-plugins/blob/main/packages/css-syntax-patches-for-csstree/dist/index.json; it’s identical. i.e. the overrides for
propertiesSyntaxwon’t be necessary anymoreI would rather have the past property aliases also included but it seems that this preference is not shared by many. i.e. it’s not a blocker
👍
This is fantastic work. Thank you for toiling behind the scenes on this, @romainmenke!
And thank you for this clear explanation as well. It helped me understand the moving parts behind the declaration-property-value-no-unknown rule.
Am I right in thinking that one of the motivations for integrating the package is to replace our current manual and error-prone patching of the syntax (to close the many issues we get with this rule) with a more robust process. If so, then I believe integration will lead to a better experience for us and, as @romainmenke said, a better user experience. It closes the gap between CSSTree’s necessarily slow releases and the needs of our users, who likely expect this rule to work out of the box without integrating another package themselves. If we do integrate the package, should we consider doing it by default and not behind a
liboption?That would slightly change the behaviour detailed in https://github.com/stylelint/stylelint/issues/8100#issuecomment-2462362107 to:
typesSyntax,propertiesSyntax,atRulesSyntaxandcssWideKeywords(With no manual patching in Stylelint)
As an aside, @romainmenke, your involvement in Stylelint has been a boon for the project! We’ve gained so much through your knowledge of the CSS specifications, the ecosystem and the inner workings of postcss and your construct parsers. Just as I’ve learned an incalculable amount about what good JavaScript looks like through @ybiquitous and others’ many refactoring PRs and new features, I’ve learned a lot about CSS’s broader ecosystem from you.
You had
atRuleSyntaxwith a singleSinstead ofatRulesSyntaxwithsSOtherwise, your suggestion was perfect 😃I agree that we should only have soft guidelines for this rule. We can always handle specific cases differently if there is need.
Currently, we have our own overrides as below:
https://github.com/stylelint/stylelint/blob/b4bfe38e2c390ad8d17bbba2d25d56c6bc74473e/lib/rules/declaration-property-value-no-unknown/index.mjs#L69-L76
In a minor release, we can remove them and suggest an alternative package:
https://github.com/stylelint/stylelint/blob/b4bfe38e2c390ad8d17bbba2d25d56c6bc74473e/docs/about/semantic-versioning.md?plain=1#L17-L19
I realized that a new option like
atRuleSyntaxcannot support third-party packages in a JSON config. 😓So, the following idea may be better:
atRuleSyntaxoption.{ "syntaxPatches": "@csstools/css-syntax-patches-for-csstree" }in a JSON/YAML config.Just adding an option seems much easier. Any thoughts?
I think we want this order:
csstreetypesSyntax,propertiesSyntax, …Then users can always intervene and set an override.
That sounds ideal to me 👍
Not really 😃
If you want to review or give feedback on the contents or progress of that package, please do so in the repo where it is maintained. This is just like any other 3rd party dependency.
We already have a process in place to manage dependency updates and I think everyone here is very careful when merging those updates. We can inspect and consider each update in their respective pull requests.
The entire purpose of having a separate package for these CSS syntax definition patches is to make this an upstream problem. Something that doesn’t significantly add to the maintenance burden of Stylelint itself. Having in depth review of individual syntax changes within Stylelint kinda defeats the purpose.
I obviously welcome contributions and feedback on this package in https://github.com/csstools/postcss-plugins but I also hope that we can reduce the workload here. Otherwise we just create more work overall.