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
1 change: 1 addition & 0 deletions specification/eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export default defineConfig([
'es-spec-validator/single-key-dictionary-key-is-string': 'error',
'es-spec-validator/dictionary-key-is-string': 'error',
'es-spec-validator/no-native-types': 'error',
'es-spec-validator/no-same-name-as-enclosing-type': 'error',
'es-spec-validator/invalid-node-types': 'error',
'es-spec-validator/no-generic-number': 'error',
'es-spec-validator/codegen-exclude-on-request-only': 'error',
Expand Down
1 change: 1 addition & 0 deletions specification/logstash/_types/Pipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export class PipelineSettings {
*/
'queue.checkpoint.writes': integer
}
// eslint-disable-next-line es-spec-validator/no-same-name-as-enclosing-type
export class Pipeline {
/**
* A description of the pipeline.
Expand Down
1 change: 1 addition & 0 deletions specification/ml/put_trained_model/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ export class AggregateOutput {
exponent?: Weights
}

// eslint-disable-next-line es-spec-validator/no-same-name-as-enclosing-type
export class Weights {
weights: double
}
1 change: 1 addition & 0 deletions specification/nodes/_types/Stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1072,6 +1072,7 @@ export class Scripting {
contexts?: Context[]
}

// eslint-disable-next-line es-spec-validator/no-same-name-as-enclosing-type
export class Context {
context?: string
compilations?: long
Expand Down
1 change: 1 addition & 0 deletions specification/security/put_privileges/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

import { Metadata, Name } from '@_types/common'

// eslint-disable-next-line es-spec-validator/no-same-name-as-enclosing-type
export class Actions {
actions: string[]
application?: string
Expand Down
29 changes: 15 additions & 14 deletions validator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,22 @@ It is configured [in the specification directory](../specification/eslint.config

## Rules

| Name | Description |
|---------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `single-key-dictionary-key-is-string` | `SingleKeyDictionary` keys must be strings. |
| `dictionary-key-is-string` | `Dictionary` keys must be strings. |
| `no-native-types` | TypeScript native utility types (`Record`, `Partial`, etc.) and collection types (`Map`, `Set`, etc.) are not allowed. Use spec-defined aliases like `Dictionary` instead. |
| `invalid-node-types` | The spec uses a subset of TypeScript, so some types, clauses and expressions are not allowed. |
| `no-generic-number` | Generic `number` type is not allowed outside of `_types/Numeric.ts`. Use concrete numeric types like `integer`, `long`, `float`, `double`, etc. |
| `request-must-have-urls` | All Request interfaces extending `RequestBase` must have a `urls` property defining their endpoint paths and HTTP methods. |
| `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. Includes additional checks on variant tag use. |
| `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. |
| `no-all-string-literal-unions | Unions consisting entirely of string literals (e.g., `"green" \| "yellow" \| "red"`) are not allowed, use enums instead. |
| Name | Description |
|---------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `single-key-dictionary-key-is-string` | `SingleKeyDictionary` keys must be strings. |
| `dictionary-key-is-string` | `Dictionary` keys must be strings. |
| `no-native-types` | TypeScript native utility types (`Record`, `Partial`, etc.) and collection types (`Map`, `Set`, etc.) are not allowed. Use spec-defined aliases like `Dictionary` instead. |
| `no-same-name-as-enclosing-type` | Classes having fields with the same name as the class is breaking for some client libraries. |
| `invalid-node-types` | The spec uses a subset of TypeScript, so some types, clauses and expressions are not allowed. |
| `no-generic-number` | Generic `number` type is not allowed outside of `_types/Numeric.ts`. Use concrete numeric types like `integer`, `long`, `float`, `double`, etc. |
| `request-must-have-urls` | All Request interfaces extending `RequestBase` must have a `urls` property defining their endpoint paths and HTTP methods. |
| `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. Includes additional checks on variant tag use. |
| `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. |
| `no-all-string-literal-unions | Unions consisting entirely of string literals (e.g., `"green" \| "yellow" \| "red"`) are not allowed, use enums instead. |
| `jsdoc-endpoint-check` | Validates JSDoc on endpoints in the specification. Ensuring consistent formatting. Some errors can be fixed with `--fix`. |
| `codegen-exclude-on-request-only` | Ensures `@codegen_exclude` is only used on request definitions located in namespaced `specification/` files (i.e. files. |
| `codegen-exclude-on-request-only` | Ensures `@codegen_exclude` is only used on request definitions located in namespaced `specification/` files (i.e. files. |

## 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 @@ -19,6 +19,7 @@
import singleKeyDict from './rules/single-key-dictionary-key-is-string.js'
import dict from './rules/dictionary-key-is-string.js'
import noNativeTypes from './rules/no-native-types.js'
import noSameNameAsEnclosingType from './rules/no-same-name-as-enclosing-type.js'
import invalidNodeTypes from './rules/invalid-node-types.js'
import noGenericNumber from './rules/no-generic-number.js'
import requestMustHaveUrls from './rules/request-must-have-urls.js'
Expand All @@ -35,6 +36,7 @@ export default {
'single-key-dictionary-key-is-string': singleKeyDict,
'dictionary-key-is-string': dict,
'no-native-types': noNativeTypes,
'no-same-name-as-enclosing-type': noSameNameAsEnclosingType,
'invalid-node-types': invalidNodeTypes,
'no-generic-number': noGenericNumber,
'request-must-have-urls': requestMustHaveUrls,
Expand Down
93 changes: 93 additions & 0 deletions validator/rules/no-same-name-as-enclosing-type.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* 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';

const createRule = ESLintUtils.RuleCreator(name => `https://example.com/rule/${name}`)

/**
* Finds if selected field has a @codegen_name comment above
* @param comments - Array of comments from the class
* @param field - Definition of the field
* @returns {boolean}
*/
function commentAboveFieldHasCodegenName(comments, field) {
for (const comment of comments) {
if (comment.loc.end.line === field.loc.start.line-1) { // checking the comment is one line above the field
if (comment.value && comment.value.includes("@codegen_name")){
const newName = comment.value.replaceAll("*","").trim().split(" ")[1]
if (newName !== field.name) return true
}
}
}
return false
}

export default createRule({
name: 'no-same-name-as-enclosing-type',
create(context) {
return {
ClassDeclaration(node) {
if (!node.id || !node.id.name) {
return; // anonymous class - nothing to check
}
const services = ESLintUtils.getParserServices(context)
const tsClass = services.esTreeNodeToTSNodeMap.get(node);
if (!tsClass || !tsClass.members) {
return; // no fields
}
const className = node.id.name;
for (const element of node.body.body) {
if (element.type === "PropertyDefinition" && element.key.name && element.key.type === "Identifier") {
const fieldName = element.key.name
const field = element.key;
if (String(fieldName).toUpperCase() === className.toUpperCase()) {
const sourceCode = context.getSourceCode();
const commentsInside = sourceCode.getCommentsInside(node)
if (!commentsInside || commentsInside.length === 0 || !commentAboveFieldHasCodegenName(commentsInside, field)) {
context.report({
node,
messageId: 'shouldNotUseClassNameForFieldNames',
data: {
class: className,
suggestion: 'Either change the class name, or if it\'s not possible, use a different codegen name for the field by commenting it with /** @codegen_name different_name **/.'
}
})
}
}
}
}
}
,
}
},
meta:
{
docs: {
description: 'Classes having fields with the same name as the class is breaking for some client libraries.'
}
,
messages: {
shouldNotUseClassNameForFieldNames: 'Class "{{class}}" has invalid fields. {{suggestion}}.'
}
,
type: 'suggestion',
}
,
defaultOptions: []
})
71 changes: 71 additions & 0 deletions validator/test/no-same-name-as-enclosing-type.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* 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 { RuleTester } from '@typescript-eslint/rule-tester'
import rule from '../rules/no-same-name-as-enclosing-type.js'

const ruleTester = new RuleTester({
languageOptions: {
parserOptions: {
projectService: {
allowDefaultProject: ['*.ts*'],
},
tsconfigRootDir: import.meta.dirname,
},
},
})

ruleTester.run('no-same-name-as-enclosing-type', rule, {
valid: [
`class MyClass {
field: integer
anotherfield: string
}`,
`class MyClass {
/** @codegen_name new_name **/
myclass: integer
}`
],
invalid: [
{
code: `class MyClass { MyClass: integer }`,
errors: [{ messageId: 'shouldNotUseClassNameForFieldNames' }]
},
{
code: `class MyClass { myclass: integer }`,
errors: [{ messageId: 'shouldNotUseClassNameForFieldNames' }]
},
{
code: `class MyClass {
field: integer
anotherfield: string
myclass: boolean
}`,
errors: [{ messageId: 'shouldNotUseClassNameForFieldNames' }]
},
{
code: `class MyClass {
field: integer
anotherfield: string
/** @codegen_name myclass **/
myclass: boolean
}`,
errors: [{ messageId: 'shouldNotUseClassNameForFieldNames' }]
}
],
})