Skip to content
Draft
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
9 changes: 9 additions & 0 deletions .changeset/named-boolean-flags.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@frontify/eslint-config-basic': minor
'@frontify/eslint-config-react': minor
'@frontify/eslint-plugin': patch
'@frontify/oxlint-config-basic': minor
'@frontify/oxlint-config-react': minor
---

ESLint and Oxlint report functions with two or more boolean parameters as errors. Put the flags in a named options object so callers can read what each value controls. Callbacks can keep the parameters their API supplies.
1 change: 1 addition & 0 deletions packages/eslint-config-basic/eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ export default defineConfig(
},
rules: {
'@frontify/no-conditional-object-spread': 'error',
'@frontify/no-positional-boolean-flags': 'error',

// Eslint (base)
'@stylistic/linebreak-style': ['error', 'unix'],
Expand Down
2 changes: 2 additions & 0 deletions packages/eslint-plugin/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import jsxShorthandBoolean from './rules/jsx-shorthand-boolean.mjs';
import noConditionalObjectSpread from './rules/no-conditional-object-spread.mjs';
import noInlineParamType from './rules/no-inline-param-type.mjs';
import noPositionalBooleanFlags from './rules/no-positional-boolean-flags.mjs';

export default {
meta: {
Expand All @@ -12,5 +13,6 @@ export default {
'jsx-shorthand-boolean': jsxShorthandBoolean,
'no-conditional-object-spread': noConditionalObjectSpread,
'no-inline-param-type': noInlineParamType,
'no-positional-boolean-flags': noPositionalBooleanFlags,
},
};
3 changes: 2 additions & 1 deletion packages/eslint-plugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
"index.mjs",
"rules/jsx-shorthand-boolean.mjs",
"rules/no-conditional-object-spread.mjs",
"rules/no-inline-param-type.mjs"
"rules/no-inline-param-type.mjs",
"rules/no-positional-boolean-flags.mjs"
],
"scripts": {
"test": "node --test 'rules/**/*.test.mjs'"
Expand Down
122 changes: 122 additions & 0 deletions packages/eslint-plugin/rules/no-positional-boolean-flags.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/* (c) Copyright Frontify Ltd., all rights reserved. */

// @ts-check

/** @import { TSESTree } from '@typescript-eslint/types' */

const FUNCTION_TYPES = /** @type {const} */ (['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression']);
const FUNCTION_SELECTOR = `:matches(${FUNCTION_TYPES.join(', ')})`;
const CALLBACK_ANNOTATIONS = new Set(['TSFunctionType', 'TSTypeReference', 'TSTypeQuery', 'TSIndexedAccessType']);
const NAME_FLAGS_MESSAGE_ID = 'nameFlags';

/** @typedef {Extract<TSESTree.Node, { type: (typeof FUNCTION_TYPES)[number] }>} FunctionWithParameters */

/**
* Recognizes boolean annotations and defaults through parameter syntax such as constructor properties.
* @param {TSESTree.Parameter} parameter - The parameter as written in the signature.
*/
function isBooleanParameter(parameter) {
let binding = parameter;

if (binding.type === 'TSParameterProperty') {
binding = binding.parameter;
}

let defaultValue;

if (binding.type === 'AssignmentPattern') {
defaultValue = binding.right;
binding = binding.left;
}

if (binding.type !== 'Identifier') {
return false;
}

const annotation = binding.typeAnnotation?.typeAnnotation;

if (annotation) {
return annotation.type === 'TSBooleanKeyword';
}

return defaultValue?.type === 'Literal' && typeof defaultValue.value === 'boolean';
}

/**
* Recognizes explicit callback annotations without resolving types across modules.
* @param {TSESTree.TypeNode | undefined} annotation - The type written next to the callback.
*/
function hasCallbackAnnotation(annotation) {
if (!annotation) {
return false;
}

return CALLBACK_ANNOTATIONS.has(annotation.type);
}

/**
* Preserves signatures supplied at the callback's definition site.
* @param {TSESTree.Node} expression - The function or a type wrapper around it.
* @returns {boolean} Whether the definition site supplies the parameter contract.
*/
function hasCallbackContract(expression) {
const parent = expression.parent;

if (!parent) {
return false;
}

switch (parent.type) {
case 'CallExpression':
case 'NewExpression':
return parent.arguments.some((argument) => argument === expression);
case 'JSXExpressionContainer':
return parent.expression === expression && parent.parent.type === 'JSXAttribute';
case 'VariableDeclarator':
return parent.init === expression && hasCallbackAnnotation(parent.id.typeAnnotation?.typeAnnotation);
case 'TSAsExpression':
case 'TSTypeAssertion':
case 'TSSatisfiesExpression':
return (
parent.expression === expression &&
(hasCallbackAnnotation(parent.typeAnnotation) || hasCallbackContract(parent))
);
case 'TSNonNullExpression':
return parent.expression === expression && hasCallbackContract(parent);
default:
// Only parents that supply a parameter contract can exempt a function.
return false;
}
}

/** @satisfies {import('eslint').Rule.RuleModule} */
const noPositionalBooleanFlags = {
meta: {
type: 'problem',
schema: [],
messages: {
[NAME_FLAGS_MESSAGE_ID]: 'Group boolean parameters in a named options object.',
},
},
create(context) {
return {
/**
* Reports the second boolean parameter when the function owns its signature.
* @param {import('eslint').JSSyntaxElement} node - The function matched by the selector.
*/
[FUNCTION_SELECTOR](node) {
// The selector limits the listener to functions with a parameter list.
const functionNode = /** @type {FunctionWithParameters} */ (node);
const [, secondFlag] = functionNode.params.filter(isBooleanParameter);

if (!secondFlag || hasCallbackContract(functionNode)) {
return;
}

context.report({ node: secondFlag, messageId: NAME_FLAGS_MESSAGE_ID });
},
};
},
};

export default noPositionalBooleanFlags;
74 changes: 74 additions & 0 deletions packages/eslint-plugin/rules/no-positional-boolean-flags.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/* (c) Copyright Frontify Ltd., all rights reserved. */

import * as parser from '@typescript-eslint/parser';
import { RuleTester } from 'eslint';

import plugin from '../index.mjs';

const rule = plugin.rules['no-positional-boolean-flags'];
const ruleTester = new RuleTester({ languageOptions: { parser } });
const nameFlagsError = { messageId: 'nameFlags' };

const positionalFlags = [
{
name: 'reports two annotated boolean parameters in a declaration',
code: 'function connect(verbose: boolean, retry: boolean) { return { verbose, retry }; }',
},
{
name: 'counts an optional boolean and a literal boolean default',
code: 'const connect = function (verbose?: boolean, retry = true) { return { verbose, retry }; };',
},
{
name: 'counts booleans separated by a different parameter type',
code: 'const connect = (verbose: boolean, label: string, retry = false) => ({ verbose, label, retry });',
},
{
name: 'counts unannotated literal defaults in JavaScript',
filename: 'example.js',
code: 'function connect(verbose = false, retry = true) { return { verbose, retry }; }',
},
{
name: 'counts a boolean constructor property with a default',
code: 'class Connection { constructor(private verbose: boolean, public retry = true) {} }',
},
{
name: 'reports boolean parameters on an owned method',
code: 'const connection = { connect(verbose: boolean, retry: boolean) { return { verbose, retry }; } };',
},
{
name: 'reports an inline function used as the callee',
code: 'const result = ((verbose: boolean, retry: boolean) => ({ verbose, retry }))(true, false);',
},
{
name: 'reports a function whose annotation supplies no callback signature',
code: 'const connect: unknown = (verbose: boolean, retry: boolean) => ({ verbose, retry });',
},
{
name: 'reports once when a function has three boolean parameters',
code: 'const connect = (verbose: boolean, retry: boolean, awaitResponse = true) => ({});',
},
];

ruleTester.run('no-positional-boolean-flags', rule, {
valid: [
'function connect(verbose: boolean, label: string) { return { verbose, label }; }',
'function connect(verbose = false, retry = 1) { return { verbose, retry }; }',
'type ConnectOptions = { verbose: boolean; retry: boolean }; const connect = ({ verbose, retry }: ConnectOptions) => ({ verbose, retry });',
'function connect(verbose: boolean, retry: boolean | number = false) { return { verbose, retry }; }',
'register((verbose: boolean, retry: boolean) => ({ verbose, retry }));',
'new Observer(function (verbose: boolean, retry: boolean) { return { verbose, retry }; });',
'register(((verbose: boolean, retry: boolean) => ({ verbose, retry })) as unknown);',
'import type { Listener } from "./api"; const onChange: Listener = (visible: boolean, active: boolean) => {};',
'type Listener = (visible: boolean, active: boolean) => void; const onChange: Listener = (visible: boolean, active: boolean) => {};',
'const onChange: (visible: boolean, active: boolean) => void = (visible: boolean, active: boolean) => {};',
'const onChange: Props["onChange"] = (visible: boolean, active: boolean) => {};',
'const onChange: typeof listener = (visible: boolean, active: boolean) => {};',
'const onChange = ((visible: boolean, active: boolean) => {}) satisfies Listener;',
{
name: 'preserves an inline JSX callback prop',
filename: 'example.tsx',
code: 'const view = <Panel onChange={(visible: boolean, active: boolean) => {}} />;',
},
],
invalid: positionalFlags.map((testCase) => ({ ...testCase, errors: [nameFlagsError] })),
});
1 change: 1 addition & 0 deletions packages/oxlint-config-basic/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,7 @@ export default defineConfig({
},
rules: {
'@frontify/no-conditional-object-spread': 'error',
'@frontify/no-positional-boolean-flags': 'error',
'no-empty': 'error',
'no-useless-catch': 'error',
'prefer-template': 'error',
Expand Down