Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions specification/eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,61 @@ export default defineConfig({
'es-spec-validator/no-variants-on-responses': 'error',
'es-spec-validator/no-inline-unions': 'error',
'es-spec-validator/prefer-tagged-variants': 'error',
'es-spec-validator/no-duplicate-type-names': [
'error',
{
ignoreNames: ['Request', 'Response', 'ResponseBase'],
existingDuplicates: {
Action: [
'indices.modify_data_stream',
'indices.update_aliases',
'watcher._types'
],
Actions: ['ilm._types', 'security.put_privileges', 'watcher._types'],
ComponentTemplate: ['cat.component_templates', 'cluster._types'],
Context: [
'_global.get_script_context',
'_global.search._types',
'nodes._types'
],
DatabaseConfigurationMetadata: [
'ingest.get_geoip_database',
'ingest.get_ip_location_database'
],
Datafeed: ['ml._types', 'xpack.usage'],
Destination: ['_global.reindex', 'transform._types'],
Feature: ['features._types', 'indices.get', 'xpack.info'],
Features: ['indices.get', 'xpack.info'],
Filter: ['_global.termvectors', 'ml._types'],
IndexingPressure: ['cluster.stats', 'indices._types', 'nodes._types'],
IndexingPressureMemory: ['indices._types', 'nodes._types'],
Ingest: ['ingest._types', 'nodes._types'],
MigrationFeature: [
'migration.get_feature_upgrade_status',
'migration.post_feature_upgrade'
],
Operation: ['_global.mget', '_global.mtermvectors'],
ResponseBody: ['_global.search', 'ml.evaluate_data_frame'],
Phase: ['ilm._types', 'xpack.usage'],
Phases: ['ilm._types', 'xpack.usage'],
Pipeline: ['ingest._types', 'logstash._types'],
Policy: ['enrich._types', 'ilm._types', 'slm._types'],
RequestItem: ['_global.msearch', '_global.msearch_template'],
ResponseItem: ['_global.bulk', '_global.mget', '_global.msearch'],
RoleMapping: ['security._types', 'xpack.usage'],
RuntimeFieldTypes: ['cluster.stats', 'xpack.usage'],
ShardsStats: ['indices.field_usage_stats', 'snapshot._types'],
ShardStats: ['ccr._types', 'indices.stats'],
Source: ['_global.reindex', 'transform._types'],
Token: [
'_global.termvectors',
'security.authenticate',
'security.create_service_token',
'security.enroll_kibana'
]
}
}
],
'es-spec-validator/jsdoc-endpoint-check': [
'error',
{
Expand Down
1 change: 1 addition & 0 deletions validator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ It is configured [in the specification directory](../specification/eslint.config
| `no-variants-on-responses` | `@variants` is only supported on Interface types, not on Request or Response classes. Use value_body pattern with `@codegen_name` instead. |
| `no-inline-unions` | Inline union types (e.g., `field: A \| B`) are not allowed in properties/fields. Define a named type alias instead to improve code generation for statically-typed languages. |
| `prefer-tagged-variants` | Union of class types should use tagged variants (`@variants internal` or `@variants container`) instead of inline unions for better deserialization support in statically-typed languages. |
| `no-duplicate-type-names` | All types must be unique across class and enum definitions. |
| `jsdoc-endpoint-check` | Validates JSDoc on endpoints in the specification. Ensuring consistent formatting. Some errors can be fixed with `--fix`. |

## Usage
Expand Down
2 changes: 2 additions & 0 deletions validator/eslint-plugin-es-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import requestMustHaveUrls from './rules/request-must-have-urls.js'
import noVariantsOnResponses from './rules/no-variants-on-responses.js'
import noInlineUnions from './rules/no-inline-unions.js'
import preferTaggedVariants from './rules/prefer-tagged-variants.js'
import noDuplicateTypeNames from './rules/no-duplicate-type-names.js'
import jsdocEndpointCheck from './rules/jsdoc-endpoint-check.js'

export default {
Expand All @@ -38,6 +39,7 @@ export default {
'no-variants-on-responses': noVariantsOnResponses,
'no-inline-unions': noInlineUnions,
'prefer-tagged-variants': preferTaggedVariants,
'no-duplicate-type-names': noDuplicateTypeNames,
'jsdoc-endpoint-check': jsdocEndpointCheck
}
}
190 changes: 190 additions & 0 deletions validator/rules/no-duplicate-type-names.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { ESLintUtils } from '@typescript-eslint/utils';
import ts from 'typescript';

/**
* Formats location information for error messages
* @param {Array} classes - Array of class locations
* @returns {string} Formatted location string
*/
function formatLocation(classes) {
const locations = classes.slice(0, 3).map(c =>
`\n\t${c.fileName}:${c.line}:${c.column}`
).join('');

const additionalCount = classes.length > 3 ? `\n ... and ${classes.length - 3} more` : '';
const plural = classes.length > 1 ? 's' : '';

return `${classes.length} other location${plural}:${locations}${additionalCount}`;
}

const typeCache = new Map();
let clearCache = true;

function getNamespace(context) {
const filename = context.filename;
const specIndex = filename.indexOf('/specification/');

if (specIndex === -1) {
return filename;
}

const pathAfterSpec = filename.substring(specIndex + '/specification/'.length);
return pathAfterSpec.split('/').slice(0, -1).join('.');
}

export const noDuplicateTypeNamesFactory = (getParserServices) => {
if (!getParserServices) {
throw new Error('getParserServices is required');
}
return ESLintUtils.RuleCreator.withoutDocs(
{
name: 'no-duplicate-type-names',
meta: {
type: 'problem',
docs: {
description: 'Ensure type aliases and interfaces have unique names across the package',
},
messages: {
duplicateTypeName: 'Duplicate: "{{typeName}}" is already declared in {{location}}\nRename this type to avoid conflicts with other types in the specification.'
},
schema: [
{
type: 'object',
properties: {
ignoreNames: {
type: 'array',
items: {
type: 'string'
},
description: 'Array of type names to ignore when checking for duplicates'
},
existingDuplicates: {
type: 'object',
additionalProperties: {
type: 'array',
items: {
type: 'string'
}
},
description: 'Object mapping type names to arrays of locations where duplicates are expected'
}
},
additionalProperties: false
}
],
},
defaultOptions: [{ ignoreNames: [], existingDuplicates: {} }],
create(context) {
const parserServices = getParserServices(context);
const { ignoreNames, existingDuplicates } = context.options[0];
const kinds = [
ts.SyntaxKind.FunctionDeclaration,
ts.SyntaxKind.ClassDeclaration,
ts.SyntaxKind.InterfaceDeclaration,
ts.SyntaxKind.TypeAliasDeclaration,
ts.SyntaxKind.EnumDeclaration,
];

if (clearCache) {
typeCache.clear();
clearCache = false;
}

function findDuplicates(node) {
try {
if (!node.id || !node.id.name) {
return;
}

if (ignoreNames.includes(node.id.name)) {
return;
}

const existingDuplicatesForName = existingDuplicates[node.id.name];
if (existingDuplicatesForName && existingDuplicatesForName.includes(getNamespace(context))) {
return;
}

let types = typeCache.get(node.id.name);
if (!types) {
types = [];
parserServices.program.getSourceFiles().forEach(sourceFile => {
if (sourceFile.fileName.includes('node_modules')) {
return;
}

sourceFile.forEachChild(fnDecl => {
if (kinds.includes(fnDecl.kind)) {
fnDecl.forEachChild(identifier => {
if (identifier.kind === ts.SyntaxKind.Identifier &&
identifier.escapedText === node.id.name) {
const { line, character } = sourceFile.getLineAndCharacterOfPosition(identifier.pos);
types.push({
typeName: identifier.escapedText,
fileName: sourceFile.fileName,
line: line + 1,
column: character + 2
});
}
});
}
});
});
typeCache.set(node.id.name, types);
}

const filteredClasses = types.filter(c => c.fileName !== context.filename);
if (filteredClasses.length > 0) {
context.report({
node: node.id,
messageId: 'duplicateTypeName',
data: {
typeName: node.id.name,
location: formatLocation(filteredClasses)
}
});
}
} catch (error) {
console.error('ERROR in findDuplicates:', error.message, error.stack);
throw error;
}
}

return {
'ClassDeclaration, InterfaceDeclaration, TypedAliasDeclaration, TSEnumDeclaration, TSInterfaceDeclaration, TSTypeAliasDeclaration'(node) {
findDuplicates(node);
},
}
}
}
)
}

export const noDuplicateTypeNames = noDuplicateTypeNamesFactory(ESLintUtils.getParserServices);

export default noDuplicateTypeNames;

export const ___testing_only = {
cache: typeCache,
setClearCache(value) {
clearCache = value;
}
}
Loading