Files
lucide/scripts/eslint/jsonSchemaPlugin.mjs
55b9969b82 ci(lint): split lint jobs and annotate Prettier and JSON schema errors in PRs (#4982)
* ci: split lint-code into ESLint, Prettier and JSON Schema jobs with PR annotations

- ESLint: annotations via setup-node's built-in eslint-stylish problem matcher.
- Prettier: new scripts/lintFormat.mts formats unformatted files in memory, diffs
  them and emits line-level `::error` annotations with the expected code.
- JSON Schema: replace ajv-cli with a local ESLint rule (Ajv draft 2020-12) that
  validates icons/categories JSON against their `$schema` and reports at the
  offending property. eslint-plugin-json-schema-validator was not used because it
  runs Ajv in draft-07 mode and ignores `dependentRequired`.

All annotations use workflow commands, so they work on fork PRs with a read-only token.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FVxEtqNswEDq1N23taZYh8

* Improve root value check and property error handling

Enhance error reporting for JSON schema validation.

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* style(lint): format jsonSchemaPlugin with Prettier

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FVxEtqNswEDq1N23taZYh8

* test commit

* fix(lint): annotate syntax errors from Prettier and ESLint in PRs

- ESLint/JSON Schema jobs use a small GitHub formatter that prints `::error`
  workflow commands. setup-node's eslint-stylish matcher skipped parsing errors
  because they have no rule id.
- lintFormat.mts annotates Prettier syntax errors (exit code 2) at their line and
  column instead of only printing stderr, and still checks the other files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FVxEtqNswEDq1N23taZYh8

* ci(lint): spell check icon and category metadata with cspell annotations

- New "Spelling" job runs scripts/lintSpelling.mts, which turns cspell findings
  into `::error` annotations (with cspell's suggested fix when it has one).
- cspell accepts both US and British English, ignores contributor usernames and
  deprecated `alias.typo` aliases.
- Add existing search tags and domain terms to .cspell/custom-words.txt so the
  current metadata passes.
- Add `lint:spelling` to `pnpm lint` and lint-staged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FVxEtqNswEDq1N23taZYh8

* fix(lint): pin JSON schemas per file set and drop typo tags

- json-schema/no-invalid now takes the schema from config (icon.schema.json for
  icons, category.schema.json for categories) and reports a `$schema` that
  points elsewhere, so metadata can't opt out of validation.
- Remove the misspelled `frigerator` and `sterisk` tags and their allowlist entries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FVxEtqNswEDq1N23taZYh8

* fix(icons): split joined-word tags into separate words

Tags like `groupchat` and `timemachine` become `group chat` and `time machine`
so they read naturally and pass the spell check without allowlisting. Where the
spaced tag already existed (`smart home`) the joined one is dropped.

cspell now skips all alias names, since they are icon names that can't change
(e.g. the deprecated `palmtree` alias).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FVxEtqNswEDq1N23taZYh8

* Revert

* Try another error

* Revert error

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-10-09 11:30:00 +02:00

148 lines
4.9 KiB
JavaScript

import fs from 'node:fs';
import path from 'node:path';
import { Ajv2020 } from 'ajv/dist/2020.js';
import { getStaticJSONValue } from 'jsonc-eslint-parser';
/**
* ESLint plugin that validates JSON files against a configured JSON Schema (draft 2020-12),
* reporting each error at the offending property. It also requires the file's `$schema` field to
* point at that schema.
*
* Off-the-shelf plugins (e.g. eslint-plugin-json-schema-validator) only run Ajv in draft-07 mode,
* which silently skips 2020-12 keywords such as `dependentRequired`.
*/
const ajv = new Ajv2020({ allErrors: true });
/** @type {Map<string, import('ajv').ValidateFunction>} */
const validators = new Map();
/** @param {string} schemaPath */
const getValidator = (schemaPath) => {
let validate = validators.get(schemaPath);
if (!validate) {
validate = ajv.compile(JSON.parse(fs.readFileSync(schemaPath, 'utf-8')));
validators.set(schemaPath, validate);
}
return validate;
};
/**
* Find the AST node for a JSON pointer (e.g. `/aliases/0/name`). Returns the property node for
* object members so the report points at the key, falling back to the closest existing parent.
*
* @param {any} node
* @param {string} pointer
*/
const findNode = (node, pointer) => {
const segments = pointer
.split('/')
.slice(1)
.map((segment) => segment.replaceAll('~1', '/').replaceAll('~0', '~'));
let current = node;
let reportNode = node;
for (const segment of segments) {
if (current?.type === 'JSONObjectExpression') {
const property = current.properties.find(
(/** @type {any} */ prop) => (prop.key.value ?? prop.key.name) === segment,
);
if (!property) break;
reportNode = property;
current = property.value;
} else if (current?.type === 'JSONArrayExpression') {
const element = current.elements[Number(segment)];
if (!element) break;
reportNode = element;
current = element;
} else {
break;
}
}
return { node: current, reportNode };
};
/** @type {import('eslint').Rule.RuleModule} */
const noInvalid = {
meta: {
type: 'problem',
docs: {
description: 'Validate JSON files against a JSON Schema and require `$schema` to point at it',
},
schema: [
{
type: 'object',
properties: {
// Path to the schema, relative to the ESLint working directory (the repo root).
schema: { type: 'string' },
},
required: ['schema'],
additionalProperties: false,
},
],
},
create(context) {
return {
/** @param {any} program */
Program(program) {
const root = program.body[0]?.expression;
if (root?.type !== 'JSONObjectExpression') {
context.report({ node: root ?? program, message: 'Root value must be an object.' });
return;
}
const data = getStaticJSONValue(root);
if (typeof data?.$schema !== 'string') {
context.report({ node: root, message: 'Missing `$schema` field.' });
return;
}
// Validate against the configured schema, not whatever `$schema` points at, so a file can't
// opt out of validation by referencing a more permissive schema.
const schemaPath = path.resolve(context.cwd, context.options[0].schema);
const expectedRef = path
.relative(path.dirname(context.filename), schemaPath)
.split(path.sep)
.join('/');
if (path.resolve(path.dirname(context.filename), data.$schema) !== schemaPath) {
context.report({
node: findNode(root, '/$schema').reportNode,
message: `\`$schema\` must be "${expectedRef}".`,
});
}
const validate = getValidator(schemaPath);
if (validate(data)) return;
for (const error of validate.errors ?? []) {
const { node, reportNode } = findNode(root, error.instancePath);
const location = error.instancePath || '(root)';
if (error.keyword === 'additionalProperties' && node?.type === 'JSONObjectExpression') {
const property = findNode(
node,
`/${error.params.additionalProperty.replaceAll('~', '~0').replaceAll('/', '~1')}`,
).reportNode;
context.report({
node: property,
message: `${location} has unexpected property "${error.params.additionalProperty}".`,
});
continue;
}
const isContainer =
reportNode.type === 'JSONObjectExpression' || reportNode.type === 'JSONArrayExpression';
context.report({
// Report objects and arrays at their opening bracket only, not their whole range.
loc: isContainer ? reportNode.loc.start : reportNode.loc,
message: `${location} ${error.message}.`,
});
}
},
};
},
};
export default {
meta: { name: 'json-schema' },
rules: { 'no-invalid': noInvalid },
};